Skip to content

Preserve scoped CTE identity when combining metric queries - #2756

Open
Miskho wants to merge 2 commits into
DataJunction:mainfrom
Miskho:codex/dj-fix-cte-identity
Open

Miskho wants to merge 2 commits into
DataJunction:mainfrom
Miskho:codex/dj-fix-cte-identity

Conversation

@Miskho

@Miskho Miskho commented Nov 26, 2026 •

Copy link
Copy Markdown

Summary

Two metric queries can each work on their own but fail when combined because their independently optimized CTEs have the same name and different columns. This PR preserves both variants when their resolved SQL differs.

For example, a regression fixture starts with (day, account_id, cnt) rows (1, 1, 2), (1, 1, 3), (1, 2, 0), and (2, 1, 4). A shared transform groups by day and account, computing downloaded_any = MAX(CASE WHEN cnt > 0 THEN 1 ELSE 0 END) and download_cnt = SUM(cnt):

day account_id downloaded_any download_cnt
1 1 1 5
1 2 0 0
2 1 1 4

The two metric branches independently remove columns they do not need:

Branch Upstream CTE name Columns retained after pruning Metric
A: membership cteidentity_download_window day, account_id, downloaded_any SUM(downloaded_any)
B: volume cteidentity_download_window day, account_id, download_cnt SUM(download_cnt)

The names match, but the CTE bodies no longer do. Previously, deduplicating by name could keep A's version and leave B referring to a missing download_cnt column. Reversing metric order can change which column is missing. Other same-name conflicts can silently substitute a different expression.

The fix shares equal resolved bodies and assigns distinct names to conflicting variants, updating their consumers. Both standalone metrics and the combined query then agree:

day Downloaded accounts Downloads
1 1 5
2 1 4
Query Before After
Either metric alone Correct results Correct results
Both metrics together Missing-column error in this fixture Both expected daily rows above

Share CTEs only when their rendered bodies match after resolving dependencies in their original scopes. Give conflicting variants and their readers distinct names while preserving aliases, qualified bindings, nested shadowing, and physical table references. Use the same collector for combined measures and reserve generated wrapper names while preserving window-lookback lookup.

Resolve quoted and unquoted identifiers using the target dialect's SQLGlot normalization rules, preserving the producer's quoting when rebinding readers. This prevents mixed-case CTE readers from falling through to a physical table while retaining quoted-case distinctions in dialects such as PostgreSQL.

Test Plan

  • Current integration run with all three compiler fixes and Greptile follow-ups: 1,950 compiler, cube API, and SQL instrumentation tests passed; 14 expected failures, zero failures. Combined Ruff, format and mypy checks passed.
  • Current CTE, combined-measures, and lookback checks: 211 passed, with 100% statement/branch coverage for the CTE helper. Existing metrics SQL module: 140 passed. Six additional native PostgreSQL controls passed.
  • Hooks passed on all five public files, including Ruff and mypy.
  • Focused CTE regressions include API-generated SQL executed unchanged in DuckDB, both metric orders, combined measures, conflicting expressions, dependencies, aliases, nested scopes, generated-name collisions, and mixed-case/quoted readers with physical-table-shadowing controls. Before the follow-up fix, 42 selected new cases produced 34 failures and eight passing controls.
  • Earlier full server/doctest run before the review follow-ups: 7,016 passed, 823 skipped, 26 expected failures; 100% statement/branch coverage. Earlier live authenticated HTTP/native DuckDB restart checks also passed.

Local execution used Python 3.13, DuckDB, and six native PostgreSQL controls. Spark/Trino and other dialect policies received AST/rendering checks; their native execution, other Python CI versions, and optional integration stacks were not run locally. Identifier matching uses SQLGlot's dialect defaults; engine session overrides and plugin-specific matching rules are not modeled. CTE resolution covers ordered, non-recursive CTEs; SQL equality is conservative. A direct AST input with an unqualified physical table named base_metrics remains a lookback-densification corner case; no ordinary API reproduction was found with catalog/schema-qualified sources.

Deployment Plan

No schema migration. Generated SQL may retain distinct CTE variants that were previously deduplicated by name.

Companion compiler fixes, validated together: #2754 (cross-fact aggregation) and #2755 (output-dimension filters). These PRs share compiler files; later PRs may need rebasing after the first merge.

@netlify

netlify Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

👷 Deploy request for thriving-cassata-78ae72 pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 082da84

@Miskho
Miskho marked this pull request as ready for review November 26, 2026 09:14
@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge; the previous quoted-reader issue is addressed.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the previous quoted-reader issue is addressed.

Summary

The PR preserves distinct same-name CTEs when their resolved SQL differs.

  • Combined metric queries keep conflicting CTE bodies with their matching readers.

Miskho documents the existing direct-AST lookback corner case with an unqualified physical table named base_metrics as known; it is not a new finding.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Independent grain-group queries] --> B[Resolve CTE readers in each original scope]
  B --> C{Same name and resolved body?}
  C -->|Yes| D[Share one CTE]
  C -->|No| E[Allocate distinct names]
  E --> F[Rebind readers and keep aliases]
  D --> G[Build combined query]
  F --> G
Loading

Reviews (2) · Last reviewed commit: "Respect dialect identifier rules when bi..." · Reviewed by Greptile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant