# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-branch-before-its-rollback-journal-is-sealed-the-unsealed-commit-hazard-in-speculative.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-branch-before-its-rollback-journal-is-sealed-the-unsealed-commit-hazard-in-speculative.warrant.json
# Markdown SHA-256:   0f0fb871e9596bb29b559cfddde1584f6f75ddacd6dd5f3f5617eef0e27617cb
# Code AST SHA-256:   7e315c9f7ba90ce25ec1c5c65852dbc4d33956f1955f4a9845faf36701f270b3
# Verified Classes:   RollbackInvariantError, OpState, JournalEntry, BranchJournal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Dict, List, Optional


class RollbackInvariantError(RuntimeError):
    """Raised when a rollback sweep would run against an unsealed or unclosed journal."""


class OpState(Enum):
    PENDING = "pending"
    TERMINAL = "terminal"
    CANCELLED = "cancelled"


@dataclass
class JournalEntry:
    op_id: str
    state: OpState
    inverse: Optional[Callable[[], None]] = None


@dataclass
class BranchJournal:
    branch_id: str
    entries: Dict[str, JournalEntry] = field(default_factory=dict)
    sealed: bool = False
    authority_granted: bool = True

    def submit(self, op_id: str) -> None:
        if not self.authority_granted:
            raise RollbackInvariantError(
                f"commit authority revoked for {self.branch_id}; op {op_id} rejected"
            )
        if self.sealed:
            raise RollbackInvariantError(
                f"append to sealed journal {self.branch_id} (op {op_id}); route to reconciler"
            )
        self.entries[op_id] = JournalEntry(op_id=op_id, state=OpState.PENDING)

    def complete(self, op_id: str, inverse: Callable[[], None]) -> None:
        if self.sealed:
            # Late completion after seal: must be reconciled, never silently dropped.
            raise RollbackInvariantError(
                f"late completion of {op_id} on sealed journal {self.branch_id}; "
                f"quarantine and reconcile"
            )
        entry = self.entries[op_id]
        entry.state = OpState.TERMINAL
        entry.inverse = inverse

    def is_closed(self) -> bool:
        return all(e.state is not OpState.PENDING for e in self.entries.values())

    def seal_and_revoke(self) -> None:
        # Atomic transition: seal + revoke authority in one step.
        self.sealed = True
        self.authority_granted = False


def rollback_sweep(journal: BranchJournal, deadline_s: float = 30.0) -> str:
    """Apply inverses only if the journal is sealed and closed. Never sweep a live journal."""
    if not journal.sealed:
        raise RollbackInvariantError(
            f"sweep attempted on unsealed journal {journal.branch_id}"
        )
    if not journal.is_closed():
        pending = [e.op_id for e in journal.entries.values() if e.state is OpState.PENDING]
        raise RollbackInvariantError(
            f"sweep attempted with pending ops {pending} on {journal.branch_id}; "
            f"drain or quarantine first"
        )
    for entry in journal.entries.values():
        if entry.state is OpState.TERMINAL and entry.inverse is not None:
            entry.inverse()
    return "ROLLED_BACK"


def speculative_rollback(
    journal: BranchJournal,
    verdict_diverged: bool,
    drain_deadline_s: float = 30.0,
    clock: Callable[[], float] = time.monotonic,
) -> str:
    """Verdict revokes authority; closure gates the sweep. Drain if bounded, else quarantine."""
    if not verdict_diverged:
        return "NO_OP"

    # Step 1: revoke authority immediately on verdict — capacity to commit dies now.
    journal.authority_granted = False

    # Step 2: attempt drain until closure or deadline.
    start = clock()
    while not journal.is_closed():
        if clock() - start > drain_deadline_s:
            # Unbounded in-flight op: do not sweep. Quarantine for reconciliation.
            journal.sealed = True
            return "QUARANTINED"
        time.sleep(0.05)

    # Step 3: closure achieved — seal atomically, then sweep.
    journal.seal_and_revoke()
    return rollback_sweep(journal, deadline_s=drain_deadline_s)
