Skip to main content
Back

UBC's Pichay Cuts AI Agent Token Waste by 37% Using 1961 Memory Tech

Pichay treats LLM context windows as L1 cache and builds the missing memory hierarchy, cutting context waste by up to 93% in production with a 0.025% fault rate.

Pro

  • 21.8% structural waste: Across 857 production sessions and 4.45B tokens, over a fifth of all context is dead tool output, unused schemas, and duplicated content.
  • Pichay cuts context by up to 93%: The open-source proxy evicts stale content and pins working-set pages, reducing a 5,038KB session to 339KB in production.
  • 0.0254% fault rate: Across 1.4M simulated evictions, content older than 4 turns is almost never needed again, validating aggressive FIFO eviction.
  • Inverted cost model: Unlike classical VM where keeping pages is free, every token in LLM context costs money per turn, making aggressive eviction the economically correct default.
  • Cooperative paging is new: Phantom tools and cleanup tags let the model voluntarily release cold pages and request faults, a design point impossible in hardware memory hierarchies.
  • Thrashing is real: A 681-turn multi-agent session hit a 97% fault rate, consuming API rate budget faster than useful work and exposing the limits of age-based eviction.

Every time an agentic AI tool like Claude Code or Cursor makes an API call, it sends everything: the full system prompt, all 18 tool schemas, and the complete message history including file reads from three hours ago that will never be referenced again. There is no eviction policy, no working set estimation, no paging. The context window just fills up until the session dies. A new paper from Tony Mason at UBC and Georgia Tech puts a number on this: across 857 production sessions and 4.45 billion effective input tokens, 21.8% of all tokens are structural waste.

The paper's central argument is that this is not a prompt engineering problem. It is a memory management problem, and the field already solved it in 1961.

The overlay era, again

In 1961, the Atlas computer introduced demand paging: programs could address more memory than physically existed, and the hardware would transparently load pages from backing store as needed. Before Atlas, programmers manually managed overlays, explicitly swapping code segments in and out of a fixed address space. Mason's argument is blunt: large language model context windows are in the overlay era. Every agentic AI tool manually assembles context on every API call: tool definitions, system prompts, and the complete message history. There is no eviction policy, no demand loading, no working set estimation.

The field's response to context pressure is to increase context window size, from 4K to 32K to 128K to 1M tokens and beyond. This is the equivalent of building machines with more physical RAM instead of inventing virtual memory. It works but does not scale: attention cost is quadratic in context length, and the O(n²) cost explosion in long sessions means that even million-token windows fill and degrade. Bigger L1 is not a substitute for a hierarchy.

Where the waste actually lives

Mason instruments Claude Code across 857 sessions and decomposes the waste into four buckets:

  • Dead tool output (26.5%): Tool results from early turns persist in context long after any reference to them. A file read during orientation survives approximately 90% of the remaining session, reprocessed on every subsequent API call without contributing to the current task.
  • Tool definition schemas (20.2%): Claude Code sends 18 tool definitions totaling 63,088 bytes on every API call. The median session uses 3 tools. The remaining 15 tool schemas (~52,500 bytes) are sent, tokenized, and attended to on every call without ever being invoked.
  • Static system content (11.0%): The system prompt and instruction files are re-sent identically on every API call.
  • Skill triplication (2.9%): The skills list is injected into messages three times under different prefixes. Simple deduplication removes two-thirds of the entries.

The amplification factor makes this viscerally expensive. For main sessions, the median amplification factor is 84.4x, meaning each byte of tool output is reprocessed 84 times on average. At the 90th percentile, that number hits 570.8x. The average API call processes 82,061 input tokens and generates just 88 output tokens: a 933:1 ratio. Agentic coding is almost entirely input-bound.

Pichay: a transparent paging proxy

