# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-roll-back-a-speculative-tool-invocation-that-was-committed-to-a-shared-external-side-effect-channel-before-branch-reco.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-roll-back-a-speculative-tool-invocation-that-was-committed-to-a-shared-external-side-effect-channel-before-branch-reco.warrant.json
# Markdown SHA-256:   28c81f2e26e42df1540f83b67f40e11565dee59f4556e18b9cc3dede0ac28161
# Code AST SHA-256:   134f764c0c0b28e429fcd3c4406b219e0ab1ea6a7f2c6163a538536eb91a72d4
# Verified Classes:   SpeculativeEffectLeak, EffectHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeEffectLeak(RuntimeError):
    """Raised when a losing speculative branch externalized an effect the reconciler cannot revoke."""
    pass


class EffectHandle:
    def __init__(self, handle_id: str, branch_id: str, reconciler_owned: bool, revocable: bool):
        self.handle_id = handle_id
        self.branch_id = branch_id
        self.reconciler_owned = reconciler_owned
        self.revocable = revocable
        self.revoked = False


def commit_speculative_effect(
    branch_id: str,
    tool_name: str,
    handle: EffectHandle,
    tombstone_index: dict,
) -> None:
    # Invariant: a branch may only externalize through a reconciler-owned, revocable handle.
    if not handle.reconciler_owned or not handle.revocable:
        raise SpeculativeEffectLeak(
            f"branch {branch_id} attempted optimistic externalization of {tool_name} "
            f"via handle {handle.handle_id} that the reconciler cannot revoke "
            f"(reconciler_owned={handle.reconciler_owned}, revocable={handle.revocable}); "
            f"defer to post-reconciliation commit or re-issue a reconciler-scoped handle"
        )
    # Record the effect in the tombstone index so rollback cannot erase it.
    tombstone_index.setdefault(branch_id, []).append(
        {"handle_id": handle.handle_id, "tool": tool_name, "revoked": False}
    )


def rollback_branch(branch_id: str, tombstone_index: dict, handles: dict) -> None:
    # Rollback revokes handles; it does NOT prune the tombstone index.
    for record in tombstone_index.get(branch_id, []):
        handle = handles[record["handle_id"]]
        if not handle.revocable:
            raise SpeculativeEffectLeak(
                f"rollback of branch {branch_id} found non-revocable effect "
                f"{record['handle_id']} on tool {record['tool']}; orphan requires out-of-band audit"
            )
        handle.revoked = True
        record["revoked"] = True
    # Tombstones are retained deliberately: pruning them is what makes orphans undetectable.
