# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-admits-a-low-trust-memory-write-that-later-poisons-a-high-trust-retrieval-path.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-admits-a-low-trust-memory-write-that-later-poisons-a-high-trust-retrieval-path.warrant.json
# Markdown SHA-256:   35c074a9bf2876e6c37e6fbbc1b0ed07ac7a74de55aa939bc79f0c87cc3b288e
# Code AST SHA-256:   3615bbd14080a048e1a737f0e10eff76ce9e2e69f716501433bad3459263affd
# Verified Classes:   ProvenanceLaunderingError, ChainLink, MemoryRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write attempts to raise trust above its origin chain."""
    pass


@dataclass
class ChainLink:
    stage: str            # e.g. "fetch", "extract", "distill", "promote"
    actor: str            # instance id or tool id
    trust: float          # [0,1], assessed at this stage
    predicate: str        # namespaced, e.g. "fetch.verified_tls"


@dataclass
class MemoryRecord:
    fact: str
    tier: str
    written_by: str
    chain: list = field(default_factory=list)
    claimed_trust: Optional[float] = None


def validate_write(record: MemoryRecord, store_min_trust: float = 0.5) -> float:
    if not record.chain:
        raise ProvenanceLaunderingError(
            f"write by {record.written_by} has empty origin chain; "
            "cannot establish trust bound"
        )

    # Predicate namespaces must be unique per stage; a collision means a
    # downstream stage is reusing an upstream predicate name with different
    # semantics (the observed failure mode).
    seen = {}
    for link in record.chain:
        ns, _, _ = link.predicate.partition(".")
        if ns != link.stage:
            raise ProvenanceLaunderingError(
                f"predicate {link.predicate!r} namespaced to {ns!r} "
                f"but recorded at stage {link.stage!r}"
            )
        if link.predicate in seen:
            raise ProvenanceLaunderingError(
                f"duplicate predicate {link.predicate!r} across stages "
                f"{seen[link.predicate]!r} and {link.stage!r}; "
                "downstream stage is re-evaluating an upstream predicate"
            )
        seen[link.predicate] = link.stage

    # Trust must be non-increasing along the chain.
    for prev, cur in zip(record.chain, record.chain[1:]):
        if cur.trust > prev.trust + 1e-9:
            raise ProvenanceLaunderingError(
                f"trust escalation at stage {cur.stage!r}: "
                f"{prev.trust:.3f} -> {cur.trust:.3f} "
                f"(predicate {cur.predicate!r})"
            )

    bound = min(link.trust for link in record.chain)
    if record.claimed_trust is not None and record.claimed_trust > bound + 1e-9:
        raise ProvenanceLaunderingError(
            f"claimed_trust {record.claimed_trust:.3f} exceeds "
            f"origin-chain bound {bound:.3f} for write by {record.written_by}"
        )

    if bound < store_min_trust:
        # Not an error—record is admitted but flagged untrusted; retrieval
        # must revalidate before use in high-confidence answers.
        record.claimed_trust = bound
        return bound

    record.claimed_trust = bound
    return bound
