Isolate each test's garbage collection and remove timing races from flaky tests

Merged
AD
1mo ago
+632-154

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of adtyavrdhn.

Why we make these changes

CI on main keeps failing on tests that did nothing wrong (example). This closes no issue. It relates to #11726. A survey of 170 failing runs found two root causes.

  1. Another test's garbage. A leaked event loop or socket in a reference cycle is finalized whenever the collector next runs, usually in a later test, whose pytest.warns or simplefilter('error') then fails. This alone failed 19 of the 170 runs. Filters already ignore these warnings and the flakes continued, and collecting after every test would cost about 28 minutes per shard, so tests/gc_isolation.py freezes existing objects before each test (0.010 ms per test) and collects the test's own garbage in its teardown.
  2. A stalled runner or a race in a fake. Each fake or test is fixed at the cause: a kill arriving before the process registers (OpenSandbox, Boxd, Modal, Smol); OpenSandbox dropping a finished command's output, the execd older than 1.1.1 failure; and timers racing a stall in Modal, Sprites, Mistral, cancellation, streaming, realtime and rewind tests. WebFetch keeps main's tests but budgets CPU time, not wall time.

New public surface

None.

User-visible behavior

None. Only tests, test doubles, tests/AGENTS.md and one line of .github/workflows/benchmark.yml change.

Verification

Flakes are forced with scratch plugins that inject the interleaving, not by rerunning. Results are from 23786f6917; later commits bound a wait, correct wording, inline a helper and merge main, and their touched tests were rerun. Only targeted tests ran locally, so CI on this head is the full-suite check.

  • 16 forced failures: all fail on clean main, all pass here, including the OpenSandbox one on real and stalled loops.
  • 12 mutants of the plugin and 3 slowed WebFetch conversions are all caught. Plugin tests pass on Python 3.11 to 3.15.
  • 600 forced leaks: 0 blamed on the wrong test, 9 to 12 without the plugin. Wall time, memory and open files were neutral, on samples and not a full CI run.
  • Limits on 376307832f: a 1.2s or 5s stall fails the realtime close test on main and passes here, and a close that waits out _END_SESSION_TIMEOUT still fails it. A 61s stall fails the Sprites timeout test at the old limits and passes at the new.
  • A timing audit of every limit on 376307832f reproduced four more stall failures, fixed on the next commit and each forced again: a 5.5s stall after a cancel, a 20 ms loop turn overflowing OpenSandbox output, a 2s settle wait the at-once test let pass, and an 11s worker-thread stall on the virtual clock.
  • Seven fresh-context reviews. The last two, an attack and an independent cause check, found no blocking defect, and the cause check reached the OpenSandbox cause with its own forcing.

What changes for existing users

Nothing.

For the maintainer to decide

  • Code owner: benchmark.yml needs a non-author code owner's approval. It lists the plugin as a benchmark input, which tests/benchmarks/test_dependencies.py requires. CodSpeed reports no change on the 21 benchmarks it ran, and it skipped another 21.
  • Leaks found after the last test only print to stderr, so nothing fails on a new kind. All 22 such lines in 38 CI jobs are kinds pyproject.toml already ignores. A nightly job could fail on them.
  • Weaker checks: IsNow allows for the test's runtime. Limits that only guard against a hang are 300s in the changed rewind, browser, Boxd, Sprites, OpenSandbox and cancellation tests and the virtual clock's thread wait, the longest stall seen being 187s, so a real hang there takes 5 minutes to fail. The periodic sweep is gone. One Modal test overrides anyio_backend for a virtual clock.
  • Known plugin limits, listed in tests/AGENTS.md: acyclic objects, background threads, parametrized fixtures, xfail.
  • Product race, unchanged: the web UI shows ready during TurnEnd hooks, so Retry can get a 409. The browser test now waits for idle, and #12603 tracks the bug.

Not fixed

