Spaces:
Sleeping

File size: 4,760 Bytes
c995899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bounded local-only evidence loader. Invalid datasets become explicit empty states."""
from dataclasses import dataclass, field
from collections import Counter
import hashlib
import json
from pathlib import Path

from .provenance import source_url
from .validation import EvidenceError, validate_manifest_document, validate_row

DATA_ROOT = Path(__file__).resolve().parents[1] / "data"
MAX_BYTES = 2_000_000


@dataclass
class Catalog:
    manifest: dict = field(default_factory=dict)
    datasets: dict = field(default_factory=dict)
    errors: list[str] = field(default_factory=list)


def read_local(root: Path, relative: str) -> bytes:
    if not isinstance(relative, str) or Path(relative).is_absolute() or ".." in Path(relative).parts:
        raise EvidenceError("Dataset path rejected")
    target = (root / relative).resolve()
    if not target.is_relative_to(root.resolve()) or not target.is_file() or target.stat().st_size > MAX_BYTES:
        raise EvidenceError("Dataset unavailable or exceeds size limit")
    return target.read_bytes()


def strict_json(data):
    def reject_constant(_):
        raise EvidenceError("Non-finite JSON constant")
    def unique_keys(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise EvidenceError("Duplicate JSON key")
            result[key] = value
        return result
    return json.loads(data, parse_constant=reject_constant, object_pairs_hook=unique_keys)


def load_catalog(root: Path = DATA_ROOT) -> Catalog:
    catalog = Catalog()
    try:
        manifest = strict_json(read_local(root, "manifest.json"))
        if manifest.get("schema_version") != 1 or not isinstance(manifest.get("datasets"), list):
            raise EvidenceError("Unsupported catalog schema")
        for key, source in manifest["sources"].items():
            source_url(key, source["commit"], source["version_source"])
        catalog.manifest = manifest
    except (OSError, ValueError, KeyError, TypeError, AttributeError):
        catalog.errors.append("Evidence catalog unavailable or invalid. Awaiting a reviewed publication.")
        return catalog
    for entry in manifest["datasets"]:
        try:
            if entry["format"] != "cuda-rows-jsonl-v1":
                raise EvidenceError("Unsupported dataset format")
            if entry["source_commit"] != manifest["sources"][entry["repository"]]["commit"]:
                raise EvidenceError("Catalog provenance mismatch")
            blobs = {}
            for name, meta in entry["files"].items():
                source_url(entry["repository"], entry["source_commit"], meta["source_file"])
                raw = read_local(root, meta["path"])
                if hashlib.sha256(raw).hexdigest() != meta["sha256"]:
                    raise EvidenceError("Dataset checksum mismatch")
                blobs[name] = raw
            run = strict_json(blobs["baseline-run-manifest.json"])
            machine = strict_json(blobs["machine-manifest.json"])
            validate_manifest_document(run, "run")
            validate_manifest_document(machine, "machine")
            if run["machine_manifest_id"] != machine["manifest_id"]:
                raise EvidenceError("Run and machine identities differ")
            gates = run["gates"]
            if (run["status"] != "complete" or any(gates[k] is not True for k in ("copy_checksum", "kernel_reference", "sanity"))
                    or gates["failed_cells"] or gates["sanity_violations"]):
                raise EvidenceError("Incomplete or failed run")
            lines = blobs["baseline-rows.jsonl"].splitlines()
            if not lines or len(lines) > 5000:
                raise EvidenceError("Empty or oversized row population")
            rows = [validate_row(strict_json(line), run["run_id"]) for line in lines]
            identities = Counter((row["arm"], row["field"]) for row in rows)
            # The producer repeats an identically named control before and after
            # the suite. Preserve both in source order; neither enters a curve.
            for (arm, _), count in identities.items():
                if count > 1 and not (arm in {
                    "copy.h2d.pinned.9950000.control|events",
                    "copy.h2d.pinned.9950000.control|host",
                } and count == 2):
                    raise EvidenceError("Duplicate non-control measurement identity")
            catalog.datasets[entry["id"]] = {"metadata": entry, "run": run, "machine": machine, "rows": rows}
        except (OSError, ValueError, KeyError, TypeError, AttributeError):
            catalog.errors.append("A published dataset failed validation and was withheld. No replacement values were generated.")
    return catalog