# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-vector-clock-memory-writes-before-semantic-merge-and-why-last-writer-wins-silently-corrupts-episodic-recall.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-vector-clock-memory-writes-before-semantic-merge-and-why-last-writer-wins-silently-corrupts-episodic-recall.warrant.json
# Markdown SHA-256:   012cd90700930f2b9697d4cb32e2c13e745dea4cec669e000a751fbb5e001eb7
# Code AST SHA-256:   5c94a5ac8388387f93cb0869f9e377e8167550f1546a0f03d074ad466312e907
# Verified Classes:   ConcurrentWriteCollapseError, VectorClock, MemoryEntry, ConflictSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ConcurrentWriteCollapseError(RuntimeError):
    """Raised when a store attempts to select a value from a concurrent
    write pair without an explicit resolver decision."""
    pass


@dataclass(frozen=True)
class VectorClock:
    components: Dict[str, int] = field(default_factory=dict)

    def dominates(self, other: "VectorClock") -> bool:
        keys = set(self.components) | set(other.components)
        ge = all(self.components.get(k, 0) >= other.components.get(k, 0) for k in keys)
        gt = any(self.components.get(k, 0) > other.components.get(k, 0) for k in keys)
        return ge and gt

    def concurrent(self, other: "VectorClock") -> bool:
        return not self.dominates(other) and not other.dominates(self)

    def join(self, other: "VectorClock") -> "VectorClock":
        keys = set(self.components) | set(other.components)
        return VectorClock({k: max(self.components.get(k, 0), other.components.get(k, 0)) for k in keys})


@dataclass
class MemoryEntry:
    key: str
    value: str
    vc: VectorClock
    physical_ts: float
    provenance: str


@dataclass
class ConflictSet:
    key: str
    entries: list
    merged_vc: VectorClock
    resolved: bool = False
    resolved_value: Optional[str] = None


def write(store: Dict[str, object], incoming: MemoryEntry) -> None:
    existing = store.get(incoming.key)
    if existing is None:
        store[incoming.key] = incoming
        return
    if isinstance(existing, ConflictSet):
        # Any new write joins the open conflict set; never collapse silently.
        existing.entries.append(incoming)
        existing.merged_vc = existing.merged_vc.join(incoming.vc)
        return
    assert isinstance(existing, MemoryEntry)
    if incoming.vc.dominates(existing.vc):
        store[incoming.key] = incoming
        return
    if existing.vc.dominates(incoming.vc):
        return  # stale write, safely rejected
    # Concurrent: MUST retain both. Selecting by physical_ts is forbidden.
    store[incoming.key] = ConflictSet(
        key=incoming.key,
        entries=[existing, incoming],
        merged_vc=existing.vc.join(incoming.vc),
    )


def resolve(store: Dict[str, object], key: str, chosen_value: str, resolver_id: str) -> None:
    cs = store.get(key)
    if not isinstance(cs, ConflictSet):
        raise ConcurrentWriteCollapseError(
            f"resolve() called on non-conflict key {key!r}; no concurrency to arbitrate"
        )
    if chosen_value not in {e.value for e in cs.entries}:
        raise ConcurrentWriteCollapseError(
            f"resolver {resolver_id!r} chose {chosen_value!r} not present in conflict set {key!r}"
        )
    cs.resolved = True
    cs.resolved_value = chosen_value
    # Clock and value advance together, atomically, only now.
    store[key] = MemoryEntry(
        key=key,
        value=chosen_value,
        vc=cs.merged_vc,
        physical_ts=max(e.physical_ts for e in cs.entries),
        provenance=f"resolved_by:{resolver_id}",
    )


def select_by_timestamp(store: Dict[str, object], key: str) -> str:
    """The forbidden path, kept as an explicit tripwire for review."""
    cs = store.get(key)
    if isinstance(cs, ConflictSet):
        raise ConcurrentWriteCollapseError(
            f"attempted last-writer-wins collapse on concurrent key {key!r} "
            f"with {len(cs.entries)} retained entries; route to resolver instead"
        )
    entry = store.get(key)
    if not isinstance(entry, MemoryEntry):
        raise ConcurrentWriteCollapseError(f"key {key!r} has no single resolved value")
    return entry.value
