Multi-Agent Collaboration and Long-Running Execution: An Engineering Implementation Guide

    This guide walks engineering teams through the problems they hit in long-horizon coding, multi-agent collaboration, and long-running autonomous execution, in the order those problems usually appear. It covers context state management, task dispatch and result merging, budget and human takeover rules, rate limiting, heterogeneous compute benchmarking, cost accounting, and a pre-launch checklist. Each section gives steps, parameter guidance, code skeletons, and checks. All numeric values are starting points that should be tuned against your own workloads and load tests.

    Long-horizon coding, multi-agent collaboration, and long-running autonomous execution are entering everyday development. A model can work continuously for hours, but its context can exceed the window, subtasks can conflict with each other, traffic can spike suddenly, and costs can exceed the budget. This guide follows the order in which engineering teams encounter these problems. For each stage, it provides steps, parameter definitions, code skeletons, and checks. All numbers in this guide are starting points. Adjust them based on your own task data and load test results. Do not treat them as performance conclusions.

    1. How to Maintain Context State in Long-Horizon Coding

    A model cannot retain the full history of a project for its entire lifecycle. Teams usually combine three approaches.

    Approach Method Use cases Main cost Risk of loss Checklist item
    Sliding window Keep only the most recent conversation turns and code changes Local edits and single-file debugging Almost no extra storage cost Early constraints get pushed out of the window Confirm that constraints outside the window are recorded in a summary or stored in the original text
    Summary compression Organize design decisions, interface agreements, and open issues into a structured summary Cross-module, multi-day tasks Requires an extra model call to generate the summary Boundary conditions and numerical details get lost Confirm that key constraints are kept in their original wording, and that a person spot-checks the summaries
    External retrieval Store complete code versions, error logs, and dependency information in external storage, and recall them by keyword or vector search Version history lookup and large codebases Storage and index maintenance Semantically similar fragments with different logic get recalled by mistake Confirm that recalled results match the current constraints

    Each approach has limits. Summaries lose detail, so numeric ranges, permission rules, and security constraints for interfaces should be kept in their original wording. Vector retrieval depends on embedding quality. Two code fragments that are semantically close can behave in completely different ways. KV cache compression is an inference-side optimization. It mainly reduces GPU memory usage and inference latency. It does not store business state, and it cannot guarantee that the model remembers why a particular change was made. Your team must keep business state in its own storage.

    Record each code change as a structured entry that includes:

    • The files modified, and the functions or interfaces involved
    • The purpose of the change, linked to a requirement or defect ID
    • Related error messages and test results
    • The rollback method, including the identifier of the last verified version

    When a build fails, the system should read the most recent change records first, then decide which version to roll back to. The model should not guess the reason for a change from memory.

    Use the following conditions to trigger summarization. These are starting values:

    1. Trigger a summary when context usage exceeds 70% of the model’s window.
    2. Trigger a summary at each milestone, for example when all tests for a module pass.
    3. When a problem remains unresolved after several conversation rounds, write the problem and the approaches already tried into a summary, and mark it “unresolved.”

    Rollback rule: If the build fails twice in a row, or the number of passing unit tests falls below that of the last verified version, roll back to the most recent record marked “verified,” and then reassign the task.

    Human review: When the vector recall results do not match the key terms in the current constraints, escalate the case to a person for confirmation. Each week, a team can spot-check a batch of recall results and calculate the rate of incorrect recalls. If that rate keeps rising, review the embedding model and the text chunking method.

    2. How to Dispatch and Aggregate Results in Multi-Agent Tasks

    Multi-agent collaboration follows five basic steps:

    1. Task decomposition: Split the goal into subtasks that are independent of each other. Specify the input, output, and acceptance criteria for each subtask.
    2. Dispatch: Assign each subtask to a suitable agent based on capability or current load.
    3. Timeouts and retries: Set a timeout for every attempt. After a failure, back off exponentially. Mark the task as failed once it exceeds the maximum number of attempts.
    4. Deduplication and merging: Keep only one result for each idempotency key, then merge the results in decomposition order.
    5. Conflict arbitration: If two agents modify the same file or the same interface, do not overwrite automatically. Hand the conflict to an arbitration agent or a person.

    The skeleton below uses only the Python standard library and requires Python 3.9 or later. It demonstrates deduplication, concurrency limits, timeouts, retries, budget checks, and result merging. Log fields include task_id, attempt, timeout, and cost to make troubleshooting easier.

    1. import asyncio
    2. import logging
    3. import random
    4. from dataclasses import dataclass
    5. from typing import Awaitable, Callable, Dict, List, Tuple
    6. MAX_RETRY = 3 # Maximum number of attempts per subtask, including the first attempt
    7. MAX_INFLIGHT = 8 # Maximum number of subtasks in flight at once; adjust based on downstream load test results
    8. TIMEOUT_S = 30.0 # Timeout in seconds for a single attempt; set based on the P95 of historical durations
    9. BUDGET = 5.0 # Cost limit for the whole batch (example value; the unit must match your cost metering)
    10. logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    11. log = logging.getLogger("orchestrator")
    12. @dataclass
    13. class SubTask:
    14. task_id: str # Idempotency key; if the same key is submitted again, the task runs only once
    15. payload: str
    16. attempt: int = 0
    17. Handler = Callable[[SubTask], Awaitable[Tuple[str, float]]] # Returns (result, cost of this call)
    18. async def run_one(task: SubTask, handler: Handler, sem: asyncio.Semaphore, state: dict) -> None:
    19. async with sem:
    20. while task.attempt < MAX_RETRY:
    21. if state["spent"] >= state["budget"]:
    22. log.error("budget_exceeded task_id=%s spent=%.4f", task.task_id, state["spent"])
    23. state["failed"].append(task.task_id)
    24. return
    25. task.attempt += 1
    26. try:
    27. output, cost = await asyncio.wait_for(handler(task), timeout=TIMEOUT_S)
    28. except asyncio.TimeoutError:
    29. log.warning("timeout task_id=%s attempt=%d timeout=%.1f",
    30. task.task_id, task.attempt, TIMEOUT_S)
    31. except Exception as exc:
    32. log.warning("error task_id=%s attempt=%d err=%r",
    33. task.task_id, task.attempt, exc)
    34. else:
    35. state["spent"] += cost
    36. state["results"][task.task_id] = output
    37. log.info("ok task_id=%s attempt=%d cost=%.4f", task.task_id, task.attempt, cost)
    38. return
    39. await asyncio.sleep(min(2 ** task.attempt, 8) * 0.05) # Exponential backoff; shortened in this example
    40. state["failed"].append(task.task_id)
    41. log.error("give_up task_id=%s attempts=%d", task.task_id, task.attempt)
    42. async def dispatch(tasks: List[SubTask], handler: Handler) -> dict:
    43. unique: Dict[str, SubTask] = {}
    44. for t in tasks:
    45. unique.setdefault(t.task_id, t) # Deduplicate: keep only the first task for each idempotency key
    46. state = {"spent": 0.0, "budget": BUDGET, "results": {}, "failed": []}
    47. sem = asyncio.Semaphore(MAX_INFLIGHT)
    48. await asyncio.gather(*(run_one(t, handler, sem, state) for t in unique.values()))
    49. return state
    50. async def fake_agent(task: SubTask) -> Tuple[str, float]:
    51. # Example handler: replace with an async function that calls your model or tool in production
    52. await asyncio.sleep(random.uniform(0.01, 0.05))
    53. if random.random() < 0.2:
    54. raise RuntimeError("simulated downstream error")
    55. return f"done:{task.payload}", 0.01
    56. async def main() -> None:
    57. tasks = [SubTask(task_id=f"job-{i % 5}", payload=f"part-{i}") for i in range(10)]
    58. state = await dispatch(tasks, fake_agent)
    59. print("succeeded:", len(state["results"]), "failed:", state["failed"],
    60. "spent:", round(state["spent"], 4))
    61. if __name__ == "__main__":
    62. asyncio.run(main())

    This skeleton suits a single process, a few dozen tasks at most, and a workload that can be rerun in full if it fails. Move to a message queue in these cases:

    • Subtasks must run across processes or machines.
    • Unfinished tasks must continue to run after a process restart.
    • A dead-letter queue is needed to hold tasks that fail repeatedly for manual handling.
    • Idempotency keys must be persisted, for example with a database unique index or Redis SET NX. An in-memory dictionary cannot be shared across multiple instances.
    • Timeouts and retries should be managed by a central scheduler, not by each worker separately.

    Do not skip conflict arbitration. When two subtasks write to the same file, keep both results and let an arbitration agent or a person choose between them. Do not let the result that finishes later overwrite the one that finished first.

    3. Long-Task Budgets and Human Takeover

    The cost and risk of long-running tasks accumulate over time. Set budget and takeover rules before the task starts.

    Parameter Meaning Starting value Basis for adjustment
    TIMEOUT_S Maximum duration of a single attempt P95 of historical durations Set separately for each task type
    MAX_RETRY Maximum number of attempts per subtask 3 Whether the error is retryable determines the count
    BUDGET Cost limit for the whole batch About 80% of the real budget Reserve room for the cost of tasks still in flight
    Same-error threshold Number of consecutive occurrences of the same error type 3 Recovery cost of the error
    Cost alert line Share of the limit at which an alert fires 80% Time needed for a person to respond to an alert

    The budget check runs before each attempt. In-flight tasks are counted only after they finish, so the actual spend can slightly exceed the limit. Set the limit below the real budget to leave a margin.

    Conditions that trigger human takeover:

    • Cost reaches the alert line: Pause new dispatches and notify the owner.
    • The same type of error recurs consecutively: Pause tasks of that type and preserve the logs.
    • Deleting data, publishing a release, changing permissions, or sending messages externally: A person must confirm first. The agent must not run these actions on its own.
    • Output fails acceptance criteria or conflicts with requirements: Hand it to a person for a decision.

    The takeover process has these steps: raise the alert, pause dispatch, keep the results of in-flight tasks, let a person decide, then resume, roll back, or terminate. Let tasks that are still running after the pause finish. This avoids leaving half-written state behind.

    4. Rate Limiting Under High Concurrency

    Rate limiting needs to control three things at once: the number of in-flight requests, the request rate per unit of time, and the length of the waiting queue.

    • Concurrency limit: Use a semaphore to cap the number of tasks running at the same time. Start at half of the downstream service’s documented limit. Then raise concurrency gradually, and record the error rate and P95 latency. Use the value just before the point where errors or latency start to climb.
    • Rate limit: For external APIs, use a token bucket to cap requests per second. A token bucket allows short bursts while keeping the long-term rate under the limit.
    • Backpressure: Set a maximum length for the waiting queue. When the queue is full, reject new tasks and return a clear error. Do not let requests pile up in memory without limit.

    When you receive an HTTP 429 response, read the Retry-After header first. If that header is missing, use exponential backoff with random jitter. This prevents multiple workers from retrying at the same moment.

    The following skeleton shows a token bucket. Create the instance inside a running event loop.

    1. import asyncio
    2. import time
    3. class TokenBucket:
    4. def __init__(self, rate: float, capacity: int):
    5. self.rate = rate # Number of tokens added per second
    6. self.capacity = capacity # Bucket size, which is the number of burst requests allowed
    7. self.tokens = float(capacity)
    8. self.updated = time.monotonic()
    9. self._lock = asyncio.Lock()
    10. async def acquire(self) -> None:
    11. async with self._lock:
    12. while True:
    13. now = time.monotonic()
    14. self.tokens = min(self.capacity,
    15. self.tokens + (now - self.updated) * self.rate)
    16. self.updated = now
    17. if self.tokens >= 1:
    18. self.tokens -= 1
    19. return
    20. await asyncio.sleep((1 - self.tokens) / self.rate)

    Record the source of every rate-limit parameter, such as the ID and date of the load test report. A number with no source should be treated as a temporary value, and you should replace it before launch.

    5. Heterogeneous Compute Benchmarking and Cost Accounting

    Teams often use several models, GPU types, or cloud instances at once. To compare them fairly, use one consistent test method.

    The test matrix covers model version, hardware type, batch size, and concurrency. Run every configuration on the same task set, fix the random seed and sampling temperature, and record the versions of drivers, frameworks, and dependencies. Without these controls, differences in results may come from the environment rather than the hardware.

    Metrics to record:

    • Time to first token: the time from sending the request to receiving the first output token.
    • End-to-end latency at P50 and P95.
    • Output tokens per second.
    • Error rate, including timeouts and 429 responses.
    • Cost per task.

    Calculate cost per task as follows:

    Cost per task = (input token cost + output token cost + tool call cost + cost of retries) ÷ number of successfully completed tasks

    Include the cost of failed attempts and retries in the numerator. If you count only the cost of successful requests, you underestimate the real cost, and your selection decision can be wrong.

    When you compare hardware, compare how many valid tasks each unit of cost produces, not only the unit price. An option with a low unit price but a high error rate may not be cheaper.

    Take cost data from billing statements or billing APIs, not from estimates based on unit prices. Record the exchange rates, unit prices, and billing rule versions in the test report, because they change over time.

    6. Pre-Launch Checklist

    Check item Pass criterion
    Context preservation Key constraints are recorded in their original wording; every code change has a structured record; the rollback steps have been run at least once
    Task dispatch and aggregation Each idempotency key runs only once; timeouts and retries have log fields; conflicts have clear arbitration rules
    Budget