Skip to content

feat(e6): subquery-tree multidialect transpile, HYBRID through the tree, dialect-regions performance - #334

Merged
tkaunlaky-e6 merged 30 commits into
mainfrom
merge/subtree-into-main
Nov 17, 2026
Merged

tkaunlaky-e6 merged 30 commits into
mainfrom
merge/subtree-into-main

Conversation

@tkaunlaky-e6

@tkaunlaky-e6 tkaunlaky-e6 commented Oct 30, 2026 •

Copy link
Copy Markdown

Brings wip/e6-multidialect-subquery-tree (including #333) into main, with main merged in.

What this adds

  • Subquery-tree multidialect transpile (apis/utils/subquery_tree.py, lite_parser.py): one lightweight structural parse of the query into a tree of subquery regions; each region is transpiled to e6 in its own dialect (Postgres, else Databricks) and spliced back.
  • HYBRID_MULTIDIALECT through the subquery tree (hybrid_lite_parser.py): for Freshworks; backticks are rewritten up front and the whole query is tried as Postgres before the tree.
  • Dialect-regions performance work (perf: cut parser, cleanup and e6 generator overhead in subquery-tree conversion #329, perf: dialect-regions optimizations, benchmark cleanup and MULTIDIALECT-only trigger #333): region-token reuse (Python and sqlglotrs), parser early exits, cheaper e6 generation and pipeline pre-checks.
  • Corpus tests: Samsung (704), Condé Nast (924) and OneTrust prod queries, checked under both multidialect methods.

Flags

Flag Kind Effect
MULTIDIALECT (+ INNER_DIALECT) request feature flag, sent by the planner when ENABLE_MULTIDIALECT_TRANSPILE is on triggers the multidialect path
SUBQUERY_TREE deployment env, default off inside that path: on = subquery tree, off = existing split_pg_outer
SAMSUNG_TABLEAU_DASHBOARD deployment env unchanged
HYBRID_MULTIDIALECT deployment env Freshworks

With SUBQUERY_TREE and HYBRID_MULTIDIALECT at their default (off), MULTIDIALECT requests take the same split_pg_outer path as on main today.

Also included: the Rust tokenizer now handles Databricks unknown escapes like the Python one (test_native_escape_parity).

Merge of main

No conflicts. Parity with current main (fb35337) over all 1,736 Samsung, Condé Nast and OneTrust queries, plain and MULTIDIALECT paths, java and native executor: identical except one query, fixed on purpose below.

TIMESTAMPDIFF in Postgres regions

Postgres has no TIMESTAMPDIFF, so a multidialect region read as Postgres filled the slots by position: main emits TIMESTAMP_DIFF('PreviousMonth', TRY_CAST(SubMonth AS TIMESTAMP), "MONTH") on the MULTIDIALECT path. The Postgres parser now reads the Databricks/MySQL TIMESTAMPDIFF(unit, start, end) (build_date_delta, as Spark and MySQL), and the HYBRID-only end-first reassembly in timestamp_diff_sql is removed. Every path (plain, MULTIDIALECT, subtree, hybrid; java or native) now emits main's unit-first TIMESTAMP_DIFF('MONTH', start, end).

Testing

  • make check: style (ruff, ruff-format, mypy) passes; make test and make test-rs pass.
  • The prod-query corpora (Samsung, Condé Nast, OneTrust) are a side suite so they don't slow CI: they skip under make test / make test-rs and run with make test-multidialect (passes).
  • httpx and uvicorn added to the dev extras: the subtree tests import converter_api and use FastAPI's TestClient.

Performance

Subquery tree on this branch vs before #329/#333 (Docker, 1 CPU, 3 repeats, 1,628 Samsung + Condé Nast queries, output identical on all):

Tokenizer Pretty Mean ms / query
Rust on 86.6 → 47.1 (−45.6%)
Rust off 79.3 → 46.8 (−40.9%)
Python on 116.8 → 66.7 (−42.9%)
Python off 108.8 → 62.9 (−42.1%)

tkaunlaky-e6 and others added 26 commits September 23, 2026 16:30
Parse once with the Databricks parser (error_level=IGNORE), reuse sqlglot's
parsed hierarchy to build a subquery-nodes tree from each exp.Subquery's
meta["raw_sql"], then walk bottom-up transpiling each subquery to e6 (Postgres
first, Databricks fallback on parse failure).
…r walk)

Normalize Databricks backticks to double quotes, parse once as Postgres, and emit
e6 in a single generator walk; the e6 HYBRID_MULTIDIALECT hook reparses any
subquery/join carrying a Databricks tell from its verbatim source.
…uery tree

Add a subquery-tree path meant to replace the MULTIDIALECT split for BI-tool queries
(Postgres/Tableau outer around a Databricks "Custom SQL Query" inner).

- apis/utils/lite_parser.py: LiteParser, the base sqlglot Parser with the SELECT list and
  trailing modifiers skipped; it still walks FROM/JOIN/LATERAL, so every subquery keeps its
  verbatim meta["raw_sql"] at a fraction of a full parse.
- apis/utils/subquery_tree.py: build a labelled subquery tree from the lite parse
  (reproduce() rebuilds the exact source), then transpile region by region;
  parse_region reads a region as Postgres, else Databricks, and its parse is reused.
- converter_api.py: SUBQUERY_TREE env flag routes /convert-query through the tree, each
  region going through _region_to_e6 (from_sql=None lets parse_region pick the dialect);
  generation skips the deep copy (copy=False).
- Remove apis/utils/hybrid_multidialect.py (the single-Postgres-parse approach).

Tests:
- tests/test_subquery_tree.py: round-trip and structure of the tree.
- tests/samsung/: all 704 Samsung Tableau prod queries in queries.csv.gz with the expected
  e6; the 674 on which subtree, MULTIDIALECT and SAMSUNG_TABLEAU_DASHBOARD agree must keep
  returning it under each mode. The other 30 differ only in Samsung emitting
  CAST(x AS DATE) where subtree/multidialect keep DATE(x); they are listed, not asserted.

On the 704 queries (4 CPU container), subtree mean 261 ms vs 443 ms for MULTIDIALECT, with
identical output on all 704.
tests/condenast/ mirrors tests/samsung/: queries.csv.gz holds the 924 distinct Conde Nast Qlik
prod queries (plain Databricks SQL, no Postgres wrapper) with the expected e6.

- all_match (858): subtree and MULTIDIALECT must both keep returning e6 exactly.
- subtree_fixes (48): Databricks-only syntax in the outermost query (a backtick name, a column
  starting with a digit). split_pg_outer raises "parse error not inside a subquery"; subtree
  reads the outer query as Databricks and must return e6, which is the plain Databricks transpile.
- both_fail (18): listed, not asserted -- // line comments (16) and truncated source (2).
…conversion

- parser: inline hot helpers (_advance, Expression.__init__, Parser.expression),
  fast exits in _parse_types, _parse_select_query, _parse_range and _parse_bitwise
  when no matching token follows, inlined _match_set in operator-precedence loops,
  faster _match_text_seq and update_positions
- helpers: normalize_unicode_spaces as precompiled regexes (fast path when nothing
  to replace); apply_e6_ast_transforms as an explicit stack walk
- e6: build the quote_identifier keyword set once at module level; indent fast path
  when no line toggles quote state

Output is identical on all 1,628 Samsung + Conde Nast queries (both tokenizers,
pretty on and off). Test suite unchanged: 937 passed / 4 skipped (Python
tokenizer), 940 passed / 1 skipped (Rust tokenizer).
- apis/utils/hybrid_lite_parser.py: HybridLiteParser splits out only a subquery Postgres
  cannot parse, after masking the subqueries already split out of it. The rest stay in
  their parent's region, where the e6 generator reparses a Databricks subquery or join
  with its context (raw_sql, the parent's joins).
- apis/utils/lite_parser.py: lite_parse uses it when e6.HYBRID_MULTIDIALECT is on.
- converter_api.py: the backtick -> double-quote rewrite runs before the tree; under
  HYBRID_MULTIDIALECT the whole query is tried as Postgres first and the tree is built
  only when that fails.
- tests/test_hybrid_subquery_tree.py: subtree and MULTIDIALECT give the same e6 on the
  hybrid edge cases.
…d subtree

tests/onetrust/ mirrors tests/condenast/: queries.csv.gz holds the 108 OneTrust Power BI
prod queries (99 distinct texts, a "$Table" outer around Databricks SQL, no backticks)
with the expected e6.

OneTrust runs the old MULTIDIALECT split (split_pg_outer); its output is the expected e6,
and subtree returns the same on all 108, so every query is all_match and must keep
returning e6 exactly under both modes.
perf: cut parser, cleanup and e6 generator overhead in subquery-tree conversion
…match

- parser: return early when the next token can't start what is being probed
  (alias, set operation, window, lambda tail on ")"/","/end; interval only on
  INTERVAL; AT TIME ZONE only on AT), inline bracket/look-ahead/comment checks in
  _parse_bracket, _match, _parse_select and _parse_function
- expressions: precompute each class's mandatory arg keys for error_messages
- generator: call maybe_comment only for nodes that have comments; e6 cast_sql
  compares the INTERVAL type directly; e6 indent returns early for single lines
- pipeline: LiteParser._skip scans by index and advances once; the e6 transform
  walk reads node.args directly; plain substring pre-checks before the STRUCT and
  unicode-space regexes

Test suite unchanged: 937 passed / 4 skipped (Python tokenizer), 940 passed /
1 skipped (Rust tokenizer).
They documented the measurements behind the region-token and parser changes; nothing
imports them. Keeps the upstream benchmarks/ (bench, optimize, parse).
…e' into codex/experiment-dialect-regions

# Conflicts:
#	converter_api.py
- ruff format the files the subtree/hybrid/region-token work left unformatted
- lite_parse: cast the parsed tree to its declared return type
- parse_region: name the token-reuse parse result separately so mypy sees the None check
- region_tokens: '# type: ignore' the sqlglotrs import, as sqlglot.tokens does
- _region_to_e6: from_sql is Optional (the subquery tree passes None)
- setup.cfg: skip mypy errors in converter_api, as for guardrail (tests now import it)
SUBQUERY_TREE now only picks the multidialect method (subquery tree vs split_pg_outer); the
path itself is triggered by the MULTIDIALECT feature flag (or SAMSUNG_TABLEAU_DASHBOARD).
Before, a deployment with SUBQUERY_TREE on sent every request through the subquery tree,
plain single-dialect ones included, ignoring from_sql.

The corpus tests' subtree mode now sends MULTIDIALECT, and a test pins that SUBQUERY_TREE
alone does not reach the tree.
perf: dialect-regions optimizations, benchmark cleanup and MULTIDIALECT-only trigger
…TAMP_DIFF

main's unit-first TIMESTAMP_DIFF (#322) changes the e6 output of one all_match query.
Subtree and MULTIDIALECT still return the same e6 on all 858 all_match queries.
@github-actions

Copy link
Copy Markdown

Benchmark for 006aa7e

Click to view benchmark
Test Base PR %
long 229.5±2.91µs 162.0±2.33µs -29.41%

The corpus and subquery-tree tests import converter_api (uvicorn) and use FastAPI's
TestClient (httpx).
@github-actions

Copy link
Copy Markdown

Benchmark for 81bbdbe

Click to view benchmark
Test Base PR %
long 188.6±8.20µs 125.7±4.35µs -33.35%

The Samsung, Conde Nast and OneTrust corpus tests run every query through both
multidialect methods and dominate the test time. They now skip unless
MULTIDIALECT_CORPUS=1; make test-multidialect runs them.
@github-actions

Copy link
Copy Markdown

Benchmark for 1f82cc5

Click to view benchmark
Test Base PR %
long 135.4±4.18µs 97.4±3.50µs -28.06%

…regions

Postgres has no TIMESTAMPDIFF, so a multidialect region read as Postgres filled the
TimestampDiff slots by position and emitted TIMESTAMP_DIFF('<end column>', start, MONTH).
Parse it like Spark/MySQL (build_date_delta), so every path -- plain, MULTIDIALECT,
subtree, hybrid, java or native executor -- emits main's unit-first
TIMESTAMP_DIFF('MONTH', start, end).

- drop the HYBRID_MULTIDIALECT reassembly in timestamp_diff_sql, which undid the old
  scramble into the end-first form
- Conde Nast: the one TIMESTAMPDIFF query now matches the plain Databricks transpile
@github-actions

Copy link
Copy Markdown

Benchmark for 0e9e572

Click to view benchmark
Test Base PR %
long 136.7±9.45µs 96.6±1.46µs -29.33%

_t = time.perf_counter()
try:
if tokens is None:
tree = sqlglot.parse_one(region, read="postgres")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see "postgres" hardcoded here. Is it specifically for postgres.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, Postgres is intentional. These queries come from BI tools which always wrap the customer's SQL in a Postgres style outer query, so each part is tried as Postgres first.

Comment thread apis/utils/subquery_tree.py Resolved
…onstant

Review follow-ups on #334:

- parse_region fell back to a hardcoded "databricks" for a region that fails the
  Postgres parse, ignoring the request's INNER_DIALECT that split_pg_outer honours.
  It now takes inner_dialect (default "databricks"), passed from the converter, so a
  Snowflake inner (e.g. a::VARIANT:b) gives the same e6 under both methods.
- "(SELECT NULL AS {})" was spelled out at five sites; it is now PLACEHOLDER next to
  MARKER in multidialect.py.
@github-actions

Copy link
Copy Markdown

Benchmark for a100879

Click to view benchmark
Test Base PR %
long 206.1±6.05µs 147.0±3.76µs -28.68%

@tkaunlaky-e6
tkaunlaky-e6 merged commit 8b98e40 into main Nov 17, 2026
7 checks passed
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.

3 participants