lekdan commited on
Commit
0807f19
·
verified ·
1 Parent(s): ebf6e45

Reject reused update batch IDs

Browse files
README.md CHANGED
@@ -250,6 +250,10 @@ The latest-view rebuild is per-table and internally parallel over source
250
  Parquet files. Set `LATEST_REBUILD_WORKERS` to tune that fan-out for the
251
  machine's RAM and disk.
252
 
 
 
 
 
253
  Use `scripts/rebuild_compact_v1.sh` only for a destructive full rebuild from a
254
  local complete `archives/` tree.
255
 
 
250
  Parquet files. Set `LATEST_REBUILD_WORKERS` to tune that fan-out for the
251
  machine's RAM and disk.
252
 
253
+ Every ingest that can commit new archives must use a fresh `BATCH_ID`.
254
+ Reusing a committed batch ID is rejected because all-revisions files are named
255
+ from that ID.
256
+
257
  Use `scripts/rebuild_compact_v1.sh` only for a destructive full rebuild from a
258
  local complete `archives/` tree.
259
 
docs/PIPELINE_RUNBOOK.md CHANGED
@@ -73,6 +73,11 @@ FETCHER_RPM=480 # default RPM for osu! API + every download mirror
73
  DISCOVER_SEARCH_RPM=480 # default RPM for mirror discovery search endpoints
74
  ```
75
 
 
 
 
 
 
76
  Do not sync bucket `archives/` onto an update worker. The update worker only
77
  uploads its local `archives/` tree with:
78
 
 
73
  DISCOVER_SEARCH_RPM=480 # default RPM for mirror discovery search endpoints
74
  ```
75
 
76
+ Use a fresh `BATCH_ID` for every ingest that may commit new archives. The
77
+ wrapper and `ingest_osz.py` refuse to ingest with a batch ID that already has
78
+ committed `archive_revisions`, because reusing it can overwrite existing
79
+ `part-<batch>.parquet` files.
80
+
81
  Do not sync bucket `archives/` onto an update worker. The update worker only
82
  uploads its local `archives/` tree with:
83
 
