# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-memory-conflict-against-a-provenance-chain-it-cannot-re-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-memory-conflict-against-a-provenance-chain-it-cannot-re-verify.warrant.json
# Markdown SHA-256:   bf35ef5ff2e77a53ba434358f930a1872a6bc501484734a9959dbd2ed8eb356e
# Code AST SHA-256:   699f387801d5189698c22e85eb361338a9d77139a355d5d5ec856764e62d8e0b
# Verified Classes:   ProvenanceLaunderingError, Episode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when same-root episodes disagree on payload and the store is asked to rank them."""


@dataclass(frozen=True)
class Episode:
    episode_id: str
    key: str
    payload: str
    provenance_root: str          # call-hash + parent, identity of originating event
    recorded_at: int              # monotonic write timestamp
    confidence: float
    derivation: Optional[str] = None  # name of transform if this is a distilled episode


def resolve(store: list[Episode], key: str) -> Episode:
    candidates = [e for e in store if e.key == key]
    if not candidates:
        raise ProvenanceLaunderingError(f"no episodes for key={key!r}")

    roots = {e.provenance_root for e in candidates}
    if len(roots) > 1:
        # independent observations: ranking is meaningful
        return max(candidates, key=lambda e: (e.confidence, e.recorded_at))

    # single root: candidates are not independent
    payloads = {e.payload for e in candidates}
    if len(payloads) == 1:
        return candidates[0]

    # same root, disagreeing payloads: at least one is a distillation mutation.
    # Ranking by recency would select the mutation; ranking by confidence is meaningless.
    observations = [e for e in candidates if e.derivation is None]
    if len(observations) != 1:
        raise ProvenanceLaunderingError(
            f"same-root conflict on key={key!r}, root={next(iter(roots))!r}: "
            f"{len(observations)} un-derived observations among {len(candidates)} candidates; "
            f"cannot identify the originating episode. Force live re-observation."
        )
    return observations[0]


def read_verified(store: list[Episode], key: str, live_check) -> Episode:
    """Resolve with a live re-observation fallback when provenance is unverifiable."""
    try:
        return resolve(store, key)
    except ProvenanceLaunderingError:
        fresh = live_check(key)
        if fresh is None:
            raise ProvenanceLaunderingError(
                f"provenance laundering on key={key!r} and live source unreachable; "
                f"refusing to return a ranked winner"
            )
        return fresh
