# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-leaking-side-effects-across-an-agent-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-leaking-side-effects-across-an-agent-swarm.warrant.json
# Markdown SHA-256:   255016e296103ec35b7856513da12cafe3affadfd954ace202bbe933fcaba039
# Code AST SHA-256:   f8dcc3eb776a836a37148aa1351920cc8541ff22bfac080b97d50c241ae18a18
# Verified Classes:   SpeculativeLeakError, CommitToken, Branch
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class SpeculativeLeakError(RuntimeError):
    """Raised when a speculative branch attempts an effect it is not warranted to perform,
    or when a rollback is issued without a verified compensation receipt."""
    pass


EFFECT_CLASSES = {"read_only", "idempotent_write", "non_idempotent_write", "external_irreversible"}
UNWARRANTED = {"non_idempotent_write", "external_irreversible"}


@dataclass
class CommitToken:
    branch_id: str
    plan_hash: str
    call_seq_hash: str

    def matches(self, branch_id: str, plan_hash: str, call_seq_hash: str) -> bool:
        return (self.branch_id == branch_id
                and self.plan_hash == plan_hash
                and self.call_seq_hash == call_seq_hash)


@dataclass
class Branch:
    branch_id: str
    plan_hash: str
    issued_calls: list = field(default_factory=list)
    committed: bool = False
    rolled_back: bool = False


def _seq_hash(calls: list) -> str:
    h = hashlib.sha256()
    for c in calls:
        h.update(f"{c['tool']}:{c['effect_class']}:{c['idem_key']}".encode())
    return h.hexdigest()


def dispatch_tool_call(branch: Branch, tool: str, effect_class: str,
                       idem_key: str, token: Optional[CommitToken]) -> dict:
    if effect_class not in EFFECT_CLASSES:
        raise SpeculativeLeakError(f"unknown effect_class={effect_class!r}")

    call = {"tool": tool, "effect_class": effect_class, "idem_key": idem_key}

    if effect_class in UNWARRANTED:
        if token is None:
            raise SpeculativeLeakError(
                f"branch {branch.branch_id} attempted {effect_class} call to {tool} "
                f"without a commit token; effect would leak past rollback"
            )
        if not token.matches(branch.branch_id, branch.plan_hash, _seq_hash(branch.issued_calls)):
            raise SpeculativeLeakError(
                f"commit token does not bind to branch {branch.branch_id} "
                f"plan {branch.plan_hash}; refusing cross-branch warrant"
            )
        if branch.rolled_back:
            raise SpeculativeLeakError(
                f"branch {branch.branch_id} is rolled back; commit token is stale"
            )

    branch.issued_calls.append(call)
    return {"acknowledged": True, "call": call}


def rollback_branch(branch: Branch) -> dict:
    if branch.committed:
        raise SpeculativeLeakError(
            f"cannot roll back committed branch {branch.branch_id}"
        )
    leaked = [c for c in branch.issued_calls if c["effect_class"] in UNWARRANTED]
    if leaked:
        # This should be unreachable if dispatch_tool_call is the only path to effects.
        raise SpeculativeLeakError(
            f"branch {branch.branch_id} issued {len(leaked)} unwarranted effects; "
            f"logical rollback would leak them: {[c['tool'] for c in leaked]}"
        )
    branch.rolled_back = True
    return {"rolled_back": True, "compensations_required": 0}


def commit_branch(branch: Branch, token: CommitToken) -> dict:
    if branch.rolled_back:
        raise SpeculativeLeakError(
            f"branch {branch.branch_id} already rolled back; cannot commit"
        )
    if not token.matches(branch.branch_id, branch.plan_hash, _seq_hash(branch.issued_calls)):
        raise SpeculativeLeakError(
            f"commit token does not bind to branch {branch.branch_id}; "
            f"possible token reuse across branches"
        )
    branch.committed = True
    return {"committed": True, "branch_id": branch.branch_id}


# --- Failure trace demonstrating the invariant ---
def _demo():
    b_a = Branch(branch_id="A", plan_hash="plan-direct-api")
    b_b = Branch(branch_id="B", plan_hash="plan-staged-csv")

    # Branch A tries a non-idempotent write with no token: gated.
    try:
        dispatch_tool_call(b_a, "POST /ledger/reconcile", "non_idempotent_write",
                           idem_key="A-9", token=None)
    except SpeculativeLeakError as e:
        print("GATE HELD:", e)

    # Auditor commits B; token is bound to B only.
    tok_b = CommitToken(branch_id="B", plan_hash="plan-staged-csv",
                        call_seq_hash=_seq_hash(b_b.issued_calls))
    commit_branch(b_b, tok_b)

    # A cannot reuse B's token.
    try:
        dispatch_tool_call(b_a, "POST /ledger/reconcile", "non_idempotent_write",
                           idem_key="A-9", token=tok_b)
    except SpeculativeLeakError as e:
        print("CROSS-BRANCH BLOCKED:", e)

    rollback_branch(b_a)
    print("A rolled back with zero compensations; no leak.")


if __name__ == "__main__":
    _demo()
