Skip to content

fix: refetch SQL query "All" options on every dashboard refresh - #3862

Open
karl-power wants to merge 3 commits into
claude/sql-filter-all-sql-queryfrom
claude/sql-filter-all-refresh-options
Open

karl-power wants to merge 3 commits into
claude/sql-filter-all-sql-queryfrom
claude/sql-filter-all-refresh-options

Conversation

@karl-power

@karl-power karl-power commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A SQL query filter set to "All" now refetches its options on every dashboard refresh, so new values reach tiles. Stacked on #3861, which added "All" for SQL query filters.

  • Before, an options query that doesn't use the time range kept its cache key across refreshes, and the five-minute staleTime never triggers a fetch on its own. "All" kept the options from the first load, so new services or regions stayed out of tiles until the page reloaded.
  • The refresh button, auto-refresh in live mode and time range changes all move the time range, so the page-level expansion now refetches the options of every SQL query filter with "All" selected when the range changes. This also covers kiosk mode.
  • useSqlQueryFilterValues takes a refreshKey: when it changes, every query refetches, and a request already in flight is reused. The dropdown and the page share one cache entry, so each refresh issues one options request per filter, not two, including for queries whose key changes with the range anyway.
  • Dropdowns of filters not set to "All" keep their cached options as before.

How to test

Use the test dashboard from #3861, and:

  1. Click "Edit filters", then "Add filter", and choose "SQL query values". Name it Minute, pick the connection, enter SELECT toString(toStartOfMinute(now())), set the variable name to minute, tick "Include "All" option" and save.
  2. Add a Markdown tile with the text Minute: $minute. Pick "All" in the Minute dropdown. The tile shows the current minute.
  3. Wait for the next minute and click the refresh button. The tile shows the new minute.

References


Note

Low Risk
Dashboard filter caching/refresh behavior only; no auth, security, or data-write paths. Risk is mainly extra ClickHouse options queries on refresh.

Overview
SQL query dashboard filters with "All" selected now refetch their options on every dashboard refresh (time range change), even when the options SQL ignores $__timeFilter, so tiles pick up newly appearing values instead of staying on the first load until a full page reload.

useSqlQueryFilterValues gains an optional refreshKey: when it changes, all options queries are refetched via refetch({ cancelRefetch: false }), including queries whose react-query key is unchanged. useExpandedSqlQueryVariables passes a key derived from the start/end timestamps of the dashboard date range (equal range by value does not refetch). Filter bar and tile expansion share the same query cache, so each refresh still issues one request per filter, not duplicate fetches.

New integration tests cover refresh with time-agnostic SQL, time-filtered SQL, unchanged range, and dependent-variable changes.

Reviewed by Cursor Bugbot for commit 2b90978. Bugbot is set up for automated code reviews on this repo. Configure here.

@karl-power
karl-power requested a review from a team as a code owner November 30, 2026 10:33
@vercel

vercel Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Dec 2, 2026 10:35am UTC
hyperdx-storybook Ready Ready Preview Dec 2, 2026 10:35am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2b90978

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@hyperdx/app Patch
@hyperdx/api Patch
@hyperdx/otel-collector Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

2 finding(s): 🔴 0 P0/P1 · 🟡 2 P2 · 🔵 0 P3

1 posted as inline comment(s) on the changed lines. 1 listed below.

Findings outside the changed lines

  • 🟡 P2 packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx:174 — "Equal time range" test can't detect a refetch: it asserts synchronously, but the query function calls the client asynchronously → The queryFn runs await renderValuesCall(...) before calling getClickhouseClient().query, so mockQuery is only called after a microtask. Asserting toHaveBeenCalledTimes(1) straight after rerender therefore passes even if an equal range triggers a refetch. Flush pending work first, for example with await act(async () => {}) or a short waitFor with an expected failure, then assert the call count.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found.

The refetch-on-refreshKey mechanism is implemented carefully: the lastRefreshKeyRef guard keeps the effect idempotent across useQueries' per-render array churn, and cancelRefetch: false coalesces the manual refetch with React Query's own key-change fetch so time-aware queries fetch once per refresh. Four new tests pin the main paths. Findings below are recommendations and nits, not merge blockers.

🟡 P2 -- recommended

  • packages/app/src/hooks/useExpandedSqlQueryVariables.ts:113 -- refreshKey is derived only from the range timestamps, so refreshing a dashboard pinned to a fixed/absolute range leaves the key unchanged and a time-range-ignoring "All" filter never picks up new values — the exact case the change targets, met only for relative/live ranges.
    • Fix: Fold an explicit refresh nonce into refreshKey alongside the timestamps, or document that refetch is intentionally scoped to range-moving refreshes.
  • packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx:188 -- the documented in-flight-reuse contract (cancelRefetch: false) and the error-recovery refetch path are not isolated: the only call-count guard also changes the query key, and no test re-runs a previously-errored options query on refresh.
    • Fix: Add a test that defers an in-flight response under an unchanged query key to assert a single call, and one that errors then recovers on refresh.
    • testing, correctness
