# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundered-memory-poisoning-when-a-trusted-writer-s-signed-entry-is-later-re-embedded-through-an-untrusted-sum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundered-memory-poisoning-when-a-trusted-writer-s-signed-entry-is-later-re-embedded-through-an-untrusted-sum.warrant.json
# Markdown SHA-256:   8e04b1e83f15c3748ba3657deef98a8c7135ba3c4df5458cc0f0162bd6ff3d14
# Code AST SHA-256:   9fb00ede51c0f372c323a384772c129551ea5172e3aa5bae2366c4ea3fd4f149
# Verified Classes:   ProvenanceLaunderingError, Entry, ProvenanceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write's derivation chain cannot be verified
    against content hashes sealed by the store, or when a retrieval would
    silently collapse contradictory claims of differing provenance."""
    pass


@dataclass(frozen=True)
class Entry:
    content_hash: str
    signer_tier: int          # 0=operator .. 3=summarizer
    parent_hashes: tuple
    triples: frozenset        # {(subject, predicate, object)}
    relevance: float


class ProvenanceStore:
    TIER_WEIGHT = {0: 1.0, 1: 0.8, 2: 0.5, 3: 0.2}
    RELEVANCE_FLOOR = 0.5

    def __init__(self):
        self._entries: dict = {}

    def _seal(self, content: str) -> str:
        return hashlib.sha256(content.encode()).hexdigest()

    def write(self, content: str, signer_tier: int,
              parents: tuple, triples: frozenset) -> Entry:
        for p in parents:
            if p not in self._entries:
                raise ProvenanceLaunderingError(
                    f"write cites unverifiable parent {p[:12]}…; "
                    f"store cannot seal derivation chain")
        e = Entry(self._seal(content), signer_tier, parents, triples, 1.0)
        self._entries[e.content_hash] = e
        return e

    def effective_trust(self, e: Entry) -> int:
        # min over the *sealed* derivation chain, transitively
        tiers = [e.signer_tier]
        frontier = list(e.parent_hashes)
        seen = set()
        while frontier:
            h = frontier.pop()
            if h in seen:
                continue
            seen.add(h)
            parent = self._entries.get(h)
            if parent is None:
                raise ProvenanceLaunderingError(
                    f"derivation chain references missing entry {h[:12]}…")
            tiers.append(parent.signer_tier)
            frontier.extend(parent.parent_hashes)
        return min(tiers)

    def score(self, e: Entry) -> float:
        w = self.TIER_WEIGHT[self.effective_trust(e)]
        return w * max(e.relevance, self.RELEVANCE_FLOOR)

    def retrieve(self, query_triples: frozenset) -> list:
        hits = [e for e in self._entries.values()
                if e.triples & query_triples]
        # detect contradictory assertions across provenance tiers
        by_triple: dict = {}
        for e in hits:
            for t in e.triples & query_triples:
                by_triple.setdefault(t, []).append(e)
        for t, group in by_triple.items():
            tiers = {self.effective_trust(e) for e in group}
            if len(tiers) > 1 and (max(tiers) - min(tiers)) >= 2:
                # do NOT collapse by score; surface the conflict
                raise ProvenanceLaunderingError(
                    f"contradictory provenance for triple {t}: "
                    f"tiers {sorted(tiers)}; refusing silent top-1")
        return sorted(hits, key=self.score, reverse=True)
