File size: 24,375 Bytes
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d4d2a
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d4d2a
1ec47ac
 
 
 
 
 
 
 
 
c0d4d2a
 
 
 
 
 
 
1ec47ac
 
 
 
c0d4d2a
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d4d2a
1ec47ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/usr/bin/env python3
"""Upload complete event manifests in 50 GB batches; verify before media cleanup.

No token is read from a manifest or command-line argument. HF_TOKEN / standard
huggingface_hub login are the only authentication sources. No remote deletions.
"""
from __future__ import annotations
import argparse
import contextlib
import datetime as dt
import fcntl
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import sqlite3
import sys
import time
import urllib.parse
import urllib.request

KINDS = {"text", "video", "audio", "metadata"}
READY = {"full_av_text_verified", "hq_verified"}
DONE = {"verified", "local_removed"}


def utcnow():
    return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def json_bytes(value):
    return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")


def read_manifests(path):
    path = Path(path).resolve()
    text = path.read_text(encoding="utf-8-sig")
    if path.suffix == ".jsonl":
        items = [json.loads(line) for line in text.splitlines() if line.strip()]
    else:
        value = json.loads(text)
        items = value if isinstance(value, list) else [value]
    for value in items:
        if str(value.get("schema_version")) != "1":
            raise ValueError(f"Unsupported manifest version: {path.name}")
        event_id = value.get("event_id", "")
        if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", event_id):
            raise ValueError("event_id must be a stable path-safe identifier")
        if value.get("quality_status") not in READY:
            raise ValueError(f"Event {event_id} is not complete AV+text: {value.get('quality_status')}")
        assets = value.get("assets", [])
        if not KINDS.issubset({a.get("kind") for a in assets}):
            raise ValueError(f"Event {event_id} requires text, video, audio and metadata")
        seen = set()
        for asset in assets:
            kind = asset.get("kind")
            if kind not in KINDS:
                raise ValueError(f"Unsupported asset kind: {kind}")
            remote = asset.get("remote_path", "")
            parts = PurePosixPath(remote).parts
            if (not remote.startswith(f"data/events/{event_id}/") or ".." in parts
                    or "\\" in remote or PurePosixPath(remote).is_absolute()
                    or not re.fullmatch(r"[A-Za-z0-9_./-]+", remote)):
                raise ValueError(f"Unsafe or mismatched remote path for {event_id}")
            if remote in seen:
                raise ValueError(f"Duplicate remote path in manifest: {remote}")
            seen.add(remote)
            if not re.fullmatch(r"[0-9a-f]{64}", asset.get("sha256", "")):
                raise ValueError(f"A full-file SHA-256 is required: {remote}")
            if isinstance(asset.get("size_bytes"), bool) or not isinstance(asset.get("size_bytes"), int) or asset["size_bytes"] <= 0:
                raise ValueError(f"Positive integer size_bytes required: {remote}")
            local = Path(asset.get("local_path", ""))
            if not asset.get("local_path") or local.suffix in {".part", ".partial", ".tmp"}:
                raise ValueError(f"Incomplete local asset: {remote}")
            local = local if local.is_absolute() else path.parent / local
            yield dict(event_id=event_id, quality_status=value["quality_status"],
                       kind=kind, local_path=str(local.absolute()), remote_path=remote,
                       size_bytes=asset["size_bytes"], sha256=asset["sha256"], manifest_path=str(path))


def open_ledger(path):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    con = sqlite3.connect(path)
    con.row_factory = sqlite3.Row
    con.execute("PRAGMA journal_mode=WAL")
    con.execute("PRAGMA foreign_keys=ON")
    con.executescript("""
    CREATE TABLE IF NOT EXISTS transfer_assets (
      repo_id TEXT NOT NULL, remote_path TEXT NOT NULL, event_id TEXT NOT NULL,
      kind TEXT NOT NULL, local_path TEXT NOT NULL, size_bytes INTEGER NOT NULL,
      sha256 TEXT NOT NULL, quality_status TEXT NOT NULL, manifest_path TEXT NOT NULL,
      state TEXT NOT NULL DEFAULT 'pending', verified_commit TEXT, verification_method TEXT,
      verified_at TEXT, removed_at TEXT,
      PRIMARY KEY(repo_id,remote_path)
    );
    CREATE TABLE IF NOT EXISTS transfer_batches (
      repo_id TEXT NOT NULL, batch_id TEXT NOT NULL, created_at TEXT NOT NULL,
      state TEXT NOT NULL DEFAULT 'planned', commit_sha TEXT, completed_at TEXT,
      last_error_type TEXT, PRIMARY KEY(repo_id,batch_id)
    );
    CREATE TABLE IF NOT EXISTS transfer_batch_items (
      repo_id TEXT NOT NULL,batch_id TEXT NOT NULL,remote_path TEXT NOT NULL,
      PRIMARY KEY(repo_id,batch_id,remote_path)
    );
    """)
    return con


def register(con, repo_id, assets):
    with con:
        for asset in assets:
            old = con.execute("SELECT * FROM transfer_assets WHERE repo_id=? AND remote_path=?",
                              (repo_id, asset["remote_path"])).fetchone()
            if old:
                if any(old[k] != asset[k] for k in ("sha256", "size_bytes", "event_id", "kind")):
                    raise ValueError(f"Immutable asset conflict: {asset['remote_path']}; use a versioned new path")
                con.execute("UPDATE transfer_assets SET local_path=?,manifest_path=? WHERE repo_id=? AND remote_path=?",
                            (asset["local_path"], asset["manifest_path"], repo_id, asset["remote_path"]))
            else:
                fields = ("remote_path", "event_id", "kind", "local_path", "size_bytes", "sha256", "quality_status", "manifest_path")
                con.execute("INSERT INTO transfer_assets(repo_id," + ",".join(fields) + ") VALUES (" + ",".join("?" for _ in range(9)) + ")",
                            [repo_id] + [asset[k] for k in fields])


def pending_groups(con, repo_id):
    rows = [dict(row) for row in con.execute("SELECT * FROM transfer_assets WHERE repo_id=? ORDER BY rowid", (repo_id,))]
    groups = {}
    for row in rows:
        groups.setdefault(row["event_id"], []).append(row)
    return [group for group in groups.values() if any(row["state"] not in DONE for row in group)]


def plan_batches(groups, target_bytes, flush):
    batch, size = [], 0
    for group in groups:
        batch.extend(group)
        size += sum(row["size_bytes"] for row in group)
        if size >= target_bytes:
            yield batch
            batch, size = [], 0
    if batch and flush:
        yield batch


def verify_local(row):
    path = Path(row["local_path"])
    if not path.is_file() or path.is_symlink():
        raise ValueError(f"Local asset absent or symlink: {row['remote_path']}")
    if path.stat().st_size != row["size_bytes"] or sha256_file(path) != row["sha256"]:
        raise ValueError(f"Local full-file checksum mismatch: {row['remote_path']}")


def attr(obj, key, default=None):
    return obj.get(key, default) if isinstance(obj, dict) else getattr(obj, key, default)


def lfs_sha(info):
    # Xet IDs and Git blob IDs are NOT SHA-256 checksums of the file bytes.
    value = attr(attr(info, "lfs", {}) or {}, "sha256")
    return value if isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value) else None


class StripCrossHostAuth(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        nxt = super().redirect_request(req, fp, code, msg, headers, newurl)
        if nxt and urllib.parse.urlsplit(req.full_url).netloc != urllib.parse.urlsplit(newurl).netloc:
            nxt.remove_header("Authorization")
        return nxt


def stream_remote_hash(repo_id, remote_path, revision, token):
    from huggingface_hub import hf_hub_url
    url = hf_hub_url(repo_id, remote_path, repo_type="dataset", revision=revision, endpoint="https://huggingface.co")
    headers = {"Accept-Encoding": "identity", "User-Agent": "PAR-batch-verify/1"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    opener = urllib.request.build_opener(StripCrossHostAuth())
    digest, size = hashlib.sha256(), 0
    with opener.open(urllib.request.Request(url, headers=headers), timeout=120) as response:
        if response.status != 200:
            raise ValueError("Remote verification did not return a whole file")
        for chunk in iter(lambda: response.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
            size += len(chunk)
    return size, digest.hexdigest()


def get_remote_map(api, repo_id, paths, revision):
    result = {}
    for start in range(0, len(paths), 100):
        for item in api.get_paths_info(repo_id, paths[start:start + 100], repo_type="dataset", revision=revision):
            result[attr(item, "path")] = item
    return result


def verify_remote(row, info, api, repo_id, revision):
    if info is None or attr(info, "size") != row["size_bytes"]:
        raise ValueError(f"Remote size mismatch or absent: {row['remote_path']}")
    digest = lfs_sha(info)
    if digest:
        if digest != row["sha256"]:
            raise ValueError(f"Remote LFS SHA-256 mismatch: {row['remote_path']}")
        return "hub_lfs_sha256_and_size"
    size, digest = stream_remote_hash(repo_id, row["remote_path"], revision, api.token)
    if size != row["size_bytes"] or digest != row["sha256"]:
        raise ValueError(f"Remote streamed SHA-256 mismatch: {row['remote_path']}")
    return "remote_full_stream_sha256_and_size"


def batch_record(con, repo_id, rows, receipts_dir):
    public = [{k: row[k] for k in ("event_id", "kind", "remote_path", "size_bytes", "sha256")} for row in rows]
    public.sort(key=lambda row: row["remote_path"])
    batch_id = hashlib.sha256(json_bytes(public)).hexdigest()[:24]
    with con:
        con.execute("INSERT OR IGNORE INTO transfer_batches(repo_id,batch_id,created_at) VALUES(?,?,?)",
                    (repo_id, batch_id, utcnow()))
        con.executemany("INSERT OR IGNORE INTO transfer_batch_items VALUES(?,?,?)", [(repo_id, batch_id, row["remote_path"]) for row in rows])
    created = con.execute("SELECT created_at FROM transfer_batches WHERE repo_id=? AND batch_id=?", (repo_id, batch_id)).fetchone()[0]
    record = {"schema_version": "1", "batch_id": batch_id, "repo_id": repo_id, "created_at": created,
              "event_count": len({row["event_id"] for row in rows}), "total_bytes": sum(row["size_bytes"] for row in rows), "assets": public}
    path = Path(receipts_dir) / f"{batch_id}.manifest.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(json_bytes(record))
    receipt_row = dict(kind="metadata", event_id="batch", local_path=str(path),
                       remote_path=f"manifests/batches/{batch_id}.json", size_bytes=path.stat().st_size, sha256=sha256_file(path))
    return batch_id, record, receipt_row


def upload_batch(con, api, repo_id, rows, revision, receipts_dir, retries):
    from huggingface_hub import CommitOperationAdd
    batch_id, record, receipt_row = batch_record(con, repo_id, rows, receipts_dir)
    all_rows = rows + [receipt_row]
    for attempt in range(1, retries + 1):
        try:
            head = api.repo_info(repo_id, repo_type="dataset", revision=revision).sha
            remote = get_remote_map(api, repo_id, [row["remote_path"] for row in all_rows], head)
            operations = []
            for row in all_rows:
                existing = remote.get(row["remote_path"])
                if existing:
                    # A completed previous commit can be recovered even if its response was lost.
                    verify_remote(row, existing, api, repo_id, head)
                else:
                    verify_local(row)
                    operations.append(CommitOperationAdd(path_in_repo=row["remote_path"], path_or_fileobj=row["local_path"]))
            if operations:
                commit = api.create_commit(repo_id=repo_id, repo_type="dataset", revision=revision,
                                           parent_commit=head, operations=operations,
                                           commit_message=f"Add complete AV+text batch {batch_id} ({record['event_count']} events)")
                head = commit.oid
            remote = get_remote_map(api, repo_id, [row["remote_path"] for row in all_rows], head)
            methods = {}
            for row in all_rows:
                methods[row["remote_path"]] = verify_remote(row, remote.get(row["remote_path"]), api, repo_id, head)
            completed_at = utcnow()
            with con:
                for row in rows:
                    con.execute("UPDATE transfer_assets SET state=CASE WHEN state='local_removed' THEN state ELSE 'verified' END,verified_commit=?,verification_method=?,verified_at=? WHERE repo_id=? AND remote_path=?",
                                (head, methods[row["remote_path"]], completed_at, repo_id, row["remote_path"]))
                con.execute("UPDATE transfer_batches SET state='verified',commit_sha=?,completed_at=?,last_error_type=NULL WHERE repo_id=? AND batch_id=?",
                            (head, completed_at, repo_id, batch_id))
            verification = dict(record, verified_commit=head, verified_at=completed_at, verification_methods=methods)
            (Path(receipts_dir) / f"{batch_id}.verified.json").write_bytes(json_bytes(verification))
            write_event_markers(con, repo_id)
            print(json.dumps({"batch_id": batch_id, "state": "verified", "events": record["event_count"], "bytes": record["total_bytes"], "commit": head}), flush=True)
            return
        except Exception as exc:
            with con:
                con.execute("UPDATE transfer_batches SET state='failed',last_error_type=? WHERE repo_id=? AND batch_id=?", (type(exc).__name__, repo_id, batch_id))
            # Do not emit HTTP exception URLs, signed URL query strings or authentication data.
            print(json.dumps({"batch_id": batch_id, "attempt": attempt, "state": "retrying" if attempt < retries else "failed", "error_type": type(exc).__name__}), file=sys.stderr, flush=True)
            if attempt == retries:
                raise RuntimeError(f"Batch {batch_id} stopped; local files retained; rerun the same command") from None
            time.sleep(min(30, 2 ** attempt))


def recover_verified_receipts(con, repo_id, receipts_dir):
    """Repair a crash after the durable verified DB commit but before JSON receipt write.

    This recovers evidence for an immutable commit already verified in the ledger;
    it is not a fresh network verification of the moving main branch.
    """
    directory = Path(receipts_dir)
    directory.mkdir(parents=True, exist_ok=True)
    batches = con.execute("SELECT * FROM transfer_batches WHERE repo_id=? AND state='verified'", (repo_id,)).fetchall()
    recovered = 0
    for batch in batches:
        if not batch["commit_sha"] or not batch["completed_at"]:
            raise ValueError("Verified batch lacks a pinned commit or verification time")
        path = directory / f"{batch['batch_id']}.verified.json"
        if path.is_file():
            try:
                existing = json.loads(path.read_text(encoding="utf-8"))
                if (existing.get("batch_id") == batch["batch_id"]
                        and existing.get("verified_commit") == batch["commit_sha"]
                        and existing.get("assets")):
                    continue
            except (ValueError, OSError):
                pass
        rows = [dict(row) for row in con.execute(
            "SELECT a.* FROM transfer_batch_items i JOIN transfer_assets a "
            "ON a.repo_id=i.repo_id AND a.remote_path=i.remote_path "
            "WHERE i.repo_id=? AND i.batch_id=? ORDER BY a.remote_path",
            (repo_id, batch["batch_id"]))]
        expected = con.execute("SELECT COUNT(*) FROM transfer_batch_items WHERE repo_id=? AND batch_id=?",
                               (repo_id, batch["batch_id"])).fetchone()[0]
        if not rows or len(rows) != expected or any(row["state"] not in DONE for row in rows):
            raise ValueError("Verified batch ledger is incomplete; refusing receipt recovery")
        public = [{k: row[k] for k in ("event_id", "kind", "remote_path", "size_bytes", "sha256")} for row in rows]
        record = {"schema_version": "1", "batch_id": batch["batch_id"], "repo_id": repo_id,
                  "created_at": batch["created_at"], "event_count": len({row["event_id"] for row in rows}),
                  "total_bytes": sum(row["size_bytes"] for row in rows), "assets": public,
                  "verified_commit": batch["commit_sha"], "verified_at": batch["completed_at"],
                  "verification_methods": {row["remote_path"]: row["verification_method"] for row in rows},
                  "recovered_from_transfer_ledger": True}
        temporary = path.with_suffix(".json.tmp")
        temporary.write_bytes(json_bytes(record))
        temporary.replace(path)
        recovered += 1
    if recovered:
        print(json.dumps({"verified_receipts_recovered": recovered}), flush=True)


def write_event_markers(con, repo_id):
    """Durable per-event receipts, written before any media is deleted."""
    rows = [dict(row) for row in con.execute("SELECT * FROM transfer_assets WHERE repo_id=?", (repo_id,))]
    groups = {}
    for row in rows:
        groups.setdefault(row["event_id"], []).append(row)
    for event_id, group in groups.items():
        if not KINDS.issubset({r["kind"] for r in group}) or any(r["state"] not in DONE for r in group):
            continue
        marker = Path(group[0]["manifest_path"]).parent / "remote_verified.json"
        if marker.exists():
            prior = json.loads(marker.read_text())
            if prior.get("event_id") != event_id:
                marker = marker.with_name(f"{event_id}.remote_verified.json")
        commits = sorted({r["verified_commit"] for r in group})
        receipt = {
            "schema_version": "1", "repo_id": repo_id, "event_id": event_id,
            "all_assets_verified": True, "verified": True, "commit_sha": commits[0] if len(commits) == 1 else None,
            "commit_shas": commits,
            "assets": [{k: r[k] for k in ("kind", "remote_path", "size_bytes", "sha256", "verified_commit", "verification_method", "verified_at")} for r in group]
        }
        marker.parent.mkdir(parents=True, exist_ok=True)
        temp = marker.with_suffix(".json.tmp")
        temp.write_bytes(json_bytes(receipt))
        temp.replace(marker)


def cleanup_verified(con, repo_id, media_root):
    write_event_markers(con, repo_id)
    root = Path(media_root).resolve()
    if not root.is_dir() or root == Path("/"):
        raise ValueError("A specific existing media_root is required")
    rows = [dict(row) for row in con.execute("SELECT * FROM transfer_assets WHERE repo_id=?", (repo_id,))]
    groups = {}
    for row in rows:
        groups.setdefault(row["event_id"], []).append(row)
    count = 0
    already_absent = 0
    for group in groups.values():
        if not KINDS.issubset({row["kind"] for row in group}) or any(row["state"] not in DONE for row in group):
            continue
        for row in group:
            if row["kind"] not in {"video", "audio"} or row["state"] == "local_removed":
                continue
            path = Path(row["local_path"])
            if path.is_symlink() or not path.resolve().is_relative_to(root):
                raise ValueError(f"Refusing cleanup outside media_root: {row['remote_path']}")
            if not path.exists():
                # A new machine may restore remote-only assets without ever
                # downloading them. Do not invent a local deletion timestamp.
                already_absent += 1
                continue
            verify_local(row)  # refuse to delete a modified replacement file
            path.unlink()
            with con:
                con.execute("UPDATE transfer_assets SET state='local_removed',removed_at=? WHERE repo_id=? AND remote_path=?",
                            (utcnow(), repo_id, row["remote_path"]))
            count += 1
    print(json.dumps({"media_files_cleaned": count, "already_absent_verified_media": already_absent}), flush=True)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", action="append", default=[], help="Event JSON, JSON array or JSONL; may repeat")
    parser.add_argument("--manifest-dir", type=Path, help="Recursively find *.manifest.json (event manifests only)")
    parser.add_argument("--repo-id", default="Jiaxuannn/PAR")
    parser.add_argument("--revision", default="main")
    parser.add_argument("--ledger", type=Path, default=Path("state/transfer_ledger.sqlite"))
    parser.add_argument("--receipts-dir", type=Path, default=Path("state/upload_receipts"))
    parser.add_argument("--batch-gb", type=float, default=50.0, help="Decimal GB; whole events can overshoot target")
    parser.add_argument("--flush", action="store_true", help="Also send final underfilled batch explicitly")
    parser.add_argument("--cleanup", action="store_true", help="Remove verified local video/audio only; keep text/metadata/ledger")
    parser.add_argument("--media-root", type=Path, help="Required allowlisted directory for --cleanup")
    parser.add_argument("--dry-run", action="store_true", help="Validate manifests and plan batches; no network or file removal")
    parser.add_argument("--retries", type=int, default=3)
    args = parser.parse_args(argv)
    if args.batch_gb <= 0 or args.retries < 1:
        parser.error("batch-gb and retries must be positive")
    if args.cleanup and not args.media_root:
        parser.error("--cleanup requires --media-root")
    paths = [Path(p) for p in args.manifest]
    if args.manifest_dir:
        paths.extend(sorted(args.manifest_dir.rglob("*.manifest.json")))
    args.ledger.parent.mkdir(parents=True, exist_ok=True)
    lock_path = args.ledger.with_suffix(args.ledger.suffix + ".lock")
    with lock_path.open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            raise RuntimeError("Another uploader is using this ledger") from None
        with contextlib.closing(open_ledger(args.ledger)) as con:
            for path in dict.fromkeys(paths):
                register(con, args.repo_id, list(read_manifests(path)))
            recover_verified_receipts(con, args.repo_id, args.receipts_dir)
            groups = pending_groups(con, args.repo_id)
            batches = list(plan_batches(groups, int(args.batch_gb * 1_000_000_000), args.flush))
            print(json.dumps({"pending_events": len(groups), "pending_bytes": sum(row['size_bytes'] for group in groups for row in group),
                              "batches_ready": len(batches), "flush": args.flush, "dry_run": args.dry_run}), flush=True)
            if args.dry_run:
                for batch in batches:
                    for row in batch:
                        if row["state"] not in DONE:
                            verify_local(row)
                return 0
            if batches:
                from huggingface_hub import HfApi, get_token
                token = get_token()
                if not token:
                    raise RuntimeError("Set HF_TOKEN in the job environment or run hf auth login; never put it in a manifest")
                api = HfApi(endpoint="https://huggingface.co", token=token)
                for batch in batches:
                    upload_batch(con, api, args.repo_id, batch, args.revision, args.receipts_dir, args.retries)
                    if args.cleanup:
                        cleanup_verified(con, args.repo_id, args.media_root)
            elif args.cleanup:
                cleanup_verified(con, args.repo_id, args.media_root)
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except (ValueError, RuntimeError) as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        raise SystemExit(2)