Engineering Long-Running Tasks and Multi-Agent Collaboration

    This article breaks down why long-running AI agent tasks fail—context decay, error accumulation, serial bottlenecks, and missing verification—and maps each failure mode to a concrete engineering practice. It covers capability tiering across planner, executor, verifier, and coordinator roles, declarative dependency modeling for parallel orchestration, isolation and merge-gate strategies, layered verification contracts, tiered memory with checkpoints, and human-in-the-loop observability. A practical checklist and a list of common anti-patterns are included for teams building deliverable agent systems.

    1. The Real Problem: Finishing the Task, Not Writing the Code

    When you ask an agent to complete a real software engineering task, the bottleneck is rarely generating a single function body. Three harder problems usually block progress: understanding the existing project structure and its implicit conventions, decomposing a vague requirement into steps that can run in parallel and be verified, and diagnosing failures well enough to recover from them. Once a task stretches from minutes to hours or even days, its nature changes. Correctness of a single inference no longer determines success; stability of the workflow, consistency of state, and trustworthiness of verification do.

    Long-running task failures fall into four categories:

    1. Context decay: early constraints get diluted along a long chain, and the model gradually drifts from the original goal.
    2. Error accumulation: small per-step deviations compound over many steps until the final artifact is unusable.
    3. Serial bottlenecks: all sub-work is squeezed onto a single chain, so progress and throughput are capped by one execution flow.
    4. Missing verification: the agent produces answers that “look right” with no executable criteria for judging them.

    Each category maps to an engineering technique: tiered memory, checkpoint rollback, parallel orchestration, and a closed verification loop. The rest of this article covers each in turn.

    2. Capability Tiering: Put the Strongest Model Where Judgment Matters

    A common industry pattern is capability tiering: hand hard reasoning and planning to the most capable model, and mechanical edits to a lightweight model. The economics are straightforward—the most expensive reasoning capacity should be spent on judgment, not on typing.

    A workable role split looks like this:

    1. Planner : requirement clarification, task decomposition, dependency and risk identification -> strong reasoning model
    2. Executor : local code changes, test additions, documentation generation -> lightweight model
    3. Verifier : running tests, reviewing diffs, raising objections -> strong reasoning model
    4. Coordinator : dispatch, aggregation, conflict arbitration, progress tracking -> strong reasoning model

    The critical rule: the verifier and the planner must not be the same agent. Letting the doer grade its own work effectively removes independent review. Only when verification is a separate role do you get genuine adversarial checking.

    3. Parallel Orchestration: From a Single Chain to a Task Squad

    The structural weakness of the single-agent model is serialization: understanding requirements, dispatching, executing, aggregating, and reviewing all happen inside one context. For cross-module changes, that chain is both a performance bottleneck and a single point of failure.

    Parallelism depends on decomposability, and decomposition quality comes down to three judgments:

    • Granularity: too coarse limits parallelism; too fine makes coordination overhead exceed the gains.
    • Dependency clarity: subtasks with hard dependencies must run serially; fake parallelism only creates rework.
    • Boundary isolation: whether different agents can be assigned non-overlapping sets of files.

    Dependencies can be expressed declaratively so the orchestration layer can run topological sorting and scheduling:

    1. task: refactor_auth_module
    2. subtasks:
    3. - id: extract_token_service
    4. writes: ["src/auth/token.*"]
    5. depends_on: []
    6. - id: migrate_call_sites
    7. writes: ["src/api/**"]
    8. depends_on: ["extract_token_service"]
    9. - id: update_tests
    10. writes: ["tests/auth/**"]
    11. depends_on: ["extract_token_service"]
    12. - id: verify
    13. writes: []
    14. depends_on: ["migrate_call_sites", "update_tests"]

    The writes field is the core of conflict control: before scheduling, the orchestration layer checks whether write sets intersect. If they do, the task is downgraded to serial execution or routed through a merge queue. That is far cheaper than resolving conflicts after the fact.

    4. Isolation and Merging: Keeping Parallel Changes from Breaking Each Other

    When parallel agents share one working tree, the most common failures are overwriting edits and semantic conflicts. Three isolation strategies are standard:

    1. Separate working copies: each agent holds its own branch or directory and submits a diff when done.
    2. Write-set partitioning: write permissions are statically divided by module or directory, eliminating overlap by policy.
    3. Merge gate: every diff must pass unified verification before landing on the mainline; failures are rolled back rather than force-merged.

    The merge flow simplifies to:

    1. def merge_gate(branch_results, verify):
    2. merged = []
    3. for r in branch_results:
    4. if not r.has_diff():
    5. continue
    6. if not verify(r.diff): # unified verification gate
    7. return Rollback(r), "verify_failed"
    8. merged.append(r.diff)
    9. return apply_all(merged), "ok"

    The principle is “rollback-ready beats forward-only.” In long-running tasks, cleaning up one bad merge costs far more than one failed verification.

    5. Verification Loops: Making Results Decidable

    Trust in a long-running task comes from verification density, not model confidence. Executable verification layers, from weakest to strongest:

    • Static checks: types, formatting, lint rules; cheap and fast.
    • Unit tests: cover local behavior; run after every change.
    • Integration tests: validate contracts between modules; run at the merge gate.
    • End-to-end or artifact acceptance: build a runnable artifact and check real usability.

    For chart-heavy documents, engineering drawings, and scanned inputs, verification has to change accordingly. Text comparison is not enough; you need structured extraction followed by consistency checks—field completeness, numeric ranges, and whether cross-page references close. Acceptance criteria for such tasks should be written as executable assertions before work starts; otherwise “done” cannot be defined.

    A minimal verification contract:

    1. CONTRACT = {
    2. "must_pass": ["unit:auth", "lint", "build"],
    3. "metrics": {"coverage_delta": ">= -0.5"},
    4. "artifacts": ["dist/app.zip"],
    5. "on_fail": "rollback_and_report",
    6. }

    6. Context and Memory: Fighting Decay Over Long Chains

    A bigger context window is not the same as effective memory. A tiered memory structure is more reliable in practice:

    • Short-term: inputs and outputs of the current subtask, released when the subtask ends.
    • Mid-term: task lists, dependency graphs, decisions made and their rationale, shared across subtasks.
    • Long-term: project conventions, historical defect patterns, domain glossary, injected on demand via retrieval.

    Two supporting mechanisms matter. A decision log records why a change was made, so later agents do not overturn settled choices. Checkpoints freeze state after each subtask completes, so a failure rolls back to the most recent usable checkpoint instead of restarting from zero.

    1. checkpoint = {
    2. "subtask": "migrate_call_sites",
    3. "status": "partial",
    4. "completed_files": 12,
    5. "next_action": "resume_from_file_13"
    6. }

    7. Human Collaboration and Observability

    Parallel does not mean out of control. A usable collaboration interface needs at least three kinds of information: each agent’s current status and output diff, verification results with failure reasons, and conflict points that require human arbitration. Human intervention should be designed to change direction, not details; otherwise coordination costs eat the gains from parallelism.

    Observability should cover the task decomposition tree, scheduling timeline, per-step latency and resource consumption, verification pass rate, and rollback count. This data supports debugging and feeds back into tuning the decomposition strategy.

    On the cloud, general-purpose service categories are usually enough: container platforms host isolated execution environments, object storage holds artifacts and checkpoints, message queues handle task distribution and backpressure, and logging plus monitoring with alerting provide tracing and anomaly notification. For multi-region parallelism, state consistency and locality of data access also need consideration.

    8. Common Anti-Patterns

    • Fake parallelism: subtasks with hard dependencies forced into concurrency, producing more rework than gain.
    • Self-grading: execution and verification in the same agent, letting defects pass through to the deliverable.
    • No acceptance criteria: no executable assertions defined before the task starts, so completion cannot be judged.
    • No checkpoints: any failure means a full restart, and long-task cost spirals.
    • Over-decomposition: coordination and merge overhead exceed the time saved by parallelism.

    9. Implementation Checklist

    1. Write the task as a dependency graph with write sets first, then decide whether to parallelize.
    2. Predefine verification commands and artifact requirements for every subtask.
    3. Reserve strong reasoning models for planning, arbitration, and verification; push everything else to lightweight models.
    4. Require every merge to pass a unified gate; on failure, roll back and produce a readable report.
    5. Establish tiered memory and checkpoints to support resume-from-breakpoint execution.
    6. Collect scheduling and verification metrics, and use the data to iterate on decomposition granularity.

    The engineering maturity of a long-running agent is not determined by how impressive a single generation looks, but by whether failures can be detected early, located precisely, and recovered from cheaply. Splitting planning, execution, and verification across distinct roles, backed by isolation and gates, is the key step in turning a demo into a deliverable system. The same orchestration frameworks and engineering constraints apply to building agent applications and model engineering practices on Baidu AI Cloud.