#3380·deepeval

Async `evaluate()` / `evals_iterator()` time out any batch longer than ~207s: gather timeout ignores `max_concurrent` queueing

Author: hardness1020Created Sep 27, 2026Updated Sep 27, 2026

What happens

On the async path, evaluate() and dataset.evals_iterator() create one task per test case (or golden), let max_concurrent of them run through a semaphore, and wrap the whole batch in asyncio.wait_for(asyncio.gather(*tasks), timeout=get_gather_timeout()).

get_gather_timeout() is DEEPEVAL_PER_TASK_TIMEOUT_SECONDS + DEEPEVAL_TASK_GATHER_BUFFER_SECONDS, the budget for one task (180s + 27s = 207s by default). The batch needs ceil(N / max_concurrent) rounds, so any batch that runs longer than ~207s after its tasks are created is cut off (with the default throttle_value=0, that is the whole batch), even when every test case finishes well inside its own per-task budget. Example: 200 test cases at ~30s each with the default max_concurrent=20 is 10 rounds, ~300s. evals_iterator() applies the cap separately to its app phase and its eval phase.

What the user sees:

  • evaluate(), ignore_errors=False (default): raises a bare TimeoutError() with no message, and the caller gets no EvaluationResult at all.
  • evaluate(), ignore_errors=True: the cases in flight are marked failed with Timed out/cancelled while evaluating metric. Increase DEEPEVAL_PER_TASK_TIMEOUT_SECONDS_OVERRIDE ..., which misattributes the cause (no case exceeded its per-task budget), and cases still waiting on the semaphore are cancelled and silently missing from the results.
  • evals_iterator() app phase: the timeout is swallowed whatever ignore_errors is. In-flight goldens are recorded as failed (their traces are marked Task was cancelled (likely due to timeout).), queued goldens never run and are silently missing, and the iterator then finishes normally. Nothing is raised; the visible signs are a lower test count and a RuntimeWarning: coroutine '...' was never awaited.
  • evals_iterator() eval phase (_a_evaluate_traces): re-raises regardless of ignore_errors. So does _evaluate_test_case_pairs, though that path has no in-tree producer (only external callers that fill test_case_metrics).

Lowering max_concurrent, the usual advice for provider rate limits, makes it worse because it adds rounds.

Repro

No API keys. Current main (385117c9c, deepeval 4.2.6). Timeouts are scaled down so it runs in seconds; with defaults the same thing happens to any batch longer than ~207s.

python
import asyncio, os, time

# 3s per test case budget, 0.5s gather buffer -> gather timeout 3.5s
os.environ["DEEPEVAL_PER_TASK_TIMEOUT_SECONDS_OVERRIDE"] = "3"
os.environ["DEEPEVAL_TASK_GATHER_BUFFER_SECONDS_OVERRIDE"] = "0.5"

from deepeval import evaluate
from deepeval.dataset import EvaluationDataset, Golden
from deepeval.evaluate.configs import AsyncConfig, DisplayConfig, ErrorConfig
from deepeval.metrics import BaseMetric
from deepeval.test_case import LLMTestCase
from deepeval.test_run import global_test_run_manager
from deepeval.tracing import observe


class OneSecondMetric(BaseMetric):
    """Each test case takes 1s, well inside the 3s per-task budget."""

    threshold = 0.5
    async_mode = True
    delay = 1

    def measure(self, test_case, *args, **kwargs):
        time.sleep(self.delay)
        self.score, self.success = 1.0, True
        return self.score

    async def a_measure(self, test_case, *args, **kwargs):
        await asyncio.sleep(self.delay)
        self.score, self.success = 1.0, True
        return self.score

    def is_successful(self):
        return bool(self.success)

    @property
    def __name__(self):
        return "OneSecondMetric"


class InstantMetric(OneSecondMetric):
    delay = 0


def run(n, ignore_errors):
    start = time.perf_counter()
    try:
        result = evaluate(
            test_cases=[LLMTestCase(input=f"q{i}", actual_output="a") for i in range(n)],
            metrics=[OneSecondMetric()],
            async_config=AsyncConfig(max_concurrent=4),
            display_config=DisplayConfig(show_indicator=False, print_results=False),
            error_config=ErrorConfig(ignore_errors=ignore_errors),
        )
    except Exception as e:
        print(f"{n} cases, ignore_errors={ignore_errors}: raised {e!r} after {time.perf_counter() - start:.1f}s")
        return
    passed = sum(r.success for r in result.test_results)
    print(
        f"{n} cases, ignore_errors={ignore_errors}: {len(result.test_results)} results, "
        f"{passed} passed, after {time.perf_counter() - start:.1f}s"
    )


@observe()
async def app(q):
    await asyncio.sleep(1)  # each golden takes 1s, well inside the 3s budget
    return "a"


