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:
- Trigger a summary when context usage exceeds 70% of the model’s window.
- Trigger a summary at each milestone, for example when all tests for a module pass.
- 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:
- Task decomposition: Split the goal into subtasks that are independent of each other. Specify the input, output, and acceptance criteria for each subtask.
- Dispatch: Assign each subtask to a suitable agent based on capability or current load.
- 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.
- Deduplication and merging: Keep only one result for each idempotency key, then merge the results in decomposition order.
- 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.
import asyncioimport loggingimport randomfrom dataclasses import dataclassfrom typing import Awaitable, Callable, Dict, List, TupleMAX_RETRY = 3 # Maximum number of attempts per subtask, including the first attemptMAX_INFLIGHT = 8 # Maximum number of subtasks in flight at once; adjust based on downstream load test resultsTIMEOUT_S = 30.0 # Timeout in seconds for a single attempt; set based on the P95 of historical durationsBUDGET = 5.0 # Cost limit for the whole batch (example value; the unit must match your cost metering)logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("orchestrator")@dataclassclass SubTask:task_id: str # Idempotency key; if the same key is submitted again, the task runs only oncepayload: strattempt: int = 0Handler = Callable[[SubTask], Awaitable[Tuple[str, float]]] # Returns (result, cost of this call)async def run_one(task: SubTask, handler: Handler, sem: asyncio.Semaphore, state: dict) -> None:async with sem:while task.attempt < MAX_RETRY:if state["spent"] >= state["budget"]:log.error("budget_exceeded task_id=%s spent=%.4f", task.task_id, state["spent"])state["failed"].append(task.task_id)returntask.attempt += 1try:output, cost = await asyncio.wait_for(handler(task), timeout=TIMEOUT_S)except asyncio.TimeoutError:log.warning("timeout task_id=%s attempt=%d timeout=%.1f",task.task_id, task.attempt, TIMEOUT_S)except Exception as exc:log.warning("error task_id=%s attempt=%d err=%r",task.task_id, task.attempt, exc)else:state["spent"] += coststate["results"][task.task_id] = outputlog.info("ok task_id=%s attempt=%d cost=%.4f", task.task_id, task.attempt, cost)returnawait asyncio.sleep(min(2 ** task.attempt, 8) * 0.05) # Exponential backoff; shortened in this examplestate["failed"].append(task.task_id)log.error("give_up task_id=%s attempts=%d", task.task_id, task.attempt)async def dispatch(tasks: List[SubTask], handler: Handler) -> dict:unique: Dict[str, SubTask] = {}for t in tasks:unique.setdefault(t.task_id, t) # Deduplicate: keep only the first task for each idempotency keystate = {"spent": 0.0, "budget": BUDGET, "results": {}, "failed": []}sem = asyncio.Semaphore(MAX_INFLIGHT)await asyncio.gather(*(run_one(t, handler, sem, state) for t in unique.values()))return stateasync def fake_agent(task: SubTask) -> Tuple[str, float]:# Example handler: replace with an async function that calls your model or tool in productionawait asyncio.sleep(random.uniform(0.01, 0.05))if random.random() < 0.2:raise RuntimeError("simulated downstream error")return f"done:{task.payload}", 0.01async def main() -> None:tasks = [SubTask(task_id=f"job-{i % 5}", payload=f"part-{i}") for i in range(10)]state = await dispatch(tasks, fake_agent)print("succeeded:", len(state["results"]), "failed:", state["failed"],"spent:", round(state["spent"], 4))if __name__ == "__main__":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.
import asyncioimport timeclass TokenBucket:def __init__(self, rate: float, capacity: int):self.rate = rate # Number of tokens added per secondself.capacity = capacity # Bucket size, which is the number of burst requests allowedself.tokens = float(capacity)self.updated = time.monotonic()self._lock = asyncio.Lock()async def acquire(self) -> None:async with self._lock:while True:now = time.monotonic()self.tokens = min(self.capacity,self.tokens + (now - self.updated) * self.rate)self.updated = nowif self.tokens >= 1:self.tokens -= 1returnawait 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 |
