Skip to content

fix(cubestore): cast aggregating index aggregation results back to the declared column types - #11413

Merged
waralexrom merged 2 commits into
masterfrom
cubestore-agg-index-decimal-cast
Jul 29, 2026
Merged

waralexrom merged 2 commits into
masterfrom
cubestore-agg-index-decimal-cast

Conversation

@waralexrom

Copy link
Copy Markdown
Member

Summary

Creating a table with an AGGREGATE INDEX over a decimal measure and actual data failed with Create 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 emits decimal for 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 failed RecordBatch validation against the declared index schema inside concat_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 uses safe: false, so a sum genuinely overflowing the declared precision fails the job instead of silently becoming NULL.
  • Applied on both paths that aggregate chunk data: post_process_columns (ingestion: CSV LOCATION import and INSERT) and merge_chunks (compaction and repartition).
  • Replaced the three concat_batches(...).unwrap() calls with error propagation, so a future type mismatch surfaces as a diagnosable error rather than task N panicked.

Testing

  • New aggregate_index_decimal test in cubestore-sql-tests: the reported repro (CSV LOCATION + decimal measure + AGGREGATE INDEX) plus an INSERT variant, with both decimal and int measures so the widening path stays covered. Added to MIGRATION_TEST_EXCLUSION_SET since older versions panic on it.
  • Extended the aggr_index_compaction unit test with a decimal sum column, covering the merge_chunks cast directly.
  • Both tests verified to fail without the cast (knockout) and pass with it; all store unit tests and aggregate-index sql tests green.
  • End to end: the Tesseract switch_rolling integration suite against a release cubestored built from this branch — the previously #[ignore]d aggregating-index rollup shape now builds and its rollup-backed result matches the raw Postgres source.

…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.
@waralexrom
waralexrom requested a review from a team as a code owner July 29, 2026 16:08
@github-actions github-actions Bot added cube store Issues relating to Cube Store rust Pull requests that update Rust code labels Jul 29, 2026
@claude

claude Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

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
  • Gather context / read diff
  • Review compaction.rs cast logic
  • Review store/mod.rs changes
  • Review tests
  • Post review

Verdict

The diagnosis and the fix both hold up. AggregateExec's output for a decimal sum is Decimal128(min(38, p+10), s), so a Decimal128(18,5) measure comes back as Decimal128(28,5) and fails RecordBatch validation against the index schema — casting back in a ProjectionExec is the minimal correct fix, and safe: false is the right default over silent NULLs.

Coverage of the aggregating paths looks complete. Every place that runs the declared aggregations over chunk data is either post_process_columns (ingestion) or merge_chunks (compaction lines 305, 403, 714 — all three call sites), and both are now wrapped. The only other AggregateExec in the write path is keys_with_counts (compaction.rs:1151), which is count(1) over key columns only and needs no cast.

Things I checked that are fine:

  • needs_cast short-circuit means zero overhead for indexes without diverging types (the common case).
  • Positional matching is safe today — add_aggregate_index (metastore/mod.rs:2017-2032) builds index columns as [sort key..., aggregate columns in table order], exactly AggregateExec's output order.
  • No nullability hazard from the new concat_batches(&schema, ...) error propagation: Into<Field> for &Column marks every field nullable (metastore/mod.rs:582).
  • ProjectionExec doesn't reorder rows, so the "data must be sorted in index order" contract downstream of both paths is preserved.
  • In merge_chunks, the schema passed to cast_plan_to_schema is the shadowed res.schema() (== l.schema()), i.e. the declared index schema — correct target.
  • Replacing the three concat_batches(...).unwrap() calls is a genuine improvement: those were panics inside cube_ext::spawn tasks, surfacing as task N panicked.

Test coverage is solid: the sql test covers both the CSV LOCATION and INSERT ingestion paths and keeps an int measure alongside the decimal one so the no-cast branch stays exercised; the extended aggr_index_compaction unit test covers merge_chunks. The MIGRATION_TEST_EXCLUSION_SET entry is necessary and correctly commented.

Findings

Sev Where Issue
Medium compaction.rs:1583-1593 Overflow on the safe: false cast surfaces as an opaque CubeError::Internal with no column/table context, and on the compaction path will retry-fail indefinitely. DECIMAL(18,5) overflows at ~10^13, which is reachable. No test for this deliberate behavior.
Low compaction.rs:1576-1578 Positional-only column matching: if index/aggregate ordering ever drifts, a previously loud type-mismatch error becomes a silent lossy cast. Suggested a name check as defense-in-depth.
Low store/mod.rs:2879-2887 The output_ordering assert! now validates the pre-cast plan rather than the executed one.

Not verified

I did not compile or run the tests — cubestore builds DataFusion from the cube-46.0.1 git fork, which isn't cached in this environment. The new APIs used (CastExpr::new(expr, ty, Option<CastOptions>), ProjectionExec::try_new, arrow::util::display::FormatOptions) match DF 46 signatures, but CI is the authority here. The knockout results reported in the PR description are taken at face value.

No security or performance concerns. No documentation changes needed — this is an internal correctness fix.

· branch `cubestore-agg-index-decimal-cast`

@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.00%. Comparing base (cad6ce8) to head (2633f9a).
⚠️ Report is 3 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (cad6ce8) and HEAD (2633f9a). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (cad6ce8) HEAD (2633f9a)
cubesql 1 0
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     
Flag Coverage Δ
cube-backend 59.00% <ø> (?)
cubesql ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

claude Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @waralexrom's task in 2m 25s —— View job


Re-review of 2633f9a: all 3 prior findings addressed — 0 blocking, 2 low (both optional)

Full review
  • Diff the new commit against the reviewed state
  • Verify the tightened cast predicate can't reject legitimate divergences
  • Verify the new overflow test actually overflows
  • Verify the moved assert! still holds
  • Resolve stale review threads

Verdict

2633f9a addresses all three findings from the previous review. Resolved threads: the error-context/overflow-test one, the positional-matching one, and the assert! placement nit.

1. Positional-drift guard (compaction.rs:1583-1598) — the chosen approach is better than what I suggested. A name check wouldn't work (aggregate output fields carry the SUM(col) alias, not the column name — confirmed at metastore/table.rs:97), and restricting the cast to same-scale Decimal128 → Decimal128 is a tighter invariant than a name match anyway: a positional drift onto a differently-typed column now returns CubeError::internal with both column names and both types instead of silently casting.

I checked that this predicate can't reject a legitimate divergence, walking every ColumnType → arrow mapping (metastore/mod.rs:560-580) against every supported aggregate (AggregateColumn::aggregate_expr):

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 ·

@waralexrom
waralexrom merged commit 26c4801 into master Jul 29, 2026
62 checks passed
@waralexrom
waralexrom deleted the cubestore-agg-index-decimal-cast branch July 29, 2026 20:43
waralexrom added a commit that referenced this pull request Jul 30, 2026
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.
waralexrom added a commit that referenced this pull request Jul 30, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cube store Issues relating to Cube Store rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants