stringforge 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.
@@ -0,0 +1,322 @@
1
+ # Copyright 2026 Andreas Schachner
2
+ #
3
+ # This file is part of StringForge.
4
+ #
5
+ # StringForge is free software: you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation, either version 3 of the License, or
8
+ # (at your option) any later version.
9
+
10
+ r"""
11
+ Verifier identity for the certified-vacuum record contract.
12
+
13
+ Every certified vacuum carries a ``verifier_id`` (see
14
+ :data:`stringforge.vulcan.schema.CERT_COLUMNS`). It is the content
15
+ hash of the *exact* certification procedure that accepted the row: the
16
+ ``jaxvacua`` version, the ordered set of physicality checks, the
17
+ numerical tolerances, and whether the extended stability suite was
18
+ applied.
19
+
20
+ The motivation is the 2026-06-02 incident (``worklog/ERRORS.md``): the
21
+ Kähler-metric positive-definiteness check was once omitted from the
22
+ acceptance cascade, and ~465 saddle points were miscounted as vacua.
23
+ At single-researcher scale that was recoverable. Auto-published to a
24
+ community-facing rolling database it would not be -- *unless* every
25
+ record records which verifier certified it, so a later bug-fix can
26
+ issue exactly the query "which published vacua did the buggy verifier
27
+ accept?" and transition them to ``invalidated`` rather than leaving
28
+ silent corruption in the corpus.
29
+
30
+ This module deliberately does **not** import any physics solver. A
31
+ :class:`VerifierSpec` is a pure-data description; the certifier that
32
+ *runs* the checks (Phase 1 of the rolling-DB plan) constructs a spec
33
+ from the live ``jaxvacua`` build and hands it here for hashing. Keeping
34
+ this module solver-free lets the curation / CI tier compute and compare
35
+ ``verifier_id`` values without a JAX install.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import hashlib
40
+ import json
41
+ from dataclasses import dataclass, field
42
+ from typing import Any, Dict, Mapping, Optional, Tuple
43
+
44
+ #: The ordered physicality-cascade check names. The order is part of
45
+ #: the verifier identity: a verifier that runs the same checks in a
46
+ #: different order is, for provenance purposes, a different verifier.
47
+ #: These names mirror the cascade in
48
+ #: ``jaxvacua.flux_utils.is_physical`` plus Vulcan's local endpoint
49
+ #: stability diagnostics.
50
+ CANONICAL_CHECK_NAMES: Tuple[str, ...] = (
51
+ "runaway_bound", # max(|moduli|, |tau|) <= moduli_max
52
+ "dilaton_floor", # Im(tau) > s_lower
53
+ "kahler_cone", # cone hyperplane test
54
+ "kahler_metric_pd", # eig(K) > 0 -- the 2026-06-02 check
55
+ "im_z_positive", # fallback Im(z_i) > 0
56
+ "hessian_min_eig", # stability: real-Hessian min eigenvalue
57
+ "mass_min_eig", # stability: mass-matrix min eigenvalue
58
+ )
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class VerifierSpec:
63
+ r"""
64
+ **Description:**
65
+ Pure-data description of a certification procedure.
66
+
67
+ The frozen fields are exactly those whose change should produce a
68
+ new :func:`verifier_id`. Two certifications agree on
69
+ ``verifier_id`` if and only if they would accept/reject every
70
+ candidate identically (modulo non-determinism the spec does not
71
+ capture, which is why ``jaxvacua_git_sha`` is included -- it pins
72
+ the implementation, not just its declared parameters).
73
+
74
+ Attributes:
75
+ jaxvacua_git_sha: Short or full git SHA of the ``jaxvacua``
76
+ build whose ``is_physical`` performed the certification.
77
+ checks: The ordered tuple of check names that were *run* and
78
+ *required to pass*. Must be a subset of
79
+ :data:`CANONICAL_CHECK_NAMES`, in canonical order. The
80
+ 2026-06-02 bug is exactly the case where
81
+ ``"kahler_metric_pd"`` was absent from this tuple.
82
+ tolerances: Mapping of tolerance name -> value used by the
83
+ checks (e.g. ``{"residual": 1e-6, "metric_tol": 1e-10,
84
+ "hessian_tol": -1e-8, "mass_tol": -1e-8, "min_im_tau":
85
+ 1.0}``). Values are normalised to ``repr`` strings before
86
+ hashing so float formatting cannot perturb the id.
87
+ stability_suite: Whether the extended Hessian / mass-matrix
88
+ stability suite was applied (vs. ``is_physical`` alone).
89
+ notes: Free-form human note; **not** part of the hash.
90
+ """
91
+ jaxvacua_git_sha: str
92
+ checks: Tuple[str, ...]
93
+ tolerances: Mapping[str, Any] = field(default_factory=dict)
94
+ stability_suite: bool = True
95
+ notes: str = ""
96
+
97
+ def __post_init__(self) -> None:
98
+ unknown = [c for c in self.checks if c not in CANONICAL_CHECK_NAMES]
99
+ if unknown:
100
+ raise ValueError(
101
+ f"VerifierSpec.checks contains unknown check names {unknown}; "
102
+ f"expected a subset of {CANONICAL_CHECK_NAMES}"
103
+ )
104
+ # Enforce canonical ordering so two specs listing the same
105
+ # checks in different orders are rejected (rather than silently
106
+ # producing two ids for the same procedure).
107
+ canonical_order = [c for c in CANONICAL_CHECK_NAMES if c in self.checks]
108
+ if list(self.checks) != canonical_order:
109
+ raise ValueError(
110
+ f"VerifierSpec.checks must be in canonical order "
111
+ f"{canonical_order}; got {list(self.checks)}"
112
+ )
113
+
114
+ def hashable_payload(self) -> Dict[str, Any]:
115
+ r"""
116
+ **Description:**
117
+ Return the canonical, JSON-serialisable dict that is hashed to
118
+ produce :func:`verifier_id`. Excludes ``notes`` (human-only).
119
+
120
+ Returns:
121
+ Dict[str, Any]: The payload, with tolerances normalised to
122
+ ``repr`` strings for float-format stability.
123
+ """
124
+ return {
125
+ "jaxvacua_git_sha": str(self.jaxvacua_git_sha),
126
+ "checks": list(self.checks),
127
+ "tolerances": {k: repr(self.tolerances[k]) for k in sorted(self.tolerances)},
128
+ "stability_suite": bool(self.stability_suite),
129
+ }
130
+
131
+ @property
132
+ def verifier_id(self) -> str:
133
+ r"""
134
+ **Description:**
135
+ The content-addressed verifier identifier:
136
+ ``"v1-" + sha1(canonical-json(hashable_payload))[:16]``.
137
+
138
+ The ``v1-`` prefix is a *format* version for the hashing scheme
139
+ itself (so the scheme can evolve without colliding), distinct
140
+ from ``stringforge.vulcan.schema.SCHEMA_VERSION`` (the parquet
141
+ layout version).
142
+
143
+ Returns:
144
+ str: The verifier id.
145
+ """
146
+ canonical = json.dumps(
147
+ self.hashable_payload(), sort_keys=True, separators=(",", ":"),
148
+ )
149
+ digest = hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]
150
+ return f"v1-{digest}"
151
+
152
+ def includes_metric_pd_check(self) -> bool:
153
+ r"""
154
+ **Description:**
155
+ Whether this verifier ran the Kähler-metric positive-definiteness
156
+ check -- the one whose omission caused the 2026-06-02 incident.
157
+
158
+ A community-facing certifier MUST return ``True`` here; the
159
+ Phase-3 gate should refuse any verifier for which this is
160
+ ``False``.
161
+
162
+ Returns:
163
+ bool: ``True`` iff ``"kahler_metric_pd"`` is in ``checks``.
164
+ """
165
+ return "kahler_metric_pd" in self.checks
166
+
167
+
168
+ def verifier_id(spec: VerifierSpec) -> str:
169
+ r"""
170
+ **Description:**
171
+ Functional alias for :attr:`VerifierSpec.verifier_id`.
172
+
173
+ Args:
174
+ spec: The verifier description.
175
+
176
+ Returns:
177
+ str: The content-addressed verifier id.
178
+ """
179
+ return spec.verifier_id
180
+
181
+
182
+ class VerifierRegistry:
183
+ r"""
184
+ **Description:**
185
+ In-memory registry mapping ``verifier_id -> VerifierSpec``.
186
+
187
+ The registry is the committed artefact that makes the bus-factor
188
+ risk (a single maintainer) survivable: it lets any later operator
189
+ answer "what did ``verifier_id`` X actually check?" from a file,
190
+ not from memory. It round-trips losslessly through JSON so it can
191
+ be committed alongside the dataset.
192
+
193
+ Args:
194
+ specs: Optional iterable of :class:`VerifierSpec` to register
195
+ at construction.
196
+ """
197
+
198
+ def __init__(self, specs: Optional[Any] = None) -> None:
199
+ self._by_id: Dict[str, VerifierSpec] = {}
200
+ if specs:
201
+ for spec in specs:
202
+ self.register(spec)
203
+
204
+ def register(self, spec: VerifierSpec) -> str:
205
+ r"""
206
+ **Description:**
207
+ Register a spec and return its ``verifier_id``. Idempotent:
208
+ re-registering an identical spec is a no-op; registering a
209
+ *different* spec under a colliding id raises (should never
210
+ happen short of a hash collision).
211
+
212
+ Args:
213
+ spec: The verifier description.
214
+
215
+ Returns:
216
+ str: The registered ``verifier_id``.
217
+
218
+ Raises:
219
+ ValueError: On an id collision with a differing spec.
220
+ """
221
+ vid = spec.verifier_id
222
+ existing = self._by_id.get(vid)
223
+ if existing is not None and existing.hashable_payload() != spec.hashable_payload():
224
+ raise ValueError(
225
+ f"verifier_id collision for {vid!r}: two distinct specs hash "
226
+ f"to the same id"
227
+ )
228
+ self._by_id[vid] = spec
229
+ return vid
230
+
231
+ def get(self, vid: str) -> Optional[VerifierSpec]:
232
+ r"""
233
+ **Description:**
234
+ Look up a registered spec by id.
235
+
236
+ Args:
237
+ vid: The ``verifier_id`` to resolve.
238
+
239
+ Returns:
240
+ Optional[VerifierSpec]: The spec, or ``None`` if unknown.
241
+ """
242
+ return self._by_id.get(vid)
243
+
244
+ def __contains__(self, vid: str) -> bool:
245
+ return vid in self._by_id
246
+
247
+ def __len__(self) -> int:
248
+ return len(self._by_id)
249
+
250
+ def to_dict(self) -> Dict[str, Any]:
251
+ r"""
252
+ **Description:**
253
+ Serialise the registry to a JSON-able dict
254
+ (``{verifier_id: {jaxvacua_git_sha, checks, tolerances,
255
+ stability_suite, notes}}``).
256
+
257
+ Returns:
258
+ Dict[str, Any]: The serialised registry.
259
+ """
260
+ return {
261
+ vid: {
262
+ "jaxvacua_git_sha": spec.jaxvacua_git_sha,
263
+ "checks": list(spec.checks),
264
+ "tolerances": dict(spec.tolerances),
265
+ "stability_suite": spec.stability_suite,
266
+ "notes": spec.notes,
267
+ }
268
+ for vid, spec in sorted(self._by_id.items())
269
+ }
270
+
271
+ @classmethod
272
+ def from_dict(cls, data: Mapping[str, Any]) -> "VerifierRegistry":
273
+ r"""
274
+ **Description:**
275
+ Reconstruct a registry from :meth:`to_dict` output. Verifies
276
+ that each entry's key matches the recomputed ``verifier_id``
277
+ (so a hand-edited registry cannot silently mislabel a spec).
278
+
279
+ Args:
280
+ data: A mapping as produced by :meth:`to_dict`.
281
+
282
+ Returns:
283
+ VerifierRegistry: The reconstructed registry.
284
+
285
+ Raises:
286
+ ValueError: If a stored key does not match the recomputed
287
+ ``verifier_id`` of its spec.
288
+ """
289
+ reg = cls()
290
+ for vid, entry in data.items():
291
+ spec = VerifierSpec(
292
+ jaxvacua_git_sha=entry["jaxvacua_git_sha"],
293
+ checks=tuple(entry["checks"]),
294
+ tolerances=dict(entry.get("tolerances", {})),
295
+ stability_suite=bool(entry.get("stability_suite", True)),
296
+ notes=entry.get("notes", ""),
297
+ )
298
+ if spec.verifier_id != vid:
299
+ raise ValueError(
300
+ f"registry key {vid!r} does not match recomputed "
301
+ f"verifier_id {spec.verifier_id!r}; the registry has been "
302
+ f"corrupted or hand-edited inconsistently"
303
+ )
304
+ reg.register(spec)
305
+ return reg
306
+
307
+
308
+ #: The full physicality cascade including the stability suite -- the
309
+ #: verifier a community-facing certifier (Phase 3) MUST use. The
310
+ #: jaxvacua git SHA is a placeholder to be filled at certification time
311
+ #: from the live build; it is intentionally not pinned here so this
312
+ #: module stays solver-free.
313
+ FULL_CASCADE_CHECKS: Tuple[str, ...] = CANONICAL_CHECK_NAMES
314
+
315
+
316
+ __all__ = (
317
+ "CANONICAL_CHECK_NAMES",
318
+ "FULL_CASCADE_CHECKS",
319
+ "VerifierSpec",
320
+ "VerifierRegistry",
321
+ "verifier_id",
322
+ )