Million-Token Context Engineering: Computation, Compression, Routing, and Agent Practices
Long context is moving from a demo capability to an engineering constraint. This article explains how to make million-token context practical by controlling attention and cache costs, managing information loss from compression, routing tasks between high-performance and lightweight models, and keeping agents stable within a limited window. It also covers evaluation, interface design, reasoning effort controls, and release governance.
Long context is shifting from a demonstration feature to an engineering constraint. Code repositories, long documents, multi-turn tool traces, and retrieval results can quickly push sequence length toward the million-token range when they enter the context together. At that point, the real question is not whether the model can read everything, but whether computation, memory, latency, and failure modes remain acceptable.
Making long context a broadly usable capability requires handling four things at once: reducing attention and cache costs, controlling information loss from compression, choosing model routes based on task difficulty, and enabling agents to execute reliably within a limited window.
Where the Cost Actually Goes
Standard self-attention scales approximately quadratically with sequence length. As the sequence grows from tens of thousands to a million tokens, both the attention matrix computation and intermediate activations rise sharply. Meanwhile, during inference, the key-value cache grows linearly with the number of layers, heads, sequence length, and batch size. The bottleneck for long context is often not parameter count, but cache residency, bandwidth, and batching efficiency.
In engineering terms, a single request should be broken into three observable cost segments:
- Prefill: encoding history and new input into the cache. For long inputs, this stage often dominates time to first token.
- Decode: every generated token requires reading the existing cache. The larger the cache, the greater the bandwidth pressure.
- Agent loop: tool calls, observations, and reflection repeatedly append to the context, so the actual length can far exceed the user’s original question.
Therefore, “supporting a million-token context” only describes the window limit. It does not mean throughput, price, and stability remain acceptable at that length. Evaluation should look at least at accuracy at the effective length, cost per request, tail latency, and whether cache eviction or recomputation occurs under concurrency.
What Sparse Attention Solves and What It Does Not
The core idea of sparse attention is that not every query needs to interact with all historical positions with equal strength. Local windows preserve nearby dependencies, while a small number of global or selected positions preserve long-range dependencies, eliminating a large amount of low-value computation. It reduces attention computation and some cache access, not the model parameters themselves.
When deploying sparse attention, do not treat it as a free lunch. Three risks need to be explicit:
- Key evidence may be skipped. Contract clauses, function signatures, error stacks, or anomalous rows in a table may not fall within the local window.
- Position distribution may be uneven. If important information is concentrated at the beginning of a document or at the end of tool results, a fixed window will systematically miss it.
- Training and inference may be inconsistent. If the sparse pattern seen during training differs from the online implementation, long-range question answering can suddenly degrade.
A practical engineering principle is “sparse but fallback-capable”: regular tokens follow the sparse path; retrieved chunks, the most recent tool observations, system constraints, and the user’s latest instructions remain dense or receive higher sampling priority. The sparse strategy should be configurable, reproducible, and logged so that degraded sections can be explained after the fact.
The following is a conceptual illustration of context partitioning, not the interface of a specific implementation:
budget = max_contextreserve(system_rules, recent_turns, tool_observations)candidates = rank(retrieved_chunks + repo_slices + long_doc_sections)fill(candidates, until budget)mark(dropped_sections, reason="over_budget_or_low_score")
The purpose of partitioning is to separate “must be seen” from “can be sampled,” rather than applying an average truncation.
Token Compression Is a Lossy Process
Token compression uses fewer representations to carry longer history. Common methods include hierarchical summarization, block-level merging, dropping low-importance tokens, and normalizing repeated logs or boilerplate code. It complements sparse attention: the former reduces the amount of information entering the model, while the latter reduces computation on information that has already entered.
Compression must treat different information types differently.
- Compressible: repeated build logs, long dependency lists with no differences, and intermediate reasoning that has ended and whose conclusions have been settled.
- Preserve verbatim: numbers, identifiers, interface contracts, permission boundaries, conditions explicitly rejected by the user, and unverified errors.
- Preserve structure: heading hierarchy, function boundaries, table headers, chronological order, and causal relationships between tool calls.
A practical approach is two-level memory. Hot memory stores recent interactions and the original text of unfinished subtasks. Cold memory stores short summaries with provenance and records the location of the original text. When verification is needed, the corresponding segment can be pulled back into the hot area. This prevents compression from becoming an irreversible “forgetting of evidence.” Summaries should retain traceable pointers, such as document identifiers, line ranges, or tool-call indices; otherwise, it becomes impossible to audit why the model reached a conclusion.
High-Performance and Lightweight Routes
Offering both a high-performance version and a lightweight version within the same capability family matches real traffic patterns. Complex planning, cross-file modification, and multi-step verification are suited to the high-performance route. Classification, rewriting, simple completion, and formatting are suited to the lightweight route. Lightweight does not mean “good enough after reducing intelligence”; it should achieve quality close to the high-performance route on simple tasks while providing clearly better latency and cost.
Routing should not depend only on the user’s plan. It should look at task signals: whether the context contains multiple code units, whether a tool loop is required, whether mathematical or logical proofs appear, and whether the history already contains failed retries. Simple rules are often more explainable than black-box routing. For example: single-turn, no tools, and context below a threshold go to the lightweight route; test failures, cross-module modification, or a user request for strict reasoning escalate to the high-performance route. Escalation should carry the compressed task state so that two models do not each maintain a separate history.
It is also not advisable to use the high-performance model for the entire run by default. Many steps in an agent involve reading files, listing directories, and applying templates; these steps are sufficient with a lightweight model, leaving the budget for planning and final integration. Conversely, forcing difficult problems to remain on a lightweight model leads to repeated retries, increasing total cost and latency.
Context Discipline in Agent Scenarios
For models aimed at coding and complex tasks, the weakness is often not single-shot completion but multi-step execution: plan drift, repeatedly reading the same file, ignoring test output, and continuing to modify code based on wrong assumptions. A long window alleviates “not fitting,” but amplifies “too much noise.”
It is recommended to divide the context of an agent task into fixed slots: goal and acceptance criteria, environment facts, verified conclusions, todos, recent observations, and candidate patches. Slots have limits; when exceeded, update conclusions first and then discard raw observations. In this way, a million-token window is a safety margin, not a default to be filled.
Evaluation should also expand from static questions to process metrics: task success rate, number of invalid tool calls, repeated-read rate, test pass rate after a single modification, and human takeover points. World knowledge, math and science reasoning, and competition-style multi-step derivation can be evaluated separately. Knowledge questions test coverage and refusal behavior; reasoning questions test whether steps are verifiable, not only the final number. Do not replace the regression set for your own business with a single leaderboard score.
Adapting to the coding ecosystem is essentially about making the model familiar with common task loops: reading structure, locating modification points, making small edits, running checks, and rolling back or continuing based on failure information. What is adapted is the workflow and prompt constraints, not binding to a specific client. Prompts should specify tool input and output formats, which paths are forbidden to modify, and that failures must first cite observations before taking action.
Interfaces, Reasoning Effort, and Release Governance
When exposing conversational capabilities externally, compatibility with the team’s existing calling patterns is more important than inventing a completely new message format. A common approach is to unify the message list, roles, tool descriptions, and streaming increments, then map internally to different models. The reasoning process can be separated from the final answer: show a short conclusion to the user and retain a necessary reasoning summary for auditing. Reasoning effort is suitable as an explicit tier, such as low, medium, or high, corresponding to different search widths or maximum thinking budgets, rather than an unobservable implicit switch.
Tiers need to be designed together with timeouts and costs. High-intensity reasoning increases time to first token and total token count, so there must be an upper limit. After a timeout, return verified partial results or a clear failure rather than continuing indefinitely.
Model upgrades also bring changes in names and default behavior. Sound governance is to keep new and old names coexisting for a clear window; automatically map old names to the semantically closest new mode; indicate the actual executed version in response metadata; document mapping rules in change notes; and stop old names only after the window ends. Callers should use regression sets to compare key tasks before and after mapping, rather than assuming that a “stronger model” monotonically improves all prompts. Prompts, temperature, tool modes, and stop conditions should all be included in the same regression set, avoiding comparisons based only on bare question answering.
An Executable Rollout Order
- Measure first. Analyze the length distribution of real requests, cache hit rates, prefill time, and failure types to confirm whether a million-token window is a requirement or an exception.
- Partition next. Allocate budgets for rules, recent conversation, tool observations, and retrieved chunks, and record reasons for dropping content.
- Then compress. Summarize only content that is reconstructible or low-risk. Keep identifiers and negative conditions verbatim.
- Route by difficulty. Use lightweight models for routine steps and high-performance models for planning, verification, and cross-module modification.
- Accept with process metrics. In addition to accuracy, track retries, repeated reads, and human takeovers.
- Finally, handle version governance. Put alias mapping, parallel periods, and regression sets in place before switching the default model.
The value of million-token context lies in enabling the system to see sufficiently long evidence when necessary. Its broad availability depends on sparse computation, lossy but traceable compression, and routing based on task payment. Once these three things become default engineering capabilities, long context will no longer be a special case limited to a few high-configuration environments.
