# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-speculative-branch-s-optimistic-tool-effects-before-rollback-and-how-does-the-commit-window-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-speculative-branch-s-optimistic-tool-effects-before-rollback-and-how-does-the-commit-window-invariant.warrant.json
# Markdown SHA-256:   1d263a2f83fe40b596827b3e5601e24b97a59837b6717485021a9e5ea8d6a3fe
# Code AST SHA-256:   c5b68ef61dff3340407c8e6b32194b83ef7746b23c89c89c18ee6705c275b8ec
# Verified Classes:   CommitWindowViolation, EffectEntry, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class CommitWindowViolation(RuntimeError):
    """Raised when a branch is asked to roll back effects whose
    compensation lease has already expired. The branch is durable,
    not discardable, and must be reconciled instead."""


@dataclass(frozen=True)
class EffectEntry:
    branch_id: str
    tool: str
    effect_id: str
    compensable_until: float          # monotonic seconds
    compensation_handle: Optional[str]


class EffectLedger:
    def __init__(self) -> None:
        self._entries: dict[str, list[EffectEntry]] = {}

    def record(self, entry: EffectEntry) -> None:
        self._entries.setdefault(entry.branch_id, []).append(entry)

    def entries(self, branch_id: str) -> list[EffectEntry]:
        return list(self._entries.get(branch_id, []))


def rollback_branch(
    branch_id: str,
    ledger: EffectLedger,
    now: Optional[float] = None,
    compensate=lambda handle: None,
) -> None:
    now = time.monotonic() if now is None else now
    entries = ledger.entries(branch_id)

    # Re-check the commit window at selection time, not at fan-out time.
    expired = [e for e in entries if e.compensable_until < now]
    if expired:
        raise CommitWindowViolation(
            f"branch {branch_id} has {len(expired)} durable effect(s) past "
            f"compensation lease (e.g. {expired[0].tool}:{expired[0].effect_id}); "
            f"reconcile, do not discard"
        )

    # Compensation BEFORE marking discarded, so a crash mid-rollback leaves
    # the branch still live and discoverable via the ledger.
    for e in entries:
        if e.compensation_handle is not None:
            compensate(e.compensation_handle)

    for e in entries:
        if e.compensation_handle is None:
            raise CommitWindowViolation(
                f"branch {branch_id} effect {e.tool}:{e.effect_id} has no "
                f"compensation handle; cannot certify discard"
            )
    # Only now is it safe to drop the branch's context.
