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,386 @@
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
+ ML-friendly view of a Vulcan repo.
12
+
13
+ ML training jobs need a *stable* train/validation/test split that
14
+ never leaks the same Calabi-Yau geometry across splits. Vulcan rows
15
+ carry a :func:`~stringforge.vulcan.schema.geometry_id` -- a
16
+ content-addressed hash of the model -- which we use as the natural
17
+ shard key: every row sharing a ``geometry_id`` lands in exactly one
18
+ split.
19
+
20
+ This module exposes :class:`VulcanMLView`, a thin layer over
21
+ :class:`stringforge.vulcan.VulcanReader` that:
22
+
23
+ * assigns each geometry to a fixed split deterministically;
24
+ * projects rows down to a feature list and optionally pads variable-
25
+ length columns (``flux``, ``moduli_re``, ``moduli_im``, ``F_terms_*``)
26
+ to fixed-length tensors;
27
+ * hands the result back as either a :class:`pandas.DataFrame` or, when
28
+ ``datasets`` is installed, a streaming :class:`datasets.Dataset`.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ from dataclasses import dataclass
34
+ from typing import Any, Iterable, List, Mapping, Optional, Sequence, Tuple
35
+
36
+ import numpy as np
37
+ import pandas as pd
38
+
39
+ from .reader import VulcanReader
40
+ from .schema import GEOMETRY_KEYS
41
+
42
+ #: Recognised splits. Two- or three-way slicing is the standard
43
+ #: pattern; downstream code that wants a different scheme can call
44
+ #: :func:`assign_split` directly with custom fractions.
45
+ DEFAULT_SPLITS: Tuple[str, ...] = ("train", "val", "test")
46
+
47
+ #: Default split fractions (train, val, test). Sums to 1.0.
48
+ DEFAULT_FRACTIONS: Tuple[float, ...] = (0.8, 0.1, 0.1)
49
+
50
+ #: Columns whose values are variable-length lists. Pad to a fixed
51
+ #: ``max_len`` when requested.
52
+ _LIST_COLUMNS_BUILTIN: Tuple[str, ...] = (
53
+ "flux", "moduli_re", "moduli_im", "F_terms_re", "F_terms_im",
54
+ )
55
+
56
+
57
+ # ── deterministic split assignment ────────────────────────────────────────
58
+
59
+
60
+ def assign_split(
61
+ geometry_id: str,
62
+ *,
63
+ fractions: Sequence[float] = DEFAULT_FRACTIONS,
64
+ splits: Sequence[str] = DEFAULT_SPLITS,
65
+ salt: str = "",
66
+ ) -> str:
67
+ r"""
68
+ **Description:**
69
+ Map a ``geometry_id`` to one of the supplied splits
70
+ deterministically.
71
+
72
+ The function hashes ``salt + geometry_id`` to a uniform point in
73
+ ``[0, 1)`` and uses the cumulative-fraction breakpoints to pick a
74
+ split. Same ``(geometry_id, salt, fractions, splits)`` always
75
+ returns the same split.
76
+
77
+ Args:
78
+ geometry_id: The Vulcan content-addressed model identifier.
79
+ fractions: Per-split fractions. Must sum to 1.0; order must
80
+ match ``splits``.
81
+ splits: Split labels.
82
+ salt: Optional salt to perturb the assignment without changing
83
+ geometry ids -- useful when running cross-validation
84
+ folds.
85
+
86
+ Returns:
87
+ str: One of the labels in ``splits``.
88
+
89
+ Raises:
90
+ ValueError: When ``fractions`` does not match ``splits`` in
91
+ length, contains a negative value, or sums to something
92
+ other than 1.0.
93
+ """
94
+ if len(fractions) != len(splits):
95
+ raise ValueError(
96
+ f"fractions and splits length mismatch: "
97
+ f"{len(fractions)} vs {len(splits)}"
98
+ )
99
+ if any(f < 0 for f in fractions):
100
+ raise ValueError("fractions must be non-negative")
101
+ total = float(sum(fractions))
102
+ if abs(total - 1.0) > 1e-6:
103
+ raise ValueError(f"fractions must sum to 1.0; got {total}")
104
+
105
+ digest = hashlib.sha256((salt + geometry_id).encode("utf-8")).digest()
106
+ # Use 8 bytes -> uniform u in [0, 1).
107
+ n = int.from_bytes(digest[:8], "big")
108
+ u = n / float(1 << 64)
109
+ cumulative = 0.0
110
+ for name, frac in zip(splits, fractions):
111
+ cumulative += float(frac)
112
+ if u < cumulative:
113
+ return name
114
+ # Numerical fall-through.
115
+ return splits[-1]
116
+
117
+
118
+ # ── padding helpers ──────────────────────────────────────────────────────
119
+
120
+
121
+ def _pad_list_to(values: Iterable[Any], length: int, fill: Any = 0) -> np.ndarray:
122
+ r"""Right-pad with ``fill`` or silently truncate to a length-``length`` numpy array."""
123
+ arr = np.asarray(list(values))
124
+ out = np.full(length, fill, dtype=arr.dtype if arr.size else float)
125
+ n = min(length, arr.size)
126
+ if n:
127
+ out[:n] = arr[:n]
128
+ return out
129
+
130
+
131
+ def _pad_column(series: pd.Series, length: int, fill: Any = 0) -> pd.Series:
132
+ r"""Apply :func:`_pad_list_to` row-wise.
133
+
134
+ A row value may arrive as a Python list, a numpy array (after a
135
+ parquet round-trip), or ``None``. We cannot use ``lst or []``
136
+ because numpy arrays raise on truth-value checks; treat ``None``
137
+ explicitly instead.
138
+ """
139
+ def _pad(lst: Any) -> np.ndarray:
140
+ if lst is None:
141
+ lst = []
142
+ return _pad_list_to(lst, length, fill=fill)
143
+ return series.apply(_pad)
144
+
145
+
146
+ # ── feature transform ──────────────────────────────────────────────────────
147
+
148
+
149
+ @dataclass
150
+ class FeatureSpec:
151
+ r"""
152
+ **Description:**
153
+ Spec for shaping Vulcan rows into ML features.
154
+
155
+ Attributes:
156
+ features: Column projection. Optional; when ``None`` every
157
+ non-geometry column is kept.
158
+ list_max_len: Fixed length for variable-length list columns.
159
+ ``None`` leaves them as Python lists. Rows longer than
160
+ ``list_max_len`` are silently right-truncated. Callers
161
+ needing strict-length checks should pre-check
162
+ ``max(len(x) for x in series)`` against ``list_max_len``.
163
+ list_fill: Pad value when ``list_max_len`` is set.
164
+ keep_geometry_id: Whether to retain ``geometry_id`` in the
165
+ returned DataFrame -- typically wanted for monitoring
166
+ held-out performance per geometry.
167
+ """
168
+ features: Optional[Sequence[str]] = None
169
+ list_max_len: Optional[int] = None
170
+ list_fill: Any = 0
171
+ keep_geometry_id: bool = True
172
+
173
+
174
+ def shape_features(df: pd.DataFrame, spec: FeatureSpec) -> pd.DataFrame:
175
+ r"""
176
+ **Description:**
177
+ Apply a :class:`FeatureSpec` to a Vulcan-shaped DataFrame.
178
+
179
+ The returned DataFrame contains exactly the projected feature
180
+ columns (plus ``geometry_id`` when ``spec.keep_geometry_id`` is
181
+ True) with list columns padded to ``spec.list_max_len`` where
182
+ applicable.
183
+
184
+ Args:
185
+ df: Source rows (typically the output of
186
+ :meth:`stringforge.vulcan.VulcanReader.query`).
187
+ spec: The feature spec.
188
+
189
+ Returns:
190
+ pd.DataFrame: Shaped feature table.
191
+
192
+ Raises:
193
+ KeyError: When ``spec.features`` references a column missing
194
+ from ``df``.
195
+ """
196
+ if spec.features is not None:
197
+ missing = [c for c in spec.features if c not in df.columns]
198
+ if missing:
199
+ raise KeyError(f"feature spec references missing columns: {missing}")
200
+ out = df[list(spec.features)].copy()
201
+ else:
202
+ drop = list(GEOMETRY_KEYS) + ["run_id", "geometry_id", "created_at"]
203
+ out = df.drop(columns=[c for c in drop if c in df.columns]).copy()
204
+
205
+ if spec.list_max_len is not None:
206
+ for col in _LIST_COLUMNS_BUILTIN:
207
+ if col in out.columns:
208
+ out[col] = _pad_column(out[col], spec.list_max_len,
209
+ fill=spec.list_fill)
210
+
211
+ if spec.keep_geometry_id and "geometry_id" in df.columns:
212
+ if "geometry_id" not in out.columns:
213
+ out["geometry_id"] = df["geometry_id"].values
214
+
215
+ return out.reset_index(drop=True)
216
+
217
+
218
+ # ── ML view ──────────────────────────────────────────────────────────────
219
+
220
+
221
+ class VulcanMLView:
222
+ r"""
223
+ **Description:**
224
+ Train/val/test view of a Vulcan source.
225
+
226
+ Wraps a :class:`stringforge.vulcan.VulcanReader` with deterministic,
227
+ geometry-disjoint splits and a configurable
228
+ :class:`FeatureSpec`. Two consumption paths:
229
+
230
+ * :meth:`as_dataframe` -- materialise a pandas DataFrame for
231
+ light workflows.
232
+ * :meth:`as_hf_dataset` -- materialise a streaming
233
+ :class:`datasets.Dataset` (requires the ``datasets`` package).
234
+
235
+ Args:
236
+ reader: Source reader.
237
+ fractions: Per-split fractions (must sum to 1.0).
238
+ splits: Split labels.
239
+ salt: Optional salt for cross-validation folds.
240
+ feature_spec: Default :class:`FeatureSpec`; can be overridden
241
+ per call.
242
+ """
243
+
244
+ def __init__(
245
+ self,
246
+ reader: VulcanReader,
247
+ *,
248
+ fractions: Sequence[float] = DEFAULT_FRACTIONS,
249
+ splits: Sequence[str] = DEFAULT_SPLITS,
250
+ salt: str = "",
251
+ feature_spec: Optional[FeatureSpec] = None,
252
+ ) -> None:
253
+ self.reader = reader
254
+ self.fractions = tuple(fractions)
255
+ self.splits = tuple(splits)
256
+ self.salt = str(salt)
257
+ self.feature_spec = feature_spec or FeatureSpec()
258
+
259
+ def split_of(self, geometry_id: str) -> str:
260
+ r"""
261
+ **Description:**
262
+ Return the split label assigned to a specific geometry.
263
+
264
+ Args:
265
+ geometry_id: The model identifier to look up.
266
+
267
+ Returns:
268
+ str: One of :attr:`splits`.
269
+ """
270
+ return assign_split(
271
+ geometry_id,
272
+ fractions=self.fractions,
273
+ splits=self.splits,
274
+ salt=self.salt,
275
+ )
276
+
277
+ def split_assignments(self) -> pd.DataFrame:
278
+ r"""
279
+ **Description:**
280
+ Return a two-column table of ``(geometry_id, split)`` for
281
+ every geometry the reader can see.
282
+
283
+ Returns:
284
+ pd.DataFrame: One row per distinct geometry.
285
+ """
286
+ cat = self.reader.catalog()
287
+ unique = sorted(set(cat["geometry_id"].dropna().unique()))
288
+ return pd.DataFrame({
289
+ "geometry_id": unique,
290
+ "split": [self.split_of(g) for g in unique],
291
+ })
292
+
293
+ def as_dataframe(
294
+ self,
295
+ split: str,
296
+ *,
297
+ feature_spec: Optional[FeatureSpec] = None,
298
+ query_filters: Optional[Mapping[str, Any]] = None,
299
+ ) -> pd.DataFrame:
300
+ r"""
301
+ **Description:**
302
+ Materialise the rows of a specific split as a pandas
303
+ DataFrame.
304
+
305
+ The split is determined by hashing ``geometry_id``; rows from
306
+ the same geometry are guaranteed to land in the same split.
307
+
308
+ Args:
309
+ split: Label to materialise (must be in :attr:`splits`).
310
+ feature_spec: Override the default feature spec for this
311
+ call.
312
+ query_filters: Optional extra filters forwarded to
313
+ :meth:`VulcanReader.query` to scope the input rows.
314
+
315
+ Returns:
316
+ pd.DataFrame: The shaped feature table.
317
+
318
+ Raises:
319
+ ValueError: When ``split`` is not a recognised label.
320
+ """
321
+ if split not in self.splits:
322
+ raise ValueError(
323
+ f"unknown split {split!r}; expected one of {self.splits}"
324
+ )
325
+ spec = feature_spec or self.feature_spec
326
+ df = self.reader.query(**(query_filters or {}))
327
+ if df.empty:
328
+ return df
329
+ df = df[df["geometry_id"].apply(self.split_of) == split]
330
+ if df.empty:
331
+ return df
332
+ return shape_features(df, spec)
333
+
334
+ def as_hf_dataset(
335
+ self,
336
+ split: str,
337
+ *,
338
+ feature_spec: Optional[FeatureSpec] = None,
339
+ query_filters: Optional[Mapping[str, Any]] = None,
340
+ ) -> "Any":
341
+ r"""
342
+ **Description:**
343
+ Materialise the rows of a specific split as a HuggingFace
344
+ :class:`datasets.Dataset` for streaming consumption by an ML
345
+ framework.
346
+
347
+ ``datasets`` is an optional dependency; this method imports it
348
+ lazily and raises a clear error when it is not installed.
349
+
350
+ Args:
351
+ split: Label to materialise.
352
+ feature_spec: Override the default feature spec.
353
+ query_filters: Optional extra :class:`VulcanReader.query`
354
+ filters.
355
+
356
+ Returns:
357
+ datasets.Dataset: A HuggingFace dataset.
358
+
359
+ Raises:
360
+ ImportError: When the optional ``datasets`` package is
361
+ not installed.
362
+ """
363
+ try:
364
+ from datasets import Dataset # type: ignore
365
+ except ImportError as exc:
366
+ raise ImportError(
367
+ "VulcanMLView.as_hf_dataset requires the optional "
368
+ "`datasets` package. Install it with "
369
+ "`pip install datasets`."
370
+ ) from exc
371
+ df = self.as_dataframe(
372
+ split,
373
+ feature_spec=feature_spec,
374
+ query_filters=query_filters,
375
+ )
376
+ return Dataset.from_pandas(df, preserve_index=False)
377
+
378
+
379
+ __all__ = (
380
+ "VulcanMLView",
381
+ "FeatureSpec",
382
+ "assign_split",
383
+ "shape_features",
384
+ "DEFAULT_SPLITS",
385
+ "DEFAULT_FRACTIONS",
386
+ )
@@ -0,0 +1,285 @@
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
+ Rolling-window commit-rate budget for the Vulcan sync tier.
12
+
13
+ HuggingFace caps direct commits at **100 / hour per repo**. Vulcan's
14
+ sync tier maintains a rolling-window counter (default ceiling: 90
15
+ commits/hour, leaving a 10-commit safety margin) and refuses to
16
+ ``create_commit`` while the window is full. The budget is persisted
17
+ to disk so multiple sync invocations (cron jobs, daemon restarts)
18
+ share the same accounting.
19
+
20
+ This module also exposes :func:`sleep_with_backoff`, an exponential-
21
+ backoff helper that honours ``Retry-After`` headers on HTTP 429 / 503
22
+ responses (whichever the sync tier classifies as rate-limit-like).
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import threading
29
+ import time
30
+ from collections import deque
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import Callable, Deque, Optional
34
+
35
+ #: Hard ceiling enforced by HuggingFace. Our default budget sits a
36
+ #: safety margin below this.
37
+ HF_COMMITS_PER_HOUR_CAP: int = 100
38
+
39
+ #: Default budget consumed by a single sync run. 10-commit margin
40
+ #: below the HF cap leaves head-room for ad-hoc operations the user
41
+ #: may perform manually (e.g. README edits).
42
+ DEFAULT_BUDGET: int = 90
43
+
44
+ #: Default window over which the budget applies (seconds).
45
+ DEFAULT_WINDOW_S: float = 3600.0
46
+
47
+ #: Initial backoff for the exponential-backoff helper, in seconds.
48
+ INITIAL_BACKOFF_S: float = 1.0
49
+
50
+ #: Cap on a single backoff sleep. Five minutes is enough to ride out
51
+ #: most transient HF outages; anything longer should error.
52
+ MAX_BACKOFF_S: float = 300.0
53
+
54
+
55
+ @dataclass
56
+ class CommitWindow:
57
+ r"""
58
+ Rolling-window record of recent commit timestamps for a single
59
+ repo. Persisted as a JSON file under the staging directory.
60
+
61
+ Attributes:
62
+ budget: Maximum commits permitted within ``window_s``.
63
+ window_s: Window length in seconds.
64
+ timestamps: Monotonic-clock timestamps of commits recorded so
65
+ far. Older entries are pruned lazily on every
66
+ :meth:`reserve` call.
67
+ """
68
+ budget: int = DEFAULT_BUDGET
69
+ window_s: float = DEFAULT_WINDOW_S
70
+ timestamps: Deque[float] = field(default_factory=deque)
71
+
72
+ def _prune(self, now: float) -> None:
73
+ cutoff = now - self.window_s
74
+ while self.timestamps and self.timestamps[0] < cutoff:
75
+ self.timestamps.popleft()
76
+
77
+ def n_recent(self, now: Optional[float] = None) -> int:
78
+ r"""
79
+ **Description:**
80
+ Count commits inside the current rolling window.
81
+
82
+ Args:
83
+ now: Wall-clock override for tests. Defaults to
84
+ :func:`time.time`.
85
+
86
+ Returns:
87
+ int: Number of timestamps within the last ``window_s``
88
+ seconds.
89
+ """
90
+ if now is None:
91
+ now = time.time()
92
+ self._prune(now)
93
+ return len(self.timestamps)
94
+
95
+ def remaining(self, now: Optional[float] = None) -> int:
96
+ r"""
97
+ **Description:**
98
+ Compute the number of commits still available within the
99
+ current rolling window.
100
+
101
+ Args:
102
+ now: Wall-clock override for tests.
103
+
104
+ Returns:
105
+ int: Non-negative slot count.
106
+ """
107
+ return max(0, self.budget - self.n_recent(now=now))
108
+
109
+ def seconds_until_slot(self, now: Optional[float] = None) -> float:
110
+ r"""
111
+ **Description:**
112
+ Compute the wall-clock delay before a new slot opens.
113
+
114
+ Args:
115
+ now: Wall-clock override for tests.
116
+
117
+ Returns:
118
+ float: ``0.0`` if a slot is currently free; otherwise the
119
+ seconds until the oldest recorded commit ages out of the
120
+ window.
121
+ """
122
+ if now is None:
123
+ now = time.time()
124
+ self._prune(now)
125
+ if len(self.timestamps) < self.budget:
126
+ return 0.0
127
+ oldest = self.timestamps[0]
128
+ return max(0.0, (oldest + self.window_s) - now)
129
+
130
+ def reserve(self, now: Optional[float] = None) -> bool:
131
+ r"""
132
+ **Description:**
133
+ Attempt to record a new commit at ``now``.
134
+
135
+ Args:
136
+ now: Wall-clock override for tests.
137
+
138
+ Returns:
139
+ bool: ``True`` if the slot was recorded; ``False`` if the
140
+ budget is exhausted.
141
+ """
142
+ if now is None:
143
+ now = time.time()
144
+ self._prune(now)
145
+ if len(self.timestamps) >= self.budget:
146
+ return False
147
+ self.timestamps.append(now)
148
+ return True
149
+
150
+ # ── persistence ────────────────────────────────────────────────
151
+
152
+ def to_dict(self) -> dict:
153
+ return {
154
+ "budget": int(self.budget),
155
+ "window_s": float(self.window_s),
156
+ "timestamps": [float(t) for t in self.timestamps],
157
+ }
158
+
159
+ @classmethod
160
+ def from_dict(cls, data: dict) -> "CommitWindow":
161
+ return cls(
162
+ budget=int(data.get("budget", DEFAULT_BUDGET)),
163
+ window_s=float(data.get("window_s", DEFAULT_WINDOW_S)),
164
+ timestamps=deque(float(t) for t in data.get("timestamps", [])),
165
+ )
166
+
167
+
168
+ class CommitBudget:
169
+ r"""
170
+ Process-safe wrapper around a :class:`CommitWindow` persisted to
171
+ disk. Multiple processes calling ``reserve()`` against the same
172
+ state file see a consistent view modulo flush latency. Within a
173
+ single process the wrapper is thread-safe.
174
+
175
+ Note: this is *advisory* rate limiting at the process boundary.
176
+ The state file (``{state_path}``) is written atomically per-process,
177
+ but two processes hitting the same file concurrently can race; the
178
+ budget can therefore overshoot by up to (number of concurrent
179
+ writers - 1) commits per window. The cluster best-practice (see
180
+ section "Best practices for cluster runs" in the docs) is to run a
181
+ SINGLE head-node sync process, which makes this advisory-only
182
+ guarantee tight in practice.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ state_path: Path,
188
+ *,
189
+ budget: int = DEFAULT_BUDGET,
190
+ window_s: float = DEFAULT_WINDOW_S,
191
+ ) -> None:
192
+ self.state_path = Path(state_path)
193
+ self._lock = threading.Lock()
194
+ self._default_budget = int(budget)
195
+ self._default_window_s = float(window_s)
196
+
197
+ def _load(self) -> CommitWindow:
198
+ if self.state_path.is_file():
199
+ try:
200
+ data = json.loads(self.state_path.read_text())
201
+ win = CommitWindow.from_dict(data)
202
+ # Allow programmatic override of budget without losing
203
+ # the recorded history.
204
+ win.budget = self._default_budget
205
+ win.window_s = self._default_window_s
206
+ return win
207
+ except (json.JSONDecodeError, OSError):
208
+ pass
209
+ return CommitWindow(
210
+ budget=self._default_budget, window_s=self._default_window_s,
211
+ )
212
+
213
+ def _save(self, win: CommitWindow) -> None:
214
+ self.state_path.parent.mkdir(parents=True, exist_ok=True)
215
+ tmp = self.state_path.with_suffix(self.state_path.suffix + ".tmp")
216
+ tmp.write_text(json.dumps(win.to_dict(), sort_keys=True))
217
+ os.replace(tmp, self.state_path)
218
+
219
+ def remaining(self, now: Optional[float] = None) -> int:
220
+ with self._lock:
221
+ win = self._load()
222
+ return win.remaining(now=now)
223
+
224
+ def seconds_until_slot(self, now: Optional[float] = None) -> float:
225
+ with self._lock:
226
+ win = self._load()
227
+ return win.seconds_until_slot(now=now)
228
+
229
+ def reserve(self, now: Optional[float] = None) -> bool:
230
+ with self._lock:
231
+ win = self._load()
232
+ ok = win.reserve(now=now)
233
+ if ok:
234
+ self._save(win)
235
+ return ok
236
+
237
+
238
+ def sleep_with_backoff(
239
+ attempt: int,
240
+ *,
241
+ retry_after_s: Optional[float] = None,
242
+ initial: float = INITIAL_BACKOFF_S,
243
+ cap: float = MAX_BACKOFF_S,
244
+ sleep_fn: Callable[[float], None] = time.sleep,
245
+ ) -> float:
246
+ r"""
247
+ Sleep for an exponentially-backed-off interval, honouring
248
+ ``Retry-After`` when provided.
249
+
250
+ Args:
251
+ attempt: 0 for the first retry, 1 for the next, ...
252
+ retry_after_s: Server-reported retry-after (HF returns this on
253
+ 429). When supplied, the sleep duration is the maximum of
254
+ this and the exponential value -- never less than what the
255
+ server asked for.
256
+ initial: Initial backoff (seconds).
257
+ cap: Maximum sleep duration (seconds).
258
+ sleep_fn: Override for tests.
259
+
260
+ Returns:
261
+ Actual sleep duration in seconds.
262
+ """
263
+ if attempt < 0:
264
+ raise ValueError("attempt must be >= 0")
265
+ base = min(cap, initial * (2 ** attempt))
266
+ if retry_after_s is not None:
267
+ base = max(base, float(retry_after_s))
268
+ sleep_fn(base)
269
+ return base
270
+
271
+
272
+ def parse_retry_after(value: Optional[str]) -> Optional[float]:
273
+ r"""
274
+ Parse an HTTP ``Retry-After`` header value into seconds.
275
+
276
+ The header may be either an integer (seconds) or an HTTP-date.
277
+ Only the integer form is honoured here -- HF returns seconds.
278
+ Unparseable values return ``None``.
279
+ """
280
+ if value is None:
281
+ return None
282
+ try:
283
+ return float(value)
284
+ except (TypeError, ValueError):
285
+ return None