Design out 15 CI test flakes and serialize `IPythonKernel` shutdowns
No linked issue: these are the flakes in 22 of the last 60 main CI runs (2026-10-30 to 11-03), each failing a different shard and Python version.
Why we make these changes
Each test raced something it did not need to test: a wall-clock deadline, an event published before the state it announces, a port or PID another process could take, or garbage another test left for the garbage collector. Rather than widen waits, each fix waits on the event or condition the code exposes, injects the clock, or removes the dependency, per agent_docs/concurrency.md ("Testing it").
One race was in product code. IPythonKernel.shutdown() kills a kernel without the cell lock, and the run holding the lock then stops it too. jupyter-client resolves one shared _ready future per manager, so the later of two overlapping shutdown_kernel() calls raises InvalidStateError, and when that was the run's call the zmq context leaked into a later test. A lock serializes the call. _stop() also closes the context in a finally, as a cancelled restart() leaked it on main too.
New public surface
None.
User-visible behavior
src/pydantic_ai_harness/.../_kernel.py :: IPythonKernel.shutdown() # a cell ignores SIGINT
└─ _kill() -> _shutdown_kernel() ─┐ (no cell lock)
_kernel.py :: _run_cell() finds the process gone -> _stop() -> _shutdown_kernel()
- two shutdown_kernel() calls overlap -> InvalidStateError, zmq context left for the GC
+ _shutdown_lock: the calls run one after the other -> both succeed, context closed
Verification
For every flake, a scratch harness forcing the CI interleaving failed on main with the CI error and passes here. Rewritten tests were checked against mutants that restore the bug. New: test_shutdown_and_the_run_whose_kernel_it_kills_stop_it_one_call_at_a_time and test_a_restart_cancelled_while_it_stops_the_kernel_still_closes_the_zmq_context both fail on main. jupyter-client 8.6.3 (lowest) and 8.10.0: overlapping calls fail, sequential calls succeed. Not run locally: repeated loops, coverage, Linux (CI covers them). Supersedes #12308's 5 to 10 s guard for the inline-picker test.
What changes for existing users
IPythonKernel no longer raises InvalidStateError or leaks a zmq context when shutdown() kills a kernel its run is also stopping; nothing else changes.
Per-flake aim, pattern and proof
Rules every fix is held to, from the repo's own agent_docs/concurrency.md ("Testing it") and
tests/AGENTS.md ("Test cost"):
- R1 Assert the concurrency fact itself, not the output it happens to produce.
- R2 Order steps with
Events, not sleeps. A guard (READINESS_WAIT_TIMEOUT) bounds a wait on an event,
where only a lost wakeup can fire it, never a block of work, which fires whenever the runner is slow. - R3 Inject timeouts and clocks (parameter, setting,
monkeypatch) so a test never waits out a real timer. - R4 Reach the real trigger through the public path.
- R5 (root
AGENTS.md) Narrowest fix for the reproduced defect; a product change only where the defect is in
the product, and nothing that moves behaviour on a wider surface.
Proof standard for every row: a scratch harness forcing the CI interleaving fails on unchanged main with
the CI error, and passes on the fix; the touched tests pass. Mutants where a test was rewritten.
| # | Test (CI runs) | What it must prove | What it accidentally depended on | Pattern (rule, precedent) | Extra proof |
|---|---|---|---|---|---|
| A | test_web_workers::test_a_task_takes_no_prompt_once_its_agent_delegates_no_more (5) | A task prompt is refused and the conversation is unchanged | TurnEnded arriving after the turn is stored; it is sent before | Wait on the event published once the turn is saved, SessionsChanged (R2; settle() in test_web_rewind.py) | Every SessionsChanged publisher read: the only one during a turn is the title, sent before TurnEnded |
| B | test_ask_user_menu::test_custom_answer_reaches_model_through_inline_picker (2) | A custom answer typed in the picker reaches the model | A 5 s fail_after around a whole agent run; coverage on 3.14 makes it slow, not hung (CI trace shows the run already finished) | End the input instead of timing it: close the pipe, so a lost Enter declines (R2; test_question_decoder_eof_declines) | Drop-Enter mutant fails fast on a clear assertion. Supersedes open #12308 (5 -> 10 s) |
| C | test_web_sessions::test_archiving_closes_an_idle_session_no_browser_shows (2) | Archiving closes an idle session no browser shows | turn_ended as a proxy for idle; b still handles the turn's end | Wait for the exact condition archive checks, runtime.idle, with the event-driven until (R2; three uses in test_live_runtimes.py) | Browser LiveState 'idle' is not that condition (_state ignores _handling and background work), so it cannot be used. Suspected product gap, not reproduced: follow-up |
| D | browser/test_web_browser::test_at_mentions_pick_files_from_the_session_folder (2) | Accepting a mention replaces only itself, caret after it | Per-key /files requests; a list for @RE passes the wait, and Tab is deliberately held while newer files are due (Composer.tsx "wait for the ones on their way") | One input event, one request (R4: the test is about insertion, not keystroke timing) | The list is closed and fill has no @, so the only request is q=REA |
| E1 | ipython_code_mode::...[killed] (2) + zmq Unclosed context blamed on an Anthropic test (1) | shutdown() stops a kernel whose cell ignores SIGINT | Product race: _kill() and the run's _stop() both call shutdown_kernel(); jupyter-client resolves one shared _ready future, so the later of two overlapping calls raises InvalidStateError, and when it is the run's call the context leaks | Serialize the one call that cannot overlap with a lock (R5; concurrency.md "Locks": the section suspends) | jupyter-client 8.6.3 (lowest) and 8.10.0: overlap fails, sequential succeeds, also after the context is destroyed. New deterministic test asserts most_in_flight == 1 via public shutdown(), holds the kill on an Event (R1, R2, R4); fails on main with InvalidStateError. Both CI orderings forced: main fails 3/3 each, lock passes 3/3. Plus _stop closes the context in a finally: a cancelled restart() mid-stop leaked it on main too; new test fails on main with Unclosed context, passes with the finally |
| E2 | ipython_code_mode::test_timeout_is_reported_when_the_code_catches_the_interrupt (1) | A timeout is reported when the code catches the interrupt | The SIGINT landing after the cell reaches try:; the clock starts when the cell is sent | The timeout's clock stands still until the code reports it is inside (R3) | Real kernel and real SIGINT kept |
| F | test_run_cancellation x2 (2) | An external cancel is never translated to RunCancelled | A 5 s wall-clock readiness wait; the loop stalled 6.65 s | The tool cancels the task itself, so the cancel lands mid-tool by construction (R2) | Mutant translating external cancels fails the test |
| G | test_aoe::test_inert_outside_an_aoe_agent_session[nested] (1) | The plugin is inert outside an AoE session | Fake PIDs 200/4242 equal to the real os.getpid() | Fake PIDs above any real one, 1 << 22 (Linux pid_max ceiling) | Proven by exhausting the code path: ps is faked, so nested() returns False only for os.getpid() in {200, 4242} (CI did not log gw2's PID). Siblings checked: test_not_nested cases are unaffected |
| H | test_herdr::test_socket_delivery_and_release (1) | close() sends the release request | The fake server's reply racing the client's 0.5 s give-up; and reading requests without waiting | The fake server tolerates a client that left (BrokenPipeError, the only error on AF_UNIX), test waits with server.wait (R2) | The deadline itself is covered by test_incremental_reply_has_total_deadline |
| I | modal_sandbox::test_command_timeout_starts_once_the_sandbox_is_acquired (1) | The command's deadline is armed after acquisition | A real 1 s timeout racing a real 1.1 s sleep | Read the deadline the command runs under; order acquisition with events (R1, R2) | Early-clock mutant fails the test |
| L | Prefect session fixture (231 setup errors) (1) | Prefect tests get their server | bind(0)-then-close port pick; a Temporal gRPC server took the port while uvicorn started | Reserve the port in TIME_WAIT, as the Temporal SDK does | Prefect 3.9.0 (pinned = lowest) calls _find_available_port() by module global. Linux semantics from source: temporalio sdk-core get_free_port (TIME_WAIT ports are not reallocated to bind(:0); Linux randomizes ephemeral ports, macOS does not) and uvicorn --host/--port -> loop.create_server -> asyncio reuse_address defaults True on posix. Not executed on Linux locally; CI runs it |
| J | test_vercel_ai::test_server_message_history_follow_up unraisable (1) | (innocent victim) | An event loop run_sync created on a thread and nobody closed, from test_display | Close it at the source; keep the plain-thread path covered; assert one loop was created (R1) | GC-forcing harness passes |
| K | test_utils::test_group_by_temporal_first_window_starts_on_first_item (1) | The window starts at the first item (#5946) | The real clock with 40 ms of slack | Virtual clock, injected into the module by monkeypatch (R3); no product change (R5) | #5946 mutant fails the test with [[1], [2]] |
Not changed, on purpose (R5): siblings with the same pattern but no CI failure (other readiness waits in
test_run_cancellation.py, test_code_that_ignores_the_interrupt_gets_a_new_kernel, test_group_by_temporal,
herdr tests relying on the 0.5 s deadline), the composer's dropped Tab, the suspected browser/archive idle gap, and a kill landing as a cell finishes leaving a dead kernel attached (pre-existing on main, no CI evidence).
PR decisions
2026-11-03 · pre-push review 1 of 3 at dee3c787093acd0a4df5bfe7f86636c33ed2f78b · iter -
- Decision: reserved; dispatched
- Why: reviewed tree 9a3bec7b1be41b821266020f5e18f87e91948d44; scope b9894248bfc6c6e82916e429ef1c13901cba665f..dee3c787093acd0a4df5bfe7f86636c33ed2f78b (full branch, first review)
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
2026-11-03 · pre-push review 1 of 3 at dee3c787093acd0a4df5bfe7f86636c33ed2f78b · iter -
- Decision: remediated: kernel fix redesigned as a shutdown lock with a deterministic overlap test (findings 2, 4); group_by_temporal product change reverted, test injects the clock, #5946 mutant fails it (6); display test keeps the plain thread and closes the loop run_sync creates (7); findings 1, 3, 5, 8, 9 dismissed with evidence
- Why: reviewed tree 9a3bec7b1be41b821266020f5e18f87e91948d44; scope b9894248bf..dee3c78709; dismissals: 1 test waits on the exact condition archive checks via the established until(..., idle) idiom; 3 closed input bounds the run, as test_question_decoder_eof_declines, and faulthandler_timeout plus job timeout-minutes catch a hang; 5 prefect 3.9.0 calls _find_available_port() by module global and the port-steal harness showed the port held; 8 the client deadline is product behaviour covered by test_incremental_reply_has_total_deadline; 9 only one /files request can follow the closed list
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
2026-11-03 · pre-push review 2 of 3 at 9f2fe7adf7ba90cc8ce3d722c79c57fb251221c6 · iter -
- Decision: reserved; dispatched
- Why: reviewed tree 2ac7e3f7f8a69dd3d6f04d27cebd4f4bbc5c402b; follow-up scope dee3c78709 (tree 9a3bec7b1b)..9f2fe7adf7ba90cc8ce3d722c79c57fb251221c6 plus prior findings
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
2026-11-03 · pre-push review 2 of 3 at 9f2fe7adf7ba90cc8ce3d722c79c57fb251221c6 · iter -
- Decision: remediated: _stop destroys the zmq context in a finally, with test_a_restart_cancelled_while_it_stops_the_kernel_still_closes_the_zmq_context (fails on main and on the lock-only candidate with Unclosed context, passes with the finally); overlap test wording fixed; finding 2 (kill landing as a cell finishes) is pre-existing on main, not in CI evidence, proposed as a follow-up; finding 3 comments are main's and unchanged in meaning
- Why: reviewed tree 2ac7e3f7f8a69dd3d6f04d27cebd4f4bbc5c402b; the reviewer's claim that main had the finally is wrong (main's _stop has none), but the leak it describes reproduces on main
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
2026-11-03 · pre-push review 3 of 3 at c8e24d376ba7facfd261478e0c84e45eebc3966b · iter -
- Decision: reserved; dispatched
- Why: reviewed tree bbae0c72a95df34e85a6db901ecf3ffd3196602d; follow-up scope 9f2fe7adf7 (tree 2ac7e3f7f8)..c8e24d376ba7facfd261478e0c84e45eebc3966b plus call-2 findings
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
2026-11-03 · pre-push review 3 of 3 at c8e24d376ba7facfd261478e0c84e45eebc3966b · iter -
- Decision: remediated (comments/docstrings only): _interrupt/_kill comments say starting or stopping; cancel test docstring names restart(); shutdown() docstring overclaim is pre-existing and goes into the dead-manager follow-up issue. Budget exhausted; pushing ea41848be9286226381514b84842607fc7f1c372
- Why: reviewed tree bbae0c72a95df34e85a6db901ecf3ffd3196602d; delta to ea41848be9286226381514b84842607fc7f1c372 is comments/docstrings only (exempt); lifecycle class 17 passed after remediation
- Source: https://github.com/pydantic/pydantic-ai/tree/fix-ci-flakes-1103
- Session: a04a4852-2db3-422a-a4f6-1fefa17f497f
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
Fixes 15 CI test flakes that each raced something the test didn't need to test: a wall-clock deadline, an event published before the state it announces, a port or PID another process could take, or garbage another test left for the collector. The tests now wait on the event or condition the code exposes, inject the clock, or remove the dependency, per agent_docs/concurrency.md, instead of widening waits. The Prefect test server's reserved port also sets SO_REUSEADDR now, so uvicorn can bind it on Linux as on macOS.
One race was in product code. IPythonKernel.shutdown() kills a kernel without the cell lock, and the run holding that lock stops the kernel too. jupyter-client fails the later of two overlapping shutdown_kernel() calls with InvalidStateError, and that failed call leaked the zmq context into later tests. A _shutdown_lock now serializes the calls, and _stop() closes the context in a finally, so a cancelled or failed stop can't leak it either.
Bug Fixes
IPythonKernel.shutdown()no longer raisesInvalidStateErroror leaks a zmq context when it kills a kernel the run is also stopping; no other user-visible behavior changes.