# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-vector-clock-merge-that-is-causally-consistent-but-byzantine-tainted.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-vector-clock-merge-that-is-causally-consistent-but-byzantine-tainted.warrant.json
# Markdown SHA-256:   248ab44dea35d64416aa6eaa094ec179c08b716eef61dd005c473f8693aa9885
# Code AST SHA-256:   7f1239845874856dbf023750cd1a018ac700fb6a42ec9d557ae32746a81a20d6
# Verified Classes:   ByzantineClockError, Attestation, VectorClock
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ByzantineClockError(RuntimeError):
    """Raised when a vector-clock merge would admit a forged load-bearing component."""
    pass


@dataclass
class Attestation:
    attester: str
    owner: str
    component: int
    timestamp: int


@dataclass
class VectorClock:
    components: Dict[str, int]
    attestations: Set[Attestation] = field(default_factory=set)


def _foreign_attestation_count(clock: VectorClock, owner: str, component: int) -> int:
    return len({
        a.attester for a in clock.attestations
        if a.owner == owner and a.component >= component and a.attester != owner
    })


def _is_load_bearing(local: VectorClock, incoming: VectorClock, owner: str) -> bool:
    # A component is load-bearing if raising it would flip a pairwise ordering
    # against any other owner's current component.
    raised = incoming.components[owner]
    if raised <= local.components.get(owner, 0):
        return False
    for other, val in local.components.items():
        if other == owner:
            continue
        if val <= raised and raised <= val:
            continue
        if (val < raised) != (local.components.get(owner, 0) < val):
            return True
    return raised > local.components.get(owner, 0)


def merge_clocks(local: VectorClock, incoming: VectorClock, f: int) -> VectorClock:
    """Merge incoming into local, rejecting Byzantine-tainted load-bearing components."""
    merged = dict(local.components)
    for owner, comp in incoming.components.items():
        if comp <= merged.get(owner, 0):
            continue
        if _is_load_bearing(local, incoming, owner):
            foreign = _foreign_attestation_count(incoming, owner, comp)
            if foreign < f + 1:
                raise ByzantineClockError(
                    f"load-bearing component {owner}={comp} has only {foreign} "
                    f"foreign attestations, need {f + 1}"
                )
        merged[owner] = comp
    return VectorClock(merged, local.attestations | incoming.attestations)


def apply_remote_clock(local: VectorClock, incoming: VectorClock, f: int) -> VectorClock:
    try:
        return merge_clocks(local, incoming, f)
    except ByzantineClockError as e:
        # Quarantine and fall back to last quorum-attested state for the owner.
        raise ByzantineClockError(f"quarantined incoming clock: {e}") from e
