File size: 6,492 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Builders for stage, resource-snapshot, and dataset manifests.

Every stage output carries ``input_manifest_sha256``, ``code_commit``,
``config_sha256``, and ``created_at`` so that an artifact can be traced to the
exact code, config, and upstream inputs that produced it (``docs/02_DATA_PIPELINE.md``
section 1). Image paths are stored relative to the manifest so outputs reproduce
across mounts.
"""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from .atomic_io import atomic_write_json, count_jsonl, read_jsonl
from .hashing import join_manifest_sha256, sha256_file, sha256_text

# Reserved provenance keys present on every stage manifest.
STAGE_PROVENANCE_KEYS = (
    "input_manifest_sha256",
    "code_commit",
    "config_sha256",
    "created_at",
)


def stage_manifest(
    *,
    stage: str,
    input_manifest_sha256: str | None,
    code_commit: str,
    config_sha256: str,
    created_at: str,
    renderer_version: str | None = None,
    answer_normalizer_version: str | None = None,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build a stage manifest record with required provenance fields.

    ``created_at`` must be supplied by the caller (RFC 3339, UTC preferred) so
    that the pipeline stays deterministic and never relies on wall-clock time
    inside a reproducible stage.
    """
    record: dict[str, Any] = {
        "stage": stage,
        "input_manifest_sha256": input_manifest_sha256,
        "code_commit": code_commit,
        "config_sha256": config_sha256,
        "created_at": created_at,
    }
    if renderer_version is not None:
        record["renderer_version"] = renderer_version
    if answer_normalizer_version is not None:
        record["answer_normalizer_version"] = answer_normalizer_version
    if extra:
        for key, value in extra.items():
            if key in STAGE_PROVENANCE_KEYS:
                raise ValueError(f"extra manifest key collides with reserved key {key!r}")
            record[key] = value
    return record


def input_manifest_hash_from_paths(paths: Iterable[str | Path]) -> str:
    """Hash an ordered set of input artifact files by their per-file SHA-256."""
    return join_manifest_sha256(sha256_file(path) for path in paths)


def input_manifest_hash_from_jsonl(path: str | Path) -> str:
    """Fold every row's ``sha256``/``base_id`` field of a JSONL file into one hash."""
    digests: list[str] = []
    for row in read_jsonl(path):
        digest = row.get("sha256") or row.get("base_id") or row.get("group_id")
        if digest is None:
            raise ValueError(f"row in {path} has no sha256/base_id/group_id field")
        digests.append(str(digest))
    return join_manifest_sha256(digests)


@dataclass(frozen=True)
class FileEntry:
    relative_path: str
    size: int
    sha256: str


def snapshot_file_tree(root: str | Path) -> list[FileEntry]:
    """Return ``{relative_path, size, sha256}`` for every regular file under ``root``.

    Symlinks are resolved to their target's content. Entries are sorted by
    relative path so the snapshot is deterministic.
    """
    root_path = Path(root)
    entries: list[FileEntry] = []
    if not root_path.exists():
        return entries
    for path in sorted(root_path.rglob("*")):
        if not path.is_file():
            continue
        if path.is_symlink():
            target = path.resolve()
            if not target.is_file():
                continue
        relative = path.relative_to(root_path).as_posix()
        entries.append(
            FileEntry(
                relative_path=relative,
                size=path.stat().st_size,
                sha256=sha256_file(path),
            )
        )
    return entries


def resource_snapshot_row(
    *,
    logical_name: str,
    repo_id: str,
    requested_revision: str,
    resolved_commit: str,
    local_path: str,
    downloaded_at: str,
    file_count: int,
    total_bytes: int,
    manifest_sha256: str,
    kind: str = "model",
) -> dict[str, Any]:
    """Build one ``resource_snapshot.jsonl`` row (``docs/01_RESOURCE_CATALOG.md`` §7)."""
    if resolved_commit != requested_revision:
        raise ValueError(
            f"resolved commit {resolved_commit} != requested {requested_revision} "
            f"for {logical_name}; this is a preflight failure"
        )
    return {
        "logical_name": logical_name,
        "kind": kind,
        "repo_id": repo_id,
        "requested_revision": requested_revision,
        "resolved_commit": resolved_commit,
        "local_path": local_path,
        "downloaded_at": downloaded_at,
        "file_count": file_count,
        "total_bytes": total_bytes,
        "manifest_sha256": manifest_sha256,
    }


def file_tree_manifest_sha256(entries: Iterable[FileEntry]) -> str:
    """SHA-256 of the canonical ``relative_path\0size\0sha256`` list (sorted)."""
    payload = "".join(
        f"{e.relative_path}\0{e.size}\0{e.sha256}\n"
        for e in sorted(entries, key=lambda e: e.relative_path)
    )
    return sha256_text(payload)


def artifact_manifest_sha256(path: str | Path) -> str:
    """Hash one file by bytes or one directory by its deterministic file tree."""

    source = Path(path)
    if source.is_file():
        return sha256_file(source)
    if source.is_dir():
        return file_tree_manifest_sha256(snapshot_file_tree(source))
    raise FileNotFoundError(f"artifact does not exist: {source}")


def build_dataset_manifest(
    *,
    dataset_name: str,
    items_path: str | Path,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build a ``<dataset_name>.manifest.json`` summarizing a normalized JSONL file."""
    items_path = Path(items_path)
    record: dict[str, Any] = {
        "dataset_name": dataset_name,
        "items_path": items_path.name,
        "row_count": count_jsonl(items_path),
        "items_sha256": sha256_file(items_path),
    }
    if extra:
        record.update(extra)
    return record


def write_dataset_manifest(
    *,
    output_path: str | Path,
    dataset_name: str,
    items_path: str | Path,
    extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build and atomically write a dataset manifest, returning the record."""
    record = build_dataset_manifest(dataset_name=dataset_name, items_path=items_path, extra=extra)
    atomic_write_json(output_path, record)
    return record