# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-byzantine-memory-poisoning-from-surviving-a-crdt-merge-in-federated-agent-clusters.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-byzantine-memory-poisoning-from-surviving-a-crdt-merge-in-federated-agent-clusters.warrant.json
# Markdown SHA-256:   39e7846f6acaf10fa4f04802806bb519086e72d2ded85c06fd20cf93c75213a0
# Code AST SHA-256:   155ef5e1c624c6b9119a1e38d0943357d6c74cedb6e1c1146bab60fcdf5bac45
# Verified Classes:   CausalAdmissibilityError, AdmissibleMerger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CausalAdmissibilityError(RuntimeError):
    """Raised when a CRDT delta would merge a tombstone or add violating causal admissibility."""
    pass


class AdmissibleMerger:
    """
    Wraps an OR-Set-style merge with causal-admissibility gating.
    A tombstone for tag T is applied only if the add for T has been
    locally verified. Unverified tombstones are quarantined, never dropped.
    """

    def __init__(self, verified_adds, verified_tombstones, quorum_attestation):
        self.verified_adds = set(verified_adds)          # tags whose add passed signature check
        self.verified_tombstones = set(verified_tombstones)
        self.quorum_attestation = quorum_attestation      # dict tag -> set of signer ids
        self.pending_causal = {}                          # tag -> list of held tombstones
        self.pending_attest = {}                          # tag -> add awaiting f+1 attestations
        self.f = quorum_attestation.get("_f", 2)

    def merge_delta(self, delta, origin_sig_ok):
        if not origin_sig_ok:
            raise CausalAdmissibilityError(
                f"delta from origin failed signature verification; refusing merge"
            )

        for tag, record in delta.get("adds", {}).items():
            signers = self.quorum_attestation.get(tag, set())
            if len(signers) < self.f + 1:
                # structurally valid but not yet admitted to semantic memory
                self.pending_attest[tag] = record
                continue
            self.verified_adds.add(tag)

        for tag in delta.get("tombstones", set()):
            if tag in self.verified_adds or tag in self.verified_tombstones:
                self.verified_tombstones.add(tag)
            else:
                # causal predecessor not locally verified: quarantine, do NOT apply
                self.pending_causal.setdefault(tag, []).append(delta["origin"])

        return self._materialize()

    def _materialize(self):
        live = {
            tag: rec for tag, rec in self.pending_attest.items()
            if tag not in self.verified_tombstones
        }
        return {
            "live": live,
            "quarantined_tombstones": list(self.pending_causal.keys()),
            "pending_attestation": list(self.pending_attest.keys()),
        }


def apply_byzantine_delta(merger, delta, origin_sig_ok):
    result = merger.merge_delta(delta, origin_sig_ok)

    # If any quarantined tombstone references a tag that never resolves,
    # the cluster must stall and escalate rather than silently converge.
    unresolved = [
        tag for tag, origins in merger.pending_causal.items()
        if tag not in merger.verified_adds
    ]
    if len(unresolved) > merger.f:
        raise CausalAdmissibilityError(
            f"{len(unresolved)} tombstones reference unverified tags "
            f"(f={merger.f}); possible Byzantine erasure attempt, escalating"
        )
    return result
