sqlprove 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sqlprove/algebra.py ADDED
@@ -0,0 +1,1302 @@
1
+ """Unbounded sound algebraic equivalence rules (ALGEBRAICALLY_PROVEN).
2
+
3
+ Every rule in this module is strictly fail-closed:
4
+ - It checks ALL structural, semantic, 3-valued NULL, and schema preconditions.
5
+ - If any precondition cannot be confirmed, it returns None (falling back to Z3
6
+ bounded verification or UNSUPPORTED — never guessing or dropping clauses).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime as dt
12
+ import re
13
+
14
+ from sqlglot import exp
15
+
16
+ from sqlprove.prover import ProofStatus, VerificationResult
17
+ from sqlprove.schema import Schema, TableSpec
18
+
19
+ _DISALLOWED_CLAUSES = ("limit", "offset", "order", "laterals", "windows")
20
+
21
+
22
+ def _norm_sql(node: exp.Expression) -> str:
23
+ """Canonical normalized SQL string for structural AST equality checks."""
24
+ return node.sql(dialect="duckdb").strip().lower()
25
+
26
+
27
+ def _strip_parens(node: exp.Expression) -> exp.Expression:
28
+ while isinstance(node, exp.Paren):
29
+ node = node.this
30
+ return node
31
+
32
+
33
+ def _split_conjuncts(expr: exp.Expression | None) -> list[exp.Expression]:
34
+ if expr is None:
35
+ return []
36
+ out: list[exp.Expression] = []
37
+ stack = [expr]
38
+ while stack:
39
+ cur = _strip_parens(stack.pop())
40
+ if isinstance(cur, exp.And):
41
+ stack.append(cur.expression)
42
+ stack.append(cur.this)
43
+ else:
44
+ out.append(cur)
45
+ return out
46
+
47
+
48
+ def _has_disallowed_or_volatile(ast: exp.Expression) -> bool:
49
+ for sel in ast.find_all(exp.Select):
50
+ for cl in _DISALLOWED_CLAUSES:
51
+ if sel.args.get(cl):
52
+ return True
53
+ # Reject non-deterministic / volatile functions anywhere
54
+ for fn in ast.find_all(exp.Func):
55
+ fname = type(fn).__name__.lower()
56
+ sql_head = fn.sql().split("(")[0].strip().lower()
57
+ if fname in ("rand", "random", "currenttimestamp", "currentdate", "uuid") or sql_head in (
58
+ "random",
59
+ "rand",
60
+ "uuid",
61
+ "current_timestamp",
62
+ "current_date",
63
+ "now",
64
+ ):
65
+ return True
66
+ return False
67
+
68
+
69
+ def _resolve_table_spec(table_node: exp.Expression, schema: Schema) -> TableSpec | None:
70
+ if not isinstance(table_node, exp.Table) or not table_node.name:
71
+ return None
72
+ if schema.has_table(table_node.name):
73
+ return schema.get_table(table_node.name)
74
+ return None
75
+
76
+
77
+ def _resolve_column_nullable(col: exp.Column, select: exp.Select, schema: Schema) -> bool | None:
78
+ """Return True/False if nullability of `col` in `select` is statically known from Schema, else None."""
79
+ # Build alias -> TableSpec map for FROM and INNER joins (LEFT/RIGHT/FULL joins make RHS/LHS nullable!)
80
+ alias_to_spec: dict[str, TableSpec] = {}
81
+ nullable_aliases: set[str] = set()
82
+ fc = select.args.get("from_")
83
+ if fc is None or not isinstance(fc.this, exp.Table):
84
+ return None
85
+ fspec = _resolve_table_spec(fc.this, schema)
86
+ if fspec is None:
87
+ return None
88
+ falias = (fc.this.alias or fc.this.name).lower()
89
+ alias_to_spec[falias] = fspec
90
+
91
+ for j in select.args.get("joins") or []:
92
+ side = (j.side or "").upper()
93
+ if isinstance(j.this, exp.Table):
94
+ jspec = _resolve_table_spec(j.this, schema)
95
+ jalias = (j.this.alias or j.this.name).lower()
96
+ if jspec is not None:
97
+ alias_to_spec[jalias] = jspec
98
+ if side in ("LEFT", "FULL"):
99
+ nullable_aliases.add(jalias)
100
+ if side in ("RIGHT", "FULL"):
101
+ nullable_aliases.add(falias)
102
+ else:
103
+ return None
104
+
105
+ cname = col.name.lower()
106
+ if col.table:
107
+ q = col.table.lower()
108
+ if q in nullable_aliases:
109
+ return True
110
+ spec = alias_to_spec.get(q)
111
+ if spec is None or not spec.has_column(cname):
112
+ return None
113
+ return spec.is_nullable(cname)
114
+
115
+ # Unqualified column: must uniquely resolve to one table
116
+ matches = [(al, sp) for al, sp in alias_to_spec.items() if sp.has_column(cname)]
117
+ if len(matches) != 1:
118
+ return None
119
+ al, sp = matches[0]
120
+ if al in nullable_aliases:
121
+ return True
122
+ return sp.is_nullable(cname)
123
+
124
+
125
+ def _resolve_column_dtype(col: exp.Column, select: exp.Select, schema: Schema) -> str | None:
126
+ fc = select.args.get("from_")
127
+ if fc is None or not isinstance(fc.this, exp.Table):
128
+ return None
129
+ alias_to_spec: dict[str, TableSpec] = {}
130
+ fspec = _resolve_table_spec(fc.this, schema)
131
+ if fspec is not None:
132
+ alias_to_spec[(fc.this.alias or fc.this.name).lower()] = fspec
133
+ for j in select.args.get("joins") or []:
134
+ if isinstance(j.this, exp.Table):
135
+ jspec = _resolve_table_spec(j.this, schema)
136
+ if jspec is not None:
137
+ alias_to_spec[(j.this.alias or j.this.name).lower()] = jspec
138
+ cname = col.name.lower()
139
+ if col.table:
140
+ sp = alias_to_spec.get(col.table.lower())
141
+ return sp.get_column(cname).canonical_dtype if (sp and sp.has_column(cname)) else None
142
+ matches = [sp for sp in alias_to_spec.values() if sp.has_column(cname)]
143
+ if len(matches) == 1:
144
+ return matches[0].get_column(cname).canonical_dtype
145
+ return None
146
+
147
+
148
+ def _extract_equi_join_pairs(join: exp.Join, lhs_aliases: set[str], rhs_alias: str) -> tuple[list[tuple[str, str, str]], bool]:
149
+ """Return ([(lhs_alias, lhs_col, rhs_col), ...], has_extra_predicates) from join ON/USING."""
150
+ using_cols = join.args.get("using") or []
151
+ if using_cols:
152
+ if len(lhs_aliases) != 1:
153
+ return [], True
154
+ la = next(iter(lhs_aliases))
155
+ return [(la, u.name.lower(), u.name.lower()) for u in using_cols], False
156
+
157
+ on_expr = join.args.get("on")
158
+ if on_expr is None:
159
+ return [], True
160
+ pairs: list[tuple[str, str, str]] = []
161
+ extra = False
162
+ for conj in _split_conjuncts(on_expr):
163
+ if isinstance(conj, exp.EQ) and isinstance(conj.this, exp.Column) and isinstance(conj.expression, exp.Column):
164
+ c1, c2 = conj.this, conj.expression
165
+ t1, t2 = (c1.table or "").lower(), (c2.table or "").lower()
166
+ if t1 in lhs_aliases and t2 == rhs_alias:
167
+ pairs.append((t1, c1.name.lower(), c2.name.lower()))
168
+ elif t2 in lhs_aliases and t1 == rhs_alias:
169
+ pairs.append((t2, c2.name.lower(), c1.name.lower()))
170
+ else:
171
+ extra = True
172
+ else:
173
+ extra = True
174
+ return pairs, extra
175
+
176
+
177
+ def _rhs_has_unique_key_certificate(
178
+ rhs_node: exp.Expression,
179
+ rhs_join_cols: set[str],
180
+ ctes: dict[str, exp.CTE],
181
+ schema: Schema,
182
+ ) -> str | None:
183
+ """Return proof explanation string if RHS guarantees <= 1 row per non-null `rhs_join_cols` tuple."""
184
+ if not rhs_join_cols:
185
+ return None
186
+ if isinstance(rhs_node, exp.Table):
187
+ tname = rhs_node.name.lower()
188
+ if tname in ctes:
189
+ return _query_has_unique_key_certificate(ctes[tname].this, rhs_join_cols, ctes, schema)
190
+ tspec = _resolve_table_spec(rhs_node, schema)
191
+ if tspec is not None:
192
+ uk = tspec.has_unique_subset(rhs_join_cols)
193
+ if uk is not None:
194
+ return f"schema UNIQUE/PK {tspec.name}({', '.join(uk)})"
195
+ return None
196
+ if isinstance(rhs_node, exp.Subquery):
197
+ return _query_has_unique_key_certificate(rhs_node.this, rhs_join_cols, ctes, schema)
198
+ return None
199
+
200
+
201
+ def _query_has_unique_key_certificate(
202
+ query: exp.Expression,
203
+ target_cols: set[str],
204
+ ctes: dict[str, exp.CTE],
205
+ schema: Schema,
206
+ ) -> str | None:
207
+ """Return proof string if a SELECT query algebraically guarantees unique tuples on `target_cols`."""
208
+ if not isinstance(query, exp.Select):
209
+ return None
210
+ # Map output alias -> underlying expression
211
+ out_map: dict[str, exp.Expression] = {}
212
+ for e in query.expressions:
213
+ if isinstance(e, exp.Alias):
214
+ out_map[e.alias.lower()] = e.this
215
+ elif isinstance(e, exp.Column):
216
+ out_map[e.name.lower()] = e
217
+
218
+ # Case 1: GROUP BY keys are a subset of target_cols (mapped through output aliases)
219
+ group = query.args.get("group")
220
+ if group is not None and group.expressions:
221
+ # Resolve every GROUP BY key to an output column name in target_cols
222
+ gb_ok = True
223
+ gb_names: list[str] = []
224
+ for gk in group.expressions:
225
+ matched_out = None
226
+ if isinstance(gk, exp.Literal) and gk.is_int:
227
+ pos = int(gk.this) - 1
228
+ if 0 <= pos < len(query.expressions):
229
+ e = query.expressions[pos]
230
+ matched_out = (e.alias if isinstance(e, exp.Alias) else (e.name if isinstance(e, exp.Column) else "")).lower()
231
+ else:
232
+ gk_sql = _norm_sql(gk)
233
+ for oname, oexpr in out_map.items():
234
+ if _norm_sql(oexpr) == gk_sql or (isinstance(gk, exp.Column) and gk.name.lower() == oname):
235
+ matched_out = oname
236
+ break
237
+ if matched_out and matched_out in target_cols:
238
+ gb_names.append(matched_out)
239
+ else:
240
+ gb_ok = False
241
+ break
242
+ if gb_ok and gb_names:
243
+ return f"GROUP BY ({', '.join(gb_names)}) uniqueness"
244
+
245
+ # Case 2: SELECT DISTINCT projecting a subset of target_cols
246
+ if query.args.get("distinct") and not any(isinstance(e, exp.Star) for e in query.expressions):
247
+ if out_map and set(out_map.keys()).issubset(target_cols):
248
+ return f"SELECT DISTINCT ({', '.join(sorted(out_map.keys()))}) uniqueness"
249
+
250
+ return None
251
+
252
+
253
+ def _rhs_alias_strictly_unused(select: exp.Select, join_idx: int, rhs_alias: str) -> bool:
254
+ """Return True iff `rhs_alias` is provably unreferenced outside join `join_idx`'s ON clause."""
255
+ joins = select.args.get("joins") or []
256
+ # Reject any SELECT * or rhs.*
257
+ for e in select.expressions:
258
+ if isinstance(e, exp.Star):
259
+ return False
260
+ if isinstance(e, exp.Column) and isinstance(e.this, exp.Star):
261
+ if not e.table or e.table.lower() == rhs_alias:
262
+ return False
263
+
264
+ parts: list[exp.Expression] = [
265
+ *select.expressions,
266
+ *(p for p in [select.args.get("where"), select.args.get("group"), select.args.get("having"), select.args.get("qualify"), select.args.get("order")] if p is not None),
267
+ ]
268
+ for idx, oj in enumerate(joins):
269
+ if idx != join_idx and oj.args.get("on") is not None:
270
+ parts.append(oj.args["on"])
271
+ if idx != join_idx and oj.args.get("using"):
272
+ return False # Conservative: USING across multiple joins can bind rhs columns
273
+
274
+ for p in parts:
275
+ for col in p.find_all(exp.Column):
276
+ if isinstance(col.this, exp.Star):
277
+ continue
278
+ if not col.table:
279
+ # Fail closed: an unqualified column could bind to rhs_alias!
280
+ return False
281
+ if col.table.lower() == rhs_alias:
282
+ return False
283
+ return True
284
+
285
+
286
+ def _rule_a1_a2_dead_join(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
287
+ """Rules A1 (dead LEFT JOIN w/ UNIQUE or GROUP BY RHS) and A2 (dead INNER JOIN w/ NOT NULL FK + UNIQUE RHS)."""
288
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Select):
289
+ return None
290
+ joins1 = list(ast1.args.get("joins") or [])
291
+ joins2 = list(ast2.args.get("joins") or [])
292
+ if len(joins1) != len(joins2) + 1:
293
+ return None
294
+
295
+ ctes1: dict[str, exp.CTE] = {}
296
+ if ast1.args.get("with_"):
297
+ ctes1 = {c.alias.lower(): c for c in ast1.args["with_"].expressions if c.alias}
298
+
299
+ fc = ast1.args.get("from_")
300
+ if fc is None:
301
+ return None
302
+ base_alias = (fc.this.alias or fc.this.name).lower() if isinstance(fc.this, exp.Table) else (fc.this.alias or "").lower()
303
+ lhs_aliases = {base_alias} if base_alias else set()
304
+
305
+ for idx, join in enumerate(joins1):
306
+ side = (join.side or "").upper()
307
+ kind = (join.kind or "").upper()
308
+ rhs = join.this
309
+ rhs_alias = (rhs.alias or rhs.name).lower() if isinstance(rhs, exp.Table) else (rhs.alias or "").lower()
310
+ if not rhs_alias:
311
+ continue
312
+
313
+ # Check if removing join `idx` makes ast1 structurally equal to ast2 (allowing unused CTE cleanup!)
314
+ candidate = ast1.copy()
315
+ rem_joins = [j for j_i, j in enumerate(candidate.args["joins"]) if j_i != idx]
316
+ candidate.set("joins", rem_joins or None)
317
+ # Also if ast2 dropped a CTE that was ONLY referenced by this removed join, compare cleanly
318
+ if _norm_sql(candidate) != _norm_sql(ast2):
319
+ # Try stripping CTEs from candidate that aren't in ast2 and aren't referenced in candidate body
320
+ if candidate.args.get("with_"):
321
+ used_tables = {t.name.lower() for t in candidate.find_all(exp.Table) if t.name}
322
+ kept_ctes = [c for c in candidate.args["with_"].expressions if c.alias.lower() in used_tables]
323
+ if kept_ctes:
324
+ candidate.args["with_"].set("expressions", kept_ctes)
325
+ else:
326
+ candidate.set("with_", None)
327
+ if _norm_sql(candidate) != _norm_sql(ast2):
328
+ lhs_aliases.add(rhs_alias)
329
+ continue
330
+
331
+ if not _rhs_alias_strictly_unused(ast1, idx, rhs_alias):
332
+ lhs_aliases.add(rhs_alias)
333
+ continue
334
+
335
+ pairs, has_extra = _extract_equi_join_pairs(join, lhs_aliases, rhs_alias)
336
+ rhs_join_cols = {rc for _, _, rc in pairs}
337
+
338
+ if side == "LEFT":
339
+ cert = _rhs_has_unique_key_certificate(rhs, rhs_join_cols, ctes1, schema)
340
+ if cert is not None:
341
+ return VerificationResult(
342
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
343
+ rule_name="A1_dead_left_join_unique_rhs",
344
+ reason=f"Unbounded proof: unused LEFT JOIN '{rhs_alias}' is at-most-1-to-1 by {cert}",
345
+ )
346
+ elif side == "" and kind in ("", "INNER") and not has_extra and pairs:
347
+ cert = _rhs_has_unique_key_certificate(rhs, rhs_join_cols, ctes1, schema)
348
+ if (
349
+ cert is not None
350
+ and isinstance(rhs, exp.Table)
351
+ and isinstance(fc.this, exp.Table)
352
+ and rhs.name.lower() not in ctes1
353
+ and fc.this.name.lower() not in ctes1
354
+ ):
355
+ lspec = _resolve_table_spec(fc.this, schema)
356
+ rspec = _resolve_table_spec(rhs, schema)
357
+ if lspec is not None and rspec is not None and all(la == base_alias for la, _, _ in pairs):
358
+ lcols = tuple(lc for _, lc, _ in pairs)
359
+ rcols = tuple(rc for _, _, rc in pairs)
360
+ # Check FK lspec(lcols) -> rspec(rcols) AND all lcols NOT NULL
361
+ fk_match = any(
362
+ fk.ref_table.lower() == rspec.name.lower()
363
+ and tuple(c.lower() for c in fk.columns) == lcols
364
+ and tuple(c.lower() for c in fk.ref_columns) == rcols
365
+ for fk in lspec.foreign_keys
366
+ )
367
+ if fk_match and all(not lspec.is_nullable(c) for c in lcols):
368
+ return VerificationResult(
369
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
370
+ rule_name="A2_dead_inner_join_with_fk",
371
+ reason=(
372
+ f"Unbounded proof: unused INNER JOIN '{rhs_alias}' is exact 1-to-1 by "
373
+ f"NOT NULL FK {lspec.name}({', '.join(lcols)}) -> {rspec.name}({', '.join(rcols)}) + {cert}"
374
+ ),
375
+ )
376
+
377
+ lhs_aliases.add(rhs_alias)
378
+ return None
379
+
380
+
381
+ def _rule_a3_redundant_distinct(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
382
+ """Rule A3: Unbounded elimination of redundant SELECT DISTINCT (via GROUP BY or NOT NULL UNIQUE key)."""
383
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Select):
384
+ return None
385
+ if not ast1.args.get("distinct") or ast2.args.get("distinct"):
386
+ return None
387
+
388
+ stripped = ast1.copy()
389
+ stripped.set("distinct", None)
390
+ if _norm_sql(stripped) != _norm_sql(ast2):
391
+ return None
392
+
393
+ # A3a: GROUP BY keys are all projected directly in SELECT list
394
+ group = ast1.args.get("group")
395
+ if group is not None and group.expressions:
396
+ proj_sqls = set()
397
+ proj_aliases = set()
398
+ for e in ast1.expressions:
399
+ if isinstance(e, exp.Alias):
400
+ proj_sqls.add(_norm_sql(e.this))
401
+ proj_aliases.add(e.alias.lower())
402
+ else:
403
+ proj_sqls.add(_norm_sql(e))
404
+ if isinstance(e, exp.Column):
405
+ proj_aliases.add(e.name.lower())
406
+ all_gb_projected = True
407
+ for gk in group.expressions:
408
+ if isinstance(gk, exp.Literal) and gk.is_int:
409
+ pos = int(gk.this) - 1
410
+ if not (0 <= pos < len(ast1.expressions)):
411
+ all_gb_projected = False
412
+ break
413
+ elif _norm_sql(gk) not in proj_sqls and not (isinstance(gk, exp.Column) and gk.name.lower() in proj_aliases):
414
+ all_gb_projected = False
415
+ break
416
+ if all_gb_projected:
417
+ return VerificationResult(
418
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
419
+ rule_name="A3a_redundant_distinct_with_group_by",
420
+ reason="Unbounded proof: all GROUP BY keys are projected, so output rows are already unique",
421
+ )
422
+
423
+ # A3b: Single base table (no joins, no GROUP BY) projecting a NOT NULL UNIQUE/PK key
424
+ cte_names = (
425
+ {c.alias.lower() for c in ast1.args["with_"].expressions if c.alias}
426
+ if ast1.args.get("with_")
427
+ else set()
428
+ )
429
+ if group is None and not (ast1.args.get("joins") or []):
430
+ fc = ast1.args.get("from_")
431
+ if fc is not None and isinstance(fc.this, exp.Table) and fc.this.name.lower() not in cte_names:
432
+ tspec = _resolve_table_spec(fc.this, schema)
433
+ if tspec is not None:
434
+ # Extract directly projected bare columns of this table (no expressions/transformations!)
435
+ proj_cols: set[str] = set()
436
+ for e in ast1.expressions:
437
+ if isinstance(e, exp.Star) or (isinstance(e, exp.Column) and isinstance(e.this, exp.Star)):
438
+ proj_cols.update(c.lower() for c in tspec.column_names)
439
+ else:
440
+ target = e.this if isinstance(e, exp.Alias) else e
441
+ if isinstance(target, exp.Column):
442
+ proj_cols.add(target.name.lower())
443
+ uk = tspec.has_non_null_unique_subset(proj_cols)
444
+ if uk is not None:
445
+ return VerificationResult(
446
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
447
+ rule_name="A3b_redundant_distinct_on_non_null_unique_key",
448
+ reason=(
449
+ f"Unbounded proof: projection covers NOT NULL UNIQUE/PK "
450
+ f"{tspec.name}({', '.join(uk)}), so DISTINCT is redundant"
451
+ ),
452
+ )
453
+ return None
454
+
455
+
456
+ def _rule_a4_tides_view_distinct_and_dead_join(
457
+ ast1: exp.Expression, ast2: exp.Expression, schema: Schema
458
+ ) -> VerificationResult | None:
459
+ """Rule A4: Nested SELECT DISTINCT absorption (+ optional dead unique LEFT JOIN, Cal-ITP TIDES pattern)."""
460
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Select):
461
+ return None
462
+ if not ast1.args.get("distinct") or not ast2.args.get("distinct"):
463
+ return None
464
+ if not ast1.args.get("with_"):
465
+ return None
466
+
467
+ ctes = {c.alias.lower(): c for c in ast1.args["with_"].expressions if c.alias}
468
+ fc = ast1.args.get("from_")
469
+ if fc is None or not isinstance(fc.this, exp.Table) or (ast1.args.get("joins") or []):
470
+ return None
471
+ view_name = fc.this.name.lower()
472
+ if view_name not in ctes:
473
+ return None
474
+
475
+ # Unfold a view CTE `V` that is `SELECT ... FROM inner_cte LEFT JOIN rhs_cte ON ...`
476
+ v_sel = ctes[view_name].this
477
+ if not isinstance(v_sel, exp.Select) or v_sel.args.get("group") or v_sel.args.get("where"):
478
+ return None
479
+ v_fc = v_sel.args.get("from_")
480
+ if v_fc is None or not isinstance(v_fc.this, exp.Table):
481
+ return None
482
+ v_lhs_name = v_fc.this.name.lower()
483
+ v_lhs_alias = (v_fc.this.alias or v_fc.this.name).lower()
484
+
485
+ # Check every join in V is a LEFT JOIN whose RHS is unique (via schema or GROUP BY) AND unused by ast1!
486
+ outer_parts = [*ast1.expressions, *([ast1.args["where"]] if ast1.args.get("where") else [])]
487
+ outer_cols = {c.name.lower() for p in outer_parts for c in p.find_all(exp.Column) if c.name}
488
+ if any(isinstance(e, exp.Star) for e in ast1.expressions):
489
+ return None
490
+ # Map view output column -> source alias
491
+ v_col_source: dict[str, str] = {}
492
+ for e in v_sel.expressions:
493
+ if isinstance(e, exp.Star):
494
+ return None
495
+ target = e.this if isinstance(e, exp.Alias) else e
496
+ oname = (e.alias if isinstance(e, exp.Alias) else (target.name if isinstance(target, exp.Column) else "")).lower()
497
+ if isinstance(target, exp.Column) and target.table and oname:
498
+ v_col_source[oname] = target.table.lower()
499
+
500
+ lhs_aliases = {v_lhs_alias}
501
+ for j in v_sel.args.get("joins") or []:
502
+ if (j.side or "").upper() != "LEFT":
503
+ return None
504
+ rhs = j.this
505
+ ralias = (rhs.alias or rhs.name).lower() if isinstance(rhs, exp.Table) else ""
506
+ if not ralias:
507
+ return None
508
+ # Ensure outer query touches NO output column coming from ralias
509
+ if any(v_col_source.get(oc) == ralias for oc in outer_cols):
510
+ return None
511
+ pairs, _ = _extract_equi_join_pairs(j, lhs_aliases, ralias)
512
+ cert = _rhs_has_unique_key_certificate(rhs, {rc for _, _, rc in pairs}, ctes, schema)
513
+ if cert is None:
514
+ return None
515
+ lhs_aliases.add(ralias)
516
+
517
+ # Now verify every outer_col maps cleanly to v_lhs_alias (no renaming surprises)
518
+ if not all(v_col_source.get(oc) == v_lhs_alias for oc in outer_cols):
519
+ return None
520
+
521
+ # Resolve inner source (unwrapping inner SELECT DISTINCT if present!)
522
+ inner_src = ctes[v_lhs_name].this if v_lhs_name in ctes else None
523
+ if isinstance(inner_src, exp.Select) and inner_src.args.get("distinct") and not (inner_src.args.get("joins") or []) and not inner_src.args.get("group") and not inner_src.args.get("where"):
524
+ # Verify inner_src passes through every outer_col unmodified under the same name
525
+ inner_passthrough: set[str] = set()
526
+ inner_has_star = any(isinstance(e, exp.Star) for e in inner_src.expressions)
527
+ if not inner_has_star:
528
+ for ie in inner_src.expressions:
529
+ if isinstance(ie, exp.Column):
530
+ inner_passthrough.add(ie.name.lower())
531
+ elif isinstance(ie, exp.Alias) and isinstance(ie.this, exp.Column) and ie.alias.lower() == ie.this.name.lower():
532
+ inner_passthrough.add(ie.alias.lower())
533
+ if not inner_has_star and not outer_cols.issubset(inner_passthrough):
534
+ return None
535
+ inner_fc = inner_src.args.get("from_")
536
+ if inner_fc is not None and isinstance(inner_fc.this, exp.Table) and inner_fc.this.name.lower() not in ctes:
537
+ # Rewrite ast1 to select directly from inner_fc.this (stripping CTEs, preserving outer alias) and compare with ast2!
538
+ cand = ast1.copy()
539
+ cand.set("with_", None)
540
+ repl_tbl = inner_fc.this.copy()
541
+ if fc.this.args.get("alias"):
542
+ repl_tbl.set("alias", fc.this.args["alias"].copy())
543
+ else:
544
+ repl_tbl.set("alias", None)
545
+ cand.set("from_", exp.From(this=repl_tbl))
546
+ if _norm_sql(cand) == _norm_sql(ast2):
547
+ return VerificationResult(
548
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
549
+ rule_name="A4_view_dead_left_join_and_nested_distinct",
550
+ reason="Unbounded proof: view LEFT JOIN(s) have unique RHS and are unused; inner SELECT DISTINCT is absorbed by outer SELECT DISTINCT",
551
+ )
552
+ return None
553
+
554
+
555
+ def _is_bool_lit(node: exp.Expression, val: bool) -> bool:
556
+ return isinstance(node, exp.Boolean) and bool(node.this) is val
557
+
558
+
559
+ def _is_non_null_literal(node: exp.Expression) -> bool:
560
+ if isinstance(node, (exp.Literal, exp.Boolean)):
561
+ return True
562
+ if isinstance(node, exp.Neg) and isinstance(node.this, exp.Literal):
563
+ return True
564
+ return False
565
+
566
+
567
+ def _coalesce_conjunct_equiv(c1: exp.Expression, c2: exp.Expression, select: exp.Select, schema: Schema) -> str | None:
568
+ """Check if WHERE conjunct c1 is algebraically equivalent to c2 under 3-valued NULL logic."""
569
+ c1, c2 = _strip_parens(c1), _strip_parens(c2)
570
+
571
+ # Pattern 1: COALESCE(col, FALSE) <-> col = TRUE (or COALESCE(col, FALSE) = TRUE <-> col = TRUE)
572
+ co_expr = None
573
+ if isinstance(c1, exp.Coalesce):
574
+ co_expr = c1
575
+ elif isinstance(c1, exp.EQ) and isinstance(c1.this, exp.Coalesce) and _is_bool_lit(c1.expression, True):
576
+ co_expr = c1.this
577
+ if co_expr is not None and len(co_expr.expressions) == 1:
578
+ col, default = co_expr.this, co_expr.expressions[0]
579
+ if isinstance(col, exp.Column) and _is_bool_lit(default, False):
580
+ if _resolve_column_dtype(col, select, schema) == "BOOL":
581
+ if (
582
+ isinstance(c2, exp.EQ)
583
+ and _norm_sql(c2.this) == _norm_sql(col)
584
+ and _is_bool_lit(c2.expression, True)
585
+ ) or _norm_sql(c2) == _norm_sql(col):
586
+ return "COALESCE(bool_col, FALSE) <-> bool_col = TRUE (3-valued NULL exact)"
587
+
588
+ # Pattern 2: COALESCE(col, lit) <> lit <-> col <> lit
589
+ if isinstance(c1, exp.NEQ) and isinstance(c1.this, exp.Coalesce) and len(c1.this.expressions) == 1:
590
+ col, default = c1.this.this, c1.this.expressions[0]
591
+ rhs = c1.expression
592
+ if isinstance(col, exp.Column) and _is_non_null_literal(default) and _norm_sql(default) == _norm_sql(rhs):
593
+ if (
594
+ isinstance(c2, exp.NEQ)
595
+ and _norm_sql(c2.this) == _norm_sql(col)
596
+ and _norm_sql(c2.expression) == _norm_sql(rhs)
597
+ ):
598
+ return f"COALESCE({col.sql()}, {rhs.sql()}) <> {rhs.sql()} <-> {col.sql()} <> {rhs.sql()} (3-valued NULL exact)"
599
+
600
+ # Pattern 3: NOT COALESCE(col, FALSE) <-> (col = FALSE OR col IS NULL) [or col = FALSE iff NOT NULL]
601
+ if isinstance(c1, exp.Not) and isinstance(_strip_parens(c1.this), exp.Coalesce):
602
+ co = _strip_parens(c1.this)
603
+ if len(co.expressions) == 1 and isinstance(co.this, exp.Column) and _is_bool_lit(co.expressions[0], False):
604
+ col = co.this
605
+ if _resolve_column_dtype(col, select, schema) == "BOOL":
606
+ col_s = _norm_sql(col)
607
+ if isinstance(c2, exp.Or):
608
+ parts = {_norm_sql(_strip_parens(c2.this)), _norm_sql(_strip_parens(c2.expression))}
609
+ if parts == {f"{col_s} = false", f"{col_s} is null"}:
610
+ return f"NOT COALESCE({col.sql()}, FALSE) <-> ({col.sql()} = FALSE OR {col.sql()} IS NULL)"
611
+ if isinstance(c2, exp.EQ) and _norm_sql(c2.this) == col_s and _is_bool_lit(c2.expression, False):
612
+ if _resolve_column_nullable(col, select, schema) is False:
613
+ return f"NOT COALESCE({col.sql()}, FALSE) <-> {col.sql()} = FALSE (verified NOT NULL in schema)"
614
+
615
+ # Pattern 4: COALESCE(col, lit) = lit <-> (col = lit OR col IS NULL) [or col = lit iff NOT NULL]
616
+ if isinstance(c1, exp.EQ) and isinstance(c1.this, exp.Coalesce) and len(c1.this.expressions) == 1:
617
+ col, default = c1.this.this, c1.this.expressions[0]
618
+ rhs = c1.expression
619
+ if isinstance(col, exp.Column) and _is_non_null_literal(default) and _norm_sql(default) == _norm_sql(rhs):
620
+ col_s, lit_s = _norm_sql(col), _norm_sql(rhs)
621
+ if isinstance(c2, exp.Or):
622
+ parts = {_norm_sql(_strip_parens(c2.this)), _norm_sql(_strip_parens(c2.expression))}
623
+ if parts == {f"{col_s} = {lit_s}", f"{col_s} is null"}:
624
+ return f"COALESCE({col.sql()}, {rhs.sql()}) = {rhs.sql()} <-> ({col.sql()} = {rhs.sql()} OR {col.sql()} IS NULL)"
625
+ if isinstance(c2, exp.EQ) and _norm_sql(c2.this) == col_s and _norm_sql(c2.expression) == lit_s:
626
+ if _resolve_column_nullable(col, select, schema) is False:
627
+ return f"COALESCE({col.sql()}, {rhs.sql()}) = {rhs.sql()} <-> {col.sql()} = {rhs.sql()} (verified NOT NULL in schema)"
628
+
629
+ return None
630
+
631
+
632
+ def _rule_a5_coalesce_where_unwrap(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
633
+ """Rule A5: Unbounded 3-valued-NULL-safe COALESCE unwrapping in WHERE."""
634
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Select):
635
+ return None
636
+ w1, w2 = ast1.args.get("where"), ast2.args.get("where")
637
+ if w1 is None or w2 is None:
638
+ return None
639
+ # Verify everything outside WHERE is identical
640
+ s1, s2 = ast1.copy(), ast2.copy()
641
+ s1.set("where", None)
642
+ s2.set("where", None)
643
+ if _norm_sql(s1) != _norm_sql(s2):
644
+ return None
645
+
646
+ c1s = _split_conjuncts(w1.this)
647
+ c2s = _split_conjuncts(w2.this)
648
+ if len(c1s) != len(c2s):
649
+ return None
650
+
651
+ reasons: list[str] = []
652
+ for a, b in zip(c1s, c2s):
653
+ if _norm_sql(a) == _norm_sql(b):
654
+ continue
655
+ r = _coalesce_conjunct_equiv(a, b, ast1, schema) or _coalesce_conjunct_equiv(b, a, ast2, schema)
656
+ if r is None:
657
+ return None
658
+ reasons.append(r)
659
+
660
+ if reasons:
661
+ return VerificationResult(
662
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
663
+ rule_name="A5_coalesce_where_unwrap",
664
+ reason=f"Unbounded proof: {'; '.join(reasons)}",
665
+ )
666
+ return None
667
+
668
+
669
+ _NEG_CMP_MAP = {
670
+ exp.GTE: exp.LT,
671
+ exp.GT: exp.LTE,
672
+ exp.LTE: exp.GT,
673
+ exp.LT: exp.GTE,
674
+ exp.EQ: exp.NEQ,
675
+ exp.NEQ: exp.EQ,
676
+ }
677
+
678
+
679
+ def _negated_atomic_cmp(p: exp.Expression) -> tuple[exp.Column, exp.Expression] | None:
680
+ p = _strip_parens(p)
681
+ for cls, neg_cls in _NEG_CMP_MAP.items():
682
+ if isinstance(p, cls) and isinstance(p.this, exp.Column):
683
+ rhs = p.expression
684
+ if _is_non_null_literal(rhs) or (isinstance(rhs, exp.Cast) and _is_non_null_literal(rhs.this)):
685
+ return p.this, neg_cls(this=p.this.copy(), expression=rhs.copy())
686
+ return None
687
+
688
+
689
+ def _rule_a6_or_to_disjoint_union_all(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
690
+ """Rule A6: SELECT ... FROM T WHERE P OR Q <-> branch(P) UNION ALL branch(Q AND (neg(P) OR col IS NULL))."""
691
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Union):
692
+ return None
693
+ if ast2.args.get("distinct", True):
694
+ return None # Must be UNION ALL
695
+ if ast1.args.get("distinct") or ast1.args.get("group") or ast1.args.get("having") or ast1.args.get("qualify"):
696
+ return None
697
+ if any(isinstance(n, (exp.AggFunc, exp.Window)) for n in ast1.walk()):
698
+ return None
699
+ w1 = ast1.args.get("where")
700
+ if w1 is None:
701
+ return None
702
+ w_expr = _strip_parens(w1.this)
703
+ if not isinstance(w_expr, exp.Or):
704
+ return None
705
+
706
+ b1, b2 = ast2.this, ast2.expression
707
+ if not isinstance(b1, exp.Select) or not isinstance(b2, exp.Select):
708
+ return None
709
+ # Base SELECT shape (everything except WHERE) must match identically across ast1, b1, b2
710
+ base0, base1, base2 = ast1.copy(), b1.copy(), b2.copy()
711
+ base0.set("where", None)
712
+ base1.set("where", None)
713
+ base2.set("where", None)
714
+ if not (_norm_sql(base0) == _norm_sql(base1) == _norm_sql(base2)):
715
+ return None
716
+ if b1.args.get("where") is None or b2.args.get("where") is None:
717
+ return None
718
+
719
+ p_expr = _strip_parens(w_expr.this)
720
+ q_expr = _strip_parens(w_expr.expression)
721
+ # Branch 1 must be WHERE P
722
+ if _norm_sql(_strip_parens(b1.args["where"].this)) != _norm_sql(p_expr):
723
+ return None
724
+
725
+ neg_info = _negated_atomic_cmp(p_expr)
726
+ if neg_info is None:
727
+ return None
728
+ p_col, neg_p = neg_info
729
+
730
+ # Branch 2 must be WHERE Q AND <guard>
731
+ b2_conjs = _split_conjuncts(b2.args["where"].this)
732
+ q_conjs = _split_conjuncts(q_expr)
733
+ q_norm = [_norm_sql(c) for c in q_conjs]
734
+ b2_norm = [_norm_sql(c) for c in b2_conjs]
735
+ # Remove q_conjs from b2_conjs; remaining conjunct must be the exact disjointness guard!
736
+ rem: list[exp.Expression] = []
737
+ q_rem = list(q_norm)
738
+ for c, cn in zip(b2_conjs, b2_norm):
739
+ if cn in q_rem:
740
+ q_rem.remove(cn)
741
+ else:
742
+ rem.append(_strip_parens(c))
743
+ if q_rem or len(rem) != 1:
744
+ return None
745
+
746
+ guard = rem[0]
747
+ neg_s = _norm_sql(neg_p)
748
+ null_s = f"{_norm_sql(p_col)} is null"
749
+ if isinstance(guard, exp.Or):
750
+ g_parts = {_norm_sql(_strip_parens(guard.this)), _norm_sql(_strip_parens(guard.expression))}
751
+ if g_parts == {neg_s, null_s}:
752
+ return VerificationResult(
753
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
754
+ rule_name="A6_or_to_disjoint_union_all",
755
+ reason=f"Unbounded proof: OR split into disjoint UNION ALL with exact 3-valued NULL guard ({neg_p.sql()} OR {p_col.sql()} IS NULL)",
756
+ )
757
+ if _norm_sql(guard) == neg_s:
758
+ if _resolve_column_nullable(p_col, ast1, schema) is False:
759
+ return VerificationResult(
760
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
761
+ rule_name="A6_or_to_disjoint_union_all_not_null",
762
+ reason=f"Unbounded proof: OR split into disjoint UNION ALL with guard ({neg_p.sql()}) verified NOT NULL in schema",
763
+ )
764
+ return None
765
+
766
+
767
+ def _next_month_start(year: int, month: int) -> dt.datetime:
768
+ if month == 12:
769
+ return dt.datetime(year + 1, 1, 1, 0, 0, 0)
770
+ return dt.datetime(year, month + 1, 1, 0, 0, 0)
771
+
772
+
773
+ def _extract_ts_literal(node: exp.Expression) -> dt.datetime | None:
774
+ if isinstance(node, exp.Cast) and isinstance(node.this, exp.Literal) and node.this.is_string:
775
+ raw = str(node.this.this).strip().replace("T", " ")
776
+ if raw.endswith("Z"):
777
+ raw = raw[:-1]
778
+ elif raw.upper().endswith(" UTC"):
779
+ raw = raw[:-4]
780
+ try:
781
+ if len(raw) == 10:
782
+ return dt.datetime.fromisoformat(raw + " 00:00:00")
783
+ parsed = dt.datetime.fromisoformat(raw)
784
+ if parsed.microsecond == 0:
785
+ return parsed
786
+ except ValueError:
787
+ return None
788
+ return None
789
+
790
+
791
+ def _parse_date_extractor_window(conjs: list[exp.Expression]) -> tuple[str, dt.datetime | None, dt.datetime | None, str] | None:
792
+ """Recognize EXTRACT(YEAR/MONTH[/DAY]), STRFTIME('%Y-%m'), or DATE_TRUNC('day', col) predicates
793
+ and compute their exact mathematically equivalent half-open timestamp interval [lo, hi)."""
794
+ # 1. STRFTIME(col, '%Y-%m') = 'YYYY-MM' or FORMAT_TIMESTAMP('%Y-%m', col) = 'YYYY-MM'
795
+ if len(conjs) == 1 and isinstance(conjs[0], exp.EQ):
796
+ eq = conjs[0]
797
+ lhs, rhs = eq.this, eq.expression
798
+ if isinstance(rhs, exp.Literal) and rhs.is_string:
799
+ val = str(rhs.this).strip()
800
+ m_ym = re.fullmatch(r"(\d{4})-(\d{2})", val)
801
+ if m_ym and isinstance(lhs, (exp.TimeToStr, exp.Anonymous)):
802
+ fmt_node = lhs.args.get("format") if isinstance(lhs, exp.TimeToStr) else None
803
+ col_node = lhs.this if isinstance(lhs, exp.TimeToStr) else None
804
+ fmt_str = str(fmt_node.this) if isinstance(fmt_node, exp.Literal) else ""
805
+ if isinstance(lhs, exp.Anonymous) and lhs.name.upper() in ("STRFTIME", "FORMAT_TIMESTAMP", "FORMAT_DATE"):
806
+ args = list(lhs.expressions)
807
+ if len(args) == 2:
808
+ if isinstance(args[0], exp.Column) and isinstance(args[1], exp.Literal):
809
+ col_node, fmt_str = args[0], str(args[1].this)
810
+ elif isinstance(args[1], exp.Column) and isinstance(args[0], exp.Literal):
811
+ col_node, fmt_str = args[1], str(args[0].this)
812
+ if isinstance(col_node, exp.Column) and fmt_str == "%Y-%m":
813
+ y, mo = int(m_ym.group(1)), int(m_ym.group(2))
814
+ if 1 <= mo <= 12:
815
+ return _norm_sql(col_node), dt.datetime(y, mo, 1, 0, 0, 0), _next_month_start(y, mo), f"STRFTIME({col_node.sql()}, '%Y-%m') = '{val}'"
816
+
817
+ # 2. DATE_TRUNC('day', col) >= / <= / = TIMESTAMP 'YYYY-MM-DD 00:00:00'
818
+ if len(conjs) == 1 and isinstance(conjs[0], (exp.GTE, exp.LTE, exp.EQ, exp.GT, exp.LT)):
819
+ cmp = conjs[0]
820
+ if isinstance(cmp.this, (exp.TimestampTrunc, exp.DateTrunc)) and isinstance(cmp.this.this, exp.Column):
821
+ unit = (cmp.this.args.get("unit").name if cmp.this.args.get("unit") is not None else "").upper()
822
+ ts = _extract_ts_literal(cmp.expression)
823
+ if unit == "DAY" and ts is not None and ts.hour == 0 and ts.minute == 0 and ts.second == 0:
824
+ col_s = _norm_sql(cmp.this.this)
825
+ next_day = ts + dt.timedelta(days=1)
826
+ if isinstance(cmp, exp.GTE):
827
+ return col_s, ts, None, f"DATE_TRUNC('day', {cmp.this.this.sql()}) >= {ts}"
828
+ if isinstance(cmp, exp.LT):
829
+ return col_s, None, ts, f"DATE_TRUNC('day', {cmp.this.this.sql()}) < {ts}"
830
+ if isinstance(cmp, exp.LTE):
831
+ return col_s, None, next_day, f"DATE_TRUNC('day', {cmp.this.this.sql()}) <= {ts}"
832
+ if isinstance(cmp, exp.GT):
833
+ return col_s, next_day, None, f"DATE_TRUNC('day', {cmp.this.this.sql()}) > {ts}"
834
+ if isinstance(cmp, exp.EQ):
835
+ return col_s, ts, next_day, f"DATE_TRUNC('day', {cmp.this.this.sql()}) = {ts}"
836
+
837
+ # 3. EXTRACT(YEAR FROM col) = Y AND EXTRACT(MONTH FROM col) = M [AND EXTRACT(DAY FROM col) >= D]
838
+ year_v: int | None = None
839
+ month_v: int | None = None
840
+ day_gte: int | None = None
841
+ day_eq: int | None = None
842
+ col_s: str | None = None
843
+ for c in conjs:
844
+ if not isinstance(c, (exp.EQ, exp.GTE)):
845
+ return None
846
+ if not isinstance(c.this, exp.Extract) or not isinstance(c.expression, exp.Literal) or not c.expression.is_int:
847
+ return None
848
+ part = c.this.this.name.upper() if c.this.this is not None else ""
849
+ target_col = c.this.expression
850
+ if not isinstance(target_col, exp.Column):
851
+ return None
852
+ cs = _norm_sql(target_col)
853
+ if col_s is None:
854
+ col_s = cs
855
+ elif col_s != cs:
856
+ return None
857
+ iv = int(c.expression.this)
858
+ if part == "YEAR" and isinstance(c, exp.EQ):
859
+ year_v = iv
860
+ elif part == "MONTH" and isinstance(c, exp.EQ):
861
+ month_v = iv
862
+ elif part == "DAY" and isinstance(c, exp.GTE):
863
+ day_gte = iv
864
+ elif part == "DAY" and isinstance(c, exp.EQ):
865
+ day_eq = iv
866
+ else:
867
+ return None
868
+
869
+ if col_s is not None and year_v is not None:
870
+ try:
871
+ if month_v is None and day_gte is None and day_eq is None:
872
+ return col_s, dt.datetime(year_v, 1, 1, 0, 0, 0), dt.datetime(year_v + 1, 1, 1, 0, 0, 0), f"EXTRACT(YEAR) = {year_v}"
873
+ if month_v is not None and 1 <= month_v <= 12:
874
+ hi = _next_month_start(year_v, month_v)
875
+ if day_eq is not None:
876
+ lo = dt.datetime(year_v, month_v, day_eq, 0, 0, 0)
877
+ return col_s, lo, lo + dt.timedelta(days=1), f"EXTRACT(Y/M/D) = {year_v}-{month_v:02d}-{day_eq:02d}"
878
+ start_day = day_gte if day_gte is not None else 1
879
+ lo = dt.datetime(year_v, month_v, start_day, 0, 0, 0)
880
+ return col_s, lo, hi, f"EXTRACT(YEAR={year_v}, MONTH={month_v}, DAY>={start_day})"
881
+ except ValueError:
882
+ return None
883
+ return None
884
+
885
+
886
+ def _parse_direct_range_window(conjs: list[exp.Expression]) -> tuple[str, dt.datetime | None, dt.datetime | None] | None:
887
+ lo: dt.datetime | None = None
888
+ hi: dt.datetime | None = None
889
+ col_s: str | None = None
890
+ for c in conjs:
891
+ if not isinstance(c, (exp.GTE, exp.LT)) or not isinstance(c.this, exp.Column):
892
+ return None
893
+ ts = _extract_ts_literal(c.expression)
894
+ if ts is None:
895
+ return None
896
+ cs = _norm_sql(c.this)
897
+ if col_s is None:
898
+ col_s = cs
899
+ elif col_s != cs:
900
+ return None
901
+ if isinstance(c, exp.GTE) and lo is None:
902
+ lo = ts
903
+ elif isinstance(c, exp.LT) and hi is None:
904
+ hi = ts
905
+ else:
906
+ return None
907
+ if col_s is None or (lo is None and hi is None):
908
+ return None
909
+ return col_s, lo, hi
910
+
911
+
912
+ def _rule_a7_date_extractor_to_range(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
913
+ """Rule A7: Unbounded equivalence of calendar date/timestamp extractors <-> exact half-open [lo, hi) range."""
914
+ if not isinstance(ast1, exp.Select) or not isinstance(ast2, exp.Select):
915
+ return None
916
+ w1, w2 = ast1.args.get("where"), ast2.args.get("where")
917
+ if w1 is None or w2 is None:
918
+ return None
919
+ s1, s2 = ast1.copy(), ast2.copy()
920
+ s1.set("where", None)
921
+ s2.set("where", None)
922
+ if _norm_sql(s1) != _norm_sql(s2):
923
+ return None
924
+
925
+ c1s = _split_conjuncts(w1.this)
926
+ c2s = _split_conjuncts(w2.this)
927
+ # Remove identical shared conjuncts so extra WHERE filters don't block the rule
928
+ c2_norm = [_norm_sql(c) for c in c2s]
929
+ rem1: list[exp.Expression] = []
930
+ rem2_idx = list(range(len(c2s)))
931
+ for c in c1s:
932
+ cn = _norm_sql(c)
933
+ match_i = next((i for i in rem2_idx if c2_norm[i] == cn), None)
934
+ if match_i is not None:
935
+ rem2_idx.remove(match_i)
936
+ else:
937
+ rem1.append(c)
938
+ rem2 = [c2s[i] for i in rem2_idx]
939
+ if not rem1 or not rem2:
940
+ return None
941
+
942
+ ext = _parse_date_extractor_window(rem1)
943
+ rng = _parse_direct_range_window(rem2)
944
+ if ext is not None and rng is not None:
945
+ ec, elo, ehi, desc = ext
946
+ rc, rlo, rhi = rng
947
+ if ec == rc and elo == rlo and ehi == rhi:
948
+ # Verify column is DATE/TIMESTAMP in schema
949
+ col_node = next((c for c in rem2[0].find_all(exp.Column) if _norm_sql(c) == rc), None)
950
+ if col_node is not None and _resolve_column_dtype(col_node, ast1, schema) in ("TIMESTAMP", "DATE"):
951
+ return VerificationResult(
952
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
953
+ rule_name="A7_date_extractor_to_range",
954
+ reason=f"Unbounded proof: {desc} <-> exact half-open interval [{rlo}, {rhi})",
955
+ )
956
+ return None
957
+
958
+
959
+ def _rule_a8_repeated_source_union_all_cross_join(
960
+ ast1: exp.Expression, ast2: exp.Expression, schema: Schema
961
+ ) -> VerificationResult | None:
962
+ """Rule A8: Unbounded bag equivalence of 2x UNION ALL over identical source R <-> single scan R CROSS JOIN VALUES(0),(1)."""
963
+ if not isinstance(ast1, exp.Union) or not isinstance(ast2, exp.Select):
964
+ return None
965
+ if ast1.args.get("distinct", True):
966
+ return None
967
+ b1, b2 = ast1.this, ast1.expression
968
+ if not isinstance(b1, exp.Select) or not isinstance(b2, exp.Select):
969
+ return None
970
+ # Both branches must be plain projections from the exact same table/CTE with no joins/where/group/distinct/agg/window
971
+ for br in (b1, b2):
972
+ if br.args.get("joins") or br.args.get("where") or br.args.get("group") or br.args.get("having") or br.args.get("distinct") or br.args.get("qualify"):
973
+ return None
974
+ if any(isinstance(n, (exp.AggFunc, exp.Window)) for n in br.walk()):
975
+ return None
976
+ f1, f2 = b1.args.get("from_"), b2.args.get("from_")
977
+ if not (f1 and f2 and isinstance(f1.this, exp.Table) and isinstance(f2.this, exp.Table)):
978
+ return None
979
+ if f1.this.name.lower() != f2.this.name.lower():
980
+ return None
981
+ if len(b1.expressions) != len(b2.expressions) or not b1.expressions:
982
+ return None
983
+
984
+ # Check ast2 has identical WITH clause (if any), same FROM table, and exactly 1 CROSS JOIN VALUES with 2 distinct rows
985
+ w1, w2 = ast1.args.get("with_"), ast2.args.get("with_")
986
+ if (w1 is None) != (w2 is None):
987
+ return None
988
+ if w1 is not None and w2 is not None and _norm_sql(w1) != _norm_sql(w2):
989
+ return None
990
+ f_out = ast2.args.get("from_")
991
+ if not (f_out and isinstance(f_out.this, exp.Table) and f_out.this.name.lower() == f1.this.name.lower()):
992
+ return None
993
+ if ast2.args.get("where") or ast2.args.get("group") or ast2.args.get("having") or ast2.args.get("distinct") or ast2.args.get("qualify"):
994
+ return None
995
+ j_out = list(ast2.args.get("joins") or [])
996
+ if len(j_out) != 1 or (j_out[0].kind or "").upper() != "CROSS" or (j_out[0].side or "") != "":
997
+ return None
998
+ val_node = j_out[0].this
999
+ v0: exp.Expression | None = None
1000
+ v1: exp.Expression | None = None
1001
+ val_tbl = ""
1002
+ val_col = ""
1003
+ if isinstance(val_node, exp.Subquery) and isinstance(val_node.this, exp.Values):
1004
+ val_alias_node = val_node.args.get("alias")
1005
+ val_node = val_node.this
1006
+ elif isinstance(val_node, exp.Subquery) and isinstance(val_node.this, exp.Select):
1007
+ # Snowflake idiomatic form: (SELECT column1 AS _branch FROM VALUES (0), (1)) AS _s
1008
+ sub_sel = val_node.this
1009
+ sub_from = sub_sel.args.get("from_")
1010
+ sub_val = sub_from.this if sub_from is not None else None
1011
+ if isinstance(sub_val, exp.Subquery):
1012
+ sub_val = sub_val.this
1013
+ if (
1014
+ isinstance(sub_val, exp.Values)
1015
+ and len(sub_val.expressions) == 2
1016
+ and len(sub_sel.expressions) == 1
1017
+ and not (sub_sel.args.get("joins") or [])
1018
+ and sub_sel.args.get("where") is None
1019
+ and sub_sel.args.get("group") is None
1020
+ and sub_sel.args.get("distinct") is None
1021
+ ):
1022
+ t0, t1 = sub_val.expressions[0], sub_val.expressions[1]
1023
+ v0 = t0.expressions[0] if isinstance(t0, exp.Tuple) and len(t0.expressions) == 1 else None
1024
+ v1 = t1.expressions[0] if isinstance(t1, exp.Tuple) and len(t1.expressions) == 1 else None
1025
+ proj0 = sub_sel.expressions[0]
1026
+ if isinstance(proj0, exp.Alias) and proj0.alias:
1027
+ val_col = proj0.alias.lower()
1028
+ elif isinstance(proj0, exp.Column) and proj0.name:
1029
+ val_col = proj0.name.lower()
1030
+ sub_alias = val_node.args.get("alias")
1031
+ if isinstance(sub_alias, exp.TableAlias) and sub_alias.name:
1032
+ val_tbl = sub_alias.name.lower()
1033
+ val_alias_node = None
1034
+ elif isinstance(val_node, exp.Values):
1035
+ val_alias_node = val_node.args.get("alias")
1036
+ elif isinstance(val_node, exp.Unnest) and len(val_node.expressions) == 1 and isinstance(val_node.expressions[0], exp.Array):
1037
+ arr = val_node.expressions[0]
1038
+ if len(arr.expressions) == 2 and all(isinstance(s, exp.Struct) and len(s.expressions) == 1 and isinstance(s.expressions[0], exp.PropertyEQ) for s in arr.expressions):
1039
+ p0, p1 = arr.expressions[0].expressions[0], arr.expressions[1].expressions[0]
1040
+ if p0.this.name.lower() == p1.this.name.lower():
1041
+ v0, v1 = p0.expression, p1.expression
1042
+ val_col = p0.this.name.lower()
1043
+ ua = val_node.args.get("alias")
1044
+ if isinstance(ua, exp.TableAlias):
1045
+ val_tbl = (ua.name or (ua.columns[0].name if ua.columns else "")).lower()
1046
+ elif len(arr.expressions) == 2 and all(_is_non_null_literal(x) for x in arr.expressions):
1047
+ # BigQuery idiomatic form: CROSS JOIN UNNEST([0, 1]) AS _branch
1048
+ v0, v1 = arr.expressions[0], arr.expressions[1]
1049
+ ua = val_node.args.get("alias")
1050
+ if isinstance(ua, exp.TableAlias):
1051
+ col_ident = (ua.columns[0].name if ua.columns else ua.name) or ""
1052
+ val_col = col_ident.lower()
1053
+ val_tbl = (ua.name or "").lower()
1054
+ val_alias_node = None
1055
+ else:
1056
+ return None
1057
+
1058
+ if isinstance(val_node, exp.Values):
1059
+ if len(val_node.expressions) != 2:
1060
+ return None
1061
+ t0, t1 = val_node.expressions[0], val_node.expressions[1]
1062
+ v0 = t0.expressions[0] if isinstance(t0, exp.Tuple) and len(t0.expressions) == 1 else None
1063
+ v1 = t1.expressions[0] if isinstance(t1, exp.Tuple) and len(t1.expressions) == 1 else None
1064
+ if not (isinstance(val_alias_node, exp.TableAlias) and val_alias_node.name and len(val_alias_node.columns) == 1):
1065
+ return None
1066
+ val_tbl = val_alias_node.name.lower()
1067
+ val_col = val_alias_node.columns[0].name.lower()
1068
+
1069
+ if v0 is None or v1 is None or not val_col or not (_is_non_null_literal(v0) and _is_non_null_literal(v1)) or _norm_sql(v0) == _norm_sql(v1):
1070
+ return None
1071
+
1072
+ if len(ast2.expressions) != len(b1.expressions):
1073
+ return None
1074
+
1075
+ # Verify each output column i in ast2 evaluates to e1_i when tag == v0 and e2_i when tag == v1
1076
+ def _strip_alias_prefix(expr: exp.Expression, tbl_aliases: set[str]) -> str:
1077
+ c = expr.copy()
1078
+ for col in c.find_all(exp.Column):
1079
+ if col.table and col.table.lower() in tbl_aliases:
1080
+ col.set("table", None)
1081
+ return _norm_sql(c)
1082
+
1083
+ src_aliases = {
1084
+ f1.this.name.lower(),
1085
+ (f1.this.alias or f1.this.name).lower(),
1086
+ (f2.this.alias or f2.this.name).lower(),
1087
+ (f_out.this.alias or f_out.this.name).lower(),
1088
+ }
1089
+
1090
+ for e1, e2, eo in zip(b1.expressions, b2.expressions, ast2.expressions):
1091
+ t1_e = e1.this if isinstance(e1, exp.Alias) else e1
1092
+ t2_e = e2.this if isinstance(e2, exp.Alias) else e2
1093
+ to_e = eo.this if isinstance(eo, exp.Alias) else eo
1094
+ s1 = _strip_alias_prefix(t1_e, src_aliases)
1095
+ s2 = _strip_alias_prefix(t2_e, src_aliases)
1096
+ so = _strip_alias_prefix(to_e, src_aliases)
1097
+ if s1 == s2 == so:
1098
+ continue
1099
+ # Check direct tag column reference (e.g. `s.tx_type` when e1 = 'debit' and e2 = 'credit')
1100
+ if isinstance(to_e, exp.Column) and (to_e.table or "").lower() in ("", val_tbl) and to_e.name.lower() == val_col:
1101
+ if _norm_sql(t1_e) == _norm_sql(v0) and _norm_sql(t2_e) == _norm_sql(v1):
1102
+ continue
1103
+ return None
1104
+ # Check CASE WHEN tag = v0 THEN e1 ELSE e2 END
1105
+ if isinstance(to_e, exp.Case) and to_e.this is None and len(to_e.args.get("ifs") or []) == 1 and to_e.args.get("default") is not None:
1106
+ if_n = to_e.args["ifs"][0]
1107
+ cond = _strip_parens(if_n.this)
1108
+ if isinstance(cond, exp.EQ) and isinstance(cond.this, exp.Column) and (cond.this.table or "").lower() in ("", val_tbl) and cond.this.name.lower() == val_col:
1109
+ then_s = _strip_alias_prefix(if_n.args["true"], src_aliases)
1110
+ else_s = _strip_alias_prefix(to_e.args["default"], src_aliases)
1111
+ if _norm_sql(cond.expression) == _norm_sql(v0) and then_s == s1 and else_s == s2:
1112
+ continue
1113
+ if _norm_sql(cond.expression) == _norm_sql(v1) and then_s == s2 and else_s == s1:
1114
+ continue
1115
+ return None
1116
+
1117
+ return VerificationResult(
1118
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
1119
+ rule_name="A8_repeated_source_union_all_cross_join",
1120
+ reason=f"Unbounded proof: 2x UNION ALL over '{f1.this.name}' is bag-equivalent to single scan CROSS JOIN 2-row VALUES",
1121
+ )
1122
+
1123
+
1124
+ def _flatten_union_all(node: exp.Expression) -> list[exp.Select] | None:
1125
+ if isinstance(node, exp.Select):
1126
+ return [node]
1127
+ if isinstance(node, exp.Union) and not node.args.get("distinct", True):
1128
+ l = _flatten_union_all(node.this)
1129
+ r = _flatten_union_all(node.expression)
1130
+ if l is not None and r is not None:
1131
+ return l + r
1132
+ return None
1133
+
1134
+
1135
+ def _rule_a9_disjoint_union_all_group_by_collapse(
1136
+ ast1: exp.Expression, ast2: exp.Expression, schema: Schema
1137
+ ) -> VerificationResult | None:
1138
+ """Rule A9: M-branch UNION ALL over same table with disjoint `col = lit_i` filters + GROUP BY -> single pass."""
1139
+ branches = _flatten_union_all(ast1)
1140
+ if branches is None or len(branches) < 2 or not isinstance(ast2, exp.Select):
1141
+ return None
1142
+ if ast1.args.get("with_") or ast2.args.get("with_"):
1143
+ return None
1144
+ if ast2.args.get("joins") or ast2.args.get("having") or ast2.args.get("distinct") or ast2.args.get("qualify"):
1145
+ return None
1146
+ if ast2.args.get("group") is None or ast2.args.get("where") is None:
1147
+ return None
1148
+
1149
+ # Every branch must scan the exact same base table with no joins/having/distinct/qualify and identical GROUP BY keys
1150
+ f_out = ast2.args.get("from_")
1151
+ if not (f_out and isinstance(f_out.this, exp.Table)):
1152
+ return None
1153
+ base_tbl = f_out.this.name.lower()
1154
+ if not schema.has_table(base_tbl):
1155
+ return None
1156
+
1157
+ base_gb: list[str] | None = None
1158
+ branch_tags: list[tuple[str, str, list[exp.Expression]]] = [] # (disc_col, disc_lit_sql, extra_conjs)
1159
+ disc_col_name: str | None = None
1160
+ branch_outputs: list[tuple[exp.Expression, list[exp.Expression]]] = [] # (tag_lit, other_exprs)
1161
+
1162
+ for br in branches:
1163
+ if br.args.get("joins") or br.args.get("having") or br.args.get("distinct") or br.args.get("qualify"):
1164
+ return None
1165
+ bf = br.args.get("from_")
1166
+ if not (bf and isinstance(bf.this, exp.Table) and bf.this.name.lower() == base_tbl):
1167
+ return None
1168
+ if br.args.get("group") is None or br.args.get("where") is None:
1169
+ return None
1170
+ gb_s = [_norm_sql(g) for g in br.args["group"].expressions]
1171
+ if base_gb is None:
1172
+ base_gb = gb_s
1173
+ elif gb_s != base_gb:
1174
+ return None
1175
+ if len(br.expressions) != len(ast2.expressions):
1176
+ return None
1177
+
1178
+ # Find which single column is compared with `col = distinct_lit_i` across every branch!
1179
+ all_conjs = [_split_conjuncts(br.args["where"].this) for br in branches]
1180
+ cand_cols = {
1181
+ _norm_sql(c.this)
1182
+ for c in all_conjs[0]
1183
+ if isinstance(c, exp.EQ) and isinstance(c.this, exp.Column) and _is_non_null_literal(c.expression)
1184
+ }
1185
+ chosen_col: str | None = None
1186
+ chosen_lits: list[str] = []
1187
+ shared_extra: list[str] | None = None
1188
+
1189
+ for cc in sorted(cand_cols):
1190
+ lits: list[str] = []
1191
+ extras_list: list[list[str]] = []
1192
+ ok = True
1193
+ for conjs in all_conjs:
1194
+ matched_lit = None
1195
+ ext: list[str] = []
1196
+ for c in conjs:
1197
+ if isinstance(c, exp.EQ) and isinstance(c.this, exp.Column) and _norm_sql(c.this) == cc and _is_non_null_literal(c.expression) and matched_lit is None:
1198
+ matched_lit = _norm_sql(c.expression)
1199
+ else:
1200
+ ext.append(_norm_sql(c))
1201
+ if matched_lit is None:
1202
+ ok = False
1203
+ break
1204
+ lits.append(matched_lit)
1205
+ extras_list.append(sorted(ext))
1206
+ if ok and len(set(lits)) == len(lits) and all(e == extras_list[0] for e in extras_list):
1207
+ chosen_col = cc
1208
+ chosen_lits = lits
1209
+ shared_extra = extras_list[0]
1210
+ break
1211
+
1212
+ if chosen_col is None or shared_extra is None or base_gb is None:
1213
+ return None
1214
+
1215
+ # Verify ast2 GROUP BY is base_gb + [chosen_col] (order-insensitive)
1216
+ gb2 = [_norm_sql(g) for g in ast2.args["group"].expressions]
1217
+ if sorted(gb2) != sorted([*base_gb, chosen_col]):
1218
+ return None
1219
+
1220
+ # Verify ast2 WHERE is `chosen_col IN (chosen_lits)` + shared_extra
1221
+ w2_conjs = _split_conjuncts(ast2.args["where"].this)
1222
+ in_matched = False
1223
+ w2_extras: list[str] = []
1224
+ for c in w2_conjs:
1225
+ if isinstance(c, exp.In) and isinstance(c.this, exp.Column) and _norm_sql(c.this) == chosen_col and not c.args.get("query"):
1226
+ in_lits = {_norm_sql(x) for x in c.expressions}
1227
+ if in_lits == set(chosen_lits):
1228
+ in_matched = True
1229
+ continue
1230
+ w2_extras.append(_norm_sql(c))
1231
+ if not in_matched or sorted(w2_extras) != shared_extra:
1232
+ return None
1233
+
1234
+ # Verify every projected column i matches across branches:
1235
+ # Either identical expression across all branches & ast2, OR constant literal per branch matching CASE chosen_col WHEN lit_j THEN tag_j END!
1236
+ for col_i in range(len(ast2.expressions)):
1237
+ eo = ast2.expressions[col_i]
1238
+ to = eo.this if isinstance(eo, exp.Alias) else eo
1239
+ br_exprs = [(br.expressions[col_i].this if isinstance(br.expressions[col_i], exp.Alias) else br.expressions[col_i]) for br in branches]
1240
+ br_norms = [_norm_sql(e) for e in br_exprs]
1241
+ if all(n == _norm_sql(to) for n in br_norms):
1242
+ continue
1243
+ # Check CASE chosen_col WHEN lit_j THEN br_expr_j END (simple or searched CASE)
1244
+ if isinstance(to, exp.Case) and to.args.get("default") is None:
1245
+ mapping: dict[str, str] = {}
1246
+ if to.this is not None and _norm_sql(to.this) == chosen_col:
1247
+ for if_n in to.args.get("ifs") or []:
1248
+ mapping[_norm_sql(if_n.this)] = _norm_sql(if_n.args["true"])
1249
+ elif to.this is None:
1250
+ for if_n in to.args.get("ifs") or []:
1251
+ cond = _strip_parens(if_n.this)
1252
+ if isinstance(cond, exp.EQ) and isinstance(cond.this, exp.Column) and _norm_sql(cond.this) == chosen_col:
1253
+ mapping[_norm_sql(cond.expression)] = _norm_sql(if_n.args["true"])
1254
+ if len(mapping) == len(chosen_lits) and all(mapping.get(lit) == bn for lit, bn in zip(chosen_lits, br_norms)):
1255
+ continue
1256
+ return None
1257
+
1258
+ return VerificationResult(
1259
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
1260
+ rule_name="A9_disjoint_union_all_group_by_collapse",
1261
+ reason=f"Unbounded proof: {len(branches)}-branch UNION ALL over disjoint {chosen_col} values collapses to single-pass GROUP BY",
1262
+ )
1263
+
1264
+
1265
+ def try_algebraic_proof(ast1: exp.Expression, ast2: exp.Expression, schema: Schema) -> VerificationResult | None:
1266
+ """Attempt an unbounded sound algebraic equivalence proof. Returns None if no rule applies."""
1267
+ if _has_disallowed_or_volatile(ast1) or _has_disallowed_or_volatile(ast2):
1268
+ return None
1269
+
1270
+ if _norm_sql(ast1) == _norm_sql(ast2):
1271
+ # Ensure all referenced tables actually exist in schema (fail closed on unknown tables!)
1272
+ ctes = {c.alias.lower() for c in ast1.find_all(exp.CTE) if c.alias}
1273
+ if all(
1274
+ (t.name.lower() in ctes or schema.has_table(t.name))
1275
+ for t in ast1.find_all(exp.Table)
1276
+ if t.name
1277
+ ):
1278
+ return VerificationResult(
1279
+ status=ProofStatus.ALGEBRAICALLY_PROVEN,
1280
+ rule_name="A0_syntactic_identity",
1281
+ reason="Queries are syntactically identical after normalization",
1282
+ )
1283
+
1284
+ rules = (
1285
+ _rule_a1_a2_dead_join,
1286
+ _rule_a3_redundant_distinct,
1287
+ _rule_a4_tides_view_distinct_and_dead_join,
1288
+ _rule_a5_coalesce_where_unwrap,
1289
+ _rule_a6_or_to_disjoint_union_all,
1290
+ _rule_a7_date_extractor_to_range,
1291
+ _rule_a8_repeated_source_union_all_cross_join,
1292
+ _rule_a9_disjoint_union_all_group_by_collapse,
1293
+ )
1294
+ for rule in rules:
1295
+ res = rule(ast1, ast2, schema)
1296
+ if res is not None:
1297
+ return res
1298
+ # Equivalence is symmetric: also check (ast2, ast1)
1299
+ res_rev = rule(ast2, ast1, schema)
1300
+ if res_rev is not None:
1301
+ return res_rev
1302
+ return None