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 0 only 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:

    1. docker run --rm --memory=2g --memory-swap=2g --cpus=2 \
    2. -v "$(pwd)/workspace:/work" -w /work agent-eval-image \
    3. 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:

    1. Have a human produce a reference solution for the same task and verify that it passes the acceptance script.
    2. Run the reference solution three to five times in the target environment. Record runtime, peak memory, and retry counts for each run.
    3. Multiply the maximum observed value for each metric by 1.5 to 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.
    4. Validate the thresholds on at least two different tasks. They should leave sufficient headroom for reference solutions while rejecting clearly failing solutions.
    5. 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_args as an argument list, such as ["python", "agent_runner.py"], rather than a concatenated shell command. The script does not use shell=True, avoiding shell command injection.
    • Prepare an independent acceptance script, such as acceptance_tests.py.

    The complete code follows:

    1. import subprocess
    2. import sys
    3. import time
    4. import psutil
    5. def _signal_quietly(p, action):
    6. try:
    7. getattr(p, action)()
    8. except psutil.NoSuchProcess:
    9. pass
    10. class AgentTaskEvaluator:
    11. def __init__(self, task_args, time_limit=600, mem_limit_mb=2048,
    12. log_path="agent_run.log", poll_interval=1.0):
    13. if not isinstance(task_args, (list, tuple)) or not task_args:
    14. raise ValueError("task_args must be a non-empty list")
    15. self.task_args = list(task_args)
    16. self.time_limit = time_limit
    17. self.mem_limit_mb = mem_limit_mb
    18. self.log_path = log_path
    19. self.poll_interval = poll_interval
    20. self.execution_log = []
    21. self.peak_mem_mb = 0.0
    22. self.elapsed = 0.0
    23. self.exit_code = None
    24. self.stopped_reason = None
    25. def _record(self, message):
    26. self.execution_log.append(message)
    27. def _tree_memory_mb(self, pid):
    28. total = 0
    29. try:
    30. root = psutil.Process(pid)
    31. for item in [root] + root.children(recursive=True):
    32. try:
    33. total += item.memory_info().rss
    34. except psutil.NoSuchProcess:
    35. continue
    36. except psutil.NoSuchProcess:
    37. return 0.0
    38. return total / (1024 * 1024)
    39. def _stop(self, proc, reason):
    40. self.stopped_reason = reason
    41. self._record(reason)
    42. try:
    43. children = psutil.Process(proc.pid).children(recursive=True)
    44. except psutil.NoSuchProcess:
    45. children = []
    46. for child in children:
    47. _signal_quietly(child, "terminate")
    48. proc.terminate()
    49. _, alive = psutil.wait_procs(children, timeout=10)
    50. for child in alive:
    51. _signal_quietly(child, "kill")
    52. try:
    53. proc.wait(timeout=10)
    54. except subprocess.TimeoutExpired:
    55. proc.kill()
    56. proc.wait()
    57. self._record("Process tree terminated")
    58. def run(self):
    59. start = time.monotonic()
    60. with open(self.log_path, "w", encoding="utf-8") as log_file:
    61. proc = subprocess.Popen(
    62. self.task_args,
    63. stdout=log_file,
    64. stderr=subprocess.STDOUT,
    65. )
    66. self._record(f"Started process pid={proc.pid}")
    67. while True:
    68. ret = proc.poll()
    69. self.elapsed = time.monotonic() - start
    70. mem = self._tree_memory_mb(proc.pid)
    71. self.peak_mem_mb = max(self.peak_mem_mb, mem)
    72. if ret is not None:
    73. self.exit_code = ret
    74. break
    75. if self.elapsed > self.time_limit:
    76. self._stop(
    77. proc,
    78. f"Timeout: {self.elapsed:.0f}s, limit {self.time_limit}s",
    79. )
    80. self.exit_code = proc.returncode
    81. break
    82. if mem > self.mem_limit_mb:
    83. self._stop(
    84. proc,
    85. f"Memory exceeded: {mem:.0f}MB, limit {self.mem_limit_mb}MB",
    86. )
    87. self.exit_code = proc.returncode
    88. break
    89. time.sleep(self.poll_interval)
    90. return self.summary()
    91. def summary(self):
    92. return {
    93. "agent_exit_code": self.exit_code,
    94. "elapsed_s": round(self.elapsed, 2),
    95. "peak_mem_mb": round(self.peak_mem_mb, 1),
    96. "stopped_reason": self.stopped_reason,
    97. "log_path": self.log_path,
    98. }
    99. def evaluate(self, acceptance_args, acceptance_timeout=120):
    100. summary = self.run()
    101. if self.stopped_reason is not None:
    102. summary["task_passed"] = False
    103. return summary
    104. try:
    105. result = subprocess.run(
    106. acceptance_args,
    107. capture_output=True,
    108. text=True,
    109. timeout=acceptance_timeout,
    110. )
    111. except subprocess.TimeoutExpired:
    112. summary["task_passed"] = False
    113. summary["acceptance_output"] = "Acceptance script timed out"
    114. return summary
    115. summary["acceptance_exit_code"] = result.returncode
    116. summary["task_passed"] = result.returncode == 0
    117. summary["acceptance_output"] = (result.stdout + result.stderr)[-2000:]
    118. return summary
    119. if __name__ == "__main__":
    120. evaluator = AgentTaskEvaluator(
    121. task_args=["python", "agent_runner.py", "--task", "build_rest_api_service"],
    122. time_limit=600,
    123. mem_limit_mb=2048,
    124. log_path="agent_run.log",
    125. )
    126. result = evaluator.evaluate(
    127. acceptance_args=["python", "acceptance_tests.py", "--task", "build_rest_api_service"],
    128. )
    129. for key, value in result.items():
    130. print(f"{key}: {value}")
    131. 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.