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,261 @@
|
|
|
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
|
+
Community submission gate for the rolling certified-vacua database.
|
|
12
|
+
|
|
13
|
+
Phase 3 of the rolling-DB plan: let external contributors propose
|
|
14
|
+
vacua, but **trust nothing client-side**. A submission is a parquet of
|
|
15
|
+
candidate rows; the maintainer's server re-runs the *full* physics
|
|
16
|
+
cascade (it never believes a submitter's ``is_susy`` / ``residual`` /
|
|
17
|
+
``verifier_id`` / ``cert_status``), and only re-certified, de-duplicated
|
|
18
|
+
rows are admitted.
|
|
19
|
+
|
|
20
|
+
Two structural guards make this safe:
|
|
21
|
+
|
|
22
|
+
1. **Full-cascade requirement.** :func:`review_submission` refuses any
|
|
23
|
+
verifier whose :meth:`VerifierSpec.includes_metric_pd_check` is
|
|
24
|
+
``False``. The current curated-vault CI runs F-term / tadpole but
|
|
25
|
+
*not* the Kähler-metric positive-definiteness check; opening
|
|
26
|
+
community writes without that guard would re-introduce the
|
|
27
|
+
2026-06-02 bug (≈465 saddle points miscounted as vacua) at the front
|
|
28
|
+
door.
|
|
29
|
+
|
|
30
|
+
2. **Client-cert stripping.** Any certification columns a submitter
|
|
31
|
+
set are *dropped before re-certification*, so a forged
|
|
32
|
+
``cert_status="certified"`` / ``verifier_id`` can never survive --
|
|
33
|
+
the server stamps its own.
|
|
34
|
+
|
|
35
|
+
This module is solver-free: the server-side certifier is injected
|
|
36
|
+
(built via :func:`stringforge.vulcan.certify.build_jaxvacua_certifier`
|
|
37
|
+
in production; a stub in tests).
|
|
38
|
+
"""
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
from dataclasses import dataclass, field
|
|
42
|
+
from typing import Any, Iterable, List, Mapping, Optional, Set, Tuple
|
|
43
|
+
|
|
44
|
+
import pandas as pd
|
|
45
|
+
|
|
46
|
+
from .certify import Certifier, certify_shard
|
|
47
|
+
from .schema import canonical_flux, geometry_id, metric_pd_passed
|
|
48
|
+
from .verifier import VerifierSpec
|
|
49
|
+
|
|
50
|
+
#: Physical dedup key type: ``(geometry_id, canonical_flux)``. This is
|
|
51
|
+
#: deliberately *verifier-independent* -- the same vacuum is one entry
|
|
52
|
+
#: regardless of which verifier certified it (cf. ``record_id``, which
|
|
53
|
+
#: includes the verifier and is the per-row key, not the dedup key).
|
|
54
|
+
DedupKey = Tuple[str, Tuple[int, ...]]
|
|
55
|
+
|
|
56
|
+
#: Client-supplied columns the gate must NOT trust: unverified physics /
|
|
57
|
+
#: telemetry flags, the orientifold ``tadpole_charge`` (a physics
|
|
58
|
+
#: quantity the certifier does not recompute, so a forged value would
|
|
59
|
+
#: otherwise survive into the DB), and provenance fields the server
|
|
60
|
+
#: re-derives. All are stripped before re-certification; the writer
|
|
61
|
+
#: then supplies authoritative ``tadpole_charge`` / ``created_at`` at
|
|
62
|
+
#: write time. (Identity columns -- ``geometry_id`` and the geometry
|
|
63
|
+
#: keys -- are NOT listed here because the certifier re-stamps them
|
|
64
|
+
#: authoritatively from the trusted ``geometry``. ``tags`` /
|
|
65
|
+
#: ``extra_data`` are the designed free-form user-metadata channel and
|
|
66
|
+
#: are intentionally preserved.)
|
|
67
|
+
UNTRUSTED_CLIENT_COLUMNS: Tuple[str, ...] = (
|
|
68
|
+
# cert columns the server re-stamps
|
|
69
|
+
"verifier_id", "cert_status", "cert_checks",
|
|
70
|
+
"kahler_metric_min_eig", "hessian_min_eig", "mass_min_eig", "record_id",
|
|
71
|
+
# unverified physics / telemetry
|
|
72
|
+
"is_susy", "is_isd", "residual", "n_iterations",
|
|
73
|
+
"W_re", "W_im", "F_terms_re", "F_terms_im",
|
|
74
|
+
"solver_name", "solver_config_hash",
|
|
75
|
+
# physics quantity the certifier does not recompute -> never trust
|
|
76
|
+
"tadpole_charge",
|
|
77
|
+
# provenance the server re-derives / re-stamps
|
|
78
|
+
"git_sha", "seed", "wall_clock_s", "created_at",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass
|
|
83
|
+
class CommunityGateResult:
|
|
84
|
+
r"""
|
|
85
|
+
**Description:**
|
|
86
|
+
Outcome of :func:`review_submission`.
|
|
87
|
+
|
|
88
|
+
Attributes:
|
|
89
|
+
accepted: ``True`` iff at least one row survived re-certification
|
|
90
|
+
and de-duplication.
|
|
91
|
+
certified: The admitted rows, stamped by the *server's*
|
|
92
|
+
verifier (empty when nothing survived).
|
|
93
|
+
n_submitted: Number of submitted rows.
|
|
94
|
+
n_certified: Rows that passed server-side re-certification.
|
|
95
|
+
n_duplicates: Certified rows dropped because their physical
|
|
96
|
+
dedup key was already present.
|
|
97
|
+
n_admitted: Rows finally admitted (certified minus duplicates).
|
|
98
|
+
reasons: Human-readable notes (rejections, dedup counts, gate
|
|
99
|
+
decisions).
|
|
100
|
+
"""
|
|
101
|
+
accepted: bool
|
|
102
|
+
certified: pd.DataFrame
|
|
103
|
+
n_submitted: int
|
|
104
|
+
n_certified: int
|
|
105
|
+
n_duplicates: int
|
|
106
|
+
n_admitted: int
|
|
107
|
+
reasons: List[str] = field(default_factory=list)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def dedup_key(geometry: Mapping[str, Any], flux: Iterable[Any]) -> DedupKey:
|
|
111
|
+
r"""
|
|
112
|
+
**Description:**
|
|
113
|
+
Return the verifier-independent physical dedup key
|
|
114
|
+
``(geometry_id, canonical_flux)`` for a vacuum.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
geometry: Geometry index dict (mirror convention).
|
|
118
|
+
flux: Integer flux vector.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
DedupKey: The dedup key.
|
|
122
|
+
"""
|
|
123
|
+
return (geometry_id(geometry), canonical_flux(flux))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def review_submission(
|
|
127
|
+
df: pd.DataFrame,
|
|
128
|
+
*,
|
|
129
|
+
certifier: Certifier,
|
|
130
|
+
verifier_spec: VerifierSpec,
|
|
131
|
+
geometry: Mapping[str, Any],
|
|
132
|
+
seen_keys: Optional[Set[DedupKey]] = None,
|
|
133
|
+
require_metric_pd: bool = True,
|
|
134
|
+
) -> CommunityGateResult:
|
|
135
|
+
r"""
|
|
136
|
+
**Description:**
|
|
137
|
+
Independently re-certify a community submission and admit only the
|
|
138
|
+
rows that pass and are not duplicates.
|
|
139
|
+
|
|
140
|
+
The submission's own certification columns are discarded before
|
|
141
|
+
re-certification (trust nothing client-side); the server stamps its
|
|
142
|
+
own ``verifier_id`` / ``cert_status`` via
|
|
143
|
+
:func:`stringforge.vulcan.certify.certify_shard`.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
df: Submitted candidate rows (untrusted).
|
|
147
|
+
certifier: The *server's* per-row physics certifier.
|
|
148
|
+
verifier_spec: The server's verifier description. Must include
|
|
149
|
+
the Kähler-metric PD check unless ``require_metric_pd`` is
|
|
150
|
+
explicitly disabled.
|
|
151
|
+
geometry: The model's geometry index dict (mirror convention).
|
|
152
|
+
seen_keys: Physical dedup keys already present in the DB; any
|
|
153
|
+
certified row whose key is in this set is dropped as a
|
|
154
|
+
duplicate. ``None`` treats the DB as empty.
|
|
155
|
+
require_metric_pd: Refuse the submission unless the verifier
|
|
156
|
+
runs the metric-PD check (default ``True`` -- the
|
|
157
|
+
2026-06-02 guard).
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
CommunityGateResult: The admission decision and admitted rows.
|
|
161
|
+
|
|
162
|
+
Raises:
|
|
163
|
+
ValueError: If ``require_metric_pd`` and the verifier does not
|
|
164
|
+
run the Kähler-metric PD check.
|
|
165
|
+
"""
|
|
166
|
+
if require_metric_pd and not verifier_spec.includes_metric_pd_check():
|
|
167
|
+
raise ValueError(
|
|
168
|
+
"community gate: the server-side verifier MUST run the "
|
|
169
|
+
"Kähler-metric positive-definiteness check ('kahler_metric_pd'). "
|
|
170
|
+
"Refusing to open the community write path with a verifier that "
|
|
171
|
+
"would re-introduce the 2026-06-02 saddle-point bug. Pass "
|
|
172
|
+
"require_metric_pd=False only in a deliberately-degraded test."
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
reasons: List[str] = []
|
|
176
|
+
n_submitted = int(len(df))
|
|
177
|
+
|
|
178
|
+
# Trust nothing client-side: drop any certification columns AND any
|
|
179
|
+
# unverified physics/telemetry flags the submitter set, so a forged
|
|
180
|
+
# value can never survive re-certification. Identity columns
|
|
181
|
+
# (geometry_id, geometry keys) are re-stamped authoritatively by the
|
|
182
|
+
# certifier from the trusted `geometry`, so they need not be stripped
|
|
183
|
+
# here -- but the physics flags have no server-recomputed counterpart
|
|
184
|
+
# yet, so they MUST be removed rather than carried through unverified.
|
|
185
|
+
forged = [c for c in UNTRUSTED_CLIENT_COLUMNS if c in df.columns]
|
|
186
|
+
if forged:
|
|
187
|
+
reasons.append(f"stripped client-supplied / unverified columns before re-cert: {forged}")
|
|
188
|
+
stripped = df.drop(columns=forged, errors="ignore")
|
|
189
|
+
|
|
190
|
+
result = certify_shard(
|
|
191
|
+
stripped, certifier=certifier, verifier_spec=verifier_spec, geometry=geometry,
|
|
192
|
+
)
|
|
193
|
+
reasons.append(
|
|
194
|
+
f"server re-certification: {result.n_certified}/{n_submitted} rows passed "
|
|
195
|
+
f"under verifier {result.verifier_id}"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
certified = result.certified
|
|
199
|
+
|
|
200
|
+
# Per-row metric-PD consistency: never admit a row the certifier
|
|
201
|
+
# marked passed if its own evidence (cert_checks / min-eig) shows the
|
|
202
|
+
# Kähler metric was not positive-definite. Defence-in-depth against
|
|
203
|
+
# an internally-inconsistent certifier (the 2026-06-02 signature),
|
|
204
|
+
# not a client exploit.
|
|
205
|
+
if require_metric_pd and len(certified):
|
|
206
|
+
pd_mask = [
|
|
207
|
+
metric_pd_passed(cj, me)
|
|
208
|
+
for cj, me in zip(certified["cert_checks"], certified["kahler_metric_min_eig"])
|
|
209
|
+
]
|
|
210
|
+
n_bad = int(len(pd_mask) - sum(pd_mask))
|
|
211
|
+
if n_bad:
|
|
212
|
+
reasons.append(
|
|
213
|
+
f"dropped {n_bad} row(s): certifier reported passed but "
|
|
214
|
+
f"kahler_metric_pd != True / min-eig <= 0 (passed/checks inconsistency)"
|
|
215
|
+
)
|
|
216
|
+
certified = certified.loc[pd_mask].reset_index(drop=True)
|
|
217
|
+
|
|
218
|
+
# De-duplicate against the DB AND within the submission itself: a
|
|
219
|
+
# submitter must not inflate a vacuum's count by repeating the same
|
|
220
|
+
# flux, which would also break the record_id uniqueness invariant.
|
|
221
|
+
n_duplicates = 0
|
|
222
|
+
if len(certified):
|
|
223
|
+
seen = set(seen_keys) if seen_keys else set()
|
|
224
|
+
keep_mask: List[bool] = []
|
|
225
|
+
batch_seen: Set[DedupKey] = set()
|
|
226
|
+
for flux in certified["flux"]:
|
|
227
|
+
k = dedup_key(geometry, flux)
|
|
228
|
+
keep = k not in seen and k not in batch_seen
|
|
229
|
+
keep_mask.append(keep)
|
|
230
|
+
if keep:
|
|
231
|
+
batch_seen.add(k)
|
|
232
|
+
n_duplicates = int(len(keep_mask) - sum(keep_mask))
|
|
233
|
+
if n_duplicates:
|
|
234
|
+
reasons.append(
|
|
235
|
+
f"dropped {n_duplicates} duplicate row(s) (already in the DB "
|
|
236
|
+
f"or repeated within the submission)"
|
|
237
|
+
)
|
|
238
|
+
certified = certified.loc[keep_mask].reset_index(drop=True)
|
|
239
|
+
|
|
240
|
+
n_admitted = int(len(certified))
|
|
241
|
+
accepted = n_admitted > 0
|
|
242
|
+
if not accepted:
|
|
243
|
+
reasons.append("submission rejected: no rows survived re-certification + dedup")
|
|
244
|
+
|
|
245
|
+
return CommunityGateResult(
|
|
246
|
+
accepted=accepted,
|
|
247
|
+
certified=certified,
|
|
248
|
+
n_submitted=n_submitted,
|
|
249
|
+
n_certified=result.n_certified,
|
|
250
|
+
n_duplicates=n_duplicates,
|
|
251
|
+
n_admitted=n_admitted,
|
|
252
|
+
reasons=reasons,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
__all__ = (
|
|
257
|
+
"CommunityGateResult",
|
|
258
|
+
"DedupKey",
|
|
259
|
+
"dedup_key",
|
|
260
|
+
"review_submission",
|
|
261
|
+
)
|
|
@@ -0,0 +1,296 @@
|
|
|
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
|
+
HuggingFace Hub I/O wrappers for Vulcan.
|
|
12
|
+
|
|
13
|
+
Vulcan uses :class:`huggingface_hub.HfApi.create_commit` to upload
|
|
14
|
+
many staged shards in **one** commit -- avoiding the
|
|
15
|
+
one-commit-per-file pattern in
|
|
16
|
+
:func:`stringforge.vacua_writer.VacuaWriter.designate_vacua` that
|
|
17
|
+
would hit HF's 100-commit-per-hour cap almost immediately on a cluster
|
|
18
|
+
workload.
|
|
19
|
+
|
|
20
|
+
The HuggingFace SDK is an *optional* runtime dependency: this module
|
|
21
|
+
loads it lazily so the rest of Vulcan (worker writes, schema
|
|
22
|
+
validation, run-id rendering, queries against a local cache) keeps
|
|
23
|
+
working in environments without ``huggingface_hub`` installed.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import os
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Iterable, List, Optional, Sequence
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class CommitResult:
|
|
35
|
+
r"""
|
|
36
|
+
Outcome of a single batched commit.
|
|
37
|
+
|
|
38
|
+
Attributes:
|
|
39
|
+
ok: ``True`` if the commit landed on HF.
|
|
40
|
+
commit_oid: The commit OID returned by the Hub (``None`` on
|
|
41
|
+
failure or dry-run).
|
|
42
|
+
paths: HF-repo-relative paths that were carried in this commit.
|
|
43
|
+
error: Stringified error when ``ok`` is False.
|
|
44
|
+
retry_after_s: Minimum retry interval for rate-limit responses;
|
|
45
|
+
``0.0`` when the server didn't suggest one, ``None`` when
|
|
46
|
+
the failure is not rate-limit-shaped.
|
|
47
|
+
is_transient: ``True`` when the failure looks like a transient
|
|
48
|
+
network error (connection reset, timeout) with no HTTP
|
|
49
|
+
response attached. The sync tier treats this as
|
|
50
|
+
retry-eligible under its own back-off schedule.
|
|
51
|
+
"""
|
|
52
|
+
ok: bool
|
|
53
|
+
commit_oid: Optional[str]
|
|
54
|
+
paths: List[str]
|
|
55
|
+
error: Optional[str] = None
|
|
56
|
+
retry_after_s: Optional[float] = None
|
|
57
|
+
is_transient: bool = False
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _load_hf_api() -> Any:
|
|
61
|
+
r"""
|
|
62
|
+
Lazily import :class:`huggingface_hub.HfApi`.
|
|
63
|
+
|
|
64
|
+
Raises a clear ``ImportError`` referencing the M2 dependency hint
|
|
65
|
+
rather than the SDK's own message.
|
|
66
|
+
"""
|
|
67
|
+
try:
|
|
68
|
+
from huggingface_hub import HfApi # type: ignore
|
|
69
|
+
except ImportError as exc:
|
|
70
|
+
raise ImportError(
|
|
71
|
+
"huggingface_hub is required for Vulcan sync. "
|
|
72
|
+
"Install it via `pip install 'stringforge[sync]'`."
|
|
73
|
+
) from exc
|
|
74
|
+
return HfApi
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _commit_operations(paths_and_locals: Sequence[tuple[str, Path]]) -> list:
|
|
78
|
+
r"""
|
|
79
|
+
Build a list of ``CommitOperationAdd`` operations for
|
|
80
|
+
``HfApi.create_commit``. ``paths_and_locals`` pairs the in-repo
|
|
81
|
+
path with the on-disk source.
|
|
82
|
+
"""
|
|
83
|
+
try:
|
|
84
|
+
from huggingface_hub import CommitOperationAdd # type: ignore
|
|
85
|
+
except ImportError as exc:
|
|
86
|
+
raise ImportError(
|
|
87
|
+
"Vulcan sync requires `huggingface_hub.CommitOperationAdd`. "
|
|
88
|
+
"Install or upgrade huggingface_hub."
|
|
89
|
+
) from exc
|
|
90
|
+
ops = []
|
|
91
|
+
for path_in_repo, local_path in paths_and_locals:
|
|
92
|
+
ops.append(
|
|
93
|
+
CommitOperationAdd(
|
|
94
|
+
path_in_repo=path_in_repo,
|
|
95
|
+
path_or_fileobj=str(local_path),
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
return ops
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _extract_retry_after(exc: BaseException) -> Optional[float]:
|
|
102
|
+
r"""
|
|
103
|
+
**Description:**
|
|
104
|
+
Best-effort extraction of a ``Retry-After`` value from an
|
|
105
|
+
:class:`huggingface_hub.errors.HfHubHTTPError` or its underlying
|
|
106
|
+
``requests.Response``.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
exc: The exception raised by the HF client.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
Optional[float]: Seconds to wait, or ``None`` if the response
|
|
113
|
+
carried no header (or no response object).
|
|
114
|
+
"""
|
|
115
|
+
response = getattr(exc, "response", None)
|
|
116
|
+
if response is None:
|
|
117
|
+
return None
|
|
118
|
+
headers = getattr(response, "headers", None)
|
|
119
|
+
if not headers:
|
|
120
|
+
return None
|
|
121
|
+
from .ratelimit import parse_retry_after
|
|
122
|
+
return parse_retry_after(headers.get("Retry-After"))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _is_rate_limit_error(exc: BaseException) -> bool:
|
|
126
|
+
r"""
|
|
127
|
+
Heuristic for "this looks like an HF rate-limit response". Accepts
|
|
128
|
+
HTTP 429 and 503; rejects everything else. We intentionally do
|
|
129
|
+
not catch generic network errors here -- those are handled by the
|
|
130
|
+
sync tier's wider retry envelope.
|
|
131
|
+
"""
|
|
132
|
+
response = getattr(exc, "response", None)
|
|
133
|
+
if response is None:
|
|
134
|
+
return False
|
|
135
|
+
status = getattr(response, "status_code", None)
|
|
136
|
+
return status in (429, 503)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _is_transient_network_error(exc: BaseException) -> bool:
|
|
140
|
+
r"""
|
|
141
|
+
**Description:**
|
|
142
|
+
Heuristic for "this looks like a transient network failure" --
|
|
143
|
+
i.e. a connection reset or timeout with no HTTP response object
|
|
144
|
+
attached. Such failures are retry-eligible under the sync tier's
|
|
145
|
+
own back-off schedule.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
exc: The exception raised by the HF client.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
bool: ``True`` if the exception is a connection / timeout
|
|
152
|
+
class with no response object, ``False`` otherwise.
|
|
153
|
+
"""
|
|
154
|
+
if getattr(exc, "response", None) is not None:
|
|
155
|
+
return False
|
|
156
|
+
try:
|
|
157
|
+
import requests.exceptions as _rexc # type: ignore
|
|
158
|
+
except ImportError:
|
|
159
|
+
_rexc = None # type: ignore[assignment]
|
|
160
|
+
if _rexc is not None and isinstance(
|
|
161
|
+
exc, (_rexc.ConnectionError, _rexc.Timeout)
|
|
162
|
+
):
|
|
163
|
+
return True
|
|
164
|
+
return exc.__class__.__name__ in {"ConnectionError", "Timeout", "ReadTimeout"}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def create_batched_commit(
|
|
168
|
+
*,
|
|
169
|
+
repo_id: str,
|
|
170
|
+
paths_and_locals: Sequence[tuple[str, Path]],
|
|
171
|
+
commit_message: str,
|
|
172
|
+
token: Optional[str] = None,
|
|
173
|
+
repo_type: str = "dataset",
|
|
174
|
+
create_pr: bool = False,
|
|
175
|
+
revision: Optional[str] = None,
|
|
176
|
+
dry_run: bool = False,
|
|
177
|
+
) -> CommitResult:
|
|
178
|
+
r"""
|
|
179
|
+
**Description:**
|
|
180
|
+
Upload a batch of files to ``repo_id`` in a single commit.
|
|
181
|
+
|
|
182
|
+
The call is atomic on the HuggingFace side: either every file
|
|
183
|
+
lands or none does. Failures (auth, network, rate-limit) are
|
|
184
|
+
reported back as a :class:`CommitResult` with ``ok=False`` rather
|
|
185
|
+
than being raised, so the sync tier can route them to ``failed/``
|
|
186
|
+
or retry without losing the batch.
|
|
187
|
+
|
|
188
|
+
On ``dry_run=True`` no network call is made and ``ok`` is reported
|
|
189
|
+
as ``True`` with ``commit_oid=None``.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
repo_id: ``"user/repo"`` on the Hub.
|
|
193
|
+
paths_and_locals: Iterable of ``(path_in_repo, local_path)``
|
|
194
|
+
pairs. Each ``local_path`` must be readable.
|
|
195
|
+
commit_message: Single commit message for the whole batch.
|
|
196
|
+
token: HF write token. Falls back to ``HF_TOKEN`` env var if
|
|
197
|
+
unset.
|
|
198
|
+
repo_type: ``"dataset"`` for Vulcan; the SDK default would be
|
|
199
|
+
``"model"``.
|
|
200
|
+
create_pr: When ``True``, opens a PR instead of pushing to the
|
|
201
|
+
default branch.
|
|
202
|
+
revision: Optional ref name; defaults to the repo's default
|
|
203
|
+
branch.
|
|
204
|
+
dry_run: Skip the network call. Used by the sync CLI in
|
|
205
|
+
inspect mode.
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
CommitResult: Summary of the outcome. ``retry_after_s`` is
|
|
209
|
+
populated only on rate-limit responses.
|
|
210
|
+
"""
|
|
211
|
+
paths = [p for (p, _) in paths_and_locals]
|
|
212
|
+
if not paths:
|
|
213
|
+
return CommitResult(ok=True, commit_oid=None, paths=[])
|
|
214
|
+
|
|
215
|
+
if dry_run:
|
|
216
|
+
return CommitResult(ok=True, commit_oid=None, paths=paths)
|
|
217
|
+
|
|
218
|
+
HfApi = _load_hf_api()
|
|
219
|
+
api = HfApi(token=token or os.environ.get("HF_TOKEN"))
|
|
220
|
+
operations = _commit_operations(paths_and_locals)
|
|
221
|
+
|
|
222
|
+
try:
|
|
223
|
+
commit_info = api.create_commit(
|
|
224
|
+
repo_id=repo_id,
|
|
225
|
+
repo_type=repo_type,
|
|
226
|
+
operations=operations,
|
|
227
|
+
commit_message=commit_message,
|
|
228
|
+
create_pr=create_pr,
|
|
229
|
+
revision=revision,
|
|
230
|
+
)
|
|
231
|
+
except Exception as exc: # noqa: BLE001 -- we report this back, not raise
|
|
232
|
+
if _is_rate_limit_error(exc):
|
|
233
|
+
retry_after = _extract_retry_after(exc)
|
|
234
|
+
if retry_after is None:
|
|
235
|
+
retry_after = 0.0 # rate-limit-shaped, no Retry-After: fall back to exponential schedule
|
|
236
|
+
else:
|
|
237
|
+
retry_after = None
|
|
238
|
+
is_transient = _is_transient_network_error(exc)
|
|
239
|
+
return CommitResult(
|
|
240
|
+
ok=False,
|
|
241
|
+
commit_oid=None,
|
|
242
|
+
paths=paths,
|
|
243
|
+
error=f"{type(exc).__name__}: {exc}",
|
|
244
|
+
retry_after_s=retry_after,
|
|
245
|
+
is_transient=is_transient,
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
oid = (
|
|
249
|
+
getattr(commit_info, "oid", None)
|
|
250
|
+
or getattr(commit_info, "commit_oid", None)
|
|
251
|
+
or getattr(commit_info, "commit_url", None)
|
|
252
|
+
)
|
|
253
|
+
return CommitResult(ok=True, commit_oid=oid, paths=paths)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def ensure_repo_exists(
|
|
257
|
+
repo_id: str,
|
|
258
|
+
*,
|
|
259
|
+
token: Optional[str] = None,
|
|
260
|
+
repo_type: str = "dataset",
|
|
261
|
+
private: bool = False,
|
|
262
|
+
) -> None:
|
|
263
|
+
r"""
|
|
264
|
+
**Description:**
|
|
265
|
+
Idempotent :func:`huggingface_hub.HfApi.create_repo` wrapper.
|
|
266
|
+
|
|
267
|
+
Safe to invoke before every sync; the SDK no-ops when the repo
|
|
268
|
+
already exists (using ``exist_ok=True`` where available, with a
|
|
269
|
+
fallback to swallowing "already exists" errors on older SDKs).
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
repo_id: ``"user/repo"`` on the Hub.
|
|
273
|
+
token: HF write token; falls back to ``HF_TOKEN``.
|
|
274
|
+
repo_type: ``"dataset"`` for Vulcan.
|
|
275
|
+
private: Mark the repo private at creation time.
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
None
|
|
279
|
+
"""
|
|
280
|
+
HfApi = _load_hf_api()
|
|
281
|
+
api = HfApi(token=token or os.environ.get("HF_TOKEN"))
|
|
282
|
+
try:
|
|
283
|
+
api.create_repo(
|
|
284
|
+
repo_id=repo_id,
|
|
285
|
+
repo_type=repo_type,
|
|
286
|
+
private=private,
|
|
287
|
+
exist_ok=True,
|
|
288
|
+
)
|
|
289
|
+
except TypeError:
|
|
290
|
+
# Older huggingface_hub: no exist_ok kwarg. Swallow the
|
|
291
|
+
# "already exists" path; re-raise anything else.
|
|
292
|
+
try:
|
|
293
|
+
api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private)
|
|
294
|
+
except Exception as exc: # noqa: BLE001
|
|
295
|
+
if "exists" not in str(exc).lower():
|
|
296
|
+
raise
|