Repository navigation
fix(cubestore): cast aggregating index aggregation results back to the declared column types - #11413
Conversation
…e declared column types Building an aggregating index runs the declared aggregations over chunk data, and DataFusion widens some aggregate output types — a decimal SUM gains 10 digits of precision, so a Decimal128(18, 5) column comes back as Decimal128(28, 5). The widened batches then failed RecordBatch validation against the index schema inside concat_batches().unwrap(), so any table with an aggregating index over a decimal measure and actual data failed to build with 'task N panicked' instead of an error. Wrap the aggregation plan into a projection casting each diverged column back to the index schema, both on the ingestion path (post_process_columns) and on the compaction/repartition path (merge_chunks). The cast uses safe: false so a sum genuinely overflowing the declared precision fails the job instead of silently becoming NULL. The concat_batches unwraps are replaced with error propagation so a future type mismatch surfaces as a diagnosable error rather than a panic in a spawned task.
|
Claude finished @waralexrom's task in 3m 51s —— View job Review: looks correct and well-scoped — 0 blocking, 1 medium, 2 low (3 inline comments)Full review
VerdictThe diagnosis and the fix both hold up. Coverage of the aggregating paths looks complete. Every place that runs the declared aggregations over chunk data is either Things I checked that are fine:
Test coverage is solid: the sql test covers both the CSV Findings
Not verifiedI did not compile or run the tests — cubestore builds DataFusion from the No security or performance concerns. No documentation changes needed — this is an internal correctness fix. |
Codecov Report✅ All modified and coverable lines are covered by tests.
Additional details and impacted files@@ Coverage Diff @@
## master #11413 +/- ##
===========================================
- Coverage 83.92% 59.00% -24.93%
===========================================
Files 257 223 -34
Lines 80755 17891 -62864
Branches 0 3636 +3636
===========================================
- Hits 67777 10556 -57221
+ Misses 12978 6817 -6161
- Partials 0 518 +518
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Restrict cast_plan_to_schema to the only known-legitimate divergence — a decimal precision change at the same scale — so a positional drift between the plan output and the index columns fails loudly instead of silently casting a column to a wrong type. A field-name check would not work here: aggregate output fields carry the 'SUM(col)' alias rather than the column name. Add the index and table names to the ingestion-path error context, and cover the safe: false overflow behavior with a test: a per-key sum overflowing the declared decimal(18, 5) fails the insert with a diagnosable error instead of panicking or storing NULL. Also validate output ordering on the plan actually executed (after the cast projection) rather than on the pre-cast aggregate.
|
Claude finished @waralexrom's task in 2m 25s —— View job Re-review of
|
| Aggregate | Declared type | DF output | Diverges? |
|---|---|---|---|
sum(decimal(p,s)) |
Decimal128(p,s) |
Decimal128(min(38,p+10), s) |
yes — same scale, cast applies |
sum(decimal96) |
Decimal128(p,s) |
same widening | yes — same scale, cast applies |
sum(int) / sum(int96) |
Int64 / Decimal128(38,0) |
Int64 / Decimal128(38,0) (capped) |
no |
sum(float) |
Float64 |
Float64 |
no |
min/max |
any | input type | no |
merge (HLL) |
Binary |
Binary (udfs.rs:715) |
no |
No path produces a scale change or a non-decimal widening, so the hard error is unreachable for valid schemas. And since any divergence panicked in concat_batches before this PR, an error here is strictly an improvement even if some future case does trip it.
2. Overflow test (aggregate_index_decimal_overflow) — the arithmetic checks out: each 9000000000000 scales to 9e17, which fits Decimal128(18,5) (max ~9.99e17); the per-key sum scales to 1.8e18, which does not. The intermediate Decimal128(28,5) holds it fine, so the failure lands exactly on the safe: false cast, which is the behavior being pinned. Correctly added to MIGRATION_TEST_EXCLUSION_SET.
3. Error context (store/mod.rs:2896-2903) — collect failures on the ingestion path now carry the index and table name.
4. assert! moved below the cast (store/mod.rs:2882-2886) — now validates the executed plan. ProjectionExec projects the group-key columns as identity Column exprs (no cast — their types match), so DF maps the input ordering through and output_ordering().len() == key_size still holds. aggregate_index_decimal exercises this exact path, so CI is the check here — if DF didn't propagate the ordering, that test would panic rather than pass silently.
Remaining (low, optional)
| Sev | Where | Note |
|---|---|---|
| Low | compaction.rs merge paths |
The index/table context was added on the ingestion path only. A cast overflow during compaction/repartition still surfaces as a bare Invalid argument error: ... too large to store in a Decimal128 of precision 18. The scheduler logs the failing job's partition id alongside it, so it's diagnosable with one extra hop — fine to leave, but wrapping the merge_chunks callers the same way would make it self-describing. |
| Low | tests.rs overflow test |
msg.contains("too large to store") couples the test to arrow's wording; a future DF bump could turn a real regression into a confusing test failure. Asserting only that the insert errors, or matching on the error variant, would be more durable. Minor — the current form does document the intent well. |
Neither blocks. No security or performance concerns; no docs needed.
Not verified
Still haven't compiled or run tests — cubestore builds DataFusion from the cube-46.0.1 git fork, which isn't cached in this environment. CI is the authority on the build and on the two knockout results reported in the description.
· branch cubestore-agg-index-decimal-cast ·
Building an aggregating index over a decimal measure used to panic before any query ran — the sum widened to `Decimal128(28, 5)` against a column declared `Decimal128(18, 5)`. Fixed in #11413, so the test runs: the rollup with an aggregating index returns exactly what the plain one does, which is the property worth pinning, and it is now the regression guard for that cast. The four-entrypoint query stays ignored; a plan that deep still exceeds Cube Store's protobuf decode recursion limit, which reproduces on a real model too.
…11400) * fix(tesseract): project the requested grain into rolling-window CTEs A `case` entrypoint dispatching between rolling-window measures on a `type: switch` calc-group dimension could not be queried with a granular time dimension: planning failed with "Alias not found for partition_by dimension <calc group>". The rolling-window CTE built its projection from the ROOT query dimensions, while the case parent adds the switch dimension to the grain of everything below it. The arithmetic layer above the rolling windows (e.g. `r3 - prev_r3`) then partitions by that switch dimension and looks it up in the CTE schema, where it was never projected. Building the CTE schema from the description's own state fixes it and also covers the `grain: include` widening of the same shape. - rolling-window CTEs project `description.state()` dimensions and time dimensions instead of the root query's - rust: fixture gains a `window_kind` switch dimension plus case entrypoints over the rolling / rolling-change measures, and a regression test building SQL for them with a month time dimension - schema-compiler: month-granularity specs on the shared calc-group Postgres suite — the sales rollup serves the query with deterministic monthly values; a new model variant keys the joined cube's rollup on the queried time dimension and both rollups are served, with the rollup result asserted equal to the raw-source result Two remaining matching limitations are pinned by the new specs: a rollup keyed on its own (join-equal) time dimension can't serve a query grouping by the other side's dimension, and losing one cube's rollup drops the whole query to the raw source; and expressing the range as an `inDateRange` filter on the time dimension instead of `timeDimensions[].dateRange` stops every rollup from matching (skipped FIXME spec). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CmA7TSPTdq9z83Am3e7s4u * test(cubejs-testing): Cube Store smoke coverage for month-granularity rolling queries Adds the month-granularity time-dimension queries to the shared calc-group birdbox suite and keys the share_metrics rollup on the time dimension the view exposes (`sales.date`), so the planner can match both rollups — the cube's own `share_metrics.date` is equal by the join condition but is not a member the matcher can resolve. The four existing no-time-dimension smoke tests still pass with that fixture change. The two new queries are skipped: the plan is planned and matched correctly (covered end to end against Postgres in the schema-compiler suite) but Cube Store cannot execute it — Internal: Optimizer rule 'optimize_projections' failed Schema error: No field named fk_aggregate.sales__r3_amount The rolling-window CTE groups by (date, product, calc group) while its consumer projects a strict subset of those group-by columns — dropping the filter-pinned calc-group column but keeping the aggregate — and Cube Store's projection optimizer prunes the aggregate out of the CTE schema. A plain rolling measure at month granularity over the same rollup (no `case` entrypoint, so no calc-group column in the CTE) is served by Cube Store without trouble, and the same SQL runs on Postgres, so this is specific to the calc-group projection shape. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CmA7TSPTdq9z83Am3e7s4u * test(tesseract): use month-based rolling windows in the calc-group switch fixture The switch case entrypoints dispatched between a 7-day trailing window and the year-to-date one. A 7-day window can never be served from a rollup stored at month granularity, so it does not match the shape these specs stand in for. Adds a `rolling_sum_3m` (trailing 3 month) leaf and dispatches between whole-month windows — trailing 3 month vs year-to-date — with the switch values renamed R3 / YTD accordingly, mirroring the model in the schema-compiler and birdbox suites. The regression test still fails with "Alias not found for partition_by dimension orders.window_kind" when the rolling-window CTE projection fix is reverted. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CmA7TSPTdq9z83Am3e7s4u * test(tesseract): cover switch/calc-group rolling windows over rollups end to end Every shape the calc-group switch model produces is now exercised twice: served from an external rollup in CubeStore, and straight from the source Postgres with pre-aggregations filtered out. The two results are compared cell by cell, with timestamp rendering normalised and numbers rounded (ratios are f64 in CubeStore against Postgres NUMERIC, so they differ in the last digit), which pins the rollup path as an optimization rather than a different answer. A separate always-running test asserts rollup matching for all of them, independently of whether an engine can execute the plan. New fixture integration_cubestore_switch_rolling.yaml mirrors the shapes of a production model: a `type: switch` dimension with trailing and to-date windows behind one `case` entrypoint, an entrypoint dispatching straight onto a `time_shift` measure, a difference and a ratio layer above the rolling windows, grain by an own dimension and by a joined cube's, and rollups that variously omit the calc group, store it, or carry an aggregating index. The seed carries data from the preceding year so a 12-month trailing window and year-to-date produce different sums — without it the two coincide and a test could not tell them apart. Two shapes stay ignored for CubeStore limitations unrelated to the calc-group grain, each with the reason on the test: a four-entrypoint query builds a plan too deep for CubeStore to decode (protobuf recursion limit), and a rollup with an aggregating index fails at table creation with a column-type mismatch. Also adds rolling_sum_7d_reduce_time and an executed test for it: an Aggregate parent that reduces by the time dimension makes the child rolling-window state narrower than the root query, and the rolling CTE must still project and group by the rolling time dimension so the time_series join does not fan out. * test(tesseract): address review of the switch/rolling coverage Five points from the review, all in the test layer: Stale docs. The note on `test_case_entrypoint` described the CubeStore `RollingOptimizerRule` widening in the present tense, but that test is not ignored and holds a real CubeStore snapshot — #11410 is an ancestor of this branch and fixes exactly that rewrite. Reworded to past tense, naming the fix and what the test now guards. The birdbox `FIXME` had the same problem: the Cube Store side is fixed, what still blocks those two specs is that birdbox pulls the published `cubejs/cubestore:latest` while the Cube server is built from the working tree, so only the planner fix is in the containers under test. Value coverage in the plain Postgres configuration. `run_both` computed the raw-source rows and threw them away unless CubeStore was also available, so a run without `integration-cubestore` asserted only rollup matching. It now snapshots `normalize()` of whichever engine ran; the snapshots become engine-independent tables instead of one engine's rendering, and the values are pinned in an ordinary `cargo test --features integration-postgres` run. Separator filter. `normalize()` dropped every line starting with `-`, which would silently discard a data row whose first cell is negative — both tables lose the same rows, so the comparison would still pass with reduced coverage. It now drops only lines made of the separator characters. Correlated seed columns. Each account sold exactly one category, so the by-account snapshot was the by-category one with a column renamed and the joined-grain test could not tell the two groupings apart. Each account now sells both categories, and the two results genuinely differ. Derived entrypoints on their `else` branch. Both fell back to the absolute `ytd_amount` under measures named `..._change` and `format: percent`, so no test covered an arithmetic layer over a to-date window — the shape closest to what broke originally. They now dispatch to a difference and to a new `ytd_growth`, with a test each. The seed gains early-2023 rows so the year-over-year shift has something to subtract and those tests assert numbers rather than NULLs. * test(tesseract): keep string cells intact when normalising results `normalize_cell` replaced `T` and `Z` unconditionally to turn CubeStore's `2024-05-01T00:00:00.000Z` into a space-separated timestamp, which also rewrote string cells: the `YTD` calc-group value was recorded as `Y D` in switch_rolling_grouped_switch.snap, so the committed artifact showed a value the model does not declare, and the rollup-versus-source comparison lost fidelity because both sides dropped the same characters. The substitution now matches the timestamp shape — trailing `Z` with a `T` inside — and leaves everything else alone. Also fixes the seed comment: rows giving each account both categories mean the invariant is one row per (account, category, month), not per (category, month). * test(tesseract): unignore the aggregating-index rollup case Building an aggregating index over a decimal measure used to panic before any query ran — the sum widened to `Decimal128(28, 5)` against a column declared `Decimal128(18, 5)`. Fixed in #11413, so the test runs: the rollup with an aggregating index returns exactly what the plain one does, which is the property worth pinning, and it is now the regression guard for that cast. The four-entrypoint query stays ignored; a plan that deep still exceeds Cube Store's protobuf decode recursion limit, which reproduces on a real model too. --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Aleksandr Romanenko <alex.romanenko@cube.dev>
Summary
Creating a table with an
AGGREGATE INDEXover adecimalmeasure and actual data failed withCreate table failed: Internal: task N panicked ... InvalidArgumentError("column types must match schema types, expected Decimal128(18, 5) but found Decimal128(28, 5)"). Any rollup with a decimal measure and an aggregating index hit this, since Cube emitsdecimalfor numeric measures.Building an aggregating index runs the declared aggregations over chunk data, and DataFusion widens a decimal SUM's precision by 10 digits (
Decimal128(18, 5)→Decimal128(28, 5)). The widened batches then failedRecordBatchvalidation against the declared index schema insideconcat_batches(...).unwrap()— a panic in a spawned task instead of an error.Changes
cast_plan_to_schema(store/compaction.rs): wraps the aggregation plan into a projection casting each diverged column back to the declared index schema. The cast usessafe: false, so a sum genuinely overflowing the declared precision fails the job instead of silently becoming NULL.post_process_columns(ingestion: CSVLOCATIONimport andINSERT) andmerge_chunks(compaction and repartition).concat_batches(...).unwrap()calls with error propagation, so a future type mismatch surfaces as a diagnosable error rather thantask N panicked.Testing
aggregate_index_decimaltest in cubestore-sql-tests: the reported repro (CSVLOCATION+ decimal measure +AGGREGATE INDEX) plus anINSERTvariant, with both decimal and int measures so the widening path stays covered. Added toMIGRATION_TEST_EXCLUSION_SETsince older versions panic on it.aggr_index_compactionunit test with a decimal sum column, covering themerge_chunkscast directly.switch_rollingintegration suite against a releasecubestoredbuilt from this branch — the previously#[ignore]d aggregating-index rollup shape now builds and its rollup-backed result matches the raw Postgres source.