🔵 P3 nitpicks (7)
  • packages/app/src/hooks/useSqlQueryFilterValues.tsx:256 -- the effect re-runs every render because results gets a fresh identity each render; correctness depends entirely on the ref-guard early-return, which a future edit could strip.
    • Fix: Add a one-line comment noting results is in the deps only to read the current array and the ref guard gates the actual refetch.
    • maintainability, kieran-typescript
  • packages/app/src/hooks/useSqlQueryFilterValues.tsx:254 -- under live auto-refresh faster than query latency, cancelRefetch: false drops rather than queues the newest refresh, so a time-range-independent "All" filter can persistently trail by ~one cycle.
    • Fix: Accept the documented tradeoff, or use cancelRefetch: true / re-run after settle if freshness on every refresh matters.
  • packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx:299 -- the equal-range "doesn't refetch" test asserts the call count synchronously with no flush, so a spuriously scheduled refetch could slip past and the guard could regress undetected.
    • Fix: Flush pending microtasks before asserting toHaveBeenCalledTimes(1), and optionally assert isFetching stays false.
  • packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx:213 -- a useSqlQueryFilterValues caller without refreshKey is mounted but never asserted on, leaving the shared-cache propagation claim and the dropdown refresh path unverified.
    • Fix: Assert the no-refreshKey return observes refreshed values via the shared cache and issues no extra fetch.
  • packages/app/src/hooks/__tests__/useExpandedSqlQueryVariables.test.tsx:244 -- the expandedValues helper reads .values after an optional-chained index (variables?.[0].values), which throws if variables is a defined-but-empty array.
    • Fix: Use variables?.[0]?.values so the helper survives an empty-options fixture.
  • packages/app/src/hooks/useSqlQueryFilterValues.tsx:306 -- the file crosses the repo's 300-line guideline (now 306) by adding the prop and refetch effect.
    • Fix: Extract the refresh-driven refetch effect into a small helper hook if staying under the limit is desired.
  • packages/app/src/hooks/useExpandedSqlQueryVariables.ts:113 -- "what counts as a refresh" lives both in the caller's refreshKey string template and implicitly in the hook, which already receives dateRange, so the two must be kept in sync.
    • Fix: Consider a boolean opt-in (e.g. refetchOnDateRangeChange) and let the hook derive the comparison key internally.

Reviewers (9): correctness, testing, maintainability, project-standards, kieran-typescript, julik-frontend-races, agent-native, learnings-researcher, previous-comments.

Pre-existing (not counted): the jscpd-flagged ~23-line clone between useSqlQueryFilterValues.tsx and usePromqlLabelFilterValues.tsx already existed on main; this PR only shifted its line numbers, and the check is advisory.

Testing gaps:

  • No isolated test for cancelRefetch: false reusing an in-flight request under an unchanged query key.
  • No test for a previously-errored options query recovering on refresh.
  • No test for a refresh landing while results is empty (sources still loading), then recovering.
  • Equal-range no-refetch test asserts synchronously without flushing async work.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Duplicate code analysis

1 new clone introduced by this PR.

  • packages/app/src/hooks/usePromqlLabelFilterValues.tsx:131-139 ↔ packages/app/src/hooks/useSqlQueryFilterValues.tsx:261-270 — 9 lines

If one of these duplicates a helper that already exists, import it instead
of redefining it. If the duplication is deliberate, ignore this comment —
the check is advisory and never fails the build.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 109 in total (1.09%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

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

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

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 495 passed • 1 skipped • 1106s

Status Count
✅ Passed 495
❌ Failed 0
⚠️ Flaky 11
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

pulpdrew
pulpdrew previously approved these changes Nov 30, 2026
@karl-power
karl-power force-pushed the claude/sql-filter-all-refresh-options branch from b3b2426 to 2b90978 Compare December 2, 2026 10:31
@github-actions github-actions Bot added the review/tier-2 Low risk — AI review + quick human skim label Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

🔵 Tier 2 — Low Risk

Small, isolated change with no API route or data model modifications.

Why this tier:

  • Standard feature/fix — introduces new logic or modifies core functionality

Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns.
SLA: Resolve within 4 business hours.

Stats
  • Production files changed: 2
  • Production lines changed: 27 (+ 162 in test files, excluded from tier calculation)
  • Branch: claude/sql-filter-all-refresh-options
  • Author: karl-power

To override this classification, remove the review/tier-2 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

});

const lastRefreshKeyRef = useRef(refreshKey);
useEffect(() => {

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 — On refresh, tiles still run once with the old "All" options for queries that ignore the time range

The refetch starts in an effect after the render that moved the range. Because the cached query already has data, isLoading stays false and useExpandedSqlQueryVariables expands "All" with the old values. Tiles therefore run for the new range with stale options, then run again when the refetch lands. Queries that use $__timeFilter behave differently: they get a new key and a new useQueries observer, so isLoading is true and tiles wait. To fix it, have the expansion report a filter as loading while a refresh-triggered refetch is pending: track the refresh key the data was fetched for and compare it with the current one, or check isFetching after a key change. Then add a test asserting unavailableVariables shows loading right after rerender({ dateRange: refreshedRange }).

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

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 2b909780 Deployed Dec 2, 2026 by vercel[bot]
Preview – hyperdx-storybook — 2b909780 Deployed Dec 2, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-2 Low risk — AI review + quick human skim

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants