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,434 @@
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
+ Worker-side shard writer for Vulcan.
12
+
13
+ Worker code never touches HuggingFace. :func:`write_shard` lands a
14
+ validated parquet file inside ``{staging_dir}/pending/`` together with
15
+ a per-file ``.meta.json`` sidecar carrying the geometry, solver, and
16
+ provenance dicts. The sync tier (:mod:`stringforge.vulcan.sync`)
17
+ later batches these into HuggingFace commits.
18
+
19
+ Atomicity: each of the parquet body and the JSON sidecar is staged as a .tmp file and os.replace-d into place, so neither file is ever observed half-written. The two os.replace calls are sequential, not atomic as a pair: a crash between them can leave a parquet without a sidecar. :func:`list_pending` silently skips such orphan parquets, so the sync tier never uploads a half-pair, and a re-run of the same write rebuilds the missing sidecar.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import shutil
26
+ import uuid
27
+ from dataclasses import dataclass
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+ from typing import Any, Mapping, Optional
31
+
32
+ import pandas as pd
33
+ import pyarrow as pa
34
+ import pyarrow.parquet as pq
35
+
36
+ from .schema import (
37
+ GEOMETRY_KEYS,
38
+ GEOMETRY_KEY_SENTINEL,
39
+ REQUIRED_COLUMNS,
40
+ SCHEMA_VERSION,
41
+ geometry_id as _geometry_id,
42
+ is_safe_run_id,
43
+ pyarrow_schema,
44
+ shard_relpath,
45
+ validate_schema,
46
+ )
47
+
48
+ #: Parquet kv-metadata key under which we stash the full provenance
49
+ #: blob. Mirrors the pattern at vacua_writer.py:1714-1727.
50
+ PROVENANCE_METADATA_KEY: bytes = b"stringforge.vulcan.provenance"
51
+ #: Parquet kv-metadata key carrying the schema version.
52
+ SCHEMA_VERSION_METADATA_KEY: bytes = b"schema_version"
53
+
54
+ PENDING_DIRNAME: str = "pending"
55
+ SYNCED_DIRNAME: str = "synced"
56
+ FAILED_DIRNAME: str = "failed"
57
+
58
+
59
+ @dataclass
60
+ class StagedShard:
61
+ r"""
62
+ Reference to a freshly staged shard on local disk.
63
+
64
+ Attributes:
65
+ run_id: The run identifier carried on every row.
66
+ parquet_path: Absolute path to the staged parquet file.
67
+ sidecar_path: Absolute path to the per-file ``.meta.json``.
68
+ path_in_repo: Canonical HF-repo-relative target path.
69
+ n_rows: Number of vacuum rows written.
70
+ """
71
+ run_id: str
72
+ parquet_path: Path
73
+ sidecar_path: Path
74
+ path_in_repo: str
75
+ n_rows: int
76
+
77
+
78
+ def ensure_staging_layout(staging_dir: Path) -> Path:
79
+ r"""
80
+ **Description:**
81
+ Ensure the Vulcan staging directory carries the canonical
82
+ ``pending/``, ``synced/``, and ``failed/`` subdirectories.
83
+
84
+ Idempotent: safe to call before every :func:`write_shard` or
85
+ :func:`~stringforge.vulcan.sync.sync_pending` invocation.
86
+
87
+ Args:
88
+ staging_dir: Root staging directory.
89
+
90
+ Returns:
91
+ Path: The resolved staging root (with the three subdirectories
92
+ guaranteed to exist).
93
+ """
94
+ root = Path(staging_dir).resolve()
95
+ for sub in (PENDING_DIRNAME, SYNCED_DIRNAME, FAILED_DIRNAME):
96
+ (root / sub).mkdir(parents=True, exist_ok=True)
97
+ return root
98
+
99
+
100
+ def _coerce_dataframe(
101
+ df: pd.DataFrame,
102
+ *,
103
+ run_id: str,
104
+ geometry: Mapping[str, Any],
105
+ tadpole_charge: Optional[int],
106
+ solver: Optional[Mapping[str, Any]] = None,
107
+ provenance: Optional[Mapping[str, Any]] = None,
108
+ ) -> pd.DataFrame:
109
+ r"""
110
+ Fill in the production-tier required columns that callers shouldn't
111
+ have to set by hand.
112
+
113
+ ``run_id``, ``geometry_id``, and the geometry-key columns overwrite
114
+ any existing column with the same name -- the writer is the
115
+ authority on identity, not the caller. ``created_at`` is filled in
116
+ only if absent. Selected solver/provenance fields are denormalised
117
+ into row-level columns when the caller has not already supplied them.
118
+ """
119
+ out = df.copy()
120
+ out["run_id"] = run_id
121
+ out["geometry_id"] = _geometry_id(geometry)
122
+
123
+ if "created_at" not in out.columns:
124
+ out["created_at"] = pd.Timestamp(datetime.now(tz=timezone.utc))
125
+ else:
126
+ out["created_at"] = pd.to_datetime(out["created_at"], utc=True)
127
+
128
+ # Denormalise geometry keys -- writer is authoritative, mirroring run_id/geometry_id.
129
+ for key in GEOMETRY_KEYS:
130
+ out[key] = int(geometry.get(key, GEOMETRY_KEY_SENTINEL))
131
+
132
+ if tadpole_charge is not None and "tadpole_charge" not in out.columns:
133
+ out["tadpole_charge"] = int(tadpole_charge)
134
+
135
+ # Denormalise solver / provenance entries into row-level columns
136
+ # (only when the caller did not already supply the column and the
137
+ # source value is non-None).
138
+ if solver is not None:
139
+ if "solver_name" not in out.columns and solver.get("name") is not None:
140
+ out["solver_name"] = solver["name"]
141
+ if "solver_config_hash" not in out.columns and solver.get("config_hash") is not None:
142
+ out["solver_config_hash"] = solver["config_hash"]
143
+ if provenance is not None:
144
+ if "git_sha" not in out.columns and provenance.get("git_sha") is not None:
145
+ out["git_sha"] = provenance["git_sha"]
146
+ if "seed" not in out.columns and provenance.get("seed") is not None:
147
+ out["seed"] = provenance["seed"]
148
+ if "wall_clock_s" not in out.columns and provenance.get("wall_clock_s") is not None:
149
+ out["wall_clock_s"] = provenance["wall_clock_s"]
150
+
151
+ return out
152
+
153
+
154
+ def _arrow_table(df: pd.DataFrame, provenance: Mapping[str, Any]) -> pa.Table:
155
+ r"""
156
+ **Description:**
157
+ Convert ``df`` to a pyarrow Table that conforms to the canonical
158
+ Vulcan schema, attaching schema-version and provenance metadata.
159
+
160
+ The schema is *intersected* with ``df.columns`` so callers may
161
+ omit optional columns -- only :data:`REQUIRED_COLUMNS` must be
162
+ present (and :func:`validate_schema` has already checked that).
163
+ Extension columns -- anything ``df`` carries that the canonical
164
+ schema does not name -- are inferred by Arrow from the underlying
165
+ numpy/pandas values rather than from the pandas dtype, so
166
+ ``object``-dtype columns (lists, strings, ``Decimal``, ...) round-trip
167
+ correctly.
168
+
169
+ Args:
170
+ df: Coerced DataFrame whose required columns are all populated.
171
+ provenance: JSON-serialisable provenance dict to embed as
172
+ parquet kv-metadata under
173
+ :data:`PROVENANCE_METADATA_KEY`.
174
+
175
+ Returns:
176
+ pa.Table: An Arrow table ready for :func:`pyarrow.parquet.write_table`.
177
+ """
178
+ canonical = pyarrow_schema()
179
+ known = {f.name for f in canonical}
180
+
181
+ # Build the canonical-column slice first so we get the correct
182
+ # logical types (`list<int32>` for `flux`, timestamp[us, tz=UTC]
183
+ # for `created_at`, etc.) rather than whatever Arrow would infer.
184
+ column_arrays: dict[str, pa.Array] = {}
185
+ selected_fields: list[pa.Field] = []
186
+ for field in canonical:
187
+ if field.name not in df.columns:
188
+ continue
189
+ try:
190
+ column_arrays[field.name] = pa.array(df[field.name].to_list(), type=field.type)
191
+ except (pa.ArrowInvalid, pa.ArrowTypeError):
192
+ # Surface this with the field name; the caller's df has a
193
+ # value that doesn't fit the canonical type.
194
+ raise ValueError(
195
+ f"column {field.name!r} cannot be cast to canonical type "
196
+ f"{field.type}; check the underlying values"
197
+ )
198
+ selected_fields.append(field)
199
+
200
+ # Extension columns: let Arrow infer the type from the values. We
201
+ # use ``pa.array`` on the column's Python list (not the numpy dtype)
202
+ # because pandas object dtype loses the per-element type info that
203
+ # numpy would otherwise paper over with ``object``.
204
+ extra_fields: list[pa.Field] = []
205
+ for name in df.columns:
206
+ if name in known:
207
+ continue
208
+ arr = pa.array(df[name].to_list())
209
+ extra_fields.append(pa.field(name, arr.type))
210
+ column_arrays[name] = arr
211
+
212
+ schema = pa.schema(selected_fields + extra_fields).with_metadata({
213
+ SCHEMA_VERSION_METADATA_KEY: str(SCHEMA_VERSION).encode("ascii"),
214
+ PROVENANCE_METADATA_KEY: json.dumps(provenance, sort_keys=True, default=str).encode("utf-8"),
215
+ })
216
+ ordered = [column_arrays[f.name] for f in schema]
217
+ return pa.Table.from_arrays(ordered, schema=schema)
218
+
219
+
220
+ def write_shard(
221
+ df: pd.DataFrame,
222
+ *,
223
+ staging_dir: Path,
224
+ run_id: str,
225
+ geometry: Mapping[str, Any],
226
+ tadpole_charge: Optional[int] = None,
227
+ solver: Optional[Mapping[str, Any]] = None,
228
+ provenance: Optional[Mapping[str, Any]] = None,
229
+ bucket_bits: int = 4,
230
+ ) -> StagedShard:
231
+ r"""
232
+ **Description:**
233
+ Write a single vacuum-batch parquet shard to ``staging_dir/pending/``.
234
+
235
+ The writer is the authority on identity: ``run_id``,
236
+ ``geometry_id``, and the geometry-key columns are unconditionally
237
+ overwritten here, regardless of any per-row values the caller may
238
+ have supplied. ``tadpole_charge`` and ``created_at``, by contrast,
239
+ are filled in only when absent from ``df``. The default ``run_id``
240
+ substitution dict used by the calling Vulcan handle is the union of
241
+ ``geometry``, ``solver['name']`` (when supplied), ``provenance['seed']``
242
+ (when supplied), and ``extra_kwargs``.
243
+
244
+ Schema validation runs after this coercion --
245
+ :func:`~stringforge.vulcan.schema.validate_schema` must succeed
246
+ before any I/O happens, so a bad batch never leaves a half-written
247
+ shard behind.
248
+
249
+ The on-disk write is atomic per-file -- not per-pair: each of the
250
+ parquet body and the JSON sidecar is staged as a ``.tmp`` file and
251
+ ``os.replace``-d into place, but the two replacements are sequential.
252
+ A crash between them can leave a parquet without a sidecar;
253
+ :func:`list_pending` silently skips such orphans, so the sync tier
254
+ never uploads a half-pair, and a re-run of the same write rebuilds
255
+ the missing sidecar. The ``.tmp`` suffix carries a per-process,
256
+ per-call nonce so concurrent writers on the same
257
+ ``(geometry, run_id)`` do not corrupt each other's staged files.
258
+
259
+ Args:
260
+ df: Per-vacuum DataFrame. Must carry the vault-floor columns
261
+ (see :data:`~stringforge.vulcan.schema.REQUIRED_COLUMNS`).
262
+ staging_dir: Root staging directory. Subdirs are created on
263
+ demand via :func:`ensure_staging_layout`.
264
+ run_id: Identifier carried on every row. Must satisfy
265
+ :func:`~stringforge.vulcan.schema.is_safe_run_id`.
266
+ geometry: ``{h11, h12, ks_id, triang_id, conifold_id, cicy_id}``
267
+ mapping. h11, h12 are interpreted in mirror (jaxvacua /
268
+ lcs_tree) convention. Missing keys are filled with
269
+ :data:`~stringforge.vulcan.schema.GEOMETRY_KEY_SENTINEL`,
270
+ but at least one key must be set to a non-sentinel value.
271
+ tadpole_charge: ``N_flux`` for the batch. Required unless
272
+ already present on ``df`` as a column.
273
+ solver: Optional ``{name, config_hash, ...}`` mapping; embedded
274
+ in the parquet kv-metadata blob.
275
+ provenance: Optional ``{git_sha, seed, wall_clock_s, ...}``
276
+ mapping; embedded alongside ``solver`` in the same blob.
277
+ bucket_bits: Width of the bucket prefix in the HF path layout.
278
+
279
+ Returns:
280
+ StagedShard: Reference to the on-disk parquet + sidecar pair
281
+ and the canonical HF-repo-relative path.
282
+
283
+ Raises:
284
+ ValueError: ``run_id`` is not slug-safe, ``df`` is empty,
285
+ ``geometry`` carries no non-sentinel keys, or
286
+ :func:`~stringforge.vulcan.schema.validate_schema` rejects
287
+ the coerced DataFrame.
288
+ """
289
+ if not is_safe_run_id(run_id):
290
+ raise ValueError(
291
+ f"run_id is not slug-safe: {run_id!r}. "
292
+ f"Must match LABEL_SLUG_RE."
293
+ )
294
+ if len(df) == 0:
295
+ raise ValueError("Vulcan.write: cannot stage an empty DataFrame")
296
+
297
+ provided = {k: geometry.get(k) for k in GEOMETRY_KEYS}
298
+ if all(v is None or int(v) == GEOMETRY_KEY_SENTINEL for v in provided.values()):
299
+ raise ValueError(
300
+ "Vulcan.write: geometry must carry at least one of "
301
+ f"{GEOMETRY_KEYS} set to a non-sentinel value; got {dict(geometry)!r}"
302
+ )
303
+
304
+ root = ensure_staging_layout(Path(staging_dir))
305
+ pending = root / PENDING_DIRNAME
306
+
307
+ coerced = _coerce_dataframe(
308
+ df, run_id=run_id, geometry=geometry, tadpole_charge=tadpole_charge,
309
+ solver=solver, provenance=provenance,
310
+ )
311
+ # Extension columns are a designed writer feature, so don't warn on
312
+ # them here (validate_schema still aggregates real schema problems).
313
+ validate_schema(coerced, warn_unknown=False)
314
+
315
+ provenance_blob: dict[str, Any] = {
316
+ "schema_version": SCHEMA_VERSION,
317
+ "run_id": run_id,
318
+ "geometry": {k: int(geometry.get(k, GEOMETRY_KEY_SENTINEL)) for k in GEOMETRY_KEYS},
319
+ "solver": dict(solver) if solver else {},
320
+ "provenance": dict(provenance) if provenance else {},
321
+ "n_rows": int(len(coerced)),
322
+ }
323
+ table = _arrow_table(coerced, provenance=provenance_blob)
324
+
325
+ # Path in the HF repo. We also use this (slashes -> "__") as the
326
+ # local filename so two shards with identical (run_id, geometry)
327
+ # collide at the same local path -- deliberate: a retry of the
328
+ # same call overwrites cleanly.
329
+ path_in_repo = shard_relpath(geometry, run_id, bucket_bits=bucket_bits)
330
+ local_name = path_in_repo.replace("/", "__")
331
+ parquet_path = pending / local_name
332
+ sidecar_path = pending / (local_name + ".meta.json")
333
+ nonce = f".{os.getpid()}.{uuid.uuid4().hex}.tmp"
334
+ tmp_parquet = parquet_path.with_suffix(parquet_path.suffix + nonce)
335
+ tmp_sidecar = sidecar_path.with_suffix(sidecar_path.suffix + nonce)
336
+
337
+ pq.write_table(table, tmp_parquet)
338
+ tmp_sidecar.write_text(json.dumps({
339
+ "path_in_repo": path_in_repo,
340
+ "run_id": run_id,
341
+ "n_rows": int(len(coerced)),
342
+ "provenance": provenance_blob,
343
+ }, indent=2, sort_keys=True, default=str))
344
+
345
+ os.replace(tmp_parquet, parquet_path)
346
+ os.replace(tmp_sidecar, sidecar_path)
347
+
348
+ return StagedShard(
349
+ run_id=run_id,
350
+ parquet_path=parquet_path,
351
+ sidecar_path=sidecar_path,
352
+ path_in_repo=path_in_repo,
353
+ n_rows=int(len(coerced)),
354
+ )
355
+
356
+
357
+ def list_pending(staging_dir: Path) -> list[StagedShard]:
358
+ r"""
359
+ **Description:**
360
+ Enumerate currently-staged shards awaiting sync.
361
+
362
+ Each ``.parquet`` in ``pending/`` is paired with its
363
+ ``.parquet.meta.json`` sidecar. Shards without a sidecar (e.g.
364
+ after a crashed write where the parquet flushed but the sidecar
365
+ did not) are skipped silently -- the next worker call recreates
366
+ them.
367
+
368
+ Args:
369
+ staging_dir: Root staging directory.
370
+
371
+ Returns:
372
+ list[StagedShard]: All complete shard records found in
373
+ ``pending/``, sorted by filename for deterministic ordering.
374
+ """
375
+ root = Path(staging_dir).resolve()
376
+ pending = root / PENDING_DIRNAME
377
+ if not pending.is_dir():
378
+ return []
379
+ out: list[StagedShard] = []
380
+ for parquet_path in sorted(pending.glob("*.parquet")):
381
+ sidecar = parquet_path.with_suffix(parquet_path.suffix + ".meta.json")
382
+ if not sidecar.is_file():
383
+ continue
384
+ try:
385
+ meta = json.loads(sidecar.read_text())
386
+ except json.JSONDecodeError:
387
+ continue
388
+ out.append(StagedShard(
389
+ run_id=meta["run_id"],
390
+ parquet_path=parquet_path,
391
+ sidecar_path=sidecar,
392
+ path_in_repo=meta["path_in_repo"],
393
+ n_rows=int(meta.get("n_rows", 0)),
394
+ ))
395
+ return out
396
+
397
+
398
+ def move_to(shard: StagedShard, staging_dir: Path, target: str) -> StagedShard:
399
+ r"""
400
+ **Description:**
401
+ Move a staged shard's ``(parquet, sidecar)`` pair into a sibling
402
+ subdirectory.
403
+
404
+ The two files are moved sequentially, not as an atomic pair: a
405
+ crash between the two ``shutil.move`` calls can leave the parquet
406
+ in the destination directory while the sidecar remains in the
407
+ source. Orphan recovery is the responsibility of
408
+ :func:`list_pending` (which skips parquets without a sidecar) and
409
+ of a future ``prune_orphans`` helper.
410
+
411
+ Args:
412
+ shard: The shard reference returned by :func:`write_shard`.
413
+ staging_dir: Root staging directory.
414
+ target: Target subdirectory name -- typically
415
+ :data:`SYNCED_DIRNAME` or :data:`FAILED_DIRNAME`.
416
+
417
+ Returns:
418
+ StagedShard: A new shard record whose paths point at the
419
+ post-move locations.
420
+ """
421
+ root = ensure_staging_layout(Path(staging_dir))
422
+ dest_dir = root / target
423
+ dest_parquet = dest_dir / shard.parquet_path.name
424
+ dest_sidecar = dest_dir / shard.sidecar_path.name
425
+ # shutil.move falls back to copy+remove across filesystems.
426
+ shutil.move(str(shard.parquet_path), str(dest_parquet))
427
+ shutil.move(str(shard.sidecar_path), str(dest_sidecar))
428
+ return StagedShard(
429
+ run_id=shard.run_id,
430
+ parquet_path=dest_parquet,
431
+ sidecar_path=dest_sidecar,
432
+ path_in_repo=shard.path_in_repo,
433
+ n_rows=shard.n_rows,
434
+ )