# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-survive-rollback-when-its-committed-side-effect-was-idempotent-on-retry-but-not-idempotent-on-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-survive-rollback-when-its-committed-side-effect-was-idempotent-on-retry-but-not-idempotent-on-replay.warrant.json
# Markdown SHA-256:   cc37b91fe6a783325854c2bb40852719b7bed5a984996f1b6153ab3d37548591
# Code AST SHA-256:   701c1c23aca33cf84bec125562148dd579800323a57080b2a7c5d7c44c4daaa6
# Verified Classes:   PhantomRecommitError, EffectLedger, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class PhantomRecommitError(RuntimeError):
    """Raised when a pruned branch attempts to mint a fresh effect identity."""


@dataclass
class EffectLedger:
    # append-only: (branch_id, effect_id) -> frozen idempotency key
    entries: dict = field(default_factory=dict)

    def record(self, branch_id: str, effect_id: str, key: str) -> None:
        self.entries[(branch_id, effect_id)] = key

    def key_for(self, branch_id: str, effect_id: str) -> Optional[str]:
        return self.entries.get((branch_id, effect_id))


@dataclass
class Branch:
    branch_id: str
    pruned: bool = False
    checkpoint: dict = field(default_factory=dict)


def execute_tool_call(
    branch: Branch,
    ledger: EffectLedger,
    tool_name: str,
    payload: dict,
    replay: bool,
) -> str:
    """
    Execute (or replay) a tool call under a branch.

    Invariant enforced: a pruned branch may only REPLAY a ledgered effect
    identity. It may never mint a fresh one, because a fresh key on a
    pruned branch is a net-new committed side effect that no live branch owns.
    """
    if branch.pruned and not replay:
        # Attempting live execution under a pruned checkpoint: this is the
        # exact path that regenerates gen_uuid()/time.time() and re-commits.
        raise PhantomRecommitError(
            f"live tool call '{tool_name}' attempted under pruned branch "
            f"{branch.branch_id}; replay-from-ledger required"
        )

    if replay:
        effect_id = payload.get("effect_id")
        if effect_id is None:
            raise PhantomRecommitError(
                f"replay of branch {branch.branch_id} has no ledgered effect_id"
            )
        key = ledger.key_for(branch.branch_id, effect_id)
        if key is None:
            raise PhantomRecommitError(
                f"replay references effect {effect_id} absent from ledger for "
                f"branch {branch.branch_id}; refusing to mint a new key"
            )
        # Pure replay: use the frozen key, do not call gen_uuid()/time.time().
        return key

    # First execution: mint identity ONCE and freeze it in the ledger.
    effect_id = payload["effect_id"]
    key = hashlib.sha256(
        f"{branch.branch_id}:{effect_id}".encode()
    ).hexdigest()
    ledger.record(branch.branch_id, effect_id, key)
    return key


def verify_rollback(branch: Branch, ledger: EffectLedger) -> None:
    """
    Auditor verification pass over a pruned branch. Must be replay-only.
    If this raises, the rollback state is untrustworthy and must not be
    used to drive further branch decisions.
    """
    if not branch.pruned:
        raise PhantomRecommitError(
            f"verify_rollback called on unpruned branch {branch.branch_id}"
        )
    try:
        execute_tool_call(
            branch,
            ledger,
            tool_name="create_ticket",
            payload={"effect_id": "T-9001"},
            replay=True,
        )
    except PhantomRecommitError:
        # Rollback cannot be verified against a corrupted ledger.
        raise
