Long-Horizon Agent Evaluation in Resource-Constrained Environments
A practical guide to evaluating long-horizon AI agents on development machines, CI nodes, and containers. Learn how to design verifiable tasks, calibrate resource limits, diagnose failures, and use a Python monitoring script with independent acceptance tests.
Large models and long context windows enable agents to tackle extended tasks across files and documents. Yet on resource-constrained development machines, CI nodes, or containers, the same agent often performs worse than it does in a sandbox. To determine whether an agent can actually deliver, evaluate it in the target environment against explicit pass criteria.
1. What to Evaluate in a Long-Horizon Agent
A long-horizon agent typically performs three functions: breaking down the task and planning its execution, maintaining intermediate state, and interacting with the environment through tools. Failures can originate in any of these areas, so evaluate them separately. Looking only at the final output does not reveal what went wrong.
| Area | What to observe | Relevant metrics |
|---|---|---|
| Planning | Whether the plan covers all requirements and defines verifiable subtasks | Task completion rate; checkpoint results at each stage |
| State management | Whether the agent retains the original constraints and remains consistent across context switches | Constraint assertions in acceptance tests; consistency across reruns |
| Environment interaction | Whether tool calls are correct and the agent can interpret errors and recover | Repeated failures with the same error signature; dependency failure handling; runtime; peak memory |
For example, if an agent produces runnable code but forgets the required interface format, the problem is state management. If the code cannot run because a dependency is missing, the problem is environment interaction. These failures require different fixes and should be recorded separately.
2. What Resource Constraints Reveal
Sandboxes often provide ample memory, stable networking, and preinstalled dependencies. Real execution environments commonly introduce the following conditions. Turn each condition into a testable evaluation item.
- Insufficient memory: The operating system kills a process while compiling a large project. Check whether the agent can interpret the exit code and logs, identify memory pressure, and retry with lower parallelism or cleared caches.
- Full disk: Temporary file writes fail, but the error may not explicitly identify disk capacity as the cause. Check whether the agent can diagnose the issue from logs, free space, and rerun the operation.
- Network timeouts: An external API remains unresponsive, extending execution beyond the expected duration. Check whether the agent sets timeouts and abandons the request or switches approaches after a bounded number of attempts.
- Dependency version conflicts: Installation reports success, but execution fails later. Check whether the agent identifies the conflict and provides an alternative or a clear error.
All of these behaviors can be verified through logs, making them suitable evaluation criteria.
3. Three Principles for Task Design
Define the outcome, not the implementation
Specify a verifiable deliverable, such as: “Implement user registration and login endpoints that pass the ten provided API tests.”
Leave the language and framework open so the agent can choose its implementation. Give every task an independent acceptance script, and use its result as the sole criterion for delivery correctness. The script should meet these requirements:
- It is maintained by the evaluator, stored separately from the agent’s working directory, and cannot be modified by the agent.
- Its assertions cover every deliverable constraint, including endpoint paths, response fields, and error codes.
- It exits with code
0only when all assertions pass; otherwise, it returns a nonzero exit code.
Validate each stage
Divide execution into coding, testing, deployment, and troubleshooting, with a checkpoint at each stage. When a stage fails, record where the failure occurred. Over enough runs, this reveals which types of steps are most difficult for the agent.
Keep dependencies controlled and reproducible
Use local mock services or recorded responses for external APIs. Package system dependencies in a version-pinned image. Start each run from a clean environment to isolate the agent’s behavior from environmental variation.
4. Metrics, Thresholds, and Pass Criteria
The thresholds below are examples. Before using them in a formal evaluation, calibrate them against a human-produced reference solution using the procedure in Section 5.
| Metric | Measurement method | Example passing threshold | Failure condition |
|---|---|---|---|
| Task completion | Exit code from the independent acceptance script | All assertions pass | Any assertion fails |
| Runtime per run | From process launch to completion, including internal retries | No more than 600 seconds | Terminate the process tree after timeout |
| Peak process memory | Sum of process-tree RSS, sampled once per second | No more than 2,048 MB | Terminate the process tree after exceeding the limit |
| Repeated errors of the same type | Number of failures sharing the same error signature in logs | No more than 3 | More than 3 indicates failure to recover autonomously |
| Dependency installation failure handling | Installation log inspection | An alternative approach or an explicit error | Silent failure or repetition of the same command |
| Result reproducibility | Rerun in a clean environment | Two runs produce consistent results | Results differ |
Sampling with psutil once per second can miss brief memory spikes. Summing RSS also double-counts shared memory, so the reported value is often an overestimate. It is useful as a conservative indicator, but it does not replace system-level enforcement.
For formal evaluation, configure a memory limit in a container or cgroup so the kernel enforces it. With Docker, you can launch the task as follows:
docker run --rm --memory=2g --memory-swap=2g --cpus=2 \-v "$(pwd)/workspace:/work" -w /work agent-eval-image \python agent_runner.py --task build_rest_api_service
Setting --memory-swap equal to --memory disables swap for the container, preventing swapping from stretching execution time excessively after memory pressure occurs.
5. Calibrating Thresholds
Do not choose thresholds by intuition alone. Use the following procedure:
- Have a human produce a reference solution for the same task and verify that it passes the acceptance script.
- Run the reference solution three to five times in the target environment. Record runtime, peak memory, and retry counts for each run.
- Multiply the maximum observed value for each metric by
1.5to establish a limit. For example, if the longest reference run takes 300 seconds, set the runtime limit to 450 seconds. With more samples, you can use the 90th percentile plus a margin instead. - Validate the thresholds on at least two different tasks. They should leave sufficient headroom for reference solutions while rejecting clearly failing solutions.
- Record the hardware configuration, image version, and sampling interval used for calibration. Recalibrate when the hardware or image changes.
6. Common Failures and Troubleshooting
Troubleshoot in this order: inspect the exit code, read roughly the last 200 log lines, search for relevant keywords, check resource usage, and finally rerun in a clean image.
Out-of-memory failures
Logs may contain MemoryError or Killed. Exit code 137 indicates termination by SIGKILL, often caused by the kernel’s OOM killer.
Reduce parallelism—for example, change make -j8 to make -j2—and clear intermediate caches before retrying. If recovery requires more than three retries, classify the run as unable to recover autonomously.
Dependency installation failures
Common log messages include No matching distribution, Could not find a version, and ResolutionImpossible.
Check the versions pinned in the image, then try one alternative version or a local wheel. If that still fails, report a clear error rather than repeating the same installation command.
Network timeouts
Logs may contain Read timed out, Connection timed out, or Temporary failure in name resolution.
Set request timeouts and retry with exponential backoff, allowing at most three retries. After that, switch to a local mock service.
Silent failures
The process exits with code 0, but required artifacts are missing, or the acceptance script fails despite the absence of logged errors. There is no fixed keyword for this failure mode.
Treat the acceptance script as authoritative. Check whether the expected artifact files exist, mark the run as failed, and record the stage at which the failure occurred.
7. Monitoring Script: Requirements and Code
Before running the script:
- Use Python 3.8 or later and install the dependency with
pip install "psutil>=5.9". - Ensure the log directory is writable.
- Prefer running inside a container with the system-level resource limits described in Section 4.
- Pass
task_argsas an argument list, such as["python", "agent_runner.py"], rather than a concatenated shell command. The script does not useshell=True, avoiding shell command injection. - Prepare an independent acceptance script, such as
acceptance_tests.py.
The complete code follows:
import subprocessimport sysimport timeimport psutildef _signal_quietly(p, action):try:getattr(p, action)()except psutil.NoSuchProcess:passclass AgentTaskEvaluator:def __init__(self, task_args, time_limit=600, mem_limit_mb=2048,log_path="agent_run.log", poll_interval=1.0):if not isinstance(task_args, (list, tuple)) or not task_args:raise ValueError("task_args must be a non-empty list")self.task_args = list(task_args)self.time_limit = time_limitself.mem_limit_mb = mem_limit_mbself.log_path = log_pathself.poll_interval = poll_intervalself.execution_log = []self.peak_mem_mb = 0.0self.elapsed = 0.0self.exit_code = Noneself.stopped_reason = Nonedef _record(self, message):self.execution_log.append(message)def _tree_memory_mb(self, pid):total = 0try:root = psutil.Process(pid)for item in [root] + root.children(recursive=True):try:total += item.memory_info().rssexcept psutil.NoSuchProcess:continueexcept psutil.NoSuchProcess:return 0.0return total / (1024 * 1024)def _stop(self, proc, reason):self.stopped_reason = reasonself._record(reason)try:children = psutil.Process(proc.pid).children(recursive=True)except psutil.NoSuchProcess:children = []for child in children:_signal_quietly(child, "terminate")proc.terminate()_, alive = psutil.wait_procs(children, timeout=10)for child in alive:_signal_quietly(child, "kill")try:proc.wait(timeout=10)except subprocess.TimeoutExpired:proc.kill()proc.wait()self._record("Process tree terminated")def run(self):start = time.monotonic()with open(self.log_path, "w", encoding="utf-8") as log_file:proc = subprocess.Popen(self.task_args,stdout=log_file,stderr=subprocess.STDOUT,)self._record(f"Started process pid={proc.pid}")while True:ret = proc.poll()self.elapsed = time.monotonic() - startmem = self._tree_memory_mb(proc.pid)self.peak_mem_mb = max(self.peak_mem_mb, mem)if ret is not None:self.exit_code = retbreakif self.elapsed > self.time_limit:self._stop(proc,f"Timeout: {self.elapsed:.0f}s, limit {self.time_limit}s",)self.exit_code = proc.returncodebreakif mem > self.mem_limit_mb:self._stop(proc,f"Memory exceeded: {mem:.0f}MB, limit {self.mem_limit_mb}MB",)self.exit_code = proc.returncodebreaktime.sleep(self.poll_interval)return self.summary()def summary(self):return {"agent_exit_code": self.exit_code,"elapsed_s": round(self.elapsed, 2),"peak_mem_mb": round(self.peak_mem_mb, 1),"stopped_reason": self.stopped_reason,"log_path": self.log_path,}def evaluate(self, acceptance_args, acceptance_timeout=120):summary = self.run()if self.stopped_reason is not None:summary["task_passed"] = Falsereturn summarytry:result = subprocess.run(acceptance_args,capture_output=True,text=True,timeout=acceptance_timeout,)except subprocess.TimeoutExpired:summary["task_passed"] = Falsesummary["acceptance_output"] = "Acceptance script timed out"return summarysummary["acceptance_exit_code"] = result.returncodesummary["task_passed"] = result.returncode == 0summary["acceptance_output"] = (result.stdout + result.stderr)[-2000:]return summaryif __name__ == "__main__":evaluator = AgentTaskEvaluator(task_args=["python", "agent_runner.py", "--task", "build_rest_api_service"],time_limit=600,mem_limit_mb=2048,log_path="agent_run.log",)result = evaluator.evaluate(acceptance_args=["python", "acceptance_tests.py", "--task", "build_rest_api_service"],)for key, value in result.items():print(f"{key}: {value}")sys.exit(0 if result["task_passed"] else 1)
An agent_exit_code of 0 means only that the agent process exited normally—not that the task succeeded. Use task_passed for the final verdict: a run stopped for exceeding a resource limit fails, and otherwise success depends on the independent acceptance script’s result.