python/ingest_osz.py ADDED
@@ -0,0 +1,1491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Ingest one or more .osz archives into the compact v1 store.
3
+
4
+ End-to-end pipeline (PER CHUNK):
5
+ 1. Invoke the Rust ``osu_indexer`` binary on a chunk of archives;
6
+ the indexer copies the raw archive to ``archives/sha256/``, hashes each
7
+ member without writing extracted blob files, parses every .osu / .osb,
8
+ resolves references, computes rosu-pp difficulty attributes, and emits one
9
+ NDJSON line per row tagged with ``_table``.
10
+ 2. Group rows by ``_table``; derive the ``set_shard`` partition column from
11
+ ``set_revisions``.
12
+ 3. Atomically write compact all-revisions Parquet files with
13
+ ``archive_revisions`` deferred.
14
+ 4. Atomically commit ``archive_revisions`` as the chunk commit marker.
15
+ Only after this row exists for an archive is the rest of its data
16
+ guaranteed to be on disk.
17
+
18
+ Crash-safety guarantees:
19
+ - Archive copies are tmp+rename atomic in the indexer.
20
+ - Every parquet write is tmp+rename atomic via parquet_writer._atomic_write_parquet.
21
+ - The chunk commit marker is ``archive_revisions``: if a chunk crashes
22
+ before commit, ``--skip-already-ingested`` (default on) re-runs that
23
+ chunk on the next invocation. Re-running the same chunk_batch_id is
24
+ idempotent at every step.
25
+ - Across chunks, only the in-progress chunk's work is at risk on Ctrl+C.
26
+ - On startup we sweep orphan ``*.tmp.<pid>`` files older than
27
+ ``--gc-tmp-files-age-min`` (default 60 minutes) so leaks don't grow
28
+ unbounded.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import contextlib
35
+ import datetime as _dt
36
+ import hashlib
37
+ import json
38
+ import os
39
+ import re
40
+ import secrets
41
+ import subprocess
42
+ import sys
43
+ import tempfile
44
+ import time
45
+ from pathlib import Path
46
+
47
+ import pyarrow.dataset as ds
48
+ from tqdm.auto import tqdm
49
+
50
+ from parquet_writer import (
51
+ commit_archive_revisions,
52
+ group_rows_by_table,
53
+ load_schemas,
54
+ write_all_revisions_tables,
55
+ )
56
+
57
+
58
+ def _log(msg: str) -> None:
59
+ """Print to stderr with ``flush=True``.
60
+
61
+ Once stderr is not a TTY, Python switches it to block buffering, and
62
+ progress lines for long-running steps stop appearing in real time.
63
+ Forcing a flush per line keeps the log live without changing the host
64
+ terminal's buffering policy.
65
+ """
66
+ print(msg, file=sys.stderr, flush=True)
67
+
68
+
69
+ def _default_batch_id() -> str:
70
+ stamp = _dt.datetime.now(_dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
71
+ return f"{stamp}-{secrets.token_hex(3)}"
72
+
73
+
74
+ # Windows SetThreadExecutionState flags (winbase.h).
75
+ # Setting ES_CONTINUOUS | ES_SYSTEM_REQUIRED tells the OS to keep
76
+ # resetting the system idle timer until cleared — i.e. don't sleep.
77
+ # Display sleep / screen lock are NOT inhibited; only system sleep.
78
+ _ES_CONTINUOUS = 0x80000000
79
+ _ES_SYSTEM_REQUIRED = 0x00000001
80
+
81
+
82
+ def _process_alive(pid: int) -> bool:
83
+ """Best-effort check whether process ``pid`` is still running.
84
+
85
+ Used by :func:`repo_lock` to detect stale lock files left behind by a
86
+ crashed previous run. False positives (treating a dead process as alive)
87
+ only block the user with a clear "remove the lock" instruction; false
88
+ negatives (treating a live process as dead) would let two writers race,
89
+ which is the actual hazard — so the implementation errs on the side of
90
+ "alive" whenever it cannot definitively prove the process has exited.
91
+ """
92
+ if pid <= 0:
93
+ return False
94
+ if sys.platform.startswith("win"):
95
+ try:
96
+ import ctypes # noqa: PLC0415
97
+
98
+ # use_last_error=True lets us read the Win32 error from
99
+ # OpenProcess so we can distinguish "no such PID" (truly dead)
100
+ # from "exists but unqueryable" (assume alive).
101
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
102
+ # PROCESS_QUERY_LIMITED_INFORMATION (0x1000) is granted even
103
+ # across user / integrity-level boundaries, so we don't false-
104
+ # negative on processes we don't own.
105
+ handle = kernel32.OpenProcess(0x1000, False, pid)
106
+ if not handle:
107
+ err = ctypes.get_last_error()
108
+ # ERROR_INVALID_PARAMETER (87) is what the kernel returns
109
+ # when there is no process with the given PID — that is the
110
+ # only signal that lets us safely report "dead". Anything
111
+ # else (ACCESS_DENIED = 5, etc.) means the process probably
112
+ # exists but we can't query it; play it safe and assume
113
+ # alive, because a false negative would let two writers race.
114
+ return err != 87
115
+ exit_code = ctypes.c_ulong(0)
116
+ ok = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
117
+ kernel32.CloseHandle(handle)
118
+ if not ok:
119
+ return True # uncertain — assume alive
120
+ # STILL_ACTIVE = 259. Anything else = the process has exited.
121
+ return exit_code.value == 259
122
+ except (ImportError, OSError, AttributeError):
123
+ return True # uncertain — assume alive
124
+ # POSIX: signal 0 just probes for liveness without delivering a signal.
125
+ try:
126
+ os.kill(pid, 0)
127
+ return True
128
+ except ProcessLookupError:
129
+ return False
130
+ except PermissionError:
131
+ # Process exists but we don't own it — alive.
132
+ return True
133
+ except OSError:
134
+ return True # uncertain — assume alive
135
+
136
+
137
+ def _try_atomic_create_lock(lock_path: Path, payload: str) -> bool:
138
+ """Atomically create the lock file with ``payload``.
139
+
140
+ Returns ``True`` on success, ``False`` if the file already exists.
141
+ ``O_CREAT | O_EXCL`` is the kernel's only race-free way to take an
142
+ exclusive lock against a concurrent process — a separate ``exists()``
143
+ check followed by ``write_text()`` has a TOCTOU window where two
144
+ launches both see "no lock" and both write, producing two writers
145
+ that each believe they hold it.
146
+ """
147
+ try:
148
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
149
+ except FileExistsError:
150
+ return False
151
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
152
+ f.write(payload)
153
+ return True
154
+
155
+
156
+ @contextlib.contextmanager
157
+ def repo_lock(repo_root: Path, force: bool = False):
158
+ """Hold an exclusive single-writer lock on ``repo_root`` for the with body.
159
+
160
+ Stores ``<pid>\\n<utc-iso-timestamp>\\n`` in ``repo_root/.ingest.lock``.
161
+ On entry, refuses to proceed if the lock already exists and points to a
162
+ PID that's still alive — two concurrent ingests against the same repo
163
+ would race on the orphan-parquet GC and the latest-bucket transaction
164
+ promotion, producing duplicate rows and lost work.
165
+
166
+ Acquisition uses ``O_CREAT | O_EXCL`` so two simultaneous launches can't
167
+ both pass the existence check before either writes. Stale locks (PID no
168
+ longer alive) are cleaned up automatically with a one-line stderr notice.
169
+ Pass ``force=True`` (CLI ``--force-lock``) to override even a live-PID
170
+ lock — only safe if the user has manually confirmed the other process
171
+ is gone.
172
+
173
+ Released on exit even if the body raises. The lock file lives at the
174
+ repo root rather than under ``data/`` so that ``rm -rf data/`` for a
175
+ fresh restart doesn't accidentally remove an active lock.
176
+
177
+ Yields ``had_stale_lock: bool`` so the body can decide whether paranoid
178
+ crash-recovery sweeps (e.g. orphan tmp file GC) need to run. Lock file
179
+ presence at startup means the previous run did not unwind cleanly:
180
+ either it was hard-killed (OS crash, SIGKILL, power loss) before its
181
+ ``finally`` could unlink the file, or the user is overriding a live
182
+ lock with ``--force-lock``. A clean exit (including caught Ctrl+C and
183
+ propagated exceptions) always unlinks the lock, so its absence on the
184
+ next startup is a positive proof of clean shutdown.
185
+ """
186
+ repo_root.mkdir(parents=True, exist_ok=True)
187
+ lock_path = repo_root / ".ingest.lock"
188
+ payload = (
189
+ f"{os.getpid()}\n"
190
+ f"{_dt.datetime.now(_dt.timezone.utc).isoformat()}\n"
191
+ )
192
+ had_stale_lock = False
193
+
194
+ if not _try_atomic_create_lock(lock_path, payload):
195
+ # Lock already exists. Diagnose owner before deciding whether to clean.
196
+ had_stale_lock = True
197
+ existing_pid: int | None = None
198
+ existing_started: str = "?"
199
+ try:
200
+ content = lock_path.read_text(encoding="utf-8").strip().splitlines()
201
+ existing_pid = int(content[0])
202
+ if len(content) > 1:
203
+ existing_started = content[1]
204
+ except (OSError, ValueError, IndexError):
205
+ pass
206
+
207
+ if existing_pid is not None and _process_alive(existing_pid):
208
+ if not force:
209
+ raise SystemExit(
210
+ f"error: ingest lock at {lock_path} is held by PID "
211
+ f"{existing_pid} (started {existing_started}). "
212
+ f"Refusing to launch a second writer against {repo_root} — "
213
+ f"two concurrent ingests would corrupt the dataset "
214
+ f"(orphan-parquet GC and latest-bucket promotion are not "
215
+ f"multi-writer safe). If you are certain that PID is gone, "
216
+ f"remove the lock file or pass --force-lock."
217
+ )
218
+ print(
219
+ f"warning: --force-lock overriding existing lock "
220
+ f"(PID {existing_pid}, started {existing_started}); this is "
221
+ f"unsafe if the other process is still writing.",
222
+ file=sys.stderr,
223
+ )
224
+ elif existing_pid is not None:
225
+ print(
226
+ f"info: removing stale ingest lock at {lock_path} "
227
+ f"(PID {existing_pid} no longer alive; was started "
228
+ f"{existing_started})",
229
+ file=sys.stderr,
230
+ )
231
+ else:
232
+ print(
233
+ f"info: removing unparseable ingest lock at {lock_path}",
234
+ file=sys.stderr,
235
+ )
236
+
237
+ try:
238
+ lock_path.unlink()
239
+ except OSError:
240
+ pass
241
+ # Re-attempt atomically. If a third process raced in between our
242
+ # unlink and create, refuse rather than overwriting their lock.
243
+ if not _try_atomic_create_lock(lock_path, payload):
244
+ raise SystemExit(
245
+ f"error: lock at {lock_path} was re-acquired by another "
246
+ f"process between cleanup and retry; refusing to proceed."
247
+ )
248
+
249
+ try:
250
+ yield had_stale_lock
251
+ finally:
252
+ try:
253
+ lock_path.unlink()
254
+ except OSError:
255
+ pass
256
+
257
+
258
+ @contextlib.contextmanager
259
+ def keep_awake(enabled: bool = True):
260
+ """Inhibit system sleep for the duration of the ``with`` block.
261
+
262
+ On Windows: ``SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)``
263
+ on entry, ``SetThreadExecutionState(ES_CONTINUOUS)`` on exit (clears the
264
+ flags so the system can sleep again on its normal idle policy).
265
+
266
+ On non-Windows or when ``enabled=False``: no-op.
267
+
268
+ The display is NOT kept awake — only the system. Phase 17 runs unattended,
269
+ so we want to let the screen turn off but keep the box awake.
270
+ """
271
+ if not enabled or not sys.platform.startswith("win"):
272
+ yield
273
+ return
274
+
275
+ try:
276
+ import ctypes # noqa: PLC0415 — keep import optional for non-win platforms
277
+ except ImportError:
278
+ print(
279
+ "warning: ctypes unavailable; system may sleep during the run",
280
+ file=sys.stderr,
281
+ )
282
+ yield
283
+ return
284
+
285
+ try:
286
+ kernel32 = ctypes.windll.kernel32
287
+ except (AttributeError, OSError) as e:
288
+ print(
289
+ f"warning: SetThreadExecutionState unavailable ({e}); "
290
+ f"system may sleep during the run",
291
+ file=sys.stderr,
292
+ )
293
+ yield
294
+ return
295
+
296
+ prev = kernel32.SetThreadExecutionState(_ES_CONTINUOUS | _ES_SYSTEM_REQUIRED)
297
+ if prev == 0:
298
+ # 0 means the call failed; the doc says GetLastError gives details,
299
+ # but a single warning is enough — fall through and let the run
300
+ # proceed even without the inhibitor.
301
+ print(
302
+ "warning: SetThreadExecutionState failed; system may sleep during the run",
303
+ file=sys.stderr,
304
+ )
305
+ yield
306
+ return
307
+
308
+ print(
309
+ "keep-awake: system sleep inhibited (ES_SYSTEM_REQUIRED). "
310
+ "Display can still sleep on its normal timer.",
311
+ file=sys.stderr,
312
+ )
313
+ try:
314
+ yield
315
+ finally:
316
+ try:
317
+ kernel32.SetThreadExecutionState(_ES_CONTINUOUS)
318
+ print("keep-awake: released; normal sleep policy restored.", file=sys.stderr)
319
+ except Exception:
320
+ # We're already exiting; swallow rather than mask the real error.
321
+ pass
322
+
323
+
324
+ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
325
+ p = argparse.ArgumentParser(
326
+ prog="ingest_osz",
327
+ description="Ingest .osz archives into the compact v1 store.",
328
+ )
329
+ p.add_argument(
330
+ "archives",
331
+ nargs="+",
332
+ help=".osz files (or directories of .osz files) to ingest",
333
+ )
334
+ p.add_argument(
335
+ "--repo-root",
336
+ default=".",
337
+ help="root of the osu-everything repo (default: cwd)",
338
+ )
339
+ p.add_argument(
340
+ "--schema-version",
341
+ default="v1",
342
+ help="schema version directory under data/",
343
+ )
344
+ p.add_argument(
345
+ "--schemas-dir",
346
+ default=None,
347
+ help="override schema-loading directory (default: <repo>/schemas/<schema-version>)",
348
+ )
349
+ p.add_argument(
350
+ "--rosu-indexer",
351
+ default="./target/release/osu_indexer",
352
+ help="path to the compiled Rust indexer binary",
353
+ )
354
+
355
+ p.add_argument(
356
+ "--archives-dir",
357
+ default=None,
358
+ help="absolute directory where archive .osz CAS copies are written "
359
+ "(default: <repo-root>/archives)",
360
+ )
361
+
362
+ p.add_argument(
363
+ "--indexer-workers",
364
+ type=int,
365
+ default=None,
366
+ help="number of archives the Rust indexer processes concurrently per "
367
+ "chunk (forwarded as --workers). Defaults to the indexer's own "
368
+ "default of min(4, available_parallelism). Higher values keep both "
369
+ "input and CAS drives busy continuously and parallelize rosu-pp "
370
+ "across cores; on a single HDD spindle, going past 4 workers "
371
+ "thrashes seeks.",
372
+ )
373
+
374
+ p.add_argument(
375
+ "--write-all-revisions",
376
+ dest="write_all_revisions",
377
+ action="store_true",
378
+ default=True,
379
+ )
380
+ p.add_argument(
381
+ "--no-write-all-revisions",
382
+ dest="write_all_revisions",
383
+ action="store_false",
384
+ )
385
+
386
+ p.add_argument(
387
+ "--physical-partitioning",
388
+ choices=("schema", "none"),
389
+ default="none",
390
+ help="physical all_revisions partition layout. 'schema' preserves the "
391
+ "schema partition dirs; 'none' writes one parquet per table per chunk "
392
+ "while retaining partition columns in the file body.",
393
+ )
394
+
395
+ p.add_argument(
396
+ "--ingest-batch-id",
397
+ default=None,
398
+ help="parent batch id; chunks get '-chunk-NNNN' suffix when >1 chunk "
399
+ "(defaults to UTC ISO-8601 + random suffix)",
400
+ )
401
+ p.add_argument(
402
+ "--limit",
403
+ type=int,
404
+ default=None,
405
+ help="stop after N archives (useful for smoke tests)",
406
+ )
407
+ p.add_argument(
408
+ "--dry-run",
409
+ action="store_true",
410
+ help="run the indexer but do not write Parquet",
411
+ )
412
+
413
+ p.add_argument(
414
+ "--skip-difficulty",
415
+ action="store_true",
416
+ help="forward to osu_indexer: skip the rosu-pp difficulty pass",
417
+ )
418
+ p.add_argument(
419
+ "--keep-ndjson",
420
+ type=Path,
421
+ default=None,
422
+ help="path to keep the indexer's NDJSON output for inspection "
423
+ "(default: write to a temp file and delete after; in chunked mode "
424
+ "the per-chunk NDJSON gets a '.<chunk_idx>' suffix)",
425
+ )
426
+
427
+ # Resume / crash-safety knobs.
428
+ p.add_argument(
429
+ "--skip-already-ingested",
430
+ dest="skip_already_ingested",
431
+ action="store_true",
432
+ default=True,
433
+ help="hash each input archive at startup and skip those whose "
434
+ "archive_sha256 is already in archive_revisions/ (default on)",
435
+ )
436
+ p.add_argument(
437
+ "--no-skip-already-ingested",
438
+ dest="skip_already_ingested",
439
+ action="store_false",
440
+ )
441
+ p.add_argument(
442
+ "--archive-sha-cache",
443
+ dest="archive_sha_cache",
444
+ action="store_true",
445
+ default=True,
446
+ help="cache (path, mtime, size, sha256) for input archives in "
447
+ ".scratch/input_archive_shas.json so the pre-chunk hashing pass "
448
+ "skips files that haven't changed since last run (default on)",
449
+ )
450
+ p.add_argument(
451
+ "--no-archive-sha-cache",
452
+ dest="archive_sha_cache",
453
+ action="store_false",
454
+ help="force-rehash every input archive at startup, ignoring the cache",
455
+ )
456
+ p.add_argument(
457
+ "--chunk-size",
458
+ type=int,
459
+ default=1000,
460
+ help="archives per indexer invocation; smaller = finer resume "
461
+ "granularity, larger = fewer parquet files (default 1000)",
462
+ )
463
+ p.add_argument(
464
+ "--gc-tmp-files",
465
+ dest="gc_tmp_files",
466
+ action="store_true",
467
+ default=True,
468
+ help="enable orphan *.tmp.<pid> file GC on startup (default on). "
469
+ "By default the walk only runs when a stale .ingest.lock is "
470
+ "detected at startup (= previous run was hard-killed); on clean "
471
+ "exits and Ctrl+C the walk is skipped because atomic tmp+rename + "
472
+ "the indexer's signal-aware drain leave no orphans. Pass "
473
+ "--always-gc-tmp-files to walk unconditionally.",
474
+ )
475
+ p.add_argument(
476
+ "--no-gc-tmp-files",
477
+ dest="gc_tmp_files",
478
+ action="store_false",
479
+ help="never walk for orphan tmp files. Use only when you've "
480
+ "manually confirmed the repo is clean — leftover tmp files will "
481
+ "stay on disk forever as wasted space until cleaned by hand.",
482
+ )
483
+ p.add_argument(
484
+ "--always-gc-tmp-files",
485
+ dest="always_gc_tmp_files",
486
+ action="store_true",
487
+ default=False,
488
+ help="walk archives/ and data/ for orphan *.tmp.<pid> files on every "
489
+ "startup, regardless of whether the previous run shut down cleanly.",
490
+ )
491
+ p.add_argument(
492
+ "--always-crash-recovery",
493
+ dest="always_crash_recovery",
494
+ action="store_true",
495
+ default=False,
496
+ help="run orphan-Parquet cleanup on every startup, regardless of "
497
+ "whether the previous run shut down cleanly.",
498
+ )
499
+ p.add_argument(
500
+ "--gc-tmp-files-age-min",
501
+ type=int,
502
+ default=60,
503
+ help="minimum age in minutes for tmp files to be eligible for GC "
504
+ "(default 60); set to 0 to delete all orphans",
505
+ )
506
+ p.add_argument(
507
+ "--cleanup-orphan-parquets",
508
+ dest="cleanup_orphan_parquets",
509
+ action="store_true",
510
+ default=True,
511
+ help="on startup, delete all_revisions/<table>/.../part-<batch>.parquet "
512
+ "files whose batch_id has no archive_revisions commit marker — "
513
+ "fixes duplicate rows after a crashed chunk (default on)",
514
+ )
515
+ p.add_argument(
516
+ "--no-cleanup-orphan-parquets",
517
+ dest="cleanup_orphan_parquets",
518
+ action="store_false",
519
+ )
520
+
521
+ p.add_argument(
522
+ "--quiet-indexer",
523
+ action="store_true",
524
+ help="forward --quiet to the Rust indexer, suppressing the per-archive "
525
+ "progress line. The chunk-level ETA/timing summary is still printed.",
526
+ )
527
+
528
+ p.add_argument(
529
+ "--keep-awake",
530
+ dest="keep_awake",
531
+ action="store_true",
532
+ default=True,
533
+ help="on Windows, prevent system sleep for the duration of the run "
534
+ "via SetThreadExecutionState (ES_SYSTEM_REQUIRED). Display sleep is "
535
+ "not inhibited. Default on; no-op on non-Windows.",
536
+ )
537
+ p.add_argument(
538
+ "--no-keep-awake",
539
+ dest="keep_awake",
540
+ action="store_false",
541
+ )
542
+
543
+ p.add_argument(
544
+ "--force-lock",
545
+ dest="force_lock",
546
+ action="store_true",
547
+ default=False,
548
+ help="override an existing repo lock even if the holding PID is still "
549
+ "alive. UNSAFE: two concurrent ingests against the same repo will "
550
+ "corrupt the dataset. Only pass this if you have manually confirmed "
551
+ "the previous process is gone.",
552
+ )
553
+
554
+ return p.parse_args(argv)
555
+
556
+
557
+ def _resolve_indexer_path(indexer: Path, repo_root: Path) -> Path | None:
558
+ """Find the indexer binary by trying cwd- and repo-root-relative,
559
+ with and without a Windows .exe suffix."""
560
+ candidates: list[Path] = []
561
+ if indexer.is_absolute():
562
+ candidates.append(indexer)
563
+ else:
564
+ candidates.extend([Path.cwd() / indexer, repo_root / indexer])
565
+ if sys.platform.startswith("win"):
566
+ candidates += [c.with_suffix(c.suffix + ".exe") for c in list(candidates)]
567
+ for c in candidates:
568
+ if c.exists():
569
+ return c.resolve()
570
+ return None
571
+
572
+
573
+ def collect_archives(inputs: list[str]) -> list[Path]:
574
+ out: list[Path] = []
575
+ for arg in inputs:
576
+ p = Path(arg)
577
+ if p.is_dir():
578
+ out.extend(sorted(p.rglob("*.osz")))
579
+ elif p.is_file() and p.suffix.lower() == ".osz":
580
+ out.append(p)
581
+ else:
582
+ print(f"warning: skipping non-.osz argument {arg!r}", file=sys.stderr)
583
+ return out
584
+
585
+
586
+ def _format_duration(seconds: float) -> str:
587
+ """Compact human-readable duration ('42s', '7.3m', '4.2h')."""
588
+ if seconds < 60:
589
+ return f"{seconds:.0f}s"
590
+ if seconds < 3600:
591
+ return f"{seconds / 60:.1f}m"
592
+ return f"{seconds / 3600:.1f}h"
593
+
594
+
595
+ def _format_size(num_bytes: float) -> str:
596
+ """Compact human-readable byte size ('312 KB', '47.2 MB', '3.1 GB')."""
597
+ n = float(num_bytes)
598
+ for unit in ("B", "KB", "MB", "GB", "TB"):
599
+ if n < 1024 or unit == "TB":
600
+ return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} B"
601
+ n /= 1024
602
+ return f"{n:.1f} TB"
603
+
604
+
605
+ def already_ingested_shas(archive_revisions_dir: Path) -> set[str]:
606
+ """Read existing all_revisions/archive_revisions/ parquets and return the
607
+ set of archive_sha256 values currently committed.
608
+
609
+ Returns an empty set if the directory is empty or missing. Iterates
610
+ batches under a tqdm bar so the user sees progress while a full-corpus
611
+ archive_revisions/ (tens of thousands of rows across many parquets) is
612
+ being read.
613
+ """
614
+ if not archive_revisions_dir.exists():
615
+ return set()
616
+ parquets = list(archive_revisions_dir.rglob("*.parquet"))
617
+ if not parquets:
618
+ return set()
619
+ dataset = ds.dataset([str(p) for p in parquets], format="parquet")
620
+ scanner = dataset.scanner(columns=["archive_sha256"])
621
+ total = scanner.count_rows()
622
+ out: set[str] = set()
623
+ bar = tqdm(
624
+ total=total,
625
+ desc=f"reading committed archive_sha256s ({len(parquets)} parquet(s))",
626
+ unit="row",
627
+ unit_scale=True,
628
+ file=sys.stderr,
629
+ mininterval=1.0,
630
+ dynamic_ncols=True,
631
+ )
632
+ try:
633
+ for batch in scanner.to_batches():
634
+ out.update(batch.column("archive_sha256").to_pylist())
635
+ bar.update(batch.num_rows)
636
+ finally:
637
+ bar.close()
638
+ return out
639
+
640
+
641
+ def sha256_of_file(path: Path) -> str:
642
+ h = hashlib.sha256()
643
+ with path.open("rb") as f:
644
+ for chunk in iter(lambda: f.read(1 << 20), b""):
645
+ h.update(chunk)
646
+ return h.hexdigest()
647
+
648
+
649
+ # JSON sidecar mapping ``str(path.resolve()) -> {mtime_ns, size_bytes, sha256}``.
650
+ # A re-run with unchanged inputs is dominated by the cost of statting each file
651
+ # and reading the cache; on a 38k-archive HDD corpus this collapses ~55 minutes
652
+ # of SHA-256 to a few seconds. A stale cache loses correctness only if the user
653
+ # replaces a file's contents while preserving both mtime AND size — pass
654
+ # ``--no-archive-sha-cache`` to force re-hashing if that's a real concern.
655
+ _ARCHIVE_SHA_CACHE_BASENAME = "input_archive_shas.json"
656
+
657
+
658
+ def _archive_sha_cache_path(repo_root: Path) -> Path:
659
+ return repo_root / ".scratch" / _ARCHIVE_SHA_CACHE_BASENAME
660
+
661
+
662
+ def _load_archive_sha_cache(cache_path: Path) -> dict[str, dict]:
663
+ if not cache_path.exists():
664
+ return {}
665
+ try:
666
+ data = json.loads(cache_path.read_text(encoding="utf-8"))
667
+ except (OSError, json.JSONDecodeError) as e:
668
+ _log(f" warning: ignoring unreadable sha cache at {cache_path}: {e}")
669
+ return {}
670
+ if not isinstance(data, dict):
671
+ return {}
672
+ return data
673
+
674
+
675
+ def _save_archive_sha_cache(cache_path: Path, cache: dict[str, dict]) -> None:
676
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
677
+ tmp = cache_path.with_suffix(cache_path.suffix + f".tmp.{os.getpid()}")
678
+ try:
679
+ tmp.write_text(json.dumps(cache), encoding="utf-8")
680
+ os.replace(tmp, cache_path)
681
+ except OSError as e:
682
+ _log(f" warning: could not save sha cache to {cache_path}: {e}")
683
+ try:
684
+ tmp.unlink()
685
+ except OSError:
686
+ pass
687
+
688
+
689
+ def filter_already_ingested(
690
+ archives: list[Path],
691
+ known_shas: set[str],
692
+ cache_path: Path | None = None,
693
+ ) -> tuple[list[Path], list[Path], list[tuple[Path, Path]]]:
694
+ """Hash each archive and partition into (to_ingest, already_done, duplicates).
695
+
696
+ The hashing pass also de-duplicates the *input* list by content SHA-256.
697
+ If ``osu_archives/`` accidentally contains two files whose bytes are
698
+ identical (e.g. ``1.osz`` plus ``copy_of_1.osz``), the duplicate would
699
+ otherwise produce two ``archive_revisions`` rows with the same primary
700
+ key in the same chunk. We keep the first occurrence (sorted glob order
701
+ is already deterministic) and report the rest as ``duplicates``.
702
+
703
+ Always hashes — including when ``known_shas`` is empty, so duplicate
704
+ inputs in a fresh run are still caught. To opt out of the hashing cost
705
+ on small/trusted inputs, pass ``--no-skip-already-ingested`` to
706
+ ``ingest_osz.py``; that path skips this entire function.
707
+
708
+ With ``cache_path`` set, an on-disk sidecar maps
709
+ ``str(path.resolve()) -> {mtime_ns, size_bytes, sha256}``. Inputs whose
710
+ (path, mtime_ns, size_bytes) match a cache entry skip the full hash; new
711
+ or modified files are hashed once and added to the cache. Saved every
712
+ 5,000 hashes and again at function exit so a Ctrl+C mid-pass keeps the
713
+ work done so far. The first full-corpus pass on HDD still takes ~50 min
714
+ (~12 archives/sec); subsequent passes finish in seconds.
715
+ """
716
+ cache: dict[str, dict] = (
717
+ _load_archive_sha_cache(cache_path) if cache_path is not None else {}
718
+ )
719
+ cache_dirty = False
720
+ cache_hits = 0
721
+ save_every = 5000
722
+ hashes_since_save = 0
723
+
724
+ def _persist() -> None:
725
+ nonlocal cache_dirty, hashes_since_save
726
+ if cache_path is None or not cache_dirty:
727
+ return
728
+ _save_archive_sha_cache(cache_path, cache)
729
+ cache_dirty = False
730
+ hashes_since_save = 0
731
+
732
+ to_ingest: list[Path] = []
733
+ already_done: list[Path] = []
734
+ duplicates: list[tuple[Path, Path]] = []
735
+ seen_in_input: dict[str, Path] = {}
736
+ try:
737
+ for p in tqdm(
738
+ archives,
739
+ total=len(archives),
740
+ desc="hashing archives",
741
+ unit="archive",
742
+ file=sys.stderr,
743
+ mininterval=1.0,
744
+ dynamic_ncols=True,
745
+ ):
746
+ cache_key: str | None = None
747
+ mtime_ns: int | None = None
748
+ size_bytes: int | None = None
749
+ try:
750
+ stat = p.stat()
751
+ size_bytes = stat.st_size
752
+ mtime_ns = stat.st_mtime_ns
753
+ cache_key = str(p.resolve())
754
+ except OSError:
755
+ # If we can't stat, fall through to a fresh hash; sha256_of_file
756
+ # will surface the same OSError if the file is genuinely gone.
757
+ pass
758
+ entry = cache.get(cache_key) if cache_key is not None else None
759
+ if (
760
+ isinstance(entry, dict)
761
+ and entry.get("mtime_ns") == mtime_ns
762
+ and entry.get("size_bytes") == size_bytes
763
+ and isinstance(entry.get("sha256"), str)
764
+ ):
765
+ sha = entry["sha256"]
766
+ cache_hits += 1
767
+ else:
768
+ sha = sha256_of_file(p)
769
+ if cache_key is not None:
770
+ cache[cache_key] = {
771
+ "mtime_ns": mtime_ns,
772
+ "size_bytes": size_bytes,
773
+ "sha256": sha,
774
+ }
775
+ cache_dirty = True
776
+ hashes_since_save += 1
777
+ if hashes_since_save >= save_every:
778
+ _persist()
779
+ if sha in seen_in_input:
780
+ duplicates.append((p, seen_in_input[sha]))
781
+ elif sha in known_shas:
782
+ already_done.append(p)
783
+ seen_in_input[sha] = p
784
+ else:
785
+ to_ingest.append(p)
786
+ seen_in_input[sha] = p
787
+ finally:
788
+ _persist()
789
+ if cache_path is not None:
790
+ _log(
791
+ f" sha cache: {cache_hits:,}/{len(archives):,} hit(s); "
792
+ f"{len(archives) - cache_hits:,} fresh hash(es) "
793
+ f"({cache_path})"
794
+ )
795
+ return to_ingest, already_done, duplicates
796
+
797
+
798
+ _TMP_PATTERN = re.compile(r"\.tmp\.\d+$")
799
+ _PART_BATCH_ID_PATTERN = re.compile(r"^part-(.+)\.parquet$")
800
+
801
+
802
+ def committed_batch_ids(archive_revisions_dir: Path) -> set[str]:
803
+ """Return the set of ``batch_id``s with a committed ``archive_revisions``
804
+ parquet file on disk.
805
+
806
+ Each AR file is named ``part-<batch_id>.parquet``; its existence is the
807
+ commit marker for that batch. Used by :func:`cleanup_orphan_parquets`
808
+ to identify all_revisions parquets from crashed chunks.
809
+ """
810
+ if not archive_revisions_dir.exists():
811
+ return set()
812
+ out: set[str] = set()
813
+ bar = tqdm(
814
+ desc="scanning archive_revisions/",
815
+ unit="file",
816
+ file=sys.stderr,
817
+ mininterval=1.0,
818
+ dynamic_ncols=True,
819
+ )
820
+ try:
821
+ for f in archive_revisions_dir.rglob("*.parquet"):
822
+ bar.update(1)
823
+ m = _PART_BATCH_ID_PATTERN.match(f.name)
824
+ if m:
825
+ out.add(m.group(1))
826
+ finally:
827
+ bar.close()
828
+ return out
829
+
830
+
831
+ def committed_batch_ids_for_parent(
832
+ archive_revisions_dir: Path,
833
+ parent_batch_id: str,
834
+ ) -> list[str]:
835
+ prefix = f"{parent_batch_id}-chunk-"
836
+ return sorted(
837
+ batch_id
838
+ for batch_id in committed_batch_ids(archive_revisions_dir)
839
+ if batch_id == parent_batch_id or batch_id.startswith(prefix)
840
+ )
841
+
842
+
843
+ def cleanup_orphan_parquets(
844
+ all_revisions_root: Path,
845
+ committed: set[str],
846
+ ) -> dict[str, int]:
847
+ """Delete ``part-<batch_id>.parquet`` files in non-archive_revisions
848
+ tables whose ``batch_id`` is not in ``committed``.
849
+
850
+ These are remnants of crashed chunks: their tables were written but
851
+ the chunk's ``archive_revisions`` row never made it to disk, so
852
+ skip-already-ingested will re-process the chunk and write fresh
853
+ parquets. Without cleanup the resume produces duplicate rows.
854
+
855
+ AR itself is never touched. Returns a per-table count of deletions.
856
+ """
857
+ out: dict[str, int] = {}
858
+ if not all_revisions_root.exists():
859
+ return out
860
+ table_dirs = [
861
+ d for d in all_revisions_root.iterdir()
862
+ if d.is_dir() and d.name != "archive_revisions"
863
+ ]
864
+ for table_dir in tqdm(
865
+ table_dirs,
866
+ total=len(table_dirs),
867
+ desc="scanning all_revisions tables",
868
+ unit="table",
869
+ file=sys.stderr,
870
+ mininterval=1.0,
871
+ dynamic_ncols=True,
872
+ ):
873
+ n = 0
874
+ for parquet in table_dir.rglob("*.parquet"):
875
+ m = _PART_BATCH_ID_PATTERN.match(parquet.name)
876
+ if not m:
877
+ continue
878
+ if m.group(1) not in committed:
879
+ try:
880
+ parquet.unlink()
881
+ n += 1
882
+ except OSError:
883
+ pass
884
+ if n:
885
+ out[table_dir.name] = n
886
+ return out
887
+
888
+
889
+ def cleanup_orphan_tmp_files(
890
+ repo_root: Path,
891
+ max_age_seconds: int,
892
+ extra_roots: list[tuple[str, Path]] | None = None,
893
+ ) -> dict[str, int]:
894
+ """Delete orphan ``*.tmp.<pid>`` files under archives/ and data/.
895
+
896
+ Files are eligible when their mtime is older than ``max_age_seconds``;
897
+ very young tmp files might belong to a concurrent run, so we skip them.
898
+ Returns ``{subdir: count_deleted}``.
899
+
900
+ ``extra_roots`` is an optional list of ``(label, absolute_path)`` pairs
901
+ to also walk, used when ``--archives-dir`` points outside ``repo_root``.
902
+
903
+ Pass ``max_age_seconds=0`` to delete unconditionally (dangerous if any
904
+ other process is mid-write — only safe when we're the sole writer).
905
+
906
+ Each subdir's rglob is wrapped in an indeterminate-total tqdm spinner
907
+ because we don't know the file count up-front and a full-corpus repo
908
+ can hold millions of entries — without the bar a user on HDD just sees
909
+ silence for 5-10 minutes.
910
+ """
911
+ standard_subs = ("archives", "data")
912
+ out: dict[str, int] = {s: 0 for s in standard_subs}
913
+ extras = list(extra_roots or [])
914
+ for label, _ in extras:
915
+ out.setdefault(label, 0)
916
+
917
+ # Build the (label, path) walk list, deduping by resolved absolute path so
918
+ # an extra root that aliases repo_root/archives does not get scanned twice.
919
+ seen: set[Path] = set()
920
+ targets: list[tuple[str, Path]] = []
921
+ for label, path in (
922
+ [(s, repo_root / s) for s in standard_subs] + extras
923
+ ):
924
+ try:
925
+ key = Path(path).resolve()
926
+ except OSError:
927
+ key = Path(path)
928
+ if key in seen:
929
+ continue
930
+ seen.add(key)
931
+ targets.append((label, path))
932
+
933
+ now = time.time()
934
+ for sub, root in targets:
935
+ if not root.exists():
936
+ continue
937
+ bar = tqdm(
938
+ desc=f"scanning {sub}/",
939
+ unit="file",
940
+ file=sys.stderr,
941
+ mininterval=1.0,
942
+ dynamic_ncols=True,
943
+ )
944
+ try:
945
+ for f in root.rglob("*"):
946
+ bar.update(1)
947
+ if not f.is_file():
948
+ continue
949
+ if _TMP_PATTERN.search(f.name) is None:
950
+ continue
951
+ try:
952
+ age = now - f.stat().st_mtime
953
+ except OSError:
954
+ continue
955
+ if age < max_age_seconds:
956
+ continue
957
+ try:
958
+ f.unlink()
959
+ out[sub] += 1
960
+ except OSError:
961
+ pass
962
+ finally:
963
+ bar.close()
964
+ return out
965
+
966
+
967
+ # Per-chunk indexer wall-time bound. Phase 15 cold-cache wall is ~42 s for 100
968
+ # archives (~0.42 s/archive); chunk_size=1000 should finish well under 10 min.
969
+ # 1800 s is ~4× the projected typical chunk wall, leaving ample headroom for
970
+ # I/O contention but bounded so a single deadlocked rosu-pp call (or any other
971
+ # stuck syscall) cannot hang the orchestrator indefinitely with --keep-awake
972
+ # active. On TimeoutExpired the chunk fails cleanly: the deferred
973
+ # archive_revisions commit means no rows commit, and resume re-runs the chunk.
974
+ INDEXER_TIMEOUT_SECONDS = 1800
975
+
976
+
977
+ def run_indexer(
978
+ indexer: Path,
979
+ archives: list[Path],
980
+ archives_dir: Path,
981
+ blobs_dir: Path,
982
+ out_file: Path,
983
+ batch_id: str,
984
+ schema_version: str,
985
+ skip_difficulty: bool,
986
+ quiet: bool = False,
987
+ workers: int | None = None,
988
+ timeout_seconds: int | None = INDEXER_TIMEOUT_SECONDS,
989
+ ) -> None:
990
+ """Invoke the Rust indexer; raise CalledProcessError on non-zero exit.
991
+
992
+ The indexer streams a per-archive progress line to its own stderr, which
993
+ we let pass through unbuffered so the user sees real-time progress
994
+ during long chunks. Pass ``quiet=True`` to suppress (the indexer's
995
+ summary line still prints).
996
+
997
+ ``workers`` overrides the indexer's parallelism; ``None`` lets the
998
+ indexer pick its own default (``min(4, available_parallelism)``).
999
+ Larger values keep input + CAS drives busy in parallel and parallelize
1000
+ the per-beatmap rosu-pp pass across cores.
1001
+
1002
+ A wall-time ``timeout_seconds`` (default ``INDEXER_TIMEOUT_SECONDS``)
1003
+ bounds the call so a deadlocked subprocess cannot hang the orchestrator
1004
+ forever; pass ``None`` to disable. On timeout, the call site sees
1005
+ ``subprocess.TimeoutExpired`` propagate up; the chunk's
1006
+ ``archive_revisions`` commit has not happened yet, so resume re-runs it.
1007
+ """
1008
+ cmd: list[str] = [
1009
+ str(indexer),
1010
+ "--archives-dir", str(archives_dir),
1011
+ "--blobs-dir", str(blobs_dir),
1012
+ "--out-file", str(out_file),
1013
+ "--ingest-batch-id", batch_id,
1014
+ "--schema-version", schema_version,
1015
+ ]
1016
+ if skip_difficulty:
1017
+ cmd.append("--skip-difficulty")
1018
+ cmd.append("--no-write-blobs")
1019
+ if quiet:
1020
+ cmd.append("--quiet")
1021
+ if workers is not None:
1022
+ cmd.extend(["--workers", str(workers)])
1023
+ cmd.extend(str(a) for a in archives)
1024
+ _log(
1025
+ f" indexer: {len(archives)} archive(s); batch_id={batch_id}"
1026
+ )
1027
+ try:
1028
+ subprocess.run(cmd, check=True, timeout=timeout_seconds)
1029
+ except subprocess.TimeoutExpired as e:
1030
+ _log(
1031
+ f" indexer TIMEOUT after {e.timeout}s on batch_id={batch_id} "
1032
+ f"({len(archives)} archive(s)); chunk will not commit, "
1033
+ f"resume the run to retry."
1034
+ )
1035
+ raise
1036
+
1037
+
1038
+ def _process_chunk(
1039
+ chunk: list[Path],
1040
+ chunk_batch_id: str,
1041
+ args: argparse.Namespace,
1042
+ indexer_path: Path,
1043
+ schemas: dict,
1044
+ repo_root: Path,
1045
+ archives_dir: Path,
1046
+ blobs_dir: Path,
1047
+ all_revisions_root: Path,
1048
+ keep_ndjson: Path | None,
1049
+ ) -> dict:
1050
+ """Run the full per-chunk pipeline. Returns counts/paths/timings for reporting.
1051
+
1052
+ Each step is timed separately (``*_seconds`` keys in the returned dict)
1053
+ so a long-running chunk's bottleneck is visible without re-running.
1054
+ """
1055
+
1056
+ # NDJSON destination: --keep-ndjson if supplied, else a temp file.
1057
+ # The tempfile lives under repo_root/.scratch (typically the same drive
1058
+ # as the canonical store, e.g. E: on the dev box) rather than the OS
1059
+ # default ($TEMP / C:\) — at chunk_size=1000 each chunk's NDJSON is
1060
+ # 2-5 GB, and 38 chunks of create+delete on the system drive would
1061
+ # waste ~115 GB of write churn unrelated to the dataset.
1062
+ if keep_ndjson is not None:
1063
+ ndjson_path = keep_ndjson
1064
+ ndjson_path.parent.mkdir(parents=True, exist_ok=True)
1065
+ cleanup_ndjson = False
1066
+ else:
1067
+ scratch_dir = repo_root / ".scratch"
1068
+ scratch_dir.mkdir(parents=True, exist_ok=True)
1069
+ tmp = tempfile.NamedTemporaryFile(
1070
+ prefix=f"ingest-{chunk_batch_id}-",
1071
+ suffix=".ndjson",
1072
+ dir=str(scratch_dir),
1073
+ delete=False,
1074
+ )
1075
+ tmp.close()
1076
+ ndjson_path = Path(tmp.name)
1077
+ cleanup_ndjson = True
1078
+
1079
+ chunk_start = time.perf_counter()
1080
+ summary: dict = {"chunk_batch_id": chunk_batch_id, "n_archives": len(chunk)}
1081
+
1082
+ try:
1083
+ t0 = time.perf_counter()
1084
+ run_indexer(
1085
+ indexer=indexer_path,
1086
+ archives=chunk,
1087
+ archives_dir=archives_dir,
1088
+ blobs_dir=blobs_dir,
1089
+ out_file=ndjson_path,
1090
+ batch_id=chunk_batch_id,
1091
+ schema_version=args.schema_version,
1092
+ skip_difficulty=args.skip_difficulty,
1093
+ quiet=args.quiet_indexer,
1094
+ workers=args.indexer_workers,
1095
+ )
1096
+ summary["indexer_seconds"] = time.perf_counter() - t0
1097
+
1098
+ try:
1099
+ summary["ndjson_bytes"] = ndjson_path.stat().st_size
1100
+ except OSError:
1101
+ summary["ndjson_bytes"] = 0
1102
+
1103
+ t0 = time.perf_counter()
1104
+ rows_by_table = group_rows_by_table(ndjson_path)
1105
+ summary["group_seconds"] = time.perf_counter() - t0
1106
+ n_rows = sum(len(rs) for rs in rows_by_table.values())
1107
+ summary["n_rows"] = n_rows
1108
+ summary["archive_revisions_emitted"] = len(rows_by_table.get("archive_revisions", []))
1109
+ summary["set_revisions"] = len(rows_by_table.get("set_revisions", []))
1110
+ summary["beatmaps"] = len(rows_by_table.get("beatmaps", []))
1111
+
1112
+ # P0 safety: an indexer that exited 0 but produced no archive rows is
1113
+ # never expected during a normal run. Refuse to commit an empty chunk
1114
+ # — the resume path (skip-already-ingested) treats archive_revisions
1115
+ # as proof the chunk is done, so a silently-empty commit would
1116
+ # permanently mask a broken chunk.
1117
+ if rows_by_table.get("archive_revisions") is None or not rows_by_table.get("archive_revisions"):
1118
+ raise RuntimeError(
1119
+ f"indexer exited 0 but produced no archive_revisions rows for "
1120
+ f"chunk {chunk_batch_id} ({len(chunk)} input archive(s)); "
1121
+ f"refusing to commit an empty chunk. NDJSON at {ndjson_path}"
1122
+ )
1123
+
1124
+ if args.dry_run:
1125
+ print(" dry-run: skipping Parquet writes", file=sys.stderr)
1126
+ summary["wall_seconds"] = time.perf_counter() - chunk_start
1127
+ return summary
1128
+
1129
+ # Step 3: write all_revisions tables EXCEPT archive_revisions.
1130
+ # (archive_revisions is the chunk commit marker — written last.)
1131
+ if args.write_all_revisions:
1132
+ t0 = time.perf_counter()
1133
+ written = write_all_revisions_tables(
1134
+ rows_by_table,
1135
+ schemas,
1136
+ all_revisions_root,
1137
+ chunk_batch_id,
1138
+ defer_tables=("archive_revisions",),
1139
+ physical_partitioning=args.physical_partitioning,
1140
+ )
1141
+ summary["parquet_seconds"] = time.perf_counter() - t0
1142
+ summary["written_files"] = sum(len(ps) for ps in written.values())
1143
+
1144
+ # Step 4: COMMIT — atomically write archive_revisions.
1145
+ # After this returns, --skip-already-ingested treats this chunk's
1146
+ # archives as done.
1147
+ if args.write_all_revisions:
1148
+ t0 = time.perf_counter()
1149
+ ar_paths = commit_archive_revisions(
1150
+ rows_by_table,
1151
+ schemas,
1152
+ all_revisions_root,
1153
+ chunk_batch_id,
1154
+ physical_partitioning=args.physical_partitioning,
1155
+ )
1156
+ summary["ar_commit_seconds"] = time.perf_counter() - t0
1157
+ summary["archive_revisions_committed"] = len(ar_paths)
1158
+
1159
+ finally:
1160
+ if cleanup_ndjson:
1161
+ try:
1162
+ ndjson_path.unlink()
1163
+ except OSError:
1164
+ pass
1165
+
1166
+ summary["wall_seconds"] = time.perf_counter() - chunk_start
1167
+ return summary
1168
+
1169
+
1170
+ def main(argv: list[str] | None = None) -> int:
1171
+ args = parse_args(argv)
1172
+
1173
+ repo_root = Path(args.repo_root).resolve()
1174
+ if args.schemas_dir is not None:
1175
+ schemas_dir = Path(args.schemas_dir).resolve()
1176
+ else:
1177
+ schemas_dir = repo_root / "schemas" / args.schema_version
1178
+ if not schemas_dir.exists():
1179
+ print(
1180
+ f"error: {schemas_dir} not found - run from repo root or pass --repo-root",
1181
+ file=sys.stderr,
1182
+ )
1183
+ return 2
1184
+
1185
+ indexer_path = _resolve_indexer_path(Path(args.rosu_indexer), repo_root)
1186
+ if indexer_path is None:
1187
+ print(
1188
+ f"error: indexer binary not found at {args.rosu_indexer} "
1189
+ f"(searched cwd and {repo_root}) - build it with "
1190
+ f"`cargo build --release -p osu_indexer`",
1191
+ file=sys.stderr,
1192
+ )
1193
+ return 2
1194
+
1195
+ archives = collect_archives(args.archives)
1196
+ if args.limit:
1197
+ archives = archives[: args.limit]
1198
+ if not archives:
1199
+ print("error: no .osz archives to ingest", file=sys.stderr)
1200
+ return 2
1201
+
1202
+ parent_batch_id = args.ingest_batch_id or _default_batch_id()
1203
+ archives_dir = (
1204
+ Path(args.archives_dir).resolve()
1205
+ if args.archives_dir
1206
+ else repo_root / "archives"
1207
+ )
1208
+ blobs_dir = repo_root / "blobs"
1209
+ all_revisions_root = repo_root / "data" / args.schema_version / "all_revisions"
1210
+
1211
+ if archives_dir != repo_root / "archives":
1212
+ _log(f"archives dir: {archives_dir}")
1213
+
1214
+ # Acquire the single-writer repo lock BEFORE inhibiting sleep — if the
1215
+ # lock fails we don't want to leave the system in a no-sleep state.
1216
+ # The lock context yields had_stale_lock=True when a prior lock file
1217
+ # existed at startup; that's our signal that the previous run was
1218
+ # hard-killed (its finally never ran) and orphan tmp file GC should
1219
+ # actually run instead of being short-circuited.
1220
+ try:
1221
+ with repo_lock(repo_root, force=args.force_lock) as had_stale_lock:
1222
+ with keep_awake(enabled=args.keep_awake):
1223
+ return _run_main(
1224
+ args=args,
1225
+ repo_root=repo_root,
1226
+ archives=archives,
1227
+ parent_batch_id=parent_batch_id,
1228
+ archives_dir=archives_dir,
1229
+ blobs_dir=blobs_dir,
1230
+ all_revisions_root=all_revisions_root,
1231
+ schemas_dir=schemas_dir,
1232
+ indexer_path=indexer_path,
1233
+ had_stale_lock=had_stale_lock,
1234
+ )
1235
+ except KeyboardInterrupt:
1236
+ # Propagated up after both context managers have unwound. The chunk
1237
+ # commit marker (archive_revisions) is the last write in a chunk's
1238
+ # pipeline, so any uncommitted chunk simply doesn't appear on disk —
1239
+ # rerunning with --skip-already-ingested resumes from the next chunk.
1240
+ _log(
1241
+ "\ningest_osz: ctrl+c received; in-flight chunk did not commit, "
1242
+ "resume the run to retry it."
1243
+ )
1244
+ return 130
1245
+
1246
+
1247
+ def _run_main(
1248
+ args: argparse.Namespace,
1249
+ repo_root: Path,
1250
+ archives: list[Path],
1251
+ parent_batch_id: str,
1252
+ archives_dir: Path,
1253
+ blobs_dir: Path,
1254
+ all_revisions_root: Path,
1255
+ schemas_dir: Path,
1256
+ indexer_path: Path,
1257
+ had_stale_lock: bool,
1258
+ ) -> int:
1259
+ """Body of ``main`` extracted so the wake-lock context manager wraps every
1260
+ long-running step (GC, hashing pass, chunked ingest) without nesting
1261
+ half the function under an extra indent."""
1262
+
1263
+ schemas = load_schemas(schemas_dir)
1264
+ _log(f"loaded {len(schemas)} table schema(s) from {schemas_dir}")
1265
+
1266
+ # Crash-recovery cleanup runs first; each step is a no-op when the repo is
1267
+ # already clean.
1268
+ # The orphan-tmp-file walk is paranoid crash recovery: it costs ~150
1269
+ # file/s on a HDD spindle (multiple minutes for full-corpus repos).
1270
+ # It's only useful when the previous run might have left in-flight
1271
+ # tmp+rename writes incomplete. With:
1272
+ # - atomic_copy_if_absent and _atomic_write_parquet using tmp+rename
1273
+ # - the indexer's ctrlc::set_handler draining workers on Ctrl+C
1274
+ # - repo_lock's finally unlinking .ingest.lock on every soft exit
1275
+ # a clean shutdown leaves zero orphans. So we only run the walk when
1276
+ # the lock file *survived* the previous run (= hard-killed) or the
1277
+ # user explicitly forces it via --always-gc-tmp-files.
1278
+ if args.gc_tmp_files and (args.always_gc_tmp_files or had_stale_lock):
1279
+ reason = (
1280
+ "forced by --always-gc-tmp-files"
1281
+ if args.always_gc_tmp_files
1282
+ else "previous run left a stale lock"
1283
+ )
1284
+ _log(
1285
+ f"scanning for orphan *.tmp.<pid> files older than "
1286
+ f"{args.gc_tmp_files_age_min} min ({reason})"
1287
+ )
1288
+ # Also walk an archive CAS root that lives outside repo_root.
1289
+ extra_roots = []
1290
+ if archives_dir != repo_root / "archives":
1291
+ extra_roots.append((f"archives ({archives_dir})", archives_dir))
1292
+ gc_summary = cleanup_orphan_tmp_files(
1293
+ repo_root,
1294
+ max_age_seconds=args.gc_tmp_files_age_min * 60,
1295
+ extra_roots=extra_roots,
1296
+ )
1297
+ gc_total = sum(gc_summary.values())
1298
+ _log(f" removed {gc_total} orphan tmp file(s) ({gc_summary})")
1299
+ elif args.gc_tmp_files:
1300
+ _log(
1301
+ "skipping orphan tmp file scan "
1302
+ "(previous run shut down cleanly; pass --always-gc-tmp-files "
1303
+ "to force a paranoid walk)"
1304
+ )
1305
+
1306
+ ar_dir = all_revisions_root / "archive_revisions"
1307
+
1308
+ # Crash-recovery suite. The compact writer only needs orphan parquet
1309
+ # cleanup: any table parquet whose batch_id lacks an archive_revisions
1310
+ # commit marker belongs to an interrupted chunk and must be removed before
1311
+ # retry to avoid duplicate rows.
1312
+ should_run_recovery = had_stale_lock or args.always_crash_recovery
1313
+ if should_run_recovery:
1314
+ recovery_reason = (
1315
+ "forced by --always-crash-recovery"
1316
+ if args.always_crash_recovery
1317
+ else "previous run left a stale lock"
1318
+ )
1319
+ _log(f"running crash-recovery suite ({recovery_reason})")
1320
+
1321
+ if args.cleanup_orphan_parquets:
1322
+ _log("scanning all_revisions/ for orphan parquet files")
1323
+ committed = committed_batch_ids(ar_dir)
1324
+ orphan_summary = cleanup_orphan_parquets(
1325
+ all_revisions_root, committed
1326
+ )
1327
+ orphan_total = sum(orphan_summary.values())
1328
+ _log(
1329
+ f" removed {orphan_total} orphan parquet(s) "
1330
+ f"({len(orphan_summary)} table(s); "
1331
+ f"{len(committed)} committed batch_id(s))"
1332
+ )
1333
+ else:
1334
+ _log(
1335
+ "skipping crash-recovery suite "
1336
+ "(previous run shut down cleanly; pass --always-crash-recovery "
1337
+ "to force orphan-parquet cleanup)"
1338
+ )
1339
+
1340
+ # Hash each input archive and partition into (to-ingest, already-done,
1341
+ # duplicate) so two copies of the same .osz can't produce duplicate
1342
+ # archive_revisions rows in one chunk and a resumed run skips committed
1343
+ # archives without re-running the indexer on them.
1344
+ if args.skip_already_ingested:
1345
+ known = already_ingested_shas(ar_dir)
1346
+ if known:
1347
+ _log(
1348
+ f"hashing {len(archives):,} input(s) against "
1349
+ f"{len(known):,} known archive_sha256(s)"
1350
+ )
1351
+ else:
1352
+ _log(
1353
+ f"hashing {len(archives):,} input(s) (dedup-only; "
1354
+ f"no committed archives yet)"
1355
+ )
1356
+ cache_path = (
1357
+ _archive_sha_cache_path(repo_root) if args.archive_sha_cache else None
1358
+ )
1359
+ archives, already_done, duplicates = filter_already_ingested(
1360
+ archives, known, cache_path=cache_path
1361
+ )
1362
+ if already_done:
1363
+ _log(f" skipped {len(already_done):,} already-ingested archive(s)")
1364
+ if duplicates:
1365
+ _log(
1366
+ f" warning: dropped {len(duplicates):,} duplicate input archive(s) "
1367
+ f"(same content SHA-256 as another input). First few:"
1368
+ )
1369
+ for dup, kept in duplicates[:5]:
1370
+ try:
1371
+ dup_rel = dup.relative_to(repo_root)
1372
+ except ValueError:
1373
+ dup_rel = dup
1374
+ try:
1375
+ kept_rel = kept.relative_to(repo_root)
1376
+ except ValueError:
1377
+ kept_rel = kept
1378
+ _log(f" {dup_rel} == {kept_rel}")
1379
+ if len(duplicates) > 5:
1380
+ _log(f" ... and {len(duplicates) - 5} more")
1381
+ if not archives:
1382
+ _log("all input archives are already ingested; nothing to do")
1383
+ return 0
1384
+
1385
+ if not args.dry_run:
1386
+ existing_batches = committed_batch_ids_for_parent(ar_dir, parent_batch_id)
1387
+ if existing_batches:
1388
+ preview = ", ".join(existing_batches[:5])
1389
+ if len(existing_batches) > 5:
1390
+ preview += f", ... ({len(existing_batches)} total)"
1391
+ raise RuntimeError(
1392
+ f"ingest_batch_id {parent_batch_id!r} already has committed "
1393
+ f"archive_revisions parquet(s): {preview}. Refusing to ingest "
1394
+ "new archives with a reused batch id because it would overwrite "
1395
+ "existing part-<batch>.parquet files. Choose a fresh BATCH_ID."
1396
+ )
1397
+
1398
+ chunk_size = max(1, args.chunk_size)
1399
+ chunks = [archives[i : i + chunk_size] for i in range(0, len(archives), chunk_size)]
1400
+ multi_chunk = len(chunks) > 1
1401
+
1402
+ _log(
1403
+ f"ingest_osz: {len(archives)} archive(s); repo={repo_root}; "
1404
+ f"parent_batch={parent_batch_id}; "
1405
+ f"{len(chunks)} chunk(s) of up to {chunk_size}; dry_run={args.dry_run}"
1406
+ )
1407
+
1408
+ overall_start = time.perf_counter()
1409
+ cumulative_archives = 0
1410
+ total_archives = len(archives)
1411
+ chunk_summaries: list[dict] = []
1412
+ for chunk_idx, chunk in enumerate(chunks):
1413
+ if multi_chunk:
1414
+ chunk_batch_id = f"{parent_batch_id}-chunk-{chunk_idx:04d}"
1415
+ else:
1416
+ chunk_batch_id = parent_batch_id
1417
+
1418
+ # Per-chunk NDJSON path (suffixed when multi-chunk so retained traces don't clobber).
1419
+ if args.keep_ndjson is not None:
1420
+ if multi_chunk:
1421
+ keep_ndjson = args.keep_ndjson.with_suffix(
1422
+ f".chunk-{chunk_idx:04d}{args.keep_ndjson.suffix}"
1423
+ )
1424
+ else:
1425
+ keep_ndjson = args.keep_ndjson
1426
+ else:
1427
+ keep_ndjson = None
1428
+
1429
+ _log(
1430
+ f"\n[{chunk_idx + 1}/{len(chunks)}] chunk_batch_id={chunk_batch_id} "
1431
+ f"({len(chunk)} archive(s))"
1432
+ )
1433
+
1434
+ summary = _process_chunk(
1435
+ chunk=chunk,
1436
+ chunk_batch_id=chunk_batch_id,
1437
+ args=args,
1438
+ indexer_path=indexer_path,
1439
+ schemas=schemas,
1440
+ repo_root=repo_root,
1441
+ archives_dir=archives_dir,
1442
+ blobs_dir=blobs_dir,
1443
+ all_revisions_root=all_revisions_root,
1444
+ keep_ndjson=keep_ndjson,
1445
+ )
1446
+ chunk_summaries.append(summary)
1447
+ cumulative_archives += len(chunk)
1448
+
1449
+ if not args.dry_run:
1450
+ elapsed = time.perf_counter() - overall_start
1451
+ rate = cumulative_archives / elapsed if elapsed > 0 else 0.0
1452
+ remaining = max(total_archives - cumulative_archives, 0)
1453
+ eta_seconds = remaining / rate if rate > 0 else 0.0
1454
+ wall = summary.get("wall_seconds", 0.0)
1455
+ ndjson_b = summary.get("ndjson_bytes", 0)
1456
+ pct = 100.0 * cumulative_archives / total_archives if total_archives else 100.0
1457
+ _log(
1458
+ f" chunk {chunk_idx + 1}/{len(chunks)} done in "
1459
+ f"{_format_duration(wall)} | "
1460
+ f"{cumulative_archives:,}/{total_archives:,} ({pct:.1f}%) | "
1461
+ f"{rate:.2f} ar/s | ETA {_format_duration(eta_seconds)}"
1462
+ )
1463
+ _log(
1464
+ f" timings: indexer {summary.get('indexer_seconds', 0):.1f}s | "
1465
+ f"group {summary.get('group_seconds', 0):.1f}s | "
1466
+ f"parquet {summary.get('parquet_seconds', 0):.1f}s | "
1467
+ f"ar-commit {summary.get('ar_commit_seconds', 0):.1f}s"
1468
+ )
1469
+ _log(
1470
+ f" output: {summary.get('written_files', 0)} all_rev parquet(s), "
1471
+ f"AR={summary.get('archive_revisions_committed', 0)}, "
1472
+ f"NDJSON={_format_size(ndjson_b)} "
1473
+ f"({summary.get('n_rows', 0):,} rows)"
1474
+ )
1475
+
1476
+ overall_elapsed = time.perf_counter() - overall_start
1477
+ if cumulative_archives:
1478
+ overall_rate = cumulative_archives / overall_elapsed if overall_elapsed > 0 else 0.0
1479
+ _log(
1480
+ f"\ningest_osz: done. {len(chunks)} chunk(s), "
1481
+ f"{cumulative_archives:,} archive(s) in "
1482
+ f"{_format_duration(overall_elapsed)} "
1483
+ f"({overall_rate:.2f} ar/s)."
1484
+ )
1485
+ else:
1486
+ _log(f"\ningest_osz: done. {len(chunks)} chunk(s) processed.")
1487
+ return 0
1488
+
1489
+
1490
+ if __name__ == "__main__":
1491
+ raise SystemExit(main())
scripts/update_maps_v1.sh CHANGED
@@ -54,6 +54,21 @@ cleanup_stale_lock_file() {
54
  fi
55
  }
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  cleanup_stale_lock_file "${STATE_DB}.run.lock" "fetcher"
58
  cleanup_stale_lock_file ".ingest.lock" "ingest"
