Skip to content

feat(tesseract): pre-agg matching without stored calc-group dims; collapse trivial pass-through subqueries; e2e specs for cross-cube rolling measures over rollups - #11346

Merged
paveltiunov merged 11 commits into
masterfrom
claude/query-preagg-matching-tuhpz0
Jul 25, 2026

Conversation

@paveltiunov

@paveltiunov paveltiunov commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Check List

  • Tests have been run in packages where changes have been made if available
  • Linter has been run for changed code
  • Tests for the changes have been added if not covered yet
  • Docs have been added / updated if required

Description of Changes Made (if issue reference is not provided)

Feature: pre-aggregation matching no longer requires calc-group (switch) dimensions to be stored in the rollup (Tesseract). Calc-group dimensions are virtual enumerations — they carry no stored data, and materializing one in a rollup just CROSS JOINs the value list into the build SQL, multiplying rollup size by the number of values while adding zero information. They previously had to be listed in every rollup definition purely because the matcher treated them like ordinary dimensions. Now:

  • dimension_matcher.rs: a calc-group dimension always matches (MatchState::Full) regardless of the rollup's stored dimensions.
  • query.rs (physical plan builder): calc-group resolution — a filter-pinned value renders as a literal, otherwise the enumeration is cross-joined as a virtual values table — now also applies when the query source is a pre-aggregation, covering exactly the calc groups not stored in the rollup. Stored calc groups keep resolving to the rollup column, so existing rollup definitions behave exactly as before (backward compatible). Literal render references are re-added after the pre-aggregation render-reference reset so they survive it.

Fix: physical-plan optimizer collapsing trivial pass-through subqueries (Tesseract). Multi-stage planning wraps every CTE reference into a derived table of the form (SELECT * FROM cte_n AS cte_n) AS alias. Each wrapper is a semantic no-op, but engines that inline CTE bodies at every reference (Cube Store / DataFusion) pay two extra plan nodes (projection + subquery alias) per usage — deep multi-stage queries over pre-aggregations could overflow Cube Store's serialized-plan protobuf decode recursion limit and fail with Error during planning: Error decoding expr as protobuf: ... recursion limit reached. The new pass in physical_plan/optimizers/trivial_subquery.rs rewrites such wrappers into direct <table> AS alias references across the whole plan (top-level select, CTE bodies, join sides, unions, nested subqueries), collapsing only pure pass-throughs (SELECT *, no filter/group/having/order/distinct/limit/offset/CTEs, single table-reference source). On the repro query below this removes all 23 wrappers, and the previously failing query now executes in Cube Store.

Verification: 1076 cubesqlplanner tests (including --features integration-postgres, which executes generated SQL and compares results) and the integration-cubestore test pass; a test asserts the collapsed SQL shape and unchanged execution results.

Test coverage added for rolling-window metrics exposed through multi-stage case entrypoint measures dispatched by a type: switch dimension (calc group) across two joined fact cubes combined in a view:

  1. Schema-compiler integration spec (pre-aggregations-shared-calc-group.test.ts, Postgres rollups): a shared single-row calc-group cube joined 1 = 1 into both fact cubes lets one filter resolve every case measure — cross-cube query matches both rollups; per-cube switch dimensions also match now that calc groups no longer block matching (asserted); a slim-rollup model verifies rollups that do not store the calc-group dimension still match, render the pinned value as a literal, and execute; deterministic value assertions pin the rolling/time-shift arithmetic.
  2. Birdbox smoke test (smoke-shared-calc-group.test.ts + fixture): the same model on a real Cube server with rollups in Cube Store (CUBEJS_ROLLUP_ONLY, Tesseract), with the switch dimension omitted from both rollup definitions. Single-cube, cross-cube, three-measure, and the previously failing four-measure deep query all execute from Cube Store rollups.

Remaining gaps documented as skipped FIXME tests:

  1. Granular time dimension: fails in the physical plan builder with Alias not found for partition_by dimension …rolling_window — the calc-group dimension is not projected into the multi-stage window input CTE.
  2. Date-range-only time dimension (no granularity) stops matching the rollups even though allow_non_strict_date_range_match: true is set and the range is month-aligned.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY

…a shared calc-group switch

Adds an integration spec covering rollup pre-aggregation matching for
multi-stage case entrypoint measures dispatched by a `type: switch`
dimension (calc group) across two joined fact cubes combined in a view:

- when each cube declares its own switch dimension, a query combining
  rolling measures from both cubes pins only one switch with a filter,
  the other stays unresolved, and no pre-aggregation can match
  (anti-pattern case, asserted);
- when the switch lives on a shared single-row calc-group cube joined
  `1 = 1` into both fact cubes, a single rolling_window filter resolves
  every case measure and the query is served from both rollups,
  verified end to end against Postgres;
- rolling window and time-shift arithmetic is pinned with deterministic
  value assertions on a rollup-free copy of the model.

Two currently unsupported paths are documented as skipped tests:
querying with a granular time dimension fails with "Alias not found for
partition_by dimension" (the calc-group dimension is not projected into
the multi-stage window input CTE), and a date-range-only time dimension
stops matching the rollups even with allow_non_strict_date_range_match.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@github-actions github-actions Bot added the javascript Pull requests that update Javascript code label Jul 24, 2026
@paveltiunov
paveltiunov marked this pull request as ready for review July 24, 2026 19:56
@paveltiunov
paveltiunov requested a review from a team as a code owner July 24, 2026 19:56
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 42s —— View job


Code Review

