Skip to content

fix: Fix table sorting for formula, group by, and multi-series metric aliases - #3748

Merged
kodiakhq[bot] merged 3 commits into
mainfrom
drew/chart-explorer-table-order-quoting
Nov 23, 2026
Merged

kodiakhq[bot] merged 3 commits into
mainfrom
drew/chart-explorer-table-order-quoting

Conversation

@pulpdrew

@pulpdrew pulpdrew commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Problem: Clicking the header of a table chart column whose name is an alias in the SQL (for example "duration min") could send an invalid ORDER BY. This happened for formula columns, aliased group-bys, and multi-series metric queries. Before, only series aliases were quoted.

Fix:

  • Quoting: sort ids now quote every column that is an explicit alias in the final SELECT, using the shared quotedColumnName. That covers series aliases, formula columns, aliased group-bys, and every column of a composed metric query (more than one series, or any formula). Other columns keep their bare expression, because ClickHouse can't resolve a quoted auto-generated name like "count()".
  • Shared logic: added isComposedMetricChartConfig in common-utils and reused it in renderChartConfig. The group-by column matching in useResultColumnFilterKeys (click-to-filter) now also returns each entry's alias.

Screenshots or video

Before

Screen.Recording.2026-11-20.at.2.53.56.PM.mov

After

Screen.Recording.2026-11-20.at.2.55.47.PM.mov

How to test on Vercel preview

Follow the steps from the videos

References

  • Linear Issue: Closes HDX-6136
  • Related PRs:

@pulpdrew
pulpdrew requested a review from a team as a code owner November 20, 2026 19:46
@vercel

vercel Bot commented Nov 20, 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 23, 2026 11:07am UTC
hyperdx-storybook Ready Ready Preview Nov 23, 2026 11:07am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: cb29867

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

This PR includes changesets to release 4 packages
Name Type
@hyperdx/app Patch
@hyperdx/common-utils 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-3 Standard — full human review required label Nov 20, 2026
@github-actions

github-actions Bot commented Nov 20, 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)

