# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-merge-a-federated-crdt-memory-delta-when-its-causal-history-is-only-partially-visible.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-merge-a-federated-crdt-memory-delta-when-its-causal-history-is-only-partially-visible.warrant.json
# Markdown SHA-256:   e511c7e91ea9706b0ee1a305738c04b06e486b45ab6ae9516ecdc597636476c3
# Code AST SHA-256:   553cf126299d5c6d7edc1584ebd6b32cb0343d1ac25b9351fbd5ccc715da2f77
# Verified Classes:   CausalGapError, FederatedDelta, LocalReplica
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Optional, Set, Tuple

OpId = Tuple[int, str]  # (lamport, replica_id)


class CausalGapError(RuntimeError):
    """Raised when a federated CRDT delta advances a replica's frontier across
    a redaction gap whose remove-coverage cannot be computed."""
    pass


@dataclass
class FederatedDelta:
    origin_replica: str
    version_vector: Dict[str, int]           # claimed visible frontier
    gaps: Dict[str, Set[int]]                # replica_id -> missing lamports
    visible_dots: Set[OpId]                  # dots present in this delta
    redaction_tombstones: Dict[OpId, str]    # redacted op dot -> acl predicate
    removes: Set[OpId]                       # remove ops in this delta
    is_remove_wins: bool = False


@dataclass
class LocalReplica:
    replica_id: str
    version_vector: Dict[str, int] = field(default_factory=dict)
    known_dots: Set[OpId] = field(default_factory=set)
    causally_incomplete_slots: Set[str] = field(default_factory=set)


def merge_delta(local: LocalReplica, delta: FederatedDelta, slot: str) -> None:
    # 1. Determine whether the delta's frontier is dominated by local frontier
    #    *plus* the delta's own declared gaps.
    for replica, claimed in delta.version_vector.items():
        local_v = local.version_vector.get(replica, 0)
        if claimed <= local_v:
            continue  # already seen up to claimed; nothing new for this replica
        # Delta advances our frontier for `replica`. Check for gaps we cannot fill.
        missing = delta.gaps.get(replica, set())
        unfillable = {m for m in missing if m > local_v}
        if unfillable:
            # A redaction gap sits between our frontier and the delta's claim.
            # We can only proceed if every redacted dot is preserved as a
            # tombstone AND the delta is add-wins (no pending remove on slot).
            covered = {d for d in delta.redaction_tombstones
                       if d[1] == replica and d[0] in unfillable}
            if covered != {(m, replica) for m in unfillable}:
                raise CausalGapError(
                    f"delta from {delta.origin_replica} advances {replica} to "
                    f"{claimed} across unfillable redaction gap {sorted(unfillable)}; "
                    f"tombstones cover only {sorted(covered)}"
                )
            if delta.is_remove_wins and delta.removes:
                raise CausalGapError(
                    f"remove-wins delta from {delta.origin_replica} carries remove(s) "
                    f"{sorted(delta.removes)} whose dot-set coverage spans redaction "
                    f"gap {sorted(unfillable)} on slot {slot!r}; coverage uncomputable"
                )
            # Add-wins, fully tombstoned: mark slot incomplete, do not advance.
            local.causally_incomplete_slots.add(slot)
            return

    # 2. Sound merge: advance frontier, fold dots, fold tombstones.
    for replica, claimed in delta.version_vector.items():
        local.version_vector[replica] = max(
            local.version_vector.get(replica, 0), claimed
        )
    local.known_dots |= delta.visible_dots
    local.known_dots |= set(delta.redaction_tombstones.keys())
    local.causally_incomplete_slots.discard(slot)


def reconcile(local: LocalReplica, deltas: list[FederatedDelta], slot: str) -> None:
    for d in deltas:
        try:
            merge_delta(local, d, slot)
        except CausalGapError:
            # Quarantine: request a gap-closing delta from the origin replica,
            # do not advance frontier, do not serve the slot as fresh.
            local.causally_incomplete_slots.add(slot)
            raise
