# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-causal-trace-divergence-when-speculative-multi-agent-branches-are-replayed-against-a-mutated-root-context.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-causal-trace-divergence-when-speculative-multi-agent-branches-are-replayed-against-a-mutated-root-context.warrant.json
# Markdown SHA-256:   e3832d1a79482fc7950214e3dcb183eff51a7e92c43ea301d71d4a02f54f2f9b
# Code AST SHA-256:   1d079ef702ce6fde088a8dd12552fa45a53341138d2b04e2bf2e21bb1254eda7
# Verified Classes:   CausalTraceUnreplayable, BranchRecord, MergerRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class CausalTraceUnreplayable(RuntimeError):
    """Raised when a speculative execution graph cannot be replayed with causal fidelity."""


@dataclass(frozen=True)
class BranchRecord:
    branch_id: str
    root_rev_hash: str            # C1: pinned at fork
    tool_payload_hashes: frozenset[str]  # C2: captured bytes, never re-executed
    served_from: Mapping[str, str]       # C3: tool_call_id -> originating branch_id


@dataclass(frozen=True)
class MergerRecord:
    input_set: frozenset[tuple[str, str, str]]  # (branch_id, output_hash, root_rev_hash)


def verify_replayable(
    branches: Mapping[str, BranchRecord],
    merger: MergerRecord,
    current_root_rev: str,
) -> None:
    # C1: every branch must pin a root revision; replay never uses current_root_rev.
    for bid, br in branches.items():
        if not br.root_rev_hash:
            raise CausalTraceUnreplayable(
                f"branch {bid} has no pinned root revision; replay would drift to {current_root_rev}"
            )

    # C2: every consumed tool result must be captured, not re-executable.
    for bid, br in branches.items():
        if not br.tool_payload_hashes:
            raise CausalTraceUnreplayable(
                f"branch {bid} consumed tools with no captured payload hashes; replay would re-execute"
            )

    # C3: cache-served calls must carry an explicit provenance edge.
    for bid, br in branches.items():
        for tool_call_id, origin in br.served_from.items():
            if origin not in branches:
                raise CausalTraceUnreplayable(
                    f"branch {bid} tool {tool_call_id} served_from unknown branch {origin}"
                )

    # C4: merger input set must be closed over pinned revisions.
    pinned = {br.root_rev_hash for br in branches.values()}
    for bid, _out_hash, rev in merger.input_set:
        if bid not in branches:
            raise CausalTraceUnreplayable(
                f"merger consumed branch {bid} absent from branch set"
            )
        if rev not in pinned:
            raise CausalTraceUnreplayable(
                f"merger consumed branch {bid} at root revision {rev} not pinned by any branch; "
                f"reconstruction would fabricate a causal edge"
            )
