# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-shared-memory-record-whose-dp-noise-budget-has-already-been-consumed-by-an-upstream-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-shared-memory-record-whose-dp-noise-budget-has-already-been-consumed-by-an-upstream-peer.warrant.json
# Markdown SHA-256:   66bf74787e9735ecc34747a14494b7d523a90139a499465a671b68e961351160
# Code AST SHA-256:   8330eb2ab05c051604d704e45cc2e3189e2e66f6e58d5bdaeac4859a0012f359
# Verified Classes:   LineageAdmissionError, LineageEntry, SharedMemoryRecord, ReceiverAccountant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageAdmissionError(RuntimeError):
    """Raised when a shared memory record cannot be admitted under the
    federation DP composition invariant."""
    pass


@dataclass
class LineageEntry:
    accountant_id: str
    epsilon: float
    delta: float


@dataclass
class SharedMemoryRecord:
    record_id: str
    payload: object
    lineage: list[LineageEntry] = field(default_factory=list)
    epoch: int = 0
    tainted: bool = False


@dataclass
class ReceiverAccountant:
    accountant_id: str
    reachable_peers: set[str]
    per_record_epsilon_cap: float
    per_record_delta_cap: float
    current_epoch: int
    ledger: dict[str, float] = field(default_factory=dict)

    def can_charge(self, entry: LineageEntry) -> bool:
        return entry.accountant_id in self.reachable_peers or entry.accountant_id == self.accountant_id

    def charge(self, entry: LineageEntry) -> None:
        self.ledger[entry.accountant_id] = self.ledger.get(entry.accountant_id, 0.0) + entry.epsilon


def admit_record(
    record: SharedMemoryRecord,
    accountant: ReceiverAccountant,
    reemission_capable: bool,
) -> SharedMemoryRecord:
    """Admit a federated memory record into the local store.

    Invariant: a record may enter a re-emission-capable store only if its
    complete budget lineage is present, every lineage principal is chargeable
    by the receiver's accountant, and the composed epsilon (lineage + proposed
    emission) stays under the tightest per-record cap in the lineage.
    """
    if not record.lineage:
        # No lineage: safe only for consume-only stores, and must be tainted
        # so downstream distillation cannot re-publish it.
        if reemission_capable:
            raise LineageAdmissionError(
                f"record {record.record_id} has empty lineage but target store "
                f"is re-emission-capable; refusing admission"
            )
        record.tainted = True
        return record

    for entry in record.lineage:
        if not accountant.can_charge(entry):
            raise LineageAdmissionError(
                f"record {record.record_id} lineage references "
                f"accountant {entry.accountant_id} which receiver "
                f"{accountant.accountant_id} cannot charge"
            )
        if entry.epoch < accountant.current_epoch - _key_rotation_window(accountant):
            raise LineageAdmissionError(
                f"record {record.record_id} lineage entry {entry.accountant_id} "
                f"predates key rotation; epsilon is un-chargeable"
            )

    if reemission_capable:
        composed_eps = sum(e.epsilon for e in record.lineage)
        tightest_cap = min(
            [accountant.per_record_epsilon_cap]
            + [_cap_for(accountant, e.accountant_id) for e in record.lineage]
        )
        if composed_eps > tightest_cap:
            raise LineageAdmissionError(
                f"record {record.record_id} composed epsilon {composed_eps:.3f} "
                f"exceeds tightest lineage cap {tightest_cap:.3f}"
            )

    for entry in record.lineage:
        accountant.charge(entry)
    return record


def distill(records: list[SharedMemoryRecord], accountant: ReceiverAccountant) -> SharedMemoryRecord:
    """Emit a semantic memory derived from admitted records.

    Guard: any tainted input propagates taint to the output, and a tainted
    output may not be published with a fresh accountant_id.
    """
    if any(r.tainted for r in records):
        raise LineageAdmissionError(
            "cannot distill from tainted records; downstream re-emission "
            "would consume un-accounted budget against originating principals"
        )
    # ... clustering / summarization ...
    output = SharedMemoryRecord(
        record_id=f"distilled-{accountant.current_epoch}",
        payload=None,
        lineage=[LineageEntry(accountant.accountant_id, 0.6, 1e-6)],
        epoch=accountant.current_epoch,
    )
    return output


def _cap_for(accountant: ReceiverAccountant, peer_id: str) -> float:
    # In practice resolved via federation agreement lookup; default to the
    # receiver's own cap as the conservative bound.
    return accountant.per_record_epsilon_cap


def _key_rotation_window(accountant: ReceiverAccountant) -> int:
    return 1
