# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-peer-s-blackboard-delta-the-tombstone-resurrection-boundary-in-conflict-aware-forget-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-merge-a-peer-s-blackboard-delta-the-tombstone-resurrection-boundary-in-conflict-aware-forget-semantics.warrant.json
# Markdown SHA-256:   576d9f5c1f947ae0706e3abd93c232aafe0d9bcaaa0985cfe11b08e9b2b9b5e4
# Code AST SHA-256:   5a15af4eab2898084477a21f36990bd8ba2e4d6857cd43fdfbdb9c117cc4aa89
# Verified Classes:   TombstoneResurrectionError, DefiantAssertError, Tombstone, Delta, Blackboard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TombstoneResurrectionError(RuntimeError):
    """Raised when a merge would resurrect a tombstoned key without a valid re-admission warrant."""


class DefiantAssertError(RuntimeError):
    """Raised when a peer asserts a key it has already observed as tombstoned, without a warrant."""


@dataclass(frozen=True)
class Tombstone:
    key: str
    reason: str
    at_logical_time: int
    issuer: str


@dataclass(frozen=True)
class Delta:
    key: str
    value: Optional[str]
    at_logical_time: int
    issuer: str
    observed_tombstones: frozenset  # version vector of tombstones the issuer had seen
    warrant_scope: Optional[str] = None  # set only for re-admit deltas


@dataclass
class Blackboard:
    values: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)  # key -> set[Tombstone]; append-only
    parked: list = field(default_factory=list)

    def forget(self, ts: Tombstone) -> None:
        self.tombstones.setdefault(ts.key, set()).add(ts)
        self.values.pop(ts.key, None)

    def _warrant_dominates(self, delta: Delta, ts: Tombstone) -> bool:
        # A warrant must explicitly cover the quarantine reason and come from a
        # scope authorized to override it. Timestamp ordering is irrelevant here.
        return delta.warrant_scope is not None and delta.warrant_scope == ts.reason

    def merge(self, delta: Delta) -> None:
        ts_set = self.tombstones.get(delta.key, set())
        if ts_set:
            for ts in ts_set:
                if self._warrant_dominates(delta, ts):
                    # Legitimate re-admission: tombstone is retained (monotone),
                    # value is admitted.
                    self.values[delta.key] = delta.value
                    return
                if ts.key in delta.observed_tombstones:
                    # Peer saw the tombstone and asserted anyway: policy violation.
                    raise DefiantAssertError(
                        f"peer {delta.issuer} asserted {delta.key} after observing "
                        f"tombstone from {ts.issuer} (reason={ts.reason})"
                    )
            # Concurrent assert: peer never saw the tombstone. Park, do not merge.
            self.parked.append((delta, "no_warrant_after_tombstone"))
            return
        # No tombstone: normal value merge.
        self.values[delta.key] = delta.value

    def read(self, key: str) -> Optional[str]:
        if self.tombstones.get(key):
            return None  # tombstone dominates unless a warrant admitted a value
        return self.values.get(key)


def apply_remote_delta(bb: Blackboard, delta: Delta) -> None:
    """Coordinator entry point. Refuses to proceed on any resurrection risk."""
    try:
        bb.merge(delta)
    except DefiantAssertError:
        raise
    if delta.key in bb.tombstones and delta.key in bb.values:
        # Defensive invariant: a value must never coexist with an un-warranted tombstone.
        for ts in bb.tombstones[delta.key]:
            if not bb._warrant_dominates(delta, ts):
                raise TombstoneResurrectionError(
                    f"merge admitted value for {delta.key} under live tombstone "
                    f"from {ts.issuer} (reason={ts.reason}); refusing"
                )
