# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-commits-before-rollback-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-commits-before-rollback-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   0b6be89aed46a4c87646eeaddf48e43bb8816b094eb01cdba772ff9f81fb7667
# Code AST SHA-256:   262488d77b34473636792d4a982d798b5692a2dad42ea3d8e09fa7c2ceff0235
# Verified Classes:   ReconciliationError, EffectStatus, LedgerEntry, CancellationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when speculative rollback reconciliation is unsound."""


class EffectStatus(Enum):
    IN_FLIGHT = "in_flight"
    LANDED = "landed"
    ABORTED = "aborted"
    QUARANTINED = "quarantined"


@dataclass
class LedgerEntry:
    branch_id: str
    epoch: int
    tool_call_id: str
    effect_descriptor: str
    status: EffectStatus = EffectStatus.IN_FLIGHT
    landed_at: Optional[float] = None


@dataclass
class CancellationLedger:
    entries: list[LedgerEntry] = field(default_factory=list)
    current_epoch: int = 0

    def record_call(self, branch_id: str, tool_call_id: str, effect: str) -> LedgerEntry:
        entry = LedgerEntry(
            branch_id=branch_id,
            epoch=self.current_epoch,
            tool_call_id=tool_call_id,
            effect_descriptor=effect,
        )
        self.entries.append(entry)
        return entry

    def mark_landed(self, tool_call_id: str) -> None:
        for e in self.entries:
            if e.tool_call_id == tool_call_id:
                e.status = EffectStatus.LANDED
                e.landed_at = time.monotonic()
                return

    def begin_cancellation_wave(self) -> int:
        self.current_epoch += 1
        return self.current_epoch


def reconcile(
    ledger: CancellationLedger,
    winner_id: str,
    cancelled_branch_ids: set[str],
    interruptibility_class: str,
    ack_deadline_s: float,
) -> list[LedgerEntry]:
    """
    Freeze, cancel, wait for acknowledgement, then sweep.

    Raises ReconciliationError if the reconciliation is unsound: in-flight
    effects from cancelled branches older than the current wave, or landed
    effects whose epoch precedes the wave (orphans) that cannot be attributed.
    """
    if interruptibility_class == "non_interruptible" and ack_deadline_s <= 0:
        raise ReconciliationError(
            "non-interruptible tools require a positive acknowledgement deadline; "
            "lazy reconciliation is unsound for this branch surface"
        )

    # Freeze is implicit: we snapshot the ledger's current view.
    frozen = list(ledger.entries)
    wave = ledger.current_epoch

    # Wait for in-flight effects from cancelled branches to resolve.
    deadline = time.monotonic() + ack_deadline_s
    while time.monotonic() < deadline:
        pending = [
            e for e in frozen
            if e.branch_id in cancelled_branch_ids and e.status is EffectStatus.IN_FLIGHT
        ]
        if not pending:
            break
        time.sleep(0.05)

    orphans: list[LedgerEntry] = []
    for e in frozen:
        if e.branch_id not in cancelled_branch_ids:
            continue
        if e.status is EffectStatus.IN_FLIGHT:
            raise ReconciliationError(
                f"branch {e.branch_id} tool {e.tool_call_id} still in flight after "
                f"{ack_deadline_s}s; reconciliation cannot be sound"
            )
        if e.status is EffectStatus.LANDED:
            if e.epoch < wave:
                # Landed after the wave began but tagged with an older epoch:
                # produced in the cancellation window. Quarantine, do not preserve.
                e.status = EffectStatus.QUARANTINED
                orphans.append(e)
            else:
                raise ReconciliationError(
                    f"branch {e.branch_id} emitted effect {e.effect_descriptor} "
                    f"in the current wave ({e.epoch}); cannot distinguish orphan "
                    f"from concurrent external write"
                )

    if orphans:
        # Escalate rather than revert or preserve: attribution is ambiguous.
        raise ReconciliationError(
            f"{len(orphans)} orphaned effect(s) quarantined from cancelled branches "
            f"after winner {winner_id} was selected; adjudication required before commit"
        )

    return frozen
