# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-during-cost-aware-pruning-of-agent-trajectories-and-how-deterministic-replay-of-committ.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-during-cost-aware-pruning-of-agent-trajectories-and-how-deterministic-replay-of-committ.warrant.json
# Markdown SHA-256:   83d2a714283ef585d23eb2a1f87fc555d493a5cfafd9cff5264408abfacf58a7
# Code AST SHA-256:   e5fcbf70ee24a6383ff43f5c7827f78d712daf50273e1b6933137bf5a91774f8
# Verified Classes:   ReplayIsolationViolation, Snapshot, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ReplayIsolationViolation(RuntimeError):
    """Raised when a committed trajectory's replay reads state produced by a pruned sibling."""


@dataclass
class Snapshot:
    generation: str
    state: dict

    @classmethod
    def capture(cls, state: dict) -> "Snapshot":
        gen = hashlib.sha256(repr(sorted(state.items())).encode()).hexdigest()[:16]
        return cls(generation=gen, state=dict(state))


@dataclass
class Branch:
    name: str
    pruned: bool
    writes: dict = field(default_factory=dict)
    reads: set = field(default_factory=set)


def commit_and_verify(pre_node: Snapshot, branches: list[Branch], committed: str) -> dict:
    """Commit one branch, then verify replay reproduces it against the pre-node snapshot.

    Invariant: the committed branch's replay must see only pre_node.state plus its own
    writes. Any read that resolves to a value written by a pruned sibling is a violation.
    """
    winner = next((b for b in branches if b.name == committed), None)
    if winner is None:
        raise ReplayIsolationViolation(f"committed branch {committed!r} not in branch set")

    # Reconstruct replay environment: pre-node state + winner's own writes only.
    replay_state = dict(pre_node.state)
    replay_state.update(winner.writes)

    # Simulate the winner's reads against the replay environment.
    for key in winner.reads:
        if key not in replay_state:
            # The read succeeded at commit time but fails on replay — the value
            # it consumed came from a pruned sibling's probe, not from pre-node state.
            leaked = [b.name for b in branches if b.pruned and key in b.writes]
            raise ReplayIsolationViolation(
                f"branch {committed!r} read {key!r} which is absent from snapshot "
                f"generation {pre_node.generation}; produced by pruned sibling(s) "
                f"{leaked or ['<unknown>']}. Pruning was not write-isolated."
            )
    return replay_state
