# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-causal-consistency-violation-under-concurrent-multi-agent-memory-tool-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-causal-consistency-violation-under-concurrent-multi-agent-memory-tool-writes.warrant.json
# Markdown SHA-256:   b2e27a10b287ef297e20ceb3945d5ee93e73a6eee024a958f8d5c8542f75e40a
# Code AST SHA-256:   55c576704c8534255cd1ff381675f6057b3a6c8f97a8c795a9b8c56ebd9b6760
# Verified Classes:   CausalWriteRefused, VectorClock, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class CausalWriteRefused(RuntimeError):
    """Raised when a memory write asserts a happens-before edge it cannot verify."""


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

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

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

    def merge(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 MemoryRecord:
    key: str
    value: str
    clock: VectorClock


def admit_write(
    writer_id: str,
    write: MemoryRecord,
    predecessor: MemoryRecord,
    merge_warrant: bool = False,
) -> MemoryRecord:
    """Admit a write under causal consistency, or refuse with a structured conflict."""
    if not write.clock.dominates(predecessor.clock):
        if predecessor.clock.concurrent_with(write.clock) and not merge_warrant:
            missing = {
                k: predecessor.clock.components[k]
                for k in predecessor.clock.components
                if write.clock.components.get(k, 0) < predecessor.clock.components[k]
            }
            raise CausalWriteRefused(
                f"write to {write.key!r} by {writer_id!r} is concurrent with stored "
                f"record; missing causal components: {missing}. "
                f"Fetch predecessor and retry, or supply a merge warrant."
            )
    # Successor: advance the write clock to dominate the predecessor.
    advanced = write.clock.merge(predecessor.clock)
    advanced.components[writer_id] = advanced.components.get(writer_id, 0) + 1
    return MemoryRecord(key=write.key, value=write.value, clock=advanced)


def run_trace() -> None:
    spec = MemoryRecord("task.spec", "spec-v1", VectorClock({"P": 1}))
    e_plan = MemoryRecord("task.plan", "plan-E", VectorClock({"P": 1, "E": 1}))
    a_plan = MemoryRecord("task.plan", "plan-A", VectorClock({"P": 1, "A": 1}))

    # E writes first: dominates spec, admitted.
    stored = admit_write("E", e_plan, spec)

    # A attempts to write without having observed E's record. Its clock is
    # concurrent with the stored record, so the tool must refuse.
    try:
        admit_write("A", a_plan, stored)
    except CausalWriteRefused as exc:
        print(f"refused: {exc}")

    # A absorbs the unseen predecessor and retries with a dominating clock.
    absorbed = MemoryRecord(
        "task.plan", "plan-A-merged", VectorClock({"P": 1, "E": 1, "A": 1})
    )
    final = admit_write("A", absorbed, stored)
    assert final.clock.dominates(stored.clock)


if __name__ == "__main__":
    run_trace()
