Repository navigation
fix(pivot-table): stop the grand-total corner from silently picking one metric - #44657
Conversation
Code Review Agent Run #f5986eActionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
The flagged issue is correct. In the current implementation, when multiple metrics are present, the grand-total cell receives records from different metrics. Previously, it would display the value of the last metric pushed, which is misleading. The fix correctly detects metric mismatches in To resolve this, the implementation in Would you like me to check the rest of the comments on this PR to see if there are other issues that need fixing? superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.ts |
fitzee
left a comment
There was a problem hiding this comment.
Outside this frontend diff, Python _collapsed_metric still picks the last metric, so a mixed-metric grand total that is now blank in the browser remains 100% in percent-total exports/reports. The backend needs the same mixed-metric guard.
|
You're right, and |
|
@fitzee good catch, that's real. |
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Code Review Agent Run #aadb8aActionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
… pass Restores the pre-SIP-216 "Aggregation function" choice (Sum/Average/ Median/Sample Variance/Sample Standard Deviation/Min/Max/Count/Count Unique Values/List Unique Values/First/Last, and the three "... as Fraction of ..." pairs), computed correctly this time: every cell, subtotal, and grand total reduces its own original contributing leaf query results, never another scope's already-computed output -- the correctness property SIP-216 (#41184) established, just applied to a genuinely different question than metric-definition totals answer. This is not a rehash of the pre-SIP-216 bug. The old "Aggregation function" control applied a chart-wide reducer to already-*displayed* subtotal values (re-aggregating aggregates, wrong for non-additive reducers). This is a second aggregation pass over a metric's own grouped results -- e.g. showing the median of a set of per-store SUM(sales) values -- a genuinely different, useful question the current metric-definition-only model has no way to express at all: rewriting a metric's own SQL aggregate changes its leaf cells too, which the SIP-216 architecture was specifically built to keep consistent between cells and totals. New `aggregateFunction` SelectControl, defaulting to "Use metric definition" (today's unchanged behavior). Selecting a result aggregation switches the query to full leaf detail (buildQuery.ts skips `grouping_sets` entirely, same as the additive fast path) and `PivotData.processResultRecord` (react-pivottable/utilities.ts) feeds each leaf record to every rollup scope it belongs to, reusing the existing `aggregators` template dict -- the same reducers the pre-SIP-216 pivot table used, never removed, just unused since the control was. Guards against the one real risk this reintroduces: a shared Total/ corner slot opposite the Metric pseudo-dimension can receive records from more than one metric when a chart has 2+ metrics (the same class of bug #44657, this branch's base, fixes for metric-definition mode). Extracted `cellValue`'s mixed-metric detection into a shared `makeMixedMetricTracker` helper and applied it to every result aggregator instance too, so a slot that would otherwise blend e.g. MAX(sales) with MEDIAN(msrp) blanks instead of guessing. Backend (report/export parity via client_processing.py) intentionally left for a follow-up folding into #44625, to keep this reviewable; the live browser view is the primary surface and where the bug this whole effort started from actually lives. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
… pass Restores the pre-SIP-216 "Aggregation function" choice (Sum/Average/ Median/Sample Variance/Sample Standard Deviation/Min/Max/Count/Count Unique Values/List Unique Values/First/Last, and the three "... as Fraction of ..." pairs), computed correctly this time: every cell, subtotal, and grand total reduces its own original contributing leaf query results, never another scope's already-computed output -- the correctness property SIP-216 (#41184) established, just applied to a genuinely different question than metric-definition totals answer. This is not a rehash of the pre-SIP-216 bug. The old "Aggregation function" control applied a chart-wide reducer to already-*displayed* subtotal values (re-aggregating aggregates, wrong for non-additive reducers). This is a second aggregation pass over a metric's own grouped results -- e.g. showing the median of a set of per-store SUM(sales) values -- a genuinely different, useful question the current metric-definition-only model has no way to express at all: rewriting a metric's own SQL aggregate changes its leaf cells too, which the SIP-216 architecture was specifically built to keep consistent between cells and totals. New `aggregateFunction` SelectControl, defaulting to "Use metric definition" (today's unchanged behavior). Selecting a result aggregation switches the query to full leaf detail (buildQuery.ts skips `grouping_sets` entirely, same as the additive fast path) and `PivotData.processResultRecord` (react-pivottable/utilities.ts) feeds each leaf record to every rollup scope it belongs to, reusing the existing `aggregators` template dict -- the same reducers the pre-SIP-216 pivot table used, never removed, just unused since the control was. Guards against the one real risk this reintroduces: a shared Total/ corner slot opposite the Metric pseudo-dimension can receive records from more than one metric when a chart has 2+ metrics (the same class of bug #44657, this branch's base, fixes for metric-definition mode). Extracted `cellValue`'s mixed-metric detection into a shared `makeMixedMetricTracker` helper and applied it to every result aggregator instance too, so a slot that would otherwise blend e.g. MAX(sales) with MEDIAN(msrp) blanks instead of guessing. Backend (report/export parity via client_processing.py) intentionally left for a follow-up folding into #44625, to keep this reviewable; the live browser view is the primary surface and where the bug this whole effort started from actually lives. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
geido
left a comment
There was a problem hiding this comment.
Thanks for the quick fix. I pushed a one-line update to the Median grand-total test, since it now renders $ 20 with the chart format.
|
One more thing the self-review turned up, separate from the fixes just pushed: the Not sure what the right fix is, so a few options as I see them:
Leaning towards A or B, but curious how you two would want to handle it. @fitzee @eschutho |
…ne metric Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…als; re-parent migration Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…nc messages.pot Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…docblock Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… and test coverage Keep all-NULL Sum/Average/variance scopes blank, default the MCP pivot aggregate_function to Metric so non-additive totals stay database-computed, and add tests for the tag DELETE 404 path, the Metric percent totals and the PivotTableChart result aggregation prop. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…otals Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…e-point the stale #44625 reference Review feedback on this PR caught two loose ends: - LegacyAggregationAlert's notice claimed Superset "previously ignored" the legacy aggregateFunction setting. That's only true for a chart that passed through the window between #41184 (SIP-216, which orphaned the control -- merged after the 6.1.0 tag) and this PR restoring it. A chart upgrading straight from 6.1 (or earlier) never had the setting ignored; it was active the whole time, just computed with the pre-SIP-216 bug this PR's result-aggregation work fixes. Reworded to cover both cases honestly. - client_processing.py's pivot_table_v2() comment pointed at #44625's "follow-up scope" for the export path's missing result-aggregation support, but #44625 was closed for a narrower, already-fixed bug (non-additive-metric re-aggregation under percent_mode/rollup_levels) -- the result-aggregation export gap itself was never tracked on its own. Filed #45215 for it and re-pointed the comment. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1UbxU1PCUDVwqVVUk4Uc5
…note export gap in UPDATING Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…es-only aggregations Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…t aggregation; skip grouping sets for MCP result aggregation Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…le pot entries Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…teFunction; let Accept work without Tag write
Two review follow-ups from sadpandajoe on the legacy-aggregation migration
and notice.
A chart that still carried the old `aggregateFunction` default ("Sum")
and later had a percent "Show values as" selected would have the orphaned
value restored as a result aggregation, which both changes its totals and
hides the percent display with no visible way back. `showValuesAs` only
exists since #42761 (after SIP-216 removed the control), so the percent
choice is the user's later, explicit intent: the migration now drops the
orphaned key from `params` and mirrors that into `query_context.form_data`
(as #42761 did) instead of tagging those charts. The XLSX export's percent
number format now uses the same effective-percent guard the pivot already
applies, so a stale percent setting under e.g. Average no longer renders
10 as 1000.0%.
Accepting the notice and the save-time cleanup both hit the tag DELETE
route, which needs `can_write` on Tag. A chart owner whose custom role
lacks it got a logged 403 and a notice that never went away. Both paths
now go through `removeLegacyAggregationTag`, which falls back on a 403 to
the chart PUT `tags` list, the path `validate_tags` already accepts via
`can_tag` on Chart.
Co-Authored-By: Evan Rusackas <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
- fractionOf forwards a sortValue so percent modes keep value ordering for rows whose mixed-metric total renders blank - treat a 422 from the legacy-aggregation tag DELETE as nothing to remove - drop the duplicate messages.pot entry Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
- effective_show_values_as now checks aggregateFunction against pivot_v2_aggfunc_map (the recognized result-aggregation values) instead of excluding only None/"Metric", so a stale/unrecognized value no longer wrongly suppresses an active percent showValuesAs in exports/reports. - import_chart now mirrors the 141b8ada7731 migration's orphan-drop for a pivot_table_v2 chart whose export predates the restoring aggregateFunction control, since migrations never touch charts arriving later through import. - Added a LegacyAggregationAlert test covering a failed (500) tag-removal DELETE, which must leave the notice and Accept button in place. - Added a utilities.test.ts case pinning fractionOf's own sortValue() under the default "Metric" aggregation + percent-total showValuesAs, the actual path a prior fix touched. - Corrected UPDATING.md's export/report caveat: CSV/XLSX exports do apply the restored aggregation (pivot_v2_aggfunc_map covers all 18 RESULT_AGGREGATIONS values), just to every cell instead of only totals/subtotals like the chart -- still tracked by #45215. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
…NG.md sadpandajoe flagged that the migration's downgrade-then-reupgrade limitation (a deliberately-chosen aggregateFunction + percent showValuesAs made after the control was restored is indistinguishable from the original pre-restoration orphan on replay) was only explained in a review reply, not in UPDATING.md itself. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
_drop_orphaned_pivot_aggregate_function mirrored the one-time 141b8ada7731 migration's orphan cleanup, but the migration's premise doesn't hold at import time: the migration ran once, against DB rows that necessarily predated the restoring control, so a legacy aggregateFunction paired with a percent showValuesAs could only be dead pre-SIP-216 data. Import has no such guarantee and runs forever, so it was also deleting aggregateFunction from any chart saved after the control shipped, where that pairing is just the ordinary result of switching to a result aggregation (which hides, but doesn't clear, the "Show values as" control). effective_show_values_as in client_processing.py already treats the percent mode as inert whenever aggregateFunction is active, the same way across render, export and report paths, so there's nothing left for the importer to clean up: it only needs to leave both values in place and let that existing mechanism do its job. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
A chart arriving through import with an orphaned aggregateFunction paired with a percent showValuesAs is neither dropped (the import-time mirror of that cleanup was removed in the prior commit, since it wrongly caught legitimate post-restoration charts too) nor tagged for review (import never runs migrations). It silently renders with the restored aggregation and no notice, unlike the same case migrated from an existing row. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
…format Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…is set Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The result-aggregation summaries now use the chart's own formatter, so the grand total renders with the USD prefix like its leaf cells. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…review audit A deeper self-review of this PR's own growing scope turned up several narrower correctness bugs in the restored result-aggregation machinery, independent of any single review thread: - Column sort read `.value()` instead of `.sortValue()`, so a blanked mixed-metric slot sorted arbitrarily against other rows instead of by the value it would otherwise carry. - The "Show values as" control's visibility check compared the raw `aggregateFunction` value instead of routing through `getResultAggregation()`, disagreeing with the renderer's own fallback semantics for an unrecognized/stale value. - `fractionOf`'s denominator handled a `null` denominator but not a literal zero one, producing Infinity/NaN instead of blank -- the backend's equivalent already replaces a zero denominator with NaN. Typing `fractionOf`'s two `any`s against real `Aggregator` types in the process surfaced a matching numerator-side gap (a string-valued numerator fell through to the same divide), fixed the same way as the existing denominator-side string handling right below it. - `_sample_dispersion`'s DataFrame branch only masked a scope with exactly one observation; a zero-observation scope (e.g. a metric entirely absent for one row of a sparse multi-metric pivot) fell through to NaN instead of 0, unlike the Series branch and unlike the one-observation case right next to it. - The MCP `PivotTableChartConfig.aggregate_function` schema was missing 7 of the 19 valid result-aggregation values (`List Unique Values` and all six "... as Fraction of ..." choices), silently rejecting them. Each is a narrow, self-contained fix with its own regression test; no behavioral changes beyond closing these specific gaps. Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]>
SUMMARY
With
Apply metrics on: Columnsand more than one metric on a pivot table, the rightmost "Total" column and the bottom-right grand-total corner silently show the wrong number — not an error, not blank, a plausible-looking number that just happens to be one metric's total mislabeled as the combined "Total".Repro: two metrics, e.g.
MAX(sales)andMEDIAN(msrp), row/column totals enabled. The "Total" column shows exactlyMEDIAN(msrp)'s own subtotal for every row —MAX(sales)'s contribution is silently discarded. Swap the metric order and the Total column would showMAX(sales)'s numbers instead.Root cause: the pivot table's rollup values come from a "passthrough" aggregator (
cellValueinreact-pivottable/utilities.ts) — since the database already computed every rollup level, each cell stores its one DB-computed record verbatim instead of re-aggregating. That's correct everywhere except the Total axis/corner opposite the Metric pseudo-dimension: when there's more than one metric, that slot receives one record per metric (e.g. bothMAX(sales)andMEDIAN(msrp)'s grand-total records), andpush()just overwrote its stored value on every call — "last write wins," with no indication anything was dropped.processRecord's own comment already flagged this as a known, deliberate gap ("a cross-metric total is not well defined and is left as future work") — this PR is that follow-up.Fix:
push()now tracks which metric each pushed record belongs to (via the existing__metricKeytagging already used elsewhere in this file for the same pseudo-dimension). When a second, different metric lands in the same slot, the cell renders blank instead of picking one — matching the existing convention already used for a genuine DB-computedNULL. There's no single number that means anything for "max of sales combined with median of msrp," so blank is the honest answer, not a fabricated one.This also fixes the equivalent bug in "Show values as" percent modes:
fractionOfwraps this same aggregator, and an existing test locked in a "self-consistent but still meaningless 100%" for the same mixed-metric cell (both numerator and denominator secretly reading the same last-metric value, canceling out to exactly 1.0). That test is updated to assert blank instead, sincefractionOfalready treats a null numerator as blank.Scope grew while this was in review. A separately-proposed, stacked PR (#44660, "restore result aggregation as a second aggregation pass") was reviewed on top of this branch and merged into it, so this PR now also:
resultAggregation.ts,controlPanel.tsx) as a correctly-computed second aggregation pass over a metric's own already-grouped results (e.g. the median of a set of per-storeSUM(sales)values) — not a rehash of the old, buggy re-aggregate-already-displayed-values behavior SIP-216 removed. Selecting a non-default aggregation hides the "Show values as" control (the two don't compose: a result aggregation has its own "... as Fraction of ..." choices).141b8ada7731) tagging every existingpivot_table_v2chart whoseparams.aggregateFunctionalready holds one of the pre-SIP-216 values with alegacy-pivot-aggregation-restoredtag, since that value silently starts computing with the new, correct result aggregation the moment this code ships — a chart's totals changing shape on upgrade is safe but deserves a heads-up, not silence. A chart whose orphanedaggregateFunctionis paired with an explicit percentshowValuesAsis treated as the later, more-explicit choice instead: the orphan is dropped (mirrored into the cachedquery_context.form_datatoo) and no tag is applied, since nothing about its rendering changes.LegacyAggregationAlert.tsx) that reads that tag and prompts the user to validate the chart's totals, with an "Accept" button that clears the tag; saving apivot_table_v2chart also best-effort clears it (saveModalActions.ts).effective_show_values_as(superset/charts/client_processing.py): the chart already treats a stored percentshowValuesAsas inert whenever a result aggregation is active (selecting one just hides the control, it doesn't clear the value), so every export/report code path that readsshowValuesAsnow goes through the same helper instead of risking a percent transform the live chart no longer shows.aggregateFunctionfrom any chart saved after the control shipped, wherever it happened to carry a dormant percentshowValuesAsalongside it — turning an inert stored value back into an active, incorrect percent display. Sinceeffective_show_values_asalready handles this correctly and uniformly, the importer-side cleanup was removed again; net diff againstmasterfor that file is zero.superset/common/form_data_query_context.py,superset/mcp_service/chart/schemas.py) so a pivot table built or queried through an MCP tool gets the same result-aggregation default and GROUPING-SETS handling as one built in Explore.Known, deliberately out-of-scope gaps (each tracked separately rather than silently folded in here):
Actual Valuesmode subtotals were a mean-of-means instead of the DB-computed rollup. Unrelated to the mixed-metric bug above, already onmaster.UPDATING.md): CSV/XLSX exports and CSV/text reports apply the restored result aggregation to every cell rather than scoping it to subtotals/totals the way the chart does, so e.g. aCountaggregation shows1for every leaf cell instead of the real per-cell metric value.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Not captured in this pass — no running dev environment was available while preparing this description. The two user-visible changes are:
Happy to add real screenshots/GIF before merge if useful — flag it and I'll grab them.
TESTING INSTRUCTIONS
react-pivottable/utilities.test.ts/tableRenders.test.tsx: the original mixed-metric grand-total blank-cell fix (two metrics mix → blank; single metric → unchanged), plus extensive new coverage added across review for per-reducer row/column summaries, sample statistics, null handling, and intermediate subtotals for the restored result aggregations.test_tag_pivot_tables_with_restored_aggregation.py: migration upgrade (tags only affected charts, idempotent across repeated runs, leaves unaffected charts'query_contextuntouched, drops the orphan+percent-display combo without tagging) and downgrade (strips the new default back out so older code doesn'tKeyErroron it).LegacyAggregationAlert.test.tsx/legacyAggregationTag.test.ts/saveModalActions.test.ts/ExploreChartPanel.test.tsx: the notice banner's fetch/accept/stale-request-guard behavior and the save-flow tag cleanup.test_client_processing.py:effective_show_values_asacross every combination ofaggregateFunction/showValuesAs.import_test.py: a same-version export/import round-trip asserting a chart'saggregateFunctionand dormant percentshowValuesAsboth survive import unchanged (added today, replacing two tests for the now-removed importer cleanup).Manually: build a pivot table with 2+ metrics,
Apply metrics on: Columns, row/column totals on — the Total column/corner should render blank instead of one metric's numbers. Separately, set a per-table "Aggregation function" (e.g. Median) on a single-metric pivot table and confirm "Show values as" disappears and the totals reflect the second aggregation pass.ADDITIONAL INFORMATION
paginated_update, idempotent (checked viatagged_object's unique constraint before inserting), anddowngrade()strips the new default back out so older code's aggregation lookup doesn'tKeyErroron it.test_tag_pivot_tables_with_restored_aggregation.py(upgrade: tagging, idempotency, orphan-drop, timestamps; downgrade: default-stripping).pivot_table_v2rows, paginated; no downtime, no schema/column changes, purely data (tag + param) mutation.🤖 Generated with Claude Code