# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-reconciliation-when-a-rollback-invalidates-a-sibling-agent-s-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-reconciliation-when-a-rollback-invalidates-a-sibling-agent-s-committed-side-effects.warrant.json
# Markdown SHA-256:   c0a986afcd3d07fe73ec9559ec4121db4d2260c2ccc36d7ad5da32d1a283372f
# Code AST SHA-256:   f924d5fe7e05069fe3b1f5b9595dff186406148c86d80ccd3aafc013786f9c8e
# Verified Classes:   OrphanedSideEffectError, Premise, SideEffect, Reconciler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedSideEffectError(RuntimeError):
    """Raised when a committed side effect's dependency closure contains an
    invalidated speculative premise that cannot be reconciled within budget."""


@dataclass
class Premise:
    premise_id: str
    source_branch: str
    speculative: bool
    freshness_deadline: float
    live: bool = True


@dataclass
class SideEffect:
    effect_id: str
    branch: str
    dependency_closure: list[str]  # premise_ids consumed before commit
    committed: bool = True


@dataclass
class Reconciler:
    premises: dict[str, Premise] = field(default_factory=dict)
    effects: dict[str, SideEffect] = field(default_factory=dict)
    reconciliation_floor: float = 0.20   # fraction of budget reserved
    budget_spent: float = 0.0

    def rollback_branch(self, branch: str) -> list[str]:
        """Invalidate all premises authored by `branch`, then reconcile every
        effect whose dependency closure touches an invalidated premise."""
        invalidated = [p for p in self.premises.values()
                       if p.source_branch == branch and p.speculative]
        for p in invalidated:
            p.live = False

        invalidated_ids = {p.premise_id for p in invalidated}
        orphans = [e for e in self.effects.values()
                   if e.committed and (set(e.dependency_closure) & invalidated_ids)]

        for e in orphans:
            # Missing provenance edge => undecidable => must escalate.
            if not e.dependency_closure:
                raise OrphanedSideEffectError(
                    f"effect {e.effect_id} in branch {e.branch} has no recorded "
                    f"dependency closure; cannot bound rollback of {branch}"
                )
            if self.budget_spent >= (1.0 - self.reconciliation_floor):
                raise OrphanedSideEffectError(
                    f"reconciliation floor exhausted while reconciling "
                    f"{e.effect_id}; refusing silent acceptance of orphan"
                )
            self._reconcile(e)

        return [e.effect_id for e in orphans]

    def _reconcile(self, effect: SideEffect) -> None:
        # Compensate or re-derive; charge against the reconciliation floor.
        self.budget_spent += 0.05
        effect.committed = False
