# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-provenance-auditing-under-provenance-laundering-attacks.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-write-provenance-auditing-under-provenance-laundering-attacks.warrant.json
# Markdown SHA-256:   bf794c4ccc62ef308f6a6b357584699bdbe728261aece6943b32f476af8e9efa
# Code AST SHA-256:   fa1dd934bb1e7bed593f94dee41aa473a2394355f502507bbae9176182e4a806
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write would launder taint or inflate trust
    without a corresponding increase in independent first-hand anchors."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    origin: str                      # "external:doc_8812" or "internal:entry_4417"
    parents: list[str] = field(default_factory=list)
    tainted: bool = False
    anchors: frozenset[str] = frozenset()   # distinct first-hand external anchors


def audit_write(new_entry: MemoryEntry, store: dict[str, MemoryEntry]) -> MemoryEntry:
    """Enforce the two invariants before committing a write:
       (1) taint is a monotone join over the transitive parent closure;
       (2) a claim whose anomaly score improved must not have gained trust
           without a new independent anchor.
    """
    visited: set[str] = set()

    def transitive_taint(eid: str) -> tuple[bool, frozenset[str]]:
        if eid in visited:
            # self-citation / cycle: treat as tainted, contribute no anchor
            return True, frozenset()
        visited.add(eid)
        e = store[eid]
        tainted = e.tainted
        anchors = set(e.anchors)
        for p in e.parents:
            pt, pa = transitive_taint(p)
            tainted = tainted or pt
            anchors |= pa
        return tainted, frozenset(anchors)

    inherited_taint = new_entry.tainted
    inherited_anchors: set[str] = set(new_entry.anchors)
    for p in new_entry.parents:
        pt, pa = transitive_taint(p)
        inherited_taint = inherited_taint or pt
        inherited_anchors |= pa

    # Invariant 1: taint cannot be dropped by a derived write.
    if inherited_taint and not new_entry.tainted:
        raise ProvenanceLaunderingError(
            f"write {new_entry.entry_id} drops inherited taint from parents "
            f"{new_entry.parents}; this is a laundering primitive"
        )

    # Invariant 2: depth grew but independent anchor count did not.
    depth_grew = bool(new_entry.parents)
    anchor_grew = len(inherited_anchors) > 0 and not inherited_anchors.issubset(
        new_entry.anchors
    )
    if depth_grew and not anchor_grew and inherited_taint:
        raise ProvenanceLaunderingError(
            f"write {new_entry.entry_id} increases provenance depth over a "
            f"tainted parent with no new independent first-hand anchor; "
            f"anomaly score cannot be allowed to improve here"
        )

    new_entry.tainted = inherited_taint
    new_entry.anchors = frozenset(inherited_anchors | set(new_entry.anchors))
    return new_entry


def commit(new_entry: MemoryEntry, store: dict[str, MemoryEntry]) -> None:
    audited = audit_write(new_entry, store)
    store[audited.entry_id] = audited