59
 
@@ -142,6 +157,8 @@ fi
142
  mkdir -p "$INPUT_DIR"
143
 
144
  if [ "$FETCH" = "1" ]; then
 
 
145
  enumerate_args=(--statuses "$STATUSES" --mode "$MODE")
146
  if [ "${ENUMERATE_FULL_RESCAN:-0}" = "1" ]; then
147
  enumerate_args+=(--full-rescan)
@@ -196,6 +213,8 @@ input_count="$(find "$INPUT_DIR" -type f -name '*.osz' | wc -l)"
196
  echo "input_archive_count=${input_count}"
197
 
198
  if [ "$input_count" -gt 0 ]; then
 
 
199
  "$PYTHON" python/ingest_osz.py "$INPUT_DIR" \
200
  --repo-root . \
201
  --rosu-indexer "$INDEXER" \
@@ -209,7 +228,7 @@ if [ "$input_count" -gt 0 ]; then
209
  "$PYTHON" python/rebuild_latest_snapshot.py --repo-root . --workers "$LATEST_REBUILD_WORKERS"
210
  "$PYTHON" python/validate_compact_v1.py --repo-root . --max-data-files 10000
211
 
212
- batch_archive_paths="$("$PYTHON" python/list_batch_archives.py --repo-root . --batch-id "$BATCH_ID" | wc -l | tr -d ' ')"
213
  echo "batch_archive_paths=${batch_archive_paths}"