Review complete — no blocking issues. 2 low-severity notes.
  • Read PR diff and the new test file
  • Check test structure and coverage
  • Look for correctness / maintainability issues

Summary

Purely additive integration spec — 660 lines, one new file, no production code touched. The test is well-scoped: it documents a real modeling anti-pattern (per-cube switches vs. shared calc-group switch), verifies end-to-end rollup matching against Postgres, and pins two currently-broken planner paths behind it.skip with clear FIXME notes so they'll surface the day the planner catches up.

Nice touches:

  • The salesCube / shareMetricsCube helpers parameterize the switch reference and the pre-agg dim, so the same cube bodies are reused across three model variants (shared / per-cube / shared-without-rollups). Keeps the ~200-line YAML DRY.
  • Deterministic value assertions are done on a rollup-free copy of the model so the assertions are stable regardless of "today"; the rollup-matching test intentionally only checks table presence, since rolling windows are anchored to the current date.
  • The share-of-total test is correctly anchored to share_metrics.date (exposed as ms_date) because that's where its time_shift is declared — the surrounding comment (L603-605) explains why, which is exactly the kind of non-obvious context worth keeping.

Notes

Low — preAggregationsSchema: '' (L506). Every other integration test in this directory (e.g. pre-aggregations.test.ts, PreAggregations.test.ts) uses 'test'. Empty string works because Postgres treats the resulting "".sales_perf_rolling as unqualified, but it's an odd outlier — worth aligning with the rest of the suite unless there's a specific reason.

Low — assertion asymmetry in the anti-pattern block (L629-653). The negative case (L634-636) checks both preAggregationsDescription emptiness and that neither rollup name appears in the SQL. The positive single-cube case (L648-652) only checks that sales_perf_rolling is present and doesn't assert that share_metrics_perf_share is absent. Given the anti-pattern narrative ("one cube can match, the other can't"), asserting the absent side too would make the contrast explicit and catch a regression where an unexpected extra rollup starts matching.

Not blocking

  • Two it.skipped tests with FIXME are appropriate here — they document the exact planner error text ("Alias not found for partition_by dimension …") so whoever fixes it upstream has a searchable breadcrumb. Consider filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
