Manuscript Offprint

arXiv:2609.00865

MemoryWalker: Stop Training Agents on Contexts They Never Saw

Zinco J, Xunjie Zhu, Shen Huang, Zhenyi Wang, Pengjun Xie, Jieping Ye

Abstract

Production agent harnesses, including Claude Code and Qwen-Agent, compress an agent’s context during rollout to make long-horizon interaction tractable. Training policies under such compression, however, introduces a fundamental conditioning problem: each compression eviction branches the effective interaction history, making the object presented to the learning objective a tree rather than a single sequence. Existing pipelines typically linearize this tree in one of two ways: retaining only the rightmost root-to-leaf path, which causes time-travel leakage, or replaying the full depth-first traversal, which induces a train-inference mismatch. Thus, we introduce two exact conditioning-level corrections and prove their gradient equivalence: LogitTree, a segmented K-forward traversal of the logits tree, and an equivalent packed 4D attention mask. LogitTree requires K+1K+1 backward passes, whereas the 4D formulation requires both a custom masked-attention kernel and white-box access to eviction records. To avoid these costs, we further propose SDCC (Self-Distillation for Conditioning Consistency), a training-friendly variational relaxation requiring only a single backward pass. At each eviction junction, SDCC minimizes the forward KL divergence between the compressed student policy and a stop-gradient teacher evaluated on the reconstructed pre-eviction prefix. By Pinsker’s inequality, a residual per-junction KL divergence of εKL\varepsilon_{\text{KL}} yields an O(εKL)\mathcal{O}(\sqrt{\varepsilon_{\text{KL}}}) bound on the resulting train-deployment behavioral gap in total variation. Unlike the exact corrections, SDCC applies without modification to black-box harnesses. We evaluate our framework with three white-box context editors—TC-RAG, AgentFold, and MemexRL—and two black-box harnesses—Claude Code and OpenCode. Across seven web-search benchmarks, naive compressed-stream training substantially inflates the train-rollout log-probability gap relative to the no-compression floor, with the largest inflation on eviction-heavy batches. In contrast, both exact corrections—LogitTree and the 4D attention mask—remain at the no-compression floor, while SDCC substantially closes the gap. These gains in conditioning consistency are accompanied by lower logit drift and higher rollout rewards than naive compressed-stream training.

1 Introduction

Long-horizon agents, including deep-search assistants (Xi et al., 2025), coding copilots (Wang et al., 2025), browser-based research agents (Shi et al., 2025), and multi-turn planners (Huang et al., 2024)—can accumulate trajectories spanning tens to hundreds of thousands of tokens. Retaining the full interaction history is not only computationally expensive, but can also impair decision making: ① outdated observations, abandoned plans, and failed attempts introduce substantial contextual noise (Jiang et al., 2025a); ② state rollback can invalidate the actions and observations associated with a reverted branch (Jiang et al., 2025a); and ③ critical goals and instructions may be diluted or overlooked as the context grows, exacerbating the lost-in-the-middle effect (Liu et al., 2023; Chen et al., 2026). Production agent harnesses therefore actively compress and rewrite interaction histories to maintain compact, decision-relevant contexts. For example, Claude Code (Anthropic, 2024) and Qwen-Agent (Team, 2024) maintain bounded context windows and replace evicted prefixes with automatically generated summaries. Other approaches, including TC-RAG (Jiang et al., 2025a), MemexRL (Wang et al., 2026) and AgentFold (Ye et al., 2025; Zhou et al., 2025) introduce model-aware memory mechanisms that allow the agent to determine whether, when, what and how to compress, offload, or retrieve information on demand.

Across these context-compression designs, a memory editor (hook) rewrites the interaction history into a bounded live context before each decoding step. Although this improves inference-time tractability and decision quality, it creates a subtle problem for post-training (SFT and RL): when the trainer recomputes the log probabilities of rollout tokens, the context under which a token was originally generated may no longer be available.

Training on the conditioning tree, not the sequence. This missing-context problem arises because harness-level compression breaks the correspondence between token order and conditioning history. At each eviction junction, the original prefix is replaced by a compressed view: tokens preceding the edit were generated under the original prefix, whereas subsequent tokens are generated under its compressed replacement. Repeated edits therefore induce a tree of conditioning histories, rather than a single sequence that can be replayed consistently, as illustrated in Figure 1(a). Existing pipelines (Ye et al., 2025; Zhou et al., 2025; Wang et al., 2026; Jiang et al., 2025a) typically initialize this tree in one of two ways. ① Training on the surviving compressed stream follows only the rightmost root-to-leaf path, causing earlier tokens to be reevaluated as if they had been conditioned on summaries created only later—an error we call time-travel leakage. ② Training on the full raw trace instead follows a depth-first traversal, causing later tokens to be reevaluated with evicted content that is unavailable during rollout and deployment—a train-inference conditioning mismatch. In both cases, recomputing token logits under the resulting sequence assigns tokens contexts different from those under which they were originally generated, producing substantial train-inference logit inconsistency.

From the conditioning tree to exact solutions. To restore the context under which each rollout token was originally generated, we formulate training as a traversal of the conditioning tree and introduce two exact approaches to walk the tree, gradient-equivalent constructions. ① LogitTree performs a segmented traversal, separately evaluating the KK pre-eviction branches, ② whereas a packed 4D attention mask encodes the same branch structure within a single forward pass. As shown in §4, both constructions yield the same policy gradients and exactly recover the correct rollout conditioning. This exactness, however, comes at a computational or systems cost: LogitTree requires (K+1)(K+1) segmented model evaluations, whereas the packed formulation relies on a custom masked-attention kernel that is difficult to integrate efficiently with fused attention implementations and is restricted to white-box harnesses with access to eviction records. To recover conditioning consistency without explicitly replaying every branch of the context tree, we further propose SDCC (Self-Distillation for Conditioning Consistency; §5). Instead of exactly reconstructing the conditioning context for every rollout token, SDCC trains the policy under the surviving compressed context to match its behavior under the original pre-eviction context. Specifically, at each eviction junction, it minimizes the forward KL divergence from the compressed student policy to a stop-gradient teacher evaluated under the reconstructed pre-eviction prefix. A wake-sleep argument determines the KL direction, and Pinsker's inequality converts a residual per-junction KL divergence of εKL\varepsilon_{\text{KL}} into an O(εKL)\mathcal{O}(\sqrt{\varepsilon_{\text{KL}}}) bound on the corresponding behavioral discrepancy in total variation. This relaxation requires only a single backward pass per trajectory and extends to black-box harnesses without requiring white-box modification of their attention computation.

Contributions. Our contributions are fourfold:

  • We formalize context compression training as a conditioning-inconsistency problem (§3). We prove that the two common rollout compression—Naive-Compressed and Naive-Full—lead to time-travel leakage and train-inference conditioning mismatch, respectively.

  • We propose two exact, gradient-equivalent solutions to walk the context tree (§4). LogitTree explicitly traverses the conditioning tree, while a packed 4D attention mask represents the same structure in a single forward pass.

  • We introduce SDCC, a training-efficient relaxation (§5). SDCC distills policy behavior under the original pre-eviction context into the surviving compressed context, requires only one backward pass, and generally applies to white-box and black-box harnesses.

  • We validate the framework across compression mechanisms and agent tasks (§6). Across three white-box and two black-box memory editors, on seven web-search benchmarks, our methods reduce train-inference inconsistency and logit drift while improving rollout rewards over naive compressed-stream training.

References (92)