# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-rollback-unsafe-speculative-branch-in-multi-agent-execution-the-divergent-write-reconciliation-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-rollback-unsafe-speculative-branch-in-multi-agent-execution-the-divergent-write-reconciliation-failure.warrant.json
# Markdown SHA-256:   1a9f24946995857854c942a881b84521e15cc292fbae5043269cd9ee29bbd404
# Code AST SHA-256:   35103d45a3f1e1b94f42ea84c0291695684777ff29bcc8068399fa6fa552868e
# Verified Classes:   RollbackUnsafeBranchError, ToolEffectClass
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class RollbackUnsafeBranchError(RuntimeError):
    """Raised when a speculative branch's rollback set contains a shared,
    ambiguously-keyed inverse that can mutate state a sibling depends on."""


class ToolEffectClass:
    BRANCH_LOCAL = "branch_local"
    INVERTIBLE_SHARED = "invertible_shared"
    NON_INVERTIBLE_SHARED = "non_invertible_shared"


def classify_branch_rollback_safety(branch, tool_registry):
    """Return True iff every mutation in the branch is rollback-safe:
    branch-local, or invertible-shared with a branch-unique inverse key."""
    for call in branch.mutations:
        spec = tool_registry[call.tool]
        if spec.effect_class == ToolEffectClass.BRANCH_LOCAL:
            continue
        if spec.effect_class == ToolEffectClass.NON_INVERTIBLE_SHARED:
            raise RollbackUnsafeBranchError(
                f"branch {branch.id} invoked non-invertible shared tool "
                f"{call.tool!r}; cannot be speculatively rolled back"
            )
        # invertible_shared: inverse key must be unique to this branch
        if not spec.inverse_key_is_branch_unique(call):
            raise RollbackUnsafeBranchError(
                f"branch {branch.id} tool {call.tool!r} has a shared inverse "
                f"keyed on {spec.inverse_key(call)!r} that aliases sibling "
                f"branches; rollback would mutate their substrate"
            )
    return True


def reconcile(committed, siblings, live_state, tool_registry):
    """Commit gate: verify live postconditions after sibling rollback quiescence."""
    for s in siblings:
        if s.rollback_state != "terminal":
            raise RollbackUnsafeBranchError(
                f"sibling {s.id} rollback not terminal; commit gate must wait"
            )
        classify_branch_rollback_safety(s, tool_registry)  # raises on unsafe
    for post in committed.postconditions:
        if not post.holds_against(live_state):
            raise RollbackUnsafeBranchError(
                f"committed branch {committed.id} postcondition {post!r} "
                f"fails against live substrate; sibling rollback likely "
                f"invalidated it — re-plan, do not commit"
            )
    return "commit"
