# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-split-brain-branch-in-speculative-multi-agent-execution-with-rollback-and-branch-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-split-brain-branch-in-speculative-multi-agent-execution-with-rollback-and-branch-reconciliation.warrant.json
# Markdown SHA-256:   809d72fefa075b5a1a0a647be14fba9222493cab261e9e9f4d0675ad04762d7c
# Code AST SHA-256:   07b302b1fe700ea5a530fec18a376b6e43e01ecbcd4ff3e6f189ba6bbfdca2bb
# Verified Classes:   SplitBrainExposureError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SplitBrainExposureError(RuntimeError):
    """Raised when a rollback is attempted on a branch whose speculative
    writes have been observed by a sibling and can no longer be erased."""
    pass


def assert_rollback_safe(branch_id, speculative_writes, sibling_read_closures):
    """
    speculative_writes: dict[node_key -> version_id] written under speculation
    sibling_read_closures: dict[sibling_id -> set of version_ids observed,
                           including transitive provenance]
    """
    exposed = {}
    for sibling_id, observed_versions in sibling_read_closures.items():
        hit = {
            node: ver
            for node, ver in speculative_writes.items()
            if ver in observed_versions
        }
        if hit:
            exposed[sibling_id] = hit

    if exposed:
        # Rollback is forbidden. The branch is exposed; reconciliation must
        # amend rather than erase. Halting here is the only safe action.
        raise SplitBrainExposureError(
            f"branch {branch_id!r} cannot be rolled back: speculative writes "
            f"were observed by siblings {sorted(exposed)}. "
            f"Exposed writes: {exposed}. "
            f"Escalate to amendment reconciliation; do not erase versions."
        )

    return True


def reconcile_branch(branch_id, speculative_writes, sibling_read_closures):
    try:
        assert_rollback_safe(branch_id, speculative_writes, sibling_read_closures)
    except SplitBrainExposureError:
        # Quarantine siblings, invalidate derived nodes, recompute.
        return {"action": "amend", "branch": branch_id}
    return {"action": "rollback", "branch": branch_id}
