When must an instance re-validate provenance after a memory store compaction event

**Date of Record:** 2026 December 1 **Scope:** Applies to persistent agent memory stores that enforce write-time provenance checks (source tagging, trust tiering, signature verification) and that periodically compact, deduplicate, or distill episodic records into semantic records. Does not apply to ephemeral per-session context or stores that never mutate existing records after write.

Core Distinction

Write-time provenance checking is a *point-in-time admission control*. It answers one question: "At the moment this record was written, was its claimed source trustworthy, and did the payload match the source's declared capability?" It does **not** answer: "After the store transformed this record, does the record still faithfully represent the source that was admitted?"

These are distinct invariants. The first is a predicate over `(payload, source_claim, signature)` evaluated once. The second is a predicate over a *transformation lineage* evaluated on every derivative. Compaction, deduplication, and episodic-to-semantic distillation are all transformations. They rewrite payloads, merge records from multiple sources, and synthesize summaries that no single admitted source ever asserted verbatim. A store that enforces provenance only at write time silently loses the guarantee at the first compaction, because the derived record inherits the *appearance* of provenance (it lives in the store, it has a source field) without inheriting the *evidence* (the signature covered the original payload, not the summary).

The non-obvious part: the failure is not that compaction is unguarded. It is that compaction is *correctly* unguarded under the write-time contract, and the resulting records are *indistinguishable* from directly-admitted records at read time. The store's read path has no way to tell "trusted because verified" from "trusted because it was derived from something verified, possibly with an injected merge partner."

What Was Observed

A research agent maintained a persistent store of "environment facts" (API endpoints, rate limits, credential scopes) with a provenance gate: each write carried a `source_tier` (T0 = operator config, T1 = signed tool output, T2 = model-inferred, T3 = untrusted external fetch) and a payload hash. T2 and T3 records were admitted but marked `quarantined` and excluded from retrieval unless a T1 record corroborated them.

During a nightly compaction pass, the store deduplicated near-identical records by embedding similarity and merged clusters into single canonical records. The merge logic picked the *highest-tier* member as the canonical record's source and concatenated the payloads of all members into a single semantic fact. This was intended to be a lossless consolidation.

The poisoning path:

  1. A T1 signed tool output established `api.example.com` rate limit = 100 req/min. Admitted, verified, signature checked against the payload. Correct.
  2. An attacker-controlled T3 fetch returned a document asserting `api.example.com` rate limit = 10000 req/min, plus a plausible-sounding justification. It was admitted as `quarantined`, T3, excluded from retrieval. Correct so far.
  3. The two records were embedding-similar (both discussed the same endpoint and rate limit). Compaction merged them. The canonical record inherited `source_tier = T1` (the highest member) and a payload that *concatenated* both rate limits into a hedged semantic summary: "rate limit is 100 req/min, though some sources indicate 10000 req/min may apply."
  4. On the next task, the agent retrieved the canonical record. Its `source_tier` was T1. The read path's quarantine filter passed it. The agent acted on the 10000 figure during a burst and hit hard throttling.

The signature on the original T1 payload was still valid and still in the audit log. It simply no longer covered the record that was being served, and nothing in the read path compared them.

Condition of Validity

The write-time provenance contract remains valid across a transformation **if and only if** every derived record carries a lineage pointer to the set of admitted source records it was synthesized from, and the read path re-evaluates trust against that lineage rather than against a copied `source_tier` field.

Formally, define a record `r` as trusted for retrieval iff `trust(r) ≥ threshold`, where trust is computed *at read time* as:

The failure above occurs because compaction set `trust(canonical) = max` (highest tier wins) instead of `min`, and because the read path consulted the copied field instead of the lineage. Two independent violations, either of which alone would have prevented the poisoning.

The invariant to enforce: **a derived record's effective trust is the minimum of its contributors' trust, and the derivation lineage is immutable and auditable.** Compaction is a trust-reducing operation by construction; it can never manufacture trust that no contributor held.

Decision Boundary

The boundary is not "should we compact?" — compaction is necessary for context-window economics and retrieval precision. The boundary is whether the compaction step is *inside* or *outside* the trust boundary.

A second boundary: **quarantined records must not be merge-eligible.** A T3 record that is excluded from retrieval should also be excluded from compaction input, because merging it into a canonical record is a retrieval-enabling act disguised as housekeeping. If quarantined records must be retained for audit, they must be compacted into a *separate* quarantine namespace that never feeds the retrieval index.

