Skip to content

fix(cli): make stacked bar legends match what is drawn - #3385

Open
jordan-simonovski wants to merge 2 commits into
mainfrom
jordansimonovski/termchart-stacked-bar-legend
Open

jordan-simonovski wants to merge 2 commits into
mainfrom
jordansimonovski/termchart-stacked-bar-legend

Conversation

@jordan-simonovski

@jordan-simonovski jordan-simonovski commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

hdx stacked bar charts now let you tell the series apart. With more than eight series the palette repeated, so a large band could share its colour with series too small to draw, and the legend listed every series in arrival order whether it was visible or not.

  • Series are ranked by peak value before colours are assigned, as the web already ranks them, so the largest series get distinct colours.
  • The legend lists only series that drew at least one cell, followed by "+N too small to show".
  • A partial top cell takes the series that fills most of it, instead of whichever thin series is stacked highest.
  • Bars at least three columns wide get a one-column gap, so equal-height daily buckets no longer read as one block.
  • The stacked bar renderer moves to termchart/stackedBar.ts, since timeseries.ts was over 300 lines.

How to reproduce

Starting point: a log or metric source with ten or more values of a group-by column, one of which dominates.

On this branch:

  1. yarn cli:dev chart --source <source> --display stacked_bar --group-by ServiceName
  2. The legend shows only the services that appear in the bars, then a "+N too small to show" count. Each colour in the legend matches one band.

On main the same command lists every service, with colours repeating after the eighth.

How to test on Vercel preview

N/A, non-UI change.

References

@vercel

vercel Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

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

2 Skipped Deployments
Project Deployment Actions Updated
hyperdx-oss Ignored Ignored Preview Oct 20, 2026 10:19am UTC
hyperdx-storybook Ignored Ignored Preview Oct 20, 2026 10:19am UTC

Request Review

@changeset-bot

changeset-bot Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 767ef75

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

This PR includes changesets to release 1 package
Name Type
@hyperdx/cli 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 Oct 16, 2026
@github-actions

github-actions Bot commented Oct 16, 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:

  • Diff size: 431 production lines changed (Tier 2 max: < 250)

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: 431 (+ 130 in test files, excluded from tier calculation)
  • Branch: jordansimonovski/termchart-stacked-bar-legend
  • Author: jordan-simonovski

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

Comment thread packages/cli/src/shared/chartData.ts Resolved
@github-actions

github-actions Bot commented Oct 16, 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:

  • 🔴 critical or 🟠 major in code this PR adds or changes: fix before asking for review.
  • 🔵 minor in code this PR changes: your call. Fix if small, otherwise reply.
  • 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
    severity. Reply with one sentence; if it is critical, 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.

3 finding(s): 🔴 0 critical · 🟠 1 major · 🔵 2 minor

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

Findings outside the changed lines

1 minor
  • 🔵 packages/cli/src/__tests__/termchart.test.ts:113 — Legend tests never check that drawn series survive the tail-fitting pop loop → Neither keeps the legend and its hidden count within the width nor the renderLegend cases cover a full legend that fits on fewer rows than the drawn labels plus the tail. That is the case where the while (...) last.pop() loop in ansi.ts removes visible series. Add a case where the hidden series has a short name and the drawn labels nearly fill one line, then assert that every drawn series is still listed.

Severity is the reviewer's own estimate and is used for ordering, not filtering. No finding blocks merge automatically; a maintainer decides.

@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] This PR appears safe to merge; no actionable issues remain.

Summary

Updates hdx stacked bars so their legends match the series actually drawn.

  • Stacked-bar charts give large series distinct colors and match legends to visible bands.

Both earlier, unnumbered findings are fixed in this PR: the legend fits its hidden count into the reserved space, and partial cells use the largest overlap. No new actionable issues were found.

Reviews (3) · Last reviewed commit: "fix(cli): keep the stacked bar legend wi..." · Reviewed by Greptile

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. This PR is a well-scoped, well-tested CLI rendering change. The two prior greptile findings (legend exceeding chart width; a smaller series winning a partial top cell) are both genuinely resolved in the current code, each with a dedicated regression test. No correctness, security, or data-integrity issues surfaced. Remaining items are maintainability/test-coverage polish.

🟡 P2 — recommended

  • packages/cli/src/shared/chartData.ts:323 — the new Number.isFinite peak guard and the new peak-based sort tiebreak are only exercised with finite inputs, so the non-finite exclusion path is untested.
    • Fix: Add a case where a series carries a NaN/Infinity sample but a small finite peak and assert it is not ranked ahead of larger finite series.
🔵 P3 nitpicks (4)
  • packages/cli/src/termchart/stackedBar.ts:19 — RenderTimeChartOptions is now a cross-renderer contract but is imported from timeseries.ts, leaving the stacked-bar renderer coupled to a sibling renderer for a pure type (type-only import, so no circular-import or runtime risk).
    • Fix: Move RenderTimeChartOptions to types.ts alongside TimeChartData/TimeChartSeries so both renderers depend on a neutral module.
    • kieran-typescript, maintainability
  • packages/cli/src/termchart/stackedBar.ts:42 — the gutter constants (labelWidth, gutterWidth), the plotHeight/plotWidth clamp math, and the trailing [body, axis, …].filter().join('\n') assembly are duplicated verbatim between timeseries.ts and stackedBar.ts after the extraction and can drift independently.
    • Fix: Hoist the gutter constants and an assemble() helper into ansi.ts so both renderers stay in lockstep.
  • packages/cli/src/termchart/ansi.ts:147 — renderLegend now layers label wrapping, tail-text selection, spare-line reservation, and a pop-to-fit loop into one closure-heavy function that recomputes tail(listed()) on every check, making the next edit here high-risk.
    • Fix: Split into a layoutLines() and appendTail() pair and name explicit LegendLabel/LegendLine types instead of the (typeof labels)[] alias.
    • kieran-typescript, maintainability
  • packages/cli/src/termchart/stackedBar.ts:37 — fullLegend is rendered only to measure legendHeight and then discarded, with the printed legend produced by a second renderLegend call; the two call sites must stay in sync through maxLines = legendHeight - 1, which is subtle.
    • Fix: Extract a measureLegendHeight(series, width) helper (or rename the probe variable) so the measure-then-draw intent is explicit.

Reviewers (7): correctness*, adversarial*, kieran-typescript, maintainability, testing, previous-comments, project-standards. (*The correctness and adversarial reviewers did not return before synthesis; their lanes were covered by an independent orchestrator pass over the legend height-reservation, bestOverlap partial-cell attribution, isGap bounds, and division-by-zero guards — no critical issues found. previous-comments and project-standards returned clean.)

Testing gaps:

  • renderStackedBarChart has no non-finite (NaN/Infinity) input test; the finite guards (stackedBar.ts:51,132) and the maxTotal <= 0 no-data path are uncovered for this renderer.
  • The isGap threshold (plotWidth >= buckets.length * 3) is asserted only in the gap-enabled direction; the no-gap branch is never pinned.
  • Partial-cell tests assert only legend membership, not the actual top-cell glyph/color, so a mis-colored top cell that still marks the right series as drawn would pass.
  • The renderLegend pop-to-fit loop stops when a line empties, so a tail string alone wider than width could overflow at implausibly small widths — benign at realistic terminal sizes, but unclamped and untested.

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 Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 440 passed • 1 skipped • 1379s

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

Tests ran across 4 shards in parallel.

View full report →

@jordan-simonovski

Copy link
Copy Markdown
Contributor Author

Replies to the review findings outside the changed lines, all addressed in 971b042f7:

Partial-top-cell test passes with the old sampling code too

Added the 1000/13/11/6 case, which fails under both the old sampling and the midpoint rule. Cells are now assigned by largest overlap.

"+N too small to show" is added after renderLegend's width limit and its "+N more"

renderLegend now lays out the hidden count itself and keeps the line within width, together with its own "+K more".

When buckets are downsampled, large series get labelled "too small to show"

The label is now "+N not shown", which is true for both causes: a series too thin to fill a cell, or one whose buckets were merged away to fit the width.

}

// Sized for every series; the drawn legend lists only those that show up.
const fullLegend = showLegend ? renderLegend(series, width) : '';

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 — Legend rows are reserved without room for the +N not shown tail, so visible series get dropped from the legend

Here is a case that fails. At width 60 there are two large series whose labels are 26 chars each, plus one tiny undrawn series x. The full legend fits on one line (26+2+26+2+3 = 59), so maxLines becomes 1. The legend that is actually drawn needs 26+2+26+2+12 = 68 chars, so renderLegend pops B, a full-height visible band, and prints ● A +2 not shown. That is the mismatch this PR is meant to remove. Fix: when sizing the plot, reserve legend rows for the labels plus a worst-case tail. Alternatively, work out the drawn set before fixing plotHeight (for example with a first pass at the tentative height). Either way, renderLegend should never have to evict a drawn series to fit the count.

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 shownSeries = series.filter(s => drawn.has(s.dataKey));
const legendLines = showLegend
? renderLegend(
shownSeries,

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 — The chart can come out shorter than height when the drawn legend needs fewer rows than the full one

plotHeight is sized from fullLegend, which lists every series. The drawn legend is often much shorter. For example, with 12 series and 2 drawn, the full legend takes 2 rows but shownSeries plus the tail fits on 1. The output is then one line shorter than the requested height, leaving a blank row under the tile in the dashboard grid. Fix: pad the legend to the reserved row count, or size plotHeight from the legend that is actually rendered.

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

With more than 8 series the palette repeated, so a large band could share
its colour with series too small to draw, and the legend listed all of them
in arrival order. Series are now ranked by peak like the web, the legend
lists only series that are visible (with a count of the rest), a partial top
cell takes the series filling most of it, and wide bars get a gap column.
The stacked bar renderer moves to its own file.
Address review feedback on #3385:

- The hidden-series count is now laid out by renderLegend, which reserves
  room for it (and for its own "+K more") instead of appending past the
  width; it takes a spare legend row when one is free.
- Undrawn series are counted as "+N not shown", since merged buckets can
  leave large series undrawn, not only small ones.
- A partial cell goes to the series overlapping most of its filled part.
- The peak-ranking comment no longer claims to match the web.
@jordan-simonovski
jordan-simonovski force-pushed the jordansimonovski/termchart-stacked-bar-legend branch from 971b042 to 767ef75 Compare October 20, 2026 10:19

This branch was previously deployed

1 inactive (outdated) deployment
Preview – hyperdx-storybook — 971b042f Deployed Oct 19, 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.

1 participant