# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-speculative-branch-commit-that-has-already-been-observed-by-a-peer-agent-before-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-speculative-branch-commit-that-has-already-been-observed-by-a-peer-agent-before-rollback.warrant.json
# Markdown SHA-256:   31562f4252cc33955623e59e27910c84a19208fb671dc45f4225f21ecffc30ea
# Code AST SHA-256:   76ba5dc160843d0c74e93c5bed9ce9e6086fe8868f0bb6ab0219f1cc961ccf51
# Verified Classes:   OrphanedBeliefError, CommitStatus, CommitToken, LedgerEntry, PeerPremise, CommitLedger, AuditorMemory
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class OrphanedBeliefError(RuntimeError):
    """Raised when a peer premise resolves to an aborted speculative branch."""
    pass


class CommitStatus(Enum):
    PENDING = "pending"
    COMMITTED = "committed"
    ABORTED = "aborted"


@dataclass(frozen=True)
class CommitToken:
    branch_id: str
    orchestrator_epoch: int
    write_id: str


@dataclass
class LedgerEntry:
    token: CommitToken
    status: CommitStatus
    terminal_at: Optional[float] = None


@dataclass
class PeerPremise:
    content: str
    token: CommitToken
    consumed_by_action: bool = False
    distilled_at: float = field(default_factory=time.time)


class CommitLedger:
    def __init__(self) -> None:
        self._entries: Dict[CommitToken, LedgerEntry] = {}

    def record(self, token: CommitToken, status: CommitStatus) -> None:
        self._entries[token] = LedgerEntry(
            token=token,
            status=status,
            terminal_at=time.time() if status is not CommitStatus.PENDING else None,
        )

    def status_of(self, token: CommitToken) -> Optional[CommitStatus]:
        entry = self._entries.get(token)
        return entry.status if entry else None


class AuditorMemory:
    def __init__(self) -> None:
        self._premises: List[PeerPremise] = []

    def distill(self, content: str, token: CommitToken) -> None:
        # Distillation preserves content and token; it must never drop the token.
        self._premises.append(PeerPremise(content=content, token=token))

    def premises(self) -> List[PeerPremise]:
        return list(self._premises)

    def invalidate(self, premise: PeerPremise) -> None:
        self._premises = [p for p in self._premises if p is not premise]


def reconcile_peer_with_ledger(
    memory: AuditorMemory,
    ledger: CommitLedger,
    current_epoch: int,
) -> List[PeerPremise]:
    """
    Returns the list of orphaned premises found. Raises OrphanedBeliefError
    on the first premise that is both orphaned and already consumed by an
    action, since that requires a hard incident rather than routine retraction.
    """
    orphans: List[PeerPremise] = []
    for premise in memory.premises():
        token = premise.token
        if token.orchestrator_epoch != current_epoch:
            # Epoch advanced; ledger entry may be compacted. Cannot adjudicate.
            continue
        status = ledger.status_of(token)
        if status is None:
            # Token never recorded: fabricated belief, not a speculation leak.
            continue
        if status is CommitStatus.ABORTED:
            orphans.append(premise)
            if premise.consumed_by_action:
                raise OrphanedBeliefError(
                    f"Premise {premise.content!r} from aborted branch "
                    f"{token.branch_id} (write {token.write_id}) was consumed "
                    f"by an action before detection; rollback of effects required."
                )
    return orphans


def repair(memory: AuditorMemory, orphans: List[PeerPremise]) -> int:
    """Retract held (unconsumed) orphaned beliefs. Returns count retracted."""
    for premise in orphans:
        memory.invalidate(premise)
    return len(orphans)
