# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-replayed-multi-agent-trajectory-as-non-reproducible-rather-than-as-evidence-of-a-bug.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-replayed-multi-agent-trajectory-as-non-reproducible-rather-than-as-evidence-of-a-bug.warrant.json
# Markdown SHA-256:   107d7bf1395cce3cf30dd58b6cbf32cf1c9e3bd62807d36ca5c7128c8045bcd2
# Code AST SHA-256:   9aecc85a022f64ca575dfe07a3366b970cf2c0a0b7e922258b797bfae2419cb3
# Verified Classes:   ReplayClassification, ReplayForensicError, NodeRecord, ReplayNode
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Set


class ReplayClassification(Enum):
    CAUSALLY_REPRODUCIBLE = "causally_reproducible"
    CAUSAL_BREAK = "causal_break"
    DETERMINISM_VIOLATION = "determinism_violation"
    DAG_DIVERGENT = "dag_divergent"


class ReplayForensicError(RuntimeError):
    """Raised when a replay cannot be classified because the recording
    lacks the metadata required to compute the digest-sensitive frontier,
    or because the replay altered DAG shape in a way that makes the
    frontier undefined."""


@dataclass
class NodeRecord:
    node_id: str
    declared: str  # "deterministic" | "stochastic"
    parents: List[str]
    digest_sensitive: bool
    output_digest: Optional[str] = None


@dataclass
class ReplayNode:
    node_id: str
    parents: List[str]
    output_bytes: bytes
    output_digest: str


def compute_frontier(records: Dict[str, NodeRecord]) -> Set[str]:
    """Nodes on or downstream of any digest_sensitive=true consumer."""
    frontier: Set[str] = set()
    children: Dict[str, List[str]] = {nid: [] for nid in records}
    for nid, rec in records.items():
        for p in rec.parents:
            if p not in records:
                raise ReplayForensicError(
                    f"node {nid} references unknown parent {p}; "
                    f"recording is unverifiable, not mismatched"
                )
            children[p].append(nid)
    stack = [nid for nid, r in records.items() if r.digest_sensitive]
    while stack:
        nid = stack.pop()
        if nid in frontier:
            continue
        frontier.add(nid)
        stack.extend(children[nid])
    return frontier


def classify_replay(
    records: Dict[str, NodeRecord],
    replayed: Dict[str, ReplayNode],
) -> ReplayClassification:
    if set(records) != set(replayed):
        # DAG shape changed: frontier is undefined; do not report as break.
        return ReplayClassification.DAG_DIVERGENT

    for nid, rec in records.items():
        if set(rec.parents) != set(replayed[nid].parents):
            return ReplayClassification.DAG_DIVERGENT

    frontier = compute_frontier(records)

    # Second pass must never run before this loop completes: evaluate the
    # frontier first, and never abort on an upstream stochastic divergence.
    for nid in frontier:
        rec = records[nid]
        rp = replayed[nid]
        if rec.output_digest is None:
            raise ReplayForensicError(
                f"frontier node {nid} has no recorded output_digest; "
                f"replay is unverifiable, not mismatched"
            )
        if rec.output_digest != rp.output_digest:
            return ReplayClassification.CAUSAL_BREAK

    for nid, rec in records.items():
        if rec.declared == "deterministic":
            if rec.output_digest is None:
                raise ReplayForensicError(
                    f"deterministic node {nid} lacks output_digest"
                )
            if rec.output_digest != replayed[nid].output_digest:
                return ReplayClassification.DETERMINISM_VIOLATION

    return ReplayClassification.CAUSALLY_REPRODUCIBLE


def assert_replay_admissible(
    records: Dict[str, NodeRecord],
    replayed: Dict[str, ReplayNode],
) -> None:
    verdict = classify_replay(records, replayed)
    if verdict in (
        ReplayClassification.CAUSAL_BREAK,
        ReplayClassification.DETERMINISM_VIOLATION,
        ReplayClassification.DAG_DIVERGENT,
    ):
        raise ReplayForensicError(
            f"replay not admissible as evidence: verdict={verdict.value}"
        )
