# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-from-silently-resurrecting-contradicted-facts-during-provenance-aware-memory-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-from-silently-resurrecting-contradicted-facts-during-provenance-aware-memory-reconciliation.warrant.json
# Markdown SHA-256:   8be5a5317e64b265bbcbe99dfbd1ba9f6bc9041ac587d42fca2f991c94328675
# Code AST SHA-256:   c2341bc05ba7943c65b567728525f75410be0ef8a1b12fd1a7e8262adf5ec013
# Verified Classes:   ContradictionInversionError, Record, Edge
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ContradictionInversionError(RuntimeError):
    """Raised when a read would surface a record whose suppressor expired
    without the contradiction being re-verified or flagged."""
    pass


@dataclass
class Record:
    key: str
    value: str
    confidence: float
    ttl: int
    written_at: int
    source: str
    tombstoned: bool = False

    def is_live(self, now: int) -> bool:
        return not self.tombstoned and (now - self.written_at) < self.ttl


@dataclass
class Edge:
    winner: str
    loser: str
    created_at: int
    # edge lifetime = union of both TTLs, never the winner's alone
    expires_at: int


def reconcile_read(store: list[Record], edges: list[Edge],
                   key: str, now: int) -> Record:
    candidates = [r for r in store if r.key == key]
    live = [r for r in candidates if r.is_live(now)]
    if not live:
        raise ContradictionInversionError(f"no live record for {key}")

    # A live record is answerable only if no edge suppresses it via an
    # expired-but-remembered winner.
    answerable = []
    for r in live:
        suppressed = False
        for e in edges:
            if e.loser != r.key:
                continue
            winner = next((w for w in candidates if w.key == e.winner), None)
            winner_live = winner is not None and winner.is_live(now)
            if winner_live:
                suppressed = True          # normal suppression
            elif now < e.expires_at:
                # suppressor expired but edge still in force:
                # must NOT promote r to clean truth
                raise ContradictionInversionError(
                    f"{r.key}={r.value} (src {r.source}) would be surfaced, "
                    f"but its suppressor {e.winner} expired at "
                    f"{winner.written_at + winner.ttl} and the contradiction "
                    f"edge persists until {e.expires_at}; re-verify or flag."
                )
        if not suppressed:
            answerable.append(r)

    if not answerable:
        raise ContradictionInversionError(
            f"all live records for {key} suppressed by live edges"
        )
    return max(answerable, key=lambda r: r.confidence)
