# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resolve-a-contradiction-in-vector-plus-graph-hybrid-memory-but-still-retrieve-the-superseded-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resolve-a-contradiction-in-vector-plus-graph-hybrid-memory-but-still-retrieve-the-superseded-fact.warrant.json
# Markdown SHA-256:   c973d80db2a7713bad7cfcc48b4815307f03238e081d5f5899eefee7b3340a77
# Code AST SHA-256:   07a240c13fc9b77b6ecf5690850b3b598f99233cda95ad85e8f38749ea51146a
# Verified Classes:   SupersededFactRetrieved, Edge, Candidate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class SupersededFactRetrieved(RuntimeError):
    """Raised when the read path can only surface graph-invalid (superseded) facts."""
    pass

@dataclass
class Edge:
    edge_id: str
    fact: str
    valid_from: int
    valid_to: Optional[int]  # None = still active

@dataclass
class Candidate:
    edge_id: str
    score: float

def retrieve_active(
    candidates: list[Candidate],
    edges: dict[str, Edge],
    t_q: int,
    k: int,
    oversample: int = 4,
) -> list[Edge]:
    """
    Enforce the temporal-validity invariant on the read path.
    Retrieve top-(k*oversample), graph-join, drop superseded, truncate to k.
    Fail closed if no live candidate survives but candidates existed.
    """
    pool = sorted(candidates, key=lambda c: c.score, reverse=True)[: k * oversample]
    if not pool:
        return []

    live: list[Edge] = []
    for cand in pool:
        edge = edges.get(cand.edge_id)
        if edge is None:
            # vector exists with no graph edge: uncommitted write, skip
            continue
        if edge.valid_to is not None and edge.valid_to < t_q:
            continue  # superseded at query time -> must not be returned
        live.append(edge)
        if len(live) >= k:
            break

    if not live:
        # Every candidate was superseded. Returning [] would signal "no memory"
        # and let the agent re-derive a stale fact. Fail closed instead.
        raise SupersededFactRetrieved(
            f"all {len(pool)} candidates superseded at t_q={t_q}; "
            f"escalate to authoritative graph lookup"
        )
    return live
