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.
- stringforge/__init__.py +307 -0
- stringforge/cy_io.py +1787 -0
- stringforge/kklt_database.py +2889 -0
- stringforge/lcs_database.py +1223 -0
- stringforge/vacua_writer.py +3079 -0
- stringforge/vacuavault/__init__.py +60 -0
- stringforge/vacuavault/__main__.py +104 -0
- stringforge/vacuavault/catalog.py +222 -0
- stringforge/vacuavault/ci.py +188 -0
- stringforge/vacuavault/curate.py +119 -0
- stringforge/vacuavault/schema.py +459 -0
- stringforge/vulcan/__init__.py +634 -0
- stringforge/vulcan/__main__.py +139 -0
- stringforge/vulcan/certify.py +543 -0
- stringforge/vulcan/community.py +261 -0
- stringforge/vulcan/hf_io.py +296 -0
- stringforge/vulcan/ml_view.py +386 -0
- stringforge/vulcan/ratelimit.py +285 -0
- stringforge/vulcan/reader.py +624 -0
- stringforge/vulcan/runid.py +248 -0
- stringforge/vulcan/schema.py +525 -0
- stringforge/vulcan/snapshot.py +436 -0
- stringforge/vulcan/sync.py +263 -0
- stringforge/vulcan/verifier.py +322 -0
- stringforge/vulcan/writer.py +434 -0
- stringforge-0.1.0.dist-info/METADATA +286 -0
- stringforge-0.1.0.dist-info/RECORD +30 -0
- stringforge-0.1.0.dist-info/WHEEL +5 -0
- stringforge-0.1.0.dist-info/licenses/LICENSE +674 -0
- stringforge-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,525 @@
|
|
|
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
|
+
Production parquet schema for the Vulcan tier.
|
|
12
|
+
|
|
13
|
+
Vulcan writes uniform, streaming-friendly parquet shards to a
|
|
14
|
+
production HuggingFace repo. The schema is intentionally a strict
|
|
15
|
+
superset of :data:`stringforge.vacuavault.schema.REQUIRED_COLUMNS` so a
|
|
16
|
+
Vulcan shard is loadable by the existing vault tooling after column
|
|
17
|
+
projection -- this is the compatibility hook that enables a future
|
|
18
|
+
Vulcan -> VacuaWriter promotion step.
|
|
19
|
+
|
|
20
|
+
The schema is frozen at ``SCHEMA_VERSION``. Forward-compatible
|
|
21
|
+
additions (new optional columns) are allowed; column removals or type
|
|
22
|
+
changes require a version bump.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import warnings
|
|
30
|
+
from typing import Any, Iterable, Mapping, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
import pandas as pd
|
|
33
|
+
import pyarrow as pa
|
|
34
|
+
|
|
35
|
+
# Re-use the vault-side floor. This is the contract Vulcan must respect
|
|
36
|
+
# for vault-tooling compatibility.
|
|
37
|
+
from stringforge.vacuavault.schema import (
|
|
38
|
+
LABEL_SLUG_RE,
|
|
39
|
+
REQUIRED_COLUMNS as VAULT_REQUIRED_COLUMNS,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
#: Vulcan production schema version. Bump on any non-additive change.
|
|
43
|
+
SCHEMA_VERSION: int = 1
|
|
44
|
+
|
|
45
|
+
#: Required columns on every Vulcan shard. Strict superset of the
|
|
46
|
+
#: vault floor; the extras are the production telemetry every cluster
|
|
47
|
+
#: write must carry.
|
|
48
|
+
REQUIRED_COLUMNS: Tuple[str, ...] = (
|
|
49
|
+
# vault-compatibility floor
|
|
50
|
+
"flux", "moduli_re", "moduli_im", "tau_re", "tau_im",
|
|
51
|
+
# production-tier required
|
|
52
|
+
"run_id", "geometry_id", "tadpole_charge", "created_at",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
#: Certification columns (the "certified-vacuum record" contract).
|
|
56
|
+
#:
|
|
57
|
+
#: These pin *which verifier* certified a row and *what it found*, so a
|
|
58
|
+
#: later verifier-bug fix can select exactly the affected records and
|
|
59
|
+
#: transition their status rather than silently leaving corrupt vacua
|
|
60
|
+
#: published. Motivated by the 2026-06-02 incident (``worklog/ERRORS.md``):
|
|
61
|
+
#: the Kähler-metric positive-definiteness check was once omitted and
|
|
62
|
+
#: ~465 saddle points were miscounted as vacua. Without ``verifier_id``
|
|
63
|
+
#: that class of bug is unrecoverable at community scale.
|
|
64
|
+
#:
|
|
65
|
+
#: * ``verifier_id`` -- content hash naming the verifier
|
|
66
|
+
#: (see :mod:`stringforge.vulcan.verifier`); the join key for
|
|
67
|
+
#: "which rows did this verifier certify?".
|
|
68
|
+
#: * ``cert_status`` -- one of :data:`CERT_STATUSES`. A verifier-bug
|
|
69
|
+
#: fix *transitions* a record (never deletes it), mirroring the
|
|
70
|
+
#: ``vacua_vault`` ``retractions.parquet`` pattern.
|
|
71
|
+
#: * ``cert_checks`` -- JSON dict of per-check pass/fail booleans for
|
|
72
|
+
#: the physicality cascade (runaway, dilaton, cone, **metric-PD**,
|
|
73
|
+
#: plus the stability min-eigs). Makes the 2026-06-02 signature
|
|
74
|
+
#: ("passed cone but failed metric-PD") queryable.
|
|
75
|
+
#: * ``kahler_metric_min_eig`` -- the number whose *absence* was the
|
|
76
|
+
#: bug; storing it makes a recurrence detectable in aggregate.
|
|
77
|
+
#: * ``hessian_min_eig`` / ``mass_min_eig`` -- distinguish a genuine
|
|
78
|
+
#: minimum from a saddle.
|
|
79
|
+
#: * ``record_id`` -- unique *row* key
|
|
80
|
+
#: ``sha(geometry_id ‖ rounded-flux ‖ verifier_id)`` for retraction
|
|
81
|
+
#: targeting. Physical dedup of a vacuum uses the
|
|
82
|
+
#: *verifier-independent* ``(geometry_id, rounded-flux)`` separately.
|
|
83
|
+
CERT_COLUMNS: Tuple[str, ...] = (
|
|
84
|
+
"verifier_id", "cert_status", "cert_checks",
|
|
85
|
+
"kahler_metric_min_eig", "hessian_min_eig", "mass_min_eig",
|
|
86
|
+
"record_id",
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
#: Recognised values of the ``cert_status`` column. ``certified`` =
|
|
90
|
+
#: passed the full cascade under its ``verifier_id``; ``provisional`` =
|
|
91
|
+
#: community-submitted, awaiting independent server-side re-cert;
|
|
92
|
+
#: ``invalidated`` = a later verifier-bug fix demoted it.
|
|
93
|
+
CERT_STATUSES: Tuple[str, ...] = ("certified", "provisional", "invalidated")
|
|
94
|
+
|
|
95
|
+
#: Optional columns recognised by the schema. Shards may carry any
|
|
96
|
+
#: subset; downstream consumers must tolerate missing optionals.
|
|
97
|
+
OPTIONAL_COLUMNS: Tuple[str, ...] = (
|
|
98
|
+
"h11", "h12", "ks_id", "triang_id", "conifold_id", "cicy_id",
|
|
99
|
+
"W_re", "W_im", "F_terms_re", "F_terms_im",
|
|
100
|
+
# derived physics (output of VacuaWriter.complete_missing). ``g_s`` and
|
|
101
|
+
# ``m_gravitino`` and the ``mass2`` spectrum are in the FluxEFT no-scale
|
|
102
|
+
# normalisation (NOT M_Pl -- the overall CY volume is unfixed at this
|
|
103
|
+
# level); see :func:`stringforge.vacua_writer._compute_derived`.
|
|
104
|
+
"g_s", "mass2", "m_gravitino",
|
|
105
|
+
"residual", "n_iterations", "is_susy", "is_isd",
|
|
106
|
+
"solver_name", "solver_config_hash",
|
|
107
|
+
"git_sha", "seed", "wall_clock_s",
|
|
108
|
+
"tags", "extra_data",
|
|
109
|
+
# certified-vacuum record contract (see CERT_COLUMNS)
|
|
110
|
+
*CERT_COLUMNS,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
#: Sentinel for geometry-key fields when not applicable to the model
|
|
114
|
+
#: (e.g. a CICY shard has ``ks_id = triang_id = -1``). Matches the
|
|
115
|
+
#: convention used by :func:`stringforge.vacua_writer._extract_model_identity`.
|
|
116
|
+
GEOMETRY_KEY_SENTINEL: int = -1
|
|
117
|
+
|
|
118
|
+
#: Geometry keys, in canonical order, used to derive ``geometry_id``.
|
|
119
|
+
#: Stable ordering is critical: the hash must be reproducible across
|
|
120
|
+
#: cluster nodes and across stringforge versions.
|
|
121
|
+
#: ``h11``, ``h12`` are interpreted in mirror (jaxvacua / lcs_tree)
|
|
122
|
+
#: convention, matching ``LCSDatabase``.
|
|
123
|
+
GEOMETRY_KEYS: Tuple[str, ...] = (
|
|
124
|
+
"h11", "h12", "ks_id", "triang_id", "conifold_id", "cicy_id",
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def pyarrow_schema(extra_columns: Optional[Mapping[str, pa.DataType]] = None) -> pa.Schema:
|
|
129
|
+
r"""
|
|
130
|
+
**Description:**
|
|
131
|
+
Return the canonical pyarrow schema for a Vulcan shard.
|
|
132
|
+
|
|
133
|
+
Required columns appear in :data:`REQUIRED_COLUMNS` order; the
|
|
134
|
+
recognised optionals follow. ``extra_columns`` lets a caller
|
|
135
|
+
extend the schema with project-specific fields without modifying
|
|
136
|
+
the canonical layout.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
extra_columns: Optional mapping ``{name: pyarrow_type}`` of
|
|
140
|
+
project-specific extension columns. Names must not
|
|
141
|
+
collide with canonical fields.
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
pa.Schema: The full schema, ready to pass to
|
|
145
|
+
:func:`pyarrow.parquet.write_table`.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
ValueError: If an entry in ``extra_columns`` shadows a
|
|
149
|
+
canonical field name.
|
|
150
|
+
"""
|
|
151
|
+
fields: list[pa.Field] = [
|
|
152
|
+
# vault floor
|
|
153
|
+
pa.field("flux", pa.list_(pa.int32())),
|
|
154
|
+
pa.field("moduli_re", pa.list_(pa.float64())),
|
|
155
|
+
pa.field("moduli_im", pa.list_(pa.float64())),
|
|
156
|
+
pa.field("tau_re", pa.float64()),
|
|
157
|
+
pa.field("tau_im", pa.float64()),
|
|
158
|
+
# production-tier required
|
|
159
|
+
pa.field("run_id", pa.string()),
|
|
160
|
+
pa.field("geometry_id", pa.string()),
|
|
161
|
+
pa.field("tadpole_charge", pa.int32()),
|
|
162
|
+
pa.field("created_at", pa.timestamp("us", tz="UTC")),
|
|
163
|
+
# optionals
|
|
164
|
+
pa.field("h11", pa.int32()),
|
|
165
|
+
pa.field("h12", pa.int32()),
|
|
166
|
+
pa.field("ks_id", pa.int32()),
|
|
167
|
+
pa.field("triang_id", pa.int32()),
|
|
168
|
+
pa.field("conifold_id", pa.int32()),
|
|
169
|
+
pa.field("cicy_id", pa.int32()),
|
|
170
|
+
pa.field("W_re", pa.float64()),
|
|
171
|
+
pa.field("W_im", pa.float64()),
|
|
172
|
+
pa.field("F_terms_re", pa.list_(pa.float64())),
|
|
173
|
+
pa.field("F_terms_im", pa.list_(pa.float64())),
|
|
174
|
+
pa.field("g_s", pa.float64()),
|
|
175
|
+
pa.field("mass2", pa.list_(pa.float64())),
|
|
176
|
+
pa.field("m_gravitino", pa.float64()),
|
|
177
|
+
pa.field("residual", pa.float64()),
|
|
178
|
+
pa.field("n_iterations", pa.int32()),
|
|
179
|
+
pa.field("is_susy", pa.bool_()),
|
|
180
|
+
pa.field("is_isd", pa.bool_()),
|
|
181
|
+
pa.field("solver_name", pa.string()),
|
|
182
|
+
pa.field("solver_config_hash", pa.string()),
|
|
183
|
+
pa.field("git_sha", pa.string()),
|
|
184
|
+
pa.field("seed", pa.int64()),
|
|
185
|
+
pa.field("wall_clock_s", pa.float32()),
|
|
186
|
+
pa.field("tags", pa.string()),
|
|
187
|
+
pa.field("extra_data", pa.string()),
|
|
188
|
+
# certified-vacuum record contract
|
|
189
|
+
pa.field("verifier_id", pa.string()),
|
|
190
|
+
pa.field("cert_status", pa.string()),
|
|
191
|
+
pa.field("cert_checks", pa.string()), # JSON-encoded dict
|
|
192
|
+
pa.field("kahler_metric_min_eig", pa.float64()),
|
|
193
|
+
pa.field("hessian_min_eig", pa.float64()),
|
|
194
|
+
pa.field("mass_min_eig", pa.float64()),
|
|
195
|
+
pa.field("record_id", pa.string()),
|
|
196
|
+
]
|
|
197
|
+
if extra_columns:
|
|
198
|
+
existing = {f.name for f in fields}
|
|
199
|
+
for name, dtype in extra_columns.items():
|
|
200
|
+
if name in existing:
|
|
201
|
+
raise ValueError(
|
|
202
|
+
f"Vulcan schema: extra_columns cannot override canonical "
|
|
203
|
+
f"field {name!r}"
|
|
204
|
+
)
|
|
205
|
+
fields.append(pa.field(name, dtype))
|
|
206
|
+
return pa.schema(fields)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def geometry_id(geometry: Mapping[str, Any]) -> str:
|
|
210
|
+
r"""
|
|
211
|
+
**Description:**
|
|
212
|
+
Compute a stable, content-addressed identifier for a Calabi-Yau
|
|
213
|
+
model.
|
|
214
|
+
|
|
215
|
+
The identifier is the first 16 hex characters of
|
|
216
|
+
``sha1(canonical-json(geometry-keys))``. Sufficient as a join key
|
|
217
|
+
against a Vulcan catalogue; not intended as a cryptographic
|
|
218
|
+
digest. Stable across processes, machines, and Python runs.
|
|
219
|
+
Missing keys are filled with :data:`GEOMETRY_KEY_SENTINEL` so a
|
|
220
|
+
sparse mapping yields the same id as one that lists every key with
|
|
221
|
+
explicit sentinels.
|
|
222
|
+
|
|
223
|
+
.. note::
|
|
224
|
+
``geometry`` MUST be a server-canonicalised index dict (mirror
|
|
225
|
+
convention; produced by the canonical identity path), never
|
|
226
|
+
derived per-row from untrusted submitter input -- otherwise the
|
|
227
|
+
same physical geometry can hash two ways and dedup silently
|
|
228
|
+
fails. An *absent* key maps to the sentinel ``-1`` ("not
|
|
229
|
+
applicable"); an explicit ``0`` (e.g. ``conifold_id=0``, the
|
|
230
|
+
conifold-limit model) is a genuinely distinct value, NOT
|
|
231
|
+
normalised to the sentinel.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
geometry: Mapping carrying any subset of :data:`GEOMETRY_KEYS`.
|
|
235
|
+
|
|
236
|
+
Returns:
|
|
237
|
+
str: 16-hex-character identifier.
|
|
238
|
+
"""
|
|
239
|
+
payload = {k: int(geometry.get(k, GEOMETRY_KEY_SENTINEL)) for k in GEOMETRY_KEYS}
|
|
240
|
+
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
|
|
241
|
+
return hashlib.sha1(canonical.encode("utf-8")).hexdigest()[:16]
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def canonical_flux(flux: Iterable[Any]) -> Tuple[int, ...]:
|
|
245
|
+
r"""
|
|
246
|
+
**Description:**
|
|
247
|
+
Coerce a flux vector to a canonical tuple of Python ints.
|
|
248
|
+
|
|
249
|
+
Used as the *verifier-independent* component of both the physical
|
|
250
|
+
dedup key ``(geometry_id, canonical_flux)`` and the per-row
|
|
251
|
+
:func:`record_id`. Rounding to int is intentional: the integer
|
|
252
|
+
flux quanta are the physical identity of a vacuum, independent of
|
|
253
|
+
any floating-point representation a producer happened to use.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
flux: An iterable of integer-valued flux components.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
Tuple[int, ...]: The flux as a tuple of rounded Python ints.
|
|
260
|
+
"""
|
|
261
|
+
return tuple(int(round(float(x))) for x in flux)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def record_id(geometry: Mapping[str, Any], flux: Iterable[Any], verifier_id: str) -> str:
|
|
265
|
+
r"""
|
|
266
|
+
**Description:**
|
|
267
|
+
Compute the unique *row* key of a certified-vacuum record.
|
|
268
|
+
|
|
269
|
+
The key is ``sha1`` of ``geometry_id ‖ canonical-flux ‖ verifier_id``,
|
|
270
|
+
truncated to 24 hex characters. It is the retraction-targeting
|
|
271
|
+
handle: re-certifying the *same* physical vacuum under a *new*
|
|
272
|
+
``verifier_id`` produces a *different* ``record_id`` (a new row,
|
|
273
|
+
preserving history) -- so this key must NOT be used for physical
|
|
274
|
+
dedup. Physical dedup uses the verifier-independent
|
|
275
|
+
``(geometry_id, canonical_flux(flux))`` pair instead.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
geometry: Geometry mapping (see :func:`geometry_id`).
|
|
279
|
+
flux: The integer flux vector of the vacuum.
|
|
280
|
+
verifier_id: The certifying verifier's content hash
|
|
281
|
+
(see :mod:`stringforge.vulcan.verifier`).
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
str: 24-hex-character unique row identifier.
|
|
285
|
+
"""
|
|
286
|
+
gid = geometry_id(geometry)
|
|
287
|
+
fcanon = canonical_flux(flux)
|
|
288
|
+
payload = json.dumps(
|
|
289
|
+
{"geometry_id": gid, "flux": list(fcanon), "verifier_id": str(verifier_id)},
|
|
290
|
+
sort_keys=True, separators=(",", ":"),
|
|
291
|
+
)
|
|
292
|
+
return hashlib.sha1(payload.encode("utf-8")).hexdigest()[:24]
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def metric_pd_passed(cert_checks_json: Any, min_eig: Any) -> bool:
|
|
296
|
+
r"""
|
|
297
|
+
**Description:**
|
|
298
|
+
Positive assertion that a row's *own evidence* confirms a
|
|
299
|
+
positive-definite Kähler metric: ``cert_checks['kahler_metric_pd']
|
|
300
|
+
is True`` **and** a finite ``kahler_metric_min_eig > 0``.
|
|
301
|
+
|
|
302
|
+
This is the **positive** form, and the distinction is load-bearing:
|
|
303
|
+
the 2026-06-02 incident was an *omitted* check (no
|
|
304
|
+
``kahler_metric_pd`` key, ``min_eig`` left ``NaN``), not a check that
|
|
305
|
+
explicitly failed. A negative test ("is it explicitly False or
|
|
306
|
+
``<= 0``?") would let an omitted check pass; this predicate treats a
|
|
307
|
+
missing key, an unparseable ``cert_checks``, or a non-finite /
|
|
308
|
+
non-positive eigenvalue as **not passed**. Both the community
|
|
309
|
+
ingest gate and the snapshot citation gate use it, so the two agree
|
|
310
|
+
by construction.
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
cert_checks_json: The row's ``cert_checks`` value (a JSON string;
|
|
314
|
+
may be ``None``).
|
|
315
|
+
min_eig: The row's ``kahler_metric_min_eig`` value.
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
bool: ``True`` iff the row positively asserts a PD Kähler metric.
|
|
319
|
+
"""
|
|
320
|
+
try:
|
|
321
|
+
checks = json.loads(cert_checks_json)
|
|
322
|
+
ok = isinstance(checks, dict) and checks.get("kahler_metric_pd") is True
|
|
323
|
+
except (TypeError, ValueError):
|
|
324
|
+
return False
|
|
325
|
+
if not ok:
|
|
326
|
+
return False
|
|
327
|
+
try:
|
|
328
|
+
eig = float(min_eig)
|
|
329
|
+
except (TypeError, ValueError):
|
|
330
|
+
return False
|
|
331
|
+
return math.isfinite(eig) and eig > 0.0
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def validate_cert_status(status: str) -> None:
|
|
335
|
+
r"""
|
|
336
|
+
**Description:**
|
|
337
|
+
Validate a ``cert_status`` value against :data:`CERT_STATUSES`.
|
|
338
|
+
|
|
339
|
+
Args:
|
|
340
|
+
status: The candidate status string.
|
|
341
|
+
|
|
342
|
+
Raises:
|
|
343
|
+
ValueError: If ``status`` is not a recognised certification
|
|
344
|
+
status.
|
|
345
|
+
"""
|
|
346
|
+
if status not in CERT_STATUSES:
|
|
347
|
+
raise ValueError(
|
|
348
|
+
f"invalid cert_status {status!r}; expected one of {CERT_STATUSES}"
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def validate_schema(df: pd.DataFrame, *, warn_unknown: bool = True) -> None:
|
|
353
|
+
r"""
|
|
354
|
+
**Description:**
|
|
355
|
+
Validate that ``df`` satisfies the Vulcan schema.
|
|
356
|
+
|
|
357
|
+
Aggregates every problem into a single :class:`ValueError` --
|
|
358
|
+
callers see all schema violations, not just the first one. Only
|
|
359
|
+
cheap structural checks are performed (column presence, run-id
|
|
360
|
+
slug shape, homogeneity of ``geometry_id``); no row-level
|
|
361
|
+
numerical validation.
|
|
362
|
+
|
|
363
|
+
Args:
|
|
364
|
+
df: Coerced DataFrame ready to be written as a shard.
|
|
365
|
+
|
|
366
|
+
Raises:
|
|
367
|
+
ValueError: If any structural invariant is violated. The
|
|
368
|
+
message names every detected problem.
|
|
369
|
+
"""
|
|
370
|
+
problems: list[str] = []
|
|
371
|
+
|
|
372
|
+
missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]
|
|
373
|
+
if missing:
|
|
374
|
+
problems.append(f"missing required columns: {missing}")
|
|
375
|
+
|
|
376
|
+
# Identity invariant: one shard = one geometry.
|
|
377
|
+
if "geometry_id" in df.columns and len(df) > 0:
|
|
378
|
+
unique_ids = df["geometry_id"].unique()
|
|
379
|
+
if len(unique_ids) > 1:
|
|
380
|
+
problems.append(
|
|
381
|
+
f"mixed geometry_ids in a single shard ({len(unique_ids)} "
|
|
382
|
+
f"distinct); Vulcan shards must be homogeneous per geometry"
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
# Run-id slug check.
|
|
386
|
+
if "run_id" in df.columns and len(df) > 0:
|
|
387
|
+
bad = [
|
|
388
|
+
rid for rid in df["run_id"].unique()
|
|
389
|
+
if not isinstance(rid, str) or not LABEL_SLUG_RE.match(rid)
|
|
390
|
+
]
|
|
391
|
+
if bad:
|
|
392
|
+
problems.append(
|
|
393
|
+
f"run_id values violate LABEL_SLUG_RE (first 3 shown): "
|
|
394
|
+
f"{bad[:3]}"
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
# Vault-floor list columns are non-null.
|
|
398
|
+
for col in ("flux", "moduli_re", "moduli_im"):
|
|
399
|
+
if col in df.columns and df[col].isna().any():
|
|
400
|
+
problems.append(f"required list column {col!r} contains nulls")
|
|
401
|
+
|
|
402
|
+
# cert_status, when present, must be a recognised value. Skip NaN:
|
|
403
|
+
# certify.py intentionally stamps rejected rows with status=None.
|
|
404
|
+
if "cert_status" in df.columns and len(df) > 0:
|
|
405
|
+
bad_status = [
|
|
406
|
+
s for s in df["cert_status"].dropna().unique() if s not in CERT_STATUSES
|
|
407
|
+
]
|
|
408
|
+
if bad_status:
|
|
409
|
+
problems.append(
|
|
410
|
+
f"cert_status values not in CERT_STATUSES (first 3 shown): "
|
|
411
|
+
f"{bad_status[:3]}"
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
unknown = [
|
|
415
|
+
c for c in df.columns
|
|
416
|
+
if c not in REQUIRED_COLUMNS and c not in OPTIONAL_COLUMNS
|
|
417
|
+
]
|
|
418
|
+
# Unknown columns are tolerated (passed through to parquet so a future
|
|
419
|
+
# schema version can absorb them) -- we do NOT raise on them. A lone
|
|
420
|
+
# unknown column is often a typo (e.g. ``cert_statuss``), so we surface
|
|
421
|
+
# it as a warning when validating possibly-untrusted / hand-built
|
|
422
|
+
# frames. The writer passes ``warn_unknown=False`` because arbitrary
|
|
423
|
+
# extension columns are a *designed* feature there (the production ML
|
|
424
|
+
# columns), so warning on every write would just cry wolf.
|
|
425
|
+
if unknown and warn_unknown:
|
|
426
|
+
warnings.warn(
|
|
427
|
+
f"Vulcan schema: unknown columns (passed through): {sorted(unknown)}",
|
|
428
|
+
stacklevel=2,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
if problems:
|
|
432
|
+
raise ValueError("Vulcan schema validation failed: " + "; ".join(problems))
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def shard_key(geometry: Mapping[str, Any], bucket_bits: int = 4) -> Tuple[int, int, int]:
|
|
436
|
+
r"""
|
|
437
|
+
**Description:**
|
|
438
|
+
Return the ``(h12, h11, bucket)`` key used to organise shards on
|
|
439
|
+
disk.
|
|
440
|
+
|
|
441
|
+
``bucket`` is drawn from the top ``bucket_bits`` of
|
|
442
|
+
``sha1(geometry_id)``. Bucketing prevents a single ``(h11, h12)``
|
|
443
|
+
point from accumulating an unmanageably large directory once many
|
|
444
|
+
geometries are present.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
geometry: Geometry mapping (see :func:`geometry_id`).
|
|
448
|
+
bucket_bits: Width of the bucket prefix in bits.
|
|
449
|
+
|
|
450
|
+
Returns:
|
|
451
|
+
Tuple[int, int, int]: ``(h12, h11, bucket)``.
|
|
452
|
+
"""
|
|
453
|
+
h11 = int(geometry.get("h11", GEOMETRY_KEY_SENTINEL))
|
|
454
|
+
h12 = int(geometry.get("h12", GEOMETRY_KEY_SENTINEL))
|
|
455
|
+
digest = hashlib.sha1(geometry_id(geometry).encode("ascii")).digest()
|
|
456
|
+
mask = (1 << bucket_bits) - 1
|
|
457
|
+
bucket = digest[0] & mask
|
|
458
|
+
return (h12, h11, bucket)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def shard_relpath(geometry: Mapping[str, Any], run_id: str, bucket_bits: int = 4) -> str:
|
|
462
|
+
r"""
|
|
463
|
+
**Description:**
|
|
464
|
+
Canonical HF-repo-relative path for a Vulcan shard.
|
|
465
|
+
|
|
466
|
+
Layout: ``h12_{H}/h11_{H}/bucket_{B}/run_{run_id}.parquet``.
|
|
467
|
+
|
|
468
|
+
Args:
|
|
469
|
+
geometry: Geometry mapping (see :func:`geometry_id`).
|
|
470
|
+
run_id: Slug-safe identifier (see :func:`is_safe_run_id`).
|
|
471
|
+
bucket_bits: Width of the bucket prefix.
|
|
472
|
+
|
|
473
|
+
Returns:
|
|
474
|
+
str: Forward-slash-separated path inside the repo.
|
|
475
|
+
"""
|
|
476
|
+
h12, h11, bucket = shard_key(geometry, bucket_bits=bucket_bits)
|
|
477
|
+
return f"h12_{h12}/h11_{h11}/bucket_{bucket}/run_{run_id}.parquet"
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def is_safe_run_id(run_id: str) -> bool:
|
|
481
|
+
r"""
|
|
482
|
+
**Description:**
|
|
483
|
+
Predicate: ``run_id`` is safe to use as a parquet filename
|
|
484
|
+
component on POSIX, as an HF path segment, and as a vault label.
|
|
485
|
+
|
|
486
|
+
Reuses :data:`stringforge.vacuavault.schema.LABEL_SLUG_RE` so a
|
|
487
|
+
Vulcan run_id is admissible as a vault label after a future
|
|
488
|
+
promotion step. Run-ids containing ``'__'`` are rejected because
|
|
489
|
+
that sequence is reserved by the staging-area encoding
|
|
490
|
+
(``writer.py`` replaces ``'/'`` with ``'__'`` to produce local
|
|
491
|
+
filenames).
|
|
492
|
+
|
|
493
|
+
Args:
|
|
494
|
+
run_id: Candidate identifier.
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
bool: ``True`` if and only if ``run_id`` is a string matching
|
|
498
|
+
``LABEL_SLUG_RE`` and does not contain ``'__'``.
|
|
499
|
+
"""
|
|
500
|
+
if not isinstance(run_id, str):
|
|
501
|
+
return False
|
|
502
|
+
if not LABEL_SLUG_RE.match(run_id):
|
|
503
|
+
return False
|
|
504
|
+
if "__" in run_id: # reserved as the local "/" encoding separator
|
|
505
|
+
return False
|
|
506
|
+
return True
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def vault_floor_compatible(df: pd.DataFrame) -> bool:
|
|
510
|
+
r"""
|
|
511
|
+
**Description:**
|
|
512
|
+
Test whether ``df`` carries every column required by the curated
|
|
513
|
+
vault layer (:data:`stringforge.vacuavault.schema.REQUIRED_COLUMNS`).
|
|
514
|
+
|
|
515
|
+
Used as a precondition for a future Vulcan-to-VacuaWriter
|
|
516
|
+
promotion step.
|
|
517
|
+
|
|
518
|
+
Args:
|
|
519
|
+
df: A coerced or freshly-loaded Vulcan shard.
|
|
520
|
+
|
|
521
|
+
Returns:
|
|
522
|
+
bool: ``True`` if ``df`` is loadable by the vault tooling
|
|
523
|
+
after column projection.
|
|
524
|
+
"""
|
|
525
|
+
return all(c in df.columns for c in VAULT_REQUIRED_COLUMNS)
|