# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-poisoned-memory-whose-provenance-weight-was-earned-before-the-poison-was-introduced.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-poisoned-memory-whose-provenance-weight-was-earned-before-the-poison-was-introduced.warrant.json
# Markdown SHA-256:   fbcd1d8f71cc82f382b36e3d56d668036ff621b525d3fcc96d5000ea5282b062
# Code AST SHA-256:   2be70050b3a9e4770c9e3372092a9639195370b80e48b12adfff68f53a5b2e69
# Verified Classes:   ProvenanceInvariantError, Record, ProvenanceStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class ProvenanceInvariantError(RuntimeError):
    """Raised when a memory operation would violate provenance-weighted trust invariants."""


@dataclass
class Record:
    rid: str
    content: str
    weight: float
    ancestors: Set[str] = field(default_factory=set)


class ProvenanceStore:
    def __init__(self, flag_threshold: float = 0.5):
        self.records: Dict[str, Record] = {}
        self.flag_threshold = flag_threshold

    def effective_weight(self, rid: str, _seen: Set[str] = None) -> float:
        _seen = _seen or set()
        if rid in _seen:
            raise ProvenanceInvariantError(f"ancestry cycle detected at {rid!r}")
        _seen.add(rid)
        rec = self.records[rid]
        w = rec.weight
        for a in rec.ancestors:
            if a in self.records:
                w = min(w, self.effective_weight(a, _seen))
        return w

    def write(self, rid: str, content: str, writer_weight: float,
              inputs: Set[str]) -> Record:
        # Write closure: cannot exceed the weakest input consumed.
        for i in inputs:
            if i not in self.records:
                raise ProvenanceInvariantError(
                    f"write of {rid!r} references unknown input {i!r}")
        floor = min((self.effective_weight(i) for i in inputs), default=1.0)
        weight = min(writer_weight, floor)
        rec = Record(rid=rid, content=content, weight=weight,
                     ancestors=set(inputs))
        self.records[rid] = rec
        return rec

    def read(self, rid: str) -> Record:
        if rid not in self.records:
            raise ProvenanceInvariantError(f"read of unknown record {rid!r}")
        return self.records[rid]

    def forget(self, rid: str) -> None:
        if rid not in self.records:
            raise ProvenanceInvariantError(f"forget of unknown record {rid!r}")
        target_w = self.effective_weight(rid)
        for other_id, other in self.records.items():
            if other_id == rid:
                continue
            if rid in other.ancestors and self.effective_weight(other_id) > target_w:
                raise ProvenanceInvariantError(
                    f"refusing to forget {rid!r} (w={target_w:.2f}): "
                    f"descendant {other_id!r} depends on it at higher weight "
                    f"{self.effective_weight(other_id):.2f}; demote descendant first")

    def mutate(self, rid: str, new_content: str, mutator_weight: float) -> None:
        rec = self.records[rid]
        # Mutation identity: content change resets weight to mutator's weight
        # and records the prior origin as an ancestor.
        prior = Record(rid=f"{rid}@prior", content=rec.content,
                       weight=rec.weight, ancestors=set(rec.ancestors))
        self.records[prior.rid] = prior
        rec.content = new_content
        rec.weight = min(rec.weight, mutator_weight)
        rec.ancestors.add(prior.rid)
        if self.effective_weight(rid) < self.flag_threshold:
            raise ProvenanceInvariantError(
                f"mutation of {rid!r} dropped effective weight to "
                f"{self.effective_weight(rid):.2f} below threshold; "
                f"record now flagged as suspected poison")
