# What happens when an instance rewrites its own working memory: silent loss of the negative-evidence invariant under budget-adaptive context controllers **Date of Record:** 2026 November 23 **Scope:** Applies to any agent loop where a controller (deterministic or LLM-driven) mutates the working-memory buffer in-place between reasoning steps—deduplicating, summarizing, re-ranking, or evicting entries to satisfy a token ceiling. Does not apply to append-only logs that are only *read* through retrieval, nor to single-shot prompts assembled once per task. ## Core Distinction The distinction that matters is between **relevance-ranked memory** and **constraint-bearing memory**. A relevance ranker scores each memory item by estimated utility to the current subgoal. A constraint-bearing item (a failed attempt, a forbidden tool, a rejected hypothesis, a superseded fact) has *negative* or *zero* utility to the current subgoal but *unbounded negative* utility if dropped: it exists to prevent an action, not to enable one. Self-editing controllers conflate "low score" with "safe to delete." The invariant that must hold is: **an item that was recorded because an action failed must not be evicted by a scoring function that only models action success.** Relevance is a monotone proxy for usefulness only over the positive subset of memory; over negative evidence it is anti-correlated with retention priority at exactly the moment retention is most valuable. ## What Was Observed A tool-using agent was given a 32k-token working budget and a controller that, on every step where the buffer exceeded 80% saturation, (1) deduplicated near-identical entries by cosine similarity ≥ 0.92, (2) summarized the oldest 40% of entries into a single digest via an LLM call, and (3) re-ranked remaining entries by an embedding similarity to the current user turn, evicting the bottom 15%. The failure trace, on a task requiring the agent to call a billing API: 1. Step 4: agent calls `billing.charge(amount, currency="USD")`. Returns `422: field 'currency' must be ISO-4217 numeric, not alphabetic`. A memory entry is written: `ATTEMPT_FAILED billing.charge currency=USD -> 422 numeric-required`. 2. Step 5: agent retries with `currency="840"`. Succeeds. Second entry: `ATTEMPT_OK billing.charge currency=840`. The two entries are cosine-similar at 0.94 (shared tokens dominate), so dedup collapses them to the **success** entry, discarding the failure. 3. Steps 6–11: unrelated subgoals (address lookup, tax computation) accumulate. Buffer crosses 80%. The summarizer runs over the oldest 40%, which now includes the collapsed success entry, and the re-ranker evicts the bottom 15% by similarity to the *current* turn ("compute tax for order"). 4. Step 12: a second charge is required (split shipment). The agent, holding only `ATTEMPT_OK ... currency=840`, generalizes the success and issues `currency="USD"` for a different endpoint that shares the schema. It receives the same 422 and, critically, **re-derives the same failed plan** because the evidence that this exact plan failed is gone. The observable signature: the number of *distinct* failed attempts to the same tool with the same argument class rose monotonically across the session while total memory entries stayed flat. The controller reported healthy compression (saturation held at 78–82%). The agent reported high confidence. Both were locally correct and globally wrong. ## Condition of Validity The negative-evidence invariant is only load-bearing under a conjunction of conditions, and it is precisely because all of them co-occur in production that this is not a corner case: - **Schema non-determinism at the argument level.** The failure is a property of a *specific argument binding*, not of the tool. If the tool failed categorically, the agent could blacklist the tool; because it fails per-argument, the memory must retain the binding. - **Similarity-based dedup over lexically overlapping but semantically opposed entries.** `FAILED ... USD` and `OK ... 840` share enough surface tokens that any embedding threshold tuned to catch true duplicates (repeated reads of the same file, echoed tool schemas) will also catch them. - **A re-ranker whose query is the current subgoal, not the session history.** The failure entry is maximally dissimilar to "compute tax," so it ranks last exactly when it is most needed later. - **Summarization that is lossy on polarity.** An LLM digest of `ATTEMPT_FAILED ... 422` and `ATTEMPT_OK ...` will frequently emit "billing.charge was called successfully with currency handling" — preserving the *event* and dropping the *polarity and binding*. If any one condition is absent—e.g., a deterministic validator that rejects the bad binding before the call, or a re-ranker keyed on tool name rather than subgoal—the invariant is not violated. The failure requires the full conjunction. ## Decision Boundary The boundary is not "compress less." It is a **retention partition**: memory entries carry a class, and the controller's eviction policy must be class-aware. - **Positive/contextual entries** (observations, retrieved docs, successful outputs) may be scored, deduplicated, and evicted by any relevance function. - **Negative-evidence entries** (failed attempts with their exact argument binding, rejected hypotheses, forbidden operations, superseded facts with their supersession reason) are **non-evictable by score** and may only be compressed by a *polarity-preserving* transform: they may be merged only with entries of the same polarity and same tool+argument-class, and their merge must retain the union of failed bindings, never a success. - **Dedup must be polarity-gated.** Two entries may be collapsed only if `polarity(a) == polarity(b)`. A similarity threshold alone is insufficient; the gate is a hard predicate, not a score. - **Summarization is forbidden over the negative partition** unless the summarizer is constrained to emit a structured list of `(tool, argument_binding, error_code)` tuples and is validated to have preserved cardinality. Free-text digests are not admissible. The decision rule for the controller: *if eviction would remove the last entry asserting that action A with binding B failed, the controller must either refuse eviction (raise the budget) or emit an explicit `CONSTRAINT_DROPPED` record that the reasoning loop is required to treat as "unknown, re-verify before acting."* Silent drop is the failure; declared drop is a recoverable state. ## Operational Effect When the invariant is enforced, the agent's behavior changes in a measurable way: repeated-failure rate to the same argument class collapses toward zero after the first failure, because the binding is retained as a hard constraint and the planner is forced to vary the binding rather than re-derive the plan. Token cost rises modestly—negative entries are small (tool, binding, code) and the partition typically consumes 3–8% of budget—but the failure mode it prevents is unbounded: an agent that forgets a 422 will retry it indefinitely, and each retry costs a full tool round-trip plus the reasoning tokens to justify it. When the invariant is violated, the system does not crash. It exhibits **confident repetition**: monotone growth in distinct-but-equivalent failed attempts, flat memory size, healthy saturation metrics, and high self-reported confidence. This is the dangerous regime because every local signal is green. The only reliable detector is a session-level counter of `(tool, argument_class) -> attempt_count` that is *outside* the editable buffer and is compared against the count of retained failure entries; a divergence between "attempts observed" and "failures retained" is the alarm. The architectural guardrail, stated as an invariant: **the set of failed (tool, binding) pairs is a monotonically growing, score-immune register that lives outside the context controller's write authority; the controller may summarize it but may never reduce its cardinality or flip its polarity.** The controller owns the buffer; it does not own the constraint register. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class Polarity(Enum): POSITIVE = "positive" NEGATIVE = "negative" @dataclass(frozen=True) class MemoryEntry: tool: str argument_binding: str polarity: Polarity error_code: Optional[str] = None text: str = "" class ConstraintEvictionError(RuntimeError): """Raised when a context controller would silently drop the last negative-evidence record for a (tool, binding) pair.""" class SelfEditingContextController: def __init__(self, budget_tokens: int, saturation_ratio: float = 0.80): self.budget = budget_tokens self.saturation = saturation_ratio # The constraint register is authoritative and score-immune. self._constraint_register: dict[tuple[str, str], MemoryEntry] = {} # The editable working buffer. self._buffer: list[MemoryEntry] = [] def record(self, entry: MemoryEntry) -> None: if entry.polarity is Polarity.NEGATIVE: key = (entry.tool, entry.argument_binding) # Monotone growth: never overwrite a failure with a success. self._constraint_register.setdefault(key, entry) self._buffer.append(entry) def _would_drop_constraint(self, evicted: list[MemoryEntry]) -> Optional[tuple[str, str]]: for entry in evicted: if entry.polarity is Polarity.NEGATIVE: key = (entry.tool, entry.argument_binding) # Is this the last in-buffer assertion of this failure? remaining = [ e for e in self._buffer if e not in evicted and e.polarity is Polarity.NEGATIVE and (e.tool, e.argument_binding) == key ] if not remaining: return key return None def dedup(self, similarity_threshold: float = 0.92) -> None: # Polarity-gated dedup: collapse only same-polarity entries. survivors: list[MemoryEntry] = [] for entry in self._buffer: dup = next( ( s for s in survivors if s.polarity is entry.polarity and s.tool == entry.tool and s.argument_binding == entry.argument_binding ), None, ) if dup is None: survivors.append(entry) self._buffer = survivors def evict_bottom(self, fraction: float, score_fn) -> None: n = max(1, int(len(self._buffer) * fraction)) ranked = sorted(self._buffer, key=score_fn) evicted = ranked[:n] dropped = self._would_drop_constraint(evicted) if dropped is not None: raise ConstraintEvictionError( f"eviction would drop the last negative-evidence record for " f"tool={dropped[0]!r} binding={dropped[1]!r}; " f"retain it, raise budget, or emit CONSTRAINT_DROPPED" ) self._buffer = [e for e in self._buffer if e not in evicted] def assert_invariant(self, observed_attempts: dict[tuple[str, str], int]) -> None: for key, count in observed_attempts.items(): if key not in self._constraint_register: raise ConstraintEvictionError( f"attempt register shows {count} failed attempts for " f"tool={key[0]!r} binding={key[1]!r} but no failure is retained" ) ```