def run_iterator(n):
    dataset = EvaluationDataset(goldens=[Golden(input=f"q{i}") for i in range(n)])
    start = time.perf_counter()
    for golden in dataset.evals_iterator(
        metrics=[InstantMetric()],
        async_config=AsyncConfig(max_concurrent=4),
        display_config=DisplayConfig(show_indicator=False, print_results=False),
        error_config=ErrorConfig(ignore_errors=False),
    ):
        dataset.evaluate(asyncio.create_task(app(golden.input)))
    cases = global_test_run_manager.get_test_run().test_cases
    print(
        f"evals_iterator, {n} goldens, ignore_errors=False: {len(cases)} test cases, "
        f"{sum(c.success for c in cases)} passed, after {time.perf_counter() - start:.1f}s"
    )


run(8, False)   # 2 rounds of 4 -> ~2s, fits in 3.5s
run(20, False)  # 5 rounds of 4 -> ~5s, yet each case still takes only 1s
run(20, True)
run_iterator(20)

Output (deepeval's own banners and log lines omitted; run unbuffered, e.g. PYTHONUNBUFFERED=1, for this ordering):

8 cases, ignore_errors=False: 8 results, 8 passed, after 2.0s
20 cases, ignore_errors=False: raised TimeoutError() after 3.5s
20 cases, ignore_errors=True: 16 results, 12 passed, after 3.5s
.../deepeval/evaluate/execute/loop.py:579: RuntimeWarning: coroutine 'app' was never awaited
evals_iterator, 20 goldens, ignore_errors=False: 16 test cases, 12 passed, after 3.6s

Every test case takes 1s against a 3s budget. The 20-case runs fail only because they need 5 rounds of 4. With ignore_errors=True, 4 cases are reported as timed out and 4 are missing from the results altogether. evals_iterator() does the same with ignore_errors=False and raises nothing.

Root cause

This looks unintended. #2128 sized the gather timeout as the per-task budget plus a "buffer for the slowest straggler", which only bounds the batch if all tasks run at once. The docs describe the buffer as time "added to gather/drain after tasks complete" (environment-variables.mdx) and "reserved for async gather / cleanup" (troubleshooting.mdx), and a maintainer in #2298 calls it "a small grace window we add on top of the task's outer budget to let asyncio.gather(...) drain".

The only hints at queueing are a settings.py comment ("Increase if many tasks are running concurrently") and a WARNING from _log_gather_timeout that suggests raising the per-task or buffer override. That warning is logged only at e2e.py#L601 (the progress-bar branch) and loop.py#L758, is hidden unless the user configures logging (deepeval attaches a NullHandler), and does not mention max_concurrent.

Workarounds today:

  • Set DEEPEVAL_TASK_GATHER_BUFFER_SECONDS_OVERRIDE to something large.
  • Raise DEEPEVAL_PER_TASK_TIMEOUT_SECONDS_OVERRIDE. This works only because the gather cap includes it. It also loosens the per-task hang guard and, unless DEEPEVAL_PER_ATTEMPT_TIMEOUT_SECONDS_OVERRIDE is set, raises the derived per-attempt provider timeout (88.5s by default, 298.5s at an override of 600).
  • DEEPEVAL_DISABLE_TIMEOUTS=1, which also turns off deepeval's per-task and per-attempt timeouts (provider SDK request timeouts may still apply).

Expected behavior

A run where every task finishes inside its per-task budget should never hit the gather timeout, whatever N and max_concurrent are. The gather timeout should still stop a run that is actually stuck.

Proposed fix

Make the gather timeout account for queueing:

gather_timeout = per_task * ceil(n_tasks / max_concurrent) + buffer

Each task's deadline is enforced inside its semaphore slot, so as long as tasks yield to the event loop and honor cancellation, a slot is held for at most about per_task and the batch finishes within roughly ceil(N / max_concurrent) * per_task. That keeps the timeout a backstop against hangs while no longer cutting off healthy runs. (Blocking sync code inside an async metric or model can overrun this bound, but it already defeats the per-task deadline today.)

Trade-off: the time to detect a stuck batch now grows with N (10,000 cases at max_concurrent=20 gives ~25h with defaults). Cooperative hangs are already caught by the per-task deadline, so this seems acceptable. If not, a progress watchdog (fail when no task completes within per_task + buffer) would keep detection time constant.

  • Give get_gather_timeout() optional n_tasks / max_concurrent arguments (current behavior when omitted).
  • Pass len(tasks) and the active max_concurrent at the 5 call sites above. The other two uses, agentic.py L179 (a span's children) and L204 (a trace's root spans), gather spans without a semaphore inside a single task's deadline, so they keep the single-task value.
  • Have _log_gather_timeout (_common.py) log the computed value instead of get_gather_timeout_seconds().

Tests: the helper math; evaluate() with N > max_concurrent over several rounds (scaled-down overrides as above) completes with all results; the async evals_iterator() variant; a task that swallows its first (per-task) cancellation still trips the gather timeout (a cooperative hang is already caught by the per-task deadline, so it would not exercise the backstop).

Related: #2128 / #2136 (added gather timeouts to the orchestration gathers; the evals_iterator() app-phase one came earlier, in #2068), #2335 (made the two a_execute_test_cases sites respect ignore_errors). None of them covers queueing. Open PR #3159 edits the same two wait_for calls in e2e.py, and open PR #3147 edits _log_gather_timeout.

Happy to open a PR for this.

Environment

  • deepeval main @ 385117c9c (4.2.6)
  • Python 3.11, macOS