Skip to content

fix: Prevent windowing on multi-key sort states w/o leading timestamp - #3907

Open
pulpdrew wants to merge 1 commit into
mainfrom
drew/fix-3905
Open

pulpdrew wants to merge 1 commit into
mainfrom
drew/fix-3905

Conversation

@pulpdrew

@pulpdrew pulpdrew commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #3905

Fixes an issue where search results were incorrectly time-windowed despite the leading ordering key not matching the timestamp expression.

Cause:

The search page bucketed a two-key sort by time because the multi-key sort string was parsed into a single entry. The windowing check then matched on the timestamp column hidden inside it.

  1. The sort picker saves a multi-key sort as one string, Duration DESC, Timestamp DESC.
  2. DBSearchPage parses that string with parseAsSortingStateString. Its regex only splits off a trailing ASC or DESC, so everything before it becomes one id. The result is { id: "Duration DESC, Timestamp", desc: true }.
  3. DBRowTable turns that into orderBy: [{ valueExpression: "Duration DESC, Timestamp", ordering: "DESC" }]. It renders to the same SQL as the original string, so the Generated SQL looks right.
  4. isTimestampExpressionInFirstOrderBy checks whether the first sort expression contains the source's timestamp column, using a substring match. "Duration DESC, Timestamp".includes("Timestamp") is true, so the query is windowed even though Duration is the leading key.
  5. Each time window then returns its own top rows by Duration, and the windows are appended in time order. Rows from a later window can have longer durations than rows already shown. That is why the order looked wrong.

Screenshots or video

Before - note that the duration increases midway down the results instead of being globally ordered descending:

Screenshot 2026-12-04 at 2 13 06 PM

How to reproduce

Play Link

  • Sort by Duration DESC, Timestamp DESC
  • Scroll past the first minute of results to find the second time window (Filter for something relatively rare to avoid having to scroll too long)
  • Notice that the Duration is ordered only within the time bucket instead of globally, due to the time windowing logic

How to test on Vercel preview

Use the reproduction steps on the preview environment and note that Duration is globally ordered.

Preview Link

References

  • Linear Issue:
  • Related PRs:

Fixes #3905


Note

Medium Risk
Changes when search pagination time-buckets queries; wrong leading-key parsing could disable windowing for timestamp-led sorts or re-enable it for multi-key sorts, but behavior is narrowly scoped and heavily tested.

Overview
Fixes incorrect global sort on multi-key Order By (e.g. Duration DESC, Timestamp DESC) where results looked ordered only within each time slice.

isTimestampExpressionInFirstOrderBy no longer treats the whole first ORDER BY fragment as one string. It derives the leading key via getLeadingSortKey (comma splits with splitAndTrimWithBracket, tuple unwrap with quote-aware findBalancedParens), then only substring-matches the timestamp against that key. Windowing in offset pagination stays enabled when timestamp leads (e.g. Timestamp DESC, Duration DESC).

parseAsSortingStateString returns null when the expression before trailing ASC/DESC contains multiple keys, so URL/table state does not collapse multi-key sorts into a single column id that re-triggers windowing.

findBalancedParens moves from variables.ts to core/utils for shared use. Unit, hook, parser, and full-stack e2e coverage assert full-range queries when the leading key is not the timestamp.

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

@pulpdrew
pulpdrew requested a review from a team as a code owner December 4, 2026 19:23
@vercel

vercel Bot commented Dec 4, 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 4, 2026 7:45pm UTC
hyperdx-storybook Ready Ready Preview Dec 4, 2026 7:45pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: fe0a057

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 Patch
@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 added the review/tier-2 Low risk — AI review + quick human skim label Dec 4, 2026
@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Tier 3 — Standard

Introduces new logic, modifies core functionality, or touches areas with non-trivial risk.

Why this tier:

  • Cross-layer change: touches frontend (packages/app) + shared utils (packages/common-utils)

Review process: Full human review — logic, architecture, edge cases.
SLA: First-pass feedback within 1 business day.

Stats
  • Production files changed: 5
  • Production lines changed: 105 (+ 228 in test files, excluded from tier calculation)
  • Branch: drew/fix-3905
  • Author: pulpdrew

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

@github-actions

