# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-and-still-commit-the-side-effect-it-was-hedging-against.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-branch-and-still-commit-the-side-effect-it-was-hedging-against.warrant.json
# Markdown SHA-256:   1e434a5d9e2142595efbf66ca666a3bf6825ecbe69634fd9e23572908ad9d22c
# Code AST SHA-256:   0808aebe55690d37532d53ab36170ee652cf6e12e4fd96b3066f7409f2f642fb
# Verified Classes:   OrphanedEffectRollbackError, EffectRegistry
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedEffectRollbackError(RuntimeError):
    """Raised when a speculative branch is retired while externally durable
    effects still carry its speculation_id. Retiring in this state splits the
    effect's creation ledger from its compensation ledger and makes
    reconciliation impossible."""
    pass


class EffectRegistry:
    """Tracks externally durable effects keyed by the branch that created them.
    The registry is the source of truth for effect ownership, NOT the
    orchestrator's merge record."""

    def __init__(self):
        self._effects_by_speculation = {}  # speculation_id -> set[effect_id]

    def register(self, speculation_id: str, effect_id: str) -> None:
        self._effects_by_speculation.setdefault(speculation_id, set()).add(effect_id)

    def live_effects(self, speculation_id: str) -> set:
        return set(self._effects_by_speculation.get(speculation_id, set()))

    def compensate(self, speculation_id: str, effect_id: str) -> None:
        self._effects_by_speculation.get(speculation_id, set()).discard(effect_id)

    def reattribute(self, from_spec: str, to_spec: str, effect_id: str) -> None:
        self._effects_by_speculation.get(from_spec, set()).discard(effect_id)
        self._effects_by_speculation.setdefault(to_spec, set()).add(effect_id)


def retire_branch(
    registry: EffectRegistry,
    speculation_id: str,
    surviving_speculation_id: str | None,
    compensate_first: bool = False,
) -> None:
    """Retire a rolled-back speculative branch. Enforces the retirement gate:
    a speculation_id may only be retired when it carries no live effects, or
    when every live effect has been compensated or explicitly re-attributed."""
    live = registry.live_effects(speculation_id)

    if live and compensate_first:
        for effect_id in list(live):
            registry.compensate(speculation_id, effect_id)
        live = registry.live_effects(speculation_id)

    if live and surviving_speculation_id is not None:
        # Re-attribute rather than deduplicate by payload. The surviving branch
        # inherits the effect handle explicitly; the merge record must reflect
        # the re-attribution, not infer ownership from execution order.
        for effect_id in list(live):
            registry.reattribute(speculation_id, surviving_speculation_id, effect_id)
        live = registry.live_effects(speculation_id)

    if live:
        raise OrphanedEffectRollbackError(
            f"refusing to retire speculation_id={speculation_id!r}: "
            f"live effects {sorted(live)!r} still carry it. "
            f"Compensate them or re-attribute to a surviving branch first."
        )

    # Safe to retire: no durable effect references this branch.
    registry._effects_by_speculation.pop(speculation_id, None)
