# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-optimistic-branches-speculative-multi-agent-rollback-divergence-at-the-commit-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-optimistic-branches-speculative-multi-agent-rollback-divergence-at-the-commit-horizon.warrant.json
# Markdown SHA-256:   5bb09e5909f31ad3e3d501e7c83560583becae8abe1b948309deee752a656408
# Code AST SHA-256:   fd4e6aa5bdf8a71c48be9c716c4da935ca376cdbc21030a34e5b08414720d77c
# Verified Classes:   LeakyBranchCommitError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class LeakyBranchCommitError(RuntimeError):
    """Raised when a losing speculative branch has leaked an effect to an
    external reader that the branch's compensation set cannot retract."""
    pass


# Effect classes assigned from the tool manifest, never from branch self-report.
PROJECTION = "projection"      # discardable, no external visibility
COMPENSABLE = "compensable"    # reversible within the branch's own scope
LEAKY = "leaky"                # observable-and-actionable outside the branch


def classify_plan(plan_steps, tool_manifest):
    """Classify each step by effect class using the authoritative manifest.

    A step is LEAKY if its tool is marked externally_visible in the manifest,
    OR if the manifest marks it as triggering async work, OR if it writes to
    a shared namespace. The branch cannot downgrade its own classification.
    """
    classes = []
    for step in plan_steps:
        spec = tool_manifest.get(step.tool_name)
        if spec is None:
            # Unknown tool: assume worst case. Never assume discardable.
            classes.append(LEAKY)
            continue
        if spec.get("externally_visible") or spec.get("triggers_async"):
            classes.append(LEAKY)
        elif spec.get("writes_shared_namespace"):
            classes.append(LEAKY)
        elif spec.get("reversible_within_branch"):
            classes.append(COMPENSABLE)
        else:
            classes.append(PROJECTION)
    return classes


def admit_branch(branch, tool_manifest, orchestrator_gate):
    """Decide whether a speculative branch may run optimistically.

    Returns the branch if it is safely discardable. Raises if the branch
    contains a LEAKY step and is therefore not safely discardable under
    optimistic execution.
    """
    classes = classify_plan(branch.plan_steps, tool_manifest)
    if LEAKY in classes:
        # The branch may still run, but only under a barrier: it must defer
        # every LEAKY step until it is the sole survivor, and the gate must
        # be orchestrator-held (the branch cannot mint its own commit token).
        if not orchestrator_gate.is_barrier_enforced(branch.id):
            raise LeakyBranchCommitError(
                f"branch {branch.id} contains LEAKY steps "
                f"{[s.tool_name for s, c in zip(branch.plan_steps, classes) if c == LEAKY]} "
                f"but no orchestrator-held barrier is enforced; "
                f"optimistic execution would leak effects that rollback cannot retract"
            )
    return branch


def reconcile(orchestrator, branches, winner_id, tool_manifest):
    """Select a winner and compensate losers, refusing to commit if any
    loser has leaked an effect to an external reader."""
    winner = next(b for b in branches if b.id == winner_id)
    losers = [b for b in branches if b.id != winner_id]

    leaked = []
    for b in losers:
        # The branch's own log is not the oracle for leak detection.
        # Ask the observer side: did any external principal read b's effects?
        readers = orchestrator.external_readers_of(b.id)
        if readers:
            leaked.append((b.id, [r.principal for r in readers]))

    if leaked:
        # Do not silently overwrite. A retract that the reader may ignore
        # is not a compensation; block commit until readers acknowledge.
        raise LeakyBranchCommitError(
            f"cannot commit winner {winner_id}: losing branches leaked to "
            f"external readers {leaked}; a retraction-and-repair pass must "
            f"run and every reader must acknowledge before commit"
        )

    for b in losers:
        orchestrator.compensate(b)
    return orchestrator.commit(winner)