• [Branch](https://github.com/cube-js/cube/tree/claude/query-preagg-matching-tuhpz0)

@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.58%. Comparing base (9f13a7f) to head (ddf3e24).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff             @@
##           master   #11346       +/-   ##
===========================================
+ Coverage   59.57%   79.58%   +20.00%     
===========================================
  Files         216      473      +257     
  Lines       17526    98240    +80714     
  Branches     3549     3549               
===========================================
+ Hits        10441    78181    +67740     
- Misses       6574    19548    +12974     
  Partials      511      511               
Flag Coverage Δ
cube-backend 59.58% <ø> (+<0.01%) ⬆️
cubesql 83.92% <ø> (?)

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.

…s in Cube Store

Adds a birdbox e2e smoke test running the shared calc-group model
against a real Cube server with rollups stored and queried in Cube
Store (CUBEJS_ROLLUP_ONLY, Tesseract planner), covering single-cube,
cross-cube, and full multi-stage rolling-window queries dispatched by
a shared switch dimension. Unlike the schema-compiler integration spec
(Postgres-backed rollups), this exercises the Cube Store execution path
used in production.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@paveltiunov
paveltiunov requested a review from a team as a code owner July 24, 2026 20:52
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 48s —— View job


Code Review (updated for latest commit)

Review complete — no blocking issues. 2 low-severity notes carried over; 1 small nit on the new smoke fixtures.
  • Read PR diff (both commits)
  • Review new birdbox fixture + Cube Store smoke test
  • Re-check schema-compiler spec

What's new since the previous review

Second commit adds a birdbox-based end-to-end smoke test (packages/cubejs-testing/test/smoke-shared-calc-group.test.ts) plus a self-contained fixture under packages/cubejs-testing/birdbox-fixtures/shared-calc-group/ (sales + share_metrics fact cubes, the shared rolling_window_dim calc-group cube, and the joining performance_view). Same shape as the schema-compiler spec, but now the rollups are built and served from Cube Store rather than Postgres, so the multi-stage plans get exercised by the production engine path. CUBEJS_ROLLUP_ONLY: true correctly forces the query router to fail rather than fall back to source-DB execution if a rollup doesn't match — that's the assertion teeth.

Three tests cover:

  1. Single-cube rolling measure → single rollup match.
  2. Cross-cube rolling measures → both rollups match (the shared-switch payoff).
  3. Full multi-stage query with rolling_amount_change + rolling_share_change → still routed to Cube Store.

Fixture and test are internally consistent: perf_rolling / perf_share pre-agg names line up with the t.includes('perf_rolling') / t.includes('perf_share') matchers, REPRO_FILTERS pins rolling_window: R3 (the branch backed by 3-month trailing rollups), and the 1 = 1 join edge into rolling_window_dim mirrors the schema-compiler model exactly.

Notes

Low — asserting count of used pre-aggs (smoke-shared-calc-group.test.ts:104-106, 124-126). The cross-cube tests check some(t => t.includes('perf_rolling')) and some(t => t.includes('perf_share')) but never assert the number of tables served. If a future regression accidentally serves one of the measures from the raw source (or from a third accidentally-created rollup) alongside the expected two, some() matches still pass. Consider expect(tables).toHaveLength(2) — with CUBEJS_ROLLUP_ONLY: true the query would fail before that, but the length assertion documents the intent.

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Every other integration test in this directory uses 'test'. Not broken — Postgres treats the unqualified name — but it's an outlier worth aligning.

Low (carried) — anti-pattern assertion asymmetry (pre-aggregations-shared-calc-group.test.ts:629-653). Negative case asserts both rollup names are absent; positive single-cube case only asserts sales_perf_rolling is present but doesn't assert share_metrics_perf_share is absent. Symmetric assertions would make the "one matches, the other can't" contrast catch regressions in either direction.

Not blocking

  • Duplicated SELECT ... UNION ALL fixture data between the schema-compiler spec and the birdbox YAML is intentional (each test owns its universe), but if the numbers drift out of sync between them the two suites will silently test different things. A shared .sql file next to the fixtures would remove that risk if the duplication grows further.
  • The two it.skipped FIXME tests in the schema-compiler spec remain appropriate as planner breadcrumbs — worth filing a tracking issue and linking it there so they don't drift into silent tech debt.
• [Branch](https://github.com/cube-js/cube/tree/claude/query-preagg-matching-tuhpz0)

Adds a growth-percentage entrypoint (an extra multi-stage layer over the
same rolling leaves) and a four-measure query matching the production
query shape, to exercise the deep FullKeyAggregate plan that can
overflow Cube Store's serialized-plan decode recursion limit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Claude Code is working…

I'll analyze this and get back to you.

View job run

…t decode limit

The four-measure query reproduces the Cube Store failure: the deep
FullKeyAggregate plan overflows the serialized-plan protobuf decode
recursion limit ("Error decoding expr as protobuf: ... recursion limit
reached"). Skipped with a FIXME until Cube Store can decode plans of
this depth; the three-measure query continues to run as a regression
guard for the working path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 45s —— View job


Code Review (updated for latest commits)

No blocking issues. Verdict: 0 high, 0 medium, 3 low (2 carried).

Details — task list, what's new, and notes
  • Read new commits' diff (4030486, 8ea0f97)
  • Re-check fixture / smoke test consistency
  • Dedupe against prior review notes

What's new since the previous review

  • sales.yml grows two hidden helper measures (r3_amount_growth_pct, ytd_amount_growth_pct) and a public rolling_amount_growth_pct calc-group measure that switches on rolling_window_dim.rolling_window — same shape as the existing rolling_amount_change, just an extra multi-stage layer computed over the same rolling leaves. Both helpers guard divide-by-zero and NULL prev-period values, returning NULL cleanly. Good.
  • performance_view.yml exposes the new measure through the sales include list.
  • smoke-shared-calc-group.test.ts adds a third scenario (test.skip) that stacks rolling_amount + rolling_amount_change + rolling_amount_growth_pct + rolling_share_change in one query. It's skipped with a precise FIXME calling out Cube Store's serialized-plan decode recursion limit (Error decoding expr as protobuf: … recursion limit reached). Appropriate: the skip documents an engine limitation rather than a test bug, and the exact error text will be searchable when Cube Store lifts the limit.

Fixture wiring is internally consistent — the new measure name in the view matches the sales cube's export, R3 branch maps to the R3 helper, else falls through to YTD (same convention as the existing rolling_amount_change).

Notes

Low — skipped test is untested code (smoke-shared-calc-group.test.ts:132-152). The new rolling_amount_growth_pct measure is only exercised by the skipped test. Nothing else in the smoke suite touches it, and the schema-compiler spec doesn't cover it either. Consider a smaller non-skipped assertion — either a single-cube query that resolves rolling_amount_growth_pct alone (should stay within the decode limit) or a schema-compiler value assertion against Postgres — so a rename or NULL-handling regression in the helper measures gets caught. Otherwise this measure is effectively dead code until Cube Store's decode limit changes.

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Every other integration test in this directory uses 'test'. Outlier worth aligning.

Low (carried) — anti-pattern assertion asymmetry (pre-aggregations-shared-calc-group.test.ts:629-653). The single-cube positive case doesn't assert share_metrics_perf_share is absent, while the negative case asserts both. Making it symmetric would make the "one matches, the other can't" narrative catch regressions in either direction.

Not blocking

  • Consider filing a Cube Store tracking issue for the protobuf decode recursion limit and linking it in the FIXME on smoke-shared-calc-group.test.ts:127, so this skip doesn't drift into silent tech debt.
  • The CASE WHEN … = 0 THEN NULL guard is duplicated between r3_amount_growth_pct and ytd_amount_growth_pct. Fine at N=2, but if a third granularity appears it's worth extracting a shared _growth_pct helper macro rather than adding a third copy.
• [Branch](https://github.com/cube-js/cube/tree/claude/query-preagg-matching-tuhpz0)

… plan

Multi-stage planning wraps every CTE reference into a derived table of
the form (SELECT * FROM cte_n AS cte_n) AS alias. Each wrapper is a
semantic no-op but costs two plan nodes (projection + subquery alias)
per usage in engines that inline CTE bodies at every reference, such as
Cube Store / DataFusion; deep multi-stage queries can overflow Cube
Store's serialized-plan decode recursion limit because of them.

Adds a physical-plan optimizer pass that rewrites
(SELECT * FROM <table reference> AS x) AS alias into a direct
<table reference> AS alias everywhere in the plan: the top-level
select, CTE bodies, join sides, unions and nested subqueries. Only
pure pass-through selects are collapsed: SELECT * projection with no
filter, grouping, having, ordering, distinct, limit, offset or own
CTEs, over a single table reference.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@github-actions github-actions Bot added the rust Pull requests that update Rust code label Jul 24, 2026
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 1m 28s —— View job


Code Review (updated for latest commit: c0465a7)

No blocking issues. Verdict: 0 high, 0 medium, 4 low (1 new on the Rust optimizer, 3 carried on tests).

Details — task list, what's new, and notes
  • Read latest commit (c0465a7 feat(tesseract): collapse trivial pass-through subqueries in physical plan)
  • Trace optimizer wiring into PhysicalPlanBuilder::build
  • Sanity-check correctness of the collapse pass
  • Re-check whether prior test-side notes still apply
  • Post review

What's new since the previous review

Adds a physical-plan optimizer (rust/cube/cubesqlplanner/cubesqlplanner/src/physical_plan/optimizers/trivial_subquery.rs, +152) run unconditionally at the end of PhysicalPlanBuilder::build (physical_plan_builder/builder.rs:74). It rewrites (SELECT * FROM <table_or_cte> AS x) AS alias into <table_or_cte> AS alias in the top-level select, CTE bodies, join sides, unions, and nested subqueries. The trivial-passthrough predicate (trivial_subquery.rs:142-152) is strict: no projection cols, filter, group_by, having, order_by, own CTEs, distinct, limit, or offset — and the inner source must be a single TableReference. That closes the door on any change to column identity or row cardinality.

Motivation is real: the PR description and the skipped smoke test document Cube Store's serialized-plan protobuf decode recursion limit tripping purely from these wrapper nodes in deep multi-stage queries.

Recursion coverage is symmetric: optimize_select → CTEs + FROM → optimize_from → Single / Join / CalcGroupsJoin arms → optimize_single_source → optimize_plan for subquery bodies → back into optimize_select. Every place a Subquery can appear structurally in a FROM is covered.

Alias handling looks correct: after collapse the outer alias is preserved via SingleAliasedSource::new_from_table_reference(reference, select.schema(), Some(alias)), and since the collapsed select is SELECT *, the outer references (alias.col) remain valid against the flattened table AS alias.

Notes

Low (new) — no unit tests for the optimizer itself (trivial_subquery.rs). The pass is currently only exercised through smoke/integration paths (birdbox, schema-compiler). A couple of small unit tests building a Select by hand would nail down the invariants and make regressions obvious: (a) a trivial (SELECT * FROM t AS x) AS a collapses to t AS a; (b) a select with a filter/limit/group_by/etc. does NOT collapse; (c) a subquery-over-subquery collapses to the innermost table; (d) collapse inside a JOIN side and inside a CTE body. Optional but cheap insurance for a pass that rewrites plan shape universally.

Low (new / minor) — missed collapse opportunities in filter/having/join-on subqueries. optimize_select reuses the surviving Select via ..select.as_ref().clone(), so filter, having, and JoinItem.on are copied verbatim without recursing into any subqueries they may contain. This is a missed optimization, not a bug (the correctness invariant still holds), and probably not worth acting on unless the multi-stage plans that hit Cube Store's decode limit also embed wrappers on those paths. Worth a // TODO breadcrumb at most.

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Every other integration test in this directory uses 'test'. Outlier worth aligning.

Low (carried) — anti-pattern assertion asymmetry (pre-aggregations-shared-calc-group.test.ts:629-653). Positive single-cube case doesn't assert share_metrics_perf_share is absent while negative case asserts both. Symmetric assertions would make the "one matches, the other can't" contrast catch regressions in either direction.

Low (carried) — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126). Consider expect(tables).toHaveLength(2) alongside the two some() matchers so an unexpected extra pre-agg being served wouldn't slip past.

Not blocking

  • The one-line optimizer wiring in builder.rs:74 runs unconditionally on every plan. Given the collapse predicate is strict (no filter/group/having/order/distinct/limit/offset/own-CTEs, single table ref), the risk of unintended rewrites on non-CTE-wrapper subqueries is low, but this pass now sits on every physical-plan build path — not just multi-stage. A one-liner in the commit message or module doc explicitly calling out "runs on every plan, not just multi-stage" would make that clear to future readers.
  • Duplicated SELECT ... UNION ALL fixture data between the schema-compiler spec and the birdbox YAML — intentional (each suite owns its universe), but if the numbers drift out of sync the two suites will silently test different things. A shared .sql file next to the fixtures would remove that risk if the duplication grows further.
  • Two skipped it.skip/test.skip FIXMEs remain in the test files with precise error strings (Cube Store decode recursion limit, calc-group dim not projected into multi-stage window CTE). Consider filing tracking issues and linking them in the FIXMEs so they don't drift into silent tech debt.

• Branch •

Asserts that multi-stage SQL no longer contains
(SELECT * FROM <table>) wrappers, that collapsed CTE references keep
their outer alias, and that executed results are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@paveltiunov
paveltiunov force-pushed the claude/query-preagg-matching-tuhpz0 branch from f5f8bb8 to a3dfe48 Compare July 24, 2026 21:37
@claude

claude Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Claude Code is working…

I'll analyze this and get back to you.

View job run

@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 59s —— View job


Code Review (updated for latest commit: a3dfe48)

No blocking issues. Verdict: 0 high, 0 medium, 4 low (1 new on the new optimizer test, 3 carried on test suites).

Details — task list, what's new, and notes
  • Read latest commit (a3dfe48 test(tesseract): cover trivial pass-through subquery collapse)
  • Inspect new test + snapshot
  • Deduplicate against prior review notes
  • Post review

What's new since the previous review

Adds rust/cube/cubesqlplanner/cubesqlplanner/src/tests/integration/multi_stage/plan_optimizers.rs (+65) with test_trivial_cte_wrappers_are_collapsed and its insta snapshot. The test drives a real multi-stage query (orders.rolling_sum_7d + orders.amount_prev_month over a monthly range), asserts:

  1. Generated SQL still contains a cte_0 multi-stage CTE (so the query is actually going through multi-stage planning).
  2. No (SELECT * FROM <ident> trivial wrapper survives — regex (?i)\(\s*SELECT\s+\*\s+FROM\s+[A-Za-z_] correctly matches bare-identifier sources only (a parenthesized inner subquery would start with ( after FROM, so it's excluded).
  3. Collapsed references keep the outer alias — cte_0 AS string check.
  4. Executed Postgres result is snapshotted (guarded by try_execute_pg so it degrades gracefully when the Postgres fixture isn't available).

This is the "unit test for the optimizer" I flagged in the prior review — it's now covered from the integration side, which is the more valuable coverage anyway (real multi-stage SQL rather than a hand-built plan).

Notes

Low (new) — brittle alias-format assertion (plan_optimizers.rs:57). The sql.contains("cte_0 AS") check pins a specific whitespace format (two spaces between the identifier and AS). It's an artifact of the current SQL pretty-printer; a future formatter tweak (single space, or newline) would fail this without any regression in behavior. Consider a regex like Regex::new(r"cte_0\s+AS\s+").unwrap() — same intent, resilient to formatting drift.

Low (new / minor) — missing negative case in the test. The test proves that in a query where multi-stage does produce wrappers, they get collapsed. It doesn't prove that a plan containing a legitimate non-trivial subquery (filter / limit / group_by present) is left alone. Given the collapse predicate is strict, the risk of over-collapse is low, but a second test case with a subquery that has, say, a LIMIT and asserting the wrapper is retained would nail down the invariant. Optional.

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Every other integration test in this directory uses 'test'. Outlier worth aligning.

Low (carried) — anti-pattern assertion asymmetry (pre-aggregations-shared-calc-group.test.ts:629-653). Positive single-cube case doesn't assert share_metrics_perf_share is absent while negative case asserts both. Symmetric assertions would make the "one matches, the other can't" contrast catch regressions in either direction.

Low (carried) — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126). Consider expect(tables).toHaveLength(2) alongside the two some() matchers so an unexpected extra pre-agg being served wouldn't slip past.

Addressed since previous review

  • ✅ Prior "no unit tests for the optimizer" note — resolved by the new integration test + snapshot.

Not blocking

  • Two skipped it.skip/test.skip FIXMEs remain in the test files with precise error strings. Consider filing tracking issues and linking them in the FIXMEs so they don't drift into silent tech debt.
  • Filter/having/join-on subquery bodies are still not recursed into by the collapse pass (missed optimization, not correctness) — worth a // TODO breadcrumb at most if it doesn't show up in real plans.

• Branch •

With the trivial-subquery collapse optimizer in the Tesseract physical
plan builder, the four-measure query's plan fits under Cube Store's
serialized-plan decode recursion limit and executes from the rollups.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 43s —— View job


Code Review (updated for latest commit: 41c720c)

No blocking issues. Verdict: 0 high, 0 medium, 3 low (all carried).

Details — task list, what's new, and notes
  • Read latest commit (41c720c test(cubejs-testing): unskip deep multi-stage Cube Store query)
  • Verify test body + comment reflect the fix
  • Dedupe against prior review notes
  • Post review

What's new since the previous review

Small, mechanical follow-up on c0465a7: smoke-shared-calc-group.test.ts:136 flips test.skip → test for the four-measure deep multi-stage query (rolling amount + growth percentage + cross-cube share change). The FIXME comment has been rewritten as historical context — kept as a searchable breadcrumb for the "Error decoding expr as protobuf: recursion limit reached" symptom, which is genuinely useful if the regression ever comes back.

This is exactly the payoff the trivial-subquery collapse optimizer was introduced for, and previously my review flagged this measure (rolling_amount_growth_pct) as effectively dead code because only the skipped test exercised it. That concern is now resolved — the measure is exercised end-to-end through Cube Store.

Nothing else changed in this commit.

Notes

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Every other integration test in this directory uses 'test'. Outlier worth aligning.

Low (carried) — anti-pattern assertion asymmetry (pre-aggregations-shared-calc-group.test.ts:629-653). Positive single-cube case doesn't assert share_metrics_perf_share is absent while the negative case asserts both. Symmetric assertions would make the "one matches, the other can't" contrast catch regressions in either direction.

Low (carried) — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126, and now 152-153). Consider expect(tables).toHaveLength(2) alongside the two some() matchers so an unexpected extra pre-agg being served wouldn't slip past. Applies to the newly-unskipped test too.

Addressed since previous review

  • ✅ Prior "skipped test is untested code — rolling_amount_growth_pct only exercised by the skip" note — resolved by the unskip in this commit, now that the optimizer lets the plan fit under Cube Store's decode limit.

Not blocking

  • One skipped it.skip FIXME remains in the schema-compiler spec (calc-group dim not projected into multi-stage window CTE). Worth filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
  • The FIXME: prefix on the comment above the now-unskipped test at smoke-shared-calc-group.test.ts:129-135 was intentionally dropped since the fix landed — the historical context is preserved as a plain comment. Reads well; nothing to change.

• Branch •

@paveltiunov paveltiunov changed the title test(schema-compiler): e2e spec for cross-cube rolling measures with a shared calc-group switch feat(tesseract): collapse trivial pass-through subqueries; e2e specs for cross-cube rolling measures over rollups Jul 24, 2026
…ollapsed SQL

- cargo fmt on trivial_subquery.rs (CI fmt/clippy + lint failures)
- OracleQuery alias assertions now accept a bare CTE reference before the
  alias, since the trivial-subquery collapse renders join sides as
  `cte_0 "q_0"` instead of `(SELECT ...) "q_0"`; the no-AS-keyword
  invariant they guard is unchanged
- symmetric rollup assertions in the per-cube switch anti-pattern spec

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 35s —— View job


Code Review (updated for latest commit: 9927f50)

No blocking issues. Verdict: 0 high, 0 medium, 2 low (both carried).

Details — what's new and remaining notes
  • Read latest commit (9927f50 fix(tesseract): rustfmt optimizer, adapt Oracle alias assertions to collapsed SQL)
  • Verify Oracle regex still enforces the no-AS invariant
  • Dedupe against prior review notes
  • Post review

What's new since the previous review

Small mechanical follow-up on c0465a7 / a3dfe48:

  1. trivial_subquery.rs — pure cargo fmt on the import list and one function signature; no behavioral change.
  2. oracle-query.test.ts — three alias-shape regexes broadened from \)\s+"?q_\d+"? to [)\w]\s+"?q_\d+"?. This is a direct consequence of the trivial-subquery collapse: join sides that were previously rendered as (SELECT …) "q_0" now render as cte_0 "q_0", so the leading char in front of the alias can be either ) or a word char. The invariant this test actually guards — no AS keyword before the alias, per Oracle's join-alias grammar — is still enforced by the untouched expect(sql).not.toMatch(/\bas\s+q_\d+/) line. Good.
  3. pre-aggregations-shared-calc-group.test.ts:652-654 — addresses the "anti-pattern assertion asymmetry" note from prior reviews: the single-cube positive case now also asserts share_metrics_perf_share is absent from both tableNames and the SQL, matching the negative-case symmetry. Contrast is now enforced in both directions.

Notes

Low (carried) — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Still the only outlier in this directory; every other integration test uses 'test'. Aligning would remove the oddity — no functional impact.

Low (carried) — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126, 152-153). expect(tables).toHaveLength(2) alongside the two some() matchers would catch an unexpected extra pre-agg being served — cheap defense-in-depth on top of CUBEJS_ROLLUP_ONLY.

Addressed since previous review

  • ✅ Anti-pattern assertion asymmetry — resolved by the new not.toContain / not.toContain symmetric assertions on the single-cube positive case.

Not blocking

  • One skipped it.skip FIXME remains in the schema-compiler spec (calc-group dim not projected into multi-stage window CTE). Worth filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
  • Filter / having / join-on subquery bodies are still not recursed into by the collapse pass (missed optimization, not correctness).

• Branch •

Copy link
Copy Markdown
Member Author

CI status note: several red checks on 9927f50 are runner-infrastructure failures, not related to the diff:

  • tests (pinot, true) and tests (databricks-jdbc-export-bucket-s3, true) — Docker Hub registry timeouts (Get "https://registry-1.docker.io/v2/": Client.Timeout exceeded), all tests fail fast at container pull.
  • Build macos-14 aarch64-apple-darwin (Python fallback) — rustup toolchain download failed with a DNS error resolving static.rust-lang.org.

The failures this PR actually caused (Check fmt/clippy, lint, unit — rustfmt on the new optimizer file and three OracleQuery alias-shape assertions) are fixed in 9927f50. The infra-failed jobs need a re-run once the registry recovers — this integration doesn't have permission to re-run them.


Generated by Claude Code

@claude

claude Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 30s —— View job


Code Review (updated for latest commit: 0f9db8c)

No blocking issues. Verdict: 0 high, 0 medium, 2 low (both carried).

Details — what's new and remaining notes
  • Inspect latest commit (0f9db8c chore: retrigger CI after Docker Hub registry and runner network incidents)
  • Dedupe against prior review notes
  • Post review

What's new since the previous review

0f9db8c is an empty chore commit with no file changes — a CI retrigger following the Docker Hub registry timeouts and the macOS rustup DNS failure noted at 22:16Z. No code to re-review. The prior review of 9927f50 still stands verbatim.

Notes (carried)

Low — preAggregationsSchema: '' (pre-aggregations-shared-calc-group.test.ts:506). Still the only outlier in this directory; every other integration test uses 'test'. Aligning would remove the oddity — no functional impact.

Low — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126, 152-153). expect(tables).toHaveLength(2) alongside the some() matchers would catch an unexpected extra pre-agg being served — cheap defense-in-depth on top of CUBEJS_ROLLUP_ONLY.

Not blocking

  • One skipped it.skip FIXME remains in the schema-compiler spec (calc-group dim not projected into multi-stage window CTE). Worth filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
  • Filter / having / join-on subquery bodies are still not recursed into by the trivial-subquery collapse pass (missed optimization, not correctness).

• Branch •

…ensions

Calc-group (switch) dimensions are virtual enumerations: they carry no
stored data, so a rollup gains nothing from materializing them — the
build SQL just CROSS JOINs the value list, multiplying rollup size by
the number of values while adding zero information. Until now they
still had to be listed in every rollup definition purely because the
pre-aggregation matcher treated them like ordinary dimensions.

- dimension_matcher: a calc-group dimension now always matches
  (MatchState::Full) regardless of the rollup's stored dimensions.
- query processor: calc-group resolution (filter-pinned value rendered
  as a literal, otherwise a virtual values cross-join) now also applies
  when the query source is a pre-aggregation, covering exactly the calc
  groups NOT stored in the rollup. Stored ones keep resolving to the
  rollup column, so existing rollups behave as before. Literal render
  references are re-added after the pre-aggregation render-reference
  reset so they survive it.
- specs: new slim-rollup model + test in the shared-calc-group Postgres
  suite; the per-cube-switch test now asserts rollups match (calc
  groups no longer block matching); birdbox fixtures drop the switch
  dimension from both rollups and all Cube Store smoke tests pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 1m 47s —— View job


Code Review (updated for latest commit: fee3d82)

No blocking issues. Verdict: 0 high, 0 medium, 2 low (1 new, 1 carried).

Details — what's new and remaining notes
  • Read latest commit (fee3d82 feat(tesseract): match pre-aggregations without stored calc-group dimensions)
  • Trace matcher + query-processor changes for correctness
  • Re-check test rewrites (anti-pattern block, new slim-rollup case)
  • Dedupe against prior review notes

What's new since the previous review

Substantive feature commit — calc-group (switch) dimensions no longer need to be materialized in a rollup for the pre-aggregation matcher to serve queries that use them.

  1. dimension_matcher.rs:201-207 — new arm returns MatchState::Full when the dimension is a calc-group. Correctly ordered after the stored-dimensions lookup (try_match_dimension:193-200), so calc-group dims that are stored in the rollup keep resolving via the existing pre-agg column path and remain backward-compatible.

  2. physical_plan_builder/processors/query.rs:70-119, 211-217 — extends calc-group query-time resolution from LogicalJoin to PreAggregation. The stored-dims set is used to subtract calc-group dims that already live in the rollup (those flow through add_pre_aggregation_dimension_reference at line 136). Only unstored calc-group dims get the literal (single value) or virtual CalcGroupsJoin (multi-value) treatment. The new calc_group_value_references collector re-adds single-value literals after clear_render_references() at line 212 — a targeted, well-motivated survivor set (comment on 213-214 explains why).

  3. Test rewrites (pre-aggregations-shared-calc-group.test.ts):

    • New sharedSwitchModelSlimRollups case pins the payoff: rollups omitting the calc-group dim still match, loadSql verifies build SQL doesn't cross-join rolling_window_values (i.e. rollups are actually slimmer, not just still-matching).
    • Anti-pattern block is now correctly re-scoped: rollups do match (calc groups no longer block matching), but the per-cube-switch problem remains semantic (one switch stays unresolved) — comment on lines 686-690 walks through that shift.

Correctness spot-checks:

  • Stored calc-group in rollup → matcher hits pre_aggregation_dimensions branch → resolves to rollup column. Not-stored → new calc-group branch → literal/cross-join in query.rs. Disjoint paths, no double-render.
  • clear_render_references() clobbering the CalcGroupsJoin path: multi-value calc-groups over a pre-agg add the join to from and rely on ReferencesBuilder scanning from for resolution, not on render_references — so clear doesn't affect them. Only the single-value literal case needs the re-insert, which is exactly what's done. Good.
  • The is_calc_group() arm runs before owned_by_cube(), so a calc-group declared on the same cube still matches (this was the prior blocker).

Notes

Low (new) — anti-pattern block no longer demonstrates the anti-pattern (pre-aggregations-shared-calc-group.test.ts:685-702). After this change, rollups match under per-cube switches too, so the test now only asserts that. The whole point of the block is to document that per-cube switches are wrong — but "wrong" now lives entirely in the numeric result (the unresolved switch's case measure gets cross-joined across values), which the test never checks. Consider one deterministic value assertion using the NoPreAggs variant of the per-cube model showing the result diverges from the shared-switch result (or from the expected number). Otherwise a future regression that silently changes the unresolved-switch behavior would slip past — the assertions only cover rollup selection, not the semantic bug the anti-pattern is meant to warn against.

Low (carried) — smoke test some() matchers don't pin count (smoke-shared-calc-group.test.ts:104-106, 124-126, 152-153). expect(tables).toHaveLength(2) alongside the some() matchers would catch an unexpected extra pre-agg being served on top of the two expected ones — cheap defense-in-depth on top of CUBEJS_ROLLUP_ONLY.

Addressed since previous review

  • ✅ Prior "anti-pattern assertion asymmetry" note — moot: block is now rewritten to reflect the new behavior.
  • ✅ Birdbox rollups previously listed the calc-group dim (per fixture diff) — dropped, matching the "slim rollups" narrative.

Not blocking

  • One skipped it.skip FIXME remains in the schema-compiler spec (calc-group dim not projected into multi-stage window CTE). Worth filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
  • The preAggregationsSchema: '' outlier (pre-aggregations-shared-calc-group.test.ts:506) is still present. Not touched by this commit; noting only for continuity.
  • Filter / having / join-on subquery bodies are still not recursed into by the trivial-subquery collapse pass from earlier commits (missed optimization, not correctness).

• Branch •

@paveltiunov paveltiunov changed the title feat(tesseract): collapse trivial pass-through subqueries; e2e specs for cross-cube rolling measures over rollups feat(tesseract): pre-agg matching without stored calc-group dims; collapse trivial pass-through subqueries; e2e specs for cross-cube rolling measures over rollups Jul 25, 2026
Address review feedback: the anti-pattern block asserted only rollup
selection after calc groups stopped blocking matching, so the semantic
bug it warns about was no longer demonstrated. A new deterministic test
on a no-pre-aggs variant of the per-cube switch model shows the
unresolved share_metrics switch emitting one row per enumeration value
(a duplicate P1 row with a null share change from the YTD branch)
instead of the single 0.3 row the shared-switch model returns.

The Cube Store smoke tests now assert the exact set of rollup tables
used instead of some() containment: usedPreAggregations keys are
per-usage (__usage_N suffix), so they are deduped to distinct rollup
tables and compared with toEqual, catching any unexpected extra
pre-aggregation being served.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QxbxLWpBwunw3FypC8zfnY
@claude

claude Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 43s —— View job


Code Review (updated for latest commit: ddf3e24)

No blocking issues. Verdict: 0 high, 0 medium, 0 low.

Details — what's new and remaining notes
  • Read latest commit (ddf3e24 test: pin rollup sets and demonstrate per-cube switch divergence)
  • Verify the new deterministic anti-pattern test
  • Verify the smoke-test rollup-set assertions
  • Dedupe against prior review notes

What's new since the previous review

Test-only follow-up that directly addresses both remaining low-severity notes from prior reviews:

  1. Anti-pattern block now demonstrates the semantic bug (pre-aggregations-shared-calc-group.test.ts:493-521, 716-748). A new perCubeSwitchModelNoPreAggs variant of the per-cube switch model + a deterministic test asserts that when only the sales switch is filter-pinned in the view, share_metrics cross-joins its whole enumeration and emits an extra row per unresolved calc-group value (a duplicate P1 row with null from the YTD branch's empty 1-year-prior window) — versus the single 0.3 row the shared-switch model returns. This is exactly the "one row per enumeration value even though the dim isn't projected" symptom the block is meant to warn about, and the values are pinned tightly enough that a planner regression on the unresolved-switch path can't silently pass. Resolves my prior "anti-pattern no longer demonstrates the anti-pattern" note.

  2. Smoke-test rollup-set assertions (smoke-shared-calc-group.test.ts:70-81, 92, 109, 127, 153). usedPreAggregations() now strips the __usage_N per-usage suffix, dedupes, and sorts; assertions swap from some(t => t.includes(...)) to toEqual([SALES_ROLLUP, SHARE_ROLLUP]). Correctness spot-check: the regex /__usage_\d+$/ only strips the trailing usage index and preserves the schema.table shape, and the SALES_ROLLUP / SHARE_ROLLUP constants (dev_pre_aggregations.sales_perf_rolling, dev_pre_aggregations.share_metrics_perf_share) match the fixture's default dev schema + pre_aggregations prefix + snake-cased cube_preAggName. Assertions now catch an unexpected extra pre-agg being served, not just the presence of the two expected ones. Resolves my prior "some() matchers don't pin count" note.

Comments on both changes are precise and non-redundant with the code (the __usage_N comment on line 70-71 explains why the strip is needed, which isn't obvious from the code).

Addressed since previous review

  • ✅ Anti-pattern block only asserted rollup selection and no longer showed the semantic divergence — resolved by the new deterministic test on the no-pre-aggs variant.
  • ✅ Smoke test some() matchers didn't pin the count — resolved by the deduped toEqual on all four scenarios.

Not blocking (carried, but only for continuity)

  • One skipped it.skip FIXME still remains in the schema-compiler spec (calc-group dim not projected into multi-stage window CTE). Worth filing a tracking issue and linking it in the FIXME so it doesn't drift into silent tech debt.
  • preAggregationsSchema: '' outlier at pre-aggregations-shared-calc-group.test.ts:506 still present (every other integration test uses 'test'). Cosmetic; not touched by this commit.
  • Filter / having / join-on subquery bodies still not recursed into by the trivial-subquery collapse pass from earlier commits (missed optimization, not correctness).

• Branch •

Copy link
Copy Markdown
Member Author

CI note: the red tests (redshift, true) check is an infrastructure failure on the manual re-run, not a test failure. The job died in setup — actions/download-artifact resolved the docker-image artifact (ID 8613461437) but GetSignedArtifactURL returned 404 Not Found: workflow run not found, a known transient GitHub Actions backend error when re-running a single job. Zero tests executed.

This matrix leg is non-required and was originally cancelled by concurrency dedup; every other check on ddf3e24 is green (103 passing). I don't have API permission to re-run failed jobs from this session (403), so if a green mark is wanted here, one more "Re-run failed jobs" from the Actions UI should do it — the artifact itself is present and only hours old.


Generated by Claude Code

@paveltiunov
paveltiunov merged commit 0730e31 into master Jul 25, 2026
196 of 199 checks passed
@paveltiunov
paveltiunov deleted the claude/query-preagg-matching-tuhpz0 branch July 25, 2026 02:43
keydunov added a commit that referenced this pull request Jul 30, 2026
…atching

- reference/core-data-apis/rest-api/reference.mdx: update the /v1/load
  response Warning to reflect that all numeric values are now always
  serialized as JSON strings across every driver (#10949),
  replacing the old "most drivers" wording, and link to castNumerics.
- reference/data-modeling/pre-aggregations.mdx: document that `switch`-type
  dimensions no longer need to be listed in a rollup's `dimensions` for
  pre-aggregation matching to succeed (#11346).
igorlukanin added a commit that referenced this pull request Aug 4, 2026
…1346) (#11441)

* docs: pre-aggregation matching for switch dimensions (follow-up to #11346)

* docs: align inDateRange wording with the query-format reference and move the all-or-nothing caveat to multi-fact matching

* docs: use CUBE[...] refs in the recipe rollup and drop the colliding base measure

* docs: move the inDateRange note to time-dimension matching and explain the CUBE[...] rollup refs

* docs: move the multi-cube switch modeling advice to the case measures reference

* docs: close the switch matching section on its version caveat, not on prose

This branch was successfully deployed

1 active deployment
Preview — ddf3e245 Deployed Jul 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update Javascript code rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants