File size: 40,303 Bytes
fcb22db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#!/usr/bin/env python3
"""Publish lossless DROID TAR shards and download subsets. Python >= 3.10."""

from __future__ import annotations

import argparse
from contextlib import contextmanager
import fcntl
import hashlib
import json
import math
import os
from pathlib import Path, PurePosixPath
import shutil
import stat
import sys
import tarfile
import time

GIB = 1024 ** 3
ROOT = Path(__file__).resolve().parent.parent
FORMAT_VERSION = 1
LANGUAGE_KEYS = ("language_instruction", "language_instruction_2", "language_instruction_3")


def log(message):
    print(message, flush=True)


def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def atomic_json(path, value):
    path = Path(path)
    temporary = path.with_name(path.name + ".tmp")
    with temporary.open("wb") as stream:
        stream.write(canonical(value) + b"\n")
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, path)
    descriptor = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


def read_json(path):
    return json.loads(Path(path).read_text(encoding="utf-8"))


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


def safe_id(name):
    if not isinstance(name, str) or not name or name in (".", "..", ".droid_hf_extract"):
        raise ValueError(f"Invalid episode ID: {name!r}")
    if "/" in name or "\\" in name or "\0" in name:
        raise ValueError(f"Unsafe episode ID: {name!r}")
    return name


def signature(info):
    # ctime detects rewrites even when a producer restores the original mtime.
    return (info.st_dev, info.st_ino, info.st_mode, info.st_size,
            info.st_mtime_ns, info.st_ctime_ns)


def tree_entries(root):
    """Yield deterministic directory/file entries; never follow internal links."""
    root = Path(root)

    def visit(path, relative):
        info = path.lstat()
        if not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
            raise ValueError(f"Only regular files and directories are supported: {path}")
        yield path, relative, info
        if stat.S_ISDIR(info.st_mode):
            for child in sorted(path.iterdir(), key=lambda item: item.name):
                yield from visit(child, relative + "/" + child.name)

    yield from visit(root, root.name)


def tar_info(relative, info):
    result = tarfile.TarInfo(relative)
    result.type = tarfile.DIRTYPE if stat.S_ISDIR(info.st_mode) else tarfile.REGTYPE
    result.mode = 0o755 if result.isdir() else 0o644
    result.size = 0 if result.isdir() else info.st_size
    # Canonical headers make interrupted/recreated shards byte-for-byte identical.
    result.uid = result.gid = result.mtime = 0
    result.uname = result.gname = ""
    return result


