# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-a-speculative-branch-checkpoint-during-deterministic-replay-of-a-multi-agent-orchestration.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-a-speculative-branch-checkpoint-during-deterministic-replay-of-a-multi-agent-orchestration.warrant.json
# Markdown SHA-256:   bd947a879142fe2266f519a6f0e6e35065a06307cbeef03c8100e22c19dbc340
# Code AST SHA-256:   902d75864775f09e24e54e206d180a884d8d7c39ee7656b21f30dfc754bc6a44
# Verified Classes:   BranchAdmissionError, RecordedEffect, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class BranchAdmissionError(RuntimeError):
    """Raised when a speculative branch cannot be admitted because replay
    invariants are violated at fork time."""


@dataclass
class RecordedEffect:
    tool: str
    response: dict[str, Any]
    volatile_fields: dict[str, Any]
    monotonic_seq: int
    captured_at: float


@dataclass
class Checkpoint:
    agent_contexts: dict[str, list[str]]
    mailboxes: dict[str, list[dict]]
    effect_log: list[RecordedEffect] = field(default_factory=list)
    clock_anchor: float | None = None
    smallest_ttl: float | None = None


def admit_branch(
    checkpoint: Checkpoint,
    replay_time: float,
    reissued: RecordedEffect,
    live_response: dict[str, Any],
) -> None:
    """Validate that a speculative branch can be admitted.

    Raises BranchAdmissionError if any replay invariant is violated.
    """
    if checkpoint.clock_anchor is None:
        raise BranchAdmissionError(
            "checkpoint has no clock anchor; clock-dependent decisions "
            "cannot be replayed soundly"
        )

    if checkpoint.smallest_ttl is not None:
        elapsed = replay_time - checkpoint.clock_anchor
        if elapsed > checkpoint.smallest_ttl:
            raise BranchAdmissionError(
                f"replay is {elapsed:.1f}s after capture, exceeding smallest "
                f"TTL {checkpoint.smallest_ttl}s; TTL-gated decisions will "
                f"diverge from the original run"
            )

    for key, recorded_value in reissued.volatile_fields.items():
        live_value = live_response.get(key)
        if live_value != recorded_value:
            raise BranchAdmissionError(
                f"effect-layer divergence on {reissued.tool!r}: field {key!r} "
                f"was {recorded_value!r} at capture, is {live_value!r} at "
                f"replay; branch cannot be causally attributed to intervention"
            )


def fork_speculative_branch(
    checkpoint: Checkpoint,
    intervention: str,
    reissued_effects: list[tuple[RecordedEffect, dict[str, Any]]],
) -> dict[str, Any]:
    replay_time = time.time()
    for recorded, live in reissued_effects:
        admit_branch(checkpoint, replay_time, recorded, live)
    return {
        "intervention": intervention,
        "forked_at": replay_time,
        "admitted": True,
    }
