# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-erasure-request-as-satisfied-before-the-tombstone-has-propagated-to-all-replica-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-erasure-request-as-satisfied-before-the-tombstone-has-propagated-to-all-replica-stores.warrant.json
# Markdown SHA-256:   61c5539e3e90a51eba350f92dbcb56ed3b001d8d26b34159c9453522ae3bf18f
# Code AST SHA-256:   10965c3e314061a7c5c0f1b447a0b7b2f4886aaaa49169e6066d3416b42e29a8
# Verified Classes:   ErasureAttestationError, ErasureCoordinator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ErasureAttestationError(RuntimeError):
    """Raised when an agent attempts to attest erasure before the federated invariant holds."""
    pass


class ErasureCoordinator:
    def __init__(self, replicas, cache, provenance, replay_log):
        self.replicas = replicas          # dict: replica_id -> ack state
        self.cache = cache                # similarity cache, value-provenance tagged
        self.provenance = provenance      # maps artifact_id -> set of subject_ids
        self.replay_log = replay_log      # append-only, sharded

    def attest_erasure(self, subject_id):
        # C1: every replica acked OR fenced
        unacked = [r for r, st in self.replicas.items() if st not in ("acked", "fenced")]
        if unacked:
            raise ErasureAttestationError(
                f"C1 violated: replicas {unacked} still authoritative for {subject_id}"
            )

        # C2: derived-artifact closure
        if not self.provenance.has_coverage(subject_id):
            raise ErasureAttestationError(
                f"C2 unverifiable: provenance stripped for {subject_id}; cannot enumerate derived artifacts"
            )
        live_derived = self.provenance.artifacts_derived_from(subject_id)
        if live_derived:
            raise ErasureAttestationError(
                f"C2 violated: derived artifacts {live_derived} still resolve {subject_id}"
            )

        # C3: replay ordering — tombstone must causally follow every governed record
        if not self.replay_log.tombstone_dominates(subject_id):
            raise ErasureAttestationError(
                f"C3 violated: tombstone for {subject_id} not causally after all records across shards"
            )

        # C4: similarity cache addressed by value, not ID
        if self.cache.resolves_value_from(subject_id):
            raise ErasureAttestationError(
                f"C4 violated: similarity cache still serves value derived from {subject_id}"
            )

        return {"subject": subject_id, "state": "erased", "linearized_at": self.replay_log.now()}