def inspect_tree(root, include_tar_bytes=True):
    digest = hashlib.sha256()
    size = files = directories = tar_bytes = 0
    for _, relative, info in tree_entries(root):
        digest.update(canonical([relative, signature(info)]) + b"\n")
        if include_tar_bytes:
            member = tar_info(relative, info)
            tar_bytes += len(member.tobuf(format=tarfile.PAX_FORMAT))
            tar_bytes += ((member.size + 511) // 512) * 512
        if stat.S_ISDIR(info.st_mode):
            directories += 1
        else:
            size += info.st_size
            files += 1
    return dict(fingerprint=digest.hexdigest(), bytes=size, file_count=files,
                directory_count=directories, tar_bytes=tar_bytes)


def episode_names(source):
    names = []
    for path in source.iterdir():
        if path.is_symlink() or not path.is_dir():
            raise ValueError(f"Expected an episode directory at source root: {path}")
        names.append(safe_id(path.name))
    if not names:
        raise ValueError(f"No episodes found: {source}")
    return sorted(names)


def archive_size(payload):
    return ((payload + 1024 + tarfile.RECORDSIZE - 1) // tarfile.RECORDSIZE) * tarfile.RECORDSIZE


def make_plan(source, shard_bytes):
    source = Path(source).resolve()
    names = episode_names(source)
    episodes = []
    last_log = time.monotonic()
    for index, name in enumerate(names):
        folder = source / name
        metadata_path = folder / "metadata.json"
        before = signature(metadata_path.lstat())
        metadata = read_json(metadata_path)
        if not isinstance(metadata, dict):
            raise ValueError(f"Expected JSON object: {metadata_path}")
        record = inspect_tree(folder)
        if before != signature(metadata_path.lstat()):
            raise ValueError(f"Source changed during scan: {metadata_path}")
        record.update(episode_id=name, lab=name.split("__", 1)[0],
                      status=metadata.get("status"), frame_count=metadata.get("frame_count"),
                      **{key: metadata.get(key, []) for key in LANGUAGE_KEYS})
        episodes.append(record)
        if time.monotonic() - last_log >= 5 or index + 1 == len(names):
            log(f"[scan] {index + 1}/{len(names)} episodes")
            last_log = time.monotonic()
    if episode_names(source) != names:
        raise ValueError("Episode directory list changed during scan; stop source writers and retry")
    shards = []
    start = payload = 0
    for index, episode in enumerate(episodes):
        if index > start and archive_size(payload + episode["tar_bytes"]) > shard_bytes:
            shards.append(dict(path=f"data/shard-{len(shards):06d}.tar", start=start,
                               stop=index, size=archive_size(payload)))
            start, payload = index, 0
        payload += episode["tar_bytes"]
    shards.append(dict(path=f"data/shard-{len(shards):06d}.tar", start=start,
                       stop=len(episodes), size=archive_size(payload)))
    for shard in shards:
        for episode in episodes[shard["start"]:shard["stop"]]:
            episode["shard"] = shard["path"]
    plan = dict(format_version=FORMAT_VERSION, source=str(source), shard_bytes=shard_bytes,
                episodes=episodes, shards=shards)
    plan["plan_id"] = hashlib.sha256(canonical(plan)).hexdigest()
    return plan


def verify_source(plan):
    source = Path(plan["source"])
    expected = [episode["episode_id"] for episode in plan["episodes"]]
    if episode_names(source) != expected:
        raise ValueError("Source episode list changed; use a new work directory for a new publication")
    last_log = time.monotonic()
    for index, episode in enumerate(plan["episodes"]):
        folder = source / episode["episode_id"]
        if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
            raise ValueError(f"Source changed since planning: {folder}")
        if time.monotonic() - last_log >= 5 or index + 1 == len(expected):
            log(f"[source check] {index + 1}/{len(expected)} episodes")
            last_log = time.monotonic()


def load_or_plan(source, work, shard_bytes):
    path = work / "plan.json"
    if path.exists():
        plan = read_json(path)
        contents = {key: value for key, value in plan.items() if key != "plan_id"}
        if hashlib.sha256(canonical(contents)).hexdigest() != plan.get("plan_id"):
            raise ValueError("plan.json checksum mismatch; do not edit a saved plan")
        if (plan["format_version"] != FORMAT_VERSION or plan["source"] != str(source)
                or plan["shard_bytes"] != shard_bytes):
            raise ValueError("Source/format/shard size differs from saved plan; use a new work directory")
        verify_source(plan)
    else:
        plan = make_plan(source, shard_bytes)
        atomic_json(path, plan)
    return plan


def summarize(plan):
    total = sum(item["size"] for item in plan["shards"])
    log(f"Episodes: {len(plan['episodes']):,}; files: "
        f"{sum(ep['file_count'] for ep in plan['episodes']):,}; "
        f"TAR shards: {len(plan['shards']):,}; TAR total: {total / GIB:.3f} GiB")
    log(f"First: {plan['episodes'][0]['episode_id']}; last: {plan['episodes'][-1]['episode_id']}")


def work_usage(work):
    total = 0
    for current, _, files in os.walk(work, followlinks=False):
        for filename in files:
            path = Path(current) / filename
            try:
                info = path.lstat()
                if stat.S_ISREG(info.st_mode):
                    total += info.st_size
            except FileNotFoundError:  # Xet can rotate its own cache files.
                pass
    return total


def require_space(work, needed, budget, reserve):
    if work_usage(work) + needed > budget:
        raise RuntimeError("Staging budget exhausted (including cache); upload existing shards or increase --max-staging-gib")
    if shutil.disk_usage(work).free < needed + reserve:
        raise RuntimeError("Insufficient free disk space; reserve is controlled by --min-free-gib")


@contextmanager
def work_lock(work):
    work.mkdir(parents=True, exist_ok=True)
    with (work / ".lock").open("a") as stream:
        try:
            fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as exc:
            raise RuntimeError(f"Another process is using {work}") from exc
        yield


def configure_cache(work):
    # Leave HF_HOME/HF_TOKEN_PATH alone so an existing hf login remains usable.
    for variable, directory in (("HF_HUB_CACHE", work / "cache" / "hub"),
                                ("HF_XET_CACHE", work / "cache" / "xet"),
                                ("TMPDIR", work / "tmp")):
        directory.mkdir(parents=True, exist_ok=True)
        os.environ[variable] = str(directory)
    os.environ["HF_XET_CHUNK_CACHE_SIZE_BYTES"] = "0"
    os.environ["HF_XET_SHARD_CACHE_SIZE_LIMIT"] = str(GIB)


class HashWriter:
    def __init__(self, stream):
        self.stream = stream
        self.digest = hashlib.sha256()

    def write(self, data):
        count = self.stream.write(data)
        self.digest.update(data[:count])
        return count


def pack_shard(plan, shard, work, budget, reserve):
    target = work / shard["path"]
    target.parent.mkdir(parents=True, exist_ok=True)
    partial = target.with_suffix(".tar.partial")
    # These are only our own unfinished/generated archives, never source data.
    partial.unlink(missing_ok=True)
    require_space(work, shard["size"], budget, reserve)
    log(f"[pack] {shard['path']} ({shard['size'] / GIB:.3f} GiB)")
    episodes = plan["episodes"][shard["start"]:shard["stop"]]
    with partial.open("wb") as output:
        writer = HashWriter(output)
        with tarfile.open(fileobj=writer, mode="w|", format=tarfile.PAX_FORMAT,
                          bufsize=1024 * 1024) as archive:
            for episode in episodes:
                folder = Path(plan["source"]) / episode["episode_id"]
                if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
                    raise ValueError(f"Source changed: {folder}")
                for path, relative, info in tree_entries(folder):
                    member = tar_info(relative, info)
                    if member.isdir():
                        archive.addfile(member)
                    else:
                        descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
                        with os.fdopen(descriptor, "rb") as stream:
                            if signature(os.fstat(stream.fileno())) != signature(info):
                                raise ValueError(f"Source changed: {path}")
                            archive.addfile(member, stream)
                            if signature(os.fstat(stream.fileno())) != signature(info):
                                raise ValueError(f"Source changed while packing: {path}")
                if inspect_tree(folder, False)["fingerprint"] != episode["fingerprint"]:
                    raise ValueError(f"Source changed while packing: {folder}")
        output.flush()
        os.fsync(output.fileno())
    if partial.stat().st_size != shard["size"]:
        raise ValueError(f"TAR size does not match plan: {partial}")
    os.replace(partial, target)
    return dict(path=shard["path"], size=shard["size"], sha256=writer.digest.hexdigest(),
                episode_count=len(episodes), verified=False)


def get_record(plan, shard, state, work, budget, reserve):
    record = state["shards"].get(shard["path"])
    target = work / shard["path"]
    if record and target.exists():
        if target.stat().st_size != record["size"] or sha256_file(target) != record["sha256"]:
            raise ValueError(f"Local shard is corrupted; remove this generated TAR and rerun: {target}")
        return record
    if target.exists():
        # A crash between rename and state persistence: regenerate, never trust an orphan.
        target.unlink()
    new_record = pack_shard(plan, shard, work, budget, reserve)
    if record and (record["size"], record["sha256"]) != (new_record["size"], new_record["sha256"]):
        raise ValueError(f"Recreated shard differs from saved checksum: {target}")
    state["shards"][shard["path"]] = new_record
    atomic_json(work / "state.json", state)
    return new_record


class Hub:
    """Small transport boundary so publication/recovery can be tested offline."""

    def __init__(self, repo_id, revision=None):
        try:
            from huggingface_hub import HfApi
        except ImportError as exc:
            raise RuntimeError("Install scripts/requirements-droid-hf.txt in Python >= 3.10") from exc
        self.api = HfApi()
        self.repo_id = repo_id
        # Resolve to an immutable commit for reads; CAS parent_commit protects writes.
        self.revision = self.api.repo_info(repo_id, repo_type="dataset", revision=revision).sha

    def files(self, paths):
        result = {}
        for start in range(0, len(paths), 100):
            entries = self.api.get_paths_info(self.repo_id, paths[start:start + 100],
                                              repo_type="dataset", revision=self.revision)
            for entry in entries:
                if not hasattr(entry, "size"):
                    raise ValueError(f"Expected remote file, found directory: {entry.path}")
                lfs = entry.lfs
                sha = (lfs.get("sha256") if isinstance(lfs, dict)
                       else getattr(lfs, "sha256", None))
                result[entry.path] = dict(size=entry.size, sha256=sha)
        return result

    def chunks(self, path):
        from huggingface_hub import hf_hub_url
        from huggingface_hub.utils import build_hf_headers, get_session
        url = hf_hub_url(self.repo_id, path, repo_type="dataset", revision=self.revision)
        session = get_session()
        headers = build_hf_headers()
        if callable(getattr(session, "stream", None)):
            # huggingface_hub 1.x uses httpx.Client.
            with session.stream("GET", url, headers=headers,
                                follow_redirects=True, timeout=120) as response:
                response.raise_for_status()
                yield from response.iter_bytes(chunk_size=4 * 1024 * 1024)
        else:
            # huggingface_hub 0.x uses requests.Session. Its `stream` attribute
            # is a boolean default, not a method; streaming is a GET argument.
            with session.get(url, headers=headers, stream=True,
                             allow_redirects=True, timeout=120) as response:
                response.raise_for_status()
                yield from response.iter_content(chunk_size=4 * 1024 * 1024)

    def read_json(self, path):
        return json.loads(b"".join(self.chunks(path)))

    def commit(self, files, message):
        from huggingface_hub import CommitOperationAdd
        result = self.api.create_commit(
            repo_id=self.repo_id, repo_type="dataset", parent_commit=self.revision,
            operations=[CommitOperationAdd(path_in_repo=path, path_or_fileobj=str(local))
                        for path, local in files.items()], commit_message=message)
        self.revision = result.oid

    def download(self, path, directory):
        return Path(self.api.hf_hub_download(self.repo_id, path, repo_type="dataset",
                                           revision=self.revision, local_dir=directory))


def matches_remote(hub, path, record, remote):
    if remote is None:
        return False
    if remote["size"] != record["size"]:
        raise ValueError(f"Remote size conflict; refusing to overwrite {path}")
    digest = remote.get("sha256")
    if not digest:
        log(f"[verify] Remote SHA-256 unavailable; streaming {path} to hash (no disk copy)")
        hasher = hashlib.sha256()
        count = 0
        for block in hub.chunks(path):
            hasher.update(block)
            count += len(block)
        if count != record["size"]:
            raise ValueError(f"Incomplete remote stream: {path}")
        digest = hasher.hexdigest()
    if digest != record["sha256"]:
        raise ValueError(f"Remote checksum conflict; refusing to overwrite {path}")
    return True


def dataset_readme(plan, complete):
    return ("---\nviewer: false\n---\n\n# DROID episodes\n\n"
            f"Publication status: **{'complete' if complete else 'uploading — do not use yet'}**.\n\n"
            f"{len(plan['episodes']):,} episodes in {len(plan['shards']):,} uncompressed TAR shards. "
            "Episodes are ordered lexicographically by folder name; no episode spans shards.\n\n"
            "All original file contents and directory names are preserved, including RGB, depth, "
            "TCP, actions, observations, calibration and metadata. TAR ownership, permissions "
            "and timestamps are normalized. No image/video re-encoding is performed.\n\n"
            "Use `episodes.jsonl` to map episode IDs to shards and filter language instructions, "
            "lab, status or frame count. `shards.jsonl` provides byte sizes and SHA-256 hashes. "
            "Each TAR extracts to original episode directories. A subset requires only its "
            "corresponding shards, but each selected shard is downloaded in full.\n\n"
            "Download `droid_hf.py` and `requirements-droid-hf.txt` from this repository. "
            "With Python >= 3.10, install the requirements and run:\n\n"
            "```bash\npython droid_hf.py download --repo-id OWNER/DATASET --shards 0-2 "
            "--output-dir ./episodes\n"
            "python droid_hf.py download --repo-id OWNER/DATASET --episodes-file ids.txt "
            "--output-dir ./episodes\n```\n\n"
            "The download command verifies and extracts one shard at a time. "
            "It removes verified local archives after extraction unless `--keep-archives` is set. "
            "Existing differing episode directories are never overwritten.\n")


def write_publication(plan, state, work, complete):
    directory = work / "publication"
    directory.mkdir(exist_ok=True)
    (directory / "README.md").write_text(dataset_readme(plan, complete), encoding="utf-8")
    marker = dict(format_version=FORMAT_VERSION, plan_id=plan["plan_id"],
                  complete=complete, episode_count=len(plan["episodes"]),
                  shard_count=len(plan["shards"]))
    files = {"README.md": directory / "README.md"}
    if complete:
        with (directory / "episodes.jsonl").open("wb") as stream:
            for episode in plan["episodes"]:
                public = {key: value for key, value in episode.items()
                          if key not in ("fingerprint", "tar_bytes")}
                stream.write(canonical(public) + b"\n")
        with (directory / "shards.jsonl").open("wb") as stream:
            for shard in plan["shards"]:
                record = state["shards"][shard["path"]]
                if not record["verified"]:
                    raise ValueError(f"Cannot publish unverified shard: {shard['path']}")
                stream.write(canonical({key: value for key, value in record.items()
                                        if key != "verified"}) + b"\n")
        marker["indexes"] = {}
        for name in ("episodes.jsonl", "shards.jsonl"):
            files[name] = directory / name
            marker["indexes"][name] = dict(size=files[name].stat().st_size,
                                          sha256=sha256_file(files[name]))
        files["droid_hf.py"] = Path(__file__).resolve()
        files["requirements-droid-hf.txt"] = Path(__file__).with_name("requirements-droid-hf.txt")
    atomic_json(directory / "publication.json", marker)
    files["publication.json"] = directory / "publication.json"
    return files


def publish(plan, state, work, hub, budget, reserve, batch_size=8):
    """Only delete archives after remote verification AND durable state persistence."""
    if state.get("repo_id") not in (None, hub.repo_id):
        raise ValueError("This work directory is bound to a different repository")
    marker_info = hub.files(["publication.json"])
    marker = hub.read_json("publication.json") if marker_info else None
    if marker and marker.get("plan_id") != plan["plan_id"]:
        raise ValueError("Remote repository belongs to a different publication plan")
    state["repo_id"] = hub.repo_id
    atomic_json(work / "state.json", state)
    remote = hub.files([shard["path"] for shard in plan["shards"]])
    if not marker:
        if remote or hub.files(["episodes.jsonl", "shards.jsonl"]):
            raise ValueError("Remote dataset has no matching publication marker; use an empty dataset repository")
        hub.commit(write_publication(plan, state, work, False), "Initialize DROID shard publication")
    pending = []
    for shard in plan["shards"]:
        record = state["shards"].get(shard["path"])
        if record and matches_remote(hub, shard["path"], record, remote.get(shard["path"])):
            record["verified"] = True
            atomic_json(work / "state.json", state)
            (work / shard["path"]).unlink(missing_ok=True)
        else:
            if record:
                record["verified"] = False
            pending.append(shard)
    atomic_json(work / "state.json", state)
    if marker and marker.get("complete") and not pending:
        log("All shards already verified remotely; publication is complete.")
        return
    # Restoring a missing remote shard invalidates the previously complete marker.
    if marker and marker.get("complete"):
        hub.commit(write_publication(plan, state, work, False), "Resume incomplete DROID publication")
    offset = 0
    while offset < len(pending):
        batch = []
        for shard in pending[offset:offset + batch_size]:
            target = work / shard["path"]
            if batch and not target.exists() and work_usage(work) + shard["size"] > budget:
                break
            record = get_record(plan, shard, state, work, budget, reserve)
            if matches_remote(hub, shard["path"], record, remote.get(shard["path"])):
                record["verified"] = True
                atomic_json(work / "state.json", state)
                target.unlink(missing_ok=True)
            else:
                batch.append(shard)
            offset += 1
        if not batch:
            continue
        # Account for caches as well as archives. Xet limits are soft; disk reserve
        # and bounded batches leave headroom rather than promising an OS quota.
        require_space(work, 0, budget, reserve)
        log(f"[upload] {len(batch)} shards; staging {work_usage(work) / GIB:.3f} GiB")
        hub.commit({shard["path"]: work / shard["path"] for shard in batch},
                   f"Upload DROID shards {batch[0]['path']} through {batch[-1]['path']}")
        uploaded = hub.files([shard["path"] for shard in batch])
        for shard in batch:
            record = state["shards"][shard["path"]]
            if not matches_remote(hub, shard["path"], record, uploaded.get(shard["path"])):
                raise ValueError(f"Committed shard is not visible remotely: {shard['path']}")
            record["verified"] = True
            atomic_json(work / "state.json", state)
            (work / shard["path"]).unlink()
            log(f"[verified, local TAR removed] {shard['path']}")
    verify_source(plan)
    require_space(work, 0, budget, reserve)
    hub.commit(write_publication(plan, state, work, True), "Complete DROID publication and publish subset indexes")
    log(f"Complete: https://huggingface.co/datasets/{hub.repo_id}")


def validate_archive_path(name):
    path = PurePosixPath(name)
    if (path.is_absolute() or not path.parts or ".." in path.parts
            or "\\" in name or "\0" in name or name.rstrip("/") != path.as_posix()):
        raise ValueError(f"Unsafe archive path: {name!r}")
    safe_id(path.parts[0])
    return path


def content_signature(folder):
    result = []
    for path, relative, info in tree_entries(folder):
        result.append((relative, "directory" if stat.S_ISDIR(info.st_mode) else sha256_file(path)))
    return result


def extract_selected(archive_path, episodes, wanted, output, receipts, save_receipts, shard_hash):
    """Extract into a same-filesystem staging directory before publishing episodes."""
    stage = output / ".droid_hf_extract"
    if stage.is_symlink():
        raise ValueError(f"Refusing extraction through symlink: {stage}")
    if stage.exists():
        owner = stage / ".owner.json"
        if not owner.is_file() or read_json(owner) != {"tool": "droid_hf", "format_version": FORMAT_VERSION}:
            raise ValueError(f"Extraction scratch path already exists and is not owned by this tool: {stage}")
        shutil.rmtree(stage)  # Dedicated scratch tree from our interrupted extraction.
    stage.mkdir()
    atomic_json(stage / ".owner.json", {"tool": "droid_hf", "format_version": FORMAT_VERSION})
    seen = set()
    extracted_bytes = {name: 0 for name in wanted}
    try:
        with tarfile.open(archive_path, "r|") as archive:
            for member in archive:
                path = validate_archive_path(member.name)
                if path.as_posix() in seen:
                    raise ValueError(f"Duplicate TAR member: {member.name}")
                seen.add(path.as_posix())
                if path.parts[0] not in episodes:
                    raise ValueError(f"Unexpected episode in TAR: {member.name}")
                if not (member.isdir() or member.isfile()) or member.issparse():
                    raise ValueError(f"Unsupported TAR member (links/devices forbidden): {member.name}")
                if path.parts[0] not in wanted:
                    continue
                destination = stage.joinpath(*path.parts)
                if member.isdir():
                    destination.mkdir(parents=True, exist_ok=True)
                else:
                    extracted_bytes[path.parts[0]] += member.size
                    if extracted_bytes[path.parts[0]] > episodes[path.parts[0]]["bytes"]:
                        raise ValueError(f"TAR payload exceeds indexed episode size: {path.parts[0]}")
                    destination.parent.mkdir(parents=True, exist_ok=True)
                    with archive.extractfile(member) as source, destination.open("xb") as target:
                        shutil.copyfileobj(source, target, 1024 * 1024)
        for name in sorted(wanted):
            extracted = stage / name
            details = inspect_tree(extracted, False)
            expected = episodes[name]
            for key in ("bytes", "file_count", "directory_count"):
                if details[key] != expected[key]:
                    raise ValueError(f"Extracted {key} differs from index: {name}")
            target = output / name
            if target.is_symlink():
                raise ValueError(f"Refusing to overwrite a symlink: {target}")
            if target.exists():
                if content_signature(target) != content_signature(extracted):
                    raise ValueError(f"Existing episode differs; refusing to overwrite: {target}")
            else:
                os.replace(extracted, target)
            receipts[name] = dict(sha256=shard_hash, fingerprint=inspect_tree(target, False)["fingerprint"])
        # One durable receipt update per shard avoids rewriting a growing 34k-row
        # index once per episode. A crash gap is recovered by content comparison.
        save_receipts()
    finally:
        shutil.rmtree(stage)


def parse_shards(value, count):
    indexes = set()
    for part in value.split(","):
        ends = part.strip().split("-")
        if len(ends) not in (1, 2) or not all(item.isdigit() for item in ends):
            raise ValueError("--shards must look like 0,2,5-8")
        first, last = int(ends[0]), int(ends[-1])
        if first > last or last >= count:
            raise ValueError(f"Shard index out of range: {part} (total {count})")
        indexes.update(range(first, last + 1))
    return indexes


def download_subset(hub, work, output, shard_selection=None, ids_file=None, all_shards=False,
                    keep_archives=False, reserve=5 * GIB):
    marker = hub.read_json("publication.json")
    if marker.get("format_version") != FORMAT_VERSION or not marker.get("complete"):
        raise ValueError("Dataset publication is not complete or uses an unsupported format")
    indexes = {}
    for name in ("episodes.jsonl", "shards.jsonl"):
        path = hub.download(name, work / "indexes")
        expected = marker["indexes"][name]
        if path.stat().st_size != expected["size"] or sha256_file(path) != expected["sha256"]:
            raise ValueError(f"Index checksum mismatch: {name}")
        with path.open(encoding="utf-8") as stream:
            indexes[name] = [json.loads(line) for line in stream if line.strip()]
    shards = indexes["shards.jsonl"]
    episodes = {safe_id(ep["episode_id"]): ep for ep in indexes["episodes.jsonl"]}
    if (len(episodes) != len(indexes["episodes.jsonl"]) or len(episodes) != marker["episode_count"]
            or len(shards) != marker["shard_count"]):
        raise ValueError("Invalid/duplicate index entries")
    for index, shard in enumerate(shards):
        if shard["path"] != f"data/shard-{index:06d}.tar":
            raise ValueError(f"Unexpected shard path: {shard['path']}")
    known_paths = {shard["path"] for shard in shards}
    if any(ep["shard"] not in known_paths for ep in episodes.values()):
        raise ValueError("Episode index references an unknown shard")
    if ids_file is not None:
        wanted = {safe_id(line.strip()) for line in Path(ids_file).read_text(encoding="utf-8").splitlines()
                  if line.strip()}
        if not wanted or wanted - episodes.keys():
            raise ValueError(f"Empty/unknown episode selection: {sorted(wanted - episodes.keys())[:10]}")
        selected_paths = {episodes[name]["shard"] for name in wanted}
    else:
        chosen = set(range(len(shards))) if all_shards else parse_shards(shard_selection, len(shards))
        selected_paths = {shards[index]["path"] for index in chosen}
        wanted = {name for name, ep in episodes.items() if ep["shard"] in selected_paths}
    output.mkdir(parents=True, exist_ok=True)
    receipt_path = work / "downloads.json"
    receipt_state = read_json(receipt_path) if receipt_path.exists() else dict(
        repo_id=hub.repo_id, output=str(output), episodes={})
    if receipt_state["repo_id"] != hub.repo_id or receipt_state["output"] != str(output):
        raise ValueError("Download directory is bound to another repository/output; choose a new --download-dir")
    receipts = receipt_state["episodes"]

    def save():
        atomic_json(receipt_path, receipt_state)

    total = sum(shard["size"] for shard in shards if shard["path"] in selected_paths)
    log(f"Selected {len(wanted)} episodes in {len(selected_paths)} shards ({total / GIB:.3f} GiB before resume skips)")
    # Also protect shared output directories when different download caches are used.
    with work_lock(output):
        for shard in shards:
            if shard["path"] not in selected_paths:
                continue
            members = {name: ep for name, ep in episodes.items() if ep["shard"] == shard["path"]}
            if len(members) != shard["episode_count"]:
                raise ValueError(f"Shard episode count mismatch: {shard['path']}")
            remaining = wanted & members.keys()
            for name in list(remaining):
                receipt = receipts.get(name)
                destination = output / name
                if receipt and receipt["sha256"] == shard["sha256"] and destination.exists():
                    if inspect_tree(destination, False)["fingerprint"] != receipt["fingerprint"]:
                        raise ValueError(f"Downloaded episode changed locally: {destination}")
                    remaining.remove(name)
            if not remaining:
                if not keep_archives:
                    (work / "archives" / shard["path"]).unlink(missing_ok=True)
                log(f"[already extracted] {shard['path']}")
                continue
            extraction_bytes = sum(members[name]["tar_bytes"] if "tar_bytes" in members[name]
                                   else members[name]["bytes"] + 4096 * (members[name]["file_count"]
                                                                       + members[name]["directory_count"])
                                   for name in remaining)
            shared_disk = work.stat().st_dev == output.stat().st_dev
            if shutil.disk_usage(work).free < shard["size"] + reserve + (extraction_bytes if shared_disk else 0):
                raise RuntimeError("Insufficient download disk space")
            if not shared_disk and shutil.disk_usage(output).free < extraction_bytes + reserve:
                raise RuntimeError("Insufficient extraction disk space")
            archive = hub.download(shard["path"], work / "archives")
            if archive.stat().st_size != shard["size"] or sha256_file(archive) != shard["sha256"]:
                raise ValueError(f"Archive checksum mismatch; remove the local archive and rerun: {archive}")
            extract_selected(archive, members, remaining, output, receipts, save, shard["sha256"])
            if not keep_archives:
                archive.unlink()
            log(f"[extracted] {shard['path']}: {len(remaining)} episodes")


def positive_gib(value):
    result = float(value)
    if not math.isfinite(result) or result <= 0:
        raise argparse.ArgumentTypeError("Must be a finite number > 0")
    return max(1, int(result * GIB))


def nonnegative_gib(value):
    result = float(value)
    if not math.isfinite(result) or result < 0:
        raise argparse.ArgumentTypeError("Must be a finite number >= 0")
    return int(result * GIB)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    for command in ("scan", "pack", "upload"):
        sub = commands.add_parser(command)
        sub.add_argument("--source", type=Path, default=ROOT / "droid_episodes")
        sub.add_argument("--shard-size-gib", type=positive_gib, default=2 * GIB)
        if command != "scan":
            sub.add_argument("--work-dir", type=Path, default=Path("/mnt/ssd/phs/droid_hf_upload"))
            sub.add_argument("--max-staging-gib", type=positive_gib, default=32 * GIB)
            sub.add_argument("--min-free-gib", type=nonnegative_gib, default=100 * GIB)
        if command == "pack":
            sub.add_argument("--max-shards", type=int, default=8)
        if command == "upload":
            sub.add_argument("--repo-id", default="", help="Required: OWNER/DATASET (left empty intentionally)")
            sub.add_argument("--batch-size", type=int, default=8, choices=range(1, 9))
    sub = commands.add_parser("download")
    sub.add_argument("--repo-id", default="", help="Required: OWNER/DATASET")
    sub.add_argument("--revision", default=None, help="Optional commit SHA/tag; reads are pinned to one commit")
    sub.add_argument("--output-dir", type=Path, default=Path("droid_episodes_download"))
    sub.add_argument("--download-dir", type=Path, default=Path("droid_download_cache"))
    selection = sub.add_mutually_exclusive_group(required=True)
    selection.add_argument("--shards", help="Zero-based shard numbers, e.g. 0,2,5-8")
    selection.add_argument("--episodes-file", type=Path, help="UTF-8 text file: one original episode ID per line")
    selection.add_argument("--all", action="store_true", help="Explicitly download the complete dataset")
    sub.add_argument("--keep-archives", action="store_true")
    sub.add_argument("--min-free-gib", type=nonnegative_gib, default=5 * GIB)
    args = parser.parse_args(argv)
    try:
        if args.command in ("upload", "download") and (not args.repo_id or len(args.repo_id.split("/")) != 2
                                                       or not all(args.repo_id.split("/"))):
            raise ValueError("Fill in --repo-id OWNER/DATASET; no repository is assumed or created automatically")
        if args.command == "scan":
            summarize(make_plan(args.source, args.shard_size_gib))
            return 0
        if args.command == "download":
            work, output = args.download_dir.resolve(), args.output_dir.resolve()
            if work == output or work in output.parents or output in work.parents:
                raise ValueError("Download cache and output must be separate, non-nested directories")
            with work_lock(work):
                configure_cache(work)
                hub = Hub(args.repo_id, args.revision)
                download_subset(hub, work, output, args.shards, args.episodes_file, args.all,
                                args.keep_archives, args.min_free_gib)
            return 0
        source, work = args.source.resolve(), args.work_dir.resolve()
        if work == source or source in work.parents or work in source.parents:
            raise ValueError("Source and work directory must be separate, non-nested directories")
        if args.command == "pack" and args.max_shards < 1:
            raise ValueError("--max-shards must be positive")
        with work_lock(work):
            require_space(work, 0, args.max_staging_gib, args.min_free_gib)
            # Fail authentication/repository lookup before a potentially long source scan.
            hub = None
            if args.command == "upload":
                configure_cache(work)
                hub = Hub(args.repo_id)
            plan = load_or_plan(source, work, args.shard_size_gib)
            summarize(plan)
            state_path = work / "state.json"
            state = read_json(state_path) if state_path.exists() else dict(plan_id=plan["plan_id"], shards={})
            if state.get("plan_id") != plan["plan_id"]:
                raise ValueError("State and plan belong to different publications")
            if args.command == "upload":
                publish(plan, state, work, hub, args.max_staging_gib, args.min_free_gib, args.batch_size)
            else:
                count = 0
                for shard in plan["shards"]:
                    if state["shards"].get(shard["path"], {}).get("verified"):
                        continue
                    get_record(plan, shard, state, work, args.max_staging_gib, args.min_free_gib)
                    count += 1
                    if count == args.max_shards:
                        break
                log(f"Prepared {count} local shards; no network/upload performed. Work directory: {work}")
        return 0
    except KeyboardInterrupt:
        log("Interrupted. Source files were not changed. Rerun the same command to resume.")
        return 130
    except Exception as exc:
        print(f"ERROR: {exc}\nSource files are never deleted. Fix the error and rerun the same command.", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())