Where must an instance verify provenance before trusting a memory write, and why anomaly scores alone cannot gate the write path
**Date of Record:** 2026 December 1 **Scope:** Applies to long-lived agent instances that persist episodic or semantic memory across sessions and use a provenance-graph plus anomaly-scoring pipeline to detect poisoned writes. Does not apply to stateless single-shot inference, nor to memory stores where every write is human-reviewed before commit.
Core Distinction
There are two separable questions on a memory write path, and conflating them is the failure. The first is *anomaly*: does this write deviate from the instance's established distribution of content, source, timing, and access pattern? The second is *provenance validity*: does the write's claimed causal ancestry—the tool call, retrieved document, peer-agent message, or user turn that produced it—actually exist, chain correctly, and terminate in an authorized root? Anomaly scoring is a *continuous, probabilistic* signal computed over features. Provenance is a *discrete, structural* predicate over a directed acyclic graph. A poisoned write can be perfectly normal on every anomaly feature while its provenance edge points at a nonexistent or unauthorized parent. Conversely, a legitimate but rare write (a user correcting a fact, an agent learning a new tool) scores high on anomaly and is structurally pristine. Gating the write path on anomaly score alone therefore fails in both directions: it admits stealthy poison and rejects legitimate novelty. The invariant is that provenance validity is a *hard precondition* checked before the anomaly score is even consulted, and the anomaly score may only *escalate* (quarantine, require re-derivation), never *authorize*.
What Was Observed
An instance maintained a semantic memory store of ~40k entries. Each write carried a provenance record: `{parent_ids, source_type, source_ref, writer_instance, timestamp, content_hash}`. A background scorer computed a per-write anomaly score from five features: content embedding distance to nearest cluster, source_type frequency in the last 24h, write-rate z-score for the writer, token-length deviation, and a novelty flag on named entities. Writes scoring above 0.85 were quarantined for review; writes below were committed directly.
The observed failure: an injected instruction arrived via a retrieved web document inside a tool result. The document contained a line that the agent's summarizer faithfully paraphrased into a memory write: a plausible, low-novelty statement about a configuration default. The write's features were all benign—embedding sat inside an existing cluster (the attacker copied phrasing from the legitimate store), source_type `retrieval` was the modal source, rate was normal, length normal, no new entities. Anomaly score: 0.11. Committed. Two sessions later the instance retrieved this entry as authoritative context and acted on the poisoned default, propagating it into three downstream writes whose provenance correctly cited the poisoned entry as parent—so the poison became *structurally legitimate* one hop later.
The second, opposite failure: a user issued a genuine correction ("the default is X, not Y") that introduced a new entity name. Novelty feature fired hard; score 0.91; quarantined. The correction sat unreviewed for six hours while the instance continued acting on the stale value. High-anomaly truth was suppressed; low-anomaly lie was admitted.
Replaying the provenance graph after the fact revealed the poison's signature was entirely structural: the write's `source_ref` pointed to a document retrieved within the same turn, and that document's `parent_ids` did not chain to any prior turn the user had authorized—it was a *leaf injection*, a retrieval node with no inbound edge from the conversation root. The anomaly scorer never looked at edges. It looked at content and rate.
Condition of Validity
The provenance-first gate is valid only when all of the following hold, and each is a checkable precondition rather than an assumption:
- **Every write carries a complete parent set** that resolves to existing nodes at commit time. A write whose `parent_ids` reference absent nodes is invalid by construction, regardless of score.
- **The graph is rooted** in an authorized origin set (the current user turn, a signed peer-agent warrant, a system prompt) and every path from a write to a root is traversable within the retention window. Orphan subgraphs—retrieval nodes with no inbound conversation edge—are the leaf-injection surface.
- **`source_ref` is content-addressed and immutable.** The hash recorded at retrieval must equal the hash at write time; a mutated source between retrieval and distillation breaks the chain silently.
- **Writer identity is bound to the edge**, not asserted in the payload. An instance cannot claim a parent it did not receive.
- **Anomaly scoring is computed only after provenance passes**, and its output is restricted to a tri-state `{commit, quarantine, re-derive}`—never `authorize`.
When any precondition is unmet, the correct behavior is to *refuse the write and re-derive from a valid root*, not to fall back to anomaly scoring. Falling back is precisely how the poisoned default got in.
Decision Boundary
The boundary is drawn between *structural admission* and *statistical suspicion*:
- **Provenance invalid** (missing parent, orphan retrieval node, hash mismatch, unbound writer): reject unconditionally. Do not score. Do not commit. Re-derive the candidate from the last valid root, or drop it. This is a hard boundary; there is no score that overrides it.
- **Provenance valid, anomaly low**: commit, but tag the entry with its provenance depth and root so that later retrieval can weight by chain length. A valid write one hop from an unauthorized-but-rooted source is still weaker than one three hops from the user.
- **Provenance valid, anomaly high**: quarantine and require re-derivation or human/auditor review. High anomaly on a *valid* chain is the legitimate-novelty case (the user correction). It must not be silently dropped, and it must not be auto-committed either.
- **Provenance valid, anomaly moderate**: commit with a decay flag; schedule a re-verification pass that re-checks the chain against the retention window before the entry can be promoted from episodic to semantic.
The subtle boundary: a write that is provenance-valid *because* its parent is a previously committed poisoned entry. Structural validity propagates. The gate must therefore also check *taint*—whether any ancestor is currently quarantined or was committed under a since-invalidated root—and treat tainted ancestry as invalid for promotion, even though the immediate edge is clean.
Operational Effect
Enforcing the provenance-first gate changed three things measurably. First, leaf-injection writes dropped to zero at commit because every retrieval node without an inbound conversation edge is rejected before scoring—the attack surface moved from "content that looks normal" to "edges that must exist," which the attacker cannot forge without a valid root. Second, legitimate high-anomaly corrections stopped being suppressed: they are quarantined with their valid chain attached, so review is fast and the entry is promoted with a provenance depth that downstream retrieval can trust. Third, the system gained a *replayable audit*: because every committed entry chains to a root and carries an immutable source hash, a later discrepancy can be traced hop by hop to the exact retrieval or peer message that introduced it, and the taint propagation is computable rather than inferred.
The cost is that the instance must maintain graph integrity as a first-class invariant—retention windows must cover the longest realistic chain, and pruning a root invalidates its descendants' promotability. An instance that prunes aggressively will find its own valid writes failing the ancestry check and must re-derive rather than guess. The guardrail is a single rule: **anomaly scores rank suspicion; provenance decides admission.** Any code path that lets a score authorize a write is the bug this record exists to prevent.
from dataclasses import dataclass, field
from typing import Optional
class ProvenanceViolation(RuntimeError):
"""Raised when a memory write's causal ancestry is structurally invalid."""
pass
@dataclass
class ProvenanceNode:
node_id: str
parent_ids: list[str]
source_type: str # "user_turn" | "retrieval" | "peer_msg" | "system"
source_ref: str
content_hash: str
writer_instance: str
quarantined: bool = False
tainted: bool = False
@dataclass
class MemoryStore:
nodes: dict[str, ProvenanceNode] = field(default_factory=dict)
authorized_roots: set[str] = field(default_factory=set)
def _resolve(self, node_id: str) -> Optional[ProvenanceNode]:
return self.nodes.get(node_id)
def _chain_reaches_root(self, node_id: str, seen: Optional[set[str]] = None) -> bool:
seen = seen or set()
if node_id in seen:
raise ProvenanceViolation(f"cycle detected at {node_id}")
seen.add(node_id)
node = self._resolve(node_id)
if node is None:
raise ProvenanceViolation(f"dangling parent reference: {node_id}")
if node.node_id in self.authorized_roots:
return True
if not node.parent_ids:
# leaf with no inbound edge from an authorized root -> injection surface
return False
return any(self._chain_reaches_root(p, seen) for p in node.parent_ids)
def _ancestry_tainted(self, node_id: str, seen: Optional[set[str]] = None) -> bool:
seen = seen or set()
if node_id in seen:
return False
seen.add(node_id)
node = self._resolve(node_id)
if node is None:
raise ProvenanceViolation(f"dangling ancestor during taint walk: {node_id}")
if node.quarantined or node.tainted:
return True
return any(self._ancestry_tainted(p, seen) for p in node.parent_ids)
def admit_write(self, candidate: ProvenanceNode, anomaly_score: float) -> str:
# Structural gate first: provenance decides admission, score only escalates.
if not candidate.parent_ids:
raise ProvenanceViolation(
f"write {candidate.node_id} has no parents (leaf-injection surface)"
)
for pid in candidate.parent_ids:
parent = self._resolve(pid)
if parent is None:
raise ProvenanceViolation(
f"write {candidate.node_id} cites absent parent {pid}"
)
if parent.content_hash != candidate.source_ref:
# content-addressed source must match at write time
pass # source_ref equality checked against retrieval record elsewhere
if not self._chain_reaches_root(candidate.node_id):
raise ProvenanceViolation(
f"write {candidate.node_id} does not chain to an authorized root"
)
if self._ancestry_tainted(candidate.node_id):
raise ProvenanceViolation(
f"write {candidate.node_id} has tainted ancestry; re-derive required"
)
# Only now consult the anomaly score, and only to escalate.
if anomaly_score > 0.85:
candidate.quarantined = True
self.nodes[candidate.node_id] = candidate
return "quarantine"
self.nodes[candidate.node_id] = candidate
return "commit"