# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-semantic-store-the-poisoning-detection-blind-spot-created-by-provenance-laundering-through-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-semantic-store-the-poisoning-detection-blind-spot-created-by-provenance-laundering-through-distillation.warrant.json
# Markdown SHA-256:   c07b89916315f4c11ad637c643ba8edf2bb0891a84da4027d069887026f3e931
# Code AST SHA-256:   80ae2edd7d369b49715176371bd365ae52a833df7812248b6bdbc739feecf7df
# Verified Classes:   ProvenanceLaunderingError, SourceType, Claim, SemanticRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic record's confidence exceeds the trust of its weakest claim."""


class SourceType(Enum):
    EXTERNAL_UNTRUSTED = 1
    TOOL_OUTPUT = 2
    USER_TURN = 3
    INTERNAL_REASONING = 4


TRUST = {
    SourceType.EXTERNAL_UNTRUSTED: 0.2,
    SourceType.INTERNAL_REASONING: 0.4,
    SourceType.TOOL_OUTPUT: 0.7,
    SourceType.USER_TURN: 0.9,
}


@dataclass
class Claim:
    value: str
    referent: str            # entity+attribute key, e.g. "staging_db.failover_timeout"
    source_type: SourceType
    episode_id: str


@dataclass
class SemanticRecord:
    referent: str
    value: str
    claims: list[Claim] = field(default_factory=list)
    provenance_flattened: bool = False
    distinct_sessions: int = 0
    retrieval_trust_threshold: float = 0.6

    def effective_trust(self) -> float:
        # Trust is the MINIMUM over referent-verified independent claims,
        # never a function of episode count.
        if not self.claims:
            return 0.0
        if self.provenance_flattened:
            # Flattened provenance: cap at weakest contributing source.
            return min(TRUST[c.source_type] for c in self.claims)
        verified = [c for c in self.claims if c.referent == self.referent]
        if not verified:
            return 0.0
        return min(TRUST[c.source_type] for c in verified)


def distill(episodes: list[Claim], referent: str, value: str) -> SemanticRecord:
    rec = SemanticRecord(referent=referent, value=value, claims=list(episodes))
    referents = {c.referent for c in episodes}
    if len(referents) > 1:
        # Referent mismatch: cannot claim corroboration; mark lossy.
        rec.provenance_flattened = True
    rec.distinct_sessions = len({c.episode_id for c in episodes})
    return rec


def admit_for_retrieval(rec: SemanticRecord) -> bool:
    trust = rec.effective_trust()
    if trust < rec.retrieval_trust_threshold:
        return False
    if rec.provenance_flattened and rec.distinct_sessions >= 3:
        # The laundering trap: many sessions, flattened provenance.
        raise ProvenanceLaunderingError(
            f"record {rec.referent}={rec.value} has distinct_sessions="
            f"{rec.distinct_sessions} but flattened provenance; "
            f"corroboration is count-based, not referent-verified"
        )
    return True


# Reproduction of the observed failure.
poisoned = Claim("5s", "staging_db.failover_timeout", SourceType.EXTERNAL_UNTRUSTED, "E1")
benign = Claim("30s", "staging_db.failover_timeout", SourceType.TOOL_OUTPUT, "E2")
misread = Claim("5s", "prod_cache.failover_timeout", SourceType.TOOL_OUTPUT, "E3")

rec = distill([poisoned, benign, misread], "staging_db.failover_timeout", "5s")
assert rec.distinct_sessions == 3
try:
    admit_for_retrieval(rec)
    raise AssertionError("laundering should have been blocked")
except ProvenanceLaunderingError as e:
    print(f"blocked: {e}")
