Skip to content
Draft
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/heatmap-filters-skip-column-refetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/app': patch
---

fix: Don't refetch the trace heatmap or filter values when a table column is added or removed
6 changes: 6 additions & 0 deletions .changeset/histogram-skip-column-refetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/app': patch
'@hyperdx/common-utils': patch
---

fix: Don't refetch the search histogram when a table column is added or removed
3 changes: 3 additions & 0 deletions packages/app/src/ChartUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ export function convertToTimeChartConfig(
// Overwrite (not conditionally spread) so a cleared `null` from the
// source config is normalized to undefined rather than carried over.
seriesLimit,
// Only feeds "View events" links (read from the unconverted config);
// leaving it in would refetch the chart whenever a table column changes.
eventTableSelect: undefined,
}
: {
...config,
Expand Down
86 changes: 65 additions & 21 deletions packages/app/src/DBSearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { tcFromSource } from '@hyperdx/common-utils/dist/core/metadata';
import { buildSearchChartConfig } from '@hyperdx/common-utils/dist/core/searchChartConfig';
import {
aliasMapToWithClauses,
getReferencedWithClauses,
isBrowser,
splitAndTrimWithBracket,
} from '@hyperdx/common-utils/dist/core/utils';
Expand Down Expand Up @@ -1304,13 +1305,22 @@ function DBSearchPageContent() {

const [displayedTimeInputValue, setDisplayedTimeInputValue] =
useState('Live Tail');
// The last time input the time query wrote, i.e. the applied range. User
// typing goes through setDisplayedTimeInputValue, so it differs once edited.
const [appliedTimeInputValue, setAppliedTimeInputValue] =
useState('Live Tail');
const setAppliedTimeInput = useCallback((value: string) => {
setDisplayedTimeInputValue(value);
setAppliedTimeInputValue(value);
}, []);
const isTimeInputEdited = displayedTimeInputValue !== appliedTimeInputValue;

const { isReady, searchedTimeRange, onSearch, onTimeRangeSelect } =
useNewTimeQuery({
initialDisplayValue: 'Live Tail',
initialTimeRange: defaultTimeRange,
showRelativeInterval: isLive ?? true,
setDisplayedTimeInputValue,
setDisplayedTimeInputValue: setAppliedTimeInput,
updateInput: !isLive,
});

Expand Down Expand Up @@ -1420,8 +1430,13 @@ function DBSearchPageContent() {
// completes "Explore your data". An explicit arg, not a shared ref, so
// concurrent submits can't consume each other's suppression.
const onSubmit = useCallback(
({ recordExploration = true }: { recordExploration?: boolean } = {}) => {
onSearch(displayedTimeInputValue);
({
recordExploration = true,
resolveTimeRange = true,
}: { recordExploration?: boolean; resolveTimeRange?: boolean } = {}) => {
if (resolveTimeRange) {
onSearch(displayedTimeInputValue);
}
handleSubmit(
({ select, where, whereLanguage, source, filters, orderBy }) => {
setSearchedConfig({
Expand Down Expand Up @@ -1858,12 +1873,15 @@ function DBSearchPageContent() {
parseAsInteger.withDefault(DEFAULT_REFRESH_FREQUENCY),
);

const updateRelativeTimeInputValue = useCallback((interval: number) => {
const label = getRelativeTimeOptionLabel(interval);
if (label) {
setDisplayedTimeInputValue(label);
}
}, []);
const updateRelativeTimeInputValue = useCallback(
(interval: number) => {
const label = getRelativeTimeOptionLabel(interval);
if (label) {
setAppliedTimeInput(label);
}
},
[setAppliedTimeInput],
);

useEffect(() => {
if (isReady && isLive) {
Expand Down Expand Up @@ -1995,7 +2013,11 @@ function DBSearchPageContent() {
setValue('orderBy', nextOrderBy);
}
}
onSubmit();
// Keep the current time range unless the user typed a new one:
// re-resolving a relative range would refetch the histogram for a
// column change. Live tail refetches on every tick anyway, so it always
// re-resolves.
onSubmit({ resolveTimeRange: !!isLive || isTimeInputEdited });
},
[
displayedColumns,
Expand All @@ -2004,6 +2026,8 @@ function DBSearchPageContent() {
getValues,
defaultSearchConfig.orderBy,
onSubmit,
isLive,
isTimeInputEdited,
],
);

Expand Down Expand Up @@ -2136,6 +2160,24 @@ function DBSearchPageContent() {
? searchedSource
: null;

const histogramGroupBy = resolveSearchGroupBy(groupByParam, searchedSource);

// The histogram, trace heatmap and filter queries don't select the table's
// columns, so they only take the aliases they use. The rest would refetch
// them whenever a column is added or removed. Everything but the table's
// select and sort can reference an alias, including the body, timestamp and
// sample-weight expressions.
const referencedAliasWith = useMemo(
() =>
chartConfig == null
? undefined
: getReferencedWithClauses(aliasWith, [
JSON.stringify({ ...chartConfig, select: '', orderBy: '' }),
histogramGroupBy ?? '',
]),
[chartConfig, aliasWith, histogramGroupBy],
);

const histogramTimeChartConfig = useMemo(() => {
if (chartConfig == null) {
return undefined;
Expand All @@ -2154,8 +2196,9 @@ function DBSearchPageContent() {
granularity: 'auto',
dateRange: searchedTimeRange,
displayType: DisplayType.StackedBar,
with: aliasWith,
// Preserve the original table select string for "View Events" links
with: referencedAliasWith,
// Preserve the original table select string for "View Events" links.
// convertToTimeChartConfig drops it from the query key.
eventTableSelect: searchedConfig.select ?? undefined,
// Never align to granularity boundaries on the search page: the histogram
// and total count must reflect the user's exact selected range so they
Expand All @@ -2166,15 +2209,14 @@ function DBSearchPageContent() {
alignDateRangeToGranularity: false,
// Make sure the end date is inclusive so that the histogram and table counts match
dateRangeEndInclusive: true,
groupBy: resolveSearchGroupBy(groupByParam, searchedSource),
groupBy: histogramGroupBy,
} satisfies BuilderChartConfigWithDateRange;
}, [
chartConfig,
searchedSource,
aliasWith,
referencedAliasWith,
searchedTimeRange,
searchedConfig.select,
groupByParam,
histogramGroupBy,
]);

// The default severity/status grouping reads without a legend.
Expand Down Expand Up @@ -2215,9 +2257,9 @@ function DBSearchPageContent() {
...chartConfig,
orderBy: undefined,
dateRange: searchedTimeRange,
with: aliasWith,
with: referencedAliasWith,
} satisfies BuilderChartConfigWithDateRange),
[chartConfig, searchedTimeRange, aliasWith],
[chartConfig, searchedTimeRange, referencedAliasWith],
);

// While the heatmap shows, live tail stays off as in delta and pattern modes:
Expand Down Expand Up @@ -2298,10 +2340,13 @@ function DBSearchPageContent() {
);

const filtersChartConfig = useMemo<BuilderChartConfigWithDateRange>(() => {
// The filter queries set their own select, so the table's would only
// change their query keys.
const overrides = {
select: '',
orderBy: undefined,
dateRange: searchedTimeRange,
with: aliasWith,
with: referencedAliasWith,
} as const;
return chartConfig
? {
Expand All @@ -2316,10 +2361,9 @@ function DBSearchPageContent() {
tableName: '',
},
where: '',
select: '',
...overrides,
};
}, [chartConfig, searchedTimeRange, aliasWith]);
}, [chartConfig, searchedTimeRange, referencedAliasWith]);

const openNewSourceModal = useCallback(() => {
setNewSourceModalOpened(true);
Expand Down
20 changes: 20 additions & 0 deletions packages/app/src/__tests__/ChartUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,26 @@ describe('ChartUtils', () => {
expect(granularityFromFunction).toBe('5 minute');
});

it('drops eventTableSelect so table column changes do not change the query key', () => {
const config: BuilderChartConfigWithDateRange = {
select: 'count()',
from: { databaseName: 'test', tableName: 'logs' },
where: '',
timestampValueExpression: 'timestamp',
connection: 'test-connection',
granularity: '5 minute',
dateRange: [
new Date('2025-11-26T00:00:00Z'),
new Date('2025-11-27T00:00:00Z'),
],
eventTableSelect: 'Timestamp, Body',
};

expect(convertToTimeChartConfig(config)).toMatchObject({
eventTableSelect: undefined,
});
});

// seriesLimit lives on the builder member of the ChartConfigWithDateRange
// union, so narrow the result before reading it. The per-tile value is
// read from the config itself (no team override anymore).
Expand Down
40 changes: 40 additions & 0 deletions packages/common-utils/src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getDistributedTableArgs,
getFirstOrderingItem,
getPercentileAggFnLevel,
getReferencedWithClauses,
getTextIndexDictionaryBlockSize,
hasNonEmptyOrderBy,
hasPositiveSeriesLimit,
Expand Down Expand Up @@ -3385,6 +3386,45 @@ describe('utils', () => {
});
});

describe('getReferencedWithClauses', () => {
const clause = (name: string, sql: string) => ({
name,
sql: { sql, params: {} },
isSubquery: false,
});
const withClauses = [
clause('service', 'ServiceName'),
clause('body', 'toString(Body)'),
clause('shout', 'upper(body)'),
];

it('returns undefined when nothing is referenced', () => {
expect(
getReferencedWithClauses(withClauses, ['level:error', '[]']),
).toBeUndefined();
});

it('keeps clauses the texts reference', () => {
expect(
getReferencedWithClauses(withClauses, ["service = 'api'", '[]'])?.map(
c => c.name,
),
).toEqual(['service']);
});

it('keeps clauses that a referenced clause depends on', () => {
expect(
getReferencedWithClauses(withClauses, ['shout:ERROR'])?.map(
c => c.name,
),
).toEqual(['body', 'shout']);
});

it('handles missing clauses', () => {
expect(getReferencedWithClauses(undefined, ['service'])).toBeUndefined();
});
});

describe('getLocalTableFromDistributedTable', () => {
const makeMetadata = (engineFull: string) =>
({ engine_full: engineFull }) as any;
Expand Down
32 changes: 32 additions & 0 deletions packages/common-utils/src/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1696,6 +1696,38 @@ export function aliasMapToWithClauses(
return withClauses.length > 0 ? withClauses : undefined;
}

/**
* Keeps only the WITH clauses that `texts` reference, directly or through
* another kept clause. Lets a query that doesn't select a config's columns
* (e.g. a count histogram) skip the aliases it never uses, so adding or
* removing a column doesn't change its query key.
*/
export function getReferencedWithClauses(
withClauses: BuilderChartConfig['with'],
texts: string[],
): BuilderChartConfig['with'] {
if (!withClauses) return undefined;

const kept = new Set<string>();
let haystack = texts.join('\n');
let added = true;
while (added) {
added = false;
for (const clause of withClauses) {
// Substring match over-includes (e.g. `svc` in `svc_name`), which only
// costs a refetch; under-including would break the query.
if (!kept.has(clause.name) && haystack.includes(clause.name)) {
kept.add(clause.name);
haystack += `\n${clause.sql?.sql ?? ''}`;
added = true;
}
}
}

const referenced = withClauses.filter(clause => kept.has(clause.name));
return referenced.length > 0 ? referenced : undefined;
}

const stripQuotes = (s: string) => s.replace(/^["'`]|["'`]$/g, '');

/** Parses and returns the cluster, database, and table from the given distributed table metadata */
Expand Down
Loading