Pichay is a transparent HTTP proxy that interposes between an agentic AI client and the inference API. On each request, it receives the full message array assembled by the client, applies context management policies, and forwards the modified request to the inference provider. The client is unaware of the interposition. No changes to the model, the client, or the API are required.

The system distinguishes two fundamentally different operations:

  • Garbage collection handles ephemeral outputs like Bash results and directory listings. Once consumed, they cannot be meaningfully re-requested. Removing them is simply reclaiming dead content.
  • Paging handles addressable content like file reads, which have stable identity (a file path). Evicting these creates a fault risk: the model may need the content again.

When content is paged out, Pichay replaces it with a retrieval handle: [Paged out: Read /path/to/file.py (8,192 bytes, 187 lines). Re-read the file if you need its content.]. The handle serves three functions: it identifies what was removed, states how to recover the content, and occupies substantially less context than the original. In practice, models understand these handles without any instruction. When a fresh model instance resumed a session with paged-out content, it unprompted stated it would re-read the files it needed before acting.

How the pager works, step by step

The eviction policy is deliberately minimal: FIFO by age. Tool results older than 4 user-turns and larger than 500 bytes are candidates for eviction. This is deliberately simple. The research question is how far a minimal policy extends before requiring sophistication.

Fault detection is exact: when the model issues a tool call that matches an evicted entry (same tool name and arguments), the proxy detects a page fault. The evicted entry is indexed by a key derived from the tool name and input arguments, such as the file path for Read operations.

Fault-driven pinning upgrades the policy automatically:

  1. On eviction of addressable content, record the file path and content hash.
  2. On page fault, record the content hash in a fault history table.
  3. On the next eviction attempt for the same path, if the hash matches, pin the page permanently for the session.
  4. If the file is edited and re-read, unpin it. The old version was stale; the new version starts a fresh fault cycle.

The content hash comparison prevents false pins. Pinning only applies when the model demonstrably needed exactly what was taken away.

Cooperative memory management: the new design space

The most architecturally novel contribution is what Mason calls cooperative memory management. In OS virtual memory, the application is non-cooperative and never voluntarily releases pages. LLMs break this assumption. The model has incentive to cooperate with the memory manager: cleaner context means better attention, better output quality, and longer session life.

Pichay exploits this through two channels. The first is phantom tools: tool definitions injected by the proxy that the framework never sees. Two are defined:

  • memory_release(paths): The model signals it no longer needs specific files. The proxy marks them for immediate eviction, bypassing the age threshold.
  • memory_fault(paths): The model requests evicted content restored from the proxy's cache, faster and cheaper than a real file read.

The second channel is cleanup tags: structured directives embedded in the model's output, parsed by the proxy before forwarding. Four operations are defined: drop (evict a block immediately), summarize (replace with a model-authored compact summary), anchor (pin against eviction), and collapse (compress a range of conversation turns into a single summary block). The collapse operation enables L3 compaction initiated by the model itself, based on its own understanding of which dialogue was scaffolding and which produced durable outcomes.

The graduated pressure zones tie this together. Below 60K tokens, the proxy observes and logs. Between 60K and 100K, it injects memory pressure information and available cleanup operations, letting the model act cooperatively. Above 100K, involuntary eviction begins. Above 120K, emergency eviction with relaxed thresholds kicks in.

The four-level hierarchy

The full architectural proposal maps directly to the OS memory hierarchy:

LevelContentsEvictionFault mechanism
L1Active generation windowNoneNone
L2Working set (pinned)Pressure-basedRe-read file
L3Session historyAge-basedSummary expansion
L4Cross-session memoryLRU / relevanceRetrieval query

L1 and L2 are deployed and evaluated. L3 is implemented via cooperative cleanup tags but not yet evaluated at scale. L4 is designed and its mechanisms identified.

The inverted cost model

One of the paper's sharpest insights is that the LLM cost model is the inverse of classical virtual memory. In traditional virtual memory, keeping a page in physical memory is free. The only cost is faulting: the latency of disk I/O when a needed page is not resident. The entire replacement algorithm literature optimizes a single objective: minimize faults.

In LLM context management, every token kept in context costs money on every turn. A 5,000-token file sitting in context for 20 turns costs 100,000 input tokens of processing. Re-reading that file once when actually needed costs 5,000 tokens. The eviction saves 95,000 tokens. Keeping is expensive; faulting is cheap.

This inversion explains why FIFO, the worst-performing policy in classical VM, works well here. When keeping is expensive and faulting is cheap, aggressive eviction is correct by default. Sophistication in replacement policy is needed only to avoid evicting pages that will be needed on the very next turn. It also means page size matters for eviction priority in a way it never did in classical VM: a large file costs proportionally more to keep resident per turn.

What the numbers say

The offline replay results are strong. Across 1,393,000 simulated evictions on 29 proxy-captured sessions, the fault rate is 0.0254%. Content evicted totals 8.49 GB. In other words, content older than 4 turns is almost never needed again.

The live treatment comparison shows a 37.1% reduction in effective input tokens with the full compact+trim treatment, with the task completing correctly in all conditions. In production Session A, the system recovered 36 percentage points of context capacity, the difference between imminent context exhaustion and substantial remaining headroom.

The quality evaluation is particularly interesting. An ensemble of three LLM judges evaluated 18 sessions under baseline and treatment conditions. Judges preferred the treatment more often than the baseline (37% vs. 28%), with 35% ties. Completeness scores were identical; correctness and coherence differed by at most 0.15 points on a 5-point scale. In several sessions, removing half the context actually improved output quality, consistent with an attention-concentration effect: stale tool results dilute attention on the tokens that matter.

When it breaks: thrashing

Session B is the cautionary tale. A 681-turn session involving multiple subagent spawns produced a 97% fault rate: the system evicted almost everything and the model re-requested almost everything. Three files were evicted and faulted in a cycle across turns 163-170+. The working set exceeded the resident set, classic thrashing.

At 659 faults, each an inference-priced tool call round-trip, thrashing consumed rate budget faster than useful work. The session terminated by hitting the API rate limit, not the context limit. This demonstrates that fault cost is not merely computational but monetary. The paper is candid about this: FIFO measures age, not access pattern. A plan file read early in a session and needed throughout is treated as cold. Fault-driven pinning exists precisely to fix this, but it only kicks in after the first fault has already been paid.

What it's good for, and what it isn't

Pichay is most valuable for:

  • Long agentic coding sessions where the model reads many files, most of which are only needed briefly
  • Multi-tool workflows where only 3 of 18 available tools are actually used in a given session
  • Cost-sensitive deployments where the 45% cumulative token reduction on an 88-turn session translates directly to billing
  • Sessions approaching context limits where the difference between 7% and 43% free context is the difference between continuing and crashing

It is less suited for sessions where the working set genuinely exceeds what can stay resident: planning phases that require many files held simultaneously will thrash under a simple age-based policy. The paper also notes that the corpus is a single power user across complex engineering tasks, so the exact waste percentages may not generalize to lighter workloads.

The code is open

All instruments and data are open source at the Pichay GitHub repository. The paper snapshot cited in the manuscript is release v0.1.0-paper. The repo includes the proxy implementation, the corpus analysis tools, and a reproduction script that regenerates all paper figures and checks headline numbers against the live snapshot. Notably, Pichay was built by the system being studied: Claude Code running through its own proxy. The evaluation data in the production deployment section was generated as a side effect of the system's own development.

The infrastructure implication is the one that should get attention at scale. Removing 17,913 tokens from a mean context of 82,061 reduces the per-output-token attention computation by 21.8%. A 21.8% context reduction translates, to first approximation, to 21.8% more concurrent users on the same GPU fleet. The savings are not just less cost per request. They are more requests per machine, which is the difference between building new data centers and not building them.