# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-nondeterministic-tool-replay-as-a-forensic-integrity-failure-rather-than-a-tolerable-variance.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-nondeterministic-tool-replay-as-a-forensic-integrity-failure-rather-than-a-tolerable-variance.warrant.json
# Markdown SHA-256:   31327dfe3cec07088647c191b1fb658fd5c25180253953c600ceac3de5231df7
# Code AST SHA-256:   d27028844fdb06351a616d12ead9fc83a54050eec10d8643a1e0f48a85a2d4e5
# Verified Classes:   CustodyBreak, RecordedObservation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class CustodyBreak(RuntimeError):
    """Raised when a re-executed tool observation cannot be admitted as forensic evidence."""
    pass


@dataclass
class RecordedObservation:
    tool: str
    payload: Any
    volatile_fields: frozenset = field(default_factory=frozenset)


def _canonical(payload: Any, volatile: frozenset) -> str:
    if isinstance(payload, dict):
        stripped = {k: v for k, v in payload.items() if k not in volatile}
        return repr(sorted(stripped.items()))
    return repr(payload)


def replay_node(recorded: RecordedObservation, reexecuted: Any) -> str:
    """Return 'verified' or raise CustodyBreak. Never returns a coerced match."""
    rec_c = _canonical(recorded.payload, recorded.volatile_fields)
    new_c = _canonical(reexecuted, recorded.volatile_fields)
    if rec_c != new_c:
        raise CustodyBreak(
            f"tool={recorded.tool!r} observation diverged outside declared volatile "
            f"fields; recorded_hash={hashlib.sha256(rec_c.encode()).hexdigest()[:12]} "
            f"replayed_hash={hashlib.sha256(new_c.encode()).hexdigest()[:12]} "
            f"-- node quarantined, downstream steps must be flagged reconstructed"
        )
    return "verified"


def replay_trace(recorded_nodes, reexecuted_nodes) -> dict:
    """Replay until first custody break; report verified prefix and reconstruction boundary."""
    verified = 0
    for rec, new in zip(recorded_nodes, reexecuted_nodes):
        try:
            replay_node(rec, new)
            verified += 1
        except CustodyBreak as e:
            return {
                "verified_prefix_len": verified,
                "quarantined_at": verified,
                "reconstructed_suffix_len": len(recorded_nodes) - verified,
                "reason": str(e),
                "forensic_status": "partial",
            }
    return {
        "verified_prefix_len": verified,
        "quarantined_at": None,
        "reconstructed_suffix_len": 0,
        "forensic_status": "complete",
    }
