# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branch-replay-when-audit-time-tool-nondeterminism-silently-reorders-agent-decisions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branch-replay-when-audit-time-tool-nondeterminism-silently-reorders-agent-decisions.warrant.json
# Markdown SHA-256:   67228e7b2b9e9bb06fe8ace076ebf6274d50fcd559f185f900ec3832c47e0b83
# Code AST SHA-256:   181db9556598766d437e8a23e3c500dbbac32f77227c278dd25bc838ab9f5444
# Verified Classes:   ReplayOrderArtifactError, AuditInconclusiveError, GuardEvent, ToolEvent, Transcript
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayOrderArtifactError(RuntimeError):
    """Raised when replay reorders guard/tool dependencies relative to the recording."""


class AuditInconclusiveError(RuntimeError):
    """Raised when the recorded transcript lacks the instrumentation needed to validate replay order."""


@dataclass
class GuardEvent:
    guard_id: str
    logical_clock: int
    resolved_dependency_set: Optional[frozenset]  # call_ids the guard actually observed
    branch_committed: str


@dataclass
class ToolEvent:
    call_id: str
    logical_clock: int
    response_hash: str


@dataclass
class Transcript:
    guards: list = field(default_factory=list)
    tools: list = field(default_factory=list)


def validate_replay_order(recorded: Transcript, replayed: Transcript) -> None:
    """
    Assert that every guard observed the same dependency set, in the same
    logical-causal position, as in the recording. Raises before any branch
    comparison is attempted.
    """
    rec_guards = {g.guard_id: g for g in recorded.guards}
    rep_guards = {g.guard_id: g for g in replayed.guards}

    if set(rec_guards) != set(rep_guards):
        raise ReplayOrderArtifactError(
            f"guard set diverged: recorded={sorted(rec_guards)} replayed={sorted(rep_guards)}"
        )

    for gid, rec in rec_guards.items():
        if rec.resolved_dependency_set is None:
            # The original runtime did not instrument the guard's observed
            # dependencies. No amount of replay can recover the true order.
            raise AuditInconclusiveError(
                f"guard {gid} has no recorded resolved_dependency_set; "
                f"replay order cannot be validated"
            )
        rep = rep_guards[gid]
        if rep.resolved_dependency_set != rec.resolved_dependency_set:
            raise ReplayOrderArtifactError(
                f"guard {gid} observed deps {sorted(rep.resolved_dependency_set or [])} "
                f"but recording shows {sorted(rec.resolved_dependency_set)}; "
                f"branch decision is not comparable"
            )
        if rep.logical_clock != rec.logical_clock:
            raise ReplayOrderArtifactError(
                f"guard {gid} evaluated at logical clock {rep.logical_clock}, "
                f"recording shows {rec.logical_clock}; causal position shifted"
            )


def audit_branch(recorded: Transcript, replayed: Transcript) -> str:
    validate_replay_order(recorded, replayed)
    # Only now is it safe to compare committed branches.
    for gid, rec in ((g.guard_id, g) for g in recorded.guards):
        rep = next(g for g in replayed.guards if g.guard_id == gid)
        if rec.branch_committed != rep.branch_committed:
            raise ReplayOrderArtifactError(
                f"genuine logic divergence at guard {gid}: "
                f"recorded={rec.branch_committed} replayed={rep.branch_committed}"
            )
    return "AUDIT_VALID"
