# Total Recall: The Context Window as a Cache Over the Session Record: v7.6 → v7.7

From v7.6 (14 Jun) to v7.7 (29 Jul): 8,208 words to 9,052 words, 1,093 words in new or rewritten paragraphs and 249 taken out, 26 paragraphs changed.

## Change note of v7.7

**Measured: compaction fired far too early; adds prefix stability**

Changes driven by measurements listed in the improvement notes of 28 July.

- New section making prefix stability (keeping the start of the context unchanged so caching works) a design constraint, and admitting that pointer eviction is in tension with it.
- Reports that in production, compaction fired at a median of about 5.5% of the real window, because the budget signal was wrong by a factor of about 20.
- Reports that one measurement of tool output in the context read zero because of an instrument bug, and corrects the interpretation.
- Gives a measured recall rate of 22% of turns, used in the cost comparison.
- The limitations, the production evidence and the context-record schema grow to match.

## Changed paragraphs

Marks: [-removed-] {+added+}.

### Abstract

Persistent LLM agents must preserve precise strings, causal chains, and decision rationales across sessions that routinely exceed context limits. The industry-standard approach — narrative compaction — replaces this high-resolution state with lossy prose summaries, creating an irrecoverable "only copy" failure. We present **Total Recall**, a lossless, event-sourced memory architecture that treats the context window as a managed cache over a durable store. Instead of summarizing, Total Recall evicts history via **pointer-based compaction** — inserting compact time-range markers with topic hints and retrieval directives — while making all evicted content recoverable through a `recall(query)` tool. Retrieval is **task-conditioned**: injection depends on the active task and expected future needs, not just embedding similarity. To keep total memory bounded along both axes — the in-context cache *and* the long-term store — Total Recall adds a **write-reconciliation** step that classifies each candidate memory as ADD, UPDATE, DELETE, or NONE, so the working set stays bounded while the audit log stays append-only and complete. The **TRACE** production implementation validates these claims. Its full automated test suite passes with zero failures, and controlled benchmarks show **100% needle-in-haystack recall** under forced compaction versus 0% for truncation, and **94% exact-match recall at 2-hop** versus 4% for narrative compaction and 36% for MemGPT-style paging. Compaction [-latency is sub-linear,-] {+completes+} on the order of [-milliseconds,-] {+milliseconds in the tested range,+} and months of production operation indexing thousands of real emails recorded zero lossless-invariant violations.

### 1.1 Why Narrative Compaction Fails

[-1. **Irreversibility.** Once details are omitted from the summary, no reliable recovery mechanism exists. The summary becomes the _only cognitively accessible copy_ of that information. 2. **Compression at maximum load.** Compaction fires near context saturation, precisely when long-context failure modes are most severe.-]

### 1.1 Why Narrative Compaction Fails

[-In production, long-running sessions accumulate massive tool results and repeatedly trigger compaction. The result looks like "forgetfulness" but is actually **cache eviction without storage**. Our system confirmed this directly: sessions over email archives, codebases, and multi-day task threads consistently lost the exact hashes, file paths, and error strings needed for task completion under narrative compaction.-]

### 1.1 Why Narrative Compaction Fails

{+1. **Irreversibility.** Once details are omitted from the summary, no reliable recovery mechanism exists. The summary becomes the _only cognitively accessible copy_ of that information. 2. **Compression on an untrusted budget signal.** Compaction is commonly armed by a token estimate rather than the prompt actually sent to the model. It can therefore fire near saturation, where long-context reasoning is weakest, or far below saturation, where destructive compression buys no useful headroom.+}

### 1.1 Why Narrative Compaction Fails

{+In production, long-running sessions accumulate massive tool results and repeatedly trigger compaction. The result looks like "forgetfulness" but is actually **cache eviction without storage**. Our system confirmed this directly: sessions over email archives, codebases, and multi-day task threads consistently lost the exact hashes, file paths, and error strings needed for task completion under narrative compaction. A separate seven-day deployment trace exposed a trigger-side failure: a per-message field containing aggregate usage across internal calls was interpreted as a context snapshot, reporting 6,448,106 tokens against a one-million-token window. Compaction consequently fired at a median of roughly 5.5% of the window; 29 attempts reached a 540-second orchestration cap and were discarded even though the compaction operation itself took 19 ms. These measurements concern the surrounding runtime's narrative compactor, not Total Recall's pointer compactor. They show that the trigger and orchestration path, not the eviction algorithm alone, determines deployed safety and latency.+}

