Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dashboard-filter-all-option-sql-query-refresh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/app': patch
---

fix: refetch the options of SQL query filters set to "All" on every dashboard refresh, so "All" picks up new values even when the filter's query ignores the time range.
Original file line number Diff line number Diff line change
@@ -1,21 +1,38 @@
import React from 'react';
import {
ChartVariable,
SqlQueryDashboardFilter,
StaticListDashboardFilter,
} from '@hyperdx/common-utils/dist/types';
import { renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook, waitFor } from '@testing-library/react';

import {
getUnavailableVariablesMessage,
useExpandedSqlQueryVariables,
} from '@/hooks/useExpandedSqlQueryVariables';
import { useSqlQueryFilterValues } from '@/hooks/useSqlQueryFilterValues';

const mockQuery = jest.fn();

jest.mock('@/hooks/useSqlQueryFilterValues', () => ({
useSqlQueryFilterValues: jest.fn(),
}));
jest.mock('@/clickhouse', () => ({
getClickhouseClient: () => ({ query: mockQuery }),
}));
jest.mock('@/source', () => ({
useSources: () => ({ data: [], isLoading: false }),
}));
jest.mock('@/hooks/useMetadata', () => ({
useMetadataWithSettings: () => ({}),
}));

const mockValues = jest.mocked(useSqlQueryFilterValues);
const { useSqlQueryFilterValues: realUseSqlQueryFilterValues } =
jest.requireActual<typeof import('@/hooks/useSqlQueryFilterValues')>(
'@/hooks/useSqlQueryFilterValues',
);

const sqlFilter: SqlQueryDashboardFilter = {
id: 'region-filter',
Expand Down Expand Up @@ -146,6 +163,149 @@ describe('useExpandedSqlQueryVariables', () => {
message: 'Select a value for $conn to load the options for Region.',
});
});

// The real values hook, with the filter bar's dropdown and the page's
// expansion sharing one cache
describe('on dashboard refresh', () => {
const respondWith = (values: string[]) =>
mockQuery.mockResolvedValue({
json: async () => ({ data: values.map(value => ({ value })) }),
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — "doesn't refetch for an equal time range" checks the call count before any refetch could reach mockQuery

The queryFn first awaits renderValuesCall (useSqlQueryFilterValues.tsx:217) and only then calls getClickhouseClient().query. So a refetch fired by the effect on this rerender would not have called mockQuery yet when line 174 runs synchronously, and the test passes even if refreshKey were built from Date identity. Wait before asserting, for example with await waitFor(() => expect(result.current...isFetching).toBe(false)) or by flushing microtasks with await act(async () => {}), then check toHaveBeenCalledTimes(1).

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

const firstRange: [Date, Date] = [new Date(1000), new Date(2000)];
const refreshedRange: [Date, Date] = [new Date(61_000), new Date(62_000)];

let wrapper: React.ComponentType<{ children: React.ReactNode }>;

type DashboardProps = {
dateRange: [Date, Date];
variables?: ChartVariable[];
};

const renderDashboard = (
sqlTemplate: string,
variables: ChartVariable[] = [allRegion],
) => {
const filters = [{ ...sqlFilter, sqlTemplate }];
const initialProps: DashboardProps = { dateRange: firstRange };
return renderHook(
(props: DashboardProps) => {
const current = props.variables ?? variables;
useSqlQueryFilterValues({
filters,
dateRange: props.dateRange,
variables: current,
});
return useExpandedSqlQueryVariables({
filters,
variables: current,
dateRange: props.dateRange,
});
},
{ wrapper, initialProps },
);
};

// Holds the next options query open until `respond` is called
const deferNextResponse = () => {
let respond: (values: string[]) => void = () => {};
mockQuery.mockReturnValueOnce(
new Promise(resolve => {
respond = values =>
resolve({
json: async () => ({ data: values.map(value => ({ value })) }),
});
}),
);
return (values: string[]) => respond(values);
};

const expandedValues = (result: {
current: { variables: ChartVariable[] | undefined };
}) => result.current.variables?.[0].values;

beforeEach(() => {
mockValues.mockImplementation(realUseSqlQueryFilterValues);
mockQuery.mockReset();
respondWith(['east']);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
wrapper = ({ children }) => (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
);
});

it('refetches options that ignore the time range', async () => {
const { result, rerender } = renderDashboard(
'SELECT region FROM regions',
);
await waitFor(() => expect(expandedValues(result)).toEqual(['east']));
expect(mockQuery).toHaveBeenCalledTimes(1);

respondWith(['east', 'west']);
rerender({ dateRange: refreshedRange });

await waitFor(() =>
expect(expandedValues(result)).toEqual(['east', 'west']),
);
expect(mockQuery).toHaveBeenCalledTimes(2);
});

it('runs options that read the time range once per refresh', async () => {
const { result, rerender } = renderDashboard(
'SELECT region FROM regions WHERE $__timeFilter(ts)',
);
await waitFor(() => expect(expandedValues(result)).toEqual(['east']));

respondWith(['east', 'west']);
rerender({ dateRange: refreshedRange });

await waitFor(() =>
expect(expandedValues(result)).toEqual(['east', 'west']),
);
expect(mockQuery).toHaveBeenCalledTimes(2);
});

it("doesn't refetch for an equal time range", async () => {
const { result, rerender } = renderDashboard(
'SELECT region FROM regions',
);
await waitFor(() => expect(expandedValues(result)).toEqual(['east']));

rerender({ dateRange: [new Date(1000), new Date(2000)] });

expect(mockQuery).toHaveBeenCalledTimes(1);
});

it('waits for new options when a variable the query uses changes', async () => {
const cloud = (value: string): ChartVariable => ({
name: 'cloud',
values: [value],
});
const { result, rerender } = renderDashboard(
'SELECT region FROM regions WHERE $__filter(cloud, $cloud)',
[allRegion, cloud('aws')],
);
await waitFor(() => expect(expandedValues(result)).toEqual(['east']));

const respond = deferNextResponse();
rerender({ dateRange: firstRange, variables: [allRegion, cloud('gcp')] });

await waitFor(() =>
expect(result.current.unavailableVariables.get('region')).toEqual({
isLoading: true,
message: 'Loading the options for Region…',
}),
);
expect(expandedValues(result)).toEqual([]);

respond(['west']);
await waitFor(() => expect(expandedValues(result)).toEqual(['west']));
});
});
});

describe('getUnavailableVariablesMessage', () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/app/src/hooks/useExpandedSqlQueryVariables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ export function getUnavailableVariablesMessage(
* macros treat as no constraint, so filters that reference each other don't
* loop. Runs the same queries as the filter bar, so they share results, but
* doesn't depend on it, since kiosk mode hides it.
*
* Every dashboard refresh moves the time range, and the options refetch then,
* even for a query that ignores the time range, so "All" picks up new values.
*/
export function useExpandedSqlQueryVariables({
filters,
Expand Down Expand Up @@ -88,6 +91,8 @@ export function useExpandedSqlQueryVariables({
dateRange,
variables,
getDashboardFilters,
// By value, so a caller passing a new but equal range doesn't refetch
refreshKey: `${dateRange[0].getTime()}-${dateRange[1].getTime()}`,
});

return useMemo(() => {
Expand Down
22 changes: 20 additions & 2 deletions packages/app/src/hooks/useSqlQueryFilterValues.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import {
ClickHouseQueryError,
ResponseJSON,
Expand Down Expand Up @@ -158,7 +158,16 @@ export function useSqlQueryFilterValues({
dateRange,
variables,
getDashboardFilters,
}: DashboardState & { filters: SqlQueryDashboardFilter[] }) {
refreshKey,
}: DashboardState & {
filters: SqlQueryDashboardFilter[];
/**
* When this changes, every query refetches, including one whose key didn't
* change because its SQL ignores the time range. A request already in
* flight is reused rather than repeated.
*/
refreshKey?: string;
}) {
const { sourcesById, isLoadingSources } = useSourcesById();
const metadata = useMetadataWithSettings();

Expand Down Expand Up @@ -225,6 +234,15 @@ export function useSqlQueryFilterValues({
})),
});

const lastRefreshKeyRef = useRef(refreshKey);
useEffect(() => {
if (lastRefreshKeyRef.current === refreshKey) return;
lastRefreshKeyRef.current = refreshKey;
for (const result of results) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — Refetched "All" options aren't treated as loading, so tiles run twice per refresh with stale options first

For a query that ignores the time range, refetch keeps the cached data and leaves isLoading false. useExpandedSqlQueryVariables (line 117) therefore expands "All" right away with the old options at the new range, so tiles run at once. When the new values arrive, the expanded variables change and the tiles run again. Queries that read the time range get a new key and wait instead, which is the behaviour the 'waits for new options' test pins. To fix this, surface a refreshKey-triggered fetch as loading, for example by tracking isFetching after a key change and mapping it to isLoading in the expansion. Then tiles wait once for the fresh options, as they do for time-aware queries.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

void result.refetch({ cancelRefetch: false });
}
}, [refreshKey, results]);

return useMemo(() => {
const data = new Map<string, { values: string[]; isLoading: boolean }>();
const erroredFilterIds = new Set<string>();
Expand Down
Loading