-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructured_set_pipeline.py
More file actions
1914 lines (1629 loc) · 71.8 KB
/
Copy pathstructured_set_pipeline.py
File metadata and controls
1914 lines (1629 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import decimal
import json
import os
import random
import re
import sqlite3
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
import pandas as pd
import pymysql
import requests
import sqlglot
from dotenv import load_dotenv
from sqlglot import exp
from tqdm.auto import tqdm
load_dotenv()
@dataclass
class PipelineConfig:
db_name: str = "pubs"
sample_count: int = 50
text_answer_fraction: float = 0.20
snapshot_min_rows: int = 60
snapshot_max_rows: int = 120
output_root: str = "structured_set"
random_seed: int = 42
preview_rows_per_table: int = 3
remote_host: str = "relational.fel.cvut.cz"
remote_port: int = 3306
remote_user: str = "guest"
remote_password: str = "ctu-relational"
codestral_model: str = "codestral-latest"
codestral_api_url: str = "https://api.mistral.ai/v1/chat/completions"
question_model: str = "mistral-large-latest"
question_api_url: str = "https://api.mistral.ai/v1/chat/completions"
llm_temperature: float = 0.2
http_timeout: int = 180
max_plan_attempts: int = 50
max_clause_repairs: int = 20
max_sample_retries: int = 200
diversity_similarity_threshold: float = 0.78
diversity_compare_same_join_only: bool = False
numeric_answer_min_value: float = 7.0
numeric_answer_tolerance: float = 3.0
enforce_numeric_answer_uniqueness: bool = True
drop_empty_predicates: bool = True
retry_log_every: int = 5
def load_api_keys() -> Tuple[str, str]:
mistral_api_key = os.getenv("MISTRAL_API_KEY")
codestral_api_key = os.getenv("CODESTRAL_KEY") or mistral_api_key
if not codestral_api_key:
raise ValueError("Set CODESTRAL_KEY or MISTRAL_API_KEY before running the pipeline.")
if not mistral_api_key:
mistral_api_key = codestral_api_key
return codestral_api_key, mistral_api_key
def codestral_api_key_for_url(config: PipelineConfig) -> str:
mistral_api_key = os.getenv("MISTRAL_API_KEY")
codestral_api_key = os.getenv("CODESTRAL_KEY")
if "codestral.mistral.ai" in config.codestral_api_url:
selected_key = codestral_api_key or mistral_api_key
if not selected_key:
raise ValueError("Set CODESTRAL_KEY for codestral.mistral.ai, or MISTRAL_API_KEY as a fallback.")
return selected_key
selected_key = mistral_api_key or codestral_api_key
if not selected_key:
raise ValueError("Set MISTRAL_API_KEY before using api.mistral.ai.")
return selected_key
MYSQL_TO_SQLITE_TYPES = {
"int": "INTEGER",
"tinyint": "INTEGER",
"smallint": "INTEGER",
"mediumint": "INTEGER",
"bigint": "INTEGER",
"float": "REAL",
"double": "REAL",
"decimal": "REAL",
"numeric": "REAL",
"date": "TEXT",
"datetime": "TEXT",
"timestamp": "TEXT",
"time": "TEXT",
"year": "INTEGER",
"char": "TEXT",
"varchar": "TEXT",
"text": "TEXT",
"longtext": "TEXT",
"mediumtext": "TEXT",
"tinytext": "TEXT",
"blob": "BLOB",
"longblob": "BLOB",
"mediumblob": "BLOB",
"tinyblob": "BLOB",
"enum": "TEXT",
"set": "TEXT",
}
def strip_code_fences(text: str) -> str:
text = text.strip()
if text.startswith("```"):
text = re.sub(r"^```[a-zA-Z0-9_-]*", "", text).strip()
text = re.sub(r"```$", "", text).strip()
return text
def extract_first_json_object(text: str) -> str:
text = strip_code_fences(text)
start = text.find("{")
if start == -1:
raise ValueError(f"No JSON object found in model output:\n{text}")
depth = 0
for idx in range(start, len(text)):
char = text[idx]
if char == "{":
depth += 1
elif char == "}":
depth -= 1
if depth == 0:
return text[start : idx + 1]
raise ValueError(f"Unbalanced JSON object in model output:\n{text}")
def call_chat_completion(
*,
url: str,
api_key: str,
model: str,
prompt: str,
temperature: float = 0.0,
response_format: Optional[Dict[str, Any]] = None,
max_tokens: Optional[int] = None,
timeout: int = 180,
) -> str:
payload: Dict[str, Any] = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
}
if response_format is not None:
payload["response_format"] = response_format
if max_tokens is not None:
payload["max_tokens"] = max_tokens
response = requests.post(
url,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json=payload,
timeout=timeout,
)
try:
response.raise_for_status()
except requests.HTTPError as exc:
body = response.text[:1000]
raise requests.HTTPError(
f"{exc}. API response body: {body}. "
"Check that MISTRAL_API_KEY is set for api.mistral.ai, or set CODESTRAL_KEY only "
"when using the dedicated codestral.mistral.ai endpoint."
) from exc
data = response.json()
return data["choices"][0]["message"]["content"]
def call_codestral_json(prompt: str, config: PipelineConfig) -> Dict[str, Any]:
raw_text = call_chat_completion(
url=config.codestral_api_url,
api_key=codestral_api_key_for_url(config),
model=config.codestral_model,
prompt=prompt,
temperature=config.llm_temperature,
response_format={"type": "json_object"},
timeout=config.http_timeout,
)
return json.loads(extract_first_json_object(raw_text))
def call_mistral_text(prompt: str, config: PipelineConfig) -> str:
_, mistral_api_key = load_api_keys()
raw_text = call_chat_completion(
url=config.question_api_url,
api_key=mistral_api_key,
model=config.question_model,
prompt=prompt,
temperature=0.0,
timeout=config.http_timeout,
)
return strip_code_fences(raw_text).strip()
def mysql_connection(config: PipelineConfig):
return pymysql.connect(
host=config.remote_host,
port=config.remote_port,
user=config.remote_user,
password=config.remote_password,
database=config.db_name,
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor,
)
def sqlite_type_for(mysql_type: str) -> str:
mysql_type = mysql_type.lower()
for key, value in MYSQL_TO_SQLITE_TYPES.items():
if key in mysql_type:
return value
return "TEXT"
def sqlite_value(value: Any) -> Any:
if value is None:
return None
if isinstance(value, decimal.Decimal):
return float(value)
if isinstance(value, (datetime.datetime, datetime.date)):
return value.isoformat()
if isinstance(value, datetime.time):
return value.strftime("%H:%M:%S.%f") if value.microsecond else value.strftime("%H:%M:%S")
if isinstance(value, datetime.timedelta):
total_seconds = int(value.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
return value
def get_all_tables(cursor, db_name: str) -> List[str]:
cursor.execute(
"""
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = %s
ORDER BY TABLE_NAME
""",
(db_name,),
)
return [row["TABLE_NAME"] for row in cursor.fetchall()]
def get_table_columns(cursor, db_name: str, table_name: str) -> List[Dict[str, Any]]:
cursor.execute(
"""
SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA, ORDINAL_POSITION
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
ORDER BY ORDINAL_POSITION
""",
(db_name, table_name),
)
return cursor.fetchall()
def get_table_row_count(cursor, table_name: str) -> int:
cursor.execute(f'SELECT COUNT(*) AS row_count FROM `{table_name}`')
return int(cursor.fetchone()["row_count"])
def fetch_sample_rows(cursor, table_name: str, target_limit: int) -> Tuple[int, List[Dict[str, Any]]]:
row_count = get_table_row_count(cursor, table_name)
if row_count <= target_limit:
cursor.execute(f'SELECT * FROM `{table_name}`')
else:
cursor.execute(f'SELECT * FROM `{table_name}` ORDER BY RAND() LIMIT %s', (target_limit,))
return row_count, cursor.fetchall()
def fetch_rows_by_column_values(
cursor,
table_name: str,
column_name: str,
values: List[Any],
limit: int,
) -> List[Dict[str, Any]]:
clean_values = []
seen = set()
for value in values:
if value is None or value in seen:
continue
clean_values.append(value)
seen.add(value)
if len(clean_values) >= limit:
break
if not clean_values or limit <= 0:
return []
placeholders = ", ".join(["%s"] * len(clean_values))
cursor.execute(
f'SELECT * FROM `{table_name}` WHERE `{column_name}` IN ({placeholders}) LIMIT %s',
tuple(clean_values) + (limit,),
)
return cursor.fetchall()
def row_identity(row: Dict[str, Any], pk_columns: List[str]) -> Tuple[Any, ...]:
if pk_columns:
return tuple(row.get(column) for column in pk_columns)
return tuple(sorted(row.items()))
def merge_priority_rows(
existing_rows: List[Dict[str, Any]],
priority_rows: List[Dict[str, Any]],
pk_columns: List[str],
limit: int,
) -> List[Dict[str, Any]]:
merged = []
seen = set()
for row in priority_rows + existing_rows:
identity = row_identity(row, pk_columns)
if identity in seen:
continue
merged.append(row)
seen.add(identity)
if len(merged) >= limit:
break
return merged
def normalize_mysql_rows(rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
return [{key.lower(): sqlite_value(value) for key, value in row.items()} for row in rows]
def relationally_augment_table_data(
cursor,
tables: List[str],
table_columns: Dict[str, List[Dict[str, Any]]],
table_data: Dict[str, List[Dict[str, Any]]],
target_limits: Dict[str, int],
max_passes: int = 3,
) -> Dict[str, int]:
table_names_by_lower = {table.lower(): table for table in tables}
pk_by_table = {
table.lower(): [column["COLUMN_NAME"].lower() for column in columns if column["COLUMN_KEY"] == "PRI"]
for table, columns in table_columns.items()
}
columns_by_table = {
table.lower(): {column["COLUMN_NAME"].lower() for column in columns}
for table, columns in table_columns.items()
}
single_pk_targets: Dict[str, List[str]] = {}
for table_lower, pk_columns in pk_by_table.items():
if len(pk_columns) == 1:
single_pk_targets.setdefault(pk_columns[0], []).append(table_lower)
added_counts = {table.lower(): 0 for table in tables}
for _ in range(max_passes):
changed = False
for source_lower, source_rows in list(table_data.items()):
for column_name in columns_by_table.get(source_lower, set()):
target_tables = [
table_lower
for table_lower in single_pk_targets.get(column_name, [])
if table_lower != source_lower
]
if not target_tables:
continue
values = [row.get(column_name) for row in source_rows if row.get(column_name) is not None]
if not values:
continue
for target_lower in target_tables:
current_rows = table_data.get(target_lower, [])
target_limit = target_limits[target_lower]
target_pk = pk_by_table[target_lower]
original_identities = {row_identity(row, target_pk) for row in current_rows}
fetch_limit = max(target_limit, len(values))
fetched_rows = normalize_mysql_rows(
fetch_rows_by_column_values(
cursor=cursor,
table_name=table_names_by_lower[target_lower],
column_name=column_name,
values=values,
limit=fetch_limit,
)
)
merged_rows = merge_priority_rows(current_rows, fetched_rows, target_pk, target_limit)
new_identities = {row_identity(row, target_pk) for row in merged_rows}
added = len(new_identities - original_identities)
if added > 0:
table_data[target_lower] = merged_rows
added_counts[target_lower] += added
changed = True
if not changed:
break
return added_counts
def create_sqlite_table(sqlite_conn: sqlite3.Connection, table_name: str, columns: List[Dict[str, Any]]) -> None:
parts = []
pk_columns = []
for column in columns:
col_name = column["COLUMN_NAME"].lower()
col_type = sqlite_type_for(column["DATA_TYPE"])
nullable = "" if column["IS_NULLABLE"] == "YES" else " NOT NULL"
parts.append(f'"{col_name}" {col_type}{nullable}')
if column["COLUMN_KEY"] == "PRI":
pk_columns.append(f'"{col_name}"')
if pk_columns:
parts.append(f"PRIMARY KEY ({', '.join(pk_columns)})")
sql = f'CREATE TABLE IF NOT EXISTS "{table_name.lower()}" ({", ".join(parts)})'
sqlite_conn.execute(sql)
def insert_rows_sqlite(
sqlite_conn: sqlite3.Connection,
table_name: str,
rows: List[Dict[str, Any]],
columns: List[Dict[str, Any]],
) -> None:
if not rows:
return
ordered_columns = [column["COLUMN_NAME"].lower() for column in columns]
placeholders = ", ".join(["?"] * len(ordered_columns))
quoted_columns = ", ".join([f'"{column}"' for column in ordered_columns])
sql = f'INSERT INTO "{table_name.lower()}" ({quoted_columns}) VALUES ({placeholders})'
values = []
for row in rows:
normalized = {key.lower(): sqlite_value(value) for key, value in row.items()}
values.append([normalized.get(column) for column in ordered_columns])
sqlite_conn.executemany(sql, values)
def build_local_snapshot(sample_dir: Path, config: PipelineConfig, rng: random.Random) -> Dict[str, Any]:
sample_dir.mkdir(parents=True, exist_ok=True)
csv_dir = sample_dir / "csv"
csv_dir.mkdir(parents=True, exist_ok=True)
sqlite_path = sample_dir / "local_snapshot.db"
if sqlite_path.exists():
sqlite_path.unlink()
manifest: Dict[str, Any] = {
"db_name": config.db_name,
"sample_dir": str(sample_dir),
"snapshot_min_rows": config.snapshot_min_rows,
"snapshot_max_rows": config.snapshot_max_rows,
"tables": [],
}
with mysql_connection(config) as remote_conn:
with remote_conn.cursor() as cursor:
tables = get_all_tables(cursor, config.db_name)
table_columns: Dict[str, List[Dict[str, Any]]] = {}
table_data: Dict[str, List[Dict[str, Any]]] = {}
remote_counts: Dict[str, int] = {}
target_limits: Dict[str, int] = {}
for table_name in tables:
columns = get_table_columns(cursor, config.db_name, table_name)
target_limit = rng.randint(config.snapshot_min_rows, config.snapshot_max_rows)
remote_count, rows = fetch_sample_rows(cursor, table_name, target_limit)
table_lower = table_name.lower()
table_columns[table_name] = columns
target_limits[table_lower] = min(target_limit, remote_count)
remote_counts[table_lower] = remote_count
table_data[table_lower] = normalize_mysql_rows(rows)
added_counts = relationally_augment_table_data(
cursor=cursor,
tables=tables,
table_columns=table_columns,
table_data=table_data,
target_limits=target_limits,
)
sqlite_conn = sqlite3.connect(sqlite_path)
try:
for table_name in tables:
table_lower = table_name.lower()
columns = table_columns[table_name]
normalized_rows = table_data[table_lower]
create_sqlite_table(sqlite_conn, table_name, columns)
insert_rows_sqlite(sqlite_conn, table_name, normalized_rows, columns)
df = pd.DataFrame(normalized_rows)
if df.empty:
df = pd.DataFrame(columns=[column["COLUMN_NAME"].lower() for column in columns])
df.to_csv(csv_dir / f"{table_name.lower()}.csv", index=False)
manifest["tables"].append(
{
"table_name": table_lower,
"remote_row_count": remote_counts[table_lower],
"snapshot_row_count": len(normalized_rows),
"target_limit": target_limits[table_lower],
"relational_rows_added": added_counts.get(table_lower, 0),
"columns": [
{
"name": column["COLUMN_NAME"].lower(),
"mysql_type": column["DATA_TYPE"],
"sqlite_type": sqlite_type_for(column["DATA_TYPE"]),
}
for column in columns
],
}
)
sqlite_conn.commit()
finally:
sqlite_conn.close()
(sample_dir / "snapshot_manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2))
return manifest
def build_snapshot_description(sample_dir: Path, preview_rows: int) -> str:
manifest = json.loads((sample_dir / "snapshot_manifest.json").read_text())
csv_dir = sample_dir / "csv"
chunks = [
f"Database name: {manifest['db_name']}",
f"Tables in snapshot: {len(manifest['tables'])}",
"",
]
for table_info in manifest["tables"]:
table_name = table_info["table_name"]
chunks.append(f"Table: {table_name}")
chunks.append(
"Columns: "
+ ", ".join(f"{column['name']} ({column['sqlite_type']})" for column in table_info["columns"])
)
chunks.append(
f"Snapshot rows: {table_info['snapshot_row_count']} / remote rows: {table_info['remote_row_count']}"
)
csv_path = csv_dir / f"{table_name}.csv"
preview_df = pd.read_csv(csv_path).head(preview_rows)
if preview_df.empty:
chunks.append("Sample rows: <empty table>")
else:
chunks.append("Sample rows:")
chunks.append(preview_df.to_markdown(index=False))
chunks.append("")
return "\n".join(chunks)
def normalize_sql_for_sqlite(sql: str) -> str:
sql = strip_code_fences(sql).strip().rstrip(";")
return sql.replace("`", '"')
def run_sqlite_query(db_path: Path, sql: str) -> Tuple[bool, Any]:
normalized_sql = normalize_sql_for_sqlite(sql)
with sqlite3.connect(db_path) as conn:
try:
df = pd.read_sql_query(normalized_sql, conn)
return True, df
except Exception as exc:
return False, str(exc)
def is_effectively_empty(df: pd.DataFrame) -> bool:
if df.empty:
return True
if df.shape == (1, 1) and pd.isna(df.iloc[0, 0]):
return True
return False
def unique_preview_columns(columns: List[Any]) -> List[str]:
seen: Dict[str, int] = {}
unique_columns = []
for column in columns:
base_name = str(column)
count = seen.get(base_name, 0)
seen[base_name] = count + 1
unique_columns.append(base_name if count == 0 else f"{base_name}__dup{count}")
return unique_columns
def dataframe_preview_records(df: pd.DataFrame, limit: int = 5) -> List[Dict[str, Any]]:
preview_df = df.head(limit).copy()
preview_df.columns = unique_preview_columns(list(preview_df.columns))
return preview_df.to_dict(orient="records")
def validate_sql(db_path: Path, sql: str, *, expect_scalar: bool, expect_text: bool = False) -> Dict[str, Any]:
success, result = run_sqlite_query(db_path, sql)
if not success:
return {
"success": False,
"empty": True,
"error": result,
"row_count": 0,
"column_count": 0,
"preview": None,
"scalar": False,
"text_scalar": False,
}
df: pd.DataFrame = result
scalar = df.shape[0] == 1 and df.shape[1] == 1
text_scalar = scalar and isinstance(df.iloc[0, 0], str)
empty = is_effectively_empty(df)
valid = not empty
if expect_scalar:
valid = valid and scalar
if expect_text:
valid = valid and text_scalar
return {
"success": valid,
"empty": empty,
"error": None,
"row_count": int(df.shape[0]),
"column_count": int(df.shape[1]),
"preview": dataframe_preview_records(df),
"scalar": scalar,
"text_scalar": text_scalar,
"dataframe": df,
}
def scalar_answer_from_df(df: pd.DataFrame) -> str:
value = df.iloc[0, 0]
if isinstance(value, float):
return format(value, ".12g")
return str(value)
def numeric_scalar_from_df(df: pd.DataFrame) -> Optional[float]:
if df.shape[0] != 1 or df.shape[1] != 1:
return None
value = df.iloc[0, 0]
if value is None or pd.isna(value) or isinstance(value, bool):
return None
if isinstance(value, (int, float, decimal.Decimal)):
return float(value)
if isinstance(value, str):
cleaned = value.strip().replace(",", "")
if not cleaned:
return None
try:
return float(cleaned)
except ValueError:
return None
return None
def generation_constraints(sample_index: int, answer_mode: str) -> Dict[str, Any]:
constraints = {
"answer_mode": answer_mode,
"target_join_count": 3,
"min_hops": 2,
"max_hops": 4,
"require_group_by": False,
"require_having": False,
"require_nested_subquery": True,
}
if answer_mode == "aggregate":
constraints["require_group_by"] = sample_index % 2 == 0
constraints["require_having"] = sample_index % 5 == 0
return constraints
def build_query_plan_prompt(snapshot_text: str, answer_mode: str, constraints: Dict[str, Any], feedback: str = "") -> str:
mode_instruction = (
"The final answer must be a single scalar aggregate value."
if answer_mode == "aggregate"
else "The final answer must be a single scalar textual value, not a numeric aggregate."
)
grouping_lines = []
if constraints["require_group_by"]:
grouping_lines.append("The final logic must include GROUP BY.")
if constraints["require_having"]:
grouping_lines.append("The final logic must include HAVING.")
if not grouping_lines:
grouping_lines.append("GROUP BY and HAVING are optional unless naturally needed.")
feedback_block = f"Previous failed attempt and provenance feedback:\n{feedback}\n\n" if feedback else ""
return f"""
You are generating one complex SQL example over a local SQLite snapshot.
Important requirements:
- Work ONLY with the tables and columns present in the snapshot description.
- Use realistic multi-hop relational reasoning with exactly {constraints['target_join_count']} JOIN clauses in the final SQL query.
- The final SQL query must not use fewer or more than {constraints['target_join_count']} JOIN clauses.
- Every JOIN must be semantically necessary for the final answer. Do not add a table only to reach the target JOIN count.
- A JOIN is allowed only if at least one of these is true:
(a) its columns are used in SELECT, WHERE, GROUP BY, HAVING, ORDER BY, or a nested predicate;
(b) it intentionally changes row multiplicity for the metric and this is part of the question intent.
- Do not join payment, statement, member, provider, corporation, category, or region unless that table affects the metric,
a filter, a grouping key, a label returned to the user, or row multiplicity that the question explicitly relies on.
- If you cannot make exactly {constraints['target_join_count']} meaningful JOIN clauses, choose a different analytical intent.
- Use post-order structure: list leaf blocks first, root block last.
- Each block must be executable after substitution of child placeholders.
- Child blocks can be referenced only by placeholders like {{{{leaf_1}}}}.
- If the root block reads from a child subquery, the root SELECT must reference only columns exposed by that subquery,
optionally qualified by the subquery alias. Do not reference inner table aliases such as c, m, p, r, cat from the root.
- Return JSON only.
- No CTEs.
- No comments.
- Use lowercase table and column names as they appear in the snapshot.
- {mode_instruction}
- {' '.join(grouping_lines)}
- A nested subquery is required somewhere in the plan.
{feedback_block}Return exactly this JSON schema:
{{
"question_intent": "short natural description of what the query computes",
"answer_mode": "{answer_mode}",
"final_block_name": "root",
"detail_query": "row-level SQL with the same filters that returns supporting rows before the final scalar answer",
"blocks": [
{{
"name": "leaf_1",
"role": "leaf",
"select_clause": "SELECT ...",
"from_clause": "FROM ...",
"join_clauses": ["JOIN ... ON ..."],
"where_clauses": ["predicate 1", "predicate 2"],
"group_by_clause": "GROUP BY ... or empty string",
"having_clauses": ["predicate 3"],
"notes": "what this block returns"
}},
{{
"name": "root",
"role": "root",
"select_clause": "SELECT ...",
"from_clause": "FROM {{{{leaf_1}}}} AS leaf_1",
"join_clauses": [],
"where_clauses": [],
"group_by_clause": "",
"having_clauses": [],
"notes": "final scalar block"
}}
]
}}
Snapshot description:
{snapshot_text}
"""
def build_clause_repair_prompt(
snapshot_text: str,
block: Dict[str, Any],
clause_kind: str,
failing_clause: str,
accepted_joins: List[str],
accepted_wheres: List[str],
accepted_havings: List[str],
failure_reason: str,
) -> str:
return f"""
You are repairing one SQL clause inside a partially validated block.
Return JSON only: {{"repaired_clause": "..."}}
Rules:
- Change only the failing clause.
- Preserve the block intent.
- Keep table names and columns limited to the snapshot.
- The repaired clause must stay in the same clause family: JOIN, WHERE predicate, or HAVING predicate.
- For JOIN repairs, the JOIN must be semantically necessary. Do not add a table only to satisfy a JOIN count.
- If the previous clause made the result empty, relax only that clause.
- If the previous clause caused an execution error, fix only the syntax or column/table reference in that clause.
Block:
{json.dumps(block, ensure_ascii=False, indent=2)}
Clause kind: {clause_kind}
Failing clause: {failing_clause}
Accepted joins so far: {json.dumps(accepted_joins, ensure_ascii=False)}
Accepted where predicates so far: {json.dumps(accepted_wheres, ensure_ascii=False)}
Accepted having predicates so far: {json.dumps(accepted_havings, ensure_ascii=False)}
Failure reason: {failure_reason}
Snapshot description:
{snapshot_text}
"""
def build_sql_to_text_prompt(sql: str) -> str:
return f"""
You are an expert SQL-to-question translator.
Your task is to convert the given SQL query into a clear, natural-sounding English question.
Important rules:
1. Preserve the exact semantics of the SQL query.
2. Do not simplify the query meaning based on table or column names alone.
3. Pay special attention to:
- aggregation functions such as AVG, SUM, COUNT, MIN, MAX;
- nested queries;
- GROUP BY logic;
- averages of averages;
- filters in WHERE or HAVING;
- joins that may affect row multiplicity;
- DISTINCT;
- ORDER BY and LIMIT.
4. If the outer query aggregates over the result of an inner grouped query, express that explicitly.
For example:
- SQL meaning: AVG of category-level averages
- Question: "What is the average of the average charge amounts across categories?"
Do NOT translate it as:
- "What is the average charge amount for each category?"
5. If the query returns one scalar value, the question should ask for one value.
6. If the query returns one row per group, the question should ask for values "for each" group.
7. If the SQL includes joins that are not needed to express the business meaning, do not mention them unless they change the result.
8. Do not invent filters, conditions, entities, or business context that are not present in the SQL.
9. Use natural English, but prioritize correctness over sounding casual.
10. The final question must be concise and understandable to a non-technical user.
Before writing the final question, analyze the SQL internally:
- What is the final SELECT returning?
- Is the result scalar or grouped?
- What aggregation happens at each level?
- What entities are being grouped by?
- Are there nested aggregations?
- Do joins only provide labels, or can they affect the number of rows?
Output only the final English question. Do not explain your reasoning.
SQL:
{sql}
"""
def build_golden_cells_prompt(final_sql: str, answer_mode: str) -> str:
return f"""
Produce a SQL query that returns the row-level cells needed to verify the answer for the final query.
Rules:
- Keep the same semantic filters.
- For aggregate queries, remove the final aggregation and expose the supporting rows and columns needed to recompute the answer.
- For non-aggregate text queries, return the same query if it already exposes the needed cells.
- If the same query is sufficient, return the single word: same
- Return JSON only in the form {{"golden_cells_sql": "..."}}
Answer mode: {answer_mode}
Final SQL:
{final_sql}
"""
def ensure_list(value: Any) -> List[str]:
if value is None:
return []
if isinstance(value, list):
return [str(item).strip().rstrip(";") for item in value if str(item).strip()]
if isinstance(value, str) and value.strip():
return [value.strip().rstrip(";")]
return []
def ensure_plan_shape(plan: Dict[str, Any]) -> Dict[str, Any]:
if "blocks" not in plan or not isinstance(plan["blocks"], list) or not plan["blocks"]:
raise ValueError(f"Plan is missing blocks: {plan}")
if "final_block_name" not in plan:
plan["final_block_name"] = plan["blocks"][-1]["name"]
if "detail_query" not in plan:
plan["detail_query"] = ""
for block in plan["blocks"]:
block["join_clauses"] = ensure_list(block.get("join_clauses"))
block["where_clauses"] = ensure_list(block.get("where_clauses"))
block["having_clauses"] = ensure_list(block.get("having_clauses"))
block["group_by_clause"] = (block.get("group_by_clause") or "").strip().rstrip(";")
for key in ["select_clause", "from_clause", "name", "role"]:
if key not in block or not str(block[key]).strip():
raise ValueError(f"Block is missing required field {key}: {block}")
block[key] = str(block[key]).strip().rstrip(";")
return plan
def count_sql_joins(sql: str) -> int:
try:
parsed = sqlglot.parse_one(normalize_sql_for_sqlite(sql), read="sqlite")
return sum(1 for node in parsed.walk() if isinstance(node, exp.Join))
except Exception:
return len(re.findall(r"\bjoin\b", sql, flags=re.IGNORECASE))
def scalar_values_equal(left: Any, right: Any, tolerance: float = 1e-9) -> bool:
if pd.isna(left) and pd.isna(right):
return True
try:
return abs(float(left) - float(right)) <= tolerance
except (TypeError, ValueError):
return str(left) == str(right)
def dataframes_equivalent(left: pd.DataFrame, right: pd.DataFrame) -> bool:
if left.shape != right.shape:
return False
if left.shape == (1, 1):
return scalar_values_equal(left.iloc[0, 0], right.iloc[0, 0])
try:
return left.reset_index(drop=True).equals(right.reset_index(drop=True))
except Exception:
return False
def sql_without_join_at(sql: str, join_index: int) -> Optional[str]:
try:
parsed = sqlglot.parse_one(normalize_sql_for_sqlite(sql), read="sqlite")
except Exception:
return None
modified = parsed.copy()
seen = 0
for select_node in modified.find_all(exp.Select):
joins = list(select_node.args.get("joins") or [])
if join_index < seen + len(joins):
local_index = join_index - seen
del joins[local_index]
select_node.set("joins", joins)
return modified.sql(dialect="sqlite")
seen += len(joins)
return None
def join_necessity_check(db_path: Path, final_sql: str, config: PipelineConfig) -> Dict[str, Any]:
original_validation = validate_sql(db_path, final_sql, expect_scalar=True)
if not original_validation["success"]:
return {"accepted": True, "reason": "original query is not valid yet", "redundant_joins": []}
original_df = original_validation["dataframe"]
redundant_joins = []
join_count = count_sql_joins(final_sql)
for join_index in range(join_count):
ablated_sql = sql_without_join_at(final_sql, join_index)
if not ablated_sql:
continue
ablated_validation = validate_sql(db_path, ablated_sql, expect_scalar=True)
if not ablated_validation["success"]:
continue
if dataframes_equivalent(original_df, ablated_validation["dataframe"]):
redundant_joins.append(
{
"join_index": join_index,
"ablated_sql": ablated_sql,
"result_preview": ablated_validation["preview"],
}
)
return {
"accepted": not redundant_joins,
"reason": "ok" if not redundant_joins else "removing at least one JOIN leaves the answer unchanged",
"redundant_joins": redundant_joins,
}
def jaccard(left: Set[str], right: Set[str]) -> float: