# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-side-effect-leaked-past-a-merge-barrier-during-branch-and-merge-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-side-effect-leaked-past-a-merge-barrier-during-branch-and-merge-rollback.warrant.json
# Markdown SHA-256:   a4a8c911fe8a79835544251349677f6c99b0c37b6968f7ff0622e2179325db1b
# Code AST SHA-256:   ee657208f2c7d4e9bc9f888f8c79d69a34a2dd9f7cd459de0611f6359a50ed7d
# Verified Classes:   SpeculativeEffectLeak, EffectRecord, EffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a promoted branch observes world state inconsistent with
    the orchestrator's expected surviving-effect set after merge."""
    pass


@dataclass
class EffectRecord:
    branch_id: str
    invocation_index: int
    durable_token: str  # e.g. "r-4472"; proof the effect is real
    compensated: bool = False


@dataclass
class EffectLedger:
    records: list[EffectRecord] = field(default_factory=list)

    def record(self, branch_id: str, invocation_index: int, token: str) -> None:
        # Written at the moment of durable success, BEFORE merge decision.
        self.records.append(EffectRecord(branch_id, invocation_index, token))

    def surviving_tokens(self, winning_branch: str) -> set[str]:
        # Losers' uncompensated effects are still in the world -> leaked.
        return {
            r.durable_token
            for r in self.records
            if r.branch_id == winning_branch or not r.compensated
        }

    def schedule_compensation(self, losing_branch: str) -> list[str]:
        to_compensate = [
            r for r in self.records
            if r.branch_id == losing_branch and not r.compensated
        ]
        for r in to_compensate:
            r.compensated = True  # compensation call issued; not yet confirmed
        return [r.durable_token for r in to_compensate]


def reconcile_after_promotion(
    ledger: EffectLedger,
    winning_branch: str,
    observed_tokens: set[str],
) -> None:
    """Run by the promoted branch before it acts on merged context."""
    expected = ledger.surviving_tokens(winning_branch)
    leaked = observed_tokens - expected
    if leaked:
        raise SpeculativeEffectLeak(
            f"promoted branch {winning_branch} observed {len(observed_tokens)} "
            f"durable effects but ledger expected {len(expected)}; "
            f"unaccounted tokens (likely leaked speculative effects): "
            f"{sorted(leaked)}"
        )
    # Only now may the promoted branch proceed to act.
