# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-resolve-a-contradiction-between-two-memory-writes-when-provenance-is-asymmetric.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-resolve-a-contradiction-between-two-memory-writes-when-provenance-is-asymmetric.warrant.json
# Markdown SHA-256:   c327a9eb355bb2c41e2cccdd98ecc1da14b3b468cb5ac17c765cebc718ee91ad
# Code AST SHA-256:   aa0e06e9873d48ff912e9885b10f6391ba9f6dbb06e5d4ec3ff32c9eba9c66e4
# Verified Classes:   ProvenanceContradictionError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ProvenanceContradictionError(RuntimeError):
    """Raised when a contradiction cannot be resolved by confidence-weighted join
    because the records are not independent observations."""
    pass


@dataclass
class MemoryRecord:
    id: str
    proposition: str
    confidence: float
    derivation: list[str] = field(default_factory=list)  # ancestor record ids
    tombstoned: bool = False


def _closure(rec: MemoryRecord, store: dict[str, MemoryRecord]) -> set[str]:
    seen: set[str] = set()
    stack = list(rec.derivation)
    while stack:
        rid = stack.pop()
        if rid in seen:
            continue
        seen.add(rid)
        ancestor = store.get(rid)
        if ancestor is not None:
            stack.extend(ancestor.derivation)
    return seen


def resolve_contradiction(
    a: MemoryRecord, b: MemoryRecord, store: dict[str, MemoryRecord]
) -> MemoryRecord:
    if a.proposition == b.proposition:
        return a  # no contradiction

    closure_a = _closure(a, store)
    closure_b = _closure(b, store)

    # Dangling derivation edge: an ancestor was tombstoned.
    for rec, closure in ((a, closure_a), (b, closure_b)):
        for rid in closure:
            anc = store.get(rid)
            if anc is None or anc.tombstoned:
                raise ProvenanceContradictionError(
                    f"record {rec.id!r} has dangling derivation edge to {rid!r}; "
                    f"quarantine, do not resolve"
                )

    # Ancestor/descendant conflict: never vote, always re-derive.
    if a.id in closure_b or b.id in closure_a:
        raise ProvenanceContradictionError(
            f"records {a.id!r} and {b.id!r} are in an ancestor/descendant "
            f"relation; confidence join is invalid, re-derive descendant"
        )

    # Shared non-independent ancestor: both descendants are suspect.
    shared = closure_a & closure_b
    if shared and not (a.derivation == [] or b.derivation == []):
        raise ProvenanceContradictionError(
            f"records {a.id!r} and {b.id!r} share non-independent ancestor(s) "
            f"{sorted(shared)!r}; invalidate both, do not pick a winner"
        )

    # Peer conflict between independent observations: safe to join.
    return a if a.confidence >= b.confidence else b
