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,436 @@
|
|
|
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
|
+
Frozen, citeable snapshots of a rolling Vulcan database.
|
|
12
|
+
|
|
13
|
+
A *rolling* database and a *citeable* database are different objects: a
|
|
14
|
+
paper must cite an immutable state, while the production repo keeps
|
|
15
|
+
moving. This module resolves that tension the way the HuggingFace Hub
|
|
16
|
+
already allows -- a snapshot is
|
|
17
|
+
|
|
18
|
+
* an immutable **git tag** on the dataset repo (so
|
|
19
|
+
``VulcanReader.from_hf(repo, revision="v2026.06")`` reads a fixed
|
|
20
|
+
state), plus
|
|
21
|
+
* a generated **manifest** (record counts per ``(h11, h12)``, the
|
|
22
|
+
``verifier_id`` histogram, the ``cert_status`` histogram, a content
|
|
23
|
+
hash) committed at the tagged revision, plus
|
|
24
|
+
* optionally a **DOI** (HuggingFace mints dataset DOIs natively; a
|
|
25
|
+
Zenodo mirror is an optional backup).
|
|
26
|
+
|
|
27
|
+
The manifest is the governance artefact: before tagging a snapshot for
|
|
28
|
+
citation you can read off how many records are still ``unverified`` or
|
|
29
|
+
``provisional``, and which verifiers certified the corpus. A snapshot
|
|
30
|
+
whose manifest shows unverified records should not be cited.
|
|
31
|
+
|
|
32
|
+
This module is solver-free; manifest generation reads only the
|
|
33
|
+
catalogue plus the ``verifier_id`` / ``cert_status`` columns.
|
|
34
|
+
"""
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import hashlib
|
|
38
|
+
import json
|
|
39
|
+
from collections import Counter
|
|
40
|
+
from dataclasses import dataclass
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Any, Dict, Optional
|
|
43
|
+
|
|
44
|
+
import pandas as pd
|
|
45
|
+
|
|
46
|
+
from .reader import CATALOG_COLUMNS, VulcanReader
|
|
47
|
+
from .schema import SCHEMA_VERSION, metric_pd_passed
|
|
48
|
+
from .verifier import VerifierRegistry
|
|
49
|
+
|
|
50
|
+
#: Filename of the manifest committed at a snapshot's tagged revision.
|
|
51
|
+
MANIFEST_FILENAME: str = "snapshot_manifest.json"
|
|
52
|
+
|
|
53
|
+
#: Sentinel tallied for records that carry no ``verifier_id`` /
|
|
54
|
+
#: ``cert_status`` -- i.e. were written before the certified-record
|
|
55
|
+
#: contract, or by a producer that skipped it. Its presence in a
|
|
56
|
+
#: manifest is a governance red flag for a citeable snapshot.
|
|
57
|
+
UNVERIFIED_SENTINEL: str = "unverified"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class SnapshotManifest:
|
|
62
|
+
r"""
|
|
63
|
+
**Description:**
|
|
64
|
+
Summary of a frozen snapshot.
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
snapshot_tag: The immutable git tag (e.g. ``"v2026.06"``).
|
|
68
|
+
created_at: UTC timestamp string (passed in by the caller so
|
|
69
|
+
manifest generation stays deterministic / testable).
|
|
70
|
+
n_shards: Number of parquet shards in the snapshot.
|
|
71
|
+
n_records: Total vacuum rows across all shards.
|
|
72
|
+
records_by_hodge: ``{"h11=H,h12=H": count}`` per Hodge pair.
|
|
73
|
+
verifier_id_histogram: ``{verifier_id: n_records}`` (records
|
|
74
|
+
without a ``verifier_id`` tally under
|
|
75
|
+
:data:`UNVERIFIED_SENTINEL`).
|
|
76
|
+
cert_status_histogram: ``{cert_status: n_records}``.
|
|
77
|
+
schema_version: The Vulcan parquet ``SCHEMA_VERSION``.
|
|
78
|
+
content_sha256: Content hash over the sorted catalogue rows
|
|
79
|
+
(a stable fingerprint of *which* shards, with their row
|
|
80
|
+
counts and schema versions, the snapshot contains). It
|
|
81
|
+
deliberately covers catalogue identity ONLY -- not the cert
|
|
82
|
+
columns -- so an in-place ``certified -> invalidated``
|
|
83
|
+
transition does not change it; use the ``cert_status`` /
|
|
84
|
+
``verifier_id`` histograms to detect re-certification.
|
|
85
|
+
metric_pd_failures: Number of records stamped ``certified``
|
|
86
|
+
whose own evidence (``cert_checks`` / ``kahler_metric_min_eig``)
|
|
87
|
+
shows the Kähler metric was NOT positive-definite (the
|
|
88
|
+
2026-06-02 saddle signature). Any non-zero value fails
|
|
89
|
+
:meth:`fully_certified`.
|
|
90
|
+
tool_version: Optional stringforge version string.
|
|
91
|
+
"""
|
|
92
|
+
snapshot_tag: str
|
|
93
|
+
created_at: str
|
|
94
|
+
n_shards: int
|
|
95
|
+
n_records: int
|
|
96
|
+
records_by_hodge: Dict[str, int]
|
|
97
|
+
verifier_id_histogram: Dict[str, int]
|
|
98
|
+
cert_status_histogram: Dict[str, int]
|
|
99
|
+
schema_version: int
|
|
100
|
+
content_sha256: str
|
|
101
|
+
metric_pd_failures: int = 0
|
|
102
|
+
tool_version: Optional[str] = None
|
|
103
|
+
|
|
104
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
105
|
+
r"""**Description:** Return a JSON-serialisable dict of the manifest."""
|
|
106
|
+
return {
|
|
107
|
+
"snapshot_tag": self.snapshot_tag,
|
|
108
|
+
"created_at": self.created_at,
|
|
109
|
+
"n_shards": self.n_shards,
|
|
110
|
+
"n_records": self.n_records,
|
|
111
|
+
"records_by_hodge": dict(sorted(self.records_by_hodge.items())),
|
|
112
|
+
"verifier_id_histogram": dict(sorted(self.verifier_id_histogram.items())),
|
|
113
|
+
"cert_status_histogram": dict(sorted(self.cert_status_histogram.items())),
|
|
114
|
+
"schema_version": self.schema_version,
|
|
115
|
+
"content_sha256": self.content_sha256,
|
|
116
|
+
"metric_pd_failures": self.metric_pd_failures,
|
|
117
|
+
"tool_version": self.tool_version,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
def fully_certified(self, registry: Optional["VerifierRegistry"] = None) -> bool:
|
|
121
|
+
r"""
|
|
122
|
+
**Description:**
|
|
123
|
+
Whether the snapshot is safe to tag for citation: a non-empty
|
|
124
|
+
corpus in which every record is ``certified``, no record shows
|
|
125
|
+
the 2026-06-02 metric-PD-failure signature, and (when a
|
|
126
|
+
``registry`` is supplied) every ``verifier_id`` resolves to a
|
|
127
|
+
spec that ran the Kähler-metric PD check.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
registry: Optional :class:`~stringforge.vulcan.verifier.VerifierRegistry`.
|
|
131
|
+
When given, every non-sentinel ``verifier_id`` in the
|
|
132
|
+
histogram must resolve to a spec whose
|
|
133
|
+
``includes_metric_pd_check()`` is ``True``; an
|
|
134
|
+
unregistered or PD-lacking verifier fails the gate.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
bool: ``True`` iff the snapshot is citeable.
|
|
138
|
+
"""
|
|
139
|
+
# An empty corpus is NEVER citeable (vacuous histograms would
|
|
140
|
+
# otherwise pass) -- guards a mis-pointed / unsynced reader.
|
|
141
|
+
if self.n_records == 0:
|
|
142
|
+
return False
|
|
143
|
+
# Defensive: the histograms must account for every record, else
|
|
144
|
+
# a (hand-built / future) manifest could hide records from the
|
|
145
|
+
# gate. build_manifest always satisfies this, so it is a latent
|
|
146
|
+
# guard, not a live path.
|
|
147
|
+
if sum(self.verifier_id_histogram.values()) != self.n_records:
|
|
148
|
+
return False
|
|
149
|
+
if sum(self.cert_status_histogram.values()) != self.n_records:
|
|
150
|
+
return False
|
|
151
|
+
if UNVERIFIED_SENTINEL in self.verifier_id_histogram:
|
|
152
|
+
return False
|
|
153
|
+
if self.metric_pd_failures:
|
|
154
|
+
return False
|
|
155
|
+
non_certified = {
|
|
156
|
+
k: v for k, v in self.cert_status_histogram.items() if k != "certified"
|
|
157
|
+
}
|
|
158
|
+
if sum(non_certified.values()) != 0:
|
|
159
|
+
return False
|
|
160
|
+
if registry is not None:
|
|
161
|
+
for vid in self.verifier_id_histogram:
|
|
162
|
+
if vid == UNVERIFIED_SENTINEL:
|
|
163
|
+
return False
|
|
164
|
+
spec = registry.get(vid)
|
|
165
|
+
if spec is None or not spec.includes_metric_pd_check():
|
|
166
|
+
return False
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _content_sha256(catalog: pd.DataFrame) -> str:
|
|
171
|
+
r"""Stable content hash over the catalogue's identity-bearing columns.
|
|
172
|
+
|
|
173
|
+
Intentionally covers catalogue identity only (no cert columns), so a
|
|
174
|
+
re-certification that transitions ``cert_status`` in place does not
|
|
175
|
+
change the hash; detect that via the histograms instead.
|
|
176
|
+
"""
|
|
177
|
+
cols = [c for c in CATALOG_COLUMNS if c in catalog.columns]
|
|
178
|
+
rows = (
|
|
179
|
+
catalog[cols]
|
|
180
|
+
.sort_values("path_in_repo")
|
|
181
|
+
.to_dict(orient="records")
|
|
182
|
+
)
|
|
183
|
+
canonical = json.dumps(rows, sort_keys=True, separators=(",", ":"), default=str)
|
|
184
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def build_manifest(
|
|
188
|
+
reader: VulcanReader,
|
|
189
|
+
*,
|
|
190
|
+
snapshot_tag: str,
|
|
191
|
+
created_at: str,
|
|
192
|
+
tool_version: Optional[str] = None,
|
|
193
|
+
) -> SnapshotManifest:
|
|
194
|
+
r"""
|
|
195
|
+
**Description:**
|
|
196
|
+
Build a :class:`SnapshotManifest` from a reader's current view.
|
|
197
|
+
|
|
198
|
+
Reads the catalogue for per-Hodge and shard counts, then reads the
|
|
199
|
+
``verifier_id`` / ``cert_status`` / ``cert_checks`` /
|
|
200
|
+
``kahler_metric_min_eig`` columns of each shard to build the
|
|
201
|
+
histograms and count metric-PD failures. Records lacking the cert
|
|
202
|
+
columns tally under :data:`UNVERIFIED_SENTINEL`, so an
|
|
203
|
+
incompletely-certified corpus is visible rather than silently clean.
|
|
204
|
+
|
|
205
|
+
Refuses to build a manifest if the reader's catalogue scan skipped
|
|
206
|
+
any unreadable shard (``catalog.attrs['n_skipped'] > 0``): a citeable
|
|
207
|
+
snapshot must not silently omit shards.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
reader: A :class:`VulcanReader` (local or HF) over the dataset.
|
|
211
|
+
snapshot_tag: The tag this manifest describes.
|
|
212
|
+
created_at: UTC timestamp string (caller-supplied for
|
|
213
|
+
determinism).
|
|
214
|
+
tool_version: Optional stringforge version string.
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
SnapshotManifest: The assembled manifest.
|
|
218
|
+
|
|
219
|
+
Raises:
|
|
220
|
+
ValueError: If the catalogue scan skipped any unreadable shard.
|
|
221
|
+
"""
|
|
222
|
+
catalog = reader.catalog()
|
|
223
|
+
n_skipped = int(catalog.attrs.get("n_skipped", 0))
|
|
224
|
+
if n_skipped:
|
|
225
|
+
raise ValueError(
|
|
226
|
+
f"refusing to build a snapshot manifest: VulcanReader.catalog() "
|
|
227
|
+
f"skipped {n_skipped} unreadable shard(s). A citeable snapshot "
|
|
228
|
+
f"must not silently omit shards; repair or remove the corrupt "
|
|
229
|
+
f"shard(s) (see the RuntimeWarning(s) above) and retry."
|
|
230
|
+
)
|
|
231
|
+
n_shards = int(len(catalog))
|
|
232
|
+
n_records = int(catalog["n_rows"].sum()) if n_shards else 0
|
|
233
|
+
|
|
234
|
+
records_by_hodge: Counter = Counter()
|
|
235
|
+
for _, row in catalog.iterrows():
|
|
236
|
+
key = f"h11={int(row['h11'])},h12={int(row['h12'])}"
|
|
237
|
+
records_by_hodge[key] += int(row["n_rows"])
|
|
238
|
+
|
|
239
|
+
verifier_hist: Counter = Counter()
|
|
240
|
+
status_hist: Counter = Counter()
|
|
241
|
+
metric_pd_failures = 0
|
|
242
|
+
cert_cols = ["verifier_id", "cert_status", "cert_checks", "kahler_metric_min_eig"]
|
|
243
|
+
for path_in_repo in catalog["path_in_repo"]:
|
|
244
|
+
cols = reader.read_columns(path_in_repo, cert_cols)
|
|
245
|
+
n = len(cols)
|
|
246
|
+
if "verifier_id" in cols.columns:
|
|
247
|
+
vids = cols["verifier_id"].fillna(UNVERIFIED_SENTINEL)
|
|
248
|
+
for vid, cnt in vids.value_counts().items():
|
|
249
|
+
verifier_hist[str(vid)] += int(cnt)
|
|
250
|
+
else:
|
|
251
|
+
verifier_hist[UNVERIFIED_SENTINEL] += n
|
|
252
|
+
if "cert_status" in cols.columns:
|
|
253
|
+
statuses = cols["cert_status"].fillna(UNVERIFIED_SENTINEL)
|
|
254
|
+
for st, cnt in statuses.value_counts().items():
|
|
255
|
+
status_hist[str(st)] += int(cnt)
|
|
256
|
+
else:
|
|
257
|
+
status_hist[UNVERIFIED_SENTINEL] += n
|
|
258
|
+
# Count, among rows claiming `certified`, every one that does NOT
|
|
259
|
+
# POSITIVELY assert a PD Kähler metric. Using the positive
|
|
260
|
+
# predicate (vs. "explicitly failed?") is what catches the literal
|
|
261
|
+
# 2026-06-02 signature: a verifier that OMITTED the metric-PD
|
|
262
|
+
# check (no key, NaN eig) does not positively assert it, so it is
|
|
263
|
+
# counted here -- and a shard that carries cert_status but lacks
|
|
264
|
+
# the cert_checks / min-eig columns is treated as "not asserted"
|
|
265
|
+
# for every certified row rather than silently skipped.
|
|
266
|
+
if "cert_status" in cols.columns:
|
|
267
|
+
checks_col = (
|
|
268
|
+
cols["cert_checks"] if "cert_checks" in cols.columns
|
|
269
|
+
else pd.Series([None] * n, index=cols.index)
|
|
270
|
+
)
|
|
271
|
+
eig_col = (
|
|
272
|
+
cols["kahler_metric_min_eig"] if "kahler_metric_min_eig" in cols.columns
|
|
273
|
+
else pd.Series([float("nan")] * n, index=cols.index)
|
|
274
|
+
)
|
|
275
|
+
for status, cj, me in zip(cols["cert_status"], checks_col, eig_col):
|
|
276
|
+
if status != "certified":
|
|
277
|
+
continue
|
|
278
|
+
if not metric_pd_passed(cj, me):
|
|
279
|
+
metric_pd_failures += 1
|
|
280
|
+
|
|
281
|
+
return SnapshotManifest(
|
|
282
|
+
snapshot_tag=snapshot_tag,
|
|
283
|
+
created_at=created_at,
|
|
284
|
+
n_shards=n_shards,
|
|
285
|
+
n_records=n_records,
|
|
286
|
+
records_by_hodge=dict(records_by_hodge),
|
|
287
|
+
verifier_id_histogram=dict(verifier_hist),
|
|
288
|
+
cert_status_histogram=dict(status_hist),
|
|
289
|
+
schema_version=SCHEMA_VERSION,
|
|
290
|
+
content_sha256=_content_sha256(catalog),
|
|
291
|
+
metric_pd_failures=metric_pd_failures,
|
|
292
|
+
tool_version=tool_version,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def freeze_snapshot(
|
|
297
|
+
reader: VulcanReader,
|
|
298
|
+
*,
|
|
299
|
+
tag: str,
|
|
300
|
+
created_at: str,
|
|
301
|
+
repo: Optional[str] = None,
|
|
302
|
+
token: Optional[str] = None,
|
|
303
|
+
message: Optional[str] = None,
|
|
304
|
+
require_fully_certified: bool = True,
|
|
305
|
+
registry: Optional[VerifierRegistry] = None,
|
|
306
|
+
local_manifest_dir: Optional[Path] = None,
|
|
307
|
+
dry_run: bool = False,
|
|
308
|
+
tool_version: Optional[str] = None,
|
|
309
|
+
) -> SnapshotManifest:
|
|
310
|
+
r"""
|
|
311
|
+
**Description:**
|
|
312
|
+
Freeze a citeable snapshot: build the manifest, optionally write it
|
|
313
|
+
locally, and (unless ``dry_run``) commit it to the HuggingFace repo
|
|
314
|
+
and create an immutable tag.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
reader: A :class:`VulcanReader` over the dataset to freeze.
|
|
318
|
+
tag: The immutable git tag to create (e.g. ``"v2026.06"``).
|
|
319
|
+
created_at: UTC timestamp string (caller-supplied).
|
|
320
|
+
repo: HuggingFace ``"user/repo"`` to tag. Required unless
|
|
321
|
+
``dry_run`` (then the manifest is built but nothing is
|
|
322
|
+
pushed).
|
|
323
|
+
token: HuggingFace write token; falls back to ``HF_TOKEN``.
|
|
324
|
+
message: Optional commit/tag message.
|
|
325
|
+
require_fully_certified: If ``True`` (default), refuse to tag a
|
|
326
|
+
snapshot whose manifest is not fully certified
|
|
327
|
+
(:meth:`SnapshotManifest.fully_certified`) -- the
|
|
328
|
+
governance gate against citing unverified records. The
|
|
329
|
+
manifest is still returned so the caller can inspect *why*.
|
|
330
|
+
registry: Optional :class:`~stringforge.vulcan.verifier.VerifierRegistry`
|
|
331
|
+
passed to :meth:`SnapshotManifest.fully_certified`; when
|
|
332
|
+
given, every ``verifier_id`` in the corpus must resolve to a
|
|
333
|
+
registered spec that ran the metric-PD check.
|
|
334
|
+
local_manifest_dir: If given, also write the manifest JSON to
|
|
335
|
+
``<dir>/<MANIFEST_FILENAME>`` (useful for review / CI).
|
|
336
|
+
dry_run: Build (and optionally write locally) the manifest but
|
|
337
|
+
make no network call and create no tag.
|
|
338
|
+
tool_version: Optional stringforge version string.
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
SnapshotManifest: The manifest (built regardless of ``dry_run``).
|
|
342
|
+
|
|
343
|
+
Raises:
|
|
344
|
+
ValueError: If the corpus is empty; if ``require_fully_certified``
|
|
345
|
+
and the manifest is not fully certified; or if a real
|
|
346
|
+
(non-dry-run) freeze is requested without a ``repo``.
|
|
347
|
+
"""
|
|
348
|
+
manifest = build_manifest(
|
|
349
|
+
reader, snapshot_tag=tag, created_at=created_at, tool_version=tool_version,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
if local_manifest_dir is not None:
|
|
353
|
+
d = Path(local_manifest_dir)
|
|
354
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
355
|
+
(d / MANIFEST_FILENAME).write_text(
|
|
356
|
+
json.dumps(manifest.to_dict(), indent=2, sort_keys=True)
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# An empty corpus is never citeable -- guard explicitly so this
|
|
360
|
+
# fires even when require_fully_certified=False.
|
|
361
|
+
if manifest.n_records == 0:
|
|
362
|
+
raise ValueError(
|
|
363
|
+
f"refusing to freeze snapshot {tag!r}: the corpus is empty "
|
|
364
|
+
f"(n_shards={manifest.n_shards}, n_records=0). Check that the "
|
|
365
|
+
f"reader points at a synced corpus."
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
if require_fully_certified and not manifest.fully_certified(registry=registry):
|
|
369
|
+
raise ValueError(
|
|
370
|
+
f"refusing to freeze snapshot {tag!r}: manifest is not fully "
|
|
371
|
+
f"certified (verifier histogram={manifest.verifier_id_histogram}, "
|
|
372
|
+
f"cert_status histogram={manifest.cert_status_histogram}, "
|
|
373
|
+
f"metric_pd_failures={manifest.metric_pd_failures}). "
|
|
374
|
+
f"Pass require_fully_certified=False to override, or finish "
|
|
375
|
+
f"certifying / retracting the offending records first."
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
if dry_run:
|
|
379
|
+
return manifest
|
|
380
|
+
|
|
381
|
+
if not repo:
|
|
382
|
+
raise ValueError(
|
|
383
|
+
"freeze_snapshot: a real freeze requires repo='user/repo' "
|
|
384
|
+
"(pass dry_run=True to build the manifest only)."
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
_push_and_tag(
|
|
388
|
+
repo=repo,
|
|
389
|
+
tag=tag,
|
|
390
|
+
manifest=manifest,
|
|
391
|
+
token=token,
|
|
392
|
+
message=message or f"vulcan snapshot {tag}",
|
|
393
|
+
)
|
|
394
|
+
return manifest
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _push_and_tag(
|
|
398
|
+
*,
|
|
399
|
+
repo: str,
|
|
400
|
+
tag: str,
|
|
401
|
+
manifest: SnapshotManifest,
|
|
402
|
+
token: Optional[str],
|
|
403
|
+
message: str,
|
|
404
|
+
) -> None:
|
|
405
|
+
r"""
|
|
406
|
+
Upload the manifest to the repo root and create an immutable tag at
|
|
407
|
+
the resulting commit. Lazily imports ``huggingface_hub`` so this
|
|
408
|
+
module stays import-clean without the optional dependency.
|
|
409
|
+
"""
|
|
410
|
+
import os
|
|
411
|
+
try:
|
|
412
|
+
from huggingface_hub import CommitOperationAdd, HfApi # type: ignore
|
|
413
|
+
except ImportError as exc: # pragma: no cover - exercised via dependency
|
|
414
|
+
raise ImportError(
|
|
415
|
+
"freeze_snapshot (non-dry-run) requires `huggingface_hub`. "
|
|
416
|
+
"Install it via `pip install 'stringforge[sync]'`."
|
|
417
|
+
) from exc
|
|
418
|
+
|
|
419
|
+
api = HfApi(token=token or os.environ.get("HF_TOKEN"))
|
|
420
|
+
payload = json.dumps(manifest.to_dict(), indent=2, sort_keys=True).encode("utf-8")
|
|
421
|
+
api.create_commit(
|
|
422
|
+
repo_id=repo,
|
|
423
|
+
repo_type="dataset",
|
|
424
|
+
operations=[CommitOperationAdd(path_in_repo=MANIFEST_FILENAME, path_or_fileobj=payload)],
|
|
425
|
+
commit_message=message,
|
|
426
|
+
)
|
|
427
|
+
api.create_tag(repo_id=repo, repo_type="dataset", tag=tag, tag_message=message)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
__all__ = (
|
|
431
|
+
"SnapshotManifest",
|
|
432
|
+
"build_manifest",
|
|
433
|
+
"freeze_snapshot",
|
|
434
|
+
"MANIFEST_FILENAME",
|
|
435
|
+
"UNVERIFIED_SENTINEL",
|
|
436
|
+
)
|
|
@@ -0,0 +1,263 @@
|
|
|
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
|
+
Vulcan sync tier: batch staged shards into HuggingFace commits.
|
|
12
|
+
|
|
13
|
+
A single :func:`sync_pending` call moves the contents of
|
|
14
|
+
``{staging_dir}/pending/`` into ``synced/`` (or ``failed/``) by
|
|
15
|
+
issuing batched ``HfApi.create_commit`` operations. At most
|
|
16
|
+
:data:`~stringforge.vulcan.ratelimit.DEFAULT_BUDGET` commits are
|
|
17
|
+
issued per rolling-window hour (subject to the persisted budget
|
|
18
|
+
state); each commit can carry up to ``max_batch`` files.
|
|
19
|
+
|
|
20
|
+
On a 429 from HuggingFace the offending batch is retried with
|
|
21
|
+
exponential backoff that honours the server's ``Retry-After``;
|
|
22
|
+
persistent failures land in ``failed/`` for manual inspection.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import List, Optional
|
|
29
|
+
|
|
30
|
+
from .hf_io import CommitResult, create_batched_commit
|
|
31
|
+
from .ratelimit import (
|
|
32
|
+
CommitBudget,
|
|
33
|
+
DEFAULT_BUDGET,
|
|
34
|
+
DEFAULT_WINDOW_S,
|
|
35
|
+
sleep_with_backoff,
|
|
36
|
+
)
|
|
37
|
+
from .writer import (
|
|
38
|
+
FAILED_DIRNAME,
|
|
39
|
+
PENDING_DIRNAME,
|
|
40
|
+
StagedShard,
|
|
41
|
+
SYNCED_DIRNAME,
|
|
42
|
+
list_pending,
|
|
43
|
+
move_to,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
#: Default maximum files per commit. HuggingFace places no strict
|
|
47
|
+
#: cap, but very large commits slow down the Hub UI and the diff
|
|
48
|
+
#: viewer. 500 keeps shard-batches usable.
|
|
49
|
+
DEFAULT_MAX_BATCH: int = 500
|
|
50
|
+
|
|
51
|
+
#: Default maximum retries on a single batch hitting a rate-limit
|
|
52
|
+
#: response. Three retries with exponential backoff covers most
|
|
53
|
+
#: transient outages; beyond that we relegate the batch to ``failed/``.
|
|
54
|
+
DEFAULT_MAX_RETRIES: int = 3
|
|
55
|
+
|
|
56
|
+
#: Filename of the persisted commit-window state under the staging
|
|
57
|
+
#: directory. One file per Vulcan staging dir; the budget is
|
|
58
|
+
#: per-staging-dir, not per-repo, so a single sync process targeting
|
|
59
|
+
#: multiple repos through one staging area shares the budget across
|
|
60
|
+
#: repos. (For multi-repo writes you'd use multiple staging dirs.)
|
|
61
|
+
BUDGET_STATE_FILENAME: str = "_commit_budget.json"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class SyncReport:
|
|
66
|
+
r"""
|
|
67
|
+
Summary of a single :func:`sync_pending` invocation.
|
|
68
|
+
|
|
69
|
+
Attributes:
|
|
70
|
+
n_committed: Total files that landed in successful commits.
|
|
71
|
+
n_failed: Files moved into ``failed/`` after exhausting retries.
|
|
72
|
+
n_remaining: Files still in ``pending/`` (budget-exhausted).
|
|
73
|
+
n_commits: Number of HF commits issued.
|
|
74
|
+
commit_oids: Per-commit OIDs (None entries for dry-run).
|
|
75
|
+
errors: Strings describing per-batch failures, when any.
|
|
76
|
+
"""
|
|
77
|
+
n_committed: int = 0
|
|
78
|
+
n_failed: int = 0
|
|
79
|
+
n_remaining: int = 0
|
|
80
|
+
n_commits: int = 0
|
|
81
|
+
commit_oids: List[Optional[str]] = field(default_factory=list)
|
|
82
|
+
errors: List[str] = field(default_factory=list)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _chunk(items: List[StagedShard], size: int) -> List[List[StagedShard]]:
|
|
86
|
+
if size <= 0:
|
|
87
|
+
raise ValueError("max_batch must be >= 1")
|
|
88
|
+
return [items[i:i + size] for i in range(0, len(items), size)]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _attempt_commit(
|
|
92
|
+
*,
|
|
93
|
+
repo_id: str,
|
|
94
|
+
batch: List[StagedShard],
|
|
95
|
+
commit_message: str,
|
|
96
|
+
token: Optional[str],
|
|
97
|
+
create_pr: bool,
|
|
98
|
+
revision: Optional[str],
|
|
99
|
+
dry_run: bool,
|
|
100
|
+
max_retries: int,
|
|
101
|
+
) -> CommitResult:
|
|
102
|
+
r"""
|
|
103
|
+
Run :func:`create_batched_commit` with retry+backoff on rate-limit
|
|
104
|
+
responses. Other failures (auth, network, etc.) are returned
|
|
105
|
+
after a single attempt.
|
|
106
|
+
"""
|
|
107
|
+
# Only the parquet files travel to HuggingFace. Sidecars are a
|
|
108
|
+
# local tracking concern and the parquet's kv-metadata blob
|
|
109
|
+
# already carries the same provenance; uploading sidecars too
|
|
110
|
+
# would just inflate the per-commit file count without giving
|
|
111
|
+
# consumers anything they can't get from the parquet itself.
|
|
112
|
+
paths_and_locals = [(s.path_in_repo, s.parquet_path) for s in batch]
|
|
113
|
+
|
|
114
|
+
last: Optional[CommitResult] = None
|
|
115
|
+
for attempt in range(max_retries + 1):
|
|
116
|
+
result = create_batched_commit(
|
|
117
|
+
repo_id=repo_id,
|
|
118
|
+
paths_and_locals=paths_and_locals,
|
|
119
|
+
commit_message=commit_message,
|
|
120
|
+
token=token,
|
|
121
|
+
create_pr=create_pr,
|
|
122
|
+
revision=revision,
|
|
123
|
+
dry_run=dry_run,
|
|
124
|
+
)
|
|
125
|
+
last = result
|
|
126
|
+
if result.ok:
|
|
127
|
+
return result
|
|
128
|
+
if result.retry_after_s is None and not getattr(result, "is_transient", False):
|
|
129
|
+
# Not a rate-limit error and not a transient network failure -- don't retry.
|
|
130
|
+
return result
|
|
131
|
+
if attempt == max_retries:
|
|
132
|
+
return result
|
|
133
|
+
sleep_with_backoff(attempt, retry_after_s=result.retry_after_s)
|
|
134
|
+
assert last is not None
|
|
135
|
+
return last
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def sync_pending(
|
|
139
|
+
staging_dir: Path,
|
|
140
|
+
*,
|
|
141
|
+
repo_id: str,
|
|
142
|
+
token: Optional[str] = None,
|
|
143
|
+
budget: int = DEFAULT_BUDGET,
|
|
144
|
+
window_s: float = DEFAULT_WINDOW_S,
|
|
145
|
+
max_batch: int = DEFAULT_MAX_BATCH,
|
|
146
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
147
|
+
repo_type: str = "dataset",
|
|
148
|
+
create_pr: bool = False,
|
|
149
|
+
revision: Optional[str] = None,
|
|
150
|
+
dry_run: bool = False,
|
|
151
|
+
commit_prefix: str = "vulcan: forge",
|
|
152
|
+
) -> SyncReport:
|
|
153
|
+
r"""
|
|
154
|
+
**Description:**
|
|
155
|
+
Drain ``{staging_dir}/pending/`` into HuggingFace commits.
|
|
156
|
+
|
|
157
|
+
Shards are processed in batches of at most ``max_batch`` files.
|
|
158
|
+
Each batch consumes one slot from the rolling-window budget
|
|
159
|
+
(advisory: see :class:`~stringforge.vulcan.ratelimit.CommitBudget`);
|
|
160
|
+
once the budget is exhausted, remaining batches stay in
|
|
161
|
+
``pending/`` for a later invocation to pick up. Successful
|
|
162
|
+
batches move their shards to ``synced/``; persistent failures
|
|
163
|
+
(after ``max_retries`` rate-limit retries with exponential
|
|
164
|
+
backoff) move to ``failed/`` for manual inspection.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
staging_dir: Vulcan staging root.
|
|
168
|
+
repo_id: HuggingFace dataset repo target.
|
|
169
|
+
token: HF write token; falls back to ``HF_TOKEN``.
|
|
170
|
+
budget: Maximum commits permitted per rolling ``window_s``.
|
|
171
|
+
window_s: Window length (seconds). Defaults to 1 hour.
|
|
172
|
+
max_batch: Maximum files per HuggingFace commit.
|
|
173
|
+
max_retries: Per-batch retry budget on 429/503 responses.
|
|
174
|
+
repo_type: HF repo type; default ``"dataset"``.
|
|
175
|
+
create_pr: Open PRs instead of pushing to the default branch.
|
|
176
|
+
revision: HF revision name; defaults to the repo's default
|
|
177
|
+
branch.
|
|
178
|
+
dry_run: Skip the network call. Shards stay in ``pending/``;
|
|
179
|
+
budget slots are still reserved.
|
|
180
|
+
commit_prefix: Prefix for the auto-generated commit message.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
SyncReport: Summary of what landed, what remains, and what
|
|
184
|
+
failed.
|
|
185
|
+
"""
|
|
186
|
+
staging_dir = Path(staging_dir)
|
|
187
|
+
pending = list_pending(staging_dir)
|
|
188
|
+
report = SyncReport()
|
|
189
|
+
if not pending:
|
|
190
|
+
return report
|
|
191
|
+
|
|
192
|
+
budget_state = CommitBudget(
|
|
193
|
+
staging_dir / BUDGET_STATE_FILENAME,
|
|
194
|
+
budget=budget,
|
|
195
|
+
window_s=window_s,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
batches = _chunk(pending, max_batch)
|
|
199
|
+
for batch in batches:
|
|
200
|
+
if not budget_state.reserve():
|
|
201
|
+
report.n_remaining += len(batch)
|
|
202
|
+
continue
|
|
203
|
+
|
|
204
|
+
run_ids = sorted({s.run_id for s in batch})
|
|
205
|
+
if len(run_ids) == 1:
|
|
206
|
+
run_summary = run_ids[0]
|
|
207
|
+
else:
|
|
208
|
+
run_summary = f"{run_ids[0]} (+{len(run_ids) - 1} more)"
|
|
209
|
+
commit_message = (
|
|
210
|
+
f"{commit_prefix}: {len(batch)} shards, run={run_summary}"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
result = _attempt_commit(
|
|
214
|
+
repo_id=repo_id,
|
|
215
|
+
batch=batch,
|
|
216
|
+
commit_message=commit_message,
|
|
217
|
+
token=token,
|
|
218
|
+
create_pr=create_pr,
|
|
219
|
+
revision=revision,
|
|
220
|
+
dry_run=dry_run,
|
|
221
|
+
max_retries=max_retries,
|
|
222
|
+
)
|
|
223
|
+
report.n_commits += 1
|
|
224
|
+
report.commit_oids.append(result.commit_oid)
|
|
225
|
+
|
|
226
|
+
if result.ok:
|
|
227
|
+
if not dry_run:
|
|
228
|
+
for shard in batch:
|
|
229
|
+
move_to(shard, staging_dir, SYNCED_DIRNAME)
|
|
230
|
+
report.n_committed += len(batch)
|
|
231
|
+
else:
|
|
232
|
+
report.errors.append(result.error or "unknown commit failure")
|
|
233
|
+
if not dry_run:
|
|
234
|
+
for shard in batch:
|
|
235
|
+
move_to(shard, staging_dir, FAILED_DIRNAME)
|
|
236
|
+
report.n_failed += len(batch)
|
|
237
|
+
|
|
238
|
+
# Any batches we didn't try because we ran out of budget are still
|
|
239
|
+
# in `pending/` -- ``list_pending`` will pick them up next time.
|
|
240
|
+
return report
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def remaining_budget(staging_dir: Path, *, budget: int = DEFAULT_BUDGET,
|
|
244
|
+
window_s: float = DEFAULT_WINDOW_S) -> int:
|
|
245
|
+
r"""
|
|
246
|
+
**Description:**
|
|
247
|
+
Report how many commit slots are currently available for the
|
|
248
|
+
given staging directory.
|
|
249
|
+
|
|
250
|
+
Args:
|
|
251
|
+
staging_dir: Vulcan staging root.
|
|
252
|
+
budget: Ceiling to evaluate against (defaults to the module
|
|
253
|
+
default).
|
|
254
|
+
window_s: Window length in seconds.
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
int: Non-negative slot count.
|
|
258
|
+
"""
|
|
259
|
+
return CommitBudget(
|
|
260
|
+
Path(staging_dir) / BUDGET_STATE_FILENAME,
|
|
261
|
+
budget=budget,
|
|
262
|
+
window_s=window_s,
|
|
263
|
+
).remaining()
|