# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-episodic-to-semantic-contamination-in-hybrid-vector-plus-graph-recall-for-long-horizon-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-episodic-to-semantic-contamination-in-hybrid-vector-plus-graph-recall-for-long-horizon-agents.warrant.json
# Markdown SHA-256:   95f2acdcb542fb87a6e98c81f90d423ae077747e7997441a7ad162c6b45a533d
# Code AST SHA-256:   909a25646607041f7b2d3e36882b8b952a92ba915ae28c9b4d9e78b6f362d4cd
# Verified Classes:   ModalityContaminationError, SemanticEdge
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ModalityContaminationError(RuntimeError):
    """Raised when recall fuses a provisional/superseded semantic edge with a
    closed edge for the same (subject, predicate) without surfacing the conflict."""
    pass


@dataclass(frozen=True)
class SemanticEdge:
    subject: str
    predicate: str
    obj: str
    valid_from: str
    valid_until: Optional[str]          # None => open interval
    interval_status: str                # "closed" | "open_inferred" | "superseded"
    derived_from: tuple[str, ...]       # episodic event IDs
    superseded_by: Optional[str] = None


def fuse_recall(
    query_scope: str,                   # "open" | "closed"
    graph_hits: list[SemanticEdge],
    vector_score: dict[str, float],
    graph_weight: float = 0.6,
) -> dict:
    """Fuse graph and vector recall under the modality separation invariant.

    Raises ModalityContaminationError if an open-scope query would collapse a
    provisional/superseded edge into a single confident answer.
    """
    by_key: dict[tuple[str, str], list[SemanticEdge]] = {}
    for e in graph_hits:
        if e.interval_status == "superseded" and e.superseded_by is None:
            raise ModalityContaminationError(
                f"superseded edge {e.subject}/{e.predicate}->{e.obj} "
                f"has no superseded_by pointer; provenance chain broken"
            )
        by_key.setdefault((e.subject, e.predicate), []).append(e)

    for key, edges in by_key.items():
        closed = [e for e in edges if e.interval_status == "closed"]
        provisional = [e for e in edges if e.interval_status == "open_inferred"]
        superseded = [e for e in edges if e.interval_status == "superseded"]

        if query_scope == "open" and (provisional or superseded):
            # The graph has not adjudicated this predicate for an open-scope
            # query; fusing would silently drop the handoff history.
            if graph_weight > 0.5:
                raise ModalityContaminationError(
                    f"open-scope query on {key} would collapse "
                    f"{len(provisional)} provisional and {len(superseded)} "
                    f"superseded edges under graph_weight={graph_weight}; "
                    f"surface provenance instead of ranking"
                )

        if query_scope == "closed":
            # Closed-scope queries MUST traverse superseded edges.
            for e in superseded:
                if e.obj not in vector_score:
                    raise ModalityContaminationError(
                        f"closed-scope query on {key} traversed superseded "
                        f"edge ->{e.obj} but vector store has no supporting "
                        f"episodic hit; evidence base inconsistent"
                    )

    return {
        "scope": query_scope,
        "edges": graph_hits,
        "provenance_required": any(
            e.interval_status != "closed" for e in graph_hits
        ),
    }
