File size: 5,417 Bytes
c8beaf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Read-only verification of fixed Hugging Face dependency objects."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import urllib.parse
import urllib.request
from pathlib import Path


def read_tsv(path: Path) -> list[dict[str, str]]:
    with path.open("r", encoding="utf-8", newline="") as handle:
        return list(csv.DictReader(handle, delimiter="\t"))


def fetch_tree(repo: str, revision: str) -> dict[str, dict[str, object]]:
    encoded = urllib.parse.quote(repo, safe="/")
    rev = urllib.parse.quote(revision, safe="")
    url = f"https://huggingface.co/api/datasets/{encoded}/tree/{rev}?recursive=true&expand=true"
    with urllib.request.urlopen(url, timeout=60) as response:
        rows = json.load(response)
    return {str(row["path"]): row for row in rows if row.get("type") == "file"}


def full_remote_sha(repo: str, revision: str, path: str) -> str:
    url = (
        f"https://huggingface.co/datasets/{repo}/resolve/{revision}/"
        f"{urllib.parse.quote(path)}?download=true"
    )
    digest = hashlib.sha256()
    with urllib.request.urlopen(url, timeout=60) as response:
        while True:
            chunk = response.read(8 * 1024 * 1024)
            if not chunk:
                break
            digest.update(chunk)
    return digest.hexdigest()


def range_remote_sha(repo: str, revision: str, path: str, start: int, end: int) -> str:
    url = (
        f"https://huggingface.co/datasets/{repo}/resolve/{revision}/"
        f"{urllib.parse.quote(path)}?download=true"
    )
    request = urllib.request.Request(url, headers={"Range": f"bytes={start}-{end}"})
    with urllib.request.urlopen(request, timeout=60) as response:
        if response.status != 206:
            raise ValueError(f"server did not honor byte range: HTTP {response.status}")
        payload = response.read()
    if len(payload) != end - start + 1:
        raise ValueError(f"range length mismatch: {len(payload)} != {end - start + 1}")
    return hashlib.sha256(payload).hexdigest()


def main() -> int:
    default = Path(__file__).resolve().parents[1] / "dependencies" / "DEPENDENCIES.tsv"
    parser = argparse.ArgumentParser()
    parser.add_argument("--dependencies", type=Path, default=default)
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    rows = read_tsv(args.dependencies)
    trees: dict[tuple[str, str], dict[str, dict[str, object]]] = {}
    results: list[dict[str, object]] = []
    failed = 0
    for row in rows:
        key = (row["source_repo"], row["source_revision"])
        if key not in trees:
            trees[key] = fetch_tree(*key)
        remote = trees[key].get(row["repository_path"])
        status = "PASS"
        method = "lfs_oid"
        detail = ""
        if remote is None:
            status, detail = "FAIL", "path missing"
        elif int(remote.get("size", -1)) != int(row["bytes"]):
            status, detail = "FAIL", f"size {remote.get('size')} != {row['bytes']}"
        elif remote.get("lfs"):
            oid = str(remote["lfs"].get("oid", ""))
            if oid != row["sha256"]:
                status, detail = "FAIL", f"LFS oid {oid} != expected SHA-256"
        elif int(row["bytes"]) <= 20_000_000:
            method = "full_download_sha256"
            actual = full_remote_sha(row["source_repo"], row["source_revision"], row["repository_path"])
            if actual != row["sha256"]:
                status, detail = "FAIL", f"SHA-256 {actual} != expected"
        elif row.get("range_bytes") and row.get("range_first_sha256") and row.get("range_last_sha256"):
            method = "fixed_range_sha256"
            width = int(row["range_bytes"])
            total = int(row["bytes"])
            try:
                first = range_remote_sha(
                    row["source_repo"], row["source_revision"], row["repository_path"], 0, width - 1
                )
                last = range_remote_sha(
                    row["source_repo"],
                    row["source_revision"],
                    row["repository_path"],
                    total - width,
                    total - 1,
                )
                if first != row["range_first_sha256"] or last != row["range_last_sha256"]:
                    status, detail = "FAIL", "fixed-range SHA-256 mismatch"
            except Exception as exc:
                status, detail = "UNRESOLVED", str(exc)
        else:
            method = "metadata_only"
            status, detail = "UNRESOLVED", "no LFS oid and no fixed-range receipt"
        if status == "FAIL":
            failed += 1
        results.append(
            {
                "component": row["component"],
                "path": row["repository_path"],
                "status": status,
                "method": method,
                "detail": detail,
            }
        )
    receipt = {
        "status": "PASS" if failed == 0 else "FAIL",
        "checked": len(results),
        "failed": failed,
        "results": results,
        "service_commitment": "none; this is a manually runnable verification capability",
    }
    text = json.dumps(receipt, indent=2, sort_keys=True) + "\n"
    if args.output:
        args.output.write_text(text, encoding="utf-8")
    print(text, end="")
    return 0 if failed == 0 else 1


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