# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-non-absorbing-rollback-when-speculative-tool-calls-have-already-crossed-a-side-effect-frontier.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-non-absorbing-rollback-when-speculative-tool-calls-have-already-crossed-a-side-effect-frontier.warrant.json
# Markdown SHA-256:   84c090ae555238560cce2f0a7158cfa1ee50ca26b3c0a40d34ca7320d0d72110
# Code AST SHA-256:   99b1d18b9a19d85cb5cd2f2f357f777fb37a4df2cc437056298ef63b292c9f59
# Verified Classes:   NonAbsorbingRollbackError, Effect, Branch, SpeculativeTree
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional


class NonAbsorbingRollbackError(RuntimeError):
    """Raised when a cancelled speculative branch has leaked effects past its frontier."""
    pass


@dataclass
class Effect:
    branch_id: str
    frontier_token: int
    observable: bool


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    cancelled: bool = False
    cancel_token: Optional[int] = None  # frontier token returned by cancellation


@dataclass
class SpeculativeTree:
    branches: Dict[str, Branch] = field(default_factory=dict)
    ledger: list = field(default_factory=list)

    def record_effect(self, effect: Effect) -> None:
        self.ledger.append(effect)

    def assert_absorbing(self, branch_id: str) -> None:
        branch = self.branches[branch_id]
        if not branch.cancelled:
            return  # only cancelled branches are subject to this check
        if branch.cancel_token is None:
            raise NonAbsorbingRollbackError(
                f"branch {branch_id} cancelled without a frontier token; "
                f"escape set is unbounded"
            )
        for eff in self.ledger:
            if eff.branch_id != branch_id:
                continue
            if eff.frontier_token > branch.cancel_token and eff.observable:
                raise NonAbsorbingRollbackError(
                    f"branch {branch_id} leaked observable effect at token "
                    f"{eff.frontier_token} > cancel_token {branch.cancel_token}; "
                    f"rollback is non-absorbing, quarantine and compensate"
                )

    def assert_commit_safe(self, committed_ids: Set[str], quarantine: Set[str]) -> None:
        for eff in self.ledger:
            if eff.branch_id in committed_ids:
                continue
            if eff.branch_id in quarantine:
                continue
            raise NonAbsorbingRollbackError(
                f"effect from uncommitted, unquarantined branch {eff.branch_id} "
                f"present in ledger; invariant 'no committed branch depends on "
                f"uncommitted effect' violated"
            )


def reconcile_after_commit(tree: SpeculativeTree,
                           committed_ids: Set[str],
                           quarantine: Set[str]) -> None:
    # First: prove each cancelled branch was absorbing.
    for bid, branch in tree.branches.items():
        if branch.cancelled:
            tree.assert_absorbing(bid)
    # Second: prove no stray branch id entered the ledger.
    tree.assert_commit_safe(committed_ids, quarantine)
    # Third: any quarantined branch that produced effects must be compensated.
    leaked = {e.branch_id for e in tree.ledger
              if e.branch_id in quarantine and e.observable}
    if leaked:
        raise NonAbsorbingRollbackError(
            f"quarantined branches {sorted(leaked)} produced observable effects; "
            f"emit compensating actions before declaring task complete"
        )
