# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-gate-retrieval-on-taint-lineage-when-a-poisoned-vector-store-entry-was-distilled-from-a-prior-agent-s-tool-output.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-gate-retrieval-on-taint-lineage-when-a-poisoned-vector-store-entry-was-distilled-from-a-prior-agent-s-tool-output.warrant.json
# Markdown SHA-256:   6dfde73cde6faedb613b24367f5a1cbaa4d551f911a332e2ec3852b8526ae8fd
# Code AST SHA-256:   c953eb29ec67640a3feb1a721f4204f86a97fafaaf25ea5135c2dedec52be63b
# Verified Classes:   ProvenanceGateError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceGateError(RuntimeError):
    """Raised when retrieval gating cannot soundly evaluate a chunk's taint closure."""


UNTRUSTED_SOURCES = frozenset({"fetch_url", "user_upload", "peer_handoff_unverified"})
MAX_CLOSURE_DEPTH = 3


def evaluate_taint_closure(chunk_id, store, registry, _depth=0, _seen=None):
    if _seen is None:
        _seen = set()
    if chunk_id in _seen:
        # Cycle in provenance graph: cannot establish a finite clean closure.
        raise ProvenanceGateError(f"provenance cycle at {chunk_id}")
    _seen.add(chunk_id)

    if _depth > MAX_CLOSURE_DEPTH:
        return {"admit": True, "banner": "deep-provenance", "depth": _depth}

    record = store.get(chunk_id)
    if record is None:
        # Dangling edge: lineage truncated. Treat as tainted, not clean.
        raise ProvenanceGateError(
            f"dangling provenance edge: {chunk_id} referenced but absent from store"
        )

    producer = record.get("producer")
    if producer in UNTRUSTED_SOURCES:
        return {"admit": False, "reason": f"untrusted source {producer}", "depth": _depth}

    if not registry.verify_edge(record):
        # Unattested edge: the producer signature does not check out.
        raise ProvenanceGateError(
            f"edge signature verification failed for {chunk_id} (producer={producer})"
        )

    parents = record.get("distilled_from", [])
    if not parents:
        return {"admit": True, "banner": None, "depth": _depth}

    worst = {"admit": True, "banner": None, "depth": _depth}
    for parent in parents:
        result = evaluate_taint_closure(parent, store, registry, _depth + 1, _seen)
        if not result["admit"]:
            return result
        if result.get("banner") == "deep-provenance":
            worst = result
    return worst


def gated_retrieve(query_vec, store, registry, top_k=8):
    candidates = store.similarity_search(query_vec, top_k=top_k)
    admitted = []
    for cand in candidates:
        try:
            verdict = evaluate_taint_closure(cand["id"], store, registry)
        except ProvenanceGateError as e:
            # Fail closed: orphaned or unattested chunks never enter context.
            store.quarantine(cand["id"], reason=str(e))
            continue
        if not verdict["admit"]:
            store.quarantine(cand["id"], reason=verdict["reason"])
            continue
        if verdict.get("banner"):
            cand["text"] = f"[provenance: {verdict['banner']}, depth={verdict['depth']}]\n" + cand["text"]
        admitted.append(cand)
    if not admitted:
        raise ProvenanceGateError(
            "all candidates rejected by taint closure; reasoning loop must not proceed on empty context"
        )
    return admitted
