# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-memory-tombstone-with-a-differential-privacy-noise-floor-that-already-absorbed-the-forgotten-record.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-federated-memory-tombstone-with-a-differential-privacy-noise-floor-that-already-absorbed-the-forgotten-record.warrant.json
# Markdown SHA-256:   2ba0f6c264bbb98f757122d60315eb124471e673ffa5a8182894df497295427b
# Code AST SHA-256:   aade0162696142cdd369b80525d0ad811f55782c9159e599f5c14160c99ca844
# Verified Classes:   TombstoneComplianceError, EpochWarrant, FederatedAggregate, FederatedMemoryFabric
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TombstoneComplianceError(RuntimeError):
    """Raised when a forget request cannot be honored without violating
    either the DP calibration or the reconstruction-oracle invariant."""
    pass


@dataclass(frozen=True)
class EpochWarrant:
    epoch_id: int
    cohort_hash: str
    epsilon_charged: float
    noise_seed_commitment: str
    tombstone_set: frozenset  # record ids retired in this epoch
    retired: bool = False


@dataclass
class FederatedAggregate:
    warrant: EpochWarrant
    published_value: float
    externally_observed: bool  # any peer cached this value


class FederatedMemoryFabric:
    def __init__(self):
        self._epochs: dict[int, FederatedAggregate] = {}
        self._current_epoch = 0

    def publish(self, cohort_hash: str, value: float, eps: float, seed_commit: str):
        self._current_epoch += 1
        w = EpochWarrant(
            epoch_id=self._current_epoch,
            cohort_hash=cohort_hash,
            epsilon_charged=eps,
            noise_seed_commitment=seed_commit,
            tombstone_set=frozenset(),
        )
        self._epochs[w.epoch_id] = FederatedAggregate(
            warrant=w, published_value=value, externally_observed=False
        )
        return w.epoch_id

    def honor_forget(self, record_id: str) -> int:
        """A forget request must retire the epoch, never edit it in place."""
        current = self._epochs[self._current_epoch]

        # Guard 1: never subtract from a published, externally-observed aggregate.
        if current.externally_observed:
            raise TombstoneComplianceError(
                f"epoch {current.epoch_id} is externally observed; "
                f"in-place subtraction of {record_id!r} would create a "
                f"reconstruction oracle (delta = x_i + noise_diff). "
                f"Retire the epoch and re-derive from clean source."
            )

        # Guard 2: tombstone sets are monotonic; a stale epoch cannot be re-used.
        if record_id in current.warrant.tombstone_set:
            raise TombstoneComplianceError(
                f"{record_id!r} already tombstoned in epoch "
                f"{current.epoch_id}; refusing to double-retire (stale checkpoint?)"
            )

        # Correct path: retire, re-derive, re-charge full epsilon, fresh noise.
        retired = EpochWarrant(
            epoch_id=current.epoch_id,
            cohort_hash=current.warrant.cohort_hash,
            epsilon_charged=current.warrant.epsilon_charged,
            noise_seed_commitment=current.warrant.noise_seed_commitment,
            tombstone_set=current.warrant.tombstone_set | {record_id},
            retired=True,
        )
        self._epochs[current.epoch_id] = FederatedAggregate(
            warrant=retired,
            published_value=current.published_value,  # burned, not edited
            externally_observed=current.externally_observed,
        )
        # caller must now re-aggregate from clean source under a NEW epoch
        return current.epoch_id

    def query(self, epoch_id: int) -> float:
        agg = self._epochs.get(epoch_id)
        if agg is None:
            raise TombstoneComplianceError(f"unknown epoch {epoch_id}")
        if agg.warrant.retired:
            raise TombstoneComplianceError(
                f"epoch {epoch_id} retired by tombstone "
                f"{sorted(agg.warrant.tombstone_set)}; queries must target "
                f"the re-derived successor epoch, not the burned aggregate."
            )
        return agg.published_value