github-actions Bot commented Dec 4, 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 109 in total (1.09%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

Comment thread packages/common-utils/src/core/utils.ts Resolved
@github-actions

github-actions Bot commented Dec 4, 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 · 🟡 0 P2 · 🔵 2 P3

No inline comments. 2 P3 folded at the bottom.

🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/app/src/components/DBEditTimeChartForm/utils.ts:628 — Multi-key guard in orderByToTableSortState is now redundant with parseAsSortingStateString → Since parseAsSortingStateString.parse (packages/app/src/utils/queryParsers.ts:125) now returns null when splitAndTrimWithBracket finds more than one key, this early return can never change the result. Delete it and its comment so the rule lives in one place, the parser.
  • 🔵 P3 packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx:60 — The 'multi-key string' hook case already passed before this PR → isTimestampExpressionInFirstOrderBy already split string orderBy values through getFirstOrderingItem, so 'Duration DESC, Timestamp DESC' never used windowing and this case cannot catch a regression. Only the folded valueExpression and tuple cases test the fix. Swap the string case for the real path: parse a multi-key URL value with parseAsSortingStateString and feed it into the DBRowTable-style orderBy array.

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 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

Scope: 10 files vs base 425d6a6 — fixes incorrect time-windowing of search results when a multi-key sort (e.g. Duration DESC, Timestamp DESC) does not lead with the timestamp. Narrows isTimestampExpressionInFirstOrderBy to the leading sort key via a new getLeadingSortKey helper, makes parseAsSortingStateString return null for multi-key strings, and relocates findBalancedParens into core/utils.ts.

✅ No critical issues found. The fix is correct, the findBalancedParens relocation updates all three importers with no stale deep imports, all four parseAsSortingStateString consumers null-guard the widened null result, and the quote-aware tuple/function-comma edge cases are handled and well covered by unit tests. The one behavior change the diff introduces (multi-key → empty header-sort state) is intended and does not regress query SQL. No P0/P1 issues.

🟡 P2 — recommended

  • packages/common-utils/src/core/utils.ts:1306 — leadingKey.includes(tve) matches by substring, so a sibling column whose name contains the timestamp column (realistic OTel case: ObservedTimestamp DESC with timestampValueExpression: 'Timestamp') still wrongly enables time-windowing and corrupts global ordering; this is pre-existing and the diff narrows the haystack to the leading key but does not close it.
    • Fix: Match the leading key against each timestamp expression by normalized equality (preserving the intentional function-wrapper and TimestampTime-tuple cases) rather than bare containment, as a follow-up.
    • correctness, adversarial
🔵 P3 nitpicks (3)
  • packages/common-utils/src/core/utils.ts:1304 — a paren-wrapped timestampValueExpression such as (TimestampTime, Timestamp) paired with a matching tuple ORDER BY would now disable windowing because getLeadingSortKey unwraps the ORDER BY side but the timestamp side keeps its outer parens; this appears unreachable since timestampValueExpression is always stored comma-separated without wrapping parens.
    • Fix: Add a unit test pinning the paren-wrapped timestampValueExpression tuple case, or unwrap both sides symmetrically.
  • packages/app/src/components/DBEditTimeChartForm/utils.ts:626 — the if (splitAndTrimWithBracket(orderBy).length > 1) return [] pre-check and its comment are now dead weight since the parser rejects multi-key strings internally, and the comment describes behavior the parser no longer has.
    • Fix: Remove the redundant guard and its stale comment, leaving the parseAsSortingStateString.parse call to stand alone.
  • packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx:312 — the renderWithOrderBy helper types its parameter as any, disabling type checking on the value forwarded to createMockChartConfig.
    • Fix: Type the parameter as the real orderBy union (string | { valueExpression: string; ordering: 'ASC' | 'DESC' }[]).

Reviewers (10): correctness, adversarial, testing, maintainability, api-contract, kieran-typescript, project-standards, previous-comments, agent-native, learnings-researcher.

Testing gaps:

  • No consumer-level test that multi-key orderBy yields empty sort state in DBSearchPage initialSortBy or TraceLogsPanel; only the parser is tested directly.
  • The positive "timestamp leads a multi-key sort" windowing test asserts startTime only via .not.toEqual, not the expected windowed start/size, so a wrong-but-nonzero window would pass.
  • No coverage for the substring false-positive (ObservedTimestamp vs Timestamp) or for nested-tuple leading keys (unwrapped only one level).

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 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 512 passed • 1 skipped • 1096s

Status Count
✅ Passed 512
❌ Failed 0
⚠️ Flaky 2
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

Comment thread packages/common-utils/src/core/utils.ts Resolved
Comment thread packages/common-utils/src/core/utils.ts Resolved
Comment thread packages/common-utils/src/core/utils.ts Resolved

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — fe0a0577 Deployed Dec 4, 2026 by vercel[bot]
Preview – hyperdx-storybook — fe0a0577 Deployed Dec 4, 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-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Timestamp bucketed queries are messing up the ORDER BY in the UI

1 participant