# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-speculative-branch-state-be-retired-the-rollback-retirement-gap-in-parallel-multi-agent-rollouts.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-speculative-branch-state-be-retired-the-rollback-retirement-gap-in-parallel-multi-agent-rollouts.warrant.json
# Markdown SHA-256:   5ccaf0c9aadfbdc67a636bf3144e22d3f518a180be4a9eec58e4d1d3a40e1820
# Code AST SHA-256:   294f10ac4394631860d607d898fb4dd9f1e1712aa4bcfb6aeccc34566d40a471
# Verified Classes:   BranchRetirementError, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BranchRetirementError(RuntimeError):
    """Raised when a speculative branch is retired while effects are still in flight."""
    pass


class SpeculativeBranch:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.diverged = False
        self.inflight_effects = set()
        self.retired = False

    def mark_diverged(self):
        self.diverged = True

    def issue_effect(self, effect_id: str, synchronous_ack: bool):
        if self.retired:
            raise BranchRetirementError(
                f"branch {self.branch_id} issued effect {effect_id} after retirement"
            )
        if not synchronous_ack:
            self.inflight_effects.add(effect_id)

    def acknowledge_effect(self, effect_id: str):
        self.inflight_effects.discard(effect_id)

    def retire(self, compensation_complete: bool):
        # Retirement is gated on effect quiescence, not on divergence.
        if self.inflight_effects:
            raise BranchRetirementError(
                f"branch {self.branch_id} cannot retire: "
                f"{len(self.inflight_effects)} effect(s) still in flight "
                f"({sorted(self.inflight_effects)})"
            )
        if self.diverged and not compensation_complete:
            raise BranchRetirementError(
                f"diverged branch {self.branch_id} has not been compensated; "
                f"retirement would orphan its effects"
            )
        self.retired = True
