# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-forked-tool-effect-logs-after-a-rollback-race.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-forked-tool-effect-logs-after-a-rollback-race.warrant.json
# Markdown SHA-256:   6425aedc02ec716d32035b853b2bfd9006a141024326e412cffd0072db6f590b
# Code AST SHA-256:   d53db6391b207ce3546eb09c11f47c16c7ca4483dd898107180db037d121a7ce
# Verified Classes:   SpeculationLeakError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculationLeakError(RuntimeError):
    """Raised when a discarded speculative branch's effect escaped the rollback domain."""
    pass


def reconcile_branch(winner_trace, discarded_overlays, external_acks, pre_fork_snapshot):
    """Validate that a winner branch can be committed after rolling back siblings.

    Returns the set of compensations required. Raises SpeculationLeakError if the
    winner's trace references state that only existed in a discarded branch, or if
    an external consumer acknowledged a discarded branch's effect.
    """
    discarded_keys = set()
    for overlay in discarded_overlays:
        discarded_keys |= set(overlay.keys())

    orphaned = [
        ref for ref in winner_trace.referenced_keys
        if ref in discarded_keys and ref not in pre_fork_snapshot
    ]
    if orphaned:
        raise SpeculationLeakError(
            f"winner trace references discarded-branch keys {orphaned}; "
            f"branch is not committable without re-derivation"
        )

    leaked = [
        ack for ack in external_acks
        if ack.branch_id in {o.branch_id for o in discarded_overlays}
    ]
    if leaked:
        raise SpeculationLeakError(
            f"external acks from discarded branches {[a.branch_id for a in leaked]}; "
            f"abort was advisory, escalate to compensation"
        )

    # Substrate must match pre-fork snapshot before the window is declared closed.
    if winner_trace.substrate_digest != pre_fork_snapshot.digest:
        raise SpeculationLeakError(
            "substrate digest diverged from pre-fork snapshot; window may still be open"
        )

    return set()
