sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
6.49 kB
"""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