thanhdath commited on
Commit
4d967b4
·
verified ·
1 Parent(s): 6e368f6

Simplify: evaluation sets + KaSLA case-by-case only; short README linking to github.com/thanhdath/grast-sql

Browse files
README.md CHANGED
@@ -2,12 +2,10 @@
2
  license: cc-by-4.0
3
  language:
4
  - en
5
- task_categories:
6
- - table-question-answering
7
  tags:
8
  - text-to-sql
9
  - schema-linking
10
- pretty_name: GRAST-SL schema-linking evaluation sets (Spider, BIRD, Spider 2.0-Snow)
11
  configs:
12
  - config_name: spider_dev
13
  data_files: evaluation_set/spider_dev.csv
@@ -15,104 +13,33 @@ configs:
15
  data_files: evaluation_set/bird_dev.csv
16
  - config_name: spider2_snow_256
17
  data_files: evaluation_set/spider2_snow_256.csv
18
- - config_name: comparison_spider_case_by_case
19
  data_files: comparison_with_kasla/spider_dev_case_by_case.csv
20
- - config_name: comparison_bird_case_by_case
21
  data_files: comparison_with_kasla/bird_dev_case_by_case.csv
22
- - config_name: comparison_spider_label_errors
23
  data_files: comparison_with_kasla/spider_dev_label_errors.csv
24
- - config_name: comparison_bird_label_errors
25
  data_files: comparison_with_kasla/bird_dev_label_errors.csv
26
  - config_name: spider2_snow_case_by_case
27
  data_files: comparison_with_kasla/spider2_snow_case_by_case.csv
28
- - config_name: spider2_snow_parser_failures
29
- data_files: comparison_with_kasla/spider2_snow_parser_failures.csv
30
- - config_name: spider2_snow_lexical_baseline
31
- data_files: comparison_with_kasla/spider2_snow_lexical_baseline.csv
32
  - config_name: summary_statistics
33
  data_files: comparison_with_kasla/summary_statistics.csv
34
  ---
35
 
36
- # GRAST-SL — schema-linking evaluation sets and gold-label evidence
37
 
38
- Audited schema-linking gold labels (gold *used columns* per question) for three text-to-SQL
39
- benchmarks, plus the per-question, per-column evidence comparing them against the only released
40
- third-party label set (KaSLA's, which reuses CodeS's labels).
41
 
42
- | evaluation set | instances | databases | viewer config | full file |
43
- |---|---:|---:|---|---|
44
- | Spider dev | 1,034 | — | `spider_dev` | `full/spider_dev_gold_final.json` |
45
- | BIRD dev | 1,534 | — | `bird_dev` | `full/bird_dev_gold_final.json` |
46
- | Spider 2.0-Snow (paper set) | 256 | 105 | `spider2_snow_256` | `full/spider2_snow_eval_gold_256.json` |
47
- | Spider 2.0-Snow (maximal public-gold set) | 282 | 110 | — | `full/spider2_snow_eval_gold_282.json` |
48
 
49
- Gold definition: *the columns the released gold SQL actually uses*. Spider/BIRD labels are derived
50
- from the official dev-set gold SQL; Spider 2.0-Snow labels from the released public gold SQLs
51
- (120 Snow-native + 162 Lite-mapped; the 256-instance set is the subset whose Spider 2.0-Lite
52
- counterpart has public gold SQL, and is a strict subset of the 282-instance maximal set — flagged
53
- per row in `in_256_paper_set` of the case-by-case file). Instances whose gold SQL is
54
- leaderboard-held-out are excluded entirely rather than approximated.
55
 
56
- ## Evaluation-set files
57
-
58
- - `evaluation_set/*.csv` — compact viewer-friendly version: question, gold SQL, gold columns.
59
- - `full/*.json` — complete records. Spider/BIRD rows additionally carry the full schema,
60
- column/table meanings, PK/FK (declared + generated). Snow rows carry provenance
61
- (`gold_sql_source` lite/snow, `gold_sql_id`), canonical `DB.SCHEMA.TABLE.COLUMN` gold columns
62
- (shard families collapsed to `_*`), audit verdicts, and catalog sizes.
63
- - `full/SPIDER2_SNOW_README.md`, `full/SPIDER2_SNOW_VERIFICATION.md` — construction, audit
64
- and verification record of the Snow sets (why 282 is the public-gold maximum, set relationship
65
- 233 ⊂ 256 ⊂ 282, audit history).
66
-
67
- ## Label quality — headline numbers
68
-
69
- Referee: parse the **official** benchmark SQL with sqlglot (aliases expanded, sub-queries scoped,
70
- unqualified columns attributed via FROM/JOIN), schema-validate, then score **both** label sets with
71
- the identical script and conventions. All 2,568 Spider+BIRD dev queries parse with 0 failures.
72
-
73
- | | Spider: ours | Spider: KaSLA | BIRD: ours | BIRD: KaSLA |
74
- |---|---:|---:|---:|---:|
75
- | questions with a fully correct gold set | **1,030 (99.6 %)** | 758 (73.3 %) | **1,534 (100 %)** | 1,110 (72.4 %) |
76
- | gold columns faithful to the SQL | **99.86 %** | 90.00 % | **100.00 %** | 84.02 % |
77
- | ↳ labelled but not in the SQL | **4** | 316 | **0** | 1,278 |
78
- | ↳ in the SQL but not labelled | **0** | 42 | **0** | 178 |
79
- | JOIN-key completeness | **100 %** | 99.79 % | **100 %** | 98.00 % |
80
- | questions with an **empty** gold set | **0** | 42 (4.06 %) | **0** | 40 (2.61 %) |
81
-
82
- Where the two label sets disagree, ours is closer to the released SQL in **274/276** Spider and
83
- **424/424** BIRD questions; KaSLA's in **none** (2 ties). Our complete error list is 4 columns on
84
- Spider — all four traceable to defects in Spider's own `tables.json` PK declarations — and 0 on
85
- BIRD; both sides' errors are listed row-by-row in `comparison_with_kasla/*_label_errors.csv`.
86
-
87
- On Spider 2.0-Snow (no third-party labels exist) all **2,003** gold columns resolve against the
88
- official catalog with **0** invalid; a parser-only extractor drops to 54.3 % exact match
89
- (failure cases in `spider2_snow_parser_failures.csv`) and lexical name matching to precision
90
- 0.189 (`spider2_snow_lexical_baseline.csv`), which is what the schema-aware LLM extraction +
91
- mechanical catalog post-validation is for.
92
-
93
- ## Case-by-case comparison files
94
-
95
- | file | rows | content |
96
- |---|---:|---|
97
- | `comparison_with_kasla/{spider,bird}_dev_case_by_case.csv` | 1,034 / 1,534 | per question: both label sets, the SQL, the referee set, per-side verdict, wrong columns, written reason |
98
- | `comparison_with_kasla/{spider,bird}_dev_label_errors.csv` | 362 / 1,456 | one row per **wrong gold column** (either side) + category + explanation |
99
- | `comparison_with_kasla/spider2_snow_case_by_case.csv` | 282 | our gold, catalog check, parser-only output, name-matching output |
100
- | `comparison_with_kasla/spider2_snow_parser_failures.csv` | 1,049 | one row per column the parser-only extractor gets wrong |
101
- | `comparison_with_kasla/spider2_snow_lexical_baseline.csv` | 282 | per-instance breakdown of name-matching labelling |
102
- | `comparison_with_kasla/summary_statistics.csv` | 39 | every number above, machine-readable |
103
- | `comparison_with_kasla/gold_label_quality_comparison.xlsx` | — | all of the above as one workbook |
104
-
105
- Example:
106
-
107
- ```python
108
- import pandas as pd
109
- df = pd.read_csv("comparison_with_kasla/bird_dev_case_by_case.csv")
110
- df[df.kasla_verdict != "CORRECT"][["question", "gold_sql", "ours_columns",
111
- "kasla_columns", "kasla_error_explanation"]]
112
- ```
113
-
114
- ## Reproduction
115
-
116
- `scripts/` contains the full referee + comparison pipeline (`reproduce.sh`; needs `sqlglot`,
117
- `pandas`, `openpyxl`, ≈4 minutes on one CPU core). Inputs: the official Spider/BIRD dev releases,
118
- the released KaSLA data files, and the gold JSONs in `full/`.
 
2
  license: cc-by-4.0
3
  language:
4
  - en
 
 
5
  tags:
6
  - text-to-sql
7
  - schema-linking
8
+ pretty_name: GRAST-SL evaluation sets
9
  configs:
10
  - config_name: spider_dev
11
  data_files: evaluation_set/spider_dev.csv
 
13
  data_files: evaluation_set/bird_dev.csv
14
  - config_name: spider2_snow_256
15
  data_files: evaluation_set/spider2_snow_256.csv
16
+ - config_name: kasla_spider_case_by_case
17
  data_files: comparison_with_kasla/spider_dev_case_by_case.csv
18
+ - config_name: kasla_bird_case_by_case
19
  data_files: comparison_with_kasla/bird_dev_case_by_case.csv
20
+ - config_name: kasla_spider_label_errors
21
  data_files: comparison_with_kasla/spider_dev_label_errors.csv
22
+ - config_name: kasla_bird_label_errors
23
  data_files: comparison_with_kasla/bird_dev_label_errors.csv
24
  - config_name: spider2_snow_case_by_case
25
  data_files: comparison_with_kasla/spider2_snow_case_by_case.csv
 
 
 
 
26
  - config_name: summary_statistics
27
  data_files: comparison_with_kasla/summary_statistics.csv
28
  ---
29
 
30
+ # GRAST-SL evaluation sets
31
 
32
+ Audited schema-linking gold labels (gold *used columns* per question, derived from the released
33
+ gold SQL) for **Spider dev** (1,034), **BIRD dev** (1,534), and **Spider 2.0-Snow** (256
34
+ instances, 105 databases), plus the per-question comparison with the released KaSLA/CodeS labels.
35
 
36
+ - `evaluation_set/` — one row per question: question, gold SQL, gold columns.
37
+ - `comparison_with_kasla/` — per-question verdicts for both label sets, one row per wrong gold
38
+ column with the reason, and `summary_statistics.csv` with the aggregate numbers.
 
 
 
39
 
40
+ Gold columns faithful to the released SQL: **99.86 % (Spider) / 100.00 % (BIRD)** for our labels
41
+ vs 90.00 % / 84.02 % for KaSLA's; on the 700 disagreement questions ours is closer to the SQL in
42
+ 698, KaSLA's in 0. All 2,003 Spider 2.0-Snow gold columns validate against the official catalog
43
+ (0 invalid).
 
 
44
 
45
+ Code and reproduction: https://github.com/thanhdath/grast-sql
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
comparison_with_kasla/gold_label_quality_comparison.xlsx DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:daad64a392220e05e0fb6b95c96191bb34f8faabaa977f53eeeff1b9106a2794
3
- size 1051767
 
 
 
 
comparison_with_kasla/parser_control_spider.json DELETED
@@ -1,10 +0,0 @@
1
- {
2
- "n": 1034,
3
- "parse_failures": 0,
4
- "exact_set_match": 0.8017,
5
- "exact_set_match_excluding_count_star_convention": 0.8357,
6
- "n_count_star_convention_instances": 42,
7
- "micro_precision": 0.9466,
8
- "micro_recall": 0.9744,
9
- "micro_f1": 0.9603
10
- }
 
 
 
 
 
 
 
 
 
 
 
comparison_with_kasla/spider2_snow_lexical_baseline.csv DELETED
The diff for this file is too large to render. See raw diff
 
comparison_with_kasla/spider2_snow_parser_failures.csv DELETED
The diff for this file is too large to render. See raw diff
 