214
  else
215
  batch_archive_paths=0
 
54
  fi
55
  }
56
 
57
+ batch_archive_path_count() {
58
+ "$PYTHON" python/list_batch_archives.py --repo-root . --batch-id "$BATCH_ID" | wc -l | tr -d ' '
59
+ }
60
+
61
+ refuse_reused_batch_id_for_ingest() {
62
+ local count
63
+ count="$(batch_archive_path_count)"
64
+ if [ "$count" -gt 0 ]; then
65
+ echo "BATCH_ID=${BATCH_ID} already has ${count} committed archive path(s)." >&2
66
+ echo "Refusing to fetch or ingest with a reused batch id because it can overwrite existing part-${BATCH_ID}.parquet files." >&2
67
+ echo "Choose a fresh BATCH_ID, for example: BATCH_ID=update-v1-\$(date -u +%Y%m%dT%H%M%SZ)" >&2
68
+ exit 64
69
+ fi
70
+ }
71
+
72
  cleanup_stale_lock_file "${STATE_DB}.run.lock" "fetcher"
73
  cleanup_stale_lock_file ".ingest.lock" "ingest"
74
 
 
157
  mkdir -p "$INPUT_DIR"
158
 
159
  if [ "$FETCH" = "1" ]; then
160
+ refuse_reused_batch_id_for_ingest
161
+
162
  enumerate_args=(--statuses "$STATUSES" --mode "$MODE")
163
  if [ "${ENUMERATE_FULL_RESCAN:-0}" = "1" ]; then
164
  enumerate_args+=(--full-rescan)
 
213
  echo "input_archive_count=${input_count}"
214
 
215
  if [ "$input_count" -gt 0 ]; then
216
+ refuse_reused_batch_id_for_ingest
217
+
218
  "$PYTHON" python/ingest_osz.py "$INPUT_DIR" \
219
  --repo-root . \
220
  --rosu-indexer "$INDEXER" \
 
228
  "$PYTHON" python/rebuild_latest_snapshot.py --repo-root . --workers "$LATEST_REBUILD_WORKERS"
229
  "$PYTHON" python/validate_compact_v1.py --repo-root . --max-data-files 10000
230
 
231
+ batch_archive_paths="$(batch_archive_path_count)"
232
  echo "batch_archive_paths=${batch_archive_paths}"
233
  else
234
  batch_archive_paths=0