### 2.4 Convergent Prior Art: Reversible Compress-Cache-Retrieve

{+Placement in the execution stack is a separate precondition from compression quality. In one deployment, a headroom proxy was installed and enabled but observed only six lifetime requests and saved no tokens because the active CLI subprocess did not inherit the proxy environment. This integration null does not test headroom's compressor; it shows that a boundary component can satisfy its local contract while missing the traffic it is meant to transform. Total Recall runs inside context assembly and therefore observes the history it evicts. Any cross-system evaluation must verify traffic coverage before comparing token savings or accuracy.+}

### 3.3 Prefix Stability as a Design Constraint

{+### 3.3 Prefix Stability as a Design Constraint+}

### 3.3 Prefix Stability as a Design Constraint

{+Prompt caching rewards a byte-identical prefix. Pointer compaction, narrative compaction, and in-place compression all contend over that same prefix: deleting or rewriting a span in the middle invalidates the cached suffix after the edit point. Prompt-cache-friendly ordering therefore means keeping stable system, workspace, skill, and tool-schema blocks first; placing volatile retrieval material near the tail; and batching eviction so the prefix is rewritten as rarely as the context budget permits.+}

### 3.3 Prefix Stability as a Design Constraint

{+This cost is material in the measured deployment. One accounting window contained 122,422,666 cache-read tokens against 15,841 fresh-input tokens, while a separate telemetry sample measured a 91.1% cache-hit rate (98.6% median) and 10.6 cache reads per write. Pointer eviction remains attractive because it mutates the prefix once per eviction rather than retaining a large artifact on every later turn, but a marker's token count alone is not its full cost. The operational metrics are cache-hit preservation, reads per write, and compactions per day.+}

### 5.1 Eviction Ordering

{+The weights describe preference, not guaranteed opportunity. In one production anatomy trace, tool-result attribution initially measured zero because the runtime used a role literal the instrument did not recognize; the zero was an instrumentation defect, not evidence that tool results were absent or free. More generally, artifact externalization (§9.3) may already have removed the highest-weight class before compaction runs. The selector must therefore report bytes by attributed class and reconcile those slices against the total rather than assume its preferred victim exists.+}

### 7.1 Linear Memory Growth

The append-only store and pointer-based compaction yield strictly linear storage growth $O(T)$, avoiding the quadratic bloat of recursive summarization. Compaction [-latency confirms this:-] {+completed in+} roughly 0.20 ms at 100 events and 0.48 ms at 200 events [-(§9.4,-] {+(§10.4,+} Table [-2).-] {+2); two points establish millisecond-scale execution in this range, not an empirical complexity class.+}

### 7.3 Marker vs. Summary vs. In-Place Compression Token Cost

[-The marker pays a small, occasional `recall` cost only when evicted detail is actually needed (measured at 22% of turns, §9.3), versus a narrative summary that pays a recurring recap tax on *every* turn whether or not the detail is used. In-place compression sits between the two: it pays a smaller recurring re-read tax than narrative summarization (the resident proxy is compressed, not full prose) and recovers the exact original from cache, but it keeps a representation resident on every turn rather than removing the span, and the resident proxy is itself a lossy artifact that can mislead before a recovery is triggered. Pointer compaction is strictly cheaper in steady state for sessions where most evicted content is never re-touched — the common case — while in-place compression is preferable precisely when the evicted content is re-touched often enough that a resident, addressable proxy earns its recurring cost. The two are composable (§2.4): compress a span before evicting it behind a marker when it is likely to be re-touched, and eviction discipline handles the rest.-]

### 7.3 Marker vs. Summary vs. In-Place Compression Token Cost

{+The marker pays a small, occasional `recall` cost only when evicted detail is needed, versus a narrative summary that pays a recurring recap tax on every turn. The 22% pull frequency in §10.3 is not itself a re-touch rate. An independent audit of coding-agent file access supplies a bounded proxy: across 890 sessions, 4,402 Read calls, and 23,376,348 bytes, exact repeats accounted for 25,042 bytes over 7 calls and subset containment for 94,971 bytes over 35 calls—about 0.5% of traffic combined. The distribution nevertheless had a heavy tail, with one file read 34 times and context residency at median 48, mean 139.6, and p90 364. This corpus is file access rather than evicted conversation history, so it supports the common-case premise without proving it for dialogue.+}

### 7.3 Marker vs. Summary vs. In-Place Compression Token Cost

{+In-place compression pays a smaller recurring re-read tax than narrative summarization and recovers the original from cache, but keeps a lossy proxy resident. Pointer compaction is cheaper when re-touch is rare and its saved recurring tokens exceed the occasional pull plus cache-prefix rebuild. In-place compression is preferable when frequent re-touch makes a resident proxy earn its cost. The two remain composable (§2.4), but the amortized comparison must include prefix invalidation: a pointer of tens of tokens can still be expensive if inserted mid-prefix after a large cached history. The correct decision variable is therefore workload-specific, not a universal ranking.+}

### 9.6 Context Anatomy

The Context Anatomy module records the [-full-] decomposition of every LLM prompt: system prompt, workspace files, skills, tool schemas, conversation history, tool results, and user message. Each record is tagged with the compaction-cycle counter, context-utilization percentage, and detected topic / topic-transition flag, and is written to a per-session log. It is the primary diagnostic for understanding compaction behavior in production: [-by-] replaying [-anatomy records,-] {+records lets+} an engineer [-reconstructs exactly-] {+compare+} what [-was in-context at any turn, which markers were present,-] {+the budget gate believed with the per-call prompt composition+} and {+identify+} when compaction [-fired. It sits at the intersection of all three memory layers — the hot tail feeds the history slice, persona-aware assembly appears in the system-prompt field, and Total Recall's pointers appear in the conversation-history slice — which makes it the single most useful tool for cross-layer memory debugging. Because it itemizes `skillBytes` and `toolSchemaBytes` as distinct slices, it also exposes the eviction headroom in static capability sets that §6.1 exploits.-] {+fired.+}

### 9.6 Context Anatomy

{+That comparison found the aggregate-usage defect reported in §1.1. It also found the opposite error: a roughly 15K-token system prompt was scored as zero because its synthetic role had no estimator branch. A later audit found the same defect for tool results, invalidating an earlier 52,116-token composition estimate and its derived percentages. Context Anatomy is therefore useful only when every block has an explicit attribution rule, unattributed content is surfaced as an error, and the sum of slices reconciles against an independently measured prompt total. Itemizing a field does not establish that production messages reach it.+}

### 10.4 TRACE Implementation Benchmark: Lossless Store Invariant

| Event count | Compaction latency | | -------------- | ------------------ | | 100 events | 0.20 ms | | 200 events | 0.48 ms | | [-Scaling factor-] {+Observed ratio+} | [-0.48× (sub-linear)-] {+2.4×+} |

### 10.4 TRACE Implementation Benchmark: Lossless Store Invariant

[-Doubling event count increased latency by 0.48× — consistent with the $O(T)$ bound (§7.1) and confirming no quadratic blowup. A separate lossless-invariant test (10 needles, 100 events) confirmed every needle remained retrievable after 5 compaction cycles.-]

### 10.4 TRACE Implementation Benchmark: Lossless Store Invariant

{+Doubling event count increased observed latency by 2.4×. This two-point microbenchmark is compatible with millisecond-scale operation at the tested sizes but is insufficient to distinguish linear from super-linear scaling. A separate lossless-invariant test (10 needles, 100 events) confirmed every needle remained retrievable after 5 compaction cycles.+}

### 10.5 Full TRACE Test Suite

The complete TRACE test suite runs against the production codebase and passes with **zero failures** across all core and integration modules — event store, ingestion, retrieval, pointer compaction, reconciliation, sleep consolidation, reflection, and the indexing-layer tests. Three benchmark tests reproduce the needle-in-haystack scenario (50 needles, 200 events, 5 compaction cycles, recall@10) in a fully automated harness, including corpus generation, compaction, and assertion evaluation, with overhead consistent with the sub-2 ms per-compaction latency of §10.4. [-The zero-failure rate confirms-] {+Passing these tests supports the invariants exercised by the suite; it does not establish+} comprehensive coverage of [-the invariants this paper claims.-] {+every production failure mode.+}

### 10.6 Production Deployment Evidence

- **Thousands of emails indexed** in the durable event store, with full recall available on demand across sessions. - **Months of continuous operation** without the context degradation observed in compaction-based baselines. - **Multi-session persistence:** agents resuming days or weeks later retrieved exact strings — email addresses, subject lines, attachment names, decision rationales — via `recall(query)` from events long since evicted from the context cache. - **Zero lossless-invariant violations** in monitored [-sessions.-] {+sessions. - **Trigger-path diagnosis:** per-call anatomy exposed a runtime usage aggregate being mistaken for context size, which armed 29 premature narrative-compaction attempts in seven days. - **Prompt-cache telemetry:** a 91.1% hit rate and 10.6 reads per write establish prefix preservation as a first-order deployment cost, not merely an ordering preference.+}

### 11. Limitations and Future Work

{+**Budget and anatomy validity.** No eviction policy is safer than the measurement that triggers it. The deployment instrument was wrong in both directions before correction: aggregate usage over-counted context, while unrecognized roles caused system-prompt and tool-result content to be omitted. A production gate must consume a per-call snapshot, attribute every prompt block, fail visibly on unattributed content, and reconcile component totals against an independent total. The corrected role handling has not yet produced a replacement composition sample, so this paper deliberately does not publish the invalidated 52,116-token slice percentages.+}

### 11. Limitations and Future Work

{+**Traffic-path coverage.** A locally correct proxy or telemetry producer can receive no live traffic. The headroom integration null (§2.4) makes traffic coverage a prerequisite for the planned shared benchmark: report requests observed at the mechanism boundary as well as accuracy and token savings.+}

### 12. Conclusion

Total Recall replaces it with a principled alternative: treat the context window as a cache over a lossless store, evict via pointers instead of summaries, retrieve on demand with task-conditioned priority, and reconcile writes so the working set stays bounded while the audit log stays complete. The [-approach is simple, the implementation is compact, and the-] {+controlled+} results are [-unambiguous:-] {+strong but preliminary:+} 100% {+storage-invariant+} needle recall where truncation achieves [-0%;-] {+0%, and+} 94% [-exact-match-] {+end-to-end exact match+} at 2-hop where narrative compaction achieves [-4%; sub-linear compaction latency;-] {+4%, across ten synthetic traces. Production evidence supports durability while exposing two costs the algorithm-only benchmark omitted: trigger validity+} and [-months of production operation with zero data loss.-] {+prompt-prefix invalidation.+} The same eviction-plus-pointer principle generalizes beyond conversation history to static capability sets, collapsing a 44-entry skill catalog from ~915 to ~130 always-resident tokens with no loss of reachability (§6.1).

### A.4 Context Anatomy Record Schema

| Field | Type | Meaning | | --------------------- | --------------- | ------------------------------------------------ | | `turnId` | identifier | Time-sortable turn ID | | `sessionId` | identifier | Owning session | | `compactionCycle` | integer | Monotonic count of compactions this session | | `contextUtilPct` | percentage | [-Tokens used-] {+Per-call attributed tokens+} / {+configured+} budget | | `systemPromptBytes` | integer | Size of the system-prompt block | | `workspaceFileBytes` | integer | Size of injected workspace files | | `skillBytes` | integer | Size of skill definitions | | `toolSchemaBytes` | integer | Size of tool schemas | | `historyEventCount` | integer | Conversation events in context | | `markerCount` | integer | Time-range markers present | | `userMessageBytes` | integer | Size of the current user message | | `topicLabel` | string or null | Detected task-domain topic | | `topicTransition` | boolean | True if the topic changed from the previous turn |

### A.4 Context Anatomy Record Schema

{+Every prompt block must be assigned by a shared canonical role classifier. Unknown roles accumulate in an `unattributedBytes` field and emit a diagnostic rather than silently contributing zero. Before a record is accepted, all attributed slices plus `unattributedBytes` must reconcile against an independently computed total within the tokenizer's declared tolerance. Aggregate turn usage is never a valid substitute for this per-call total.+}