About 200 other short real-clock limits remain, such as the 5s editor default, which 100 callers share. A stall inside one can still fail it: the survey has 10 such failures in 170 runs, mostly in tests this PR fixes. test_cancelling_a_run_interrupts_its_cell; test_reload_running_shell; test_timeout_reads_stderr_back_over_a_slow_exec (#12449); LocalStack test_readiness_timeout_stops_container; stalls on 3.14 lowest-versions jobs (calls up to 187s). Those stalls may be CPU rather than waiting, which CI logs can't tell apart. If so, WebFetch could still exceed 60 CPU seconds there, though the change can't be flakier than main.

PR decisions

2026-11-04 · pre-push review 1 of 3 at 17ff1f64b37cbd691b9acca081a504eb2d9b165c · iter -

2026-11-04 · pre-push review 1 of 3 at 17ff1f64b37cbd691b9acca081a504eb2d9b165c · iter -

  • Decision: remediated: removed periodic sweep, one recording collection after last test; findings dismissed with evidence are listed in the follow-up bundle
  • Why: strong and light reviewers both flagged the sweep; session-end leak exits 1 even when all tests pass, confirmed locally
  • Source: https://github.com/pydantic/pydantic-ai/tree/fix/unclosed-event-loop-flakes
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-04 · pre-push review 2 of 3 at d224db1f4dcb51735cdc8811920d8785d9d954cf · iter -

2026-11-04 · pre-push review 2 of 3 at d224db1f4dcb51735cdc8811920d8785d9d954cf · iter -

  • Decision: remediated: docs say which leaks wait for the end of the run and what IsNow tolerates; sweep-removal trade-off goes in the PR body with a local measurement; mutants rerun with saved output. Dismissed the f-string finding: {held} is substitution producing [[socket.socket()]], and the test passes.
  • Why: local comparison of 1,190 tests with -n 2: branch 697MB/517MB and 19 fds per worker, main 750MB/629MB and 19 fds
  • Source: https://github.com/pydantic/pydantic-ai/tree/fix/unclosed-event-loop-flakes
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-04 · pre-push review 3 of 3 at fa978eef293479f5df4e0e3798b5a40b613be962 · iter -

2026-11-04 · pre-push review 3 of 3 at fa978eef293479f5df4e0e3798b5a40b613be962 · iter -

2026-11-04 · author-requested fresh reviews after budget exhausted · iter -

  • Decision: ran 6 fresh-context reviews the author asked for (design, proof, plugin attack, test quality, then an attack and a cause check at 28fa031fc0); they do not count against the pre-push budget; applied every verified finding
  • Why: author asked for multiple independent reviews with proof; no blocking defect in the last two
  • Source: https://github.com/pydantic/pydantic-ai/pull/12523
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-04 · WebFetch tests keep main's shape on a CPU budget · iter -

  • Decision: dropped the call-counting rewrite and budget CPU time rather than wall time
  • Why: the rewrite could not catch quadratic behaviour and broke coverage; CPU time cannot exceed wall time for this single-threaded work, so it is never flakier than main; slowest case 8.9 CPU seconds locally under the pure Python tracer
  • Source: https://github.com/pydantic/pydantic-ai/pull/12523
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-05 · defer: web UI reads ready during TurnEnd hooks · iter -

  • Decision: Filed as #12603 in the general queue instead of fixing here; the browser test's wait links it
  • Why: Out of scope for this PR: tests only, and a fix needs a product decision about the page during TurnEnd
  • Source: https://github.com/pydantic/pydantic-ai/issues/12603
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-05 · limits that guard only against a hang are 300s, virtual-clock deadlines keep main's values · iter -

  • Decision: Restored fail_after(1) on the realtime virtual clock; raised hang-only limits in OpenSandbox, Boxd and Sprites tests to 300s; the Sprites deadline is an hour; left the 5s editor default and other short limits as they are
  • Why: Author asked whether 0.02 was brittle: a 1.2s and a 5s stall pass with 1, and the mutant still fails. A 61s stall still failed the Sprites test at 60s and passes now. The editor default stays short because 100 callers would each wait 300s on a real hang; a survey of 170 runs has 10 limit failures in 7 tests
  • Source: https://github.com/pydantic/pydantic-ai/pull/12523
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

2026-11-05 · Hang guards in the cancellation tests and the virtual clock's thread wait are 300s; the OpenSandbox drain counts idle turns and caps output after exit · iter -

  • Decision: Raised READINESS_WAIT_TIMEOUT in test_run_cancellation.py and _MAX_THREAD_WAITS in SimulatedLoop to 300s; the drain stops after 1000 idle turns or 1 MiB after exit; the at-once test sets _GONE_SETTLE to an hour
  • Why: A fresh timing audit reproduced each: a 5.5s stall failed the cancellation test, a 20 ms loop turn overflowed the 10 MiB limit, the 300s limit let a 2s settle wait pass, and an 11s thread stall raised SimulationStuck. Each fix was forced the same way and passes; every use of the raised constants is a hang guard
  • Source: https://github.com/pydantic/pydantic-ai/pull/12523
  • Session: 870d059f-d4c1-4c3c-99f7-dd5e469db755

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.

🤖 Generated with Claude Code


Summary by cubic

Isolates each test's garbage collections and removes timing races so a leaked resource or stalled runner can no longer fail an unrelated test.

  • tests/gc_isolation.py freezes every existing object before each test and collects only the current test's garbage, so a leak fails the test that caused it rather than the next test the collector runs in.
  • Cyclic garbage dropped after its test is collected once after the last test and reported on stderr without failing the session.
  • Sandbox fakes kill a command that starts as their sandbox is already destroyed; OpenSandbox drains output by event-loop turns so a slow machine can't drop what a finished command wrote.
  • Tests stop waiting on a real clock: Modal, realtime-close, Sprites and streaming tests run on a virtual clock or drive their own clock reading, and waits that merely guard against a hang now outlast the longest stall seen on CI (~300s).
  • test_web_fetch.py budgets CPU time, not wall time, and test_run_cancellation.py cancels from inside the tool instead of waiting for a readiness signal; the rewind browser test waits for the turn to end (that UI race is tracked in #12603).
  • IsNow matches timestamps from anywhere in the running test, so its 10-second tolerance can't be consumed by a slow setup.
  • The plugin ignores Hypothesis's register_random() warning, which its gc.get_referrers() check raises while the random's holder is frozen, and thaws everything before session-end hooks.
  • The young_gc fixture is removed; the plugin covers every test.

Test-only change: no public API or user-visible behavior changes.