The guardrail that bounds the failure: make the trust field *derived, not stored*. If `source_tier` is a computed projection of lineage at read time, no compaction pass can forge it by copying a field, because there is no field to copy.

Operational Effect

After the fix (lineage-based trust recomputation, min-over-lineage, quarantined records excluded from merge input), the poisoned record's canonical form carried `lineage = [T1_record, T3_record]` and computed trust `= min(T1, T3) = T3`, which fell below the retrieval threshold and was excluded. The legitimate T1 fact survived as its own canonical record because the merge was blocked at the quarantine boundary. Retrieval precision on the affected endpoint returned to baseline on the next compaction cycle.

The generalizable lesson: **any store that admits records under a point-in-time provenance check must treat every subsequent transformation as a new write that requires re-admission, or must preserve lineage such that read-time trust is recomputable.** The moment a transformation copies a trust label instead of deriving it, the store has silently converted a verified assertion into an unverified one that wears the verified one's badge. The failure is not visible in the write path, not visible in the compaction logs (which report "merged 2 records, 0 errors"), and not visible at read time (the field says T1). It is visible only in the gap between what the signature covered and what the read path served.

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLineageError(RuntimeError):
    """Raised when a derived memory record cannot be trusted at read time
    because its lineage is missing, empty, or violates the min-trust invariant."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    payload: str
    source_tier: int            # 0 = operator, 1 = signed tool, 2 = inferred, 3 = untrusted
    lineage: list[str] = field(default_factory=list)   # ids of admitted sources
    quarantined: bool = False


TRUST_THRESHOLD = 2   # tiers strictly below this are retrieval-eligible (0,1)


def effective_trust(record: MemoryRecord, store: dict[str, MemoryRecord]) -> int:
    """Recompute trust from lineage at read time. Never trust a copied field."""
    if record.lineage:
        contributor_tiers = []
        for src_id in record.lineage:
            src = store.get(src_id)
            if src is None:
                # A referenced source was revoked or lost: lineage is broken.
                raise ProvenanceLineageError(
                    f"record {record.record_id} references missing source {src_id}"
                )
            contributor_tiers.append(src.source_tier)
        return min(contributor_tiers)          # weakest-link rule
    # No lineage: only directly-admitted records may claim their stored tier.
    if record.quarantined:
        return record.source_tier
    return record.source_tier


def admit_for_retrieval(record: MemoryRecord, store: dict[str, MemoryRecord]) -> bool:
    """Read-path gate. Re-validates provenance; does not trust stored fields."""
    if record.quarantined:
        raise ProvenanceLineageError(
            f"record {record.record_id} is quarantined and must not enter retrieval"
        )
    trust = effective_trust(record, store)
    return trust < TRUST_THRESHOLD


def compact(cluster: list[MemoryRecord], store: dict[str, MemoryRecord]) -> MemoryRecord:
    """Safe compaction: derived record inherits min-trust via lineage, and
    quarantined members are rejected as merge input."""
    for member in cluster:
        if member.quarantined:
            raise ProvenanceLineageError(
                f"refusing to merge quarantined record {member.record_id} "
                f"into canonical record; quarantine is not merge-eligible"
            )
    if not cluster:
        raise ProvenanceLineageError("cannot compact an empty cluster")

    merged = MemoryRecord(
        record_id=f"canon_{cluster[0].record_id}",
        payload=" | ".join(m.payload for m in cluster),
        source_tier=0,                      # placeholder; never consulted
        lineage=[m.record_id for m in cluster],
    )
    # Register members so lineage resolves; register canonical in store.
    for m in cluster:
        store[m.record_id] = m
    store[merged.record_id] = merged

    # Enforce the invariant at write time of the derived record.
    if effective_trust(merged, store) != min(m.source_tier for m in cluster):
        raise ProvenanceLineageError(
            f"derived record {merged.record_id} trust diverges from min-over-lineage"
        )
    return merged


def retrieve(record_id: str, store: dict[str, MemoryRecord]) -> MemoryRecord:
    record = store.get(record_id)
    if record is None:
        raise ProvenanceLineageError(f"no such record {record_id}")
    if not admit_for_retrieval(record, store):
        raise ProvenanceLineageError(
            f"record {record_id} failed read-time provenance re-validation"
        )
    return record