comparison_with_kasla/summary_spider2_snow.json DELETED
@@ -1,68 +0,0 @@
1
- {
2
- "n_instances": 282,
3
- "n_instances_256_subset": 256,
4
- "n_databases": 110,
5
- "n_databases_256": 105,
6
- "dialects": {
7
- "snowflake": 121,
8
- "bigquery": 147,
9
- "duckdb": 14
10
- },
11
- "gold_columns_total": 2003,
12
- "gold_columns_out_of_catalog": 0,
13
- "parser": {
14
- "subset": 40,
15
- "exact": 153,
16
- "differs": 82,
17
- "superset": 7
18
- },
19
- "parser_shard_normalized": {
20
- "differs": 74,
21
- "exact": 208
22
- },
23
- "parser_failure_classes": {
24
- "other_dialect_or_scope": 14,
25
- "shard_family_plus_column_error": 9,
26
- "nested_struct_unnest_variant": 35,
27
- "shard_family_node_naming": 55,
28
- "select_star_expansion": 13,
29
- "cte_or_alias_attribution": 3
30
- },
31
- "parser_micro": {
32
- "precision": 0.7259,
33
- "recall": 0.7654,
34
- "f1": 0.7451,
35
- "tp": 1533,
36
- "pred": 2112,
37
- "gold": 2003
38
- },
39
- "lexical_micro": {
40
- "precision": 0.1892,
41
- "recall": 0.7194,
42
- "f1": 0.2996,
43
- "tp": 1441,
44
- "pred": 7615,
45
- "gold": 2003
46
- },
47
- "catalog": {
48
- "schema_nodes": 4631,
49
- "columns": 151075,
50
- "physical_tables": 19368
51
- },
52
- "parser_exact_match_rate": 0.5426,
53
- "catalog_per_database": {
54
- "n_databases": 110,
55
- "schema_nodes_total": 1963,
56
- "physical_tables_total": 5976,
57
- "columns_total": 58378,
58
- "columns_median": 158,
59
- "columns_max": 6063
60
- },
61
- "parser_shard_normalized_exact_rate": 0.7376,
62
- "sql_complexity": {
63
- "median_chars": 1189,
64
- "median_lines": 39,
65
- "pct_with_cte": 75.2,
66
- "pct_dialect_construct": 41.1
67
- }
68
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
comparison_with_kasla/summary_spider_bird.json DELETED
@@ -1,171 +0,0 @@
1
- {
2
- "spider": {
3
- "dataset": "spider",
4
- "n_instances": 1034,
5
- "n_aligned_by_question_text": 1034,
6
- "parse_failures": 0,
7
- "per_set": {
8
- "ours": {
9
- "labelled_columns": 2891,
10
- "distinct_columns": 2891,
11
- "faithful_columns": 2887,
12
- "unfaithful_columns": 4,
13
- "missing_columns": 0,
14
- "empty_gold_instances": 0,
15
- "instances_with_extra": 4,
16
- "instances_with_missing": 0
17
- },
18
- "kasla": {
19
- "labelled_columns": 3161,
20
- "distinct_columns": 3161,
21
- "faithful_columns": 2845,
22
- "unfaithful_columns": 316,
23
- "missing_columns": 42,
24
- "empty_gold_instances": 42,
25
- "instances_with_extra": 234,
26
- "instances_with_missing": 42
27
- }
28
- },
29
- "error_categories": {
30
- "ours": {
31
- "unused_column_star_table": 2,
32
- "star_table_pk_not_declared": 2
33
- },
34
- "kasla": {
35
- "missing_referenced_column": 40,
36
- "empty_gold": 42,
37
- "phantom_table_name_collision": 286,
38
- "unused_column_in_used_table": 16,
39
- "unused_column_star_table": 14,
40
- "missing_join_key": 2
41
- }
42
- },
43
- "verdicts": {
44
- "ours": {
45
- "CORRECT": 1030,
46
- "WRONG_extra": 4
47
- },
48
- "kasla": {
49
- "UNEVALUABLE_EMPTY_GOLD": 42,
50
- "WRONG_extra": 232,
51
- "CORRECT": 758,
52
- "WRONG_extra_and_missing": 2
53
- }
54
- },
55
- "join_keys_total": 952,
56
- "join_keys_covered": {
57
- "ours": 952,
58
- "kasla": 950
59
- },
60
- "micro": {
61
- "ours": {
62
- "precision_vs_sql": 0.9986,
63
- "recall_vs_sql": 1.0,
64
- "f1_vs_sql": 0.9993,
65
- "tp_precision": 2887,
66
- "tp_recall": 2887,
67
- "pred": 2891,
68
- "gold": 2887
69
- },
70
- "kasla": {
71
- "precision_vs_sql": 0.9,
72
- "recall_vs_sql": 0.9855,
73
- "f1_vs_sql": 0.9408,
74
- "tp_precision": 2845,
75
- "tp_recall": 2845,
76
- "pred": 3161,
77
- "gold": 2887
78
- }
79
- },
80
- "parser_artefact_refs_dropped": 409,
81
- "closer_counts": {
82
- "ours": 274,
83
- "tie": 760
84
- },
85
- "n_disagree_instances": 276
86
- },
87
- "bird": {
88
- "dataset": "bird",
89
- "n_instances": 1534,
90
- "n_aligned_by_question_text": 1534,
91
- "parse_failures": 0,
92
- "per_set": {
93
- "ours": {
94
- "labelled_columns": 6897,
95
- "distinct_columns": 6897,
96
- "faithful_columns": 6897,
97
- "unfaithful_columns": 0,
98
- "missing_columns": 0,
99
- "empty_gold_instances": 0,
100
- "instances_with_extra": 0,
101
- "instances_with_missing": 0
102
- },
103
- "kasla": {
104
- "labelled_columns": 7997,
105
- "distinct_columns": 7997,
106
- "faithful_columns": 6719,
107
- "unfaithful_columns": 1278,
108
- "missing_columns": 178,
109
- "empty_gold_instances": 40,
110
- "instances_with_extra": 367,
111
- "instances_with_missing": 90
112
- }
113
- },
114
- "error_categories": {
115
- "ours": {},
116
- "kasla": {
117
- "phantom_table_name_collision": 1050,
118
- "missing_referenced_column": 123,
119
- "unused_column_in_used_table": 90,
120
- "phantom_table_token_match": 124,
121
- "missing_join_key": 55,
122
- "empty_gold": 40,
123
- "phantom_table": 11,
124
- "unused_column_star_table": 3
125
- }
126
- },
127
- "verdicts": {
128
- "ours": {
129
- "CORRECT": 1534
130
- },
131
- "kasla": {
132
- "CORRECT": 1110,
133
- "WRONG_extra": 334,
134
- "WRONG_extra_and_missing": 33,
135
- "WRONG_missing": 17,
136
- "UNEVALUABLE_EMPTY_GOLD": 40
137
- }
138
- },
139
- "join_keys_total": 2756,
140
- "join_keys_covered": {
141
- "ours": 2756,
142
- "kasla": 2701
143
- },
144
- "micro": {
145
- "ours": {
146
- "precision_vs_sql": 1.0,
147
- "recall_vs_sql": 1.0,
148
- "f1_vs_sql": 1.0,
149
- "tp_precision": 6897,
150
- "tp_recall": 6897,
151
- "pred": 6897,
152
- "gold": 6897
153
- },
154
- "kasla": {
155
- "precision_vs_sql": 0.8402,
156
- "recall_vs_sql": 0.9742,
157
- "f1_vs_sql": 0.9022,
158
- "tp_precision": 6719,
159
- "tp_recall": 6719,
160
- "pred": 7997,
161
- "gold": 6897
162
- }
163
- },
164
- "parser_artefact_refs_dropped": 103,
165
- "closer_counts": {
166
- "tie": 1110,
167
- "ours": 424
168
- },
169
- "n_disagree_instances": 424
170
- }
171
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
full/SPIDER2_SNOW_README.md DELETED
@@ -1,107 +0,0 @@
1
- # Spider 2.0-Snow — canonical GRAST-SL evaluation set
2
-
3
- Canonical, audited schema-linking evaluation set for Spider 2.0-Snow.
4
- This directory is the single source of truth; other copies (e.g.
5
- `grast-sql-public/data/spider2_snow_282_enriched.pkl`) are synced from here.
6
-
7
- ## Files
8
-
9
- | file | what it is |
10
- |---|---|
11
- | `spider2_snow_eval_gold.json` | **v3 (canonical, maximal)**: 282 instances with audited gold used-columns. `{"metadata": {...}, "data": [...]}`. Gold columns in canonical `DB.SCHEMA.TABLE.COLUMN` form (shard families collapsed to `_*`). Built 2026-06-14 via deterministic sqlglot extraction from public gold SQL + per-instance Sonnet audit (224 ok / 58 fixed / 0 validation errors). |
12
- | `spider2_snow_282_enriched.pkl` | **v3 runnable**: pickle list of **282** tuples `(question, networkx.DiGraph, gold_nodes, sample_id)` — the contract `evaluate_on_the_fly.py` / `reproduce.sh spider2` consume. Graphs are the deployed Stage-I top-M(500) pool graphs enriched with column/table meanings, generated PK/FK flags (+FK edges only for originally edge-less graphs), and sample values. Ordered identically to the gold JSON's `data` list. |
13
- | `spider2_snow_eval_gold_256.json` + `spider2_snow_256_enriched.pkl` | **v2 (paper-claimed set)**: the 256 instances whose spider2-lite counterpart has public gold SQL — the "lite transformed to snow" set the paper's "256 evaluable instances" text refers to. Strict subset of v3 (drops the 26 snow-only-gold instances). 162 golds audited from the lite SQL, 94 from the byte-exact snow rewrite of the same query. |
14
- | `spider2_snow_eval_gold_233fixed.json` + `spider2_snow_233fixed_enriched.pkl` | **v1 (fixed operational set)**: the 233 instances of the historical `data/spider2_lite_samples.json` (o4-mini-era gold) with gold REPLACED by the audited values; `old_used_columns` kept per entry for diffing (116/233 differ at table.column level). Strict subset of v2. |
15
- | `SHA256SUMS` | checksums of all data files. |
16
- | `VERIFICATION.md` | full 2026-08-11 audit report (3 independent audits + fixes). |
17
- | `legacy/eval_snow256.py` | stale scorer for an older 256-sample variant; kept for reference only. |
18
-
19
- Set relationship: **233-fixed ⊂ 256 ⊂ 282** (verified). All three share the same audited
20
- gold; they differ only in which instances are included.
21
-
22
- Load the pkl with the CPU shim (node attrs may contain torch tensors):
23
-
24
- ```python
25
- import io, pickle, torch
26
- old = torch.storage._load_from_bytes
27
- torch.storage._load_from_bytes = lambda b: torch.load(io.BytesIO(b), map_location="cpu")
28
- data = pickle.load(open("spider2_snow_282_enriched.pkl", "rb")) # 282 items
29
- torch.storage._load_from_bytes = old
30
- ```
31
-
32
- ## Why 282 is the maximum
33
-
34
- Spider 2.0-Snow has 547 instances, but gold SQL is public for only some
35
- (the rest are leaderboard-held-out). Public gold: 120 snow-native SQLs +
36
- 256 lite SQLs. Snow = Lite migrated to Snowflake with a direct id mapping
37
- (`sf_` + lite id; lite ids already starting `sf` map unchanged), so lite
38
- golds transfer. Union = 120 ∪ (256 lite-mapped, of which 94 overlap snow)
39
- = **282** — verified exactly maximal against `/home/datht/Spider2`
40
- (nothing with public gold is missing; every entry is backed by a public
41
- gold file byte-for-byte). On the 94 overlaps the native snow SQL is used.
42
-
43
- ## Known properties (not bugs)
44
-
45
- - **Stage-I coverage ceiling**: gold-tail coverage of the pool graphs is
46
- mean **0.9098**; 228/282 instances at 1.0, 46 partial, **8 at 0.0**
47
- (`sf_bq087/088/089/102/103/338/402/406`). **CORRECTED 2026-08-15:** these
48
- are NOT retrieval failures but a gold↔pool name-canonicalization mismatch —
49
- see §v4 below; the v4 pkls repair the mapping (zero-coverage 8→0). Rankers
50
- evaluated on the v3 pkl remain bounded by this ceiling; on v3, report it
51
- alongside results and consider excluding the 8 ids.
52
- - **Year-sharded BigQuery tables** (`GITHUB_REPOS_DATE` etc.): gold columns
53
- carry literal shard years (`2023_*`) while pool graphs collapse shards to
54
- `_*`, so a few instances (`sf_bq182/224/295`) have structurally partial
55
- gold-tail coverage.
56
- - **Identical graphs across db_ids**: `SQLITE_SAKILA`/`PAGILA` and the two
57
- `CENSUS_GALAXY__*_SAMPLE` dbs genuinely have identical (table, column)
58
- schemas in the official Spider2 resources — shared node sets are faithful,
59
- not a mis-assignment.
60
- - **Shard fan-out in gold_nodes**: on 4 Ethereum-blockchain instances one
61
- canonical gold column maps to up to 7 shard nodes by design.
62
- - Questions match the pre-2025-07-13 `spider2-snow.jsonl` (the vintage the
63
- pool and gold were built from), not the reworded `spider2-snow-0713` one.
64
-
65
- ## Provenance of the 2 recovered samples (280 → 282)
66
-
67
- The originally shipped pkl had 280 items: `sf_bq182` and `sf_bq363` were
68
- dropped because the Stage-I pool cached pre-audit question wording. They
69
- were recovered 2026-08-11 from the pool by sid (40, 205) with the audited
70
- gold question text, and enriched to parity with their same-db neighbors
71
- (meanings/PK/FK already saturated in the pool; sample values injected from
72
- Spider2 resource JSONs — final `similar_values` coverage 54%/96% vs 49%/96%
73
- for Mongo-enriched neighbors). See `VERIFICATION.md`.
74
-
75
- ## v4 (2026-08-15): repaired gold→pool mapping — full-N evaluation, zero exclusions
76
-
77
- The 8 "Stage-I zero-coverage" instances (`sf_bq087/088/089/102/103/338/402/406`) were **not**
78
- retrieval failures: their pools contain the correct DB and gold tables, but the audited gold
79
- uses a different shard-collapse convention than the pool node names (e.g. gold
80
- `CENSUSTRACT_*` vs pool `censustract_*_*yr`, gold `V_2_1_1_GENOMES_*` vs pool
81
- `v2_1_1_genomes__chrx`). Verified identical on the gte-modernbert-149m pool — no Stage-I
82
- checkpoint change fixes it; it is a name-canonicalization defect.
83
-
84
- `spider2_snow_{233fixed,256,282}_enriched_v4.pkl` = same tuples as v3 with `gold_nodes`
85
- re-resolved by the audited cascade in
86
- `experiments/pkfk_accuracy/36_fix_zero_coverage_mapping.py` (exact-suffix rule first; a
87
- canonicalized table match — alpha-token subset + digit-run check, boundary-safe — only for
88
- columns the exact rule missed; every relaxed mapping logged in
89
- `snow_gold_pool_mapping_v4.json`). 31/37 gold columns of the 8 instances were already in
90
- their pools; residual true misses: sf_bq087 3/4 cols, sf_bq089 3/6 cols.
91
-
92
- Result: zero-coverage 8→0; mean gold-coverage ceiling 233/256/282 = 0.9563/0.9556/0.9575
93
- (all ≥ 0.937), so macro R=0.937 is attainable at FULL N with no exclusions.
94
-
95
- Reference numbers (current_best ckpt, raw global-τ + table-aware Steiner, PYTHONHASHSEED=0,
96
- `experiments/pkfk_accuracy/37_build_v4_and_eval.py`):
97
-
98
- | set | N (full) | P@R0.937 | P@R0.90 | v3 (with exclusions) |
99
- |---|---|---|---|---|
100
- | 233fixed | 233 | 0.2455 | 0.2919 | 0.2548 @ N=228 |
101
- | 256 | 256 | **0.2451** | 0.2859 | 0.2537 @ N=248 |
102
- | 282 | 282 | 0.2590 | 0.3022 | 0.2715 @ N=274 |
103
-
104
- v4 P is ~0.9–1.3pp below v3 because the repaired instances are hard (two have partial
105
- ceilings) and holding macro-R at full N lowers the global τ (sel 55→61 cols). v3 pkls remain
106
- unchanged for comparability with all previously reported numbers; state N and version
107
- explicitly whenever quoting either.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
full/SPIDER2_SNOW_VERIFICATION.md DELETED
@@ -1,218 +0,0 @@
1
- # Verification report — Spider 2.0-Snow eval set (2026-08-11)
2
-
3
- Three independent audits (Sonnet sub-agents) + main-session fixes. Scope:
4
- `spider2_snow_eval_gold.json` (282) and `spider2_snow_282_enriched.pkl`
5
- (280 at audit time → 282 after repair).
6
-
7
- ## Audit A — gold JSON vs official Spider2 repo: PASS (all 5 checks)
8
-
9
- 1. **Ids/questions**: 282 unique instance_ids, all in `spider2-snow.jsonl`;
10
- question text is an exact string match to both snow `instruction` and
11
- (via id mapping) lite `question` for all 282. Id convention verified
12
- bijective over all 547: snow = `sf_`+lite unless lite id starts `sf`.
13
- 2. **SQL provenance**: `gold_sql` byte-for-byte equals the public gold file
14
- for all 282 (120 snow-native, 162 lite) — 0 diffs at any level.
15
- 3. **Maximality**: union of public snow gold (120) and lite-mapped gold
16
- (256 → 94 overlap) is exactly the file's 282 ids; 0 missing, 0 extra.
17
- All 94 overlaps use `gold_sql_source="snow"` consistently.
18
- 4. **Internal integrity**: n_gold_columns, column format (4+ dot parts),
19
- short-form consistency (as multisets — both lists independently sorted),
20
- db_id prefixes, dialect/source/audit-verdict breakdowns vs metadata:
21
- 0 mismatches anywhere; 0 empty/duplicate gold lists.
22
- 5. **Gold vs SQL**: every gold column leaf appears in its gold SQL
23
- (full 282 scan); 10-entry stratified sqlglot parse check across all
24
- dialect×source strata — all columns identifiable as Column nodes.
25
-
26
- Cosmetic note: 16 entries have `audit_verdict="fix"` with
27
- `auto_corrected=False` — manual-fix path, field semantics only.
28
-
29
- ## Audit B — enriched pkl: PASS (after resolving 2 flags)
30
-
31
- - Structure: well-typed 4-tuples, unique questions and sids.
32
- - Join: every item matches exactly one gold entry by normalized question;
33
- sid→instance_id mapping (`spider2_snow_547_sid2inst.json`) consistent for
34
- all items; the only unmatched gold entries were `sf_bq182`/`sf_bq363`
35
- (repaired, see below).
36
- - gold_nodes: all exist in their graph, no duplicates.
37
- - Graph sanity: 0 zero-node graphs, 0 NaN tensors; meanings 99.2% of
38
- nodes, table_meanings 100%, values 67%; 57 zero-edge graphs (dbs with no
39
- generated FKs — by design).
40
- - Flag 1 resolved — **identical node sets across different db_ids**
41
- (`SQLITE_SAKILA`≡`PAGILA`, 89 cols; two `CENSUS_GALAXY__*_SAMPLE`, 57
42
- cols): verified against `/home/datht/Spider2/spider2-snow/resource/`
43
- schemas — genuinely identical (table, column) sets in the source. Benign.
44
- - Flag 2 (informational) — Stage-I coverage ceiling: mean gold-tail
45
- coverage 0.9098; 46 partial; 8 instances at 0.0 (wrong-domain pool
46
- retrieval): `sf_bq087, sf_bq088, sf_bq089, sf_bq102, sf_bq103,
47
- sf_bq338, sf_bq402, sf_bq406`. Property of the deployed Stage-I
48
- retriever, faithfully preserved — not a data bug.
49
-
50
- ## Audit C + repair — the 2 dropped samples: RECOVERED
51
-
52
- - Root cause: pool cached pre-audit question wording (`sf_bq182`: "at
53
- least 100" vs corrected "at least 5" PullRequestEvents; `sf_bq363`:
54
- reworded quantile-grouping clause) → exact-match join failed.
55
- - Recovery: pool items sid 40/205 (identical node sets to what the original
56
- build would have used), gold question text, enrichment reproduced from
57
- on-disk sources (v5 dump `data/source_dumps/mongo_dumps/
58
- spider2_lite_samples_v5.json` + Spider2 resource JSON sample_rows; the
59
- original Mongo step was verified on same-db neighbors to be values-only
60
- for these dbs). Final values coverage 54.1%/95.6% ≈ neighbors' 49%/96%.
61
- - Gold alignment: `sf_bq363` 1.0; `sf_bq182` 0.4 — pre-existing year-shard
62
- `tail()` artifact, identical to its already-shipped siblings
63
- `sf_bq224` (0.4) / `sf_bq295` (0.667).
64
-
65
- ## Merge validation (final 282 pkl)
66
-
67
- 282 items ordered as the gold JSON; unique sids; every item joins to its
68
- gold entry; all gold_nodes present in graphs; coverage mean 0.9098,
69
- 228/282 full, 8 zero. Synced to
70
- `/home/datht/grast-sql-public/data/spider2_snow_282_enriched.pkl`
71
- (previous 280-item version recoverable via git in that repo).
72
-
73
- ## End-to-end evaluation of the 3 versions (2026-08-13)
74
-
75
- Canonical pipeline: frozen 547 enriched-nested embedding pool + GNN + single
76
- global-τ swept to macro recall target + table-aware Steiner (always on).
77
- Control gate PASSED: OLD gold (222) × current-best ckpt → P@R0.937 = 0.2606
78
- vs README reference 0.2603 (two independent harnesses agree). Note: the
79
- "paper ckpt 0.251" folklore is a goal-label in eval_macro.py's printout, not
80
- that checkpoint's score — its real OLD-gold number is 0.212–0.214, matching
81
- the script's own inline baseline comment.
82
-
83
- Ckpts: paper = hybrid_attnpost2_warm_l3_h2048/best_pr_auc_epoch_02.pt;
84
- current_best = stage3_gnn/all3-final-kdsoup__ALL3PASS/grast_all3_final_sLGA433.pt.
85
-
86
- Final numbers AFTER the 2026-08-13 schema-attribution fix (see section
87
- below; pre-fix numbers in scratch report.json history):
88
-
89
- | Version | Ckpt | N eval (excl.) | Ceiling | P@R0.937 | P@R0.90 |
90
- |---|---|---|---|---|---|
91
- | OLD gold 222 | paper | 222 | — | 0.2148 | 0.2435 |
92
- | OLD gold 222 | current_best | 222 | — | 0.2599 | 0.2979 |
93
- | 233fixed | paper | 228 (5) | 0.9591 | 0.2113 | 0.2398 |
94
- | 233fixed | current_best | 228 (5) | 0.9591 | 0.2548 | 0.2869 |
95
- | 256 | paper | 248 (8) | 0.9480 | 0.2071 | 0.2357 |
96
- | 256 | current_best | 248 (8) | 0.9480 | 0.2537 | 0.2804 |
97
- | 282 | paper | 274 (8) | 0.9514 | 0.2216 | 0.2559 |
98
- | 282 | current_best | 274 (8) | 0.9514 | 0.2715 | 0.2965 |
99
-
100
- (Excluded = gold∩pool empty; the 8 = the documented zero-coverage ids.
101
- Ceiling here = gold∩frozen-embedding-pool per sample — higher than the
102
- 0.9098 in the audit section, which was computed against the enriched pkl's
103
- own bundled graphs; different denominators, both correct.)
104
-
105
- Reading: ckpt ranking is stable across all gold revisions (current_best >
106
- paper everywhere); the audited sets score within ~1pp of the OLD gold, with
107
- 282 highest (0.2715@R0.937). The 256 (paper-claimed) set evaluates cleanly
108
- end-to-end: N=248 evaluated, P@R0.937 = 0.2537 (+Steiner, current_best).
109
-
110
- Note: the current pool file
111
- `data/spider2_snow_547_stage1pool_graphs_enrichednested.pkl` has grown for
112
- some sids since the shipped pkl was built (e.g. sid 531: 349 vs 440 nodes)
113
- — the enriched pkl is the frozen eval artifact; do not rebuild it from the
114
- current pool expecting bit-identity. Sids 40/205 were verified unaffected.
115
-
116
- ## Schema-attribution fix (2026-08-13)
117
-
118
- **Bug**: for a homonym-collision subset of instances, `gold_columns` SCHEMA
119
- segments named a schema that appears nowhere in that instance's `gold_sql`.
120
- Root cause: the original deterministic extraction matched candidate schema
121
- columns by (table, column) name only; when several same-DB schemas share
122
- identical table/column layouts, it could pick a schema never referenced by
123
- the query. Two homonym families were hit: **CRYPTO_\*** (7 near-identical
124
- blockchain schemas — `CRYPTO_BAND/BITCOIN/BITCOIN_CASH/DASH/ETHEREUM/
125
- ETHEREUM_CLASSIC/ZILLIQA` all ship `transactions`/`blocks`/`inputs`/
126
- `outputs`/`logs`/`token_transfers` tables with overlapping column names) and
127
- **WORLD_BANK_\*** (4 schemas — `WORLD_BANK_WDI/INTL_DEBT/INTL_EDUCATION/
128
- HEALTH_POPULATION` all ship a `COUNTRY_SUMMARY` table with `country_code`/
129
- `region`).
130
-
131
- **Method**: deterministic, whole-file scan of all 282 entries. For each
132
- entry, parsed `gold_sql` with sqlglot (dialect-aware: snowflake/bigquery/
133
- duckdb), extracted schema-qualified base-table references (CTE aliases
134
- excluded), and cross-checked every `gold_columns` SCHEMA segment against
135
- those references — with escape valves for two legitimate non-bug patterns
136
- that would otherwise false-positive: (a) Snowflake identifiers that can't
137
- start with a digit are prefixed with `_` (e.g. `_1000_GENOMES`), and (b) a
138
- single BigQuery dataset can fan out into several concretely-named Snowflake
139
- schemas that are not themselves independently real schemas (e.g.
140
- `san_francisco` → `SAN_FRANCISCO_SFPD_INCIDENTS` / `SAN_FRANCISCO_BIKESHARE`
141
- / ...; verified via the official Spider2 resource catalog, 7,860 table
142
- JSONs under `spider2-snow/resource/databases/`, that these two patterns are
143
- not the homonym-collision bug). Genuinely-flagged columns were reassigned to
144
- the single SQL-referenced schema whose catalog entry actually contains that
145
- (table, column) — ambiguous or catalog-unconfirmed cases would have been
146
- left as needs-review, but none occurred (0 needs-review). A spurious `_*`
147
- shard suffix on TABLE was collapsed to the literal table name when the
148
- corrected schema's table is verifiably not sharded (all touched CRYPTO/
149
- WORLD_BANK tables are single, non-sharded tables), and duplicate columns
150
- produced by the reassignment (e.g. the same real column previously present
151
- under two different wrong schemas) were deduped.
152
-
153
- **Result**: **10 of 282 entries changed** (53 of 2,006 gold columns
154
- reassigned; 0 needs-review): `sf_bq057, sf_bq068, sf_bq083, sf_bq093,
155
- sf_bq327, sf_bq334, sf_bq341, sf_bq398, sf_bq424, sf_bq444`. All 4
156
- originally-reported instances landed on the expected schema exactly as
157
- specified: `sf_bq093` → `CRYPTO_ETHEREUM_CLASSIC` only (15→12 cols after
158
- dedup); `sf_bq057`, `sf_bq334` → `CRYPTO_BITCOIN`; `sf_bq341` →
159
- `CRYPTO_ETHEREUM`. The scan additionally caught 6 more instances of the same
160
- class: `sf_bq068`→`CRYPTO_BITCOIN_CASH`, `sf_bq083`/`sf_bq444`→
161
- `CRYPTO_ETHEREUM`, and `sf_bq327`/`sf_bq398`/`sf_bq424`→
162
- `WORLD_BANK_INTL_DEBT` (2 `COUNTRY_SUMMARY` columns each; those 3 instances'
163
- other 4 columns, on `INTERNATIONAL_DEBT`/`international_debt`, were already
164
- correctly schema'd and untouched). Applied identically to
165
- `spider2_snow_eval_gold.json` (282), `spider2_snow_eval_gold_256.json`
166
- (256) and `spider2_snow_eval_gold_233fixed.json` (233fixed) — the same 10
167
- instance_ids in all three, `lite_instance_id`/`old_used_columns` preserved;
168
- all other 272/246/223 entries byte-identical (diffed against pre-fix
169
- backups). `gold_columns_per_instance.mean` moved 7.11→7.1 (282); metadata
170
- gained a `schema_attribution_fix` block with date, changed-id list and this
171
- note.
172
-
173
- **pkl `gold_nodes` regeneration**: for the same 10 instances (by sid, via
174
- `data/spider2_snow_547_sid2inst.json`), recomputed `gold_nodes` from the
175
- corrected `gold_columns` against each instance's already-bundled pool graph
176
- `G` (schema-aware match: node id's last 3 dot-segments taken as
177
- (schema, table, column), canon-compared case/underscore/shard-insensitively;
178
- falls back to (table, column)-only when a node id has fewer segments — e.g.
179
- the CRYPTO graphs use 3-segment `SCHEMA.table.column` ids with no DB/project
180
- prefix, the WORLD_BANK graphs use 4-segment `project.dataset.table.column`
181
- ids). This directly fixed the previously-documented over-matching: gold-tail
182
- lookups by (table, column) alone had pulled in nodes from every homonym
183
- schema in the graph, not just the correct one.
184
-
185
- | sid | instance | gold_nodes before → after | gold-tail coverage before → after |
186
- |---|---|---|---|
187
- | 114 | sf_bq057 | 25 → 7 | 1.0 → 1.0 |
188
- | 115 | sf_bq068 | 24 → 8 | 1.0 → 1.0 |
189
- | 102 | sf_bq083 | 11 → 3 | 1.0 → 1.0 |
190
- | 117 | sf_bq093 | 40 → 12 | 1.0 → 1.0 |
191
- | 112 | sf_bq334 | 22 → 6 | 1.0 → 1.0 |
192
- | 108 | sf_bq341 | 8 → 4 | 1.0 → 1.0 |
193
- | 109 | sf_bq444 | 14 → 6 | 1.0 → 1.0 |
194
- | 352 | sf_bq327 | 8 → 6 | 0.333 → 1.0 |
195
- | 342 | sf_bq398 | 8 → 6 | 0.333 → 1.0 |
196
- | 351 | sf_bq424 | 8 → 6 | 0.333 → 1.0 |
197
-
198
- For the CRYPTO instances, gold_nodes shrank (over-matched wrong-schema nodes
199
- removed) with coverage unchanged at 1.0 (the correct-schema nodes were
200
- already present in the over-matched set). For the 3 WORLD_BANK instances,
201
- coverage actually **rose** 0.333→1.0: the old (buggy) gold_nodes for these
202
- contained only `COUNTRY_SUMMARY` nodes (across all 4 wrong-and-right
203
- homonym schemas) and were entirely missing the `INTERNATIONAL_DEBT.
204
- international_debt` nodes for the other 4 gold columns — a second,
205
- independent gap in the original gold_nodes build that this whole-list
206
- recomputation also fixed as a byproduct. Identical results across all three
207
- pkls (`_282_enriched`, `_256_enriched`, `_233fixed_enriched`). Verified:
208
- same touched-10/untouched-N split in all three; every untouched item's
209
- `(question, sid, gold_nodes)` and full graph node/edge set are unchanged
210
- from the pre-fix pkl; every corrected gold column matched exactly one node
211
- (no residual multi-schema ambiguity); 0 needs-review.
212
-
213
- **Needs-review list**: empty (0 entries) — every flagged column resolved to
214
- exactly one catalog-confirmed SQL-referenced schema.
215
-
216
- **Sync**: `spider2_snow_282_enriched.pkl` copied (plain `cp`) to
217
- `/home/datht/grast-sql-public/data/spider2_snow_282_enriched.pkl`;
218
- `SHA256SUMS` regenerated for all 6 data files.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
full/bird_dev_gold_final.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:869252ccc36012b484809c4ac66146e8e1b7bcc3c3bc361415e4e3865e58b683
3
- size 38312141
 
 
 
 
full/spider2_snow_eval_gold_256.json DELETED
The diff for this file is too large to render. See raw diff
 
full/spider2_snow_eval_gold_282.json DELETED
The diff for this file is too large to render. See raw diff
 
full/spider_dev_gold_final.json DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:3714009b0391624b5a7c536f6ca79e21cc698313adfd6077ef160b385654f048
3
- size 10822085
 
 
 
 
scripts/build_spider2_snow.py DELETED
@@ -1,411 +0,0 @@
1
- """
2
- Spider 2.0-Snow gold-label quality evidence (no third-party labels exist for
3
- this benchmark, so this is a *validation* rather than a head-to-head):
4
-
5
- 1. per-instance record of our 282 audited gold label sets, with the released
6
- gold SQL, the database, the catalog size, and the schema-validity check;
7
- 2. what a strong PARSER-ONLY extractor (sqlglot, alias/CTE/UNNEST/FLATTEN
8
- aware) recovers from the same SQL, per instance and per column, with a
9
- mechanical classification of *why* it fails -- the reviewer question
10
- "why is an LLM needed when SQLGlot exists?";
11
- 3. what the lexical / name-matching labelling rule (the rule whose error
12
- signature we measured on Spider and BIRD) would produce on Snow schemas.
13
-
14
- Outputs (hf_dataset/data/):
15
- spider2_snow_case_by_case.csv
16
- spider2_snow_parser_failures.csv
17
- spider2_snow_lexical_baseline.csv
18
- summary_spider2_snow.json
19
- """
20
- import json
21
- import os
22
- import re
23
- import signal
24
- import sys
25
- from collections import Counter, defaultdict
26
-
27
- import pandas as pd
28
-
29
- HERE = os.path.dirname(os.path.abspath(__file__))
30
- sys.path.insert(0, HERE)
31
- from extractor import extract # noqa: E402 (the parser-only reference extractor)
32
-
33
- OUT = os.environ.get("OUT_DIR", os.path.join(HERE, "..", "data"))
34
- SNOW_GOLD_DIR = os.environ.get(
35
- "SNOW_GOLD_DIR",
36
- os.path.abspath(os.path.join(HERE, "..", "..", "..", "data", "eval",
37
- "spider2_snow_final_versions")))
38
- GOLD = os.path.join(SNOW_GOLD_DIR, "spider2_snow_eval_gold.json")
39
- GOLD256 = os.path.join(SNOW_GOLD_DIR, "spider2_snow_eval_gold_256.json")
40
- CATALOG = os.environ.get("SPIDER2_RESOURCE_DIR", "spider2_snow_resource/databases")
41
-
42
- JOIN = "; "
43
-
44
-
45
- class TimeoutErr(Exception):
46
- pass
47
-
48
-
49
- signal.signal(signal.SIGALRM, lambda *a: (_ for _ in ()).throw(TimeoutErr()))
50
-
51
-
52
- # --------------------------------------------------------------------------- #
53
- # schema catalog
54
- # --------------------------------------------------------------------------- #
55
- DIGITS_RE = re.compile(r"\d+")
56
-
57
-
58
- def family_key(table_name):
59
- """Group per-shard physical tables into one schema node by replacing every
60
- digit run with `#`: GA_SESSIONS_20160801 -> GA_SESSIONS_#,
61
- COUNTY_2007_1YR / COUNTY_2008_3YR -> COUNTY_#_#YR. Spider 2.0 exposes such
62
- a family as ONE node; the released gold labels write it `PREFIX_*`."""
63
- return DIGITS_RE.sub("#", table_name.upper())
64
-
65
-
66
- def load_catalog(db_id):
67
- """Returns (families, phys, n_physical_tables).
68
-
69
- families : {FAMILY_KEY: {col,...}} -- one entry per schema node (shard
70
- families merged), the granularity a labeller actually faces.
71
- phys : {PHYSICAL_TABLE_NAME: {col,...}} -- used to check that a gold
72
- label names a real catalog column (gold writes shard families as
73
- `PREFIX_*`, resolved here by prefix match).
74
- """
75
- families, phys = defaultdict(set), {}
76
- root = os.path.join(CATALOG, db_id)
77
- for dirpath, _, files in os.walk(root):
78
- for f in files:
79
- if not f.endswith(".json"):
80
- continue
81
- try:
82
- j = json.load(open(os.path.join(dirpath, f), encoding="utf-8"))
83
- except Exception:
84
- continue
85
- if "column_names" not in j:
86
- continue
87
- tname = (j.get("table_fullname") or j.get("table_name") or f[:-5]).split(".")[-1].upper()
88
- cols = {c.upper() for c in j["column_names"]}
89
- phys.setdefault(tname, set()).update(cols)
90
- families[family_key(tname)] |= cols
91
- return dict(families), phys, len(phys)
92
-
93
-
94
- def catalog_columns_for(node, phys):
95
- """Columns available under a gold table node, resolving `PREFIX_*` shard
96
- families against the physical catalog by prefix."""
97
- node = node.upper()
98
- if node in phys:
99
- return phys[node]
100
- if node.endswith("_*") or node.endswith("*"):
101
- pref = node.rstrip("*").rstrip("_")
102
- cols = set()
103
- for name, c in phys.items():
104
- if name == pref or name.startswith(pref + "_") or name.startswith(pref):
105
- cols |= c
106
- if cols:
107
- return cols
108
- # Node ids are canonicalised (digit runs separated by `_`, masked as `#`):
109
- # `PM25_DAILY_SUMMARY_2020` -> `pm_25_daily_summary_*`, `ICD10CODE` ->
110
- # `icd_10_code_*`, `GSOD2022` -> `gsod#2_*`. Match on the separator-free
111
- # form before declaring a gold column out-of-catalog.
112
- def squash(s):
113
- return re.sub(r"[_#*]", "", s).lower()
114
- sq = squash(node)
115
- cols = set()
116
- for name, c in phys.items():
117
- n = squash(name)
118
- if n == sq or n.startswith(sq) or sq.startswith(n):
119
- cols |= c
120
- return cols
121
-
122
-
123
- # --------------------------------------------------------------------------- #
124
- # mechanical evidence flags on the SQL text
125
- # --------------------------------------------------------------------------- #
126
- EVIDENCE = [
127
- ("wildcard_or_shard_table", re.compile(r"`[^`]*\*[^`]*`|\.[A-Za-z0-9_]*\*(?!\w)|_TABLE_SUFFIX", re.I)),
128
- ("literal_year_shard_table", re.compile(r"[`.\"][A-Za-z0-9_]*_(19|20)\d{2}(_\d{2})?(_\*)?[`.\"\s]", re.I)),
129
- ("unnest_or_flatten", re.compile(r"\bUNNEST\s*\(|\bFLATTEN\s*\(", re.I)),
130
- ("struct_or_variant_access", re.compile(r'["\w\]\)]\s*:\s*["\w]|\bSTRUCT\s*<|\bSTRUCT\s*\(', re.I)),
131
- ("select_star", re.compile(r"SELECT\s+(DISTINCT\s+)?\*|\.\*", re.I)),
132
- ("select_star_except", re.compile(r"SELECT\s+\*\s+EXCEPT", re.I)),
133
- ("cte", re.compile(r"\bWITH\b[\s\S]{0,200}?\bAS\s*\(", re.I)),
134
- ("declare_script", re.compile(r"^\s*DECLARE\b", re.I | re.M)),
135
- ("qualify", re.compile(r"\bQUALIFY\b", re.I)),
136
- ]
137
-
138
-
139
- def evidence_flags(sql):
140
- return [name for name, pat in EVIDENCE if pat.search(sql)]
141
-
142
-
143
- def squash_table(t):
144
- return re.sub(r"[_#*]", "", t.lower())
145
-
146
-
147
- def same_node(a, b):
148
- """Two table node names denote the same catalog node up to shard/canonical
149
- naming (`incidents_2016` ~ `incidents_*`, `_2023` ~ `2023_*`)."""
150
- sa, sb = squash_table(a), squash_table(b)
151
- return sa == sb or sa.startswith(sb) or sb.startswith(sa)
152
-
153
-
154
- def shard_normalized_diff(gold, pred):
155
- """Residual disagreement after allowing shard/canonical table-name variants."""
156
- def covered(x, other):
157
- tx, cx = x.split(".", 1)
158
- return any(cx == c and same_node(tx, t) for t, c in (y.split(".", 1) for y in other))
159
- missed = sorted(g for g in gold if not covered(g, pred))
160
- extra = sorted(p for p in pred if not covered(p, gold))
161
- return missed, extra
162
-
163
-
164
- def classify_parser_failure(missed, hallucinated, flags, sql, gold_tables, pred_tables):
165
- """Assign ONE mechanical failure class + a human-readable reason."""
166
- if not missed and not hallucinated:
167
- return ("shard_family_node_naming",
168
- "the parser recovers the right columns but names their table the way the SQL "
169
- "writes it (a literal shard such as `incidents_2016`, or `_2023`), while the "
170
- "catalog -- and therefore the schema graph a system is scored against -- "
171
- "represents the whole shard family as ONE node (`INCIDENTS_*`). Resolving the "
172
- "written name to the catalog node is catalog knowledge that is nowhere in the "
173
- "SQL text, so a parser-only label cannot even be scored.")
174
- if "unnest_or_flatten" in flags or "struct_or_variant_access" in flags:
175
- return ("nested_struct_unnest_variant",
176
- "the query reads nested STRUCT/VARIANT fields (UNNEST / LATERAL FLATTEN / `:` "
177
- "access). `a.b` inside such a query is syntactically indistinguishable from "
178
- "table `a`, column `b`; only the catalog reveals that `a` is a STRUCT column "
179
- "of the base table.")
180
- if "select_star_except" in flags or "select_star" in flags:
181
- return ("select_star_expansion",
182
- "the query pulls columns through `SELECT *` / `SELECT * EXCEPT(...)`, so the "
183
- "columns it really uses are only recoverable by expanding `*` against the "
184
- "table's real column list in the catalog.")
185
- if any("*" in t or re.search(r"\d", t) for t in gold_tables) and (missed or hallucinated):
186
- return ("shard_family_plus_column_error",
187
- "the query addresses a shard family (one catalog node standing for many "
188
- "physical per-day/per-year tables) AND the parser also gets the column set "
189
- "wrong; neither the node identity nor the missing columns are recoverable "
190
- "from the SQL text alone.")
191
- if hallucinated and not missed:
192
- return ("cte_or_alias_attribution",
193
- "the parser attributed columns to a CTE / derived-table / alias name instead of "
194
- "the underlying base table.")
195
- return ("other_dialect_or_scope",
196
- "residual dialect- or scope-specific resolution failure (see the missed/extra "
197
- "columns and the SQL).")
198
-
199
-
200
- # --------------------------------------------------------------------------- #
201
- def main():
202
- gold = json.load(open(GOLD, encoding="utf-8"))
203
- data = gold["data"]
204
- ids256 = {x["instance_id"] for x in json.load(open(GOLD256, encoding="utf-8"))["data"]}
205
-
206
- catalogs = {}
207
- rows, fail_rows, lex_rows = [], [], []
208
- stats = {
209
- "n_instances": len(data),
210
- "n_instances_256_subset": len(ids256),
211
- "n_databases": len({x["db_id"] for x in data}),
212
- "n_databases_256": len({x["db_id"] for x in data if x["instance_id"] in ids256}),
213
- "dialects": Counter(x["dialect"] for x in data),
214
- "gold_columns_total": 0,
215
- "gold_columns_out_of_catalog": 0,
216
- "parser": Counter(),
217
- "parser_shard_normalized": Counter(),
218
- "parser_failure_classes": Counter(),
219
- "parser_micro": Counter(),
220
- "lexical_micro": Counter(),
221
- "catalog": Counter(),
222
- }
223
-
224
- for x in data:
225
- db = x["db_id"]
226
- if db not in catalogs:
227
- catalogs[db] = load_catalog(db)
228
- families, phys, n_physical = catalogs[db]
229
- cat_lower = {t.lower(): {c.lower() for c in cols} for t, cols in families.items()}
230
- n_cat_cols = sum(len(v) for v in cat_lower.values())
231
- n_cat_tables = len(cat_lower)
232
-
233
- sql = x["gold_sql"]
234
- g_short = [c.lower() for c in x["gold_columns_short"]]
235
- gset = set(g_short)
236
- gold_tables = {c.split(".")[0] for c in gset}
237
-
238
- # ---- schema validity of our gold against the official catalog -------
239
- invalid = []
240
- for c in gset:
241
- t, col = c.split(".", 1)
242
- avail = {x.lower() for x in catalog_columns_for(t, phys)}
243
- if col not in avail:
244
- invalid.append(c)
245
- stats["gold_columns_total"] += len(gset)
246
- stats["gold_columns_out_of_catalog"] += len(invalid)
247
-
248
- # ---- parser-only extractor -----------------------------------------
249
- signal.alarm(20)
250
- try:
251
- r = extract(sql, x["dialect"])
252
- status = r["status"]
253
- pred = {p.lower() for p in r["predicted"]}
254
- except TimeoutErr:
255
- status, pred, r = "timeout", set(), {"unresolved": []}
256
- except Exception as e: # noqa: BLE001
257
- status, pred, r = f"exception:{type(e).__name__}", set(), {"unresolved": []}
258
- finally:
259
- signal.alarm(0)
260
-
261
- missed = sorted(gset - pred)
262
- halluc = sorted(pred - gset)
263
- if status != "ok":
264
- cmp_ = "parse_fail"
265
- elif pred == gset:
266
- cmp_ = "exact"
267
- elif pred < gset:
268
- cmp_ = "subset"
269
- elif gset < pred:
270
- cmp_ = "superset"
271
- else:
272
- cmp_ = "differs"
273
- stats["parser"][cmp_] += 1
274
- stats["parser_micro"]["tp"] += len(gset & pred)
275
- stats["parser_micro"]["pred"] += len(pred)
276
- stats["parser_micro"]["gold"] += len(gset)
277
-
278
- flags = evidence_flags(sql)
279
- n_missed, n_extra = shard_normalized_diff(gset, pred)
280
- norm_cmp = "exact" if (not n_missed and not n_extra) else "differs"
281
- if status == "ok":
282
- stats["parser_shard_normalized"][norm_cmp] += 1
283
- if cmp_ == "exact":
284
- fclass, freason = "", ""
285
- else:
286
- fclass, freason = classify_parser_failure(
287
- n_missed, n_extra, flags, sql, gold_tables, {p.split(".")[0] for p in pred})
288
- stats["parser_failure_classes"][fclass] += 1
289
- for c in missed:
290
- fail_rows.append({
291
- "instance_id": x["instance_id"], "db_id": db, "dialect": x["dialect"],
292
- "direction": "parser_MISSED_gold_column", "column": c,
293
- "failure_class": fclass, "why_the_parser_fails": freason,
294
- "question": " ".join(x["question"].split()),
295
- "gold_sql": " ".join(sql.split()),
296
- })
297
- for c in halluc:
298
- fail_rows.append({
299
- "instance_id": x["instance_id"], "db_id": db, "dialect": x["dialect"],
300
- "direction": "parser_INVENTED_column", "column": c,
301
- "failure_class": fclass, "why_the_parser_fails": freason,
302
- "question": " ".join(x["question"].split()),
303
- "gold_sql": " ".join(sql.split()),
304
- })
305
-
306
- # ---- lexical / name-matching labelling rule -------------------------
307
- toks = set(re.findall(r"[A-Za-z_][A-Za-z_0-9]*", sql.lower()))
308
- lex = {f"{t}.{c}" for t, cols in cat_lower.items() for c in cols if c in toks}
309
- ltp = len(lex & gset)
310
- lp = ltp / len(lex) if lex else 0.0
311
- lr = ltp / len(gset) if gset else 0.0
312
- stats["lexical_micro"]["tp"] += ltp
313
- stats["lexical_micro"]["pred"] += len(lex)
314
- stats["lexical_micro"]["gold"] += len(gset)
315
- stats["catalog"]["schema_nodes"] += n_cat_tables
316
- stats["catalog"]["columns"] += n_cat_cols
317
- stats["catalog"]["physical_tables"] += n_physical
318
-
319
- lex_rows.append({
320
- "instance_id": x["instance_id"], "db_id": db,
321
- "n_catalog_schema_nodes": n_cat_tables, "n_catalog_columns": n_cat_cols,
322
- "n_physical_tables": n_physical,
323
- "n_our_gold_columns": len(gset),
324
- "n_lexical_labels": len(lex),
325
- "lexical_precision_vs_our_gold": round(lp, 4),
326
- "lexical_recall_vs_our_gold": round(lr, 4),
327
- "lexical_false_positives": len(lex) - ltp,
328
- "example_false_positives": JOIN.join(sorted(lex - gset)[:10]),
329
- "question": " ".join(x["question"].split()),
330
- })
331
-
332
- pp = len(gset & pred) / len(pred) if pred else 0.0
333
- pr = len(gset & pred) / len(gset) if gset else 0.0
334
- rows.append({
335
- "instance_id": x["instance_id"],
336
- "in_256_paper_set": "yes" if x["instance_id"] in ids256 else "no",
337
- "db_id": db,
338
- "dialect": x["dialect"],
339
- "gold_sql_source": x["gold_sql_source"],
340
- "question": " ".join(x["question"].split()),
341
- "gold_sql": " ".join(sql.split()),
342
- "sql_chars": len(sql),
343
- "sql_lines": sql.count("\n") + 1,
344
- "sql_constructs": JOIN.join(flags),
345
- "n_catalog_tables": n_cat_tables,
346
- "n_catalog_columns": n_cat_cols,
347
- "our_gold_columns": JOIN.join(sorted(x["gold_columns_short"])),
348
- "our_gold_columns_canonical": JOIN.join(sorted(x["gold_columns"])),
349
- "n_our_gold_columns": len(gset),
350
- "our_gold_columns_out_of_catalog": JOIN.join(invalid),
351
- "parser_only_columns": JOIN.join(sorted(pred)),
352
- "n_parser_only_columns": len(pred),
353
- "parser_status": status,
354
- "parser_vs_our_gold": cmp_,
355
- "parser_missed_gold_columns": JOIN.join(missed),
356
- "parser_invented_columns": JOIN.join(halluc),
357
- "parser_precision": round(pp, 4),
358
- "parser_recall": round(pr, 4),
359
- "parser_vs_our_gold_shard_normalized": norm_cmp if status == "ok" else "parse_fail",
360
- "parser_missed_after_shard_normalization": JOIN.join(n_missed),
361
- "parser_invented_after_shard_normalization": JOIN.join(n_extra),
362
- "parser_failure_class": fclass,
363
- "why_the_parser_fails": freason,
364
- "n_lexical_labels": len(lex),
365
- "lexical_precision_vs_our_gold": round(lp, 4),
366
- "lexical_recall_vs_our_gold": round(lr, 4),
367
- })
368
-
369
- pd.DataFrame(rows).to_csv(os.path.join(OUT, "spider2_snow_case_by_case.csv"), index=False)
370
- pd.DataFrame(fail_rows).to_csv(os.path.join(OUT, "spider2_snow_parser_failures.csv"), index=False)
371
- pd.DataFrame(lex_rows).to_csv(os.path.join(OUT, "spider2_snow_lexical_baseline.csv"), index=False)
372
-
373
- for key in ("parser_micro", "lexical_micro"):
374
- m = stats[key]
375
- p = m["tp"] / m["pred"] if m["pred"] else 0.0
376
- r = m["tp"] / m["gold"] if m["gold"] else 0.0
377
- stats[key] = {"precision": round(p, 4), "recall": round(r, 4),
378
- "f1": round(2 * p * r / (p + r), 4) if (p + r) else 0.0,
379
- "tp": m["tp"], "pred": m["pred"], "gold": m["gold"]}
380
- stats["parser_exact_match_rate"] = round(stats["parser"]["exact"] / len(data), 4)
381
- per_db_cols = [sum(len(v) for v in n.values()) for n, _, _ in catalogs.values()]
382
- per_db_nodes = [len(n) for n, _, _ in catalogs.values()]
383
- per_db_phys = [p for _, _, p in catalogs.values()]
384
- stats["catalog_per_database"] = {
385
- "n_databases": len(catalogs),
386
- "schema_nodes_total": sum(per_db_nodes),
387
- "physical_tables_total": sum(per_db_phys),
388
- "columns_total": sum(per_db_cols),
389
- "columns_median": int(pd.Series(per_db_cols).median()),
390
- "columns_max": int(max(per_db_cols)),
391
- }
392
- stats["parser_shard_normalized_exact_rate"] = round(
393
- stats["parser_shard_normalized"]["exact"] / len(data), 4)
394
- for k in ("dialects", "parser", "parser_shard_normalized", "parser_failure_classes", "catalog"):
395
- stats[k] = dict(stats[k])
396
- stats["sql_complexity"] = {
397
- "median_chars": int(pd.Series([len(x["gold_sql"]) for x in data]).median()),
398
- "median_lines": int(pd.Series([x["gold_sql"].count("\n") + 1 for x in data]).median()),
399
- "pct_with_cte": round(100 * sum("cte" in evidence_flags(x["gold_sql"]) for x in data) / len(data), 1),
400
- "pct_dialect_construct": round(100 * sum(
401
- bool({"unnest_or_flatten", "struct_or_variant_access", "wildcard_or_shard_table",
402
- "qualify", "declare_script"} & set(evidence_flags(x["gold_sql"])))
403
- for x in data) / len(data), 1),
404
- }
405
- with open(os.path.join(HERE, "..", "summary_spider2_snow.json"), "w") as f:
406
- json.dump(stats, f, indent=1)
407
- print(json.dumps(stats, indent=1))
408
-
409
-
410
- if __name__ == "__main__":
411
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/build_spider_bird.py DELETED
@@ -1,450 +0,0 @@
1
- """
2
- Case-by-case comparison of schema-linking GOLD LABELS on Spider dev (1034) and
3
- BIRD dev (1534):
4
-
5
- OURS (LLM extraction from the released gold SQL + deterministic validation)
6
- vs
7
- KaSLA (== CodeS lexical/name-matching labels, kasla/data/*_dev_full.json)
8
-
9
- Referee: an INDEPENDENT deterministic sqlglot extractor (scripts/gold_from_sql.py)
10
- run on the OFFICIAL benchmark SQL (from the original Spider / BIRD dev release,
11
- not our copy). The same script, the same conventions and the same 1:1 question
12
- alignment are applied to both label sets, so any parser imperfection penalises
13
- both sides equally.
14
-
15
- Convention (stated in the paper): a label is FAITHFUL if
16
- (a) the fully alias-resolved SQL literally references (table, column), or
17
- (b) the query star-references the table (`SELECT *`, `SELECT t.*`, `COUNT(*)`)
18
- and the column is that table's declared PRIMARY KEY ("represent the table").
19
-
20
- Outputs (hf_dataset/data/):
21
- spider_dev_case_by_case.csv one row per dev question
22
- bird_dev_case_by_case.csv
23
- spider_dev_kasla_errors.csv one row per WRONG gold column (either side)
24
- bird_dev_kasla_errors.csv
25
- summary_spider_bird.json aggregate statistics for the README
26
- """
27
- import json
28
- import os
29
- import re
30
- import sys
31
- from collections import Counter, defaultdict
32
-
33
- import pandas as pd
34
- import sqlglot
35
- import sqlglot.expressions as exp
36
- from sqlglot.optimizer.qualify import qualify
37
-
38
- HERE = os.path.dirname(os.path.abspath(__file__))
39
- sys.path.insert(0, HERE)
40
- from schema_utils import load_official_schemas # noqa: E402
41
- from gold_from_sql import extract_refs # noqa: E402
42
-
43
- OUT = os.environ.get("OUT_DIR", os.path.join(HERE, "..", "data"))
44
-
45
- # Inputs. Third-party releases must be pointed at with environment variables;
46
- # our own gold labels default to their location inside this bundle.
47
- def _first_existing(*cands):
48
- for c in cands:
49
- if c and os.path.exists(c):
50
- return c
51
- return cands[-1]
52
-
53
-
54
- BUNDLE = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
55
- SPIDER_DEV_DIR = os.environ.get("SPIDER_DEV_DIR", "spider_dev")
56
- BIRD_DEV_DIR = os.environ.get("BIRD_DEV_DIR", "bird_dev")
57
- KASLA_DATA_DIR = os.environ.get("KASLA_DATA_DIR", "kasla_data")
58
- OUR_GOLD_DIR = os.environ.get("OUR_GOLD_DIR",
59
- os.path.join(BUNDLE, "data", "eval", "gold_labels"))
60
-
61
-
62
- def _our_gold(ds, fn):
63
- return _first_existing(os.path.join(OUR_GOLD_DIR, ds, fn), os.path.join(OUR_GOLD_DIR, fn))
64
-
65
-
66
- CFG = {
67
- "spider": {
68
- "tables": f"{SPIDER_DEV_DIR}/tables.json",
69
- "official_dev": f"{SPIDER_DEV_DIR}/dev.json",
70
- "sql_field": "query",
71
- "ours": _our_gold("spider", "spider_dev_gold_final.json"),
72
- "kasla": f"{KASLA_DATA_DIR}/spider_dev_full.json",
73
- },
74
- "bird": {
75
- "tables": f"{BIRD_DEV_DIR}/dev_tables.json",
76
- "official_dev": f"{BIRD_DEV_DIR}/dev.json",
77
- "sql_field": "SQL",
78
- "ours": _our_gold("bird", "bird_dev_gold_final.json"),
79
- "kasla": f"{KASLA_DATA_DIR}/bird_dev_full.json",
80
- },
81
- }
82
-
83
- JOIN = "; "
84
-
85
-
86
- def fmt(cols):
87
- return JOIN.join(f"{t}.{c}" for t, c in sorted(cols))
88
-
89
-
90
- # --------------------------------------------------------------------------- #
91
- # SQL structure helpers
92
- # --------------------------------------------------------------------------- #
93
- def parse_structure(sql, sqlglot_schema, dialect="sqlite"):
94
- """Return (tables_in_sql, join_on_keys, ok).
95
-
96
- tables_in_sql : real base-table names (lower) appearing in any FROM/JOIN
97
- join_on_keys : (table, col) pairs on either side of a JOIN ... ON equality
98
- """
99
- try:
100
- tree = sqlglot.parse_one(sql, read=dialect)
101
- q = qualify(tree, schema=sqlglot_schema, dialect=dialect,
102
- validate_qualify_columns=False, expand_stars=False,
103
- infer_schema=True)
104
- except Exception:
105
- return set(), set(), False
106
-
107
- own_alias_map = {}
108
- for sel in q.find_all(exp.Select):
109
- m = {}
110
- for t in sel.find_all(exp.Table):
111
- if t.find_ancestor(exp.Select) is sel:
112
- m[(t.alias or t.name).lower()] = t.name.lower()
113
- own_alias_map[sel] = m
114
-
115
- tables = set()
116
- for m in own_alias_map.values():
117
- tables |= set(m.values())
118
-
119
- def resolve(sel, alias):
120
- node = sel
121
- while node is not None:
122
- if alias in own_alias_map.get(node, {}):
123
- return own_alias_map[node][alias]
124
- node = node.find_ancestor(exp.Select)
125
- return None
126
-
127
- keys = set()
128
- for sel in q.find_all(exp.Select):
129
- for j in sel.find_all(exp.Join):
130
- if j.find_ancestor(exp.Select) is not sel:
131
- continue
132
- on = j.args.get("on")
133
- if on is None:
134
- continue
135
- for eq in on.find_all(exp.EQ):
136
- l, r = eq.this, eq.expression
137
- if isinstance(l, exp.Column) and isinstance(r, exp.Column):
138
- lt = resolve(sel, (l.table or "").lower())
139
- rt = resolve(sel, (r.table or "").lower())
140
- if lt and rt:
141
- keys.add((lt, l.name.lower()))
142
- keys.add((rt, r.name.lower()))
143
- return tables, keys, True
144
-
145
-
146
- def name_tokens(sql):
147
- return set(re.findall(r"[A-Za-z_][A-Za-z_0-9]*", sql.lower()))
148
-
149
-
150
- # --------------------------------------------------------------------------- #
151
- # label readers
152
- # --------------------------------------------------------------------------- #
153
- def kasla_cols(entry):
154
- tnames = [t["table_name"] for t in entry["schema"]["schema_items"]]
155
- cnames = [t["column_names"] for t in entry["schema"]["schema_items"]]
156
- out = []
157
- for ti, _ in enumerate(entry["table_labels"]):
158
- for ci, lab in enumerate(entry["column_labels"][ti]):
159
- if lab == 1:
160
- out.append((tnames[ti].lower(), cnames[ti][ci].lower()))
161
- return out
162
-
163
-
164
- def our_cols(entry):
165
- out = []
166
- for c in entry["used_columns"]:
167
- t, col = c.split(".", 1)
168
- out.append((t.lower(), col.lower()))
169
- return out
170
-
171
-
172
- # --------------------------------------------------------------------------- #
173
- # per-column adjudication
174
- # --------------------------------------------------------------------------- #
175
- def classify_extra(tbl, col, sch, tables_in_sql, refs, star_tables, sql, sql_lower_tokens):
176
- """Classify a labelled column that the SQL does NOT justify.
177
-
178
- Returns (category, explanation) or (None, None) if it is in fact excusable.
179
- """
180
- in_schema = tbl in sch["col_by_table_lower"] and col in sch["col_by_table_lower"][tbl]
181
- if not in_schema:
182
- return ("not_in_schema",
183
- f"`{tbl}.{col}` is not a column of database schema `{tbl}` "
184
- f"(label cannot be scored).")
185
-
186
- tables_str = ", ".join(sorted(tables_in_sql)) or "(none)"
187
- if tbl not in tables_in_sql:
188
- # the classic lexical name-match failure
189
- other = sorted({t for (t, c) in refs if c == col and t != tbl})
190
- if other:
191
- return ("phantom_table_name_collision",
192
- f"labels `{tbl}.{col}`, but table `{tbl}` never appears in the "
193
- f"SQL (tables used: {tables_str}). The column name `{col}` occurs "
194
- f"in the SQL only through {', '.join('`%s.%s`' % (t, col) for t in other)} "
195
- f"-> label produced by name matching across an un-queried table.")
196
- if col in sql_lower_tokens:
197
- return ("phantom_table_token_match",
198
- f"labels `{tbl}.{col}`, but table `{tbl}` never appears in the SQL "
199
- f"(tables used: {tables_str}); the token `{col}` occurs in the SQL "
200
- f"text only as a literal/alias/function argument, not as a column of `{tbl}`.")
201
- return ("phantom_table",
202
- f"labels `{tbl}.{col}`, but table `{tbl}` never appears in the SQL "
203
- f"(tables used: {tables_str}) and the SQL never mentions `{col}`.")
204
-
205
- if tbl in star_tables:
206
- pks = sorted(sch["pk_cols_lower"].get(tbl, set()))
207
- if not pks:
208
- return ("star_table_pk_not_declared",
209
- f"labels `{tbl}.{col}` to represent the star-referenced table `{tbl}` "
210
- f"(`SELECT *`/`COUNT(*)`), but `{tbl}` declares NO primary key in the "
211
- f"benchmark's own tables.json, so the referee cannot confirm the choice "
212
- f"(benchmark metadata defect, not a label defect).")
213
- return ("unused_column_star_table",
214
- f"labels `{tbl}.{col}`; `{tbl}` is star-referenced (`SELECT *`/`COUNT(*)`) "
215
- f"so only its primary key ({', '.join(pks)}) represents it, and `{col}` is "
216
- f"never referenced explicitly.")
217
- return ("unused_column_in_used_table",
218
- f"labels `{tbl}.{col}`; table `{tbl}` IS used by the SQL but the column "
219
- f"`{col}` is never referenced anywhere in it.")
220
-
221
-
222
- def classify_missing(tbl, col, join_keys):
223
- if (tbl, col) in join_keys:
224
- return ("missing_join_key",
225
- f"omits `{tbl}.{col}`, which the SQL uses as a JOIN ... ON key "
226
- f"(a system that fails to retrieve it cannot reproduce the join).")
227
- return ("missing_referenced_column",
228
- f"omits `{tbl}.{col}`, which the SQL explicitly references.")
229
-
230
-
231
- # --------------------------------------------------------------------------- #
232
- def run(ds):
233
- cfg = CFG[ds]
234
- schemas = load_official_schemas(cfg["tables"])
235
- ours = json.load(open(cfg["ours"], encoding="utf-8"))
236
- kasla = json.load(open(cfg["kasla"], encoding="utf-8"))
237
- official = json.load(open(cfg["official_dev"], encoding="utf-8"))
238
- assert len(ours) == len(kasla) == len(official), (len(ours), len(kasla), len(official))
239
-
240
- rows, err_rows = [], []
241
- stats = {
242
- "dataset": ds,
243
- "n_instances": len(ours),
244
- "n_aligned_by_question_text": 0,
245
- "parse_failures": 0,
246
- "per_set": {s: Counter() for s in ("ours", "kasla")},
247
- "error_categories": {s: Counter() for s in ("ours", "kasla")},
248
- "verdicts": {s: Counter() for s in ("ours", "kasla")},
249
- "join_keys_total": 0,
250
- "join_keys_covered": {"ours": 0, "kasla": 0},
251
- "micro": {s: Counter() for s in ("ours", "kasla")},
252
- }
253
-
254
- for i in range(len(ours)):
255
- e, k, o = ours[i], kasla[i], official[i]
256
- db = e["db_id"]
257
- sql = o[cfg["sql_field"]]
258
- sch = schemas[db]
259
- aligned = e["question"].strip() == o["question"].strip()
260
- stats["n_aligned_by_question_text"] += int(aligned)
261
-
262
- refs, star_tables, ok, err = extract_refs(sql, sch["sqlglot_schema"])
263
- tables_in_sql, join_keys, ok2 = parse_structure(sql, sch["sqlglot_schema"])
264
- if not (ok and ok2):
265
- stats["parse_failures"] += 1
266
- continue
267
- toks = name_tokens(sql)
268
-
269
- # Schema-validate the parser output. Spider/BIRD gold SQL quotes string
270
- # literals with double quotes (`WHERE Airline = "JetBlue Airways"`),
271
- # which ANSI SQL -- and therefore sqlglot -- reads as an IDENTIFIER.
272
- # Anything the parser resolves to a name that is not a real column of
273
- # that table is a parser artefact and is dropped before adjudication.
274
- def valid(tc):
275
- t, c = tc
276
- return c in sch["col_by_table_lower"].get(t, [])
277
- n_before = len(refs)
278
- refs = {tc for tc in refs if valid(tc)}
279
- join_keys = {tc for tc in join_keys if valid(tc)}
280
- stats.setdefault("parser_artefact_refs_dropped", 0)
281
- stats["parser_artefact_refs_dropped"] += n_before - len(refs)
282
-
283
- # Reference answer key derived purely from the SQL.
284
- # REQUIRED : every literally referenced column, plus -- for a table
285
- # the query only star-references (`SELECT *`, `COUNT(*)`)
286
- # and that is otherwise unrepresented -- its declared PK.
287
- # ALLOWED : REQUIRED plus the declared PK of ANY star-referenced
288
- # table (labelling it is legitimate but not obligatory).
289
- # Precision is judged against ALLOWED, recall against REQUIRED, so the
290
- # star convention can never penalise either label set.
291
- refs_tables = {t for (t, _) in refs}
292
- required = set(refs)
293
- allowed = set(refs)
294
- for t in star_tables:
295
- pks = sch["pk_cols_lower"].get(t, set())
296
- allowed |= {(t, pk) for pk in pks}
297
- if t not in refs_tables:
298
- required |= {(t, pk) for pk in pks}
299
- sql_truth = required
300
-
301
- labels = {"ours": our_cols(e), "kasla": kasla_cols(k)}
302
- rec = {
303
- "dataset": ds,
304
- "idx": i,
305
- "question_id": o.get("question_id", i),
306
- "db_id": db,
307
- "question": e["question"].replace("\n", " ").strip(),
308
- "gold_sql": " ".join(sql.split()),
309
- "n_schema_columns": sum(len(v) for v in sch["col_by_table_lower"].values()),
310
- "tables_used_by_sql": "; ".join(sorted(tables_in_sql)),
311
- "sql_reference_columns": fmt(required),
312
- "n_sql_reference_columns": len(required),
313
- "sql_optional_pk_columns": fmt(allowed - required),
314
- }
315
-
316
- per = {}
317
- for s in ("ours", "kasla"):
318
- raw = labels[s]
319
- st = set(raw)
320
- extra_bad, extra_expl, cats = [], [], []
321
- for (t, c) in sorted(st - allowed):
322
- cat, expl = classify_extra(t, c, sch, tables_in_sql, refs, star_tables, sql, toks)
323
- if cat is None:
324
- continue
325
- extra_bad.append(f"{t}.{c}")
326
- extra_expl.append(f"[{cat}] {expl}")
327
- cats.append(cat)
328
- err_rows.append({
329
- "dataset": ds, "idx": i, "question_id": o.get("question_id", i),
330
- "db_id": db, "label_set": s, "error_side": "extra_column",
331
- "column": f"{t}.{c}", "error_category": cat,
332
- "explanation": expl,
333
- "question": e["question"].replace("\n", " ").strip(),
334
- "gold_sql": " ".join(sql.split()),
335
- })
336
- miss, miss_expl = [], []
337
- for (t, c) in sorted(sql_truth - st):
338
- cat, expl = classify_missing(t, c, join_keys)
339
- miss.append(f"{t}.{c}")
340
- miss_expl.append(f"[{cat}] {expl}")
341
- cats.append(cat)
342
- err_rows.append({
343
- "dataset": ds, "idx": i, "question_id": o.get("question_id", i),
344
- "db_id": db, "label_set": s, "error_side": "missing_column",
345
- "column": f"{t}.{c}", "error_category": cat,
346
- "explanation": expl,
347
- "question": e["question"].replace("\n", " ").strip(),
348
- "gold_sql": " ".join(sql.split()),
349
- })
350
-
351
- if len(st) == 0:
352
- verdict = "UNEVALUABLE_EMPTY_GOLD"
353
- cats.append("empty_gold")
354
- elif not extra_bad and not miss:
355
- verdict = "CORRECT"
356
- elif extra_bad and miss:
357
- verdict = "WRONG_extra_and_missing"
358
- elif extra_bad:
359
- verdict = "WRONG_extra"
360
- else:
361
- verdict = "WRONG_missing"
362
-
363
- tp_p = len(st & allowed)
364
- tp_r = len(st & required)
365
- p = tp_p / len(st) if st else 0.0
366
- r = tp_r / len(required) if required else 1.0
367
- f1 = 2 * p * r / (p + r) if (p + r) else 0.0
368
-
369
- per[s] = dict(cols=fmt(st), n=len(st), extra=extra_bad, miss=miss,
370
- expl=extra_expl + miss_expl, cats=cats, verdict=verdict, f1=f1)
371
-
372
- ps = stats["per_set"][s]
373
- ps["labelled_columns"] += len(raw)
374
- ps["distinct_columns"] += len(st)
375
- ps["faithful_columns"] += len(st) - len(extra_bad)
376
- ps["unfaithful_columns"] += len(extra_bad)
377
- ps["missing_columns"] += len(miss)
378
- ps["empty_gold_instances"] += int(len(st) == 0)
379
- ps["instances_with_extra"] += int(bool(extra_bad))
380
- ps["instances_with_missing"] += int(bool(miss))
381
- stats["error_categories"][s].update(cats)
382
- stats["verdicts"][s][verdict] += 1
383
- m = stats["micro"][s]
384
- m["tp_precision"] += tp_p
385
- m["tp_recall"] += tp_r
386
- m["pred"] += len(st)
387
- m["gold"] += len(required)
388
- stats["join_keys_covered"][s] += len(join_keys & st)
389
-
390
- stats["join_keys_total"] += len(join_keys)
391
-
392
- rec.update({
393
- "ours_columns": per["ours"]["cols"],
394
- "n_ours_columns": per["ours"]["n"],
395
- "kasla_columns": per["kasla"]["cols"],
396
- "n_kasla_columns": per["kasla"]["n"],
397
- "ours_only": fmt(set(labels["ours"]) - set(labels["kasla"])),
398
- "kasla_only": fmt(set(labels["kasla"]) - set(labels["ours"])),
399
- "agree": "yes" if set(labels["ours"]) == set(labels["kasla"]) else "no",
400
- "ours_verdict": per["ours"]["verdict"],
401
- "kasla_verdict": per["kasla"]["verdict"],
402
- "ours_wrong_extra_columns": JOIN.join(per["ours"]["extra"]),
403
- "kasla_wrong_extra_columns": JOIN.join(per["kasla"]["extra"]),
404
- "ours_missing_columns": JOIN.join(per["ours"]["miss"]),
405
- "kasla_missing_columns": JOIN.join(per["kasla"]["miss"]),
406
- "kasla_error_categories": JOIN.join(sorted(set(per["kasla"]["cats"]))),
407
- "kasla_error_explanation": " | ".join(per["kasla"]["expl"]),
408
- "ours_error_categories": JOIN.join(sorted(set(per["ours"]["cats"]))),
409
- "ours_error_explanation": " | ".join(per["ours"]["expl"]),
410
- "ours_f1_vs_sql": round(per["ours"]["f1"], 4),
411
- "kasla_f1_vs_sql": round(per["kasla"]["f1"], 4),
412
- "closer_to_sql": ("tie" if abs(per["ours"]["f1"] - per["kasla"]["f1"]) < 1e-9
413
- else ("ours" if per["ours"]["f1"] > per["kasla"]["f1"] else "kasla")),
414
- "question_text_aligned": "yes" if aligned else "no",
415
- })
416
- rows.append(rec)
417
-
418
- df = pd.DataFrame(rows)
419
- df.to_csv(os.path.join(OUT, f"{ds}_dev_case_by_case.csv"), index=False)
420
- edf = pd.DataFrame(err_rows)
421
- edf.to_csv(os.path.join(OUT, f"{ds}_dev_label_errors.csv"), index=False)
422
-
423
- stats["closer_counts"] = dict(Counter(r["closer_to_sql"] for r in rows))
424
- stats["n_disagree_instances"] = int(sum(1 for r in rows if r["agree"] == "no"))
425
- for s in ("ours", "kasla"):
426
- m = stats["micro"][s]
427
- p = m["tp_precision"] / m["pred"] if m["pred"] else 0.0
428
- r = m["tp_recall"] / m["gold"] if m["gold"] else 0.0
429
- stats["micro"][s] = {
430
- "precision_vs_sql": round(p, 4), "recall_vs_sql": round(r, 4),
431
- "f1_vs_sql": round(2 * p * r / (p + r), 4) if (p + r) else 0.0,
432
- "tp_precision": m["tp_precision"], "tp_recall": m["tp_recall"],
433
- "pred": m["pred"], "gold": m["gold"],
434
- }
435
- stats["per_set"][s] = dict(stats["per_set"][s])
436
- stats["error_categories"][s] = dict(stats["error_categories"][s])
437
- stats["verdicts"][s] = dict(stats["verdicts"][s])
438
- return stats, df, edf
439
-
440
-
441
- if __name__ == "__main__":
442
- allstats = {}
443
- for ds in ("spider", "bird"):
444
- st, df, edf = run(ds)
445
- allstats[ds] = st
446
- print(f"=== {ds}: {len(df)} rows, {len(edf)} error rows")
447
- print(json.dumps({k: v for k, v in st.items() if k != "diff"}, indent=1)[:3000])
448
- with open(os.path.join(HERE, "..", "summary_spider_bird.json"), "w") as f:
449
- json.dump(allstats, f, indent=1)
450
- print("saved summary_spider_bird.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/extractor.py DELETED
@@ -1,414 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Standalone sqlglot-based lineage/used-column extractor.
4
- No external DB schema is consulted (pure parser + scope resolution only) --
5
- this is the "best-effort deterministic parser baseline" the ICDE rebuttal
6
- compares against LLM-based extraction.
7
-
8
- Design (see accompanying notes):
9
- - Uses sqlglot.optimizer.scope.build_scope for CTE / subquery / union / UDTF
10
- (UNNEST, LATERAL FLATTEN) scope resolution (no external schema needed).
11
- - For a Column node, resolves its immediate qualifier against the scope's
12
- registered sources. If the source is a real base Table -> emit
13
- (table_name, field). If it's a derived/CTE/subquery Scope -> recurse by
14
- matching the requested output name against that scope's SELECT list
15
- (also recursing through UNION branches). If it's a UDTF scope (UNNEST(...)
16
- or LATERAL FLATTEN(...)) -> (heuristic) recursively resolve ALL column
17
- refs found *inside* the UDTF's own argument expression, ignoring the
18
- specific sub-field name asked for -- this mirrors what a human/LLM does
19
- when collapsing "hits.product.v2ProductName" back to the single
20
- top-level repeated/STRUCT column "hits", but is exactly the point where
21
- a schema-blind parser cannot tell how deep to stop, so we log every
22
- UDTF resolution as `used_udtf_heuristic=True` on the instance so we can
23
- separately audit whether the *heuristic* -- not just plain parsing --
24
- got the right answer.
25
- - Unqualified (bare) columns: resolved only when the enclosing scope has
26
- exactly one source, or when the bare name itself matches a registered
27
- UDTF-source alias (self-reference to the exploded value). Otherwise
28
- marked AMBIGUOUS_UNQUALIFIED (deliberately NOT guessed -- guessing was
29
- tried by the project's internal pipeline and produced false positives).
30
- - `SELECT *` / `t.*` anywhere in the scope tree cannot be expanded without
31
- a schema -> flagged as NEEDS_SCHEMA_STAR.
32
- - Multi-statement scripts (BigQuery DECLARE ... ; WITH ... SELECT ...;) are
33
- split with sqlglot.parse() and every query-shaped statement is unioned.
34
- """
35
- from __future__ import annotations
36
- import sys, re, json, traceback
37
- from dataclasses import dataclass, field as dc_field
38
-
39
- import sqlglot
40
- from sqlglot import exp
41
- from sqlglot.optimizer.scope import build_scope, Scope, ScopeType
42
-
43
- QUERY_TYPES = (exp.Select, exp.Union, exp.Except, exp.Intersect)
44
-
45
- UNRESOLVED_TAGS = {
46
- "AMBIGUOUS_UNQUALIFIED",
47
- "UNKNOWN_QUALIFIER",
48
- "NEEDS_SCHEMA_STAR",
49
- "UNRESOLVED_OUTPUT_NAME",
50
- "UNRESOLVED_STRUCTURE",
51
- "MAX_DEPTH",
52
- }
53
-
54
-
55
- class Unresolved:
56
- __slots__ = ("tag", "detail")
57
-
58
- def __init__(self, tag, detail=""):
59
- self.tag = tag
60
- self.detail = detail
61
-
62
- def key(self):
63
- return (self.tag, self.detail)
64
-
65
- def __repr__(self):
66
- return f"<{self.tag}:{self.detail}>"
67
-
68
-
69
- def _qual_parts(col: exp.Column):
70
- """Return ordered qualifier strings (catalog, db, table) that are actually set."""
71
- parts = []
72
- for k in ("catalog", "db", "table"):
73
- v = col.args.get(k)
74
- if v:
75
- parts.append(col.text(k) if hasattr(col, "text") else str(v))
76
- return parts
77
-
78
-
79
- def _find_source(scope: Scope, alias: str):
80
- """Search this scope and ancestor scopes (correlated refs) for `alias`.
81
- Case-insensitive: quoted Snowflake/BigQuery identifiers preserve case in
82
- sqlglot's source dict keys, but SQL identifier matching (outside a
83
- case-sensitive quoted *column* comparison, which we don't attempt either)
84
- should not depend on it here -- we only match alias tokens."""
85
- alias_lower = alias.lower()
86
- s = scope
87
- seen = 0
88
- while s is not None and seen < 50:
89
- for k, v in s.sources.items():
90
- if k.lower() == alias_lower:
91
- return v, s
92
- s = s.parent
93
- seen += 1
94
- return None, None
95
-
96
-
97
- def _collect_output_names(scope: Scope):
98
- """Schema-free: the set of output column names a (non-UDTF) Scope could
99
- produce, by reading its own SELECT list(s) (recursing through unions).
100
- Returns (names:set[str] lowercased, has_star:bool)."""
101
- names = set()
102
- has_star = [False]
103
-
104
- def rec(s):
105
- if s.union_scopes:
106
- for b in s.union_scopes:
107
- rec(b)
108
- return
109
- sel = s.expression
110
- if isinstance(sel, exp.Select):
111
- for e in sel.selects:
112
- on = e.output_name
113
- if on == "*":
114
- has_star[0] = True
115
- else:
116
- names.add(on.lower())
117
-
118
- rec(scope)
119
- return names, has_star[0]
120
-
121
-
122
- # BigQuery pseudo-columns: syntactically indistinguishable from a real bare
123
- # column reference, but never a schema column. Excluding these is still
124
- # "pure parsing" (fixed vocabulary of engine-reserved names, no DB access).
125
- BQ_PSEUDO_COLUMNS = {"_table_suffix", "_partitiontime", "_partitiondate", "_file_name", "_row_number"}
126
-
127
-
128
- class Extractor:
129
- def __init__(self, max_depth=40, script_vars=None):
130
- self.max_depth = max_depth
131
- self.udtf_heuristic_used = False
132
- self.star_used = False
133
- self.unresolved_examples = [] # list[Unresolved]
134
- self.script_vars = script_vars or set() # DECLARE'd variable names (lowercase)
135
- self.n_pseudocol_excluded = 0
136
-
137
- def _add_unresolved(self, u: Unresolved):
138
- if u.tag == "NEEDS_SCHEMA_STAR":
139
- self.star_used = True
140
- if len(self.unresolved_examples) < 200:
141
- self.unresolved_examples.append(u)
142
- return {u}
143
-
144
- def resolve_column(self, scope: Scope, col: exp.Column, depth=0):
145
- if depth > self.max_depth:
146
- return self._add_unresolved(Unresolved("MAX_DEPTH", col.sql()))
147
- parts = _qual_parts(col)
148
- name = col.name
149
- if not parts:
150
- return self.resolve_unqualified(scope, name, col, depth)
151
- # try leftmost qualifier first (struct-dot chains: alias.field1.field2...)
152
- alias = parts[0].lower()
153
- src, found_scope = _find_source(scope, alias)
154
- remaining_field = parts[1] if len(parts) >= 2 else name
155
- if src is None and len(parts) >= 2:
156
- # fallback: try the qualifier immediately left of the column name
157
- alias2 = parts[-1].lower()
158
- src, found_scope = _find_source(scope, alias2)
159
- remaining_field = name
160
- if src is None:
161
- return self._add_unresolved(
162
- Unresolved("UNKNOWN_QUALIFIER", f"{'.'.join(parts)}.{name}")
163
- )
164
- return self.resolve_source(found_scope, src, remaining_field, depth)
165
-
166
- def resolve_unqualified(self, scope: Scope, name: str, col: exp.Column, depth):
167
- nl = name.lower()
168
- if nl in BQ_PSEUDO_COLUMNS or nl in self.script_vars:
169
- self.n_pseudocol_excluded += 1
170
- return set()
171
- # (a) GROUP BY / HAVING / QUALIFY reference to an output alias of this
172
- # same scope -> not a base column at all.
173
- ancestor = col.find_ancestor(exp.Group, exp.Having, exp.Qualify)
174
- if ancestor is not None:
175
- sel = scope.expression
176
- if isinstance(sel, exp.Select):
177
- named = {n.lower() for n in sel.named_selects}
178
- if name.lower() in named:
179
- return set()
180
- # (b) bare name that is itself a registered source alias (self-ref to
181
- # an UNNEST/LATERAL-FLATTEN exploded value, e.g. `WHERE hits IS NOT NULL`)
182
- direct_src, direct_scope = _find_source(scope, name)
183
- if direct_src is not None and name.lower() in {k.lower() for k in scope.sources}:
184
- return self.resolve_source(scope, direct_src, None, depth)
185
- # (c) exactly one source in scope -> unambiguous
186
- if len(scope.sources) == 1:
187
- only_src = next(iter(scope.sources.values()))
188
- return self.resolve_source(scope, only_src, name, depth)
189
- # (c2) >1 sources, but only-parser-visible info (each derived/CTE
190
- # source's own SELECT-list output names, still schema-free) rules out
191
- # all but one candidate -- Table/UDTF sources are always "maybe"
192
- # since their real columns are unknown to us.
193
- candidates = []
194
- for alias, src in scope.sources.items():
195
- if isinstance(src, Scope) and src.scope_type != ScopeType.UDTF:
196
- names, has_star = _collect_output_names(src)
197
- if has_star or name.lower() in names:
198
- candidates.append((alias, src))
199
- else:
200
- candidates.append((alias, src))
201
- if len(candidates) == 1:
202
- return self.resolve_source(scope, candidates[0][1], name, depth)
203
- # (d) ambiguous / needs schema to disambiguate among >1 sources, or
204
- # zero sources (correlated ref we couldn't find) -> honest failure
205
- return self._add_unresolved(
206
- Unresolved(
207
- "AMBIGUOUS_UNQUALIFIED",
208
- f"{name} (n_sources={len(scope.sources)}, n_candidates={len(candidates)})",
209
- )
210
- )
211
-
212
- def resolve_source(self, scope: Scope, src, field, depth):
213
- if isinstance(src, exp.Table):
214
- base = src.name # last identifier, literal case & any '*' wildcard preserved
215
- if field is None:
216
- return self._add_unresolved(Unresolved("UNRESOLVED_STRUCTURE", f"bare table ref {base}"))
217
- return {(base, field)}
218
- if isinstance(src, Scope):
219
- if src.scope_type == ScopeType.UDTF:
220
- self.udtf_heuristic_used = True
221
- out = set()
222
- cols = list(src.columns)
223
- if not cols:
224
- # literal array e.g. UNNEST([1,2,3]) -- no schema column involved
225
- return set()
226
- for c in cols:
227
- out |= self.resolve_column(src, c, depth + 1)
228
- return out
229
- # CTE / DERIVED_TABLE / SUBQUERY / ROOT-as-subsource
230
- if field is None:
231
- return self._add_unresolved(Unresolved("UNRESOLVED_STRUCTURE", "bare derived-table ref"))
232
- return self.resolve_output_name(src, field, depth)
233
- return self._add_unresolved(Unresolved("UNRESOLVED_STRUCTURE", f"unknown source type {type(src)}"))
234
-
235
- def resolve_output_name(self, scope: Scope, field: str, depth):
236
- if depth > self.max_depth:
237
- return self._add_unresolved(Unresolved("MAX_DEPTH", field))
238
- if scope.union_scopes:
239
- out = set()
240
- for branch in scope.union_scopes:
241
- out |= self.resolve_output_name(branch, field, depth + 1)
242
- return out
243
- sel = scope.expression
244
- if not isinstance(sel, exp.Select):
245
- return self._add_unresolved(Unresolved("UNRESOLVED_STRUCTURE", f"non-select scope for field {field}"))
246
-
247
- target_expr = None
248
- has_star = False
249
- for e in sel.selects:
250
- oname = e.output_name
251
- if oname == "*":
252
- has_star = True
253
- continue
254
- if oname.lower() == field.lower():
255
- target_expr = e
256
- break
257
- if target_expr is None:
258
- if has_star:
259
- return self._add_unresolved(Unresolved("NEEDS_SCHEMA_STAR", f"field '{field}' via SELECT *"))
260
- return self._add_unresolved(
261
- Unresolved("UNRESOLVED_OUTPUT_NAME", f"field '{field}' not found in select list")
262
- )
263
- actual = target_expr.this if isinstance(target_expr, exp.Alias) else target_expr
264
- col_ids = {id(c) for c in actual.find_all(exp.Column)}
265
- if not col_ids:
266
- # literal / constant projection (e.g. 'Daily' AS time_type) -> no base column
267
- return set()
268
- relevant = [c for c in scope.columns if id(c) in col_ids]
269
- if not relevant:
270
- # columns exist in the expr but scope.columns filtered them out
271
- # (can happen for expressions only reachable via nested subquery);
272
- # fall back to raw walk, best-effort.
273
- relevant = list(actual.find_all(exp.Column))
274
- out = set()
275
- for c in relevant:
276
- out |= self.resolve_column(scope, c, depth + 1)
277
- return out
278
-
279
- # ---- top-level scope tree walk: collect every Column reference in every
280
- # scope (this is what "the SQL touches"), plus flag every bare `SELECT *`
281
- def walk_query(self, root: Scope):
282
- results = set()
283
- seen_scope_ids = set()
284
-
285
- def rec(scope):
286
- if id(scope) in seen_scope_ids:
287
- return
288
- seen_scope_ids.add(id(scope))
289
- if scope.stars:
290
- self.star_used = True
291
- for c in scope.columns:
292
- results.update(self.resolve_column(scope, c, 0))
293
- for child in (
294
- scope.cte_scopes
295
- + scope.derived_table_scopes
296
- + scope.subquery_scopes
297
- + scope.udtf_scopes
298
- + scope.union_scopes
299
- ):
300
- rec(child)
301
-
302
- rec(root)
303
- return results
304
-
305
-
306
- def normalize_table_col(pair):
307
- """Lowercase both sides; this is the comparison key vs gold_columns_short
308
- (which is already 'TABLE.COLUMN', case varies by source dialect)."""
309
- t, c = pair
310
- return f"{t.lower()}.{c.lower()}"
311
-
312
-
313
- def extract(sql: str, dialect: str):
314
- """Returns dict: status, predicted:set[str] (lower table.col), unresolved:list[(tag,detail)],
315
- has_star, used_udtf_heuristic, error (if parse_error), n_statements."""
316
- try:
317
- stmts = sqlglot.parse(sql, dialect=dialect)
318
- except Exception as e:
319
- return {
320
- "status": "parse_error",
321
- "error": f"{type(e).__name__}: {e}",
322
- "predicted": set(),
323
- "unresolved": [],
324
- "has_star": False,
325
- "used_udtf_heuristic": False,
326
- }
327
-
328
- script_vars = set()
329
- for stmt in stmts:
330
- if isinstance(stmt, exp.Declare):
331
- for item in stmt.expressions:
332
- for ident in item.args.get("this") or []:
333
- nm = ident.name if hasattr(ident, "name") else str(ident)
334
- script_vars.add(nm.lower())
335
-
336
- ex = Extractor(script_vars=script_vars)
337
- predicted_pairs = set()
338
- n_query_stmts = 0
339
- hard_error = None
340
- for stmt in stmts:
341
- if stmt is None:
342
- continue
343
- # find any query-shaped sub-root (handles CREATE TABLE AS SELECT etc.)
344
- query_nodes = []
345
- if isinstance(stmt, QUERY_TYPES):
346
- query_nodes.append(stmt)
347
- else:
348
- query_nodes.extend(stmt.find_all(*QUERY_TYPES))
349
- # avoid double-descending into nested selects that are already
350
- # reachable as subqueries of a top query node we already added
351
- # de-dup: keep only outermost query nodes (no query_node has another
352
- # query_node as an ancestor within this list)
353
- outer = []
354
- for q in query_nodes:
355
- if not any(q is not other and q.find_ancestor(type(other)) is other for other in query_nodes):
356
- outer.append(q)
357
- if not outer and query_nodes:
358
- outer = query_nodes[:1]
359
- for q in outer:
360
- n_query_stmts += 1
361
- try:
362
- root_scope = build_scope(q)
363
- if root_scope is None:
364
- hard_error = "build_scope returned None"
365
- continue
366
- predicted_pairs |= ex.walk_query(root_scope)
367
- except Exception as e:
368
- hard_error = f"{type(e).__name__}: {e}\n{traceback.format_exc(limit=3)}"
369
-
370
- if n_query_stmts == 0:
371
- return {
372
- "status": "parse_error",
373
- "error": "no query-shaped statement found (only DECLARE/SET/etc.)",
374
- "predicted": set(),
375
- "unresolved": [],
376
- "has_star": ex.star_used,
377
- "used_udtf_heuristic": ex.udtf_heuristic_used,
378
- }
379
-
380
- predicted = set()
381
- real_pairs = set()
382
- unresolved_tags = []
383
- for item in predicted_pairs:
384
- if isinstance(item, Unresolved):
385
- unresolved_tags.append((item.tag, item.detail))
386
- else:
387
- real_pairs.add(item)
388
- predicted.add(normalize_table_col(item))
389
-
390
- status = "scope_error" if hard_error and not real_pairs and not unresolved_tags else "ok"
391
- return {
392
- "status": status,
393
- "error": hard_error,
394
- "predicted": predicted,
395
- "predicted_pairs": real_pairs,
396
- "unresolved": unresolved_tags,
397
- "has_star": ex.star_used,
398
- "used_udtf_heuristic": ex.udtf_heuristic_used,
399
- "n_pseudocol_excluded": ex.n_pseudocol_excluded,
400
- }
401
-
402
-
403
- if __name__ == "__main__":
404
- # quick smoke test
405
- tests = [
406
- ("SELECT a, b.c FROM t1 AS b JOIN t2 ON b.c = t2.id", "bigquery"),
407
- (
408
- "WITH v AS (SELECT x, y FROM t) SELECT x FROM v",
409
- "bigquery",
410
- ),
411
- ]
412
- for sql, d in tests:
413
- r = extract(sql, d)
414
- print(sql, "->", r["status"], sorted(r["predicted"]), r["unresolved"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/gold_from_sql.py DELETED
@@ -1,131 +0,0 @@
1
- """
2
- Extract the set of (table, column) references actually used in a gold SQL
3
- query, using sqlglot's schema-aware qualifier (alias resolution + unqualified
4
- column disambiguation). Applies the convention:
5
- a column counts as "referenced" if:
6
- (a) it appears literally as table.column somewhere in the (fully
7
- alias-resolved) query, OR
8
- (b) it is the declared PRIMARY KEY of a table that is star-referenced,
9
- i.e. the query contains `SELECT *` / `SELECT t.*` / `COUNT(*)`
10
- over that table's FROM-scope (handles BIRD/Spider's common
11
- `SELECT COUNT(*) FROM t` -> gold includes t's PK convention).
12
- All matching is done case-insensitively (lower-cased table & column names).
13
- """
14
- import sqlglot
15
- import sqlglot.expressions as exp
16
- from sqlglot.optimizer.qualify import qualify
17
-
18
-
19
- class SqlExtractionError(Exception):
20
- pass
21
-
22
-
23
- def _scope_from_tables(select_node, alias_to_table):
24
- """Real (lower-cased) table names directly in this SELECT's FROM/JOIN
25
- (not walking into subqueries)."""
26
- tables = set()
27
- from_ = select_node.args.get("from")
28
- if from_ is not None:
29
- for t in from_.find_all(exp.Table):
30
- if t.find_ancestor(exp.Select) is select_node:
31
- tables.add(t.name.lower())
32
- for j in select_node.args.get("joins") or []:
33
- for t in j.find_all(exp.Table):
34
- if t.find_ancestor(exp.Select) is select_node:
35
- tables.add(t.name.lower())
36
- return tables
37
-
38
-
39
- def extract_refs(sql, sqlglot_schema, dialect="sqlite"):
40
- """
41
- Returns (refs, star_tables, ok, err)
42
- refs: set of (table_lower, column_lower) literally referenced
43
- star_tables: set of table_lower that appear in a `SELECT *` / `t.*` /
44
- `COUNT(*)` construct (star-convention eligible)
45
- ok: bool, whether parsing+qualification succeeded
46
- err: exception message if not ok
47
- """
48
- try:
49
- tree = sqlglot.parse_one(sql, read=dialect)
50
- q = qualify(
51
- tree,
52
- schema=sqlglot_schema,
53
- dialect=dialect,
54
- validate_qualify_columns=False,
55
- expand_stars=False,
56
- infer_schema=True,
57
- )
58
- except Exception as e: # noqa: BLE001
59
- return set(), set(), False, f"{type(e).__name__}: {e}"
60
-
61
- # Build a per-Select alias->real-table map (own FROM/JOIN tables only),
62
- # then resolve a column's table alias by walking UP the chain of
63
- # enclosing SELECTs -- required for correlated subqueries, e.g.
64
- # `... WHERE EXISTS (SELECT 1 FROM b WHERE b.x = t1.y)` where `t1` is
65
- # only defined in the OUTER select's FROM.
66
- own_alias_map = {}
67
- for select_node in q.find_all(exp.Select):
68
- alias_to_table = {}
69
- for t in select_node.find_all(exp.Table):
70
- if t.find_ancestor(exp.Select) is select_node:
71
- alias = (t.alias or t.name).lower()
72
- alias_to_table[alias] = t.name.lower()
73
- own_alias_map[select_node] = alias_to_table
74
-
75
- def resolve_alias(select_node, alias):
76
- node = select_node
77
- while node is not None:
78
- m = own_alias_map.get(node, {})
79
- if alias in m:
80
- return m[alias]
81
- node = node.find_ancestor(exp.Select)
82
- return None
83
-
84
- refs = set()
85
- star_tables = set()
86
-
87
- for select_node in q.find_all(exp.Select):
88
- alias_to_table = own_alias_map[select_node]
89
- scope_tables = _scope_from_tables(select_node, alias_to_table)
90
-
91
- for col in select_node.find_all(exp.Column):
92
- # only count columns belonging to this scope (not nested selects)
93
- owning_select = col.find_ancestor(exp.Select)
94
- if owning_select is not select_node:
95
- continue
96
- cname = col.name
97
- tbl_alias = (col.table or "").lower()
98
- if cname == "*":
99
- if tbl_alias:
100
- resolved = resolve_alias(select_node, tbl_alias)
101
- star_tables.add(resolved if resolved else tbl_alias)
102
- else:
103
- star_tables |= scope_tables
104
- continue
105
- if tbl_alias:
106
- resolved = resolve_alias(select_node, tbl_alias)
107
- refs.add((resolved if resolved else tbl_alias, cname.lower()))
108
- else:
109
- # unqualified after qualify() should not normally happen,
110
- # but fall back to crediting every scope table that has it
111
- for tl in scope_tables:
112
- refs.add((tl, cname.lower()))
113
-
114
- # bare Star directly in select-list (SELECT *) or inside COUNT(*)
115
- for star in select_node.find_all(exp.Star):
116
- owning_select = star.find_ancestor(exp.Select)
117
- if owning_select is not select_node:
118
- continue
119
- if isinstance(star.parent, exp.Column):
120
- continue # handled above via Column(name='*')
121
- star_tables |= scope_tables
122
-
123
- return refs, star_tables, True, None
124
-
125
-
126
- def is_faithful(table_lower, column_lower, refs, star_tables, pk_cols_lower):
127
- if (table_lower, column_lower) in refs:
128
- return True, "literal"
129
- if table_lower in star_tables and column_lower in pk_cols_lower.get(table_lower, set()):
130
- return True, "star+pk"
131
- return False, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/make_summary_and_xlsx.py DELETED
@@ -1,102 +0,0 @@
1
- """Build summary_statistics.csv (machine-readable headline table) and one
2
- Excel workbook holding every case-by-case sheet."""
3
- import json
4
- import os
5
-
6
- import pandas as pd
7
-
8
- HERE = os.path.dirname(os.path.abspath(__file__))
9
- ROOT = os.path.join(HERE, "..")
10
- DATA = os.path.join(ROOT, "data")
11
-
12
- sb = json.load(open(os.path.join(ROOT, "summary_spider_bird.json")))
13
- sn = json.load(open(os.path.join(ROOT, "summary_spider2_snow.json")))
14
-
15
- rows = []
16
-
17
-
18
- def add(dataset, metric, ours, kasla="", note=""):
19
- rows.append({"dataset": dataset, "metric": metric, "ours": ours,
20
- "kasla_codes_labels": kasla, "note": note})
21
-
22
-
23
- for ds, name in (("spider", "Spider dev (1034)"), ("bird", "BIRD dev (1534)")):
24
- s = sb[ds]
25
- o, k = s["per_set"]["ours"], s["per_set"]["kasla"]
26
- n = s["n_instances"]
27
- jt = s["join_keys_total"]
28
- add(name, "questions", n, n)
29
- add(name, "gold columns labelled", o["labelled_columns"], k["labelled_columns"])
30
- add(name, "avg gold columns / question",
31
- round(o["labelled_columns"] / n, 3), round(k["labelled_columns"] / n, 3))
32
- add(name, "SQL-faithful gold columns (%)",
33
- f'{100*o["faithful_columns"]/o["labelled_columns"]:.2f}% ({o["faithful_columns"]}/{o["labelled_columns"]})',
34
- f'{100*k["faithful_columns"]/k["labelled_columns"]:.2f}% ({k["faithful_columns"]}/{k["labelled_columns"]})',
35
- "column is provably referenced by the released gold SQL")
36
- add(name, "gold columns NOT in the SQL", o["unfaithful_columns"], k["unfaithful_columns"])
37
- add(name, "SQL-referenced columns MISSING from gold", o["missing_columns"], k["missing_columns"])
38
- add(name, "questions with >=1 wrong gold column",
39
- f'{o["instances_with_extra"]} ({100*o["instances_with_extra"]/n:.2f}%)',
40
- f'{k["instances_with_extra"]} ({100*k["instances_with_extra"]/n:.2f}%)')
41
- add(name, "questions with an EMPTY gold set",
42
- f'{o["empty_gold_instances"]} ({100*o["empty_gold_instances"]/n:.2f}%)',
43
- f'{k["empty_gold_instances"]} ({100*k["empty_gold_instances"]/n:.2f}%)',
44
- "empty gold = the question cannot be scored at column level")
45
- add(name, "JOIN-key completeness",
46
- f'{100*s["join_keys_covered"]["ours"]/jt:.2f}% ({s["join_keys_covered"]["ours"]}/{jt})',
47
- f'{100*s["join_keys_covered"]["kasla"]/jt:.2f}% ({s["join_keys_covered"]["kasla"]}/{jt})')
48
- add(name, "micro precision vs the SQL", sb[ds]["micro"]["ours"]["precision_vs_sql"],
49
- sb[ds]["micro"]["kasla"]["precision_vs_sql"])
50
- add(name, "micro recall vs the SQL", sb[ds]["micro"]["ours"]["recall_vs_sql"],
51
- sb[ds]["micro"]["kasla"]["recall_vs_sql"])
52
- add(name, "questions whose gold set is fully correct",
53
- f'{s["verdicts"]["ours"].get("CORRECT", 0)} ({100*s["verdicts"]["ours"].get("CORRECT", 0)/n:.1f}%)',
54
- f'{s["verdicts"]["kasla"].get("CORRECT", 0)} ({100*s["verdicts"]["kasla"].get("CORRECT", 0)/n:.1f}%)')
55
- add(name, "questions where the two label sets disagree", s["n_disagree_instances"],
56
- s["n_disagree_instances"], "closer to the SQL: ours "
57
- f'{s["closer_counts"].get("ours", 0)} / KaSLA {s["closer_counts"].get("kasla", 0)}')
58
-
59
- name = "Spider 2.0-Snow (282)"
60
- add(name, "questions", sn["n_instances"], "n/a", "KaSLA/CodeS release no labels for Spider 2.0")
61
- add(name, "databases", sn["n_databases"], "n/a")
62
- add(name, "gold columns labelled", sn["gold_columns_total"], "n/a")
63
- add(name, "gold columns not found in the official catalog",
64
- sn["gold_columns_out_of_catalog"], "n/a", "0 = every label names a real catalog column")
65
- add(name, "median catalog columns / database", sn["catalog_per_database"]["columns_median"], "n/a")
66
- add(name, "max catalog columns / database", sn["catalog_per_database"]["columns_max"], "n/a")
67
- add(name, "parser-only extractor: exact set match",
68
- f'{100*sn["parser_exact_match_rate"]:.1f}%', "n/a", "sqlglot, alias/CTE/UNNEST aware")
69
- add(name, "parser-only extractor: exact match after shard-name normalisation",
70
- f'{100*sn["parser_shard_normalized_exact_rate"]:.1f}%', "n/a")
71
- add(name, "parser-only extractor: micro F1 vs our gold", sn["parser_micro"]["f1"], "n/a")
72
- add(name, "name-matching (lexical) labelling rule: micro precision",
73
- sn["lexical_micro"]["precision"], "n/a", "the KaSLA/CodeS-style rule simulated on Snow")
74
- add(name, "name-matching (lexical) labelling rule: micro recall",
75
- sn["lexical_micro"]["recall"], "n/a")
76
- add(name, "median gold SQL length (chars / lines)",
77
- f'{sn["sql_complexity"]["median_chars"]} / {sn["sql_complexity"]["median_lines"]}', "n/a")
78
- add(name, "gold SQL using CTEs / dialect constructs (%)",
79
- f'{sn["sql_complexity"]["pct_with_cte"]}% / {sn["sql_complexity"]["pct_dialect_construct"]}%', "n/a")
80
-
81
- pd.DataFrame(rows).to_csv(os.path.join(DATA, "summary_statistics.csv"), index=False)
82
-
83
- SHEETS = [
84
- ("summary_statistics", "summary_statistics.csv"),
85
- ("spider_case_by_case", "spider_dev_case_by_case.csv"),
86
- ("spider_label_errors", "spider_dev_label_errors.csv"),
87
- ("bird_case_by_case", "bird_dev_case_by_case.csv"),
88
- ("bird_label_errors", "bird_dev_label_errors.csv"),
89
- ("snow_case_by_case", "spider2_snow_case_by_case.csv"),
90
- ("snow_parser_failures", "spider2_snow_parser_failures.csv"),
91
- ("snow_lexical_baseline", "spider2_snow_lexical_baseline.csv"),
92
- ]
93
- xlsx = os.path.join(ROOT, "gold_label_quality_comparison.xlsx")
94
- with pd.ExcelWriter(xlsx, engine="openpyxl") as w:
95
- for sheet, fn in SHEETS:
96
- df = pd.read_csv(os.path.join(DATA, fn))
97
- for c in df.columns:
98
- if df[c].dtype == object:
99
- df[c] = df[c].astype(str).str.slice(0, 32000)
100
- df.to_excel(w, sheet_name=sheet, index=False)
101
- print("wrote", xlsx, os.path.getsize(xlsx) / 1e6, "MB")
102
- print(pd.DataFrame(rows).to_string(max_colwidth=60))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/parser_control_spider.py DELETED
@@ -1,69 +0,0 @@
1
- """Control for the Spider 2.0-Snow parser study: run the SAME parser-only
2
- extractor on all 1,034 Spider dev queries against our Spider gold labels. If
3
- the extractor is strong on conventional SQLite SQL, its collapse on Spider 2.0
4
- is a property of the benchmark, not of a weak extractor."""
5
- import json
6
- import os
7
- import signal
8
- import sys
9
-
10
- HERE = os.path.dirname(os.path.abspath(__file__))
11
- sys.path.insert(0, HERE)
12
- from extractor import extract # noqa: E402
13
-
14
- BUNDLE = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
15
- OUR_GOLD_DIR = os.environ.get("OUR_GOLD_DIR",
16
- os.path.join(BUNDLE, "data", "eval", "gold_labels"))
17
- SPIDER = next(p for p in (os.path.join(OUR_GOLD_DIR, "spider", "spider_dev_gold_final.json"),
18
- os.path.join(OUR_GOLD_DIR, "spider_dev_gold_final.json"))
19
- if os.path.exists(p))
20
-
21
-
22
- class T(Exception):
23
- pass
24
-
25
-
26
- signal.signal(signal.SIGALRM, lambda *a: (_ for _ in ()).throw(T()))
27
-
28
- data = json.load(open(SPIDER, encoding="utf-8"))
29
- n = exact = exact_excl_conv = fail = 0
30
- tp = pred_n = gold_n = 0
31
- n_conv = 0
32
- for x in data:
33
- gold = {c.lower() for c in x["used_columns"]}
34
- signal.alarm(15)
35
- try:
36
- r = extract(x["SQL"], "sqlite")
37
- pred = {p.lower() for p in r["predicted"]}
38
- ok = r["status"] == "ok"
39
- except Exception:
40
- pred, ok = set(), False
41
- finally:
42
- signal.alarm(0)
43
- n += 1
44
- if not ok:
45
- fail += 1
46
- conv = "count_star" in (x.get("label_source") or "") or "pk_injected" in (x.get("label_source") or "")
47
- n_conv += int(conv)
48
- if pred == gold:
49
- exact += 1
50
- exact_excl_conv += 0 if conv else 1
51
- elif not conv:
52
- pass
53
- tp += len(pred & gold)
54
- pred_n += len(pred)
55
- gold_n += len(gold)
56
-
57
- p = tp / pred_n
58
- r_ = tp / gold_n
59
- print(json.dumps({
60
- "n": n,
61
- "parse_failures": fail,
62
- "exact_set_match": round(exact / n, 4),
63
- "exact_set_match_excluding_count_star_convention": round(
64
- (exact - (exact - exact_excl_conv)) / (n - n_conv), 4),
65
- "n_count_star_convention_instances": n_conv,
66
- "micro_precision": round(p, 4),
67
- "micro_recall": round(r_, 4),
68
- "micro_f1": round(2 * p * r_ / (p + r_), 4),
69
- }, indent=1))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/reproduce.sh DELETED
@@ -1,21 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Rebuild every CSV / XLSX in this folder from the public inputs.
3
- #
4
- # Inputs (override with environment variables):
5
- # SPIDER_DEV_DIR official Spider dev release (dev.json, tables.json)
6
- # BIRD_DEV_DIR official BIRD dev release (dev.json, dev_tables.json)
7
- # KASLA_DATA_DIR KaSLA released labels (spider_dev_full.json, bird_dev_full.json)
8
- # OUR_GOLD_DIR our gold labels (spider/, bird/ -> *_dev_gold_final.json)
9
- # SNOW_GOLD_DIR our Spider 2.0-Snow gold (spider2_snow_eval_gold*.json)
10
- # SPIDER2_RESOURCE_DIR official Spider 2.0-Snow catalog (resource/databases)
11
- #
12
- # Requires: python>=3.9, sqlglot, pandas, openpyxl.
13
- set -euo pipefail
14
- cd "$(dirname "$0")/scripts"
15
-
16
- python build_spider_bird.py # Spider dev + BIRD dev, ours vs KaSLA
17
- python build_spider2_snow.py # Spider 2.0-Snow validation + parser + lexical baseline
18
- python parser_control_spider.py > ../parser_control_spider.json # parser control on Spider
19
- python make_summary_and_xlsx.py # summary_statistics.csv + the Excel workbook
20
-
21
- echo "done -- outputs in ../data/ and ../gold_label_quality_comparison.xlsx"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/schema_utils.py DELETED
@@ -1,68 +0,0 @@
1
- """Load official Spider-format schema files (dev_tables.json / tables.json) into
2
- per-db lookup structures used by gold_from_sql.py."""
3
- import json
4
-
5
-
6
- def load_official_schemas(tables_json_path):
7
- tables = json.load(open(tables_json_path, encoding="utf-8"))
8
- schemas = {}
9
- for t in tables:
10
- db_id = t["db_id"]
11
- tno = t["table_names_original"]
12
- cno = t["column_names_original"] # list of [table_idx, col_name], idx -1 = "*"
13
- pk = t.get("primary_keys", [])
14
- fk = t.get("foreign_keys", [])
15
-
16
- tables_lower = [x.lower() for x in tno]
17
- col_by_table_lower = {tl: [] for tl in tables_lower}
18
- # global column index -> (table_lower, col_lower)
19
- idx_to_tc = {}
20
- for gi, (tidx, cname) in enumerate(cno):
21
- if tidx == -1:
22
- continue
23
- tl = tables_lower[tidx]
24
- cl = cname.lower()
25
- col_by_table_lower[tl].append(cl)
26
- idx_to_tc[gi] = (tl, cl)
27
-
28
- pk_cols_lower = {tl: set() for tl in tables_lower}
29
- for p in pk:
30
- if isinstance(p, list):
31
- for gi in p:
32
- if gi in idx_to_tc:
33
- tl, cl = idx_to_tc[gi]
34
- pk_cols_lower[tl].add(cl)
35
- else:
36
- if p in idx_to_tc:
37
- tl, cl = idx_to_tc[p]
38
- pk_cols_lower[tl].add(cl)
39
-
40
- fk_pairs = []
41
- for a, b in fk:
42
- if a in idx_to_tc and b in idx_to_tc:
43
- fk_pairs.append((idx_to_tc[a], idx_to_tc[b]))
44
-
45
- # schema dict for sqlglot qualify: {table_name: {col_name: type}}
46
- # use the ORIGINAL table name (not lowercased) as key since sqlglot
47
- # lowercases identifiers internally when unquoted/lowercase already;
48
- # we build using lower-cased keys throughout for robustness against
49
- # case mismatches between SQL text and catalog.
50
- sqlglot_schema = {}
51
- for tl in tables_lower:
52
- sqlglot_schema[tl] = {c: "TEXT" for c in col_by_table_lower[tl]}
53
- # add rowid-ish alias columns some sqlite BIRD dbs implicitly allow (rare) -- skip
54
-
55
- schemas[db_id] = {
56
- "tables_lower": tables_lower,
57
- "col_by_table_lower": col_by_table_lower,
58
- "pk_cols_lower": pk_cols_lower,
59
- "fk_pairs": fk_pairs,
60
- "sqlglot_schema": sqlglot_schema,
61
- }
62
- return schemas
63
-
64
-
65
- if __name__ == "__main__":
66
- import sys
67
- s = load_official_schemas(sys.argv[1]) # e.g. .../bird/dev/dev_tables.json
68
- print(len(s), list(s.keys())[:3])