Long-Context Agents for Long-Horizon Tasks: Practices and Pitfalls

    Long-context capabilities are often misunderstood as simply "the larger the window, the more stable the task." In reality, window capacity is just the entry ticket. The true determinants of success in long-horizon tasks are robust task state management, reliable context compaction and recovery, and engineered sub-task scheduling and result merging. This article explores the common pitfalls and actionable engineering designs for building long-context agents, covering the distinction between context types, hybrid orchestration architectures, process file management, compaction recovery design, and comprehensive observability strategies.

    Long-Context Agents for Long-Horizon Tasks: Practices and Pitfalls

    Long-context capabilities are often misunderstood as “the larger the window, the more stable the task.” In actual practice, window capacity is merely an entry ticket. What truly determines the success of long-horizon tasks is task state management, the ability to recover after context compaction, and the engineering maturity of sub-task scheduling and result merging. Any long-horizon task that runs long enough will inevitably span multiple context compactions. If the execution framework cannot correctly resume operations after compaction, even a massive window will lose state at critical nodes. This article focuses on general technical practices, discussing typical pitfalls and actionable designs for long-context agents in long-horizon tasks.

    1. Distinguish Three Types of “Context”

    Many user experience issues stem from conceptual confusion. At the very least, three layers must be distinguished:

    1. Model Window Capacity: The maximum number of tokens that can be accommodated in a single request.
    2. Effective Usable Context: The amount of information the model can stably utilize amidst noise, redundant tool outputs, and mixed historical decisions. This is typically smaller than the window capacity.
    3. Task Fact State: Task goals, plans, completed steps, artifact locations, failure records, and open questions. This should not exist solely within the conversation context.

    In common engineering practices, a context window in the 100k to 200k token range can generally maintain stable reasoning quality, but this does not mean context can be stacked infinitely. As history grows, tool output noise, repetitive descriptions, and outdated information dilute critical signals, forming “context pollution.” Therefore, the core of the long-context experience is not “whether it can fit,” but “whether it can maintain factual consistency after compaction, restarts, concurrency, and failure retries.”

    Practitioners have validated these concepts in an extreme long-horizon task involving approximately 147 million tokens. The conclusion was not to rely on a single ultra-long context to brute-force the process, but rather to break the long task into manageable units using process files, compaction recovery, and sub-agent scheduling. This experience is worth abstracting into a general methodology.

    2. Trade-offs: Single Context vs. Sub-Agent Scheduling

    Relying on a single context has its advantages: it provides global consistency, is simple to implement, and is suitable for short-chain, highly continuous reasoning tasks. However, its drawbacks include high cost, rapid noise accumulation, uncontrollable compaction loss, and difficulty in debugging after failures. Sub-agent scheduling isolates local tasks, reduces the main context burden, and supports parallelism and failure isolation. Its disadvantages are increased complexity in state synchronization, result contracts, and scheduling.

    A more robust approach is a hybrid architecture:

    • Main Agent: Responsible for goals, plans, the state machine, and final decisions, retaining only high-level summaries and key factual references.
    • Sub-agents: Handle isolated tasks such as local retrieval, code modification, data analysis, and validation. Their inputs and outputs must have strict contracts.
    • Process Files: Serve as the source of truth, saving the plan DAG, step states, artifact paths, decision records, and failure reasons.
    • Execution Orchestration Layer: Saves and restores snapshots before and after compaction, ensuring the system can locate “what to do next” after compaction.

    Do not treat sub-agents simply as “spawning a few more models.” Sub-agents without contracts will only create more inconsistencies.

    3. Process Files: The Source of Truth for Long-Horizon Tasks

    Process files should be written to versioned storage rather than just kept in memory or conversation history. It is recommended to include at least the following:

    1. {
    2. "task_id": "long-task-001",
    3. "goal": "Task goal",
    4. "plan": [{"step_id": "s1", "status": "done", "artifact": "path/to/out1"}],
    5. "decisions": [{"step_id": "s2", "reason": "Chose Plan A", "evidence": "path/to/log"}],
    6. "failures": [{"step_id": "s3", "error": "timeout", "retry": 2}],
    7. "open_questions": ["Items to be confirmed"],
    8. "compact_summary": "High-level summary after compaction",
    9. "updated_at": "Logical timestamp"
    10. }

    Key principle: Summaries can be compacted, but the source of truth cannot be lost. Append logs and save snapshots after every tool call, every step completion, and before/after compaction triggers. Snapshots must be verifiable and replayable, and sensitive information must be masked. For cloud deployments, you can use object storage for artifacts, log services for tracing, message queues to decouple sub-tasks, and container platforms to host executors. Focus on checking permissions, consistency, and lifecycle policies.

    4. Resuming After Compaction: Orchestration Layer Recovery Design

    Long-horizon tasks will inevitably trigger compaction; if they don’t, they aren’t truly long-horizon. The execution orchestration layer needs to provide compaction hooks and execute invariant validation upon recovery. The pseudocode is as follows:

    1. on_before_compact(task):
    2. snapshot = build_snapshot(task.state, artifacts, decisions)
    3. persist(snapshot)
    4. on_after_compact(task):
    5. state = load_latest_snapshot(task.id)
    6. summary = build_high_level_summary(state)
    7. assert state.goal and state.next_step
    8. assert artifacts_exist(state.completed_steps)
    9. return resume_loop(state, summary)
    10. resume_loop(state, summary):
    11. while not state.done:
    12. step = state.next_step
    13. if is_idempotent_done(step): mark_done(); continue
    14. result = execute_with_retry(step)
    15. persist_step_result(step, result)
    16. state = advance(state, result)

    The most common pitfall here is that after compaction, only a “natural language summary” is recovered, while step states and artifact references are lost. This leads to duplicate execution, overwriting of results, or skipped validations. Another pitfall is non-idempotent tool calls, which produce duplicate side effects upon retry. Solutions include: setting idempotency keys for each step, recording state before and after execution, deduplicating write operations, and routing failures to a human-in-the-loop queue.

    5. Sub-Agent Scheduling: Contracts First, Persist Results

    Sub-agent scheduling should adhere to the principles of “controllable task granularity, I/O contracts, intermediate artifacts persisted to disk, and failure isolation.” The main agent should not dump its entire history into a sub-agent. Instead, it should pass the goal, boundaries, input references, expected output format, and acceptance criteria. When returning results, the sub-agent should include conclusions, evidence references, artifact paths, open questions, and confidence levels. The main agent should only merge structured results, not blindly concatenate long texts.

    Parallelism must be limited. Excessive parallelism amplifies resource contention and state conflicts. For shared write operations, ensure consistency through locks, version numbers, or serial queues. A sub-agent failure should not crash the entire system; instead, the failure reason should be recorded, allowing the main agent to decide whether to retry, degrade, or trigger human intervention.

    6. Observability and Evaluation: Beyond Window Size

    Long-horizon tasks require observable metrics: task success rate, post-compaction recovery success rate, duplicate execution rate, artifact consistency rate, human intervention rate, context usage, token cost, end-to-end latency, and failure distribution. Logs should be replayable by task, step, sub-agent, and tool call. Evaluation sets should include fault injection scenarios such as forced compaction, breakpoint restarts, tool timeouts, artifact loss, and concurrency conflicts.

    Evaluating only “single-turn long-text Q&A” cannot prove long-horizon stability. A truly valuable evaluation is whether the system can recover from process files and correctly resume execution after forced compaction mid-task, restarting the executor, or inducing tool failures.

    7. Common Pitfalls Checklist

    1. Treating window capacity as memory, ignoring the source of truth.
    2. Keeping only summaries after compaction, losing step states and artifact references.
    3. Stuffing full tool outputs into the context, causing noise dilution.
    4. Write operations lacking idempotency keys, leading to duplicate side effects upon retry.
    5. Sub-agents lacking I/O contracts, making results unmergeable.
    6. Storing state only in memory, causing loss upon process restart.
    7. No breakpoint resume or human-in-the-loop mechanism.
    8. Process files lacking versioning, validation, and replayability.
    9. Excessive parallelism causing state conflicts.
    10. Focusing only on success rate, ignoring recovery success rate and duplicate execution rate.
    11. Ignoring permissions, data masking, and auditing.
    12. Using single-turn evaluation to replace long-horizon fault injection evaluation.

    8. Implementation Recommendations

    Start with small-scale long tasks and establish process files and a state machine. Next, integrate compaction hooks and recovery validation. Then, introduce sub-agent scheduling and result contracts. Finally, complete the setup with observability, fault injection, and cost control. Acceptance criteria should include: the ability to resume after compaction, resume after restart, retry without duplicate writes, traceable sub-agent results, and human intervention capabilities. Long context is not a shortcut to replace engineering state management; rather, it is an input condition that requires even stronger orchestration capabilities. By demoting “context” to working memory, promoting “process files” to the source of truth, and treating “compaction recovery” as a first-class capability, long-horizon tasks will successfully transition from demos to stable production environments.