"""Crash-resumable, idempotent completion-token accounting.""" from __future__ import annotations import json from collections.abc import Iterable from dataclasses import dataclass from pathlib import Path from typing import Any from ..atomic_io import atomic_write_json from ..hashing import canonical_json_hash, is_sha256 class LedgerError(RuntimeError): """Raised on cap overflow, identity drift, or corrupted resume state.""" @dataclass(frozen=True) class CompletionEntry: completion_id: str token_count: int slot_id: str | None = None generation_index: int | None = None completion_sha256: str | None = None def to_dict(self) -> dict[str, Any]: row: dict[str, Any] = { "completion_id": self.completion_id, "token_count": self.token_count, } if self.slot_id is not None: row["slot_id"] = self.slot_id if self.generation_index is not None: row["generation_index"] = self.generation_index if self.completion_sha256 is not None: row["completion_sha256"] = self.completion_sha256 return row def completion_id(run_id: str, slot_id: str, generation_index: int) -> str: if not run_id or not slot_id: raise LedgerError("run_id and slot_id must be non-empty") if ( isinstance(generation_index, bool) or not isinstance(generation_index, int) or generation_index < 0 ): raise LedgerError("generation_index must be a non-negative integer") return canonical_json_hash( { "schema_version": 1, "run_id": run_id, "slot_id": slot_id, "generation_index": generation_index, } ) class CompletionTokenLedger: """Idempotent ledger whose state can be atomically checkpointed and resumed.""" SCHEMA_VERSION = 1 def __init__( self, *, run_id: str, max_tokens: int, config_sha256: str | None = None, data_manifest_sha256: str | None = None, comparison_slot_manifest_sha256: str | None = None, ) -> None: if not run_id: raise LedgerError("run_id must be non-empty") if isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens <= 0: raise LedgerError("max_tokens must be a positive integer") for name, value in ( ("config_sha256", config_sha256), ("data_manifest_sha256", data_manifest_sha256), ("comparison_slot_manifest_sha256", comparison_slot_manifest_sha256), ): if value is not None and not is_sha256(value): raise LedgerError(f"{name} is not a SHA-256") self.run_id = run_id self.max_tokens = max_tokens self.config_sha256 = config_sha256 self.data_manifest_sha256 = data_manifest_sha256 self.comparison_slot_manifest_sha256 = comparison_slot_manifest_sha256 self._entries: dict[str, CompletionEntry] = {} self._consumed = 0 @property def consumed_tokens(self) -> int: return self._consumed @property def remaining_tokens(self) -> int: return self.max_tokens - self._consumed @property def exhausted(self) -> bool: return self._consumed >= self.max_tokens @property def completion_count(self) -> int: return len(self._entries) def record( self, completion_key: str, token_count: int, *, slot_id: str | None = None, generation_index: int | None = None, completion_sha256: str | None = None, ) -> bool: """Record once; exact duplicates are resume-safe no-ops. Returns ``True`` for a new record and ``False`` for an identical replay. Reusing an ID with different metadata is corruption and fails. """ return self.record_many( [ CompletionEntry( completion_id=completion_key, token_count=token_count, slot_id=slot_id, generation_index=generation_index, completion_sha256=completion_sha256, ) ] )[0] def record_many(self, entries: Iterable[CompletionEntry]) -> tuple[bool, ...]: pending = list(entries) seen_pending: dict[str, CompletionEntry] = {} results: list[bool] = [] new_tokens = 0 for entry in pending: if not isinstance(entry.completion_id, str) or not entry.completion_id: raise LedgerError("completion_id must be non-empty") if ( isinstance(entry.token_count, bool) or not isinstance(entry.token_count, int) or entry.token_count < 0 ): raise LedgerError("token_count must be a non-negative integer") if entry.generation_index is not None and ( isinstance(entry.generation_index, bool) or not isinstance(entry.generation_index, int) or entry.generation_index < 0 ): raise LedgerError("generation_index must be a non-negative integer") if entry.slot_id is not None and ( not isinstance(entry.slot_id, str) or not entry.slot_id ): raise LedgerError("slot_id must be a non-empty string when supplied") if entry.completion_sha256 is not None and not is_sha256(entry.completion_sha256): raise LedgerError("completion_sha256 must be a SHA-256 when supplied") existing = self._entries.get(entry.completion_id) or seen_pending.get( entry.completion_id ) if existing is not None: if existing != entry: raise LedgerError( f"completion_id {entry.completion_id} was reused with different metadata" ) results.append(False) continue seen_pending[entry.completion_id] = entry new_tokens += entry.token_count results.append(True) if self._consumed + new_tokens > self.max_tokens: raise LedgerError( f"completion-token cap exceeded: {self._consumed}+{new_tokens}>{self.max_tokens}" ) for entry in seen_pending.values(): self._entries[entry.completion_id] = entry self._consumed += new_tokens return tuple(results) def to_dict(self) -> dict[str, Any]: entries = [self._entries[key].to_dict() for key in sorted(self._entries)] return { "schema_version": self.SCHEMA_VERSION, "run_id": self.run_id, "max_tokens": self.max_tokens, "consumed_tokens": self._consumed, "config_sha256": self.config_sha256, "data_manifest_sha256": self.data_manifest_sha256, "comparison_slot_manifest_sha256": self.comparison_slot_manifest_sha256, "entries": entries, } def save(self, path: str | Path) -> None: atomic_write_json(path, self.to_dict()) @classmethod def load( cls, path: str | Path, *, expected_run_id: str | None = None, expected_max_tokens: int | None = None, expected_config_sha256: str | None = None, expected_data_manifest_sha256: str | None = None, expected_comparison_slot_manifest_sha256: str | None = None, ) -> CompletionTokenLedger: source = Path(path) try: value = json.loads(source.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise LedgerError(f"cannot load ledger {source}: {exc}") from exc if not isinstance(value, dict) or value.get("schema_version") != cls.SCHEMA_VERSION: raise LedgerError("unsupported ledger schema") try: raw_max_tokens = value.get("max_tokens", 0) if isinstance(raw_max_tokens, bool) or not isinstance(raw_max_tokens, int): raise TypeError("max_tokens is not an integer") ledger = cls( run_id=str(value.get("run_id", "")), max_tokens=raw_max_tokens, config_sha256=value.get("config_sha256"), data_manifest_sha256=value.get("data_manifest_sha256"), comparison_slot_manifest_sha256=value.get("comparison_slot_manifest_sha256"), ) except (TypeError, ValueError, LedgerError) as exc: raise LedgerError(f"invalid ledger header: {exc}") from exc checks = ( ("run_id", expected_run_id, ledger.run_id), ("max_tokens", expected_max_tokens, ledger.max_tokens), ("config_sha256", expected_config_sha256, ledger.config_sha256), ( "data_manifest_sha256", expected_data_manifest_sha256, ledger.data_manifest_sha256, ), ( "comparison_slot_manifest_sha256", expected_comparison_slot_manifest_sha256, ledger.comparison_slot_manifest_sha256, ), ) for name, expected, actual in checks: if expected is not None and expected != actual: raise LedgerError(f"resume {name} mismatch: {actual!r} != {expected!r}") raw_entries = value.get("entries") if not isinstance(raw_entries, list): raise LedgerError("ledger entries must be a list") entries: list[CompletionEntry] = [] for raw in raw_entries: if not isinstance(raw, dict): raise LedgerError("ledger entry must be an object") try: token_count = raw.get("token_count", -1) generation_index = raw.get("generation_index") if isinstance(token_count, bool) or not isinstance(token_count, int): raise TypeError("token_count is not an integer") if generation_index is not None and ( isinstance(generation_index, bool) or not isinstance(generation_index, int) ): raise TypeError("generation_index is not an integer") entries.append( CompletionEntry( completion_id=str(raw.get("completion_id", "")), token_count=token_count, slot_id=raw.get("slot_id"), generation_index=generation_index, completion_sha256=raw.get("completion_sha256"), ) ) except (TypeError, ValueError) as exc: raise LedgerError(f"invalid ledger entry: {exc}") from exc ledger.record_many(entries) raw_consumed = value.get("consumed_tokens") if isinstance(raw_consumed, bool) or not isinstance(raw_consumed, int): raise LedgerError("ledger consumed_tokens must be an integer") if ledger.consumed_tokens != raw_consumed: raise LedgerError("ledger consumed_tokens does not equal entry sum") return ledger