ectype-data 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.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,627 @@
1
+ """Report objects shared by validation (``ValidationReport``) and drift (``DriftReport``).
2
+
3
+ The *report shell* (``ReportShell``) gives every report the same surface: ``to_dict()``,
4
+ ``to_json(path)``, ``to_html(path)`` (one static, self-contained HTML file with inline CSS, light
5
+ and dark via ``prefers-color-scheme``, no external assets) and ``summary()`` (compact console
6
+ text).
7
+
8
+ Validation reports keep three sections strictly separate (calibration, sealed, holdout) and never
9
+ compute a merged score: calibration results are optimizer evidence only, sealed results are the
10
+ primary evidence of fidelity (design doc section 4.2 / 6.1).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import html
16
+ import json
17
+ import math
18
+ from abc import ABC, abstractmethod
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ # ---------------------------------------------------------------------------------------------
24
+ # JSON helpers
25
+ # ---------------------------------------------------------------------------------------------
26
+
27
+
28
+ def json_safe(obj: Any) -> Any:
29
+ """Recursively convert to JSON-safe values (non-finite floats -> None, numpy -> python)."""
30
+ if isinstance(obj, dict):
31
+ return {str(k): json_safe(v) for k, v in obj.items()}
32
+ if isinstance(obj, (list, tuple)):
33
+ return [json_safe(v) for v in obj]
34
+ if hasattr(obj, "item") and callable(obj.item) and getattr(obj, "ndim", 1) == 0:
35
+ obj = obj.item()
36
+ elif hasattr(obj, "tolist") and callable(obj.tolist):
37
+ return json_safe(obj.tolist())
38
+ if isinstance(obj, float) and not math.isfinite(obj):
39
+ return None
40
+ if obj is None or isinstance(obj, (str, int, float, bool)):
41
+ return obj
42
+ return str(obj)
43
+
44
+
45
+ def _fmt(x: float | None, digits: int = 4) -> str:
46
+ if x is None:
47
+ return "n/a"
48
+ if isinstance(x, float) and math.isinf(x):
49
+ return "inf"
50
+ if isinstance(x, float) and math.isnan(x):
51
+ return "nan"
52
+ return f"{x:.{digits}g}"
53
+
54
+
55
+ def _pct(x: float | None) -> str:
56
+ return "n/a" if x is None else f"{100.0 * x:.1f}%"
57
+
58
+
59
+ # ---------------------------------------------------------------------------------------------
60
+ # Result records
61
+ # ---------------------------------------------------------------------------------------------
62
+
63
+
64
+ @dataclass
65
+ class TargetResult:
66
+ """Outcome of comparing one target (or one data-requiring metric) with a candidate."""
67
+
68
+ id: str
69
+ metric: str
70
+ family: str
71
+ columns: list[str]
72
+ distance: float
73
+ tolerance: float
74
+ passed: bool
75
+ reference: Any = None
76
+ candidate: Any = None
77
+ error: str | None = None
78
+
79
+ @property
80
+ def ratio(self) -> float:
81
+ """distance / tolerance (inf for errors or a zero tolerance with positive distance)."""
82
+ if self.error is not None or not math.isfinite(self.distance):
83
+ return math.inf
84
+ if self.tolerance <= 0:
85
+ return 0.0 if self.distance <= 0 else math.inf
86
+ return self.distance / self.tolerance
87
+
88
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]:
89
+ d: dict[str, Any] = {
90
+ "id": self.id, "metric": self.metric, "family": self.family,
91
+ "columns": list(self.columns), "distance": self.distance,
92
+ "tolerance": self.tolerance, "passed": self.passed,
93
+ }
94
+ if self.error is not None:
95
+ d["error"] = self.error
96
+ if verbose:
97
+ d["reference"] = self.reference
98
+ d["candidate"] = self.candidate
99
+ return d
100
+
101
+
102
+ def worst_first(results: list[TargetResult]) -> list[TargetResult]:
103
+ """Failures first, then by distance/tolerance descending, then by id."""
104
+ return sorted(results, key=lambda r: (r.passed, -_finite_key(r.ratio), r.id))
105
+
106
+
107
+ def _finite_key(x: float) -> float:
108
+ return 1e300 if math.isinf(x) or math.isnan(x) else x
109
+
110
+
111
+ @dataclass
112
+ class Section:
113
+ """One independent section of a validation report. Never merged with another."""
114
+
115
+ name: str # "calibration" | "sealed" | "holdout"
116
+ title: str
117
+ evidence: str # what the section is evidence of
118
+ results: list[TargetResult] = field(default_factory=list)
119
+ notes: list[str] = field(default_factory=list)
120
+
121
+ @property
122
+ def n(self) -> int:
123
+ return len(self.results)
124
+
125
+ @property
126
+ def n_passed(self) -> int:
127
+ return sum(r.passed for r in self.results)
128
+
129
+ @property
130
+ def n_failed(self) -> int:
131
+ return self.n - self.n_passed
132
+
133
+ @property
134
+ def pass_rate(self) -> float | None:
135
+ return self.n_passed / self.n if self.n else None
136
+
137
+ @property
138
+ def median_ratio(self) -> float | None:
139
+ r = sorted(_finite_key(x.ratio) for x in self.results)
140
+ if not r:
141
+ return None
142
+ m = len(r) // 2
143
+ return r[m] if len(r) % 2 else 0.5 * (r[m - 1] + r[m])
144
+
145
+ def worst(self, k: int | None = None) -> list[TargetResult]:
146
+ w = worst_first(self.results)
147
+ return w if k is None else w[:k]
148
+
149
+ def by_family(self) -> dict[str, dict[str, Any]]:
150
+ out: dict[str, dict[str, Any]] = {}
151
+ for r in self.results:
152
+ f = out.setdefault(r.family or r.metric, {"n": 0, "passed": 0})
153
+ f["n"] += 1
154
+ f["passed"] += int(r.passed)
155
+ for f in out.values():
156
+ f["pass_rate"] = f["passed"] / f["n"]
157
+ return dict(sorted(out.items()))
158
+
159
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]:
160
+ return {
161
+ "name": self.name, "title": self.title, "evidence": self.evidence,
162
+ "n": self.n, "n_passed": self.n_passed, "n_failed": self.n_failed,
163
+ "pass_rate": self.pass_rate, "median_distance_ratio": self.median_ratio,
164
+ "by_family": self.by_family(), "notes": list(self.notes),
165
+ "results": [r.to_dict(verbose) for r in self.worst()],
166
+ }
167
+
168
+
169
+ @dataclass
170
+ class Check:
171
+ """A structural check (schema, row count, ...)."""
172
+
173
+ name: str
174
+ passed: bool
175
+ message: str
176
+ details: dict[str, Any] = field(default_factory=dict)
177
+
178
+ def to_dict(self) -> dict[str, Any]:
179
+ return {"name": self.name, "passed": self.passed, "message": self.message,
180
+ "details": self.details}
181
+
182
+
183
+ @dataclass
184
+ class ConstraintResult:
185
+ id: str
186
+ expression: str
187
+ severity: str
188
+ n_rows: int
189
+ violations: int
190
+ passed: bool
191
+ error: str | None = None
192
+
193
+ @property
194
+ def violation_rate(self) -> float:
195
+ return self.violations / self.n_rows if self.n_rows else 0.0
196
+
197
+ def to_dict(self) -> dict[str, Any]:
198
+ d = {"id": self.id, "expression": self.expression, "severity": self.severity,
199
+ "n_rows": self.n_rows, "violations": self.violations,
200
+ "violation_rate": self.violation_rate, "passed": self.passed}
201
+ if self.error is not None:
202
+ d["error"] = self.error
203
+ return d
204
+
205
+
206
+ # ---------------------------------------------------------------------------------------------
207
+ # HTML rendering (self-contained; shared by every report)
208
+ # ---------------------------------------------------------------------------------------------
209
+
210
+ _CSS = """
211
+ :root{--bg:#fbfbfa;--fg:#1d1f23;--muted:#62666d;--card:#ffffff;--line:#e3e4e6;
212
+ --ok:#1f7a3f;--ok-bg:#e6f4ea;--bad:#b42318;--bad-bg:#fdecea;--warn:#8a5a00;--warn-bg:#fff4dc;
213
+ --accent:#2d5bd7;--bar:#d9dbe0;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
214
+ @media (prefers-color-scheme:dark){:root{--bg:#141518;--fg:#e7e8ea;--muted:#9aa0a8;
215
+ --card:#1c1e22;--line:#2d3036;--ok:#6fd08f;--ok-bg:#16301f;--bad:#ff8a80;--bad-bg:#3a1a18;
216
+ --warn:#f2c45a;--warn-bg:#33290f;--accent:#8fb0ff;--bar:#33363d}}
217
+ *{box-sizing:border-box}
218
+ body{margin:0;background:var(--bg);color:var(--fg);
219
+ font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
220
+ main{max-width:1100px;margin:0 auto;padding:28px 16px 64px}
221
+ h1{font-size:1.5rem;margin:0 0 4px}h2{font-size:1.15rem;margin:0 0 4px}
222
+ .sub{color:var(--muted);margin:0 0 16px}
223
+ .card{background:var(--card);border:1px solid var(--line);border-radius:10px;
224
+ padding:16px 18px;margin:16px 0}
225
+ .meta{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px 20px;
226
+ margin:0}
227
+ .meta dt{color:var(--muted);font-size:.8rem;text-transform:uppercase;letter-spacing:.04em}
228
+ .meta dd{margin:0;font-family:var(--mono);font-size:.85rem;overflow-wrap:anywhere}
229
+ .verdict{font-weight:600;padding:10px 14px;border-radius:8px;margin:16px 0}
230
+ .verdict.ok{background:var(--ok-bg);color:var(--ok)}
231
+ .verdict.bad{background:var(--bad-bg);color:var(--bad)}
232
+ .note{background:var(--warn-bg);color:var(--warn);border-radius:6px;padding:6px 10px;
233
+ font-size:.88rem;margin:8px 0}
234
+ .stats{display:flex;flex-wrap:wrap;gap:24px;margin:8px 0 12px}
235
+ .stat b{display:block;font-size:1.35rem}.stat span{color:var(--muted);font-size:.82rem}
236
+ .tw{overflow-x:auto}
237
+ table{border-collapse:collapse;width:100%;font-size:.86rem}
238
+ th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}
239
+ th{color:var(--muted);font-weight:600;font-size:.78rem;text-transform:uppercase}
240
+ td.num{text-align:right;font-variant-numeric:tabular-nums;font-family:var(--mono)}
241
+ td code{font-family:var(--mono);font-size:.82rem}
242
+ .pill{display:inline-block;padding:1px 8px;border-radius:999px;font-size:.75rem;font-weight:600}
243
+ .pill.ok{background:var(--ok-bg);color:var(--ok)}.pill.bad{background:var(--bad-bg);color:var(--bad)}
244
+ .pill.warn{background:var(--warn-bg);color:var(--warn)}
245
+ .bar{display:inline-block;width:80px;height:8px;background:var(--bar);border-radius:4px;
246
+ vertical-align:middle;margin-left:6px;overflow:hidden}
247
+ .bar i{display:block;height:100%;background:var(--accent)}
248
+ .bar i.bad{background:var(--bad)}
249
+ .gap{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px}
250
+ .muted{color:var(--muted)}
251
+ footer{color:var(--muted);font-size:.8rem;margin-top:32px}
252
+ """
253
+
254
+
255
+ def esc(x: Any) -> str:
256
+ return html.escape("" if x is None else str(x))
257
+
258
+
259
+ def pill(ok: bool | None, text_ok: str = "pass", text_bad: str = "fail",
260
+ text_none: str = "n/a") -> str:
261
+ if ok is None:
262
+ return f'<span class="pill warn">{esc(text_none)}</span>'
263
+ return (f'<span class="pill ok">{esc(text_ok)}</span>' if ok
264
+ else f'<span class="pill bad">{esc(text_bad)}</span>')
265
+
266
+
267
+ def ratio_bar(ratio: float) -> str:
268
+ """A small bar for distance/tolerance (full width at 2x tolerance)."""
269
+ r = _finite_key(ratio)
270
+ w = max(0.0, min(1.0, r / 2.0)) * 100
271
+ cls = "bad" if r > 1 else ""
272
+ return f'<span class="bar"><i class="{cls}" style="width:{w:.0f}%"></i></span>'
273
+
274
+
275
+ def html_table(headers: list[str], rows: list[list[str]], numeric: set[int] | None = None,
276
+ empty: str = "Nothing to show.") -> str:
277
+ """Rows are pre-escaped HTML cells."""
278
+ if not rows:
279
+ return f'<p class="muted">{esc(empty)}</p>'
280
+ numeric = numeric or set()
281
+ head = "".join(f"<th>{esc(h)}</th>" for h in headers)
282
+ body = []
283
+ for row in rows:
284
+ tds = "".join(f'<td class="num">{c}</td>' if i in numeric else f"<td>{c}</td>"
285
+ for i, c in enumerate(row))
286
+ body.append(f"<tr>{tds}</tr>")
287
+ return (f'<div class="tw"><table><thead><tr>{head}</tr></thead>'
288
+ f'<tbody>{"".join(body)}</tbody></table></div>')
289
+
290
+
291
+ def meta_list(items: dict[str, Any]) -> str:
292
+ return '<dl class="meta">' + "".join(
293
+ f"<div><dt>{esc(k)}</dt><dd>{esc(v)}</dd></div>" for k, v in items.items()) + "</dl>"
294
+
295
+
296
+ def stats_row(items: dict[str, str]) -> str:
297
+ return '<div class="stats">' + "".join(
298
+ f'<div class="stat"><b>{esc(v)}</b><span>{esc(k)}</span></div>'
299
+ for k, v in items.items()) + "</div>"
300
+
301
+
302
+ def render_page(title: str, subtitle: str, body: str) -> str:
303
+ return ("<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">"
304
+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
305
+ "<meta name=\"color-scheme\" content=\"light dark\">"
306
+ f"<title>{esc(title)}</title><style>{_CSS}</style></head><body><main>"
307
+ f"<h1>{esc(title)}</h1><p class=\"sub\">{esc(subtitle)}</p>{body}"
308
+ "<footer>Generated by ectype. Static report; no external assets."
309
+ "</footer></main></body></html>\n")
310
+
311
+
312
+ def target_rows(results: list[TargetResult], limit: int = 500) -> list[list[str]]:
313
+ rows = []
314
+ for r in results[:limit]:
315
+ rows.append([
316
+ pill(r.passed),
317
+ f"<code>{esc(r.metric)}</code>",
318
+ esc(", ".join(r.columns)),
319
+ _fmt(r.distance),
320
+ _fmt(r.tolerance),
321
+ _fmt(r.ratio, 3) + ratio_bar(r.ratio),
322
+ esc(r.error or ""),
323
+ ])
324
+ return rows
325
+
326
+
327
+ TARGET_HEADERS = ["", "metric", "columns", "distance", "tolerance", "distance / tol", "note"]
328
+
329
+
330
+ # ---------------------------------------------------------------------------------------------
331
+ # Report shell
332
+ # ---------------------------------------------------------------------------------------------
333
+
334
+
335
+ class ReportShell(ABC):
336
+ """Common surface of every report."""
337
+
338
+ title: str = "Report"
339
+
340
+ @abstractmethod
341
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]: ...
342
+
343
+ @abstractmethod
344
+ def summary(self) -> str: ...
345
+
346
+ @abstractmethod
347
+ def _html_body(self) -> tuple[str, str]:
348
+ """(subtitle, body html)."""
349
+
350
+ def to_json(self, path: str | Path, *, verbose: bool = False) -> Path:
351
+ p = Path(path)
352
+ p.parent.mkdir(parents=True, exist_ok=True)
353
+ p.write_text(json.dumps(json_safe(self.to_dict(verbose=verbose)), indent=2,
354
+ allow_nan=False), encoding="utf-8")
355
+ return p
356
+
357
+ def to_html_string(self) -> str:
358
+ subtitle, body = self._html_body()
359
+ return render_page(self.title, subtitle, body)
360
+
361
+ def to_html(self, path: str | Path) -> Path:
362
+ p = Path(path)
363
+ p.parent.mkdir(parents=True, exist_ok=True)
364
+ p.write_text(self.to_html_string(), encoding="utf-8")
365
+ return p
366
+
367
+ def show(self) -> None:
368
+ print(self.summary())
369
+
370
+ def __str__(self) -> str:
371
+ return self.summary()
372
+
373
+
374
+ # ---------------------------------------------------------------------------------------------
375
+ # Validation report
376
+ # ---------------------------------------------------------------------------------------------
377
+
378
+ CALIBRATION_EVIDENCE = "optimizer evidence only"
379
+ SEALED_EVIDENCE = "primary evidence of fidelity"
380
+ HOLDOUT_EVIDENCE = "independent row-level evidence (trusted environment)"
381
+
382
+
383
+ @dataclass
384
+ class ValidationReport(ReportShell):
385
+ """Validation of a synthetic table against a fingerprint.
386
+
387
+ ``passed`` is True only if there are no structural failures, no hard-constraint violations
388
+ and the sealed section passes. With a ``sealed_decision`` (set by ``validate``), the sealed
389
+ section fails when a Benjamini-Hochberg-controlled test over all sealed targets finds a
390
+ failure beyond sampling noise (``sealed_failures``); per-target ``passed`` flags keep their
391
+ own-tolerance meaning. Without one, every sealed target must pass. Calibration failures are
392
+ reported but never fail the report (optimizer evidence only); the holdout section is
393
+ informational. No merged score exists.
394
+ """
395
+
396
+ header: dict[str, Any]
397
+ structural: list[Check]
398
+ constraints: list[ConstraintResult]
399
+ calibration: Section
400
+ sealed: Section
401
+ holdout: Section | None = None
402
+ title: str = "Validation report"
403
+ sealed_decision: dict[str, Any] | None = None
404
+
405
+ # -- verdict -------------------------------------------------------------------------
406
+ @property
407
+ def structural_passed(self) -> bool:
408
+ return all(c.passed for c in self.structural)
409
+
410
+ @property
411
+ def hard_violations(self) -> list[ConstraintResult]:
412
+ return [c for c in self.constraints if c.severity == "hard" and not c.passed]
413
+
414
+ @property
415
+ def sealed_failures(self) -> list[TargetResult]:
416
+ """Sealed targets that fail the verdict: all failed ones without a decision, else those
417
+ whose failure is beyond sampling noise under the multiplicity control."""
418
+ if self.sealed_decision is None:
419
+ return [r for r in worst_first(self.sealed.results) if not r.passed]
420
+ ids = set(self.sealed_decision.get("failed", []))
421
+ return [r for r in worst_first(self.sealed.results) if r.id in ids]
422
+
423
+ @property
424
+ def sealed_passed(self) -> bool:
425
+ return not self.sealed_failures
426
+
427
+ @property
428
+ def passed(self) -> bool:
429
+ return self.structural_passed and not self.hard_violations and self.sealed_passed
430
+
431
+ @property
432
+ def sections(self) -> dict[str, Section]:
433
+ out = {"calibration": self.calibration, "sealed": self.sealed}
434
+ if self.holdout is not None:
435
+ out["holdout"] = self.holdout
436
+ return out
437
+
438
+ def failure_reasons(self) -> list[str]:
439
+ reasons = [f"structural: {c.name}: {c.message}" for c in self.structural if not c.passed]
440
+ reasons += [f"hard constraint {c.id} violated by {c.violations} rows"
441
+ + (f" ({c.error})" if c.error else "") for c in self.hard_violations]
442
+ bad = self.sealed_failures
443
+ if bad:
444
+ d = self.sealed_decision
445
+ if d is None:
446
+ reasons.append(f"{len(bad)} of {self.sealed.n} sealed targets failed")
447
+ else:
448
+ reasons.append(
449
+ f"{len(bad)} of {self.sealed.n} sealed targets failed beyond sampling noise "
450
+ f"(sensitivity {d.get('sensitivity')}, FDR q={d.get('q')}): "
451
+ + ", ".join(r.id for r in bad[:5]) + (" ..." if len(bad) > 5 else ""))
452
+ return reasons
453
+
454
+ @property
455
+ def fidelity_gap(self) -> dict[str, float | None]:
456
+ """Calibration minus sealed: pass rate and median distance/tolerance.
457
+
458
+ A large positive pass-rate gap means the generator fits the profile it was calibrated on
459
+ better than properties it never saw (overfitting the profile).
460
+ """
461
+ cp, sp = self.calibration.pass_rate, self.sealed.pass_rate
462
+ cm, sm = self.calibration.median_ratio, self.sealed.median_ratio
463
+ return {
464
+ "pass_rate_gap": None if cp is None or sp is None else cp - sp,
465
+ "median_ratio_gap": None if cm is None or sm is None else sm - cm,
466
+ }
467
+
468
+ # -- serialisation -------------------------------------------------------------------
469
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]:
470
+ return json_safe({
471
+ "report": "validation",
472
+ "passed": self.passed,
473
+ "failure_reasons": self.failure_reasons(),
474
+ "header": self.header,
475
+ "structural": [c.to_dict() for c in self.structural],
476
+ "constraints": [c.to_dict() for c in self.constraints],
477
+ "sections": {k: s.to_dict(verbose) for k, s in self.sections.items()},
478
+ "sealed_decision": self.sealed_decision,
479
+ "fidelity_gap": self.fidelity_gap,
480
+ "merged_score": None, # deliberately never computed (design doc 6.1)
481
+ })
482
+
483
+ def summary(self) -> str:
484
+ h = self.header
485
+ lines = [
486
+ f"Validation {'PASSED' if self.passed else 'FAILED'}"
487
+ f" fingerprint {str(h.get('fingerprint_hash', ''))[:12]}"
488
+ f" policy={h.get('policy')} rows={h.get('n_rows')}",
489
+ ]
490
+ n_bad = sum(not c.passed for c in self.structural)
491
+ lines.append(f" structural {len(self.structural) - n_bad}/{len(self.structural)} "
492
+ "checks ok")
493
+ hard = [c for c in self.constraints if c.severity == "hard"]
494
+ lines.append(f" constraints {len(hard) - len(self.hard_violations)}/{len(hard)} hard "
495
+ "constraints satisfied")
496
+ for s in self.sections.values():
497
+ tag = {"calibration": f"({CALIBRATION_EVIDENCE})",
498
+ "sealed": f"({SEALED_EVIDENCE})", "holdout": "(row-level)"}[s.name]
499
+ lines.append(f" {s.name:<12} {s.n_passed}/{s.n} passed "
500
+ f"({_pct(s.pass_rate)}) {tag}")
501
+ if s.name == "sealed" and self.sealed_decision is not None:
502
+ d = self.sealed_decision
503
+ lines.append(f" {'':<12} {len(self.sealed_failures)} failed beyond sampling "
504
+ f"noise (sensitivity {d.get('sensitivity')}, "
505
+ f"FDR q={d.get('q')})")
506
+ gap = self.fidelity_gap["pass_rate_gap"]
507
+ if gap is not None:
508
+ lines.append(f" calibration - sealed pass-rate gap: {100 * gap:+.1f} pts")
509
+ for s in self.sections.values():
510
+ bad = [r for r in s.worst(3) if not r.passed]
511
+ for r in bad:
512
+ lines.append(f" worst {s.name}: {r.id} d={_fmt(r.distance)} "
513
+ f"tol={_fmt(r.tolerance)}")
514
+ if h.get("pseudonymised_columns"):
515
+ lines.append(" pseudonymised columns (stand-in tokens, compared on their level "
516
+ "structure): " + ", ".join(h["pseudonymised_columns"]))
517
+ if h.get("reference_columns"):
518
+ lines.append(" reference keys (fresh keys, compared by group size): "
519
+ + ", ".join(h["reference_columns"]))
520
+ for reason in self.failure_reasons()[:5]:
521
+ lines.append(f" ! {reason}")
522
+ return "\n".join(lines)
523
+
524
+ def _html_body(self) -> tuple[str, str]:
525
+ h = self.header
526
+ parts = []
527
+ parts.append('<section class="card">' + meta_list({
528
+ "fingerprint hash": h.get("fingerprint_hash"),
529
+ "dataset": h.get("dataset"),
530
+ "disclosure policy": h.get("policy"),
531
+ "engine version": h.get("engine_version"),
532
+ "fingerprint engine": h.get("fingerprint_engine_version"),
533
+ "format version": h.get("fingerprint_version"),
534
+ "synthetic rows": h.get("n_rows"),
535
+ "seed": h.get("seed"),
536
+ **({"pseudonymised columns": ", ".join(h["pseudonymised_columns"])}
537
+ if h.get("pseudonymised_columns") else {}),
538
+ }) + "</section>")
539
+ if self.passed:
540
+ parts.append('<div class="verdict ok">PASSED: structure and hard constraints ok, '
541
+ + ("no sealed target fails beyond sampling noise."
542
+ if self.sealed_decision is not None
543
+ else "every sealed target within tolerance.") + "</div>")
544
+ else:
545
+ items = "".join(f"<li>{esc(r)}</li>" for r in self.failure_reasons())
546
+ parts.append(f'<div class="verdict bad">FAILED<ul>{items}</ul></div>')
547
+
548
+ # gap
549
+ g = self.fidelity_gap
550
+ gap_cells = {
551
+ "calibration pass rate": _pct(self.calibration.pass_rate),
552
+ "sealed pass rate": _pct(self.sealed.pass_rate),
553
+ "pass-rate gap (calib - sealed)":
554
+ "n/a" if g["pass_rate_gap"] is None else f"{100 * g['pass_rate_gap']:+.1f} pts",
555
+ "median d/tol gap (sealed - calib)": _fmt(g["median_ratio_gap"], 3),
556
+ }
557
+ parts.append('<section class="card"><h2>Calibration vs sealed fidelity</h2>'
558
+ '<p class="sub">Only sealed results are evidence of fidelity. A large gap '
559
+ "means the generator fits the profile it was calibrated on better than "
560
+ "properties it never saw.</p>" + stats_row(gap_cells) + "</section>")
561
+
562
+ # structural + constraints
563
+ srows = [[pill(c.passed), esc(c.name), esc(c.message)] for c in self.structural]
564
+ crows = [[pill(c.passed), f"<code>{esc(c.id)}</code>", f"<code>{esc(c.expression)}</code>",
565
+ esc(c.severity), str(c.violations), _pct(c.violation_rate), esc(c.error or "")]
566
+ for c in self.constraints]
567
+ parts.append('<section class="card"><h2>Structure</h2>'
568
+ + html_table(["", "check", "result"], srows)
569
+ + "<h2 style=\"margin-top:14px\">Constraints</h2>"
570
+ + html_table(["", "id", "expression", "severity", "violations", "rate",
571
+ "note"], crows, numeric={4, 5},
572
+ empty="No confirmed constraints.")
573
+ + "</section>")
574
+
575
+ for s in self.sections.values():
576
+ parts.append(_section_html(s))
577
+ if self.holdout is None:
578
+ parts.append('<section class="card"><h2>3. Row-level holdout</h2><p class="muted">'
579
+ "Not run: no holdout data supplied (requires the trusted environment)."
580
+ "</p></section>")
581
+ subtitle = ("Three separate sections; never merged into a single score. "
582
+ "Calibration = optimizer evidence only; sealed = evidence of fidelity.")
583
+ return subtitle, "".join(parts)
584
+
585
+
586
+ _SECTION_NUM = {"calibration": "1", "sealed": "2", "holdout": "3"}
587
+
588
+
589
+ def _section_html(s: Section) -> str:
590
+ stats = stats_row({
591
+ "pass rate": _pct(s.pass_rate),
592
+ "passed": f"{s.n_passed}/{s.n}",
593
+ "median distance / tolerance": _fmt(s.median_ratio, 3),
594
+ })
595
+ notes = "".join(f'<div class="note">{esc(n)}</div>' for n in s.notes)
596
+ fam_rows = [[esc(f), f"{v['passed']}/{v['n']}", _pct(v["pass_rate"])]
597
+ for f, v in s.by_family().items()]
598
+ fam = ("<details><summary>By family</summary>"
599
+ + html_table(["family", "passed", "pass rate"], fam_rows, numeric={1, 2})
600
+ + "</details>")
601
+ rows = target_rows(s.worst())
602
+ more = (f'<p class="muted">Showing the 500 worst of {s.n}.</p>' if s.n > 500 else "")
603
+ return (f'<section class="card"><h2>{_SECTION_NUM.get(s.name, "")}. {esc(s.title)}</h2>'
604
+ f'<p class="sub">{esc(s.evidence)}</p>{notes}{stats}{fam}'
605
+ + html_table(TARGET_HEADERS, rows, numeric={3, 4, 5}, empty="No targets.")
606
+ + more + "</section>")
607
+
608
+
609
+ __all__ = [
610
+ "CALIBRATION_EVIDENCE",
611
+ "HOLDOUT_EVIDENCE",
612
+ "SEALED_EVIDENCE",
613
+ "Check",
614
+ "ConstraintResult",
615
+ "ReportShell",
616
+ "Section",
617
+ "TargetResult",
618
+ "ValidationReport",
619
+ "html_table",
620
+ "json_safe",
621
+ "meta_list",
622
+ "pill",
623
+ "render_page",
624
+ "stats_row",
625
+ "target_rows",
626
+ "worst_first",
627
+ ]