"""JSON and JSONL I/O helpers.""" import json import hashlib import os from pathlib import Path import tempfile from typing import TypeVar, Type from pydantic import BaseModel T = TypeVar("T", bound=BaseModel) def sha256_file(path: Path) -> str: """Hash files in bounded memory, including transferable image payloads.""" digest = hashlib.sha256() with Path(path).open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def append_jsonl(path: Path, item: BaseModel) -> None: """Append a single Pydantic model as one JSON line.""" with open(path, "a") as f: f.write(item.model_dump_json() + "\n") def write_jsonl(path: Path, items: list[BaseModel]) -> None: """Write multiple Pydantic models as JSONL (append mode).""" with open(path, "a") as f: for item in items: f.write(item.model_dump_json() + "\n") def write_jsonl_atomic(path: Path, items: list[BaseModel]) -> None: """Replace a JSONL artifact atomically rather than appending to it.""" path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) temporary_path = Path(temporary) try: os.fchmod(fd, 0o644) with os.fdopen(fd, "w") as f: for item in items: f.write(item.model_dump_json() + "\n") f.flush() os.fsync(f.fileno()) os.replace(temporary_path, path) except BaseException: temporary_path.unlink(missing_ok=True) raise def read_jsonl(path: Path, model_class: Type[T]) -> list[T]: """Read a JSONL file and validate each line as a Pydantic model.""" items: list[T] = [] with open(path) as f: for line in f: line = line.strip() if line: items.append(model_class.model_validate_json(line)) return items def write_json(path: Path, data: dict | BaseModel) -> None: """Write a dict or Pydantic model to a JSON file.""" with open(path, "w") as f: if isinstance(data, BaseModel): f.write(data.model_dump_json(indent=2)) else: json.dump(data, f, indent=2, default=str) def write_json_atomic(path: Path, data: dict | BaseModel) -> None: """Write JSON via an adjacent temporary file, then atomically replace it.""" path.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) temporary_path = Path(temporary) try: # ``mkstemp`` deliberately starts at 0600. Result manifests are moved # between a root-run Docker container and the unprivileged host user, # so retain the normal JSON-file readability of ``open(..., "w")``. os.fchmod(fd, 0o644) with os.fdopen(fd, "w") as f: if isinstance(data, BaseModel): f.write(data.model_dump_json(indent=2)) else: json.dump(data, f, indent=2, default=str) f.flush() os.fsync(f.fileno()) os.replace(temporary_path, path) except BaseException: temporary_path.unlink(missing_ok=True) raise def read_json(path: Path) -> dict: """Read a JSON file and return as dict.""" with open(path) as f: return json.load(f)