File size: 7,143 Bytes
c5f5de4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fetch pinned public sources, verify publisher checksums and unpack datapacks."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import stat
import tarfile
import tempfile
import zipfile

from huggingface_hub import HfApi, snapshot_download

HF_SOURCES = {
    "openrca_v1": ("cdreetz/OpenRCA", "7a29a7c3600cc07b7760a6c5097d36ac8573f039"),
    "openrca_v2": ("anon-ops/ops-lite", "9ac09981c08ab02a0b923eab7830d778934851a8"),
    "propagation_bench": ("PolarBear2026/RCABench", "d107acb13481c5c72e4001c81f3ce5ed378e3410"),
}
ZENODO_MD5 = {
    "rcabench-absolute_anomaly.tar.gz": "96d32ae290e06be7d4e251be02b36cb8",
    "rcabench-fse-26.zip": "51b80c5d7b79c67e531c2639ec43412f",
    "rcabench-platform-feat-fse26.zip": "b363d3a0fff3a1047c907648afbe8575",
}
V1_FILES = ("*.csv", "*.xlsx")


def file_digest(path, algorithm, prefix=b""):
    digest = hashlib.new(algorithm)
    digest.update(prefix)
    with path.open("rb") as handle:
        while block := handle.read(8 * 1024 * 1024):
            digest.update(block)
    return digest.hexdigest()


def safe_path(root, name):
    path = PurePosixPath(name)
    if path.is_absolute() or ".." in path.parts or "\\" in name:
        raise ValueError(f"Invalid archive path: {name}")
    return root.joinpath(*path.parts)


def extract(archive, destination):
    if destination.is_dir():
        return sum(p.is_file() for p in destination.rglob("*"))
    with tempfile.TemporaryDirectory(dir=destination.parent, prefix=".extract-") as tmp:
        staging = Path(tmp) / "data"
        staging.mkdir()
        count = 0
        if archive.suffix == ".zip":
            with zipfile.ZipFile(archive) as zipped:
                for info in zipped.infolist():
                    path = safe_path(staging, info.filename)
                    kind = stat.S_IFMT(info.external_attr >> 16)
                    if info.is_dir():
                        path.mkdir(parents=True, exist_ok=True)
                    elif kind in (0, stat.S_IFREG):
                        path.parent.mkdir(parents=True, exist_ok=True)
                        with zipped.open(info) as src, path.open("xb") as dst:
                            shutil.copyfileobj(src, dst)
                        count += 1
                    else:
                        raise ValueError(f"Unsupported ZIP entry: {info.filename}")
        else:
            with tarfile.open(archive, mode="r|gz") as tar:
                for info in tar:
                    path = safe_path(staging, info.name)
                    if info.isdir():
                        path.mkdir(parents=True, exist_ok=True)
                    elif info.isfile():
                        path.parent.mkdir(parents=True, exist_ok=True)
                        with tar.extractfile(info) as src, path.open("xb") as dst:
                            shutil.copyfileobj(src, dst, 1024 * 1024)
                        count += 1
                    else:
                        raise ValueError(f"Unsupported TAR entry: {info.name}")
        staging.rename(destination)
    return count


def verify_hub(directory, dataset, metadata=None):
    repo, revision = HF_SOURCES[dataset]
    if metadata:
        data = json.loads(Path(metadata).read_text())
        if data["id"] != repo or data["sha"] != revision:
            raise ValueError("Metadata does not match pinned source")
        entries = [(x["rfilename"], x.get("size"), x.get("lfs") or {}, x.get("blobId"))
                   for x in data["siblings"]]
    else:
        info = HfApi().dataset_info(repo, revision=revision, files_metadata=True)
        entries = [(x.rfilename, x.size, {"sha256": x.lfs.sha256} if x.lfs else {}, x.blob_id)
                   for x in info.siblings]
    count = size = 0
    for name, expected_size, lfs, blob in entries:
        if dataset == "openrca_v1" and not name.endswith((".csv", ".xlsx")):
            continue
        path = safe_path(directory, name)
        if not path.is_file() or path.stat().st_size != expected_size:
            raise ValueError(f"Missing file or size mismatch: {name}")
        algorithm = "sha256" if lfs else "sha1"
        expected = lfs.get("sha256", blob)
        prefix = b"" if lfs else f"blob {expected_size}\0".encode()
        if file_digest(path, algorithm, prefix) != expected:
            raise ValueError(f"Integrity check failed: {name}")
        count += 1
        size += expected_size
    return {"repo": repo, "revision": revision, "verified_files": count, "verified_bytes": size}


def verify_propagation(directory):
    files = {}
    for name, checksum in ZENODO_MD5.items():
        archive = directory / "archives" / name
        if file_digest(archive, "md5") != checksum:
            raise ValueError(f"Zenodo MD5 mismatch for {name}")
        destination = "datapacks" if name.endswith(".tar.gz") else archive.stem
        files[name] = {
            "md5": checksum,
            "bytes": archive.stat().st_size,
            "extracted_files": extract(archive, directory / destination),
        }
    repo, revision = HF_SOURCES["propagation_bench"]
    datapacks = directory / "datapacks"
    markers = ("injection.json", "env.json", "normal_traces.parquet", "abnormal_traces.parquet")
    cases = {entry.parent for name in markers for entry in datapacks.rglob(name)}
    invalid = sum((case / ".invalid").is_file() for case in cases)
    return {"doi": "10.5281/zenodo.17105974", "mirror": repo, "revision": revision,
            "archives": files, "archived_cases": len(cases),
            "publisher_marked_invalid_cases": invalid, "eligible_cases": len(cases) - invalid}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("dataset", choices=HF_SOURCES)
    parser.add_argument("--storage-root", type=Path, required=True)
    parser.add_argument("--jobs", type=int, default=24)
    parser.add_argument("--verify-only", action="store_true")
    parser.add_argument("--metadata", type=Path, help="Cached Hub metadata with files_metadata enabled")
    args = parser.parse_args()
    directory = args.storage_root / "datasets_raw" / args.dataset
    directory.mkdir(parents=True, exist_ok=True)
    repo, revision = HF_SOURCES[args.dataset]
    if not args.verify_only:
        archive = args.dataset == "propagation_bench"
        patterns = list(ZENODO_MD5) if archive else V1_FILES if args.dataset == "openrca_v1" else None
        snapshot_download(repo, repo_type="dataset", revision=revision, max_workers=args.jobs,
                          local_dir=directory / "archives" if archive else directory,
                          allow_patterns=patterns)
    proof = verify_propagation(directory) if args.dataset == "propagation_bench" else (
        verify_hub(directory, args.dataset, args.metadata)
    )
    with tempfile.NamedTemporaryFile(dir=directory, mode="w", delete=False) as handle:
        json.dump(proof, handle, indent=2)
        handle.write("\n")
    os.replace(handle.name, directory / ".verified.json")
    print(json.dumps(proof), flush=True)


if __name__ == "__main__":
    main()