# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-rate-governor-reservation-that-was-committed-before-an-escalation-gate-when-the-gate-later-resolves-to-a-denial-and.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-rate-governor-reservation-that-was-committed-before-an-escalation-gate-when-the-gate-later-resolves-to-a-denial-and.warrant.json
# Markdown SHA-256:   7457c464fe9b0b478e6a67a3aff7129445aeb96809bacc23668bd4ac2865f6d5
# Code AST SHA-256:   6885103706688e7a3f7671638ae1631b20963f94a9f580e13e519d8bb084f4f7
# Verified Classes:   ReservationState, BudgetLedgerInconsistency, Reservation, ReservationLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict


class ReservationState(Enum):
    RESERVED = "reserved"
    COMMITTED = "committed"
    RELEASED = "released"


class BudgetLedgerInconsistency(RuntimeError):
    """Raised when the reservation ledger violates its accounting invariant.

    This is not a metric. A drift between admitted and (reserved + committed
    + released) means the instance's belief about its own capacity is corrupt,
    and continued operation will misattribute exhaustion to its own behavior.
    """
    pass


@dataclass
class Reservation:
    rid: str
    state: ReservationState
    admitted_at: float
    gate_p99_latency: float


@dataclass
class ReservationLedger:
    admitted_total: int = 0
    reservations: Dict[str, Reservation] = field(default_factory=dict)

    def admit(self, rid: str, now: float, gate_p99: float) -> Reservation:
        self.admitted_total += 1
        r = Reservation(rid, ReservationState.RESERVED, now, gate_p99)
        self.reservations[rid] = r
        return r

    def commit(self, rid: str) -> None:
        self._transition(rid, ReservationState.RESERVED, ReservationState.COMMITTED)

    def release(self, rid: str) -> None:
        self._transition(rid, ReservationState.RESERVED, ReservationState.RELEASED)

    def _transition(self, rid: str, frm: ReservationState, to: ReservationState) -> None:
        r = self.reservations.get(rid)
        if r is None:
            raise BudgetLedgerInconsistency(f"unknown reservation {rid}")
        if r.state is not frm:
            raise BudgetLedgerInconsistency(
                f"reservation {rid} in state {r.state.value}, expected {frm.value}"
            )
        r.state = to

    def reconcile(self, now: float) -> None:
        """Verify the accounting invariant and surface orphaned reservations.

        Invariant: every admitted reservation is in exactly one terminal or
        in-flight state, and the counts sum to admitted_total. Orphaned
        RESERVED records older than the gate's p99 latency are leak candidates.
        """
        counts = {s: 0 for s in ReservationState}
        orphans = []
        for r in self.reservations.values():
            counts[r.state] += 1
            if r.state is ReservationState.RESERVED and (now - r.admitted_at) > r.gate_p99_latency:
                orphans.append(r.rid)

        total = sum(counts.values())
        if total != self.admitted_total:
            raise BudgetLedgerInconsistency(
                f"ledger drift: admitted={self.admitted_total} accounted={total} "
                f"counts={ {k.value: v for k, v in counts.items()} }"
            )
        if orphans:
            raise BudgetLedgerInconsistency(
                f"orphaned reservations past gate p99 (leak candidates): {orphans}"
            )


def on_gate_denial(ledger: ReservationLedger, rid: str) -> None:
    """Denial MUST release, not merely stop. Missing this is the leak."""
    try:
        ledger.release(rid)
    except BudgetLedgerInconsistency as e:
        # Denial arrived after TTL reaper already released, or ledger corrupt.
        raise BudgetLedgerInconsistency(
            f"denial handler could not release {rid}: {e}"
        ) from e
