Adapting Spider to sqlglot (matching.py)¶
Both ComponentMatching and ExactMatching adapt Yu et al. (EMNLP 2018) onto a single, dialect-general, bug-fixed sqlglot AST engine in src/group_by_vibes/matching.py rather than wrapping or cloning taoyds/spider.
This page explains why the original parser and dict schema could not generalize, walks through every pass of our 6-pass sqlglot decomposition pipeline, and catalogs all upstream bugs fixed and generalizations added.
1. Why Not process_sql.py or Flat-Dict Lowering?¶
During design, we measured two naive ways to bring Spider metrics into group-by-vibes against the 500 SQLite gold queries in bird_mini_dev (design doc):
| Approach | Outcome on bird_mini_dev (n = 500) |
Why It Was Rejected |
|---|---|---|
Verbatim or pure-Python port of taoyds/spider/process_sql.py |
Fails on >90% of gold queries |
Pulls nltk.word_tokenize + runtime punkt downloads; SQLite-centric grammar rejects INNER/LEFT JOIN, implicit table aliases, SELECT ... AS aliases, IS NULL, <>, and quoted identifiers. |
Parse with sqlglot, then lower into Spider's flat dict AST |
Fails on 376/500 (75.2%) of gold queries |
Spider's flat dict schema has no slots for scalar/cast functions (CAST, ROUND, IF/IIF, SUBSTR, COALESCE: 324/500), CTEs (WITH: 150/500), CASE WHEN (111/500), nested/literal arithmetic like 1.0 * a / b (111/500), or window functions (25/500). |
Direct sqlglot AST decomposition (matching.py) |
Parses & decomposes 500/500 (100.0%) of gold queries |
Zero new runtime dependencies beyond sqlglot>=30.0.0,<31.0.0, full dialect generalization across PostgreSQL/SQLite/MySQL/Snowflake/BigQuery, and full BIRD coverage (498 Select, 2 Union). |
2. Six-Pass sqlglot AST Pipeline¶
Every parsed query runs through _decompose_query_ast on a deep AST copy (caller ASTs are never mutated), catching (SqlglotError, RecursionError) so deeply nested or malformed trees never crash a batch:
flowchart TD
A["Raw Prediction (+ optional extractor) & References"] --> B["Query AST Gate: parse_sql + exp.Query unwrap"]
B --> C["Per-Row Validation: normalize_schema & union-find kmap"]
C --> D["Pass 1: Wave-by-wave topological CTE alpha-renaming"]
D --> E["Pass 2: Left-associative IUEN chain & root modifier hoisting"]
E --> F["Pass 3: Scope-aware alias, schema, FK kmap & ident folding"]
F --> G["Pass 4: SELECT alias strip, DISTINCT & ignore_values mask"]
G --> H["Pass 5: Recursive __subq_ hashing & non-literal-LHS canonicalization"]
H --> I["Pass 6: 12-component multisets, keywords, hardness & 32-char SHA-256 sig"]
I --> J["ComponentMatching"]
I --> K["ExactMatching"]
Query AST Gate (parse_query_ast)¶
- Calls optional
extractor(apply_extractor) on predictions only (references are raw SQL). - Calls
parser.parse_sqlto enforcemax_query_chars, reject empty inputs, reject multi-statement strings, and rejectexp.Commandparser fallbacks. - Unwraps outer parenthesized
exp.Subquerywrappers (hoisting outerWITH,ORDER BY,LIMIT,OFFSETonto the wrapped query) and accepts onlyexp.Selectorexp.SetOperationroots—rejecting DDL/DML (CREATE,DROP,INSERT,UPDATE,DELETE) cleanly as"non_query".
Pass 1: Wave-by-Wave Topological CTE Alpha-Renaming (_process_with_clause)¶
Equivalently structured queries often name helper CTEs differently (WITH cte1 AS (...) vs. WITH filtered AS (...)). Pass 1 canonicalizes CTE names deterministically:
- Extracts every
exp.CTEinexp.With, capturing optional explicit column alias lists (WITH c(x, y) AS (...)) and table dependencies. - Groups CTEs into Kahn topological waves (wave
0= CTEs referencing no other local CTE; wavew= CTEs whose CTE dependencies belong to waves< w), temporarily binding recursive self-references to"__self__"(and mutual cycles to"__cycle__"if encountered). - Recursively decomposes each CTE body inside the current wave, sorts wave entries by
(body_nq.canonical_signature, col_aliases), assigns consecutive placeholders__cte_0__,__cte_1__, ..., and propagatesactive_cte_mapandactive_cte_colsinto downstream waves and the outer query.
Pass 2: Left-Associative IUEN Flattening¶
UNION, INTERSECT, and EXCEPT chains are walked left-associatively (while isinstance(cur, exp.SetOperation)):
- Matches Spider's convention (
evaluation.py:235-242): the leftmost baseexp.Selectprovides the primaryselect,from,where,group,order, etc., while each right-hand branch is recursively decomposed into(op_kind, NormalizedQuery)entries iniuen_branches(union/intersect/except, or*_allwhenignore_distinct=False). - Any
WITH,ORDER BY,LIMIT, orOFFSETattached at outerSetOperationnodes is hoisted onto the base query.
Pass 3: Two-Layer Identifier Normalization, Scope Resolution, schema, and foreign_keys¶
Instead of invoking sqlglot.optimizer.qualify (which performs invasive projection expansion, subquery unnesting, and schema-dependent rewrites that break structural comparability with Spider), Pass 3 separates identifier handling into two explicit layers:
Layer A — Lookup Layer (for schema and foreign_keys resolution)¶
- Why two layers? Dialects disagree on unquoted casing rules: SQLite folds case-insensitively, Snowflake uppercases unquoted identifiers, PostgreSQL lowercases unquoted identifiers, and BigQuery (
CASE_INSENSITIVE_EXCEPT_TABLES) keeps table lookup case-sensitive while treating column names case-insensitively. - Every SQL table, alias, column, and
foreign_keysendpoint is normalized for lookup viadialects.normalize_grounding_identifier(..., dialect=dialect, is_table=...)anddialects.split_qualified_table_parts(which handles quoted names containing dots or spaces such as"1-29135051-2"or`Avg. Score`), whileschemacatalog tables and columns normalize viagrounding.normalize_schema(_normalize_schema_key_partand_normalize_schema_column, preserving exact catalog casing onpostgresandsnowflakewhile folding case-insensitively onsqlite).
Union-Find Foreign Key Equivalence (kmap)¶
- Validated eagerly per row by
normalize_foreign_keys(Noneor[]allowed; rejects 1-part/3-part names withValueError; rejectsstr/bytes/Mappingouter values withTypeError). - Pairs such as
[("users.id", "orders.user_id"), ("orders.user_id", "items.uid")]are grouped via union-find so every column in the transitive equivalence class maps to the lexicographically smallest canonical AST representative (canon_by_keyordered by(table_name, table_quoted), (col_name, col_quoted)). - Scoping invariant: Matching Spider's
build_valid_col_unitsrule,kmaprewrites a resolvedtable.colreference only when that physical table is active in the current or outer correlated query'sFROM/JOINsources. - Both
schemaandforeign_keysperform eager per-row validation with zero cross-row caching for deterministic isolation.
Alias, Self-Join, Derived Table & SELECT-Alias Protection Rules¶
- Physical aliases:
FROM users AS urewritesu.name->users.name. Self-joins (FROM emp e1 JOIN emp e2) map both aliases to physical table"emp", keepingfrom_tables = ("emp", "emp")! - Derived tables (
FROM (SELECT ...) AS sub): Decomposed eagerly, sorted by(canonical_signature, src_idx), and bound to deterministic placeholders__subq_0__,__subq_1__, ... SELECToutput aliases in clauses: Before qualifying unqualified columns insideGROUP BY,HAVING, orORDER BY,matching.pychecks_select_alias_names(viagrounding._in_clause_for_select) so projection aliases (e.g.,SELECT COUNT(*) AS cnt FROM users ORDER BY cnt) are never mis-qualified asusers.cnt.- Unqualified column qualification: If
schemais provided, qualifies an unqualified column only when exactly one active physical table in scope owns that column; ifschema is None, qualifies only when the query has a single non-opaque physical table and no CTE/derived sources. Ambiguous columns stay unqualified safely.
Layer B — Canonical AST Layer (for rendered expressions)¶
After all alias/schema/kmap lookups finish, _fold_ident_inplace folds all unquoted exp.Identifier nodes to lowercase while preserving exact text on quoted identifiers (ident.quoted == True) across every dialect. That ensures Snowflake unquoted SELECT COUNT(*) FROM USERS and lowercase SELECT count(*) FROM users fold identically, while "MixedCase" vs "mixedcase" stays distinct when quoted.
Pass 4: Alias Stripping, DISTINCT, and Value-Blind Masking¶
- Strip
SELECToutput aliases:SELECT expr AS alias->expr(now safe because Pass 3 already protectedGROUP BY/HAVING/ORDER BYalias references). ignore_distinct=True(default): ClearsSELECT DISTINCT/DISTINCT ONand unwrapsDISTINCTinside aggregate functions (COUNT(DISTINCT id)->COUNT(id)). Setignore_distinct=Falseto enforce exactDISTINCTparity.ignore_values=True(default):- Rewrites
COUNT(1)->COUNT(*)first (before masking1!). - Replaces non-exempt
exp.Neg(Literal)andLiteral/Boolean/Nullnodes withexp.Var(this="__val__"). - Explicit AST Exemptions (
_is_exempt_from_value_mask): Never masks literals insideexp.DataTypeParam/exp.DataType(CAST(x AS VARCHAR(10))),exp.Limit/exp.Fetch/exp.Offset(controlled separately byinclude_limit_value),exp.WindowSpecframe bounds (ROWS BETWEEN 1 PRECEDING AND CURRENT ROW), or positional integer ordinals directly inGROUP BY 1/ORDER BY 1.
- Rewrites
Pass 5: Recursive Subquery Hashing & Non-Literal-LHS Canonicalization¶
- Nested subquery placeholders (
_replace_nested_subqueries_in_subtree): Any nestedexp.Select,exp.SetOperation, orexp.SubqueryinsideWHERE,HAVING,SELECT, orJOIN ON(preserving outer correlated scopesouter_aliases/outer_qual/outer_physical) is recursively decomposed into aNormalizedQueryand replaced withexp.Var(this=f"__subq_{sub_nq.canonical_signature}__"). Becausecanonical_signatureis a 32-char SHA-256 hash of order-normalized sub-components, reordered clauses inside nested subqueries still match identically. - Non-literal-LHS predicate canonicalization (
_canonicalize_predicates_subtree):- Note that both
!=and<>parse toexp.NEQinsqlglot. _is_rhs_value_likeclassifiesLiteral,Boolean,Null,Placeholder,Neg(Literal),__val__, and__subq_*__(important because__subq_starts with_, ASCII 95 <'a', so subquery RHS stays onexpressionmatchingWHERE col = (SELECT ...)).- For
EQ/NEQ: always places the non-value expression onthis(LHS) and value-like operand onexpression(RHS)—so'S' = s.rtypebecomess.rtype = 'S'(ors.rtype = __val__). Equal-class operands sort lexicographically by rendered SQL (a = bvsb = a). - For ordered comparisons (
<,<=,>,>=): flips operator and operands when LHS is value-like and RHS is not (10 < age->age > 10). - Sorts literal lists inside
IN (...)when no subquery is attached, and flattens/sorts associativeAND/ORchains while keeping precedence parentheses on mixed operators ((a OR b) AND c).
- Note that both
Pass 6: Extraction, canonical_signature, and Hardness¶
- Extracts all 12 immutable clause representations into
NormalizedQuery. - Dialect AST edge cases handled explicitly: In PostgreSQL,
NOT LIKEandIS NOT NULLattachnegate=Trueonexp.Like/exp.Isinstead of wrapping inexp.Not;_extract_condition_keywords_and_countschecks bothisinstance(node, exp.Not)andbool(node.args.get("negate"))sokeywordsalways records"not". Similarly, omittedORDER BYdirection defaults to"asc"and emits"asc"inkeywords. - Computes the 32-char SHA-256
canonical_signatureover JSON-sorted component bags (retaining order onorder_by) and computes the 4-level Spider hardness bucket (easy,medium,hard,extra).
3. Complete Summary: Upstream Bugs Fixed & Generalizations¶
Verified Defects Fixed vs. taoyds/spider/evaluation.py¶
| Upstream Location | Upstream Defect | Impact | Fix in group_by_vibes |
|---|---|---|---|
evaluation.py:604-605 |
Sets f1 = 1 whenever acc == 0 and rec == 0 regardless of acc_count/rec_count. |
Components with 0% matches (IUEN, cte on BIRD) falsely score 1.000! |
finalize_component_bucket returns None only when pred_count == 0 and label_count == 0, else 0.0. |
evaluation.py:195-203, 419 |
eval_and_or returns (len(pred), len(label), 0) on mismatch while caller unpacks (label_total, pred_total, cnt); returns (1, 1, 1) on empty set(). |
Swaps precision/recall denominators on mismatch and inflates and/or F1 with empty queries. |
score_pair fixes tuple order and excludes both-empty and/or sets from corpus denominators (pred_total=label_total=0, per-example 1). |
evaluation.py:333, 338 |
count_others calls count_agg(unit[0] != 0) on where[::2] (not_op booleans) and unsliced having ('and'/'or' strings). |
Falsely inflates agg_count > 1 hardness checks. |
_count_current_level_aggs counts only genuine exp.AggFunc AST nodes at current query level. |
evaluation.py:386-390 |
sorted(label['from']['table_units']) crashes with TypeError on >= 2 subquery dicts; skips FROM check when len(label) == 0. |
Python 3 crash on multiple derived tables; false positive when gold has no FROM. |
Unconditionally checks Counter(from_tables) equality and recursive order-insensitive multiset matching on from_subqueries. |
evaluation.py:123 |
eval_sel mutates label['select'][1] in place via .remove(). |
Corrupts reused gold dicts on repeated or multi-reference evaluation. | Immutable NormalizedQuery tuples/frozensets and pure Counter set intersections. |
Generalizations Beyond taoyds/spider¶
| Area | taoyds/spider Limitation |
Generalization in group-by-vibes |
|---|---|---|
| SQL Dialects & Grammar | SQLite-centric parser + nltk; fails >90% of BIRD SQL |
Any sqlglot dialect (postgres, sqlite, mysql, snowflake, bigquery, etc.); 100% of bird_mini_dev gold (500/500) |
| Evaluated Components | 10 keys (5 headline in Paper Table 3) |
12 keys: adds cte (WITH) and opt-in join_on (include_join_conditions=True) |
| Value / Strict Toggles | Hardcoded DISABLE_VALUE = True, DISABLE_DISTINCT = True |
Same defaults for Spider parity + 5 explicit auditable toggles (ignore_values, ignore_distinct, include_limit_value, include_join_conditions, skip_unparseable_predictions) |
| HAVING & LIMIT Edges | Requires GROUP BY for group; requires ORDER BY for order; order-sensitive having lists |
Supports standalone HAVING, order-insensitive GROUP BY/HAVING multisets, LIMIT/OFFSET without ORDER BY, FETCH, and NULLS FIRST/LAST |
| Schema & Foreign Keys | Requires Spider tables.json global DB files |
Optional per-query schema dict + transitive union-find foreign_keys (kmap) with zero global state and AST-only fallback when omitted |
| Safety & Privacy | Prints/stores raw SQL dicts in memory | Bounded max_input_chars / max_query_chars, (SqlglotError, RecursionError) guards, and zero raw SQL or literals in per_example outputs or logs |