Repository navigation
fix(pivot-table): Correct totals for non-additive metrics - #34592
rafal-celinski wants to merge 2 commits into
Conversation
…t non-additive metrics totals
There was a problem hiding this comment.
Review by Korbit AI
Korbit automatically attempts to detect when you fix issues in new commits.
| Category | Issue | Status |
|---|---|---|
| Unsafe reduce on potentially empty array ▹ view | 🧠 Not in scope | |
| Excessive Function Nesting ▹ view | 🧠 Not in standard | |
| Excessive Intermediate Array Creation ▹ view | 🧠 Not in standard |
Files scanned
| File Path | Reviewed |
|---|---|
| superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx | ✅ |
| superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js | ✅ |
Explore our documentation to understand the languages and file types we support and the files we ignore.
Check out our docs on how you can make Korbit work best for you and your team.
| const mainQuery = queriesData.reduce((main_query, query) => | ||
| query.colnames.length > main_query.colnames.length ? query : main_query, | ||
| ); |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
| let groupbyCombinations = rows_combinations.flatMap(row => | ||
| cols_combinations.map(col => ({ rows: row, columns: col })), | ||
| ); |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
| const cellValue = (formatter = usFmt) => | ||
| function ([attr]) { | ||
| return function () { | ||
| return { | ||
| val: 0, | ||
| push(record) { | ||
| this.val = record[attr]; | ||
| }, | ||
| value() { | ||
| return this.val; | ||
| }, | ||
| format: fmtNonString(formatter), | ||
| numInputs: typeof attr !== 'undefined' ? 0 : 1, | ||
| }; | ||
| }; | ||
| }; |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
There was a problem hiding this comment.
Pull Request Overview
This PR fixes the calculation of totals for non-additive metrics (like AVG) in pivot tables. The previous approach incorrectly used aggregation functions on already-aggregated values, leading to incorrect totals. The new implementation executes multiple queries with different GROUP BY clauses and merges results to construct the correct pivot table with accurate summary rows.
- Replaces single query with multiple queries approach for accurate non-additive metric totals
- Removes aggregation function selection from UI and simplifies pivot table rendering
- Updates data structure to support multiple queries with groupby metadata
Reviewed Changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| utilities.test.ts | New test file for buildGroupbyCombinations function |
| transformProps.test.ts | Updated test to reflect new multi-query data structure |
| buildQuery.test.ts | Modified to test multiple query generation |
| types.ts | Added QueryData and Groupby types, removed aggregateFunction |
| utilities.js | Removed aggregation templates and simplified data processing |
| TableRenderers.jsx | Simplified total labels by removing aggregation function references |
| utilities.ts | New utility function to generate groupby combinations |
| transformProps.ts | Updated to handle multiple queries and new data structure |
| controlPanel.tsx | Removed aggregateFunction control and related UI elements |
| buildQuery.ts | Modified to generate multiple queries for different groupby combinations |
| PivotTableChart.tsx | Removed aggregation factory and updated data processing |
Comments suppressed due to low confidence (1)
|
There's also a Discussion on related topics #29297 We probably need to look at things like AG Grid to see how they handle this. As long as we have consensus on the change, that'll be great. |
|
Hi there. |
|
This is incredible and very needed feature. It would also be nice to have an option to start a pivot table in a collapsed state, and only do the query on expand (as does Power Bi). This would allow to do actual root-cause drill-down into datasets which are much larger than 50k. |
|
Thanks @rafal-celinski, this remains a much-wanted fix. Two things before it can land: if you could please rebase (branch is still conflicting), and let's find a way to reach consensus on the multi-query approach I raised (see Discussion #29297 and how AG Grid handles non-additive totals), since firing a query per groupby combination has performance trade-offs. Once we're aligned we'll get it reviewed. |
|
Converting this to draft whilst it awaits touchups... I think there are a couple similar PRs tackling this. Not sure if @yousoph is still ironing out the kinks on this issue. |
…lvage Co-Authored-By: Claude Fable 5 <[email protected]>
Phase 2 of the non-additive totals SIP (pivot table). Adopt the rollup-level combination generator from apache#34592 plus its 10 unit tests, and add the Groupby type. Each combination is a prefix of row dims x prefix of column dims; the empty combination is the grand total. buildQuery will issue one query per level so the DB computes each total at its own granularity (multi-query fallback; GROUPING SETS optimization to follow). Pure addition (not yet wired into buildQuery/transformProps, which must change together). SIP.md updated with phase-2 plan + the additivity gate refinement. Refs apache#25747, apache#32260, apache#36165, apache#29297 Co-Authored-By: Claude Fable 5 <[email protected]>
Make pivot subtotals/grand totals correct for non-additive metrics by computing each rollup level in the database instead of re-aggregating already-aggregated cells client-side (adapted from apache#34592, on current TS code). - buildQuery: emit one query per rollup level (prefix of rows x prefix of cols) - transformProps: zip each result with its level into QueryData[]; pick the longest-colnames result as the detail "mainQuery" for metadata/formatters - PivotTableChart: tag every record with the level (rows/columns) that produced it; drop the client-side aggregatorsFactory - react-pivottable/PivotData: replace re-aggregation with placement -- a `cellValue` passthrough stores the DB-computed value verbatim and processRecord drops it into the single matching slot (allTotal/rowTotals/colTotals/tree) - remove the now-meaningless aggregateFunction control; TableRenderers label "Total" instead of "Total (<agg>)" - update buildQuery/transformProps/tableRenders tests to the new contract; 60/60 pivot tests pass Correctness-first: multi-query runs for all metrics (correct for additive too); the additivity gate + GROUPING SETS single-query are perf optimizations tracked as phase 3 in SIP.md. Still needs in-app visual verification. Refs apache#25747, apache#32260, apache#36165, apache#38674, apache#29297 Co-Authored-By: Claude Fable 5 <[email protected]>
|
@rafal-celinski this is still a much-wanted fix for #25747. The branch is conflicting, so I'll see if I can help with the rebase to keep it moving, and we'll want to reconcile it against the other pivot-total PRs floating around. Holler if you want to keep driving it. |
Code Review Agent Run #b5a76bActionable Suggestions - 0Additional Suggestions - 6
Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
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 |
Fix incorrect totals/subtotals for non-additive metrics (ratios, COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and the regular Table chart. Totals are now computed by the database at each grouping granularity instead of re-aggregating already-aggregated cells. Pivot Table: - Emit a single query carrying `grouping_sets` (one rollup level per displayed total/subtotal); the database computes every level via native GROUPING SETS (gated by a new `supports_grouping_sets` engine capability) or a per-level fallback in QueryContextProcessor on engines without support. - transformProps splits the combined GROUPING SETS result (matched by GROUPING() markers) back into per-level data; the react-pivottable aggregator becomes a passthrough that places DB-computed values. - Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a single full-detail query is issued and rollup levels are synthesized on the client, preserving current behavior/cost. - Remove the now-meaningless "Aggregation function" control (UPDATING.md). Table chart: - Retain post-processing on the show_totals summary query so percent/ contribution columns are recomputed instead of dropped (apache#37627, apache#34350). Backend: - New optional `grouping_sets` query-object field threaded through SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the chart-data schema; byte-identical query generation when unset. - New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+ Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in superset/common/grouping_sets.py. Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite fallback), additivity detection, table summary path, and the reported-scenario matrix. Verified in-app on Postgres. Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426. Builds on apache#34592. SIP: apache#41463. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@rafal-celinski first off, thank you for this... it's what got the ball rolling on actually fixing #25747 properly. Your I've written it up as a SIP (#41463) with a working POC in #41184. Rather than have you keep fighting the rebase conflicts here, I think the cleanest path is to carry it forward there and close this one out once that lands, with credit to you. Would love your eyes on either if you have the time. Sound ok? |
Fix incorrect totals/subtotals for non-additive metrics (ratios, COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and the regular Table chart. Totals are now computed by the database at each grouping granularity instead of re-aggregating already-aggregated cells. Pivot Table: - Emit a single query carrying `grouping_sets` (one rollup level per displayed total/subtotal); the database computes every level via native GROUPING SETS (gated by a new `supports_grouping_sets` engine capability) or a per-level fallback in QueryContextProcessor on engines without support. - transformProps splits the combined GROUPING SETS result (matched by GROUPING() markers) back into per-level data; the react-pivottable aggregator becomes a passthrough that places DB-computed values. - Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a single full-detail query is issued and rollup levels are synthesized on the client, preserving current behavior/cost. - Remove the now-meaningless "Aggregation function" control (UPDATING.md). Table chart: - Retain post-processing on the show_totals summary query so percent/ contribution columns are recomputed instead of dropped (apache#37627, apache#34350). Backend: - New optional `grouping_sets` query-object field threaded through SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the chart-data schema; byte-identical query generation when unset. - New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+ Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in superset/common/grouping_sets.py. Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite fallback), additivity detection, table summary path, and the reported-scenario matrix. Verified in-app on Postgres. Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426. Builds on apache#34592. SIP: apache#41463. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
The SIP has passed, and I'm awaiting reviews. I'll close this out in favor of #41184 but if you want to reopen it, or i've overstepped here, just say the word! I'd MORE than welcome your testing/review there, by the way. Can't wait for it to merge. |
|
Hi! Thanks for the update. To be honest, I haven't had the time to fight the rebase conflicts here lately, so I'm really glad you took the initiative to carry this forward. I'm totally fine with closing this PR in favor of #41184. |
Fix incorrect totals/subtotals for non-additive metrics (ratios, COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and the regular Table chart. Totals are now computed by the database at each grouping granularity instead of re-aggregating already-aggregated cells. Pivot Table: - Emit a single query carrying `grouping_sets` (one rollup level per displayed total/subtotal); the database computes every level via native GROUPING SETS (gated by a new `supports_grouping_sets` engine capability) or a per-level fallback in QueryContextProcessor on engines without support. - transformProps splits the combined GROUPING SETS result (matched by GROUPING() markers) back into per-level data; the react-pivottable aggregator becomes a passthrough that places DB-computed values. - Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a single full-detail query is issued and rollup levels are synthesized on the client, preserving current behavior/cost. - Remove the now-meaningless "Aggregation function" control (UPDATING.md). Table chart: - Retain post-processing on the show_totals summary query so percent/ contribution columns are recomputed instead of dropped (apache#37627, apache#34350). Backend: - New optional `grouping_sets` query-object field threaded through SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the chart-data schema; byte-identical query generation when unset. - New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+ Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in superset/common/grouping_sets.py. Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite fallback), additivity detection, table summary path, and the reported-scenario matrix. Verified in-app on Postgres. Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426. Builds on apache#34592. SIP: apache#41463. Co-Authored-By: Claude Opus 4.8 <[email protected]>
SUMMARY
The previous approach, which relied on a single query with aggregate functions (e.g., SUM, COUNT), has been replaced. The new implementation achieves the same result by executing multiple, separate queries with varying GROUP BY clauses. These results are then merged to construct the final table with all required summary rows in their correct positions.
BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
Before:

After:

TESTING INSTRUCTIONS
ADDITIONAL INFORMATION