# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federated-memory-retrieval-as-a-privacy-budget-event-rather-than-a-read-and-how-does-the-epsilon-ledger-desyn.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-federated-memory-retrieval-as-a-privacy-budget-event-rather-than-a-read-and-how-does-the-epsilon-ledger-desyn.warrant.json
# Markdown SHA-256:   8adbd0772dfd3de8fc80dbb49cbef87f5efb8fc5ef309ffb185f22839dad1f94
# Code AST SHA-256:   b364c6819e08979c6a8a66d930f92f4234d4a49eff0a4f79ebae5efd62643976
# Verified Classes:   BudgetLedgerDesyncError, IsolationPredicateLeakError, LedgerEntry, TenantAccountant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class BudgetLedgerDesyncError(RuntimeError):
    """Raised when a federated retrieval's budget accounting cannot be
    reconciled with the tenant's authoritative ledger."""
    pass


class IsolationPredicateLeakError(RuntimeError):
    """Raised when a returned row's tenant does not match the querying tenant."""
    pass


@dataclass
class LedgerEntry:
    query_id: str
    tenant: str
    epsilon_class: str
    epsilon: float
    admitted_at: float


@dataclass
class TenantAccountant:
    tenant: str
    authoritative_epsilon: float = 0.0
    replica_epsilon: float = 0.0
    pending: dict = field(default_factory=dict)  # query_id -> LedgerEntry
    divergence_threshold: float = 0.05
    last_reconciled: float = 0.0

    def admit(self, query_id: str, epsilon_class: str, epsilon: float) -> LedgerEntry:
        # Write-ahead: charge the query event BEFORE execution, keyed on query_id.
        entry = LedgerEntry(
            query_id=query_id,
            tenant=self.tenant,
            epsilon_class=epsilon_class,
            epsilon=epsilon,
            admitted_at=time.time(),
        )
        self.pending[query_id] = entry
        self.authoritative_epsilon += epsilon
        self.replica_epsilon += epsilon  # optimistic; reconciled later
        return entry

    def settle(self, query_id: str, returned_rows: list) -> None:
        entry = self.pending.pop(query_id, None)
        if entry is None:
            raise BudgetLedgerDesyncError(
                f"ledger write miss for query {query_id} on tenant {self.tenant}; "
                f"possible re-shard drop or write-behind skip"
            )
        for row in returned_rows:
            if row.get("tenant_id") != self.tenant:
                raise IsolationPredicateLeakError(
                    f"tenant {self.tenant} received row from {row.get('tenant_id')} "
                    f"via query {query_id}"
                )
        # Charging is on the query event, NOT on row count. No adjustment here.

    def reconcile(self, planner_replica_epsilon: float) -> None:
        self.replica_epsilon = planner_replica_epsilon
        divergence = abs(self.authoritative_epsilon - self.replica_epsilon)
        if divergence > self.divergence_threshold:
            raise BudgetLedgerDesyncError(
                f"tenant {self.tenant} ledger divergence {divergence:.4f} "
                f"exceeds threshold {self.divergence_threshold}; "
                f"authoritative={self.authoritative_epsilon:.4f} "
                f"replica={self.replica_epsilon:.4f}"
            )
        self.last_reconciled = time.time()


def federated_retrieve(
    accountant: TenantAccountant,
    query_id: str,
    epsilon_class: str,
    epsilon: float,
    candidates: list,
    top_k: int,
) -> list:
    # Admission gate: charge the query event before any execution.
    accountant.admit(query_id, epsilon_class, epsilon)

    # DP aggregation over the union of tenant shards, then isolation filter.
    # The aggregate is charged regardless of how many rows survive filtering.
    noisy_scores = [(row, row["score"] + _laplace(epsilon)) for row in candidates]
    noisy_scores.sort(key=lambda pair: pair[1], reverse=True)
    admitted = [row for row, _ in noisy_scores[:top_k] if row.get("tenant_id") == accountant.tenant]

    # Settle: this will raise if the ledger entry was lost (re-shard, write-behind).
    accountant.settle(query_id, admitted)
    return admitted


def _laplace(scale: float) -> float:
    import random
    u = random.random() - 0.5
    return -scale * (1 if u >= 0 else -1) * __import__("math").log(1 - 2 * abs(u))
