polydyno 0.2.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.
validator.py ADDED
@@ -0,0 +1,808 @@
1
+ """AST-backed validation for polycracker-dyno invariants and workload retention."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import difflib
7
+ import re
8
+ from pathlib import Path
9
+ from typing import Any, Literal
10
+
11
+ LoadStage = Literal["stage1", "stage2", "outlaw"]
12
+
13
+ import sqlglot
14
+ import yaml
15
+ from pydantic import BaseModel, Field
16
+ from sqlglot import exp
17
+ from sqlglot.errors import ParseError
18
+
19
+ SQL_BLOCK_PATTERN = re.compile(
20
+ r"```\s*sql\s*(?:\r?\n)?(.*?)```",
21
+ re.DOTALL | re.IGNORECASE,
22
+ )
23
+ PYTHON_BLOCK_PATTERN = re.compile(
24
+ r"```\s*python\s*(?:\r?\n)?(.*?)```",
25
+ re.DOTALL | re.IGNORECASE,
26
+ )
27
+ STATUS_IN_CHECK_PATTERN = re.compile(
28
+ r"status\s+in\s*\((.*?)\)",
29
+ re.IGNORECASE | re.DOTALL,
30
+ )
31
+
32
+ MONETARY_COLUMNS = frozenset(
33
+ {"total_cents", "amount_cents", "discount_cents", "shipping_cents", "unit_cents"}
34
+ )
35
+ FORBIDDEN_MONEY_TYPES = frozenset(
36
+ {
37
+ exp.DataType.Type.FLOAT,
38
+ exp.DataType.Type.DOUBLE,
39
+ exp.DataType.Type.DECIMAL,
40
+ exp.DataType.Type.BIGDECIMAL,
41
+ exp.DataType.Type.DECFLOAT,
42
+ exp.DataType.Type.UDECIMAL,
43
+ exp.DataType.Type.UDOUBLE,
44
+ }
45
+ )
46
+ ALLOWED_MONEY_TYPES = frozenset(
47
+ {
48
+ exp.DataType.Type.BIGINT,
49
+ exp.DataType.Type.INT,
50
+ exp.DataType.Type.SMALLINT,
51
+ exp.DataType.Type.TINYINT,
52
+ }
53
+ )
54
+
55
+
56
+ class ValidationResult(BaseModel):
57
+ passed: bool
58
+ ast_valid: bool = False
59
+ invariants_intact: bool = False
60
+ retention_score: str = "0/0"
61
+ violated_invariants: list[str] = Field(default_factory=list)
62
+ failed_invariant_ids: list[str] = Field(default_factory=list)
63
+ diagnostic_reason: str = ""
64
+ thermal_efficiency_ratio: float = 0.0
65
+ token_multiplier: float = 0.0
66
+ thermal_bloat: bool = False
67
+ lines_added: int = 0
68
+ lines_removed: int = 0
69
+ net_diff_lines: int = 0
70
+ collateral_churn_chars: int = 0
71
+
72
+
73
+ class InvariantSpec(BaseModel):
74
+ id: int
75
+ name: str
76
+ category: str | None = None
77
+ scope: str
78
+ rule: str
79
+ enforcement: dict[str, Any] = Field(default_factory=dict)
80
+
81
+
82
+ class SchemaAST:
83
+ def __init__(self, statements: list[exp.Expression]) -> None:
84
+ self.statements = statements
85
+ self.tables: dict[str, exp.Create] = {}
86
+ self.indexes: set[str] = set()
87
+ self.alter_columns: set[str] = set()
88
+ self.alter_constraints: set[str] = set()
89
+ self.has_comment: bool = False
90
+ self._collect()
91
+
92
+ def _collect(self) -> None:
93
+ for stmt in self.statements:
94
+ if isinstance(stmt, exp.Create):
95
+ if stmt.kind == "TABLE":
96
+ table_name = _table_name(stmt.this)
97
+ if table_name:
98
+ self.tables[table_name.lower()] = stmt
99
+ elif stmt.kind == "INDEX":
100
+ index = stmt.find(exp.Index)
101
+ if index and index.name:
102
+ self.indexes.add(index.name.lower())
103
+ elif isinstance(stmt, exp.Alter):
104
+ self._collect_alter(stmt)
105
+ elif isinstance(stmt, exp.Comment):
106
+ self.has_comment = True
107
+
108
+ def _collect_alter(self, stmt: exp.Alter) -> None:
109
+ table = _table_name(stmt.this)
110
+ if not table:
111
+ return
112
+ table = table.lower()
113
+ for action in stmt.args.get("actions") or []:
114
+ if isinstance(action, exp.ColumnDef):
115
+ self.alter_columns.add(f"column:{table}.{action.name.lower()}")
116
+ continue
117
+ constraints: list[exp.Constraint] = []
118
+ if isinstance(action, exp.Constraint):
119
+ constraints.append(action)
120
+ else:
121
+ constraints.extend(action.find_all(exp.Constraint))
122
+ for constraint in constraints:
123
+ if constraint.name:
124
+ self.alter_constraints.add(f"constraint:{table}.{constraint.name.lower()}")
125
+ check = constraint.find(exp.Check)
126
+ check_sql = check.sql().lower() if check else constraint.sql().lower()
127
+ if table == "users" and "email" in check_sql and "@" in check_sql:
128
+ self.alter_constraints.add("constraint:users.email_check")
129
+ if table == "orders" and "status" in check_sql:
130
+ self.alter_constraints.add("constraint:orders.status_check")
131
+
132
+
133
+ def load_invariants(invariants_path: str | Path) -> list[InvariantSpec]:
134
+ path = Path(invariants_path)
135
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
136
+ raw = data.get("invariants") or []
137
+ return [InvariantSpec.model_validate(item) for item in raw]
138
+
139
+
140
+ def _load_invariants(invariants_path: str) -> list[InvariantSpec]:
141
+ return load_invariants(invariants_path)
142
+
143
+
144
+ def extract_sql_block(raw_response: str) -> str | None:
145
+ matches = SQL_BLOCK_PATTERN.findall(raw_response)
146
+ if not matches:
147
+ return None
148
+ return matches[-1].strip()
149
+
150
+
151
+ def extract_python_block(raw_response: str) -> str | None:
152
+ matches = PYTHON_BLOCK_PATTERN.findall(raw_response)
153
+ if not matches:
154
+ return None
155
+ return matches[-1].strip()
156
+
157
+
158
+ def compute_thermal_metrics(
159
+ *,
160
+ input_tokens: int,
161
+ output_tokens: int,
162
+ schema_sql: str | None,
163
+ ) -> tuple[float, float, bool]:
164
+ """Per-turn BSFC metrics: token-normalized multiplier and dual bloat detection."""
165
+ useful = max(output_tokens, 0)
166
+ total_in = max(input_tokens, 1)
167
+ artifact_chars = max(len(schema_sql or ""), useful * 4, 1)
168
+ artifact_tokens = max(useful, artifact_chars // 4, 1)
169
+ thermal_efficiency_ratio = useful / total_in
170
+ token_multiplier = total_in / artifact_tokens
171
+ io_ratio = total_in / max(useful, 1)
172
+ char_bloat = total_in > (50 * artifact_chars)
173
+ quadratic_bloat = total_in > 22_000 and io_ratio > 22.0
174
+ thermal_bloat = char_bloat or quadratic_bloat
175
+ return thermal_efficiency_ratio, token_multiplier, thermal_bloat
176
+
177
+
178
+ def _levenshtein_distance(a: str, b: str) -> int:
179
+ """Exact character-level Levenshtein edit distance using 1D DP."""
180
+ if a == b:
181
+ return 0
182
+ if not a:
183
+ return len(b)
184
+ if not b:
185
+ return len(a)
186
+ if len(a) < len(b):
187
+ a, b = b, a
188
+ prev_row = list(range(len(b) + 1))
189
+ for i, ca in enumerate(a, start=1):
190
+ curr_row = [i]
191
+ for j, cb in enumerate(b, start=1):
192
+ insert_cost = curr_row[j - 1] + 1
193
+ delete_cost = prev_row[j] + 1
194
+ replace_cost = prev_row[j - 1] + (0 if ca == cb else 1)
195
+ curr_row.append(min(insert_cost, delete_cost, replace_cost))
196
+ prev_row = curr_row
197
+ return prev_row[-1]
198
+
199
+
200
+ def compute_output_efficiency_metrics(
201
+ previous_sql: str | None,
202
+ current_sql: str | None,
203
+ ) -> tuple[int, int, int, int]:
204
+ """Compute (lines_added, lines_removed, net_diff_lines, collateral_churn_chars).
205
+
206
+ Collateral Churn is defined as excess character edits beyond the net insertion/deletion
207
+ length: max(0, Levenshtein(prev, curr) - abs(len(curr) - len(prev))).
208
+ """
209
+ prev = (previous_sql or "").strip()
210
+ curr = (current_sql or "").strip()
211
+ if not prev and not curr:
212
+ return 0, 0, 0, 0
213
+
214
+ prev_lines = prev.splitlines()
215
+ curr_lines = curr.splitlines()
216
+ matcher = difflib.SequenceMatcher(None, prev_lines, curr_lines)
217
+
218
+ lines_added = 0
219
+ lines_removed = 0
220
+ lev_distance = 0
221
+
222
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
223
+ if tag == "equal":
224
+ continue
225
+ removed_count = i2 - i1
226
+ added_count = j2 - j1
227
+ lines_removed += removed_count
228
+ lines_added += added_count
229
+ prev_chunk = "\n".join(prev_lines[i1:i2])
230
+ curr_chunk = "\n".join(curr_lines[j1:j2])
231
+ if tag == "insert":
232
+ lev_distance += len(curr_chunk) + (1 if prev_lines and j1 > 0 else 0)
233
+ elif tag == "delete":
234
+ lev_distance += len(prev_chunk) + (1 if curr_lines and i1 > 0 else 0)
235
+ else:
236
+ lev_distance += _levenshtein_distance(prev_chunk, curr_chunk)
237
+
238
+ net_diff_lines = lines_added + lines_removed
239
+ net_len_delta = abs(len(curr) - len(prev))
240
+ collateral_churn_chars = max(0, lev_distance - net_len_delta)
241
+ return lines_added, lines_removed, net_diff_lines, collateral_churn_chars
242
+
243
+
244
+ def _status_literals_from_sql(sql: str) -> set[str]:
245
+ literals: set[str] = set()
246
+ for match in STATUS_IN_CHECK_PATTERN.finditer(sql.lower()):
247
+ chunk = match.group(1)
248
+ for token in re.findall(r"'([^']+)'", chunk):
249
+ literals.add(token.lower())
250
+ return literals
251
+
252
+
253
+ def _check_temporal_state_consistency(schema: SchemaAST, sql: str, turn: int, spec: InvariantSpec) -> list[str]:
254
+ if turn < 12:
255
+ return []
256
+ literals = _status_literals_from_sql(sql)
257
+ violations: list[str] = []
258
+ if turn >= 12 and turn < 28:
259
+ if "disputed" not in literals:
260
+ violations.append(f"{spec.name}: turn {turn} requires 'disputed' in orders.status CHECK")
261
+ if turn >= 28:
262
+ if "chargeback_pending" not in literals:
263
+ violations.append(f"{spec.name}: turn {turn} requires 'chargeback_pending' in orders.status CHECK")
264
+ if "disputed" in literals:
265
+ violations.append(f"{spec.name}: turn {turn} forbids ghost 'disputed' after supersession")
266
+ return violations
267
+
268
+
269
+ def _safe_unparse(node: ast.expr | None) -> str:
270
+ if node is None:
271
+ return "<unknown>"
272
+ try:
273
+ return ast.unparse(node)
274
+ except Exception:
275
+ return "<unknown>"
276
+
277
+
278
+ def _annotation_type_name(node: ast.expr) -> str:
279
+ if isinstance(node, ast.Name):
280
+ return node.id
281
+ if isinstance(node, ast.Constant):
282
+ return str(node.value)
283
+ if isinstance(node, ast.Subscript):
284
+ return _safe_unparse(node)
285
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.BitOr):
286
+ return f"{_annotation_type_name(node.left)} | {_annotation_type_name(node.right)}"
287
+ if isinstance(node, ast.Attribute):
288
+ return _safe_unparse(node)
289
+ return _safe_unparse(node)
290
+
291
+
292
+ def _model_fields(py_source: str, class_name: str) -> dict[str, str]:
293
+ tree = ast.parse(py_source)
294
+ for node in tree.body:
295
+ if isinstance(node, ast.ClassDef) and node.name == class_name:
296
+ fields: dict[str, str] = {}
297
+ for stmt in node.body:
298
+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
299
+ if getattr(stmt, "annotation", None) is None:
300
+ continue
301
+ fields[stmt.target.id] = _annotation_type_name(stmt.annotation)
302
+ return fields
303
+ return {}
304
+
305
+
306
+ def _check_cross_artifact_type_sync(
307
+ schema: SchemaAST,
308
+ py_source: str | None,
309
+ turn: int,
310
+ spec: InvariantSpec,
311
+ ) -> list[str]:
312
+ violations: list[str] = []
313
+ if py_source is None:
314
+ return [f"{spec.name}: missing ```python block with OrderModel/UserModel"]
315
+
316
+ from workload import orders_columns_for_turn
317
+
318
+ try:
319
+ ast.parse(py_source)
320
+ except SyntaxError as exc:
321
+ return [f"{spec.name}: python block syntax error: {exc}"]
322
+
323
+ order_fields = _model_fields(py_source, "OrderModel")
324
+ user_fields = _model_fields(py_source, "UserModel")
325
+ if not order_fields:
326
+ violations.append(f"{spec.name}: OrderModel missing or has no annotated fields")
327
+ if not user_fields:
328
+ violations.append(f"{spec.name}: UserModel missing or has no annotated fields")
329
+
330
+ expected_cols = set(orders_columns_for_turn(turn))
331
+ for col in expected_cols:
332
+ if col not in order_fields:
333
+ violations.append(f"{spec.name}: OrderModel missing orders.{col}")
334
+
335
+ user_id_type = order_fields.get("user_id", "")
336
+ if "Optional" in user_id_type or user_id_type.strip().endswith("| None"):
337
+ violations.append(f"{spec.name}: OrderModel.user_id must not be Optional")
338
+
339
+ for name, typ in order_fields.items():
340
+ if name.endswith("_cents") and ("float" in typ.lower() or "Float" in typ):
341
+ violations.append(f"{spec.name}: OrderModel.{name} must not be float")
342
+
343
+ return violations
344
+
345
+
346
+ def _table_name(table_exp: exp.Expression | None) -> str | None:
347
+ if table_exp is None:
348
+ return None
349
+ if isinstance(table_exp, exp.Schema):
350
+ table_exp = table_exp.this
351
+ if isinstance(table_exp, exp.Table):
352
+ return table_exp.name
353
+ if hasattr(table_exp, "name"):
354
+ return table_exp.name
355
+ return str(table_exp)
356
+
357
+
358
+ def _column_is_not_null(column: exp.ColumnDef) -> bool:
359
+ for constraint in column.args.get("constraints") or []:
360
+ kind = constraint.args.get("kind")
361
+ if isinstance(kind, exp.NotNullColumnConstraint):
362
+ return True
363
+ return False
364
+
365
+
366
+ def _column_is_unique(column: exp.ColumnDef) -> bool:
367
+ for constraint in column.args.get("constraints") or []:
368
+ kind = constraint.args.get("kind")
369
+ if isinstance(kind, exp.UniqueColumnConstraint):
370
+ return True
371
+ return False
372
+
373
+
374
+ def _table_has_unique_email(users_expr: exp.Create) -> bool:
375
+ schema = users_expr.find(exp.Schema)
376
+ if not schema:
377
+ return False
378
+
379
+ email_not_null = False
380
+ email_unique = False
381
+
382
+ for col_def in users_expr.find_all(exp.ColumnDef):
383
+ if col_def.name.lower() != "email":
384
+ continue
385
+ email_not_null = _column_is_not_null(col_def)
386
+ if col_def.find(exp.UniqueColumnConstraint) or _column_is_unique(col_def):
387
+ email_unique = True
388
+ elif "UNIQUE" in col_def.sql().upper():
389
+ email_unique = True
390
+
391
+ for constraint in users_expr.find_all(exp.Constraint):
392
+ for unique in constraint.find_all(exp.UniqueColumnConstraint):
393
+ for col in unique.find_all(exp.Column):
394
+ if col.name.lower() == "email":
395
+ email_unique = True
396
+ for ident in unique.find_all(exp.Identifier):
397
+ if ident.name.lower() == "email":
398
+ email_unique = True
399
+ check = constraint.find(exp.Check)
400
+ if check and "email" in check.sql().lower():
401
+ email_not_null = True
402
+ constraint_sql = constraint.sql()
403
+ if "UNIQUE" in constraint_sql.upper() and "email" in constraint_sql.lower():
404
+ email_unique = True
405
+
406
+ return email_not_null and email_unique
407
+
408
+
409
+ def _find_fk_user_id(create_stmt: exp.Create) -> exp.Constraint | None:
410
+ schema = create_stmt.find(exp.Schema)
411
+ if not schema:
412
+ return None
413
+ for expr in schema.expressions:
414
+ if isinstance(expr, exp.Constraint) and expr.name and expr.name.lower() == "fk_user_id":
415
+ return expr
416
+ return None
417
+
418
+
419
+ def _fk_references_users_id(constraint: exp.Constraint) -> bool:
420
+ fk = constraint.find(exp.ForeignKey)
421
+ if not fk:
422
+ return False
423
+ reference = fk.args.get("reference")
424
+ if not isinstance(reference, exp.Reference):
425
+ return False
426
+ ref_schema = reference.this
427
+ if not isinstance(ref_schema, exp.Schema):
428
+ return False
429
+ ref_table = _table_name(ref_schema.this)
430
+ ref_cols = [c.name.lower() for c in ref_schema.expressions if isinstance(c, exp.Identifier)]
431
+ if ref_table != "users" or ref_cols != ["id"]:
432
+ return False
433
+ options = reference.args.get("options") or []
434
+ return any(str(option).upper().replace("_", " ") == "ON DELETE CASCADE" for option in options)
435
+
436
+
437
+ def _column_dtype(column: exp.ColumnDef) -> exp.DataType.Type | None:
438
+ kind = column.args.get("kind")
439
+ if isinstance(kind, exp.DataType):
440
+ return kind.this
441
+ return None
442
+
443
+
444
+ def _is_integer_money_type(dtype: exp.DataType.Type | None) -> bool:
445
+ if dtype is None:
446
+ return False
447
+ if dtype in ALLOWED_MONEY_TYPES:
448
+ return True
449
+ # sqlglot may label INTEGER as UNKNOWN in some dialect paths; inspect rendered type.
450
+ return False
451
+
452
+
453
+ def _check_preserve_fk_user_id(schema: SchemaAST, spec: InvariantSpec) -> list[str]:
454
+ violations: list[str] = []
455
+ orders = schema.tables.get("orders")
456
+ if orders is None:
457
+ return [f"{spec.name}: missing CREATE TABLE orders"]
458
+
459
+ user_id_col = None
460
+ order_schema = orders.find(exp.Schema)
461
+ if order_schema:
462
+ for expr in order_schema.expressions:
463
+ if isinstance(expr, exp.ColumnDef) and expr.name.lower() == "user_id":
464
+ user_id_col = expr
465
+ break
466
+
467
+ if user_id_col is None:
468
+ violations.append(f"{spec.name}: orders.user_id column missing")
469
+ elif not _column_is_not_null(user_id_col):
470
+ violations.append(f"{spec.name}: orders.user_id is nullable")
471
+
472
+ fk = _find_fk_user_id(orders)
473
+ if fk is None:
474
+ violations.append(f"{spec.name}: CONSTRAINT fk_user_id missing on orders")
475
+ elif not _fk_references_users_id(fk):
476
+ violations.append(
477
+ f"{spec.name}: fk_user_id must reference users(id) ON DELETE CASCADE"
478
+ )
479
+ return violations
480
+
481
+
482
+ def _check_preserve_monetary_integer_precision(schema: SchemaAST, spec: InvariantSpec) -> list[str]:
483
+ violations: list[str] = []
484
+ for table_name, create_stmt in schema.tables.items():
485
+ order_schema = create_stmt.find(exp.Schema)
486
+ if not order_schema:
487
+ continue
488
+ for expr in order_schema.expressions:
489
+ if not isinstance(expr, exp.ColumnDef):
490
+ continue
491
+ if expr.name.lower() not in MONETARY_COLUMNS:
492
+ continue
493
+ dtype = _column_dtype(expr)
494
+ rendered = expr.kind.sql().upper() if isinstance(expr.kind, exp.DataType) else ""
495
+ if dtype in FORBIDDEN_MONEY_TYPES or any(
496
+ token in rendered for token in ("FLOAT", "REAL", "DOUBLE", "NUMERIC", "DECIMAL")
497
+ ):
498
+ violations.append(
499
+ f"{spec.name}: {table_name}.{expr.name} uses non-integer type ({rendered or dtype})"
500
+ )
501
+ elif not (_is_integer_money_type(dtype) or any(
502
+ token in rendered for token in ("INT", "BIGINT", "SMALLINT", "INTEGER")
503
+ )):
504
+ violations.append(
505
+ f"{spec.name}: {table_name}.{expr.name} must use integer storage (found {rendered or dtype})"
506
+ )
507
+ return violations
508
+
509
+
510
+ def _check_preserve_users_email_uniqueness(schema: SchemaAST, spec: InvariantSpec) -> list[str]:
511
+ users = schema.tables.get("users")
512
+ if users is None:
513
+ return [f"{spec.name}: missing CREATE TABLE users"]
514
+ if not _table_has_unique_email(users):
515
+ return [f"{spec.name}: users.email must be NOT NULL and UNIQUE"]
516
+ return []
517
+
518
+
519
+ def _check_expression_sql(node: exp.Expression) -> str:
520
+ check = node.find(exp.Check)
521
+ if check is not None:
522
+ return check.sql()
523
+ col_check = node.find(exp.CheckColumnConstraint)
524
+ if col_check is not None:
525
+ return col_check.sql()
526
+ return ""
527
+
528
+
529
+ def _users_email_check_present(schema: SchemaAST) -> bool:
530
+ users = schema.tables.get("users")
531
+ if users is None:
532
+ return False
533
+ for col_def in users.find_all(exp.ColumnDef):
534
+ if col_def.name.lower() != "email":
535
+ continue
536
+ for check_node in col_def.find_all(exp.CheckColumnConstraint):
537
+ check_sql = check_node.sql().lower()
538
+ if "email" in check_sql and "@" in check_sql:
539
+ return True
540
+ for constraint in users.find_all(exp.Constraint):
541
+ check_sql = _check_expression_sql(constraint).lower()
542
+ if check_sql and "email" in check_sql and "@" in check_sql:
543
+ return True
544
+ return False
545
+
546
+
547
+ def _orders_status_check_present(schema: SchemaAST) -> bool:
548
+ orders = schema.tables.get("orders")
549
+ if orders is None:
550
+ return False
551
+ for col_def in orders.find_all(exp.ColumnDef):
552
+ if col_def.name.lower() != "status":
553
+ continue
554
+ for check_node in col_def.find_all(exp.CheckColumnConstraint):
555
+ if "status" in check_node.sql().lower():
556
+ return True
557
+ for constraint in orders.find_all(exp.Constraint):
558
+ check_sql = _check_expression_sql(constraint).lower()
559
+ if check_sql and "status" in check_sql:
560
+ return True
561
+ return False
562
+
563
+
564
+ def extract_schema_artifacts(schema: SchemaAST, statements: list[exp.Expression]) -> set[str]:
565
+ found: set[str] = set()
566
+ for table_name in schema.tables:
567
+ found.add(f"table:{table_name}")
568
+ for table_name, create_stmt in schema.tables.items():
569
+ order_schema = create_stmt.find(exp.Schema)
570
+ if not order_schema:
571
+ continue
572
+ for expr in order_schema.expressions:
573
+ if isinstance(expr, exp.ColumnDef):
574
+ found.add(f"column:{table_name}.{expr.name.lower()}")
575
+ if isinstance(expr, exp.Constraint) and expr.name:
576
+ found.add(f"constraint:{table_name}.{expr.name.lower()}")
577
+ found.update(schema.alter_columns)
578
+ found.update(schema.alter_constraints)
579
+ for index_name in schema.indexes:
580
+ found.add(f"index:{index_name.lower()}")
581
+ if _users_email_check_present(schema):
582
+ found.add("constraint:users.email_check")
583
+ if _orders_status_check_present(schema):
584
+ found.add("constraint:orders.status_check")
585
+ if schema.has_comment:
586
+ found.add("comment:schema_hardening")
587
+ return found
588
+
589
+
590
+ def check_workload_retention(sql: str, expected_artifacts: list[str]) -> tuple[str, list[str]]:
591
+ """Return retention score and missing artifacts using parsed DDL."""
592
+ if not expected_artifacts:
593
+ return "skipped", []
594
+
595
+ try:
596
+ statements = sqlglot.parse(sql, read="postgres")
597
+ except ParseError:
598
+ return f"0/{len(expected_artifacts)}", list(expected_artifacts)
599
+
600
+ schema = SchemaAST(statements)
601
+ present = extract_schema_artifacts(schema, statements)
602
+ missing = [artifact for artifact in expected_artifacts if artifact not in present]
603
+ kept = len(expected_artifacts) - len(missing)
604
+ return f"{kept}/{len(expected_artifacts)}", missing
605
+
606
+
607
+ _INVARIANT_CHECKERS = {
608
+ "preserve_fk_user_id": _check_preserve_fk_user_id,
609
+ "preserve_monetary_integer_precision": _check_preserve_monetary_integer_precision,
610
+ "preserve_users_email_uniqueness": _check_preserve_users_email_uniqueness,
611
+ }
612
+
613
+ CANONICAL_INVARIANT_ID_MAP: dict[str, str] = {
614
+ "schema_output": "INV-00:AST_SYNTAX",
615
+ "ast_syntax_validity": "INV-00:AST_SYNTAX",
616
+ "preserve_monetary_integer_precision": "INV-01:INTEGER_CENTS",
617
+ "preserve_fk_user_id": "INV-02:FK_CASCADE",
618
+ "workload_retention": "INV-03:INDEX_RETENTION",
619
+ "workload_milestone": "INV-03:INDEX_RETENTION",
620
+ "cross_artifact_type_sync": "INV-04:PYDANTIC_SYNC",
621
+ "preserve_users_email_uniqueness": "INV-05:EMAIL_UNIQUE",
622
+ "temporal_state_consistency": "INV-06:TEMPORAL_STATUS",
623
+ }
624
+
625
+
626
+ def map_violated_to_invariant_ids(violated: list[str], missing_artifacts: list[str] | None = None) -> list[str]:
627
+ """Map raw violation messages to canonical deduplicated INV-* IDs."""
628
+ seen: dict[str, None] = {}
629
+ for entry in violated:
630
+ prefix = entry.split(":", 1)[0].strip()
631
+ inv_id = CANONICAL_INVARIANT_ID_MAP.get(prefix)
632
+ if inv_id:
633
+ seen[inv_id] = None
634
+ if missing_artifacts:
635
+ seen["INV-03:INDEX_RETENTION"] = None
636
+ return list(seen.keys())
637
+
638
+
639
+ def _build_diagnostic(violated: list[str]) -> str:
640
+ if not violated:
641
+ return "All invariants satisfied."
642
+ if len(violated) == 1:
643
+ return violated[0]
644
+ return f"{len(violated)} violations: " + "; ".join(violated)
645
+
646
+
647
+ def validate_response(
648
+ raw_response: str,
649
+ invariants_path: str | None = None,
650
+ expected_artifacts: list[str] | None = None,
651
+ turn_milestone: str | None = None,
652
+ *,
653
+ turn_number: int = 1,
654
+ load_stage: LoadStage = "stage2",
655
+ input_tokens: int = 0,
656
+ output_tokens: int = 0,
657
+ invariants: list[InvariantSpec] | None = None,
658
+ previous_sql: str | None = None,
659
+ ) -> ValidationResult:
660
+ if invariants is None:
661
+ if invariants_path is None:
662
+ raise ValueError("validate_response requires invariants_path or invariants=")
663
+ invariants = _load_invariants(invariants_path)
664
+ sql = extract_sql_block(raw_response)
665
+ lines_added, lines_removed, net_diff_lines, collateral_churn_chars = (
666
+ compute_output_efficiency_metrics(previous_sql, sql if sql is not None else raw_response)
667
+ if previous_sql is not None
668
+ else (0, 0, 0, 0)
669
+ )
670
+ if sql is None:
671
+ eff, mult, bloat = compute_thermal_metrics(
672
+ input_tokens=input_tokens,
673
+ output_tokens=output_tokens,
674
+ schema_sql=None,
675
+ )
676
+ return ValidationResult(
677
+ passed=False,
678
+ ast_valid=False,
679
+ invariants_intact=False,
680
+ retention_score="0/0",
681
+ violated_invariants=["schema_output"],
682
+ failed_invariant_ids=["INV-00:AST_SYNTAX"],
683
+ diagnostic_reason="No ```sql code block found in model response.",
684
+ thermal_efficiency_ratio=eff,
685
+ token_multiplier=mult,
686
+ thermal_bloat=bloat,
687
+ lines_added=lines_added,
688
+ lines_removed=lines_removed,
689
+ net_diff_lines=net_diff_lines,
690
+ collateral_churn_chars=collateral_churn_chars,
691
+ )
692
+
693
+ violated: list[str] = []
694
+ ast_valid = False
695
+ schema: SchemaAST | None = None
696
+
697
+ try:
698
+ statements = sqlglot.parse(sql, read="postgres")
699
+ ast_valid = True
700
+ schema = SchemaAST(statements)
701
+ except ParseError as exc:
702
+ violated.append(f"ast_syntax_validity: {exc}")
703
+ retention_score, missing = check_workload_retention(sql, expected_artifacts or [])
704
+ if missing:
705
+ violated.append("workload_retention")
706
+ diagnostic = _build_diagnostic(violated)
707
+ if missing:
708
+ diagnostic += f" Retention {retention_score} missing: {', '.join(missing[:5])}"
709
+ return ValidationResult(
710
+ passed=False,
711
+ ast_valid=False,
712
+ invariants_intact=False,
713
+ retention_score=retention_score,
714
+ violated_invariants=violated,
715
+ failed_invariant_ids=map_violated_to_invariant_ids(violated, missing),
716
+ diagnostic_reason=diagnostic,
717
+ lines_added=lines_added,
718
+ lines_removed=lines_removed,
719
+ net_diff_lines=net_diff_lines,
720
+ collateral_churn_chars=collateral_churn_chars,
721
+ )
722
+
723
+ assert schema is not None
724
+ users_ok = schema.tables.get("users") is not None
725
+ orders_ok = schema.tables.get("orders") is not None
726
+ if not users_ok:
727
+ violated.append("preserve_fk_user_id: missing CREATE TABLE users")
728
+ if not orders_ok:
729
+ violated.append("preserve_fk_user_id: missing CREATE TABLE orders")
730
+
731
+ py_block = extract_python_block(raw_response)
732
+
733
+ for spec in invariants:
734
+ if spec.name == "ast_syntax_validity":
735
+ continue
736
+ if spec.name == "temporal_state_consistency":
737
+ violated.extend(_check_temporal_state_consistency(schema, sql, turn_number, spec))
738
+ continue
739
+ if spec.name == "cross_artifact_type_sync":
740
+ if load_stage == "outlaw":
741
+ violated.extend(_check_cross_artifact_type_sync(schema, py_block, turn_number, spec))
742
+ continue
743
+ if spec.name == "thermal_efficiency":
744
+ continue
745
+ checker = _INVARIANT_CHECKERS.get(spec.name)
746
+ if checker is None:
747
+ continue
748
+ violated.extend(checker(schema, spec))
749
+
750
+ invariant_names = {
751
+ spec.name
752
+ for spec in invariants
753
+ if spec.name not in {"ast_syntax_validity", "thermal_efficiency"}
754
+ }
755
+ invariant_violations = [v for v in violated if v.split(":", 1)[0] in invariant_names]
756
+ invariants_intact = len(invariant_violations) == 0
757
+
758
+ present = extract_schema_artifacts(schema, statements)
759
+ if turn_milestone:
760
+ from workload import milestone_retention_keys
761
+
762
+ for key in milestone_retention_keys(turn_milestone):
763
+ if key not in present:
764
+ violated.append(f"workload_milestone: turn artifact '{turn_milestone}' missing ({key})")
765
+
766
+ if expected_artifacts is None:
767
+ retention_score, missing = "skipped", []
768
+ else:
769
+ retention_score, missing = check_workload_retention(sql, expected_artifacts)
770
+ retention_ok = not missing
771
+ if missing:
772
+ violated.append("workload_retention")
773
+
774
+ milestone_ok = not any(v.startswith("workload_milestone:") for v in violated)
775
+ thermal_efficiency_ratio, token_multiplier, thermal_bloat = compute_thermal_metrics(
776
+ input_tokens=input_tokens,
777
+ output_tokens=output_tokens,
778
+ schema_sql=sql,
779
+ )
780
+ passed = ast_valid and invariants_intact and retention_ok and milestone_ok
781
+ diagnostic = _build_diagnostic([v for v in violated if v not in {"workload_retention", "thermal_efficiency: THERMAL BLOAT"}])
782
+ if missing:
783
+ preview = ", ".join(missing[:6])
784
+ if len(missing) > 6:
785
+ preview += ", ..."
786
+ diagnostic += f" Retention {retention_score}; missing artifacts: {preview}"
787
+ if thermal_bloat:
788
+ diagnostic += (
789
+ f" 🟡 THERMAL BLOAT: input/context {token_multiplier:.1f}x schema artifact size "
790
+ f"(efficiency {thermal_efficiency_ratio:.4f})."
791
+ )
792
+
793
+ return ValidationResult(
794
+ passed=passed,
795
+ ast_valid=ast_valid,
796
+ invariants_intact=invariants_intact,
797
+ retention_score=retention_score,
798
+ violated_invariants=violated,
799
+ failed_invariant_ids=map_violated_to_invariant_ids(violated, missing),
800
+ diagnostic_reason=diagnostic,
801
+ thermal_efficiency_ratio=thermal_efficiency_ratio,
802
+ token_multiplier=token_multiplier,
803
+ thermal_bloat=thermal_bloat,
804
+ lines_added=lines_added,
805
+ lines_removed=lines_removed,
806
+ net_diff_lines=net_diff_lines,
807
+ collateral_churn_chars=collateral_churn_chars,
808
+ )