Million-Token Context and Long-Horizon Agents: Engineering Practices

    This article examines the engineering work required to use million-token context windows and build long-horizon agents. It explains the difference between context window length, effective context length, and task length; shows how to manage context budgets with pinned information, recency, summaries, and prefix reuse; and outlines state-machine design for stable agent execution. It also discusses throughput and cost controls, evaluation strategies, and an implementation checklist for production systems.

    Introduction

    A recent model upgrade event illustrates why these issues matter. In late October, a model vendor released a new series of models on the scale of 3 trillion parameters. The models support a million-token context window, focus on long-horizon professional tasks such as code generation, 3D content creation, and financial research, and include a high-speed version that increases output throughput by roughly 2–3× while maintaining the level of intelligence. According to the vendor’s own tests, the models are already close to the strongest closed-source models available at the time in code, agent, and knowledge-related evaluations.

    Apart from the specific product, the useful signal for developers is that three long-standing engineering questions have returned to the center of the stage: how to use extremely long contexts, how to make long-horizon agents converge reliably, and how to control latency and cost without sacrificing quality. This article breaks these down one by one.

    1. Context window length, effective context length, and task length are not the same thing

    One of the most common engineering mistakes is to assume that “the model supports a million tokens” means “I can send a million tokens into the model.” These three concepts need to be separated strictly:

    • Context window length: the maximum number of tokens a single inference call can accept. This is a hard limit.
    • Effective context length: the range within that window where the model can still reliably locate and use information. Public “needle in a haystack” style tests often show that as input grows, recall for information in the middle of the input drops noticeably. This is commonly referred to as middle information forgetting.
    • Task length: the metric that actually matters to the business, meaning the total number of input and output tokens needed for a task from start to convergence.

    The conclusion is straightforward: treating window length as effective context length is a typical case of overengineering. A more reasonable approach is to treat the long window as a capacity budget, not a default fill target.

    2. Context budget management: treat limited attention as a scarce resource

    At the engineering level, it is better to implement an explicit budget allocator than to rely on the model to “handle it.” There are three core principles: pin critical information, evict items by recency and relevance, and always reserve space for output.

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class Budget:
    4. window: int # Model context window
    5. reserved_output: int # Reserve output so input does not exhaust it
    6. system: int = 2000 # System prompt and tool definitions
    7. def for_input(self) -> int:
    8. return self.window - self.reserved_output - self.system
    9. def select_context(items, budget: Budget, recent_k: int = 6):
    10. """
    11. items: Candidate chunks ordered chronologically. pin=True marks goals, constraints, and key conclusions.
    12. """
    13. limit = budget.for_input()
    14. pinned = [i for i in items if i.pin] # Goals, acceptance criteria, and confirmed conclusions
    15. recent = items[-recent_k:] # Recent interactions, preserving order
    16. middle = [i for i in items if not i.pin and i not in recent]
    17. # Sort middle chunks by relevance and pack them greedily
    18. middle.sort(key=lambda i: i.score, reverse=True)
    19. kept, used = list(pinned) + list(recent), sum(estimate(i) for i in pinned + recent)
    20. for item in middle:
    21. cost = estimate(item)
    22. if used + cost <= limit:
    23. kept.append(item)
    24. used += cost
    25. else:
    26. break
    27. kept.sort(key=lambda i: i.ts) # Restore chronological order to avoid logical breaks
    28. return kept

    With this mechanism in place, two additional techniques can often be added in practice. First, combine a sliding window with layered summaries, compressing evicted history into structured summaries—such as decisions, completed actions, unfinished items, and failure reasons—and injecting them back into the context. Second, use prefix reuse by placing stable system prompts and tool definitions at the front, so that the inference side can hit key-value caches across turns. In long sessions, this is often one of the most cost-effective optimizations.

    3. Long-horizon agents: stability comes from state management, not longer context

    The root cause of long-horizon task failures is rarely “the model cannot remember.” More often, it is state drift: the model gradually moves away from the initial goal, repeats steps that have already been completed, or repeatedly retries failed branches. The corresponding engineering solution is to model the agent explicitly as a state machine rather than an infinitely long conversation.

    1. state = {
    2. "goal": goal, # Immutable; injected every turn
    3. "plan": plan_steps, # Task decomposition result
    4. "done": [], # Completed subgoals and artifact paths
    5. "artifacts": {}, # Files, intermediate results, external system identifiers
    6. "failures": [], # Failed actions and error summaries to prevent repeating mistakes
    7. }
    8. while not is_finished(state) and budget.turn_left():
    9. ctx = select_context(build_items(state, history), budget)
    10. action = llm.plan(ctx) # Output structured actions, not natural language
    11. if action.kind == "tool_call" and action in state["failures"]:
    12. action = llm.replan(ctx, reason="Duplicate action; please choose a different path") # Deduplicate actions and prevent loops
    13. result = execute(action, timeout=action.timeout)
    14. state["artifacts"].update(result.artifacts)
    15. state["failures"].append(action) if result.failed else state["done"].append(action)
    16. if result.failed and exceeds_retry_budget(state):
    17. break # Exit explicitly and report to a human instead of silently looping

    Several constraints have proven effective and are worth including in any specification for long-horizon agents:

    1. Inject the goal and acceptance criteria every turn. This is extremely cheap, but it can significantly reduce goal drift.
    2. Persist tool return results to storage and only pass back summaries and paths. This avoids overwhelming the context with large raw objects at once. If needed, the full result can be retrieved later by path.
    3. Record failed actions in a blacklist. Combine this with a retry limit and a total step limit so that failures are predictable and observable.
    4. Require human confirmation at critical nodes. This is especially important for irreversible operations such as writing to a production database, releasing a product, deleting data, or transferring external funds. This belongs to the product responsibility boundary and should not be left to the model’s self-judgment.
    5. Maintain full observability. Log the input summary, action, latency, token consumption, and exit reason for every step, connect them to monitoring and alerting, and set thresholds based on task success rate and average number of steps.

    For scenarios such as 3D content generation and financial research, where the outputs are naturally large files, artifacts should be stored uniformly in object storage. The agent context should keep only metadata, versions, and checksums. Message flows between tasks should be decoupled through message queues, isolating long-running tasks from interactive sessions so that they do not degrade each other’s latency.

    4. Throughput and cost: why “same intelligence, twice the speed” is feasible

    A high-speed version is not technically mysterious. It usually relies on a set of mature inference optimizations rather than reducing model capability:

    • Speculative decoding: use a smaller model or draft head to predict multiple tokens, then have the larger model verify them in parallel, reducing serial decoding steps.
    • Prefix caching and key-value cache reuse: cache stable prefixes such as system prompts, tool definitions, and code repository context.
    • Continuous batching and better scheduling: improve utilization of GPU memory and compute, spreading the cost of each request.
    • Quantization and sparsification: compress weights and activations within an acceptable quality-loss range.
    • Constrained decoding for structured output: use constrained decoding for tool calls to reduce invalid tokens and retries.

    For the cost model, it is important to separate two types of bills. The first is input-side cost. In long-context scenarios, this often dominates total spending, so retrieval augmentation is usually cheaper than stuffing everything into the prompt. The second is output-side cost, which is directly related to throughput and latency. The correct engineering approach is to set a latency budget and a maximum cost per task for each business scenario, then choose the appropriate model tier, rather than using the strongest and slowest configuration globally. In self-hosted deployments, container platforms can be used for elastic scaling, adding inference replicas based on queue length, while a unified logging and monitoring system can support cost accounting and capacity planning.

    5. Evaluation: do not trust a single leaderboard; build your own regression suite

    Vendor self-tests can only serve as a reference. What truly determines whether a model can go live is internal evaluation. A recommended suite should include four layers:

    1. Long-context effectiveness: do not only test “finding a needle.” Also test multiple needles, cross-section reasoning, and questions that require synthesizing three or more source materials. Break down results by position—beginning, middle, and end—to expose middle-section degradation.
    2. Code capability: focus mainly on multi-file changes in real repositories. Measure compile pass rate, unit test pass rate, and regression defects, rather than only the correctness of single-function generation.
    3. Agent long-horizon capability: use a fixed task set and a fixed step limit. Track completion rate, average number of steps, token consumption, and number of human interventions.
    4. Knowledge and domain expertise: use domain experts to write questions, use two-person annotation, and arbitrate disputed items to prevent evaluation set contamination from training data.

    Every model upgrade or parameter adjustment should run a full regression suite. Store the results by scenario so that deciding whether a new version is worth switching to becomes a data-backed judgment rather than intuition.

    6. Implementation checklist

    • Does each task type have a context budget, output reservation, and compression strategy?
    • Have you implemented pinned information, sliding windows, and summary reinjection?
    • Do long-horizon tasks have an explicit state machine, failure blacklist, step limits, and retry limits?
    • Are there human confirmation gates for irreversible operations?
    • Are artifacts externalized to object storage, with only references kept in the context?
    • Is there a latency and cost budget per scenario, with model tier selection based on those budgets?
    • Is there a reproducible internal evaluation set and an upgrade regression process?
    • Do logs, metrics, and alerts cover the entire pipeline down to the single-step level?

    In one sentence: ultra-long context and long-horizon agents expand the upper bound of capability, but actual effectiveness is still determined by “unsexy” engineering details such as context governance, state management, and observability. Keep the budget under control, keep the state clear, catch failures, and calculate costs explicitly, and each model capability upgrade can genuinely translate into business metrics.