Skip to content

feat(app): exemplar overlay for metric and PromQL time charts - #2808

Open
jordan-simonovski wants to merge 18 commits into
jordansimonovski/split-chart-filesfrom
jordansimonovski/exemplars-overlay
Open

jordan-simonovski wants to merge 18 commits into
jordansimonovski/split-chart-filesfrom
jordansimonovski/exemplars-overlay

Conversation

@jordan-simonovski

Copy link
Copy Markdown
Contributor

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 behind enableExemplars.

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:

  1. A single non-ratio histogram series with no group by.
  2. An aggregation that leaves the axis on the observation scale — a count of observations is not a duration, so a count-aggregated histogram gets no markers.
  3. For PromQL, an expression that plots a duration, with the duration call spanning the whole expression (histogram_quantile(...) * 1000 renders a different unit than its exemplars carry).
  4. A rendered-series count taken from the main query, not the exemplar response. Prometheus only returns series that carry a sampled exemplar, so the response answers "how many series had exemplars", not "how many lines are drawn" — a multi-line chart whose buffer happened to hold one series' worth would otherwise get markers of unknown provenance.

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-utils

Those 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_TimeUnix bound, 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).

@vercel

vercel Bot commented Aug 5, 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 Nov 25, 2026 6:05am UTC
hyperdx-storybook Ready Ready Preview Nov 25, 2026 6:05am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 5328079

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

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Minor
@hyperdx/app Minor
@hyperdx/api Minor
@hyperdx/otel-collector Minor

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

@greptile-apps

greptile-apps Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Adds exemplar overlay feature to time charts.

The PR appears safe to merge based on this re-review; no new blocking issue was established.

Summary

The PR adds a deployment-gated, per-chart exemplar overlay for eligible metric and PromQL time charts, including trace navigation, editor settings, and marker lifecycle handling. The changes since the previous review primarily merge updates from the base branch; no new actionable issue attributable to those changes was established.

Reviews (14) · Last reviewed commit: "Merge remote-tracking branch 'origin/jor..."

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

<!-- deep-review -->

Deep Review

⚠️ This review did not complete. Read the Coverage section before treating anything below as a verdict.

Bash was unavailable for the entire session — every invocation, including with the sandbox disabled, failed with bwrap: Can't create file at /home/.mcp.json: Permission denied. There are also no Grep or Glob tools registered in this session, and WebFetch was not permitted. Read against an exact path was the only working file access.

Consequence: the diff was never computable. git diff, git log, and gh pr diff were all unreachable, so there is no verified list of changed files and no way to distinguish lines this PR added from lines already present at eb1ac50b. I reconstructed part of the feature surface by following import statements from a seed path, and reviewed what I could read directly. Twelve reviewer sub-agents were dispatched against that reconstructed scope; their reports did not arrive before output was required, so none of their findings are represented here. The findings below are only those I verified myself by reading the files.

✅ 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

  • packages/app/src/components/DBTimeChart/useExemplarCard.ts:166 -- the range-change effect clears pinnedExemplar and hoveredExemplar but leaves clampDroppedCount untouched, so the "N exemplar markers fall outside the chart's plotted range" notice built at line 264 can outlive the range whose clamping produced it.
    • Fix: reset clampDroppedCount to 0 inside the same rangeKey effect that clears the two card states.
🔵 P3 nitpicks (2)
  • packages/app/src/components/DBTimeChart/useExemplarCard.ts:270 -- reportClampDropped hands out the raw setClampDroppedCount dispatcher, so its exported type accepts an updater function while the name and the consuming call site imply a plain count.
    • Fix: wrap it in a useCallback narrowed to (count: number) => void so the cross-module contract matches the name.
  • packages/app/src/components/Exemplars/exemplarPoints.ts:206 -- when the y-domain is non-numeric and visibleSeriesMax is 0, bounds collapse to {min: 0, max: 0} and clampExemplarY returns Math.min(y, 0), drawing every marker at 0 instead of at its own value.
    • Fix: treat a non-positive visibleSeriesMax as a degenerate ceiling and return early, leaving the value unclamped rather than flattening markers to the floor.

Notes on what I did verify

Three things I checked that are correct, recorded so they are not re-flagged on a future pass:

  • Exemplar.timestamp is epoch milliseconds (exemplarPoints.ts:74 divides by 1000 for the chart's second-based x unit), so exemplarTraceWindow(exemplar.timestamp) in useExemplarCard.ts:227 is operating in the right unit.
  • The window-split reduce at exemplarPoints.ts:147 has no initial value, but the split only runs when ordered.length > maxExemplars >= windowCount, so every slice is non-empty and it cannot throw on an empty array.
  • quantize.ts fetches the same quantised window it keys on (floor start / ceil end), so the cache entry is a genuine superset of every raw window mapping to that key.

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:

  • No diff. Changed-file list and added-vs-pre-existing attribution are both unverified; findings are scoped to code I read, not to this PR's actual delta.
  • Files read: DBTimeChart/DBTimeChart.tsx (partial), DBTimeChart/useExemplarCard.ts (lines 1–279), DBTimeChart/index.ts, Exemplars/index.ts, Exemplars/exemplarPoints.ts, hooks/useExemplars/quantize.ts, hooks/useExemplars/index.ts, root package.json.
  • Not reviewed at all: hooks/useExemplars/useExemplars.ts, exemplarNormalize.ts, useExemplarTraceMeta.ts (the fetch, normalisation and trace-lookup layer), HDXMultiSeriesTimeChart.tsx (marker rendering and the drop reporting that the P2 above depends on), ExemplarDot.tsx, ExemplarHoverCard.tsx, useChartToolbarItems, and everything under packages/common-utils/ — which is where the ClickHouse ex_TimeUnix scan, the PromQL duration/aggregation gating, and the four series-identity invariants described by the author actually live. The load-bearing correctness claims of this feature are in the unreviewed set.
  • No test files were located or assessed, so no statement is made about test coverage in either direction.
  • docs/solutions/ does not exist in this repo, so there were no prior learnings to apply.

Recommendation: re-run this review in an environment with working git and search tools before relying on it as a merge gate.

@jordan-simonovski
jordan-simonovski force-pushed the jordansimonovski/exemplars-overlay branch from 186c54f to 082981c Compare August 5, 2026 13:02
@github-actions github-actions Bot added the review/tier-4 Critical — deep review + domain expert sign-off label Aug 5, 2026
@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Tier 4 — Critical

Touches 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:

  • Critical-path files (2) — tenancy, public API, or shipped database config:
    • packages/api/src/models/team.ts
    • packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts
  • Query rendering engine substantially modified — 354 lines (bar: 150). Every chart, search, and alert query flows through this code:
    • packages/common-utils/src/core/renderChartConfig.ts
  • Cross-layer change: touches frontend (packages/app) + backend (packages/api) + shared utils (packages/common-utils)

Review process: Deep review from a domain expert. Synchronous walkthrough may be required.
SLA: Schedule synchronous review within 2 business days.

Stats
  • Production files changed: 32
  • Production lines changed: 2775 (+ 3525 in test files, excluded from tier calculation)
  • Critical-path lines changed: 361
  • Branch: jordansimonovski/exemplars-overlay
  • Author: jordan-simonovski

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

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 476 passed • 1 skipped • 1149s

Status Count
✅ Passed 476
❌ Failed 0
⚠️ Flaky 12
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@github-actions

github-actions Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

<!-- deep-review -->

Deep Review

⚠️ Partial run — read the coverage note before treating this as a clean bill of health. Two things degraded this review. (1) Bash is non-functional in this environment (every invocation, including echo, fails at the sandbox layer), so git diff could not be computed and scope was reconstructed by reading the working tree; Grep/Glob were also unavailable, leaving Read as the only working tool. (2) Of 12 dispatched reviewers, only 1 (testing) returned before output was required. The correctness, adversarial, security, reliability, performance, api-contract, frontend-races, maintainability, TypeScript, project-standards, and agent-native passes did not report. Absence of P0/P1 findings below reflects that, not a verified-clean diff.

✅ No critical issues found by the one reviewer that completed.

🟡 P2 — recommended

  • packages/app/src/components/DBTimeChart/useExemplarCard.ts:236 — the 273-line hover/pin card state machine has no dedicated test, and the only suite that renders it never hovers, clicks, pins, or switches display type.
    • Fix: Add a renderHook test covering pin/unpin precedence over hover, Escape dismissal of only the pinned card, display-type change clearing both cards, exemplarNotice precedence when a fetch error and a dropped-marker count coexist, and the constructed trace deep-link URL.
  • packages/app/src/HDXMultiSeriesTimeChart/useExemplarMarkers.ts:176 — the hovered-marker-dropped guard, the brush-zoom click suppression, and the onExemplarsDropped count argument are all unexercised; the existing suite only covers the pinned-marker guard and the domain-change guard.
    • Fix: Extend useExemplarMarkers.test.ts to assert hover-end fires when a hovered marker leaves the set, that a post-brush synthetic click is swallowed and suppressNextClickRef is reset, and that onExemplarsDropped receives a positive count rather than only an empty points array.
  • packages/app/src/hooks/useExemplars/useExemplarTraceMeta.ts:25 — nothing covers this hook's query gating, its per-source expression overrides, or the root-span ordering in the SQL it builds; the one suite that touches it mocks it wholesale.
    • Fix: Add a test asserting the query stays disabled without a trace id or with a non-trace source kind, that source-supplied serviceNameExpression / traceIdExpression / parentSpanIdExpression replace the defaults, and that an empty result set resolves to null instead of throwing.
  • packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx:127 — the exemplar notice toolbar item is untested in both its fetch-error and dropped-marker wordings.
    • Fix: Assert the exemplar-notice item renders only for a non-null notice and that its tooltip label equals the string passed in.
🔵 P3 nitpicks (1)
  • packages/app/src/hooks/useExemplars/quantize.ts:25 — quantizeStart / quantizeEnd have no test pinning their exact outputs, including a range short enough to quantize into a single bucket.
    • Fix: Add a unit test asserting floor/ceil behaviour exactly on and just across a 30s boundary, and that a degenerate range does not collapse the fetch window to zero width.

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:

  • useExemplarCard.ts (273 lines) is covered only incidentally, with its data hooks mocked out and no interaction ever triggered.
  • useExemplarTraceMeta.ts SQL construction and gating are unverified by any suite.
  • quantize.ts outputs are never asserted, only consumed opaquely.
  • Conversely, the eligibility gates (isExemplarEligible, isPromqlExemplarEligible) and the SQL renderers were found to carry thorough negative-case coverage — ratio, group-by, multi-series, count/sum aggregation, non-histogram types, top-level PromQL binary operators, and non-spanning duration calls. That is the best-tested part of the change.

Two unverified leads worth chasing before merge — surfaced during scope reconstruction, not confirmed by a reviewer, so deliberately left unscored:

  • prometheusApi.queryExemplars in packages/app/src/api.ts posts to v1/prometheus/query_exemplars; a partial read of packages/api/src/routers/api/prometheus.ts found only /query_range, /query, and /label/:name/values. Confirm the path resolves (a direct-to-Prometheus base URL or a rewrite would explain it) before assuming the PromQL half of the feature is wired.
  • No editor UI referencing enableExemplars or exemplarTraceSourceId was located across the chart-editor components, while in-code comments describe a toggle "next to 'As Ratio'". Confirm whether the per-chart flag is settable outside hand-edited dashboard JSON.

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


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

@greptile-apps

greptile-apps Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P1 Chart remount preserves stale card packages/app/src/components/DBTimeChart/DBTimeChart.tsx:467 ▶

    When a pinned exemplar is open and the chart temporarily enters its loading, error, or empty-data branch, the marker subtree unmounts while the card state survives. If the same exemplar exists when the chart renders again, the first-render cleanup preserves the old pixel coordinates, causing the card to point at the wrong location and suppress the normal series tooltip.

  • P1 Resize preserves stale exemplar cards packages/app/src/HDXMultiSeriesTimeChart/useExemplarMarkers.ts:1522 ▶

    When a dashboard tile, browser window, sidebar, or other containing layout is resized while an exemplar card is open, Recharts moves the marker without changing xAxisDomain, so this cleanup does not run. The card remains at its captured coordinates and continues suppressing the normal series tooltip while pointing at the wrong location.

// Trace source that an exemplar's trace id resolves against — used to fetch
// hover metadata and to deep-link straight to the trace. When unset, the
// chart source's linked `traceSourceId` is used as a fallback.
exemplarTraceSourceId: z.string().optional(),

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.

🟠 major — exemplarTraceSourceId is a raw source id, but dashboard export/import doesn't remap it

convertToDashboardTemplate in packages/common-utils/src/core/utils.ts (around line 788) swaps config.source and onClick.target.id for names so templates work on another instance. exemplarTraceSourceId lives in SharedChartSettingsSchema, so it survives TileTemplateSchema.strip() still holding the raw id. After an import it points at nothing. Because useExemplarCard takes exemplarTraceSourceId || source.traceSourceId, the dangling id also blocks the fallback to the linked trace source. The card then says no trace source is set, and Inspect opens /search?source=<bad id>. Fix: remap it to a name on export and back to an id on import, the same way source is handled.

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

// Markers dropped by the render-layer clamps. Reported up from MemoChart because
// the drop happens after the fetch, so the fetch-layer `dropped` reason cannot
// see it and the overlay would otherwise thin out with no explanation.
const [clampDroppedCount, setClampDroppedCount] = useState(0);

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.

🔵 minor — Clamp-dropped count goes stale once the plot unmounts

clampDroppedCount is only written from MemoChart's effect. When the chart switches to its loading, error or 'No data found' state, MemoChart unmounts without reporting 0. The toolbar then keeps showing 'N exemplar markers fall outside the chart's plotted range' over an empty chart. Fix: reset setClampDroppedCount(0) in the existing !isPlotRendered effect.

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

params.set('to', String(to));
Router.push(`/search?${params.toString()}`);
} else {
Router.push(`/trace/${encodeURIComponent(exemplar.traceId)}`);

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.

🔵 minor — Inspect link without a trace source has no time window, so it falls back to the last 14 days

The trace-source branch adds from/to from exemplarTraceWindow precisely so the link doesn't fall back to getDefaultDirectTraceDateRange (14 days). The /trace/<id> branch omits them. pages/trace/[traceId].tsx → buildTraceRedirectUrl forwards the query string unchanged, so a marker on an older dashboard range still opens an empty view. Fix: append the same from/to params in both branches, or build one /search URL and set source only when it is known.

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

(exemplar: Exemplar, cx: number, cy: number) => {
// Mid-drag: see brushOriginRef.
if (brushOriginRef.current != null) return;
setHoveredExemplarKey(

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.

🔵 minor — Marker key format is defined in three places that must stay in sync by hand

exemplar-${traceId}-${timestamp} is built separately in computeExemplarPoints (exemplarPoints.ts), in handleExemplarHoverStart here, and for pinnedExemplarKey in useExemplarCard.ts:152. The reset guards compare these strings. If one copy drifts, a pinned or hovered card closes immediately or never closes. Fix: export one exemplarKey(exemplar) helper from exemplarPoints.ts and use it in all three places.

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 {
activeExemplarKey,
onActiveExemplarMoved,

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.

🔵 minor — Unused return values: onActiveExemplarMoved and exemplarTraceSourceId

useExemplarMarkers returns onActiveExemplarMoved, but MemoChart never destructures it and passes the prop straight to ExemplarDot. Likewise useExemplarCard returns exemplarTraceSourceId (useExemplarCard.ts:268), which DBTimeChart never reads. Fix: drop both from the return objects.

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 {
exemplars:
enabled && !tooManySeries

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.

🔵 minor — Redundant !tooManySeries check

enabled is already wantsExemplars && !tooManySeries, so enabled && !tooManySeries re-tests the same condition. Fix: use enabled ? (query.data?.exemplars ?? NO_EXEMPLARS) : NO_EXEMPLARS.

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

? `exemplar-${pinnedExemplar.exemplar.traceId}-${pinnedExemplar.exemplar.timestamp}`
: null;

// Closing both cards when the markers move lives in useExemplarMarkers, keyed

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.

🔵 minor — Comment describes card-closing logic that no longer exists

The comment says closing both cards when markers move happens in useExemplarMarkers, keyed on the x-domain. In fact useExemplarMarkers never closes cards on movement: the active ExemplarDot reports its new position and moveExemplarCard re-anchors the card. Fix: delete this comment or rewrite it to describe the re-anchoring through onPositionChange.

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

multiline
w={280}
>
<Text component="span" c="dimmed" data-testid="exemplar-notice">

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.

🔵 minor — Icon-only warning notice has no accessible name and uses a raw dimmed colour

The notice is just an IconAlertTriangle inside a Text c="dimmed" span. The Tooltip label doesn't give it an accessible name, so screen readers announce nothing. It also breaks the 'Semantic component variants' convention, which asks for Text variant="warning" on status text instead of raw palette colours. Fix: add aria-label={exemplarNotice} (or role="img" plus a label) and use variant="warning".

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

</Text>
<Group gap={4} wrap="nowrap">
<Text size="xs" ff="monospace" truncate>
{exemplar.traceId.slice(0, 16)}…

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.

🔵 minor — Trace id always gets an ellipsis, even when nothing was cut

{exemplar.traceId.slice(0, 16)}… appends '…' unconditionally, so a short trace id appears truncated when it isn't. The truncate prop already handles overflow. Fix: render exemplar.traceId with truncate (and a title attribute), or add the ellipsis only when traceId.length > 16.

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

…es' into jordansimonovski/exemplars-overlay

# Conflicts:
#	packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx
// domain the y-axis actually renders — see computeExemplarYBounds for why an
// unclamped marker can silently vanish.
const exemplarYBounds = useMemo(
() => computeExemplarYBounds(yAxisBounds.domain, visibleSeriesMax),

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.

🟠 major — With a reference line, markers are pinned to the series max even though the axis extends higher, so they plot at a wrong value inside the axis

computeYAxisBounds returns an 'auto' upper bound whenever referenceLineValues is non-empty, and those reference lines extend the domain (see the extendDomain comment around useChartScales.ts:168). computeExemplarYBounds then falls back to visibleSeriesMax. Example: series max 40, alert threshold at 100. A trace measured at 80 is drawn at 40, on an axis that visibly runs to 100, so it reads as a real 40 rather than "at least this high". The new test at useChartScales.test.ts:358 expects this behaviour. Fix: when the upper bound is not numeric, clamp to Math.max(visibleSeriesMax, ...referenceLineValues). Better still, have computeYAxisBounds return the numeric domain it actually renders.

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

const query = useQuery<NormalizedExemplars>({
// The raw dateRange is replaced by its quantized form so a live-tail tick
// doesn't invalidate the overlay every second.
queryKey: ['exemplars', keyConfig, fetchRange?.map(d => d.getTime())],

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.

🔵 minor — Exemplar query key includes cosmetic display settings, so editing them refetches and blanks the overlay

keyConfig is the whole config minus dateRange, so numberFormat, color, legendTemplate and exemplarTraceSourceId are all part of the key. Changing any of them misses the cache, and placeholderData deliberately returns undefined because isEqual(prevQuery.queryKey[1], keyConfig) now fails. The markers vanish and the scan re-runs even though the result is unchanged. Key only on the query-relevant fields (source/connection/from, select, where/filters, granularity, promqlExpression).

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

// Key of the pinned marker, so the chart can close the card when a refetch or
// re-thinning drops that marker from the rendered set.
const pinnedExemplarKey = pinnedExemplar
? `exemplar-${pinnedExemplar.exemplar.traceId}-${pinnedExemplar.exemplar.timestamp}`

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.

🔵 minor — Marker key format is spelled out by hand in three places that must stay in sync

exemplar-${traceId}-${timestamp} is built separately in exemplarPoints.ts:77 (the rendered key), useExemplarMarkers.ts:104 (hover key) and here (pin key). The pin/hover reset effects compare these strings, so if one changes, every pinned card closes immediately. Export an exemplarKey(exemplar) helper from exemplarPoints.ts and use it at all three sites and in the tests.

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 {
activeExemplarKey,
onActiveExemplarMoved,

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.

🔵 minor — Hook returns onActiveExemplarMoved, which nothing reads, and its test passes a nonexistent arg

MemoChart destructures the hook's result without onActiveExemplarMoved and passes its own prop straight to ExemplarDot, so neither the pass-through return nor the hook arg does anything. Remove both. Also drop onExemplarPositionsChanged from useExemplarMarkers.test.ts:33. It is not a hook parameter, and the Record<string, unknown> overrides type hides the mismatch.

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 [from, to] = exemplarTraceWindow(exemplar.timestamp);
params.set('from', String(from));
params.set('to', String(to));
Router.push(`/search?${params.toString()}`);

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.

🔵 minor — Trace deep link is built by hand even though utils/directTrace.ts already has a helper for it

buildTraceRedirectUrl in packages/app/src/utils/directTrace.ts already builds /search?...&traceId= from a params string. Build the source/from/to params, then call buildTraceRedirectUrl({ traceId, search: params.toString() }), so the trace-link format has one owner.

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

dateRangeEndInclusive = true,
fitYAxisToData = false,
exemplars,
maxExemplars = 12,

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.

🔵 minor — Default maxExemplars = 12 duplicates DEFAULT_MAX_EXEMPLARS

Use maxExemplars = DEFAULT_MAX_EXEMPLARS from @/defaults, so changing the team default in defaults.ts also changes MemoChart's fallback.

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

multiline
w={280}
>
<Text component="span" c="dimmed" data-testid="exemplar-notice">

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.

🔵 minor — Exemplar notice is an icon-only, non-focusable tooltip trigger with no accessible label

The only explanation for missing or dropped markers lives in a hover tooltip on a bare <Text component="span"> icon. Keyboard users cannot focus it, and screen readers get no label. Make it focusable and labelled, for example add tabIndex={0}, role="img" and aria-label={exemplarNotice}, or use an ActionIcon variant="subtle" with aria-label.

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

…mplars-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/api.ts
#	packages/app/src/components/ChartDisplaySettingsDrawer.tsx
#	packages/app/src/components/ChartEditor/utils.ts
#	packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx
#	packages/app/src/components/DBTimeChart/DBTimeChart.tsx
#	packages/app/src/components/DBTimeChart/useChartToolbarItems.tsx
#	packages/app/src/components/__tests__/ChartDisplaySettingsDrawer.test.tsx
#	packages/common-utils/package.json
#	scripts/ci/ratchet-baseline.json
: [undefined, undefined];
return {
min: typeof lower === 'number' ? lower : 0,
max: typeof upper === 'number' ? upper : visibleSeriesMax,

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.

🟠 major — Ceiling falls back to series max while the drawn axis is taller, so in-range markers draw too low

When the y-domain top is 'auto', recharts extends the axis past the series max. Alert thresholds use ifOverflow="extendDomain" (Alerts.tsx), and recharts also nice-rounds. computeYAxisBounds returns [0,'auto'] whenever reference lines exist (useChartScales.ts:134). So with series max 40 and a threshold at 100, a 90 ms exemplar sits inside the visible axis but is pinned to 40, a height the hover card contradicts. useChartScales.test.ts asserts exactly this ({min:0,max:40} with a reference line at 100). Fix: when the top is 'auto', include max(...referenceLineValues) in the ceiling, or resolve the ceiling from the axis recharts actually renders.

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

const tolerance = Number.isFinite(bucketSeconds)
? Math.max(0, bucketSeconds)
: 0;
if (x < min - tolerance || x > max + tolerance) return null;

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.

🔵 minor — 30s fetch padding exceeds the one-bucket x tolerance at 15s granularity, so the 'markers dropped' notice fires falsely

quantize.ts pads the fetched window by up to 30s at each end, and both backends return exemplars from that padding. clampExemplarX only tolerates one bucket, which is 15s at the minimum auto granularity. On short-range charts, exemplars in the 15–30s padding are dropped and counted, and the toolbar warns that markers fall below a fitted floor or belong to a different window, when neither is true. Fix: make the tolerance at least the 30s fetch quantum, or exclude exemplars outside the unquantised dateRange before counting drops.

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

// can be 100x the p99 line) can't stretch the axis and crush the series flat —
// the marker pins to the top of the series range while its hover card still
// shows the true duration. See computeExemplarYBounds.
const visibleSeriesMax = useMemo(() => {

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.

🔵 minor — visibleSeriesMax re-implements scanYAxisValueRange

This memo is the same O(rows×series) loop as scanYAxisValueRange(graphResults, lineData) in this file (line 63), with the legend selection applied by hand. useChartScales already receives visibleLineData, so use hasExemplars ? scanYAxisValueRange(graphResults, visibleLineData).max : 0 and drop the copy.

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

// Key of the pinned marker, so the chart can close the card when a refetch or
// re-thinning drops that marker from the rendered set.
const pinnedExemplarKey = pinnedExemplar
? `exemplar-${pinnedExemplar.exemplar.traceId}-${pinnedExemplar.exemplar.timestamp}`

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.

🔵 minor — Marker key format is built by hand in three places

exemplar-${traceId}-${timestamp} is built separately in exemplarPoints.ts:77 (rendered keys), useExemplarMarkers.ts:104 (hover key) and here (pin key). The reset effects close cards whenever these strings disagree, so a change to one copy silently closes every pinned or hovered card. Export a single exemplarKey(exemplar) from exemplarPoints.ts and use it at all three sites.

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 {
activeExemplarKey,
onActiveExemplarMoved,

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.

🔵 minor — Hook returns values no caller reads

useExemplarMarkers returns onActiveExemplarMoved (just echoing its input), but MemoChart doesn't destructure it and passes its own prop to ExemplarDot instead. useExemplarCard likewise returns exemplarTraceSourceId (useExemplarCard.ts:268), which DBTimeChart never reads. Remove both from the return objects.

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

// Matches the series the exemplar belongs to (LineData.displayName) so the
// overlay can attach markers to the right line. Undefined => applies to all.
groupKey: z.string().optional(),
attributes: z.record(z.string()).optional(),

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.

🔵 minor — ExemplarSchema has a dead attributes field and comments that describe behaviour not in this PR

Nothing sets or reads attributes. The groupKey comment says it matches LineData.displayName and attaches markers to a line, but it actually holds a Prometheus label key used only for bucketing. The comments also mention trace-source exemplars generated per bucket, which this PR doesn't add. Drop attributes and correct the comments on groupKey, value and enableExemplars.

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)"

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.

🔵 minor — Chart marker strokes with a text token, against the data-viz color contract

The conventions say not to reuse --color-text-* for charts: chart colors go through the data_viz_colors.md palettes via the utils.ts helpers. The hardcoded #1a1a1a/#f5a623 fallbacks also bypass themes. Use a chart or border token for the outline, as CartesianGrid does with var(--color-border), 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

multiline
w={280}
>
<Text component="span" c="dimmed" data-testid="exemplar-notice">

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.

🔵 minor — Exemplar warning is an icon-only span with no accessible name and no keyboard access

The only explanation of a suppressed or failed overlay sits in a Tooltip on a non-focusable <span> that contains just an SVG. Screen readers announce nothing, and keyboard users can't open the tooltip. Add aria-label={exemplarNotice} and tabIndex={0}, or use a focusable element.

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

@jordan-simonovski
jordan-simonovski requested a review from a team as a code owner November 24, 2026 06:33
// Trace source an exemplar resolves against: the chart's explicit
// `exemplarTraceSourceId`, else the chart source's linked trace source.
const exemplarTraceSourceId =
queriedConfig.exemplarTraceSourceId ||

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 — Fallback to the chart source's linked trace source can never fire for metric or PromQL sources

Only Metric and Promql sources can show exemplars (EXEMPLAR_SUPPORTED_KINDS), and neither MetricSourceSchema nor PromqlSourceSchema in common-utils/src/types.ts has a traceSourceId (only Log and Session sources do). So the 'traceSourceId' in source branch is always false, and so is the drawer copy "Leave empty to use the chart source's linked trace source". An empty picker always shows "Set an exemplar trace source" and opens /trace/<id> with no source. DBTimeChartExemplarTrace.test.tsx only passes because it mocks a metric source with traceSourceId, which the schema doesn't allow. Fix: either remove the fallback and change the drawer description, or add a linked trace-source field to the metric and PromQL source schemas and fall back to that.

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

// Markers dropped by the render-layer clamps. Reported up from MemoChart because
// the drop happens after the fetch, so the fetch-layer `dropped` reason cannot
// see it and the overlay would otherwise thin out with no explanation.
const [clampDroppedCount, setClampDroppedCount] = useState(0);

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 — Clamp-drop notice stays up after the plot unmounts

clampDroppedCount is only updated by MemoChart's effect. When the chart switches to its loading, error, or "No data found" state, MemoChart unmounts and the last count stays. The toolbar (rendered in every state by ChartContainer) keeps saying "N exemplar markers fall outside the chart's plotted range" over an empty chart. Fix: reset it with setClampDroppedCount(0) in the existing !isPlotRendered effect.

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

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 — Table identifier built by hand with backticks instead of the existing tableExpr helper

tableExpr in packages/common-utils/src/clickhouse/index.ts:849 already binds {database}.{table} as Identifier parameters. Hand-quoting with backticks breaks on any name that contains a backtick, and it repeats an operation that already exists. Use tableExpr (or renderFrom) and chSql for this query.

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

knudtty
knudtty previously approved these changes Nov 24, 2026
…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
…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.
*/

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.

🔴 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;

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 — 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

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 5328079b Deployed Nov 25, 2026 by vercel[bot]
Preview – hyperdx-storybook — 5328079b Deployed Nov 25, 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-4 Critical — deep review + domain expert sign-off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants