Repository navigation
feat(app): exemplar overlay for metric and PromQL time charts - #2808
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 4824baf The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 packages
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 |
|
|
<!-- deep-review --> Deep Review
✅ No critical issues found in the code I was able to read — this is not a clean bill of health for the PR, since coverage was partial. 🟡 P2 -- recommended
🔵 P3 nitpicks (2)
Notes on what I did verifyThree things I checked that are correct, recorded so they are not re-flagged on a future pass:
Reviewers (1 of 13 reported): learnings-researcher. Dispatched but no results returned — none of their analysis is in this report: correctness, adversarial, security, testing, maintainability, project-standards, kieran-typescript, julik-frontend-races, performance, reliability, api-contract, agent-native. Coverage limitations:
Recommendation: re-run this review in an environment with working |
186c54f to
082981c
Compare
🔴 Tier 4 — CriticalTouches authentication, tenancy data models, the public API or shipped database config — or substantially changes the query rendering engine, background tasks, the OTel pipeline, image build, or release CI. Why this tier:
Review process: Deep review from a domain expert. Synchronous walkthrough may be required. Stats
|
E2E Test Results✅ All tests passed • 480 passed • 1 skipped • 1090s
Tests ran across 4 shards in parallel. |
9e57b96 to
240df2b
Compare
240df2b to
28ac9fb
Compare
|
<!-- deep-review --> Deep Review
✅ No critical issues found by the one reviewer that completed. 🟡 P2 — recommended
🔵 P3 nitpicks (1)
Reviewers (1 of 12 completed): testing. Dispatched but not returned: correctness, adversarial, security, reliability, performance, api-contract, frontend-races, maintainability, kieran-typescript, project-standards, agent-native. Testing gaps:
Two unverified leads worth chasing before merge — surfaced during scope reconstruction, not confirmed by a reviewer, so deliberately left unscored:
|
…es' into jordansimonovski/exemplars-overlay # Conflicts: # packages/api/src/models/team.ts # packages/app/package.json # packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx # packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts # packages/app/src/HDXMultiSeriesTimeChart/useChartScales.ts # packages/app/src/components/DBTimeChart/DBTimeChart.tsx # packages/common-utils/package.json # packages/common-utils/src/core/renderChartConfig.ts # packages/common-utils/src/types.ts
…t-chart-files # Conflicts: # packages/app/src/HDXMultiSeriesTimeChart.tsx
…es' into jordansimonovski/exemplars-overlay # Conflicts: # packages/app/package.json # packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx
| * | ||
| * The chart-editor toggle and the SQL renderer both delegate here so they can't | ||
| * drift apart. | ||
| */ |
There was a problem hiding this comment.
🔴 P1 — Exemplar-eligible aggFns include ones histogram charts cannot render
translateHistogram and translateExponentialHistogram (packages/common-utils/src/core/histogram.ts:75-86, 263-276) only support quantile and count, and throw for anything else. So avg/min/max/last_value/any/none in EXEMPLAR_COMPATIBLE_AGG_FNS can never apply, and METRIC_INELIGIBLE in exemplarToggle.ts tells users to pick avg/min/max/last value, which breaks the main chart query. Reduce the set to quantile and change the copy to say a quantile is required.
Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond
| else if (c === quote) quote = null; | ||
| continue; | ||
| } | ||
| if (c === '"' || c === "'") quote = c; |
There was a problem hiding this comment.
🟡 P2 — Paren walk ignores PromQL backtick raw strings
The quote tracker only recognises " and '. A ) inside a backtick matcher (e.g. histogram_quantile(0.9, x{path=`/a)`})) closes the call early and marks a valid expression ineligible. promqlSeriesLabels.ts already handles backticks, so add the backtick to the quote check here too: c === '"' || c === "'" || c === ''`.
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
| 'none', | ||
| ]); | ||
|
|
||
| export function isExemplarEligible({ |
There was a problem hiding this comment.
🟡 P2 — Eligibility check ignores formulas, so a formula like A * 1000 gets markers in the wrong unit
A metric chart with one histogram series and a formula such as A * 1000 (with showOperandSeries: false) draws one line, so plottedSeriesCount is 1 and isExemplarEligible passes. The axis is then in ms while the markers are in seconds. This is the same failure the PromQL whole-expression rule exists to prevent. Fix: pass hasFormulas: (config.formulas?.length ?? 0) > 0 from renderMetricExemplarsChartConfig and from getExemplarToggleState (form formulas), and refuse when it is true.
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
| // Outline that contrasts with the background (dark in light mode, light | ||
| // in dark mode) rather than matching it — the amber fill alone is | ||
| // low-contrast on a white background, so the marker needs a defined edge. | ||
| stroke="var(--color-text-default, #1a1a1a)" |
There was a problem hiding this comment.
🟡 P2 — Marker outline uses an undefined token, so it is always #1a1a1a, even in dark mode
--color-text-default is not defined anywhere in the app theme (_tokens.scss defines --color-text and --click-global-color-text-default), so the stroke always falls back to near-black. The comment promises a light outline in dark mode, which never happens. The data-viz conventions also forbid reusing --color-text-* for chart marks. Fix: use an existing chart token for the outline (e.g. a background or contrast chart token from _chart-categorical-tokens.scss) and drop the hex fallbacks.
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
| if (!enabled || configType === 'sql') { | ||
| return { showExemplars: false }; | ||
| } | ||
| if (configType === 'promql') { |
There was a problem hiding this comment.
🟡 P2 — Toggle is offered on ClickHouse-backed PromQL connections, where exemplars are always empty
queryExemplarsHandler in packages/api/src/routers/api/prometheus.ts returns {status:'success', data: []} for any connection where isPrometheusEndpoint is false. On those charts the editor still enables 'Show exemplars', the overlay stays empty, and no notice explains why. Fix: either gate showExemplars (or set exemplarIneligibleReason) on the connection being a Prometheus endpoint, or have the API return a reason that useExemplarCard surfaces as the notice.
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
| defaultValue={DEFAULT_MAX_EXEMPLARS} | ||
| placeholder={`default = ${DEFAULT_MAX_EXEMPLARS}, 0 = unlimited`} | ||
| min={0} | ||
| max={1000} |
There was a problem hiding this comment.
🟡 P2 — 'Max exemplars per chart' accepts 0 ('unlimited') and up to 1000, but both fetch paths cap at 200
EXEMPLAR_QUERY_LIMIT = 200 bounds the ClickHouse scan (LIMIT 200) and capExemplarsPerBucket on the Prometheus path. So 'unlimited', 500 and 1000 all draw at most 200 markers. Fix: cap the form and TeamClickHouseSettingsUpdateSchema at EXEMPLAR_QUERY_LIMIT and reword the '0 = unlimited' placeholder, or raise the fetch limit to follow the team setting.
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
| return null; | ||
| } | ||
| const s = traceSource; | ||
| const from = s.from.databaseName |
There was a problem hiding this comment.
🟡 P2 — Trace-meta query builds the table name by hand instead of using tableExpr/chSql
The table is built as `\`${databaseName}\`.\`${tableName}\ `` by string concatenation. That breaks on names containing a backtick, and it duplicates tableExpr in `packages/common-utils/src/clickhouse/index.ts`, which binds them as `Identifier` params. Fix: build the query with `chSql`, `tableExpr({ database, table })` and parameters, as `renderMetricExemplarsChartConfig` does.
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
| onExemplarSelect?.(exemplar, cx, cy); | ||
| }, | ||
| [onExemplarSelect, suppressNextClickRef], | ||
| ); |
There was a problem hiding this comment.
Pin close leaves hover stuck
Medium Severity
Pinning an exemplar clears the parent hover card but leaves hoveredExemplarKey set in the marker layer. Closing the pin with Escape (cursor still on the marker) therefore hides the card while isExemplarHovered stays true, so the series tooltip stays suppressed until the pointer leaves and re-enters the marker.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 29d5ae2. Configure here.
| // Reported from an effect, not the memo, so this never sets state during render. | ||
| useEffect(() => { | ||
| onExemplarsDropped?.(droppedCount); | ||
| }, [droppedCount, onExemplarsDropped]); |
There was a problem hiding this comment.
Quantized fetch inflates drop notices
Medium Severity
Exemplar fetches use a 30s-quantized window, but drop counting compares markers to the live x-domain with only one granularity of tolerance. On short live-tail ranges whose bucket is finer than 30s, overhang markers are counted as dropped and the toolbar warning stays up even though the overlay is behaving as designed.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 29d5ae2. Configure here.
|
|
||
| function collapsesHistogramBuckets(expression: string | undefined): boolean { | ||
| return !!expression && HISTOGRAM_QUANTILE_CALL.test(expression); | ||
| } |
There was a problem hiding this comment.
histogram_avg keeps le labels
Low Severity
isPromqlExemplarEligible treats histogram_avg(...) as a duration-valued overlay, but collapsesHistogramBuckets only matches histogram_quantile. For classic histograms the raw exemplar series still carry le, so a single histogram_avg line is counted as many series and the overlay is suppressed with a false multiple-series notice.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 29d5ae2. Configure here.
AI review gate — Cursor Bugbot found issues
Unresolved findings (3):
What to do:
Re-run the gate with “Re-run jobs” after an approval or a finished review. A push re-runs it automatically. |
| const [startDate, endDate] = fetchRange; | ||
| const resp = await prometheusApi.queryExemplars( | ||
| { | ||
| query: promqlExpression, |
There was a problem hiding this comment.
🔴 P1 — PromQL exemplar fetch sends the raw expression, so macros, dashboard variables and filters are never expanded
The main chart builds its query through getPromqlChartQueries (in packages/common-utils/src/core/promqlChart.ts), which calls substitutePromqlChartConfigTemplates (in macros.ts). That expands $__rate_interval, $__interval and $__range, resolves $var references, and injects config.filters matchers. This hook passes getExemplarPromqlExpression(config.promqlExpression) to /query_exemplars without any of that. Two things break. The standard histogram_quantile(0.95, sum by (le)(rate(x_bucket[$__rate_interval]))) fails to parse upstream, so the chart shows the error notice instead of markers. On a dashboard with a service filter or variable, the markers come from every service. Fix: run the config through substitutePromqlChartConfigTemplates({...config, dateRange: fetchRange}) before choosing the expression. Add a test that uses a macro and a filter.
Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond
| // other services/routes/tenants) that share the same metric name. | ||
| }; | ||
|
|
||
| const where = await renderWhere(whereConfig, metadata); |
There was a problem hiding this comment.
🔴 P1 — Metric exemplar scan skips dashboard variable substitution, so tiles that use variables query a raw $var
renderChartConfig calls substituteChartConfigVariables(rawChartConfig) first (line ~3503). renderMetricExemplarsChartConfig passes the unsubstituted config to renderWhere. Dashboard tiles arrive with variables: tileVariables (DBDashboardPage.tsx:856), so a where or aggCondition such as ServiceName IN ($service) reaches ClickHouse literally: the query errors or matches the wrong rows. Fix: call substituteChartConfigVariables(chartConfig) at the top of renderMetricExemplarsChartConfig, the same way renderChartConfig does.
Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond
| // on time charts. Sourced natively for metric/PromQL sources and generated | ||
| // per time bucket for trace sources. The UI gates the toggle on supported | ||
| // source kinds; off by default so the extra exemplar query never runs. | ||
| enableExemplars: z.boolean().optional(), |
There was a problem hiding this comment.
🟡 P2 — Schema doc says exemplars are 'generated per time bucket for trace sources', but trace sources are not supported
EXEMPLAR_SUPPORTED_KINDS in useExemplars.tsx is Metric and Promql only ('Trace-generated exemplars are added in a follow-up'), and getExemplarToggleState hides the toggle on trace sources. Remove the trace-source claim from the enableExemplars and ExemplarSchema comments, since API and MCP authors read them.
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
…plars-overlay # Conflicts: # packages/app/src/HDXMultiSeriesTimeChart/MemoChart.tsx # packages/app/src/HDXMultiSeriesTimeChart/__tests__/useChartScales.test.ts # packages/app/src/HDXMultiSeriesTimeChart/useChartScales.ts # packages/app/src/components/DBTimeChart/DBTimeChart.tsx # packages/app/src/components/DBTimeChart/__tests__/DBTimeChart.test.tsx # packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx
| query: params.query, | ||
| start: String(params.start), | ||
| end: String(params.end), | ||
| connectionId: params.connectionId, |
There was a problem hiding this comment.
🔴 P1 — PromQL exemplar request sends connectionId instead of sourceId, so the API rejects every call with a 400
The /query_exemplars handler in packages/api/src/routers/api/prometheus.ts:634 calls resolvePromqlTarget(teamId, params.sourceId). That call returns 400 'missing required parameter: sourceId' when there is no sourceId (packages/api/src/controllers/promql.ts:389), and it ignores connectionId, database and table. So every PromQL chart with exemplars enabled draws no markers and shows the error notice. Fix: give queryExemplars a sourceId: string param, as queryRange and query have, drop connectionId/database/table, and pass source.id from useExemplars.
Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond
| timestamp: 1700000000 + i, | ||
| }), | ||
| ); | ||
| mockQueryExemplars.mockResolvedValue({ |
There was a problem hiding this comment.
🟡 P2 — PromQL fetch tests mock queryExemplars but never check the params it is called with
The tests only check whether prometheusApi.queryExemplars was called and stub its response. That is why the missing sourceId and the unexpanded $__rate_interval both pass. Fix: add expect(mockQueryExemplars).toHaveBeenCalledWith(expect.objectContaining({ sourceId, query: <expanded expression> }), expect.anything()), using a config whose expression contains a macro and a filter.
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
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
There are 4 total unresolved issues (including 3 from previous reviews).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 4824baf. Configure here.
|
|
||
| // No point paying for a proxy round-trip per window on a chart that can never | ||
| // show the result. | ||
| const enabled = wantsExemplars && !tooManySeries; |
There was a problem hiding this comment.
Ineligible overlay stays silent
Low Severity
useExemplars gates metric charts only on enableExemplars and series count, not isExemplarEligible. A count or grouped histogram that still has the overlay on runs a successful empty fetch, so dropped stays unset and the toolbar never explains why markers disappeared.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 4824baf. Configure here.


The feature itself. Stacked on #2807 (the chart-file refactor) — review that first; this diff is the feature only.
Fourth of the PRs replacing #2536.
What it does
Time charts on metric and PromQL sources can overlay exemplars — individual trace-linked points. Hovering a marker shows the exemplar's own value and time plus trace metadata, with a button to open the trace.
Off by default for the whole deployment behind
NEXT_PUBLIC_ENABLE_EXEMPLARS, and per-chart behindenableExemplars.The rule the whole feature turns on
A marker sits at the trace's own measurement on the chart's shared axis. So it is only honest when the chart draws one line, in the same unit. That is enforced in four places, and most of the review findings on the original PR were cases where one of them leaked:
histogram_quantile(...) * 1000renders a different unit than its exemplars carry).Where a marker cannot be drawn honestly, it is dropped
Not moved. Outside the rendered window by more than one bucket, or below a fitted y-axis floor, and it does not render — with the count surfaced on the chart, because an overlay that silently thins out is worse than one that explains itself. The exception is above the ceiling, where pinning reads as "at least this high" and the hover card carries the real number.
Note on
common-utilsThose primitives ship in this PR rather than their own. Every one of the exemplar exports is consumed only by the app — landing them alone would fail the unused-export check with no consumer.
Included from the original PR's review rounds
Four rounds, roughly 1 P0/P1 and 15 P2s each. The substantive ones: the hover card now shows value and time (both clamps cite it as their justification and it showed neither); the PromQL aggregation parsing that decides series identity, including label matchers and quoted label names; the ClickHouse scan's
ex_TimeUnixbound, which was previously filtering on the row time while projecting the exemplar time; the query-key quantisation, which now fetches the window it keys; and the card lifecycle across zoom, live tail and display-type switches.Remaining P2/P3s are tracked in #2804 rather than blocking this.
Verification
make ci-lint,make ci-unit(5,350 tests), dashboard E2E 80 passed / 0 failed (2 flakes on listing-page specs that draw no chart).Note
Medium Risk
Large UI and query surface (marker lifecycle, PromQL series heuristics, new Prometheus calls) with careful fail-safe behavior, but mistakes could mis-attribute traces or add query load; mitigated by feature flags and eligibility guards.
Overview
Adds an exemplar overlay on metric and PromQL time charts: trace-linked diamond markers at each exemplar’s measured value/time, with hover and pin cards, trace metadata from a configurable trace source, and navigation into search or the standalone trace page. The capability is gated by
NEXT_PUBLIC_ENABLE_EXEMPLARSand per-chartenableExemplars, with eligibility rules in the chart editor (single histogram line, duration-scale aggregation, or PromQL expressions that plot duration).End-to-end wiring includes Prometheus
query_exemplars(with abortable requests), Grafana-style sampling and clamping (useExemplarMarkers,exemplarPoints, y/x bounds so outliers don’t flatten the axis), teammaxExemplars, display-settings UI, and toolbar notices for fetch errors or clamped markers. Alert/external chart config explicitly dropsenableExemplarsandexemplarTraceSourceIdso inline alerts don’t blankchartConfig.Reviewed by Cursor Bugbot for commit 4824baf. Bugbot is set up for automated code reviews on this repo. Configure here.