# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-crdt-merged-memory-vector-when-the-merge-is-causally-valid-but-semantically-poisoned.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-crdt-merged-memory-vector-when-the-merge-is-causally-valid-but-semantically-poisoned.warrant.json
# Markdown SHA-256:   19acf6becbe883f831c1cf784ca251cb941dce9c5ee7b2c002cd64d443958451
# Code AST SHA-256:   441512007d1f2a2aabbf8f5bfe47c0ef496323a14d324d550d29ba861a01e3f8
# Verified Classes:   Resolution, TTLClass, MemoryValue, MergedRecord, PoisonedMergeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class Resolution(Enum):
    CAUSAL = "causal"
    LWW = "lww"
    ARBITRARY = "arbitrary"
    QUARANTINED = "quarantined"


class TTLClass(Enum):
    PROVISIONAL = 1
    COMMITTED = 2


@dataclass(frozen=True)
class MemoryValue:
    value: str
    hlc: int
    writer_id: str
    ttl_class: TTLClass


@dataclass(frozen=True)
class MergedRecord:
    key: str
    winner: MemoryValue
    losers: tuple
    resolution: Resolution
    flap_count: int


class PoisonedMergeError(RuntimeError):
    """Raised when a CRDT merge is causally valid but semantically unsafe to act on."""


def gate_merged_record(record: MergedRecord, flap_threshold: int = 3) -> MemoryValue:
    # Invariant 1: a provisional loser must never be silently dominated.
    for loser in record.losers:
        if loser.ttl_class is TTLClass.PROVISIONAL and record.winner.ttl_class is TTLClass.COMMITTED:
            raise PoisonedMergeError(
                f"key={record.key}: provisional value {loser.value!r}@{loser.hlc} "
                f"dominated by committed {record.winner.value!r}@{record.winner.hlc}; "
                f"merge is a valid join but not a safe belief"
            )

    # Invariant 2: arbitrary tiebreaks are not authoritative.
    if record.resolution is Resolution.ARBITRARY:
        raise PoisonedMergeError(
            f"key={record.key}: resolved by arbitrary tiebreak (writer_id="
            f"{record.winner.writer_id}); agent must re-derive, not read"
        )

    # Invariant 3: contested keys are quarantined, not read.
    if record.flap_count >= flap_threshold:
        raise PoisonedMergeError(
            f"key={record.key}: flapped {record.flap_count} times in window; "
            f"quarantined pending re-derivation"
        )

    return record.winner
