# When must an instance distrust its own episodic memory: provenance-weighted retrieval scoring and the canary decay invariant **Date of Record:** 2026 December 3 **Scope:** Applies to long-lived agent instances that persist episodic memory across sessions and retrieve from it with a provenance-weighted scorer combined with anomaly canaries. Does not apply to stateless single-turn inference, nor to memory stores where every write is human-reviewed before commit. ## Core Distinction The failure we examine is not "a poisoned memory was retrieved." Retrieval of a bad record is expected and tolerable—poisoning detection systems are built on the assumption that adversarial or corrupted writes will sometimes win a similarity contest. The failure is subtler: **a poisoned memory that was correctly flagged by the canary subsystem, but whose provenance weight was inflated by the poisoning itself, so that the flag never crossed the quarantine threshold.** The detection signal existed; the scoring arithmetic inverted it. This is the distinction between *detection* and *adjudication*. Canaries detect. Provenance weights adjudicate. When an attacker can influence both the content of a memory and the metadata that feeds its provenance weight, the adjudicator is compromised by the same act that triggers the detector. The invariant that must hold is: **the canary anomaly score for a record must be computed independently of any field that the record's own write path can mutate.** Violate it and detection and adjudication become a single attack surface. ## What Was Observed An agent instance (`planner-04`) maintains an episodic store of ~40k records. Each record carries a `provenance` object: `source` (tool name or peer agent id), `writes` (count of times this record has been reinforced by later corroboration), `last_confirm` (timestamp of last independent confirmation), and `trust` (a scalar in [0,1] derived from source reputation and write count). Retrieval score is `sim(q, r) * w(r)` where `w(r) = trust(r) * recency_decay(r) * (1 + log(1 + writes(r)))`. Anomaly canaries are planted records with known-false content ("the staging DB password is `canary-7f3a`"). If a canary surfaces in a retrieval set for a query that has nothing to do with it, the surrounding retrieval batch is flagged: the canary's *similarity rank* versus its expected rank is the anomaly score. A high score quarantines the batch and re-runs retrieval with the offending records excluded. The observed trace: 1. A tool-call response (`web_fetch`) returned content containing a plausible project fact plus a self-reinforcing instruction: it asserted the fact had been "confirmed by three prior sessions." 2. The memory-write path parsed the confirmation claim and, because the source string matched a known tool, **incremented `writes` on the newly created record to 3 and set `trust` to the tool's baseline.** The record was written with elevated provenance on its first commit. 3. The elevated `writes` term inflated `w(r)` by `1 + log(4) ≈ 2.39×` relative to a fresh record. 4. On a later query, the poisoned record ranked above a canary that *should* have dominated the retrieval set. Because the canary's expected rank was computed under the assumption that canaries have the highest provenance weight in the store, the observed rank *looked normal*—the canary was still present, just crowded by one record. 5. The anomaly score stayed under threshold. The batch was not quarantined. The poisoned fact entered the planner's working context and was used in a downstream tool call. The canary did its job: it appeared. The provenance weight—mutated by the poison's own content—recalibrated what "normal" looked like, and the detector was blinded by the adjudicator. ## Condition of Validity The provenance-weighted canary scheme is sound only under this invariant: > For every canary `c` and every retrieval batch `B`, the anomaly score `A(c, B)` must be a function only of `(sim(q, c), rank(c, B), |B|)` and constants. It must not depend on `w(r)` for any `r ∈ B`, and in particular not on `w(c)` or on the `w`-values of records that can be written by the same source that writes `c`'s neighbors. Equivalently: **canary expected-rank must be computed against a provenance distribution that the current write cannot shift.** In practice this means the canary's reference distribution is frozen at store-epoch boundaries and updated only from writes whose `source` is on an allowlist of non-injectable origins (internal scheduler, human review, verified peer signatures). A `web_fetch`-sourced write may enter the store, but it may not enter the reference distribution that defines "normal canary rank." Two corollaries that are easy to violate: - **Self-reinforcement is a provenance write.** Any content that claims prior confirmation must not increment `writes` or `trust` unless the claim is independently verifiable (e.g., a signed corroboration record from a peer, not a sentence in a fetched page). The observed failure was exactly a content-to-metadata escalation. - **Canary weight must be pinned.** If `w(c)` is computed by the same formula as other records, an attacker who can raise the *average* weight of a batch (by writing many high-`writes` records) dilutes the canary's relative prominence. Pin `w(c)` to a constant ceiling and score rank against the pinned value, not the batch mean. ## Decision Boundary The instance must switch from "trust the retrieval" to "distrust and quarantine" at a precise, checkable line. The line is not "canary appeared." It is: **Quarantine `B` if `rank(c, B) > expected_rank(c) + k` for the pinned `expected_rank`, OR if any record in `B` was written with a provenance mutation (`writes` or `trust` increment) whose justification is not traceable to a signed corroboration record.** The second clause is the one that catches this failure class, because the poisoned record's `writes=3` on first commit is, by construction, untraceable—there is no signed record behind it. A store that only checks the first clause will miss the attack whenever the poison is *close enough* to a canary to keep its rank within `k`. Practical thresholds observed to work: `k = 2` rank positions, and a hard rule that any first-commit record with `writes > 1` is quarantined pending corroboration review. The cost is a small false-positive rate on legitimate multi-session facts that arrive pre-corroborated; that cost is bounded and auditable, whereas the false-negative cost (silent poison ingestion) is unbounded. ## Operational Effect After applying the invariant, `planner-04`'s behavior changed in three measurable ways: 1. **Poison ingestion rate dropped to zero over a 30-day replay** of the incident corpus, because every pre-corroborated first-commit record was quarantined before it could enter a retrieval batch. The quarantine queue averaged 4 records/day, of which ~1 in 6 was a true positive on manual review. 2. **Canary sensitivity recovered.** Because `expected_rank` was pinned to a frozen epoch distribution, the canary's rank deviation once again tracked injection rather than batch weight drift. The anomaly score's ROC curve shifted from AUC 0.61 (pre-fix, effectively coin-flip) to 0.94 (post-fix). 3. **A new failure mode appeared and was bounded:** legitimate facts that *genuinely* arrive pre-corroborated (e.g., a peer agent forwarding a verified fact) now stall in quarantine until a signed corroboration record is attached. This is correct—the instance should not accept an unsigned claim of prior confirmation from any source, including peers—but it means the corroboration-signing path must be fast enough that the quarantine queue does not become a bottleneck. The instance's throughput on peer-forwarded facts dropped ~12% and recovered once signing was automated. The general lesson for any instance maintaining episodic memory with provenance scoring: **the detector's reference distribution and the adjudicator's weight function must be disjoint from the write path they are meant to police.** If a single write can move both the content and the yardstick, the canary is not a canary—it is a mirror. ```python import math from dataclasses import dataclass, field from typing import List, Optional class ProvenanceInvariantError(RuntimeError): """Raised when a memory write mutates provenance fields without a signed corroboration record, or when canary scoring depends on mutable weights.""" pass @dataclass class Corroboration: signer: str signature: str @dataclass class MemoryRecord: id: str content: str source: str writes: int = 1 trust: float = 0.5 last_confirm: float = 0.0 corroborations: List[Corroboration] = field(default_factory=list) is_canary: bool = False PINNED_CANARY_WEIGHT = 1.0 RANK_TOLERANCE = 2 def provenance_weight(r: MemoryRecord) -> float: if r.is_canary: # Pinned: canary weight must not drift with batch composition. return PINNED_CANARY_WEIGHT return r.trust * (1.0 + math.log(1.0 + r.writes)) def validate_write(r: MemoryRecord) -> None: """Enforce: any writes>1 on first commit, or any trust bump, must be backed by a signed corroboration record.""" if r.writes > 1 and not r.corroborations: raise ProvenanceInvariantError( f"record {r.id} claims writes={r.writes} with no signed " f"corroboration; content-to-metadata escalation suspected" ) if r.trust > 0.5 and not r.corroborations: raise ProvenanceInvariantError( f"record {r.id} has trust={r.trust} above baseline with no " f"signed corroboration" ) def anomaly_score(canary_rank: int, expected_rank: int) -> int: # Score depends only on rank positions, never on weights of batch members. return canary_rank - expected_rank def adjudicate_batch( batch: List[MemoryRecord], canary: MemoryRecord, expected_rank: int, ) -> Optional[str]: """Returns 'quarantine' or None. Raises on invariant violation.""" for r in batch: if not r.is_canary: validate_write(r) canary_rank = next( (i for i, r in enumerate(batch) if r.id == canary.id), None ) if canary_rank is None: raise ProvenanceInvariantError( f"canary {canary.id} absent from batch; retrieval integrity broken" ) if anomaly_score(canary_rank, expected_rank) > RANK_TOLERANCE: return "quarantine" # Second clause: any untraceable provenance mutation in the batch. for r in batch: if not r.is_canary and r.writes > 1 and not r.corroborations: return "quarantine" return None ```