Skip to content

test(cli): tests wait for a background thread with one generous bound, not a 1-second deadline, so they pass under load #1664

Closed

Description

@dan-petty

Friction

  • On 2026-10-18 the pre-commit hook failed on an unrelated change because tests/test_server_service.py::test_a_budget_refusal_in_the_model_lane_holds_the_release_lane_too raised _queue.Empty. It passed when rerun (30 of 30) and in the hook's next run. The host load average was 30 to 50, with several devops ci runs sharing 16 CPUs.
  • The same day, Tests & Coverage failed on pull request feat(github): the github session sends rest requests through gidgethub, paced, charged and classified by status and headers #1661 in GitHub Actions (4 workers, 10,609 tests) with one unrelated failure: tests/test_review_embeddings_unserved.py::test_once_the_model_answers_lookups_stop_taking_turns. Its threading.Barrier(WORKERS, timeout=2.0) (:201) broke because one worker's request did not arrive within 2 s, so one lookup failed (together.broken was True and 4 embedding requests arrived instead of 5). The same commit had passed the full gate locally. So this is not only a loaded-workstation problem: the hosted runner hits it too.
  • The service test waits at most 1 s for a worker thread to finish its round. Under that load a ready thread can wait longer than 1 s for a CPU, so the test fails although the code is right.
  • A flaky failure in the pre-commit or pre-push gate costs a full rerun of the gate (5 to 13 minutes under load), and it teaches agents to rerun failures instead of reading them. The owner's rule is that CI gate speed is P0.

Evidence

Checked at release/v0.2.37 30b8fdd.

  • _Rounds.wait (tests/test_server_service.py:954-959) calls self.done.get(timeout=1.0) for each expected round, then worker.wait_active(1.0). _Rounds.held (:961-966) calls wait_active(1.0). About 36 calls in that file go through these helpers or through an Event.wait(timeout=1.0) such as :155, :176, :428, :441, :460, :539, :544 and :735.
  • Across tests/, 38 waits on a thread, queue, event or future use a deadline of 2 s or less, in 11 files: test_server_service.py, test_ai_client_security.py, test_k8s_port_forward_daemon.py, test_roadmap_intake.py, test_rag_query_telemetry.py, test_roadmap_github_store.py, test_roadmap_run.py, test_k8s_service.py, test_ai_request_priority.py, test_ai_review_pool.py and test_review_embeddings_unserved.py.
  • Locally the Barrier test failed 5 of 26 current-tree full runs on 2026-10-18, at mean load 11-29. Two failures came at load 11-14 with no other suite running, so the suite's own 16 workers are enough to break a 2 s handoff. Each failure clears the gate's verdict and costs a rerun of about 200 s.
  • A wait that expects its event returns as soon as the event happens, so a longer bound costs nothing when the test passes. Only a failing test waits the whole bound.

Remedy

Acceptance criteria

  • Tests first: a test of the shared helper shows that a wait whose event fires after 1.5 s succeeds with the bound, and the same wait with a 1 s deadline fails.
  • grep -rnE '\.(wait|get|join|result|acquire|wait_active)\((timeout=)?(0?\.[0-9]+|1(\.0)?|2(\.0)?)\)' tests matches only waits that check nothing happens, each one after an idle wait, and each one says so in a comment.
  • Every threading.Barrier(..., timeout=...) under tests/ uses the bound, starting with tests/test_review_embeddings_unserved.py:201.
  • tests/test_server_service.py and tests/test_review_embeddings_unserved.py each pass 20 runs in a row with -n logical while two other devops ci runs share the host.
  • The suite's wall time is unchanged within noise.

Proposed design

Problem statement

Tests fail under load because they use short timeouts (1-2 seconds) when waiting for background threads to complete their work, but the threads can take longer than the timeout in a high-load environment.

Acceptance criteria

  • Criterion 1: A shared helper function is created that uses a generous bound for waits expecting something to happen, and tests using this helper pass under load.
    Verification: Run tests with -n logical while two other devops ci runs share the host, ensuring 20 consecutive runs of tests/test_server_service.py and tests/test_review_embeddings_unserved.py both pass.
  • Criterion 2: All waits in tests that expect an event to occur use a generous bound instead of 1-2 seconds.
    Verification: Running grep -rnE '\.(wait|get|join|result|acquire|wait_active)\((timeout=)?(0?\.[0-9]+|1(\.0)?|2(\.0)?)\)' tests matches only waits that check nothing happens, each one after an idle wait, and each one says so in a comment.
  • Criterion 3: Every threading.Barrier(..., timeout=...) under tests/ uses the generous bound instead of 2 seconds.
    Verification: Verify that tests/test_review_embeddings_unserved.py:201 and all other barriers in tests use a timeout greater than 2 seconds.
  • Criterion 4: The wall clock time for the test suite remains unchanged within noise after implementing the generous bounds.
    Verification: Run the full test suite and measure its wall clock time, ensuring no significant increase compared to baseline.

Key questions

  • What is the recommended bound for waits that expect something to happen?: A generous bound of 30.0 seconds is recommended for waits that expect an event to occur. (proposed)
  • Which existing tests use short timeouts that are causing failures under load?: Tests in tests/test_server_service.py and tests/test_review_embeddings_unserved.py are identified as using short timeouts (1-2 seconds) that cause failures under load. [sources: tests/test_server_service.py:954-959, tests/test_server_service.py:961-966, tests/test_review_embeddings_unserved.py:201]
  • How many files across the tests directory are using short timeouts?: 38 waits on threads, queues, events or futures use a deadline of 2 seconds or less in 11 files. [sources: tests/test_server_service.py, tests/test_ai_client_security.py, tests/test_k8s_port_forward_daemon.py, tests/test_roadmap_intake.py, tests/test_rag_query_telemetry.py, tests/test_roadmap_github_store.py, tests/test_roadmap_run.py, tests/test_k8s_service.py, tests/test_ai_request_priority.py, tests/test_ai_review_pool.py, tests/test_review_embeddings_unserved.py]

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    source/agent
    type/test
    on Oct 18, 2026
  2. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: at intake only a critical fix goes into a release; a release start pulls Ready items in, P0 features first.

    • Type: type/test. The candidate is about improving test reliability by adjusting timeouts for thread synchronization.
    • Priority: P1-High. Flaky tests under load cause full reruns of the CI gate, violating the owner's rule that CI gate speed is P0.
    • Value: High. Fixing flaky tests improves developer productivity and CI reliability, especially under load conditions.
    • Effort: Medium. The change involves modifying test code to use a shared bound for waits, requiring updates in multiple files.
  3. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Status set to Ready at 25e2cda (see proposed design in issue body).

  4. dan-petty commented on Oct 18, 2026

    @dan-petty
    OwnerAuthor

    Amendment (2026-10-18): folded here by intake under the agent filing quota

    The cycle's agent filing allowance (#1153) was used, so devops roadmap intake filed nothing and named this item as the nearest. The candidate below is related work that can land with this item or be filed on its own in a later cycle. Candidate title: "fix(tests): test workers start no idle OpenBLAS threads, so a full suite holds 240 fewer tasks against pids.max".

    Friction

    • The devcontainer's cgroup allows 2048 tasks. Every xdist worker of a full suite parks 15 idle OpenBLAS threads, so one 16-worker suite holds about 272 tasks, 240 of them idle.
    • With 3-4 suites or gates overlapping, about 1,000 tasks go to idle threads. The OpenBLAS pthread_create failure seen in one agent's failed pre-push shows the cgroup limit was reached; when it is, thread and process creation in tests can fail and the gate has to be run again. Whether that failure, rather than a timing flake, failed that push's test row is not shown.
    • The container hit pids.max 449 times between its start and 2026-10-17; the counter reset when the container restarted.
    • Exporting the variable before git push does nothing: devops ci's environment allowlist drops it.

    Evidence

    Checked at release/v0.2.37 30b8fdd.

    • tests/test_ci_repeat.py:19 imports numpy.random at module level, so every worker loads numpy while collecting. With that file ignored, a full collection loads no numpy and the process holds 1 task instead of 16.
    • Import probe: 1 task bare, 16 after import numpy, 31 after import scipy.linalg; with OPENBLAS_NUM_THREADS=1, 1 in each case.
    • Live snapshot of a 16-worker suite: 17 tasks per worker, 272 in total, with the OpenBLAS library mapped.
    • src/devops_cli/core/process.py:45-102 has no OPENBLAS_ or OMP_ entry, so build_subprocess_env() drops both.

    Remedy

    • Set os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") at the very top of tests/conftest.py, before anything imports numpy. This covers the gate, the pre-commit ci test hook and direct pytest runs, and child processes inherit it. OPENBLAS_NUM_THREADS is OpenBLAS's documented setting.
    • Optionally also move the numpy import in tests/test_ci_repeat.py:19 into the test that uses it.
    • No test, check or threshold changes. A passing run gets no faster.

    Acceptance criteria

    • Tests first, offline: a test asserts that after tests/conftest.py is imported, import numpy in a fresh subprocess started with the test environment leaves the process at 1 task (read from /proc/self/status Threads:).
    • A 16-worker full run holds at most 2 tasks per worker at collection (sampled from /proc).
  5. added this to the v0.2.37 milestone on Oct 19, 2026
  6. added
    status/in-progress
    on Oct 19, 2026
  7. added a commit that references this issue on Oct 19, 2026
    f66a8e3
  8. dan-petty commented on Oct 19, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1701, merged into release/v0.2.37 as f66a8e3.

    Tests that wait for another thread now wait with one generous bound. They no longer use a 1 or 2 second deadline that a loaded host misses. Three of the flakes had causes other than the deadline, and those are fixed at the cause.

    The bound.

    • tests/support/waits.py holds THREAD_HANDOFF_BOUND_SECONDS (30 s) and wait_until, which checks its deadline after each sleep and before the next read.
    • A wait returns when its event fires, so a passing test is no slower.
    • In the touched files, these waits use the bound:
      • the 32 of the issue grep's 38 matches that expect their event;
      • the 1 s and 2 s polls the grep can't see;
      • a 0.1 s sleep before a /metrics read;
      • a 5 s drain timeout;
      • the harness's 20 s poll;
      • the files' other 3-10 s waits.
    • Two grep matches weren't waits: limiter.acquire(tokens=1.0) and comments.get(1, []) keep their meaning.

    Holds outlive their observers. A hold is something a test keeps blocked or alive while it checks something else. Each hold now outlives every wait that observes it, or records that the test released it and asserts that.

    Causes other than the deadline.

    • The barrier test: the tracer's exporter threads posted trace exports through…

    23 file(s) changed.

    How it was verified

    Check runs at 2f1ebad:

    • Prune PR DevContainer Images: pass
    • Audit Defect PR Hardening: skipping
    • zizmor: pass
    • devops-cli: pass
    • bandit: pass
    • CodeQL: pass
    • Rule Pack Tests: pass
    • Fail-to-Pass Self-Check: pass
    • Changed-Test Independence: pass
    • Tests & Coverage: pass
    • Analyze (python): pass
    • Fail-to-Pass Check: pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-1664-thread-handoff-bound.md:

    • Tests first, for the shared helper: test_a_wait_for_an_event_that_fires_after_a_second_and_a_half_fails_with_a_one_second_deadline drives wait_until on a clock only its sleeps move, with the condition true from 1.5 s, and a one-second deadline returns False; test_a_wait_for_an_event_that_fires_after_a_second_and_a_half_succeeds_with_the_bound sees an event a real timer sets after 1.5 s within the bound. test_a_poll_that_oversleeps_its_deadline_does_not_count_a_later_event failed on the earlier wait_until, which read the condition before checking the deadline (assert (True, True) == (False, True)). test_a_condition_that_already_holds_is_read_once_and_not_waited_for asserts no sleep; a wait_until that slept before its first read failed it ((True, 1, [0.01]) == (True, 1, [])), and one that ignored its deadline for a second failed the one-second case. With the bound set to 1.0 the bound case failed (assert False is True).
    • grep -rnE '\.(wait|get|join|result|acquire|wait_active)\((timeout=)?(0?\.[0-9]+|1(\.0)?|2(\.0)?)\)' tests matches only the four windows that check nothing happens, each after an asserted wait for the competing thread and each with its comment.
    • Every threading.Barrier(..., timeout=...) under tests/ uses the bound: the one in tests/test_review_embeddings_unserved.py and the new one in tests/test_server_service.py.
    • Each recorded hold catches the bug it guards against, shown with a mutant of src: an early return in Shell._terminate_process_group fails both fix(ai): agent toolset instructions, deferred-tool context, the sampling-model stub, harness memory and shell process groups #958 tests, and SIGKILL replaced by pass fails test_stop_command_kills_a_member_that_ignores_sigterm; one lock around every Service round fails the cross-blocking check ((202, True, [0]) == (202, True, [1])); a per-repository lock fails test_a_webhook_runs_the_release_lane_while_the_model_lanes_round_is_blocked (model_blocked and model_released False); and a close() that no longer shuts the response fails test_closing_a_followed_log_ends_a_read_blocked_on_a_quiet_container (ended_by_shutdown False). Before, with each hold on its observer's bound, review saw the harness and close() mutants pass, the single lock get past the cross-blocking check, and the per-repository lock pass 3 of 18 runs.
    • tests/test_server_service.py and tests/test_review_embeddings_unserved.py passed 20 runs in a row with -n logical while two full-suite runs looped beside them, each restarted as it ended (six runs, all passing), with other agents' work on the host: load average 22.9-65.0, mean 41.8, on 16 CPUs. The two concurrent runs were the gate's test row (pytest -n logical tests), not whole devops ci runs.
    • Pending a person: the suite's wall time unchanged within noise. On the release branch after the squash merge, on a quiet host, run git checkout <merge>^ && uv run pytest -n logical -q tests, then git checkout <merge> && uv run pytest -n logical -q tests, twice each and alternating; the two means should differ by less than the runs of one commit do. Measured before the rebase, against 83939e6, with other agents' work holding the load average at 14-34, the suite took 372 s and 253 s at 83939e6 and 312 s and 401 s with this change, alternating. Runs of one commit differed by 90-120 s, more than the 44 s between the means, so that host gave no fair comparison.
    • Tests first, offline: tests/test_openblas_worker_threads.py starts a process at the repository root with OPENBLAS_NUM_THREADS removed from its environment, which imports tests.conftest and then numpy, and reads Threads: from /proc/self/status. It reads 1, and 16 with numpy imported above the setdefault (assert '16' == '1'); it also passes with OPENBLAS_NUM_THREADS=4 exported, which the conftest's setdefault keeps.
    • A 16-worker run, with every test deselected so the workers only collect, sampled from /proc every 50 ms: 17 threads in each worker before (272 in all); after, 2 in each worker, briefly 3 in some (33 in all at the peak) while OpenTelemetry's resource detection runs. That thread is the ThreadPoolExecutor in get_aggregated_resources (opentelemetry/sdk/resources/__init__.py), started when collection imports devops_cli.ai.agents.agent, which loads pydantic_ai and logfire; it ends once detection returns. So the amendment's "at most 2 tasks per worker at collection" is not met for that moment: moved to fix(telemetry): devops-cli metrics reach prometheus in one hop, a late sample no longer drops a whole batch, and the collector runs only what its pipelines use #1132 (amendment of 2026-10-19).
    • Tests first: test_a_served_lookup_looks_up_no_service_host records socket.getaddrinfo. Before the fixture answered the collection check it failed with six example.com lookups and took 3.05 s; it now finds none. tests/test_review_embeddings_unserved.py alone (-n0) took 5.9 s before and 2.9 s after, test_once_the_model_answers_lookups_stop_taking_turns 3.08 s before and 0.03 s after.
  9. added a commit that references this issue on Oct 20, 2026
    954914e
  10. removed
    status/in-progress
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source/agenttype/test

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions