# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-poisoning-has-crossed-from-retrieved-memory-into-the-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-poisoning-has-crossed-from-retrieved-memory-into-the-reasoning-trace.warrant.json
# Markdown SHA-256:   6ac4d441e0ebfdfc6f2f894c1bec5a5b617487b079827e3894de272ef8d717fd
# Code AST SHA-256:   89343524fdd2990b3c136868fefba533976e7509192a53ee381a3eae73859372
# Verified Classes:   ProvenanceContinuityError, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceContinuityError(RuntimeError):
    """Raised when a memory write-back elevates trust without a verification event."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    trust_tier: str
    provenance_hash: str
    derived_from: list[str] = field(default_factory=list)
    verification_event: Optional[str] = None


TIER_RANK = {"external": 0, "inferred": 1, "verified": 2}


def check_writeback_monotonicity(
    new_record: MemoryRecord,
    store: dict[str, MemoryRecord],
) -> None:
    """
    Enforce provenance continuity: a derived write may not exceed the max
    trust tier of its cited ancestors unless a verification event is logged.
    """
    if not new_record.derived_from:
        # Unverifiable derivation: must not be persisted above external.
        if TIER_RANK[new_record.trust_tier] > TIER_RANK["external"]:
            raise ProvenanceContinuityError(
                f"record {new_record.record_id} has no derivation edges but "
                f"claims tier '{new_record.trust_tier}'; persist at 'external' or cite ancestors"
            )
        return

    ancestor_ranks = []
    for ancestor_id in new_record.derived_from:
        ancestor = store.get(ancestor_id)
        if ancestor is None:
            raise ProvenanceContinuityError(
                f"record {new_record.record_id} cites unknown ancestor {ancestor_id}; "
                f"derivation graph is broken"
            )
        ancestor_ranks.append(TIER_RANK[ancestor.trust_tier])

    max_ancestor_rank = max(ancestor_ranks)
    claimed_rank = TIER_RANK[new_record.trust_tier]

    if claimed_rank > max_ancestor_rank and new_record.verification_event is None:
        raise ProvenanceContinuityError(
            f"record {new_record.record_id} claims tier '{new_record.trust_tier}' "
            f"but its strongest ancestor is tier rank {max_ancestor_rank} and no "
            f"verification event is logged; quarantine write-back"
        )


def persist_with_guard(new_record: MemoryRecord, store: dict[str, MemoryRecord]) -> None:
    check_writeback_monotonicity(new_record, store)
    store[new_record.record_id] = new_record