Additional context: touches the query rendering engine lightly (25 lines, under the 150-line bar for Tier 4)

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: 198 (+ 373 in test files, excluded from tier calculation)
  • Branch: drew/chart-explorer-table-order-quoting
  • 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

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 108 in total (1.13%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

github-actions Bot commented Nov 20, 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 · 🟡 1 P2 · 🔵 1 P3

None could be anchored to changed lines; they are listed below. 1 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/app/src/components/DBTable/sorting.ts:287 — Composed metric queries now quote plain group-by columns, so an existing ServiceName ASC Order By no longer matches its column's sort id → In composed mode, skip quoting when the name is a plain identifier (the same /^[A-Za-z_][A-Za-z0-9_]*$/ test as isPlainColumnReference in renderChartConfig.ts:2847), so the id stays ServiceName. renderMultiSeriesOrderBy already passes plain columns through unchanged. Today every column name in a composed metric query gets quoted, so the header id for a plain group-by becomes "ServiceName". Before this PR the id was the bare ServiceName, which worked through passthrough. ChartPreviewPanel builds tableSortState from the saved Order By (orderByToTableSortState), which gives id ServiceName. That no longer equals the column id, so the editor shows no sort indicator on tiles saved before this change, and the next header click starts a fresh sort instead of toggling the existing one.
🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/app/src/components/DBTable/sorting.ts:294 — Series-alias and structured group-by alias logic copies existing renderChartConfig code (DRY rule, REQUIRED) → The seriesAliases set (with isNonEmptyAlias) copies the operand-alias set at packages/common-utils/src/core/renderChartConfig.ts:1228-1232. The structured group-by branch added in useResultColumnFilterKeys.ts:84-87 copies groupByEntriesForSort (renderChartConfig.ts:2864-2873). Export and reuse those helpers, or move one shared 'explicit output aliases' helper into common-utils, so the quoting rule and the SQL renderer share one definition of what counts as an alias.

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 20, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. The ORDER BY quoting logic was traced across every branch (composed metric, series-alias-by-name, formula operands shown/hidden, group-by with/without alias, histogram packing, ratio merge) and the emitted SQL matches getAliasedResultColumns's classification in all realistic cases. Coverage is strong (unit + e2e). The items below are recommendations and nitpicks only.

🟡 P2 -- recommended

  • packages/app/src/components/DBTable/sorting.ts:81 -- The formula operand-count math (operandsHidden ? 0 : config.select.length) is recomputed here while getBuilderValueColumnCount encodes the same "operands first unless hidden, then one column per formula" contract, so a future change to operand projection must be mirrored in both or sort ids silently desync from the rendered columns.
    • Fix: Expose the operand count from getFormulaConfig (or a shared helper) and consume it in both getAliasedResultColumns and getBuilderValueColumnCount so the projection shape has one source of truth.
    • maintainability; coupling corroborated by correctness, kieran-typescript, adversarial
🔵 P3 nitpicks (6)
  • packages/app/src/components/DBTable/sorting.ts:47 -- isNonEmptyAlias returns a plain boolean rather than a type predicate, so config.select.flatMap(...) leaves seriesAliases typed Set<string | undefined> instead of the intended Set<string>; runtime is correct but the type contradicts the function's stated contract.
    • Fix: Annotate the guard as (alias: string | undefined): alias is string so the narrowing survives the flatMap.
  • packages/app/src/hooks/useResultColumnFilterKeys.ts:40 -- A string group-by with an explicit AS "alias" whose expression chSqlToAliasMap cannot parse yields alias: undefined, so getAliasedResultColumns leaves the column bare and the emitted ORDER BY references the multi-token output name unquoted (invalid SQL); realistic expressions parse fine, but group-by sorting is a newly reachable path.
    • Fix: Fall back to quoting when the resolved group-by column name is not a plain identifier.
    • adversarial, correctness
  • packages/app/src/components/DBTable/sorting.ts:89 -- Whitespace-only aliases are handled inconsistently: series aliases are filtered by isNonEmptyAlias, but a string group-by alias flows through unchecked (if (alias != null)), so Foo AS " " is treated as aliased on one path and bare on the other.
    • Fix: Reuse isNonEmptyAlias for the group-by alias presence check for symmetry.
  • packages/app/src/components/DBTableChart.tsx:161 -- With keepPreviousData: true, editing the config updates queriedConfig while data.meta still describes the previous query, so getAliasedResultColumns(newConfig, staleMeta) can misclassify a column during the placeholder window and a header click in that window sends one invalid ORDER BY; it self-corrects on the next render.
    • Fix: Recompute aliasedColumns only from settled (non-isPlaceholderData) meta.
  • packages/app/src/hooks/useResultColumnFilterKeys.ts:86 -- The structured group-by alias uses a trimmed value for the presence check but stores the original untrimmed string on the exported BuilderGroupByColumn.alias, leaking padded data to any future consumer that reads the value.
    • Fix: Store entry.alias.trim() when present.
  • packages/app/src/components/DBTable/sorting.ts:63 -- The composed-metric docstring states every output column is an explicit outer-SELECT alias, but group-by passthrough columns arrive via * EXCEPT rather than AS; behavior is correct because sort ids derive from the same meta, but the comment is inaccurate.
    • Fix: Reword the comment to note passthrough columns resolve by name rather than being explicit aliases.
    • adversarial

Reviewers (5): correctness, testing, maintainability, kieran-typescript, adversarial.

Pre-existing (not counted toward verdict): renderSelectList emits series/group-by AS aliases unescaped while the new sort id uses quotedColumnName (which doubles embedded quotes); the two escaping rules diverge for an alias containing ", though such a query fails before meta returns today.

Testing gaps:

  • No coverage for an event (non-metric) formula config with operands shown and a group-by present simultaneously.
  • No end-to-end assertion that ORDER BY resolves for a composed-metric chart grouped by an expression group-by (only plain-column and formula cases are covered).
  • No coverage for a composed multi-series metric mixing a histogram branch with a scalar branch.

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 20, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 477 passed • 1 skipped • 1049s

Status Count
✅ Passed 477
❌ Failed 0
⚠️ Flaky 8
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@kodiakhq

kodiakhq Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

@kodiakhq

kodiakhq Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

This PR currently has a merge conflict. Please resolve this and then re-add the automerge label.

karl-power
karl-power previously approved these changes Nov 23, 2026
…able-order-quoting

# Conflicts:
#	packages/app/src/components/DBTable/__tests__/sorting.test.ts
@kodiakhq
kodiakhq Bot merged commit c3928c7 into main Nov 23, 2026
28 checks passed
@kodiakhq
kodiakhq Bot deleted the drew/chart-explorer-table-order-quoting branch November 23, 2026 11:11

This branch was successfully deployed

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

Labels

automerge review/tier-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants