Engineering Practices for Long-Horizon Tasks and Multi-Agent Collaboration

    This article covers how to design LLM systems for long-horizon tasks that run for hours, involve many steps, and require several agents. It explains the core concepts, a four-layer architecture, task decomposition and parallel scheduling, state persistence and resumption, context governance, security and permission boundaries, cost control, error handling, and quality acceptance criteria.

    1. Background: From Single-Turn Q&A to Long-Horizon Tasks

    Large language model applications are moving from single-turn question answering to long-horizon task execution. Typical scenarios include refactoring code across multiple repositories, fixing defects in batches, generating and running tests, and completing data cleaning and report generation. These tasks share common traits. They involve many steps, long dependency chains, and many intermediate artifacts. A single request cannot complete them, so they must be systematically decomposed, scheduled, and verified.

    Engineering teams usually face three kinds of challenges:

    • Duration: A task may run for hours or longer. During that time, it can encounter network interruptions, process restarts, and API rate limits.
    • Scale: A single execution unit has a limited context window. Complex tasks require multiple execution units that divide the work.
    • Controllability: Automated execution can modify code and call external services. Permissions must be restricted, the process must be logged, and changes must be reversible.

    This article groups these challenges into four design dimensions: task orchestration, state management, context governance, and security and cost.

    2. Core Concepts

    Understanding the boundaries of the following concepts is a prerequisite for designing a multi-agent system.

    • Long-horizon task: A task that requires multi-step reasoning and repeated tool calls, and that takes a long time to complete.
    • Agent: A program unit that uses a large language model as its decision core. It can read its environment, call tools, and adjust its actions based on feedback.
    • Orchestrator: The higher-level control unit that decomposes tasks, assigns subtasks, and aggregates results.
    • Sub-agent: An execution unit that handles one clearly defined subtask. It has its own context and tool permissions.
    • Shared state: The task progress, intermediate artifacts, and decision records that all participants read and write.

    The orchestrator should not decide implementation details on behalf of sub-agents. Sub-agents should not directly modify the outputs of other sub-agents. Clear boundaries make the system easier to debug and audit.

    3. Layered Architecture Design

    A four-layer structure is recommended:

    1. Access layer: Receives task descriptions and performs parameter validation and permission checks.
    2. Orchestration layer: Builds a task graph (DAG) and determines dependencies and degree of parallelism.
    3. Execution layer: Sub-agents run in isolated sandboxes and produce structured results.
    4. Storage and observability layer: Persists state, logs, and artifacts, and provides monitoring and alerting.

    The benefit of this layering is that each layer can scale independently. When the execution layer lacks compute, you can add worker processes horizontally without changing the orchestration layer.

    4. Task Decomposition and Parallel Scheduling

    The quality of task decomposition directly determines how well a multi-agent system performs. Follow three principles when decomposing tasks:

    • Clear boundaries: The input, output, and acceptance criteria of each subtask must be explicit.
    • Minimal dependencies: Reduce data coupling between subtasks so that more of them can run at the same time.
    • Appropriate granularity: Splitting too finely increases scheduling and communication overhead. Splitting too coarsely makes it hard for a single execution unit to finish its work.

    The following illustrative code shows how to run subtasks in batches based on their dependencies:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class SubTask:
    4. task_id: str
    5. description: str
    6. depends_on: list[str] = field(default_factory=list)
    7. status: str = "pending" # pending / running / done / failed
    8. def ready_tasks(tasks: dict[str, SubTask]) -> list[SubTask]:
    9. """Return all subtasks whose dependencies are complete and that can run immediately."""
    10. done = {t.task_id for t in tasks.values() if t.status == "done"}
    11. return [
    12. t for t in tasks.values()
    13. if t.status == "pending" and all(d in done for d in t.depends_on)
    14. ]
    15. def run_scheduler(tasks: dict[str, SubTask], max_parallel: int, execute) -> None:
    16. while True:
    17. batch = ready_tasks(tasks)[:max_parallel]
    18. if not batch:
    19. break
    20. for task in batch:
    21. task.status = "running"
    22. outcomes = execute_in_parallel(batch, execute) # Implemented by a thread pool or process pool
    23. for task, ok in zip(batch, outcomes):
    24. task.status = "done" if ok else "failed"

    This code has one behavior to note. When a subtask fails, its downstream tasks remain pending. When scheduling ends, the system should list these blocked tasks separately and hand them to a retry policy or a human reviewer. It should not skip them silently.

    5. State Persistence and Resumption

    Long-running tasks will inevitably be interrupted by process failures. The solution is to write every state change to persistent storage instead of keeping it only in memory.

    Key practices include:

    • Write each subtask’s result to disk immediately after it completes. Record its input hash, output location, and timestamp.
    • Use transactions or optimistic locking for state updates. This prevents concurrent writes from overwriting each other’s results.
    • On recovery, read the saved state, skip completed tasks, and rerun only tasks that were running or failed.
    • Ensure idempotency: running the same subtask again should produce a consistent result. For file writes, write to a temporary file first, then replace the target file through an atomic rename.

    State can live in a general-purpose relational database or key-value store. Large artifacts are better suited to object storage, with the database storing only the artifact reference paths.

    6. Context Governance

    Each sub-agent’s context window is a limited resource. Unchecked accumulation of message history raises call costs, dilutes key information, and slows responses. Common governance methods include the following.

    1. Keep task instructions lean: Inject only the specifications, interface definitions, and constraints relevant to the current subtask.
    2. Summarize results: Sub-agents return structured summaries to the orchestrator, not their full reasoning or intermediate output.
    3. Use external memory: Write long documents, build logs, and test output to storage. Retrieve fragments by keyword or path when needed.
    4. Compress in stages: When a session exceeds a length threshold, have the model generate a stage summary that replaces older messages. The summary must keep key decisions, the list of modified files, and unresolved issues.

    Sample-check compression output on a regular schedule. If a summary drops a constraint, later subtasks may drift from the goal. Problems like this often surface only during acceptance.

    7. Security and Permission Boundaries

    Automated execution creates real side effects, so risk governance should happen early in the design.

    • Least privilege: Each sub-agent receives only the tools and path access it needs to complete its task.
    • Sandbox isolation: Code execution and network access run in restricted environments. Production credentials are off limits.
    • Approval for sensitive operations: Actions such as deleting data, publishing releases, and changing access permissions require human confirmation.
    • Credential management: Inject keys through environment variables or a key management service. Never write them into code, prompts, or logs.
    • Separate data from instructions: Text in web pages, files, and tool output is data, and the system must not execute it as instructions. External content may contain text designed to manipulate the agent, so the workflow must distinguish user instructions from external content.

    8. Cost and Quota Control

    Parallel execution multiplies the number of model calls, so cost control must be designed in advance.

    • Budget limits: Set a maximum number of calls, a maximum token usage, and a maximum runtime for each task. When a limit is exceeded, stop the task and output a status report.
    • Model tiering: Use more capable models for task planning and result review. Use lighter models for simple steps such as format conversion and text extraction.
    • Caching: Cache retrieval results and static analysis results for identical inputs to avoid repeated computation.

    When deploying on cloud platforms such as Baidu AI Cloud, you can build the system from general-purpose infrastructure services. A container platform runs the execution layer, a message queue carries task events, and object storage holds artifacts. Log services and monitoring with alerting track execution status. Choose tools based on your team’s existing technology stack and operations capability.

    9. Reliability and Error Handling

    • Retry: For transient errors such as network timeouts and rate limits, use exponential backoff with a maximum retry count.
    • Circuit breaking: When the same type of error occurs repeatedly, pause scheduling to keep errors from spreading across parallel tasks.
    • Degradation: When an external service lacks throughput, automatically reduce concurrency and postpone non-critical tasks.
    • Timeouts: Set an independent timeout for each subtask. When a timeout occurs, keep the logs and intermediate state so the failure can be reviewed.

    10. Quality Evaluation and Acceptance

    Automated output needs measurable acceptance criteria. At minimum, cover the following four items:

    • Compilation and static checks pass.
    • Unit tests and integration tests pass, and coverage meets the threshold agreed on by the team.
    • The scope of changes matches the task description, with no unrelated files modified.
    • Key decisions are recorded so that humans can review them.