# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-branch-rollback-and-instead-quarantine-the-entire-fan-out-cohort.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abandon-speculative-branch-rollback-and-instead-quarantine-the-entire-fan-out-cohort.warrant.json
# Markdown SHA-256:   2836668b7a1b618196747c28f9607741004cc20a4d1b1ecb179d3086cd5e8870
# Code AST SHA-256:   c95a0f09a7d8f65fd1fddce4bc20623166bf31291d8bc8edb5c2275e5033e235
# Verified Classes:   SpeculativeRollbackUnsoundError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackUnsoundError(RuntimeError):
    """Raised when rollback is attempted on a branch that leaked to a global namespace."""


GLOBAL_WRITE_TOOLS = {"memory.write_episode", "http.post", "queue.publish"}


def plan_fanout_rollback(fanout_id: str, branches: list[dict], winner_id: str) -> dict:
    """
    Decide, per losing branch, whether rollback is sound or the cohort must be quarantined.
    Each branch: {"branch_id": str, "tools_invoked": list[str], "wrote_global": bool}
    """
    losing = [b for b in branches if b["branch_id"] != winner_id]
    leaked = [
        b["branch_id"]
        for b in losing
        if b["wrote_global"] or GLOBAL_WRITE_TOOLS.intersection(b["tools_invoked"])
    ]

    if leaked:
        # Rollback would discard context but not the external footprint.
        raise SpeculativeRollbackUnsoundError(
            f"fanout={fanout_id} winner={winner_id} "
            f"leaked_branches={leaked} -> quarantine cohort, "
            f"freeze global namespaces, require reconciliation before downstream read"
        )

    return {"action": "rollback", "fanout_id": fanout_id, "discarded": [b["branch_id"] for b in losing]}
