Repository navigation
feat(e6): subquery-tree multidialect transpile, HYBRID through the tree, dialect-regions performance - #334
Merged
Conversation
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.
Benchmark for 006aa7eClick to view benchmark
|
The corpus and subquery-tree tests import converter_api (uvicorn) and use FastAPI's TestClient (httpx).
Benchmark for 81bbdbeClick to view benchmark
|
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.
Benchmark for 1f82cc5Click to view benchmark
|
…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
Benchmark for 0e9e572Click to view benchmark
|
| _t = time.perf_counter() | ||
| try: | ||
| if tokens is None: | ||
| tree = sqlglot.parse_one(region, read="postgres") |
Collaborator
There was a problem hiding this comment.
I see "postgres" hardcoded here. Is it specifically for postgres.
Author
There was a problem hiding this comment.
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.
…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.
Benchmark for a100879Click to view benchmark
|
gauravdawar-e6
approved these changes
Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Brings
wip/e6-multidialect-subquery-tree(including #333) intomain, withmainmerged in.What this adds
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_lite_parser.py): for Freshworks; backticks are rewritten up front and the whole query is tried as Postgres before the tree.sqlglotrs), parser early exits, cheaper e6 generation and pipeline pre-checks.Flags
MULTIDIALECT(+INNER_DIALECT)ENABLE_MULTIDIALECT_TRANSPILEis onSUBQUERY_TREEsplit_pg_outerSAMSUNG_TABLEAU_DASHBOARDHYBRID_MULTIDIALECTWith
SUBQUERY_TREEandHYBRID_MULTIDIALECTat their default (off),MULTIDIALECTrequests take the samesplit_pg_outerpath as onmaintoday.Also included: the Rust tokenizer now handles Databricks unknown escapes like the Python one (
test_native_escape_parity).Merge of
mainNo conflicts. Parity with current
main(fb35337) over all 1,736 Samsung, Condé Nast and OneTrust queries, plain andMULTIDIALECTpaths, 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:mainemitsTIMESTAMP_DIFF('PreviousMonth', TRY_CAST(SubMonth AS TIMESTAMP), "MONTH")on theMULTIDIALECTpath. The Postgres parser now reads the Databricks/MySQLTIMESTAMPDIFF(unit, start, end)(build_date_delta, as Spark and MySQL), and the HYBRID-only end-first reassembly intimestamp_diff_sqlis removed. Every path (plain, MULTIDIALECT, subtree, hybrid; java or native) now emits main's unit-firstTIMESTAMP_DIFF('MONTH', start, end).Testing
make check: style (ruff, ruff-format, mypy) passes;make testandmake test-rspass.make test/make test-rsand run withmake test-multidialect(passes).httpxanduvicornadded to thedevextras: the subtree tests importconverter_apiand use FastAPI'sTestClient.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):