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,408 @@
1
+ """The ``.dfp`` container: a deterministic zip of JSON + ``.npy`` arrays + checksums.
2
+
3
+ Layout::
4
+
5
+ manifest.json
6
+ arrays/<name>.npy numeric / fixed-width unicode arrays (never object dtype)
7
+ targets/calibration.json
8
+ targets/sealed.json
9
+ diagnostics/<name>.json optional
10
+ checksums.sha256 "<sha256-hex> <path>" for every other file
11
+
12
+ Loading order (fail closed): open zip -> path safety -> file allow-list -> bounded
13
+ decompression (per-member, total and ratio caps) -> checksums -> JSON parse -> version
14
+ compatibility -> manifest schema -> cross references -> seal hash -> ``.npy`` header checks.
15
+ Nothing in the archive is ever imported or executed; ``np.load`` runs with
16
+ ``allow_pickle=False`` and only after the header's declared size matches the payload.
17
+
18
+ The checksums and the seal hash protect *integrity* (accidental corruption, partial edits),
19
+ not *authenticity*: anyone can rewrite a member and regenerate them.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import io
26
+ import json
27
+ import os
28
+ import struct
29
+ import zipfile
30
+ import zlib
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path, PurePosixPath
33
+ from typing import Any
34
+
35
+ import numpy as np
36
+
37
+ from ectype._version import FORMAT_VERSION
38
+ from ectype.errors import FingerprintError, IntegrityError, VersionError
39
+ from ectype.fingerprint.schema import (
40
+ CALIBRATION_REF,
41
+ SEALED_REF,
42
+ Manifest,
43
+ TargetSet,
44
+ validate_lenient,
45
+ )
46
+
47
+ CHECKSUMS = "checksums.sha256"
48
+ MANIFEST = "manifest.json"
49
+ _ALLOWED_DIRS = ("arrays/", "targets/", "diagnostics/")
50
+ #: Hard decompression limits (zip-bomb defence). Every member is streamed and the read aborts
51
+ #: as soon as one of them is exceeded, whatever sizes the archive declares.
52
+ _MAX_MEMBER_BYTES = 1024**3 # one member, uncompressed
53
+ _MAX_TOTAL_BYTES = 2 * 1024**3 # all members together, uncompressed
54
+ _MAX_RATIO = 250 # uncompressed / compressed, for members above ...
55
+ _RATIO_MIN_BYTES = 8 * 1024**2 # ... this size (small members compress arbitrarily)
56
+ _CHUNK = 1024**2
57
+ _MAX_MEMBERS = 100_000
58
+ _ZIP_DATE = (2000, 1, 1, 0, 0, 0)
59
+
60
+
61
+ def sha256_bytes(data: bytes) -> str:
62
+ return hashlib.sha256(data).hexdigest()
63
+
64
+
65
+ def canonical_json(obj: Any) -> bytes:
66
+ """Deterministic JSON encoding used for every JSON file in the container."""
67
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
68
+ allow_nan=False).encode("utf-8")
69
+
70
+
71
+ def _array_bytes(arr: np.ndarray) -> bytes:
72
+ if arr.dtype == object:
73
+ raise FingerprintError("object-dtype arrays cannot be stored; use numeric or 'U' dtype")
74
+ buf = io.BytesIO()
75
+ np.save(buf, np.ascontiguousarray(arr), allow_pickle=False)
76
+ return buf.getvalue()
77
+
78
+
79
+ def _check_member_name(name: str) -> None:
80
+ p = PurePosixPath(name)
81
+ if (
82
+ name.startswith("/")
83
+ or "\\" in name
84
+ or ".." in p.parts
85
+ or ":" in name
86
+ or name.endswith("/")
87
+ ):
88
+ raise IntegrityError(f"unsafe path in fingerprint archive: {name!r}")
89
+ if name in (MANIFEST, CHECKSUMS):
90
+ return
91
+ if not name.startswith(_ALLOWED_DIRS) or len(p.parts) != 2:
92
+ raise IntegrityError(f"unexpected file in fingerprint archive: {name!r}")
93
+ if name.startswith("arrays/") and not name.endswith(".npy"):
94
+ raise IntegrityError(f"arrays must be .npy files: {name!r}")
95
+ if name.startswith(("targets/", "diagnostics/")) and not name.endswith(".json"):
96
+ raise IntegrityError(f"targets/diagnostics must be .json files: {name!r}")
97
+
98
+
99
+ def _parse_version(version: str) -> tuple[int, int]:
100
+ parts = str(version).split(".")
101
+ try:
102
+ if len(parts) != 3:
103
+ raise ValueError
104
+ major, minor, _ = (int(x) for x in parts)
105
+ except ValueError:
106
+ raise VersionError(f"invalid fingerprint_version {version!r}") from None
107
+ return major, minor
108
+
109
+
110
+ def _check_version(version: str) -> bool:
111
+ """Refuse other major versions. Returns True when ``version`` is a *newer minor* version
112
+ of the supported major (load permissively, warning about unknown fields)."""
113
+ major, minor = _parse_version(version)
114
+ s_major, s_minor = _parse_version(FORMAT_VERSION)
115
+ if major != s_major:
116
+ raise VersionError(
117
+ f"fingerprint format {version} is not supported by this engine "
118
+ f"(supports {s_major}.x); upgrade or downgrade ectype"
119
+ )
120
+ return minor > s_minor
121
+
122
+
123
+ def is_newer_minor(version: str) -> bool:
124
+ """True for a same-major, newer-minor ``version`` (never raises)."""
125
+ try:
126
+ return _check_version(version)
127
+ except VersionError:
128
+ return False
129
+
130
+
131
+ @dataclass
132
+ class ContainerPayload:
133
+ """Raw validated contents of a container (used by ``Fingerprint``)."""
134
+
135
+ manifest: Manifest
136
+ arrays: dict[str, np.ndarray] = field(default_factory=dict) # key: "arrays/x.npy"
137
+ calibration: TargetSet = field(default_factory=lambda: TargetSet(kind="calibration"))
138
+ sealed_bytes: bytes = b""
139
+ diagnostics: dict[str, Any] = field(default_factory=dict) # key: "diagnostics/x.json"
140
+
141
+
142
+ def encode_sealed(sealed: TargetSet) -> bytes:
143
+ return canonical_json(sealed.model_dump(mode="json"))
144
+
145
+
146
+ def write_container(payload: ContainerPayload, path: str | Path) -> Path:
147
+ """Write a deterministic ``.dfp`` zip. Returns the path written."""
148
+ files: dict[str, bytes] = {}
149
+ for name, arr in payload.arrays.items():
150
+ _check_member_name(name)
151
+ files[name] = _array_bytes(np.asarray(arr))
152
+ unreferenced = sorted(set(files) - referenced_arrays(payload.manifest))
153
+ if unreferenced:
154
+ raise IntegrityError(f"arrays not referenced by the manifest: {unreferenced[:10]}")
155
+ files[payload.manifest.targets.calibration_ref] = canonical_json(
156
+ payload.calibration.model_dump(mode="json")
157
+ )
158
+ files[payload.manifest.targets.sealed_ref] = payload.sealed_bytes
159
+ for name, obj in payload.diagnostics.items():
160
+ _check_member_name(name)
161
+ files[name] = canonical_json(obj)
162
+ files[MANIFEST] = canonical_json(payload.manifest.model_dump(mode="json"))
163
+ _check_references(payload.manifest, set(files))
164
+
165
+ lines = [f"{sha256_bytes(data)} {name}" for name, data in sorted(files.items())]
166
+ files[CHECKSUMS] = ("\n".join(lines) + "\n").encode("utf-8")
167
+
168
+ out = Path(path)
169
+ out.parent.mkdir(parents=True, exist_ok=True)
170
+ tmp = out.with_suffix(out.suffix + ".tmp")
171
+ with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED) as zf:
172
+ for name in sorted(files):
173
+ info = zipfile.ZipInfo(name, date_time=_ZIP_DATE)
174
+ info.compress_type = _compress_type(files[name])
175
+ info.external_attr = 0o644 << 16
176
+ zf.writestr(info, files[name])
177
+ tmp.replace(out)
178
+ return out
179
+
180
+
181
+ def referenced_arrays(manifest: Manifest) -> set[str]:
182
+ """Every ``arrays/*.npy`` path the manifest mentions (model specs and free-form sections
183
+ such as ``temporal``)."""
184
+ found: set[str] = set()
185
+
186
+ def walk(obj: Any) -> None:
187
+ if isinstance(obj, str):
188
+ if obj.startswith("arrays/") and obj.endswith(".npy"):
189
+ found.add(obj)
190
+ elif isinstance(obj, dict):
191
+ for v in obj.values():
192
+ walk(v)
193
+ elif isinstance(obj, list | tuple):
194
+ for v in obj:
195
+ walk(v)
196
+
197
+ walk(manifest.model_dump(mode="json"))
198
+ return found
199
+
200
+
201
+ def _check_references(manifest: Manifest, present: set[str]) -> None:
202
+ refs: list[str] = [manifest.targets.calibration_ref, manifest.targets.sealed_ref]
203
+ m = manifest.model
204
+ specs = list(m.marginals.values()) + list(m.encodings.values()) + list(
205
+ m.conditional.values()) + list(m.missingness.values()) + list(m.identifiers.values())
206
+ if m.joint is not None:
207
+ specs.append(m.joint)
208
+ for spec in specs:
209
+ refs.extend(spec.arrays.values())
210
+ for group in m.entities:
211
+ refs.append(group.keys)
212
+ for attr in group.attributes:
213
+ refs.extend((attr.values, attr.state))
214
+ refs.extend(r for r in (attr.rest_levels, attr.rest_probs) if r is not None)
215
+ if group.anchor is not None:
216
+ refs.extend((group.anchor.values, group.anchor.state))
217
+ missing = sorted(r for r in refs if r not in present)
218
+ if missing:
219
+ raise IntegrityError(f"manifest references missing files: {missing}")
220
+
221
+
222
+ def _compress_type(data: bytes) -> int:
223
+ """``ZIP_DEFLATED``, unless the member is large and so compressible that ``read_container``
224
+ would refuse it as a possible zip bomb (ratio cap ``_MAX_RATIO`` above
225
+ ``_RATIO_MIN_BYTES``, e.g. a big identity correlation): such a member is stored
226
+ uncompressed, so the writer never produces a file the reader refuses. Half the cap is used
227
+ as the margin; the deflate settings are those ``zipfile`` uses."""
228
+ if len(data) <= _RATIO_MIN_BYTES:
229
+ return zipfile.ZIP_DEFLATED
230
+ co = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
231
+ size = len(co.compress(data)) + len(co.flush())
232
+ if len(data) > (_MAX_RATIO // 2) * max(size, 1):
233
+ return zipfile.ZIP_STORED
234
+ return zipfile.ZIP_DEFLATED
235
+
236
+
237
+ def _read_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo, budget: int,
238
+ archive_bytes: int) -> bytes:
239
+ """Stream one member under hard limits (never trusts the declared sizes)."""
240
+ limit = min(_MAX_MEMBER_BYTES, budget)
241
+ compressed = max(1, min(info.compress_size, archive_bytes))
242
+ buf = bytearray()
243
+ with zf.open(info, "r") as fh:
244
+ while True:
245
+ chunk = fh.read(_CHUNK)
246
+ if not chunk:
247
+ break
248
+ buf += chunk
249
+ n = len(buf)
250
+ if n > info.file_size:
251
+ raise IntegrityError(
252
+ f"member {info.filename} inflates beyond its declared size")
253
+ if n > limit:
254
+ raise IntegrityError(f"member too large: {info.filename}")
255
+ if n > _RATIO_MIN_BYTES and n > _MAX_RATIO * compressed:
256
+ raise IntegrityError(
257
+ f"member {info.filename} exceeds the maximum compression ratio "
258
+ f"({_MAX_RATIO}:1); refusing a possible zip bomb")
259
+ if len(buf) != info.file_size:
260
+ raise IntegrityError(f"member {info.filename} is shorter than its declared size")
261
+ return bytes(buf)
262
+
263
+
264
+ _ZIP_ERRORS = (zipfile.BadZipFile, zipfile.LargeZipFile, zlib.error, EOFError,
265
+ NotImplementedError, RuntimeError, ValueError, OSError, struct.error)
266
+
267
+
268
+ def _read_members(p: Path) -> tuple[list[str], dict[str, bytes]]:
269
+ try:
270
+ archive_bytes = p.stat().st_size
271
+ with zipfile.ZipFile(p, "r") as zf:
272
+ infos = zf.infolist()
273
+ if len(infos) > _MAX_MEMBERS:
274
+ raise IntegrityError("fingerprint archive has too many members")
275
+ names = []
276
+ declared = 0
277
+ for info in infos:
278
+ _check_member_name(info.filename)
279
+ if info.file_size > _MAX_MEMBER_BYTES:
280
+ raise IntegrityError(f"member too large: {info.filename}")
281
+ declared += info.file_size
282
+ names.append(info.filename)
283
+ if declared > _MAX_TOTAL_BYTES:
284
+ raise IntegrityError("fingerprint archive is too large when decompressed")
285
+ if len(set(names)) != len(names):
286
+ raise IntegrityError("duplicate members in fingerprint archive")
287
+ if CHECKSUMS not in names or MANIFEST not in names:
288
+ raise IntegrityError(
289
+ "fingerprint archive lacks manifest.json or checksums.sha256")
290
+ data: dict[str, bytes] = {}
291
+ total = 0
292
+ for info in infos:
293
+ raw = _read_member(zf, info, _MAX_TOTAL_BYTES - total, archive_bytes)
294
+ total += len(raw)
295
+ data[info.filename] = raw
296
+ except FingerprintError:
297
+ raise
298
+ except _ZIP_ERRORS as e:
299
+ hint = ""
300
+ if isinstance(e, zipfile.BadZipFile):
301
+ hint = (" (if this is a data table, fit it first: "
302
+ "`ectype profile <table> -o <name>.dfp`, or `ectype.fit(...)` in Python)")
303
+ raise IntegrityError(f"{p} is not a valid fingerprint archive: "
304
+ f"{type(e).__name__}: {e}{hint}") from None
305
+ return names, data
306
+
307
+
308
+ def _json(data: bytes, name: str) -> Any:
309
+ try:
310
+ return json.loads(data.decode("utf-8"))
311
+ except (UnicodeDecodeError, json.JSONDecodeError, RecursionError) as e:
312
+ raise IntegrityError(f"{name} is not valid JSON: {e}") from None
313
+
314
+
315
+ def _load_npy(name: str, raw: bytes) -> np.ndarray:
316
+ """Validate the ``.npy`` header before allocating anything, then load."""
317
+ from numpy.lib import format as npf
318
+
319
+ fh = io.BytesIO(raw)
320
+ try:
321
+ version = npf.read_magic(fh)
322
+ if version == (1, 0):
323
+ shape, fortran, dtype = npf.read_array_header_1_0(fh)
324
+ elif version == (2, 0):
325
+ shape, fortran, dtype = npf.read_array_header_2_0(fh)
326
+ else:
327
+ raise ValueError(f"unsupported .npy version {version}")
328
+ except (ValueError, TypeError, SyntaxError, struct.error, EOFError) as e:
329
+ raise IntegrityError(f"array {name} could not be loaded safely: invalid .npy header: "
330
+ f"{e}") from None
331
+ if dtype.hasobject:
332
+ raise IntegrityError(f"array {name} could not be loaded safely: object dtype")
333
+ count = 1
334
+ for d in shape:
335
+ if not isinstance(d, int) or d < 0:
336
+ raise IntegrityError(f"array {name} has an invalid shape {shape!r}")
337
+ count *= d
338
+ payload = len(raw) - fh.tell()
339
+ if count * dtype.itemsize != payload:
340
+ raise IntegrityError(
341
+ f"array {name}: header declares shape {shape} of {dtype} "
342
+ f"({count * dtype.itemsize} bytes) but the payload has {payload} bytes")
343
+ try:
344
+ return np.load(io.BytesIO(raw), allow_pickle=False)
345
+ except ValueError as e:
346
+ raise IntegrityError(f"array {name} could not be loaded safely: {e}") from None
347
+
348
+
349
+ def read_container(path: str | os.PathLike[str]) -> ContainerPayload:
350
+ """Load and fully validate a ``.dfp`` container. Raises on any integrity problem."""
351
+ p = Path(path)
352
+ if not p.is_file():
353
+ raise FingerprintError(f"fingerprint file not found: {p}")
354
+ names, data = _read_members(p)
355
+
356
+ expected: dict[str, str] = {}
357
+ try:
358
+ checksum_text = data[CHECKSUMS].decode("utf-8")
359
+ except UnicodeDecodeError:
360
+ raise IntegrityError("checksums.sha256 is not UTF-8") from None
361
+ for line in checksum_text.splitlines():
362
+ if not line.strip():
363
+ continue
364
+ digest, _, name = line.partition(" ")
365
+ if not name or len(digest) != 64:
366
+ raise IntegrityError(f"malformed checksum line: {line!r}")
367
+ expected[name] = digest
368
+ actual_names = set(data) - {CHECKSUMS}
369
+ if set(expected) != actual_names:
370
+ extra = sorted(actual_names - set(expected))
371
+ absent = sorted(set(expected) - actual_names)
372
+ raise IntegrityError(f"checksum list mismatch (unlisted: {extra}, missing: {absent})")
373
+ for name, digest in expected.items():
374
+ if sha256_bytes(data[name]) != digest:
375
+ raise IntegrityError(f"checksum mismatch for {name}: file was modified")
376
+
377
+ raw_manifest = _json(data[MANIFEST], MANIFEST)
378
+ if not isinstance(raw_manifest, dict):
379
+ raise IntegrityError("manifest.json must be a JSON object")
380
+ lenient = _check_version(str(raw_manifest.get("fingerprint_version", "")))
381
+ manifest = validate_lenient(Manifest, raw_manifest, lenient=lenient, what="manifest.json")
382
+ targets = manifest.targets
383
+ if targets.calibration_ref != CALIBRATION_REF or targets.sealed_ref != SEALED_REF:
384
+ raise IntegrityError(
385
+ f"target references must be {CALIBRATION_REF!r} and {SEALED_REF!r}")
386
+ _check_references(manifest, set(data))
387
+
388
+ sealed_bytes = data[targets.sealed_ref]
389
+ if sha256_bytes(sealed_bytes) != targets.seal_hash:
390
+ raise IntegrityError("sealed targets do not match the seal hash committed at fit time")
391
+ sealed_raw = _json(sealed_bytes, SEALED_REF)
392
+ if not isinstance(sealed_raw, dict) or sealed_raw.get("kind") != "sealed":
393
+ raise IntegrityError(f"{SEALED_REF} is not a sealed target set")
394
+
395
+ cal_raw = _json(data[targets.calibration_ref], CALIBRATION_REF)
396
+ calibration = validate_lenient(TargetSet, cal_raw, lenient=lenient, what=CALIBRATION_REF)
397
+ if calibration.kind != "calibration":
398
+ raise IntegrityError(f"{CALIBRATION_REF} is not a calibration target set")
399
+
400
+ array_names = [n for n in names if n.startswith("arrays/")]
401
+ unreferenced = sorted(set(array_names) - referenced_arrays(manifest))
402
+ if unreferenced:
403
+ raise IntegrityError("archive contains arrays the manifest does not reference: "
404
+ f"{unreferenced[:10]}")
405
+ arrays = {name: _load_npy(name, data[name]) for name in array_names}
406
+ diagnostics = {n: _json(data[n], n) for n in names if n.startswith("diagnostics/")}
407
+ return ContainerPayload(manifest=manifest, arrays=arrays, calibration=calibration,
408
+ sealed_bytes=sealed_bytes, diagnostics=diagnostics)
@@ -0,0 +1,263 @@
1
+ """The in-memory ``Fingerprint`` object.
2
+
3
+ A fingerprint holds the manifest, its arrays, the calibration targets and the *sealed* targets.
4
+ Sealed targets are deliberately hard to reach: they are stored as committed bytes and only
5
+ decoded by ``open_seal()``, which the validator calls. The calibrator receives a
6
+ ``CalibrationView`` that has no route to them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+
21
+ from ectype.fingerprint.container import (
22
+ ContainerPayload,
23
+ canonical_json,
24
+ encode_sealed,
25
+ is_newer_minor,
26
+ read_container,
27
+ referenced_arrays,
28
+ sha256_bytes,
29
+ write_container,
30
+ )
31
+ from ectype.fingerprint.schema import (
32
+ Manifest,
33
+ ModelSpec,
34
+ Target,
35
+ TargetSet,
36
+ validate_lenient,
37
+ )
38
+
39
+ _REF_HASH_CHARS = 12
40
+ _REF_NAME_CHARS = 96
41
+
42
+
43
+ class ArrayStore:
44
+ """Named arrays referenced from model specs as ``arrays/<name>.npy``."""
45
+
46
+ def __init__(self, arrays: dict[str, np.ndarray] | None = None) -> None:
47
+ self._arrays: dict[str, np.ndarray] = dict(arrays or {})
48
+
49
+ @staticmethod
50
+ def ref(name: str) -> str:
51
+ """The container path for logical array ``name``.
52
+
53
+ Injective: a readable, sanitised (and length-capped) form of ``name`` plus a short
54
+ hash of the *original* name, so ``"a b"`` and ``"a_b"`` never share a file.
55
+ """
56
+ safe = "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in name)
57
+ safe = safe[:_REF_NAME_CHARS]
58
+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:_REF_HASH_CHARS]
59
+ return f"arrays/{safe}-{digest}.npy"
60
+
61
+ def put(self, name: str, arr: np.ndarray) -> str:
62
+ """Store ``arr`` under ``name`` and return its ref.
63
+
64
+ An existing entry is never overwritten: putting an identical array again returns the
65
+ existing ref, and putting a *different* array under a ref that is already taken
66
+ stores it under a fresh, suffixed ref instead (callers always use the returned ref).
67
+ """
68
+ a = np.asarray(arr)
69
+ if a.dtype == object:
70
+ a = a.astype(str)
71
+ base = self.ref(name)
72
+ ref, k = base, 0
73
+ while ref in self._arrays:
74
+ if _same_array(self._arrays[ref], a):
75
+ return ref
76
+ k += 1
77
+ ref = f"{base.removesuffix('.npy')}-{k}.npy"
78
+ self._arrays[ref] = a
79
+ return ref
80
+
81
+ def get(self, ref: str) -> np.ndarray:
82
+ return self._arrays[ref]
83
+
84
+ def __contains__(self, ref: object) -> bool:
85
+ return ref in self._arrays
86
+
87
+ def as_dict(self) -> dict[str, np.ndarray]:
88
+ return dict(self._arrays)
89
+
90
+ def subset(self, refs: set[str]) -> ArrayStore:
91
+ return ArrayStore({k: v for k, v in self._arrays.items() if k in refs})
92
+
93
+
94
+ def _same_array(a: np.ndarray, b: np.ndarray) -> bool:
95
+ return (a.dtype == b.dtype and a.shape == b.shape
96
+ and np.ascontiguousarray(a).tobytes() == np.ascontiguousarray(b).tobytes())
97
+
98
+
99
+ @dataclass
100
+ class CalibrationView:
101
+ """What calibration may see: the model and calibration targets. Never sealed targets."""
102
+
103
+ manifest: Manifest
104
+ arrays: ArrayStore
105
+ calibration: TargetSet
106
+
107
+
108
+ @dataclass
109
+ class Fingerprint:
110
+ manifest: Manifest
111
+ arrays: ArrayStore = field(default_factory=ArrayStore)
112
+ calibration: TargetSet = field(default_factory=lambda: TargetSet(kind="calibration"))
113
+ _sealed_bytes: bytes = b""
114
+ diagnostics: dict[str, Any] = field(default_factory=dict)
115
+
116
+ # -- construction --------------------------------------------------------------------
117
+ @classmethod
118
+ def build(cls, manifest: Manifest, arrays: ArrayStore, calibration: TargetSet,
119
+ sealed: TargetSet, diagnostics: dict[str, Any] | None = None) -> Fingerprint:
120
+ """Assemble a fingerprint, committing the seal hash for ``sealed``."""
121
+ sealed_bytes = encode_sealed(sealed)
122
+ m = manifest.model_copy(deep=True)
123
+ m.targets.seal_hash = sha256_bytes(sealed_bytes)
124
+ m.targets.n_calibration = len(calibration.targets)
125
+ m.targets.n_sealed = len(sealed.targets)
126
+ m.targets.sealed_families = sorted({t.family or t.metric for t in sealed.targets})
127
+ return cls(manifest=m, arrays=arrays, calibration=calibration,
128
+ _sealed_bytes=sealed_bytes, diagnostics=dict(diagnostics or {}))
129
+
130
+ # -- persistence ---------------------------------------------------------------------
131
+ def save(self, path: str | Path) -> Path:
132
+ # Arrays no model spec references (superseded by mutate/calibrate, or fitted for a
133
+ # candidate model that was not selected) are not written.
134
+ payload = ContainerPayload(
135
+ manifest=self.manifest,
136
+ arrays=self._live_arrays(),
137
+ calibration=self.calibration,
138
+ sealed_bytes=self._sealed_bytes,
139
+ diagnostics={
140
+ (k if k.startswith("diagnostics/") else f"diagnostics/{k}.json"): v
141
+ for k, v in self.diagnostics.items()
142
+ },
143
+ )
144
+ return write_container(payload, path)
145
+
146
+ @classmethod
147
+ def load(cls, path: str | os.PathLike[str]) -> Fingerprint:
148
+ p = read_container(path)
149
+ diags = {k.removeprefix("diagnostics/").removesuffix(".json"): v
150
+ for k, v in p.diagnostics.items()}
151
+ return cls(manifest=p.manifest, arrays=ArrayStore(p.arrays), calibration=p.calibration,
152
+ _sealed_bytes=p.sealed_bytes, diagnostics=diags)
153
+
154
+ def _live_arrays(self) -> dict[str, np.ndarray]:
155
+ refs = referenced_arrays(self.manifest)
156
+ return {k: v for k, v in self.arrays.as_dict().items() if k in refs}
157
+
158
+ # -- identity ------------------------------------------------------------------------
159
+ def content_hash(self) -> str:
160
+ """Identity of the fingerprint's content (ignores creation timestamp and arrays that
161
+ nothing references, which are not saved)."""
162
+ m = self.manifest.model_dump(mode="json")
163
+ m.get("provenance", {}).pop("created_at", None)
164
+ h = hashlib.sha256(canonical_json(m))
165
+ live = self._live_arrays()
166
+ for ref in sorted(live):
167
+ a = live[ref]
168
+ h.update(ref.encode())
169
+ h.update(str(a.dtype).encode())
170
+ h.update(str(a.shape).encode())
171
+ h.update(np.ascontiguousarray(a).tobytes())
172
+ h.update(canonical_json(self.calibration.model_dump(mode="json")))
173
+ h.update(self._sealed_bytes)
174
+ return h.hexdigest()
175
+
176
+ # -- targets -------------------------------------------------------------------------
177
+ def open_seal(self) -> TargetSet:
178
+ """Decode sealed targets (validation only). Verifies the committed hash."""
179
+ from ectype.errors import IntegrityError
180
+
181
+ if sha256_bytes(self._sealed_bytes) != self.manifest.targets.seal_hash:
182
+ raise IntegrityError("sealed targets do not match the committed seal hash")
183
+ try:
184
+ raw = json.loads(self._sealed_bytes.decode("utf-8"))
185
+ except (UnicodeDecodeError, json.JSONDecodeError) as e:
186
+ raise IntegrityError(f"sealed targets are not valid JSON: {e}") from None
187
+ sealed = validate_lenient(TargetSet, raw, lenient=is_newer_minor(
188
+ self.manifest.fingerprint_version), what="sealed targets")
189
+ if sealed.kind != "sealed":
190
+ raise IntegrityError("the committed sealed targets are not a sealed target set")
191
+ return sealed
192
+
193
+ def calibration_view(self) -> CalibrationView:
194
+ return CalibrationView(manifest=self.manifest.model_copy(deep=True),
195
+ arrays=self.arrays, calibration=self.calibration)
196
+
197
+ def all_target_ids(self) -> list[str]:
198
+ return [t.id for t in self.calibration.targets] + [t.id for t in self.open_seal().targets]
199
+
200
+ # -- convenience ---------------------------------------------------------------------
201
+ def spec_arrays(self, spec: ModelSpec) -> dict[str, np.ndarray]:
202
+ return {name: self.arrays.get(ref) for name, ref in spec.arrays.items()}
203
+
204
+ def copy(self) -> Fingerprint:
205
+ return Fingerprint(manifest=self.manifest.model_copy(deep=True),
206
+ arrays=ArrayStore(self.arrays.as_dict()),
207
+ calibration=self.calibration.model_copy(deep=True),
208
+ _sealed_bytes=self._sealed_bytes,
209
+ diagnostics=copy.deepcopy(self.diagnostics))
210
+
211
+ @property
212
+ def suggested_constraints(self) -> list[Any]:
213
+ return list(self.manifest.constraints.suggested)
214
+
215
+ def confirm_constraint(self, constraint_id: str) -> Fingerprint:
216
+ """Promote a suggested constraint to a confirmed hard constraint (returns a copy)."""
217
+ from ectype.errors import ConstraintError
218
+ from ectype.fingerprint.schema import ConstraintSpec
219
+ from ectype.types import Enforcement, Severity
220
+
221
+ fp = self.copy()
222
+ sugg = {s.id: s for s in fp.manifest.constraints.suggested}
223
+ if constraint_id not in sugg:
224
+ raise ConstraintError(f"no suggested constraint with id {constraint_id!r}")
225
+ s = sugg[constraint_id]
226
+ if s.expression.strip() == "true":
227
+ raise ConstraintError(
228
+ f"suggestion {constraint_id!r} ({s.family}) is evidence only and cannot be "
229
+ f"enforced as an expression in this format version")
230
+ fp.manifest.constraints.suggested = [
231
+ x for x in fp.manifest.constraints.suggested if x.id != constraint_id
232
+ ]
233
+ fp.manifest.provenance.lineage.append({
234
+ "op": "confirm_constraint", "parent": self.content_hash(),
235
+ "constraint_id": constraint_id, "expression": s.expression})
236
+ fp.manifest.constraints.confirmed.append(ConstraintSpec(
237
+ id=s.id, expression=s.expression, severity=Severity.HARD,
238
+ enforcement=Enforcement.REJECTION, source="confirmed_suggestion",
239
+ description=f"confirmed from suggestion ({s.family}, support={s.support})",
240
+ ))
241
+ return fp
242
+
243
+ # -- scenario conveniences (design §7.3 chaining) ----------------------------------------
244
+ def mutate(self, **changes: Any) -> Fingerprint:
245
+ """Return a mutated copy (see ``ectype.scenarios.mutate`` for the full
246
+ ``ScenarioResult`` with achieved values and collateral diagnostics)."""
247
+ from ectype.scenarios import mutate
248
+
249
+ return mutate(self, **changes).fingerprint
250
+
251
+ def merge(self, *others: Fingerprint, weights: list[float] | None = None) -> Fingerprint:
252
+ from ectype.scenarios import merge
253
+
254
+ return merge([self, *others], weights)
255
+
256
+ def __repr__(self) -> str:
257
+ m = self.manifest
258
+ return (f"Fingerprint(dataset={m.dataset.name!r}, rows={m.dataset.source_records}, "
259
+ f"columns={len(m.columns)}, policy={m.disclosure_policy.profile!r}, "
260
+ f"targets={m.targets.n_calibration}+{m.targets.n_sealed} sealed)")
261
+
262
+
263
+ __all__ = ["ArrayStore", "CalibrationView", "Fingerprint", "Target", "TargetSet"]