Long Context and Long-Horizon Agents: Engineering Post-Training for Trillion-Parameter Models

    A recent trillion-parameter flagship model reflects a broader shift in large-model competition: from answering questions to completing tasks. This article walks through the engineering that makes long-horizon agents practical, along the model-infrastructure-serving chain. It covers why million-token context is a managed engineering resource rather than unlimited memory, how reinforcement learning with verifiable rewards scales across hundreds of domains, and the three infrastructure pillars—sandboxing, a reliable Harness, and observability—that keep multi-hour tasks from failing midway. It also explains the inference optimizations behind "high-speed" tiers, how prompt-side cache pricing can dominate long-task costs, and how to evaluate and deploy long-horizon agents responsibly. Readers will find concrete code sketches, a layered reference architecture, a cost-estimation walkthrough, and a set of common pitfalls to avoid.

    Introduction: The Race Is Shifting from Answering Questions to Completing Tasks

    A leading Chinese model vendor recently released a new trillion-parameter flagship. It supports million-token context and focuses on strengthening code, long-horizon agents, financial research, and 3D content generation. The vendor also introduced a high-speed output tier and a managed agent service, and plans to open the full model weights. According to public data, the model reaches or approaches the level of the strongest closed-source models of the same period on code, agent, and knowledge evaluations.

    The most notable aspect of this release is not the parameter count, but the direction. Compared with the previous generation, the most significant change is a large increase in post-training compute, with reinforcement learning spanning hundreds of downstream domains. The model is further trained to act as an “executor” that can work continuously in real environments for hours or even days.

    Two practical demands drive this:

    • On one hand, tasks such as repository-level refactoring, multi-round research reports, and cross-system data analysis naturally span tens of minutes to several hours.
    • On the other hand, a single task requires repeatedly reading code, executing commands, calling tools, checking results, and self-correcting. The context easily exceeds 100K tokens, and in extreme cases approaches the million-token scale.

    This poses new questions for engineering teams: how to evaluate a model’s long-horizon capability, how to build a reliable agent runtime, and how to keep per-task cost under control. This article follows the model-infrastructure-serving chain to break down the engineering behind such capabilities and offers practical, actionable recommendations.

    1. Capability Foundation: Million-Token Context and Scaled Reinforcement Learning

    1.1 Long Context Is Both the Prerequisite for Long-Horizon Agents and an Engineering Burden

    Long-horizon tasks work by holding, within the context at the same time, the requirements document, prior conversation, code and logs returned by tools, intermediate conclusions, and a to-do list. When context capacity is insufficient, the model can only keep “forgetting” or truncating early information, so long tasks tend to suffer from inconsistency, repeated execution, and drifting off-target.

    But “supports a million tokens” does not mean “every token within a million is equally usable.” Long context involves at least three layers of engineering:

    1. Computational complexity: Standard self-attention scales quadratically with sequence length. When the sequence grows from 32K to 128K, the compute grows roughly 16x, and memory and compute pressure rise sharply.
    2. Position-encoding extrapolation: The position range during training is usually far smaller than the inference length, so extrapolation strategies such as length interpolation and position-encoding scaling are needed, together with continued training on long text to keep things stable.
    3. Information retrieval quality: As context grows, the model’s recall of middle-of-context information tends to degrade (the industry’s so-called “lost in the middle” phenomenon), so long-document tasks need structured organization and retrieval.

    For this reason, long context is better understood as an engineering resource than as unconditional memory capacity. In practice, it is usually paired with the following mechanisms:

    • Rolling summaries: Compress older history into conclusions, decisions, and to-dos.
    • External memory: Write complete records to object storage or a file system, and retrieve and backfill on demand.
    • Context budget management: Set a token quota for each category of information, and trigger compression once the quota is exceeded.
    1. CONTEXT_BUDGET = 200_000 # in tokens; reserve room for output within the model window
    2. def manage_context(history, summary, memory_store, tools):
    3. used = count_tokens(history)
    4. if used > CONTEXT_BUDGET * 0.8:
    5. # compress early turns, keeping key conclusions and decisions
    6. summary = update_summary(summary, history[: len(history) // 2])
    7. history = history[len(history) // 2:]
    8. # retrieve from external memory per current subtask; backfill only the most relevant snippets
    9. for subtask in extract_subtasks(history):
    10. docs = memory_store.search(subtask, top_k=5)
    11. history.append(f"[background for {subtask}]\n" + join(docs))
    12. # tool returns also count toward the budget, so logs/stack traces don't drown out what matters
    13. tools = [t for t in tools if count_tokens(t.description) < 2_000]
    14. return history, summary, tools

    1.2 Scaling Reinforcement Learning: From General Preference Alignment to Verifiable Rewards Across Hundreds of Domains

    In the previous generation, reinforcement learning was used mostly for general preference alignment, aiming to make answers more useful and better aligned with human preferences. But tasks such as code, terminal operations, financial-data computation, and 3D asset generation share one thing in common: their results can be judged automatically by a program. For example:

    • Code: unit-test pass rate, whether compilation succeeds.
    • Data analysis: whether conclusions match the ground truth.
    • 3D creation: geometric validity, similarity between the rendered result and a reference image.

    This shifts reinforcement learning away from being limited to “human preference scoring” toward large-scale, automatically verifiable environmental interaction—an RLVR (Reinforcement Learning with Verifiable Rewards) approach. Mainstream training frameworks usually provide two implementations at once: PPO with a trainable reward model, and GRPO, which does not require a separate value model. The table below compares supervised fine-tuning and reinforcement learning on long-horizon capability:

    Dimension Supervised Fine-Tuning (SFT) Scaled Reinforcement Learning (RL)
    Data source Human-annotated or filtered gold answers Trajectories the model explores in real environments
    Feedback Imitating the “correct answer” Verifiable results returned by the environment (pass/fail/score)
    Capability profile Strong at format, style, and basic instruction following Strong at multi-step planning, trial-and-error recovery, and policy selection
    Main bottleneck High-quality long-horizon trajectories are scarce and expensive Environment throughput, reward reliability, and training stability
    1. # skeleton of large-scale reinforcement learning (illustrative)
    2. def train_step(prompts, policy, env_pool, reward_fn):
    3. groups = []
    4. for prompt in prompts: # covers hundreds of domains, tasks graded by difficulty
    5. # sample multiple trajectories for the same task to form a comparable reward group
    6. env = env_pool.acquire(prompt.domain)
    7. try:
    8. trajs = [rollout(policy, prompt, env)] * 0 or \
    9. [rollout(policy, prompt, env) for _ in range(K)]
    10. scores = [reward_fn(env, traj) for traj in trajs]
    11. groups.append(normalize_group(scores)) # in-group normalization to reduce scale differences across tasks
    12. finally:
    13. env.release() # return the environment so its state stays clean and reusable
    14. # use in-group relative advantage as the learning signal, no separate value network needed
    15. loss = policy_loss(groups) + beta * kl_penalty(policy, ref_policy)
    16. optimize(policy, loss)

    This pipeline looks simple, but at scale the real bottleneck is not the algorithm—it is the following three systems-engineering challenges:

    • Sampling throughput: Most of reinforcement learning’s compute is spent on rollout sampling. The training cluster and the inference cluster must synchronize weights at each step, so the industry commonly splits them into separate resource pools and overlaps them asynchronously as much as possible, to avoid the training side idling while waiting for samples.
    • Reward reliability: A wrong or “gameable” reward will directly teach the model bad behavior. Test scripts, judging logic, and evaluation data all need quality control and must be strictly isolated from training data, to prevent the model from scoring high by memorizing answers rather than genuinely solving problems.
    • Data and difficulty mix: When covering hundreds of domains, task difficulty and reward scales vary widely. Layered curriculum design, dynamic sampling, and in-group reward normalization are needed; otherwise the model tends to overfit on easy tasks or become unstable during training on hard ones.

    The increase in post-training compute is the key generational difference precisely because it determines how many real, verifiable task trajectories the model is exposed to. The actual results confirm this: on terminal-programming benchmarks, a certain new-generation trillion-parameter model performs in the same range as the strongest closed-source models of the same period. This is both a payoff of the post-training paradigm and a reflection of engineering quality.

    2. Infrastructure: The Three Pillars Behind Long-Horizon Agents

    No matter how strong the model is, if the runtime is unreliable, long tasks will still fail midway. A task lasting several hours can be lost to an environment crash, a context overflow, or a tool malfunction. Infrastructure therefore needs to focus on solving three types of problems:

    1. Sandbox isolation: Code and commands executed by the model must run in a restricted environment.
    2. Harness management: Sessions, context, tool calls, and recovery mechanisms need to be managed centrally.
    3. Observability and evaluation: Every step must leave a trace, and evaluation conclusions must be reproducible.

    2.1 Sandbox: Drawing a Safety Boundary for Model Execution

    An agent executing code is essentially running untrusted programs, so a sandbox must at least satisfy the following requirements:

    • Controllable networking: External access is disabled by default; only necessary addresses such as the model API and package sources are allowed on demand.
    • Resource limits: CPU, memory, disk, and execution time are capped to prevent runaway loops from overwhelming the host.
    • Rebuildable state: Started from a fixed-version container image and destroyed after the task, to avoid leftover data contaminating the next run.
    • Behavior tracing: Commands, file changes, and network requests are fully logged for auditing and traceability.
    1. # sandbox execution policy (illustrative; the concrete implementation depends on the container or runtime chosen)
    2. SANDBOX_POLICY = {
    3. "image": "task-runner:2026.10", # pinned image version to guarantee reproducibility
    4. "cpu_limit": "4", # prevents a runaway task from saturating the host
    5. "memory_limit": "16Gi",
    6. "timeout_seconds": 1800, # maximum execution time for a single task
    7. "network": "deny_all", # offline by default
    8. "allow_list": ["model-api.internal"], # only the model service address is allowed
    9. "read_only_rootfs": False, # keep writable when the working directory needs writes
    10. "user": "sandbox", # non-root user to reduce privilege-escalation risk
    11. "workspace": "/workspace", # isolated working directory, destroyed when the task ends
    12. }

    A sandbox must also answer a key question: who decides what to execute? A mature approach follows the principle of least privilege and divides permissions into three tiers:

    • Auto-execute: Low-risk operations such as reading files, running tests, and code checks can be allowed directly.
    • Human confirmation: Medium-risk operations such as installing dependencies, committing code, and changing configuration require user authorization.
    • Prohibited: High-risk operations such as accessing credentials, deleting data, and sending information externally are blocked outright.

    For coding agents, the sandbox is not just a safety boundary but also a training environment. Reinforcement learning needs a large number of “environment instances,” so the sandbox’s startup speed and reclamation efficiency directly determine sampling throughput.

    2.2 Harness: Letting Sessions Resume Across Days

    A Harness is the runtime shell that wraps the model, responsible for session management, context organization, tool calls, error recovery, and cost control. A typical Harness main loop looks like this:

    1. def run_long_task(task, harness):
    2. session = harness.session(task)
    3. while not session.finished:
    4. if session.should_checkpoint():
    5. # persist session state to support crash recovery and cross-day resumption
    6. session.save(f"sessions/{session.id}.json")
    7. # organize context: system prompt + summary + recent history + retrieved material
    8. messages = session.build_context(max_tokens=CONTEXT_BUDGET)
    9. decision = harness.model(messages, tools=harness.tool_specs)
    10. if decision.tool_calls:
    11. results = [harness.execute(c, timeout=300, retries=2)
    12. for c in decision.tool_calls]
    13. # truncate and sanitize tool results before writing them back, to avoid noise and sensitive-info spread
    14. session.append(tool_results=sanitize(results))
    15. else:
    16. session.append(decision)
    17. if decision.task_done:
    18. session.finished = True
    19. session.save(f"sessions/{session.id}.json")
    20. return session.report()

    Beyond the main loop, a reliable Harness needs four supporting mechanisms:

    • Checkpoint resume: Periodically persist session state to shared storage so the process can recover quickly after a crash or during cross-day runs.
    • Budget control: Set limits on steps, tokens, and elapsed time; wrap up proactively as thresholds approach and output intermediate results.
    • Tool idempotency: Introduce idempotency keys for write operations such as create and submit, so that retries after a network timeout do not double-submit.
    • Permission tiers: Manage tool calls according to the three-tier permissions described earlier.

    For this reason, many vendors package the Harness itself as a managed agent service: users only submit a task definition, and the platform handles environment scheduling, session persistence, and long-running execution. For enterprises that want to bring agent capabilities online quickly, this is more realistic than building their own scheduling and sandbox system. The tradeoff to weigh is control versus cost: managed services remove the operational burden, but the platform’s capability boundaries, data-isolation approach, and billing rules should be assessed in advance.

    3. Inference Serving: The Engineering Logic Behind High-Speed Tiers and Cache Pricing

    3.1 The Inference Optimizations Behind the High-Speed Tier

    A “high-speed tier” for the same model capability is usually not a different model, but targeted optimization at the serving layer. Output speed depends on per-step decoding latency and batching strategy. Common techniques include:

    • Speculative decoding: A lightweight draft model or a multi-token prediction module guesses several tokens first, which the main model then verifies in a single parallel pass. When the acceptance rate is high, this significantly reduces the number of decoding steps.
    • Prefill/decode disaggregation: Prefill (processing the input) and decode (generating token by token) have very different compute profiles, so serving them with differently configured instance pools reduces interference from long inputs on short requests.
    • KV cache optimization: Techniques such as paged management and quantization reduce memory footprint, thereby increasing the concurrent batch size.
    • Request scheduling: Streaming output returns the first token as quickly as possible, while continuous batching improves overall throughput.

    3.2 Reading Cache Pricing: The Key to Saving Money on Long-Context Tasks

    The input price for this kind of model is usually split into two tiers:

    • Cache-hit price: Typically on the order of one-tenth of the miss price.
    • Cache-miss price: The full input price.

    Output price is noticeably higher than input price. Intuitively: inputs can be cached and reused, whereas outputs must be generated token by token in real time.

    The cache hit rate depends on two conditions:

    1. The request prefix is exactly identical.
    2. The cache has not yet expired.

    So when constructing prompts, follow these principles:

    • Stable content first: Put the system prompt, tool definitions, and fixed background material at the very front.
    • Dynamic content last: Place changing content such as timestamps, random IDs, and user input toward the end.
    • Avoid implicit changes: Do not concatenate the current time or a random number into the system prompt, or the prefix will differ on every request and the cache will never hit.
    • Keep templates stable: In batch tasks, fix the template and parameter order to prevent unrelated changes from invalidating the cache.
    1. def build_prompt(system_prompt, tools, history, user_input):
    2. # prefix part: stays constant across requests, used to hit the cache
    3. stable_prefix = system_prompt + serialize_tools(tools)
    4. # variable part: placed at the end, doesn't affect the prefix cache
    5. variable_part = render_history(history) + user_input
    6. return stable_prefix + variable_part

    3.3 Cost and Quality: Using the Strong Model Where It Counts

    The high-speed tier has the same capability as the standard tier and is usually priced at about twice the standard version. The choice should distinguish between scenarios:

    • Interactive coding assistant: Needs fast feedback, and the experience gain from the high-speed tier is often worth the premium.
    • Batch offline tasks: Such as large-scale code review or report generation, where throughput comes first and the standard tier is more economical.
    • Long-horizon agent: A single task consumes a large number of tokens, so the input cache hit rate has the greatest impact on total cost.

    A useful estimation approach works as follows. Suppose for a long-horizon task the input and output token counts are roughly equal, the cache hit rate is about 50%, and the cache-hit input price is about one-tenth of the miss price. The total cost then works out to roughly 1.1x the standard input price. If the high-speed tier is priced at about 2x the standard version, the high-speed approach costs about 2.2x—around 1.8x the standard approach. Combining the magnitude of the speed gain with the business value lets you judge whether the premium is justified.

    Beyond model calls, long-horizon tasks also incur infrastructure costs for compute, storage, logging, and monitoring. For example, general-purpose products such as Baidu AI Cloud’s cloud servers, object storage, and logging with monitoring and alerting can serve as building blocks for self-hosted sandboxes and runtime environments. If you use a managed agent service, also watch for the following costs:

    • Whether billing is based on runtime.
    • Whether failed-task retries are billed again.

    4. A Practical Guide: Evaluating and Deploying Long-Horizon Agents

    4.1 Evaluation Framework: Judge the Environment First, Then the Model

    When evaluating long-horizon agents, it is best to split the results into two parts:

    • Environment success rate: The success ratio of infrastructure steps such as sandbox creation, dependency installation, tool availability, and network reachability.
    • Model task success rate: Given a healthy environment, the proportion of tasks the model completes, such as the test pass rate for code tasks.

    Many conclusions that “the model is bad” actually trace back to environment problems. Recommended practices are as follows:

    1. Layered attribution: Classify failures first into environment, tools, context, or strategy, then optimize item by item.
    2. Multiple independent runs: Long tasks are stochastic, so a single success has no statistical meaning.
    3. Multiple metrics in parallel: Record task success rate, average steps, average token consumption, and end-to-end latency together.

    4.2 Minimum Viable Architecture: Layered Rollout

    For most teams, there is no need to build the complete infrastructure all at once. Progress can proceed in three stages:

    1. Single agent + sandbox: Focus on one high-frequency scenario, such as code fixing or data-report generation.
    2. Harness + session persistence: Support interruption recovery, budget control, and permission tiers.
    3. Multi-agent collaboration: Split roles such as planning, execution, and review, passing tasks and results through a message queue.

    The layered architecture is illustrated below:

    1. ┌──────────────┐ submit task ┌────────────────────┐ tool calls ┌──────────────┐
    2. │ Access layer │ ──────────────▶ │ Agent orchestration│ ─────────────▶ │ Exec sandbox │
    3. │ API/console │ ◀────────────── │ (Harness) │ ◀───────────── │ code/shell/ │
    4. └──────────────┘ results └─────────┬──────────┘ results │ browser tools│
    5. │ └──────────────┘
    6. ▼
    7. ┌──────────────────┐
    8. │ Model serving │ long-context inference
    9. │ │ + cache prefix + inference acceleration
    10. └──────────────────┘

    4.3 A Typical Scenario: The Code Agent

    Code tasks are the most direct test of long-horizon capability. A typical flow includes: reading the repository structure and requirements, locating the relevant modules, writing a patch, running tests, and iteratively fixing based on failure logs until the tests pass.

    1. def code_agent_task(repo_url, issue, sandbox):
    2. repo = sandbox.clone(repo_url)
    3. context = repo.summary() # repository structure summary to control context size
    4. for step in range(MAX_STEPS):
    5. plan = model.plan(issue, context, repo.relevant_files(issue))
    6. patch = model.write_patch(plan, repo.read(plan.files))
    7. if not sandbox.apply(patch):
    8. context += sandbox.last_error() # patch failed to apply; continue with the error in context
    9. continue
    10. report = sandbox.run_tests(plan.target_tests)
    11. if report.passed:
    12. return {"status": "done", "steps": step + 1}
    13. context += report.failures[:5] # backfill only key failure info to prevent context bloat
    14. return {"status": "failed", "steps": MAX_STEPS}

    This flow embodies several key points of long-horizon agents:

    • Context focus: Only read files relevant to the issue, and keep only the key information from failure logs.
    • Closed-loop verification: Use test results as the sole success criterion, avoiding “looks done.”
    • Budget constraints: Set a maximum step count to prevent infinite loops.

    5. Common Pitfalls and Key Takeaways

    In practice, the following pitfalls are worth watching out for:

    • Context maximalism: Believing longer context is always better, while overlooking the decline in mid-context recall and the linear growth in cost.
    • Parameter maximalism: Treating parameter count as the only capability metric, while ignoring post-training quality and tool-call reliability.
    • Uncontrolled execution: Running the model in an uncontrolled environment without sandboxes or permission tiers.
    • Ignoring cache-friendliness: Putting dynamic content into the system prompt, so the cache can never hit.

    Overall, the significance of the new-generation trillion-parameter model is that it shifts the post-training focus from “answering questions” to “completing tasks.” Million-token context provides the capacity to carry long tasks; verifiable reinforcement learning scaled across hundreds of domains teaches the model to plan, trial-and-error, and recover in real environments; and sandboxes, the Harness, and managed services turn these capabilities into a product experience that runs stably.

    For developers, evaluating this kind of model should adhere to three points:

    1. Run multiple, reproducible evaluations in a real task environment.
    2. Attribute failures to the specific link—environment, tools, context, or strategy.
    3. Control cost with cache-friendly prompt design and a sensible combination of model tiers.

    Only in this way can “model capability” truly be turned into “deliverable productivity.”