# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-speculative-agent-branch-whose-rollback-checkpoint-was-captured-before-a-side-effecting-tool-call-when-merge-time-r.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-speculative-agent-branch-whose-rollback-checkpoint-was-captured-before-a-side-effecting-tool-call-when-merge-time-r.warrant.json
# Markdown SHA-256:   420285c74ccf9e25966c3383275342e08f390487287f8f8fef3ebee1214d907b
# Code AST SHA-256:   1fc0cd0fd08ddfa78c6464111a205820bc732b23387cc412d93fe967506f6996
# Verified Classes:   SpeculativeEffectLeak
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeEffectLeak(RuntimeError):
    """Raised when merge reconciliation would produce a plausible state
    while the external effect ledger contains unattributed orphaned effects."""


def reconcile_merge(checkpoint, winner_branch, ledger, compensations):
    """
    checkpoint: object with .effect_offset (int) captured at fork time
    winner_branch: the surviving branch selected for merge
    ledger: append-only list of effect records with fields
            (branch_id, checkpoint_id, effect_id, idempotency_key, reversible)
    compensations: dict mapping effect_id -> compensating action callable
    """
    slice_ = ledger[checkpoint.effect_offset:]
    surviving_ids = {e.effect_id for e in slice_ if e.branch_id == winner_branch.id}
    orphaned = [e for e in slice_ if e.effect_id not in surviving_ids]

    unattributed = []
    for effect in orphaned:
        comp = compensations.get(effect.effect_id)
        if comp is None:
            unattributed.append(effect)
        else:
            comp()  # apply compensating action; ledger entry marked compensated

    if unattributed:
        raise SpeculativeEffectLeak(
            f"Merge of branch {winner_branch.id} from checkpoint "
            f"{checkpoint.id} would succeed while {len(unattributed)} "
            f"orphaned side effects lack compensation: "
            f"{[e.effect_id for e in unattributed]}. "
            f"Fail closed; surface to auditor."
        )

    return {"merged": True, "compensated": len(orphaned) - len(unattributed)}
