Repository navigation
fix(terminal): close the create and delete teardown races under the lifecycle lock (#1458, #1468) - #1463
fix(terminal): close the create and delete teardown races under the lifecycle lock (#1458, #1468)#1463plauzy wants to merge 2 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1463 +/- ##
=======================================
Coverage ? 94.41%
=======================================
Files ? 309
Lines ? 60715
Branches ? 9881
=======================================
Hits ? 57323
Misses ? 3392
Partials ? 0
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
e9001c6 to
f93e902
Compare
|
Review at The fix is right. The FIFO reader, pipe-pane, the prompt nudge and the provider are now registered while the create still holds the lifecycle lock. A same-name P3P3-1. A single-terminal delete can still slip into the same gap.
P3-2. One docstring still says FIFO setup runs after the lock.
Checked by runningAll runs used
CI is green at Re-check at
|
| Item | Status | How checked |
|---|---|---|
P3-1. delete_terminal takes no lifecycle lock |
✅ Fixed | Our probe (delete by id while the create is paused in create_reader): at 36f5919 the delete finished while the create was paused and left reader: True provider: True. At 28fbb3a the delete waits and leaves row: False reader: False provider: False. |
| P3-2. Stale "FIFO setup" docstring | ✅ Fixed (in 36f5919) |
Line 1236 now reads "Provider initialisation and the rest of create_terminal run ...". |
P2
P2-1. The post_kill_terminal plugin hook now runs inside the lifecycle lock.
- Where:
delete_terminal()→_delete_terminal_locked()→delete_terminal_row(..., registry=registry)insrc/cli_agent_orchestrator/services/terminal_service.py. - Problem: fix(sessions): make session teardown atomic so tmux and the registry cannot diverge #498 moved plugin hooks out of the lock for session teardown, and
test_no_plugin_code_runs_inside_the_lifecycle_lockguards that. This commit wraps the single-terminal teardown in the same lock, and that teardown still dispatchespost_kill_terminal.DELETE /terminals/{id}andagent_stepcall it throughasyncio.to_thread, sodispatch_plugin_eventfinds no running loop and runs the hook inline, with the lock held. A slow hook now stalls every create and delete for that session name. A hook that asks CAO for a terminal in the same session waits on the lock its own delete holds.docs/plugins.mdsays plugins "cannot block ... CAO operations". The docstring ofdelete_terminal_row(line 7504) still says "the single-terminaldelete_terminalpath holds no such lock". - Evidence (validated: yes). A probe uses the repo test's own check: the hook tries to take the session lock without blocking. A second hook takes the same-session lock from another thread, as a create would, and waits 2 s. Both call
delete_terminal(tid, registry=..., end_reason="deleted")from a worker thread, like the API.timeout 300 uv run -q pytest test/services/test_probe_1463_plugin.py -q -s --no-cov -p no:cacheprovider 36f5919: PROBE1 hook_saw=[('post_kill_terminal', True)] PROBE2 same_session_lock_within_2s=True -> 2 passed 28fbb3a: PROBE1 hook_saw=[('post_kill_terminal', False)] AssertionError: plugin hook ran while the lifecycle lock was held PROBE2 same_session_lock_within_2s=False AssertionError: a same-session create inside a post_kill_terminal hook stalls - Fix: run the locked teardown with
registry=None, keep the metadata and the "deleted" result, and dispatchpost_kill_terminalafter the lock is released, assession_service.delete_sessiondoes. Then update the line 7504 docstring. A test liketest_no_plugin_code_runs_inside_the_lifecycle_lock, but throughdelete_terminal, would guard it.
Checked by running
All runs used env -i with an empty HOME, under timeout 300. "Src reverted" means 28fbb3a with src/ set back to 36f5919 and the new tests kept.
| Check | Result |
|---|---|
New race test test_single_terminal_delete_cannot_slip_between_create_row_and_registration |
Passes on 28fbb3a. Fails with src reverted ("a single-terminal delete ran between the create's row write and its registration"). |
New herdr deadlock tests, with only the two herdr callers switched back to the locked delete_terminal |
6 fail, including "_teardown deadlocked on its own lifecycle lock" and "_cleanup_closed_session deadlocked". So the tests catch a re-entry. |
New tests plus herdr suites on 28fbb3a |
188 passed |
Nearby suites (test_session_teardown_atomic, test_terminal_service* ×5, test_restart_reattach, test_fifo_reader, test_herdr_inbox_registry, test_session_service, test_herdr_app_inbox_service, backends/test_herdr_inbox_service, backends/test_herdr_exact_cleanup), -n 4, 3 runs |
678 passed, 3/3 runs, no flakes |
- Re-entry: every caller of the locked
delete_terminalwas traced. The API route,agent_stepand both deferred-init failure paths call it throughasyncio.to_thread, outside the lock. herdrpane.closedandscript_runner._reconcile_orphanscall it on the event loop, outside the lock. The callers that hold the lock (herdr-app_teardown, herdr_cleanup_closed_session) use_delete_terminal_locked.session_service.delete_session, the herdr reconcile and startup cleanup, and the create rollbacks never calldelete_terminal. - Lock order: under the lock, the teardown takes
fifo_manager._lock, the herdr-app_state_lockand_DEFERRED_INIT_SIDECAR_LOCK. None of them ever takes the lifecycle lock. The FIFO reader publishes throughcall_soon_threadsafe, and nothing insrc/waits on the loop withrun_coroutine_threadsafe. So no thread holds the lock while it waits on the loop. - Not checked: real tmux and a real herdr backend, e2e tests and live providers.
CI is green at 28fbb3a (29 checks pass).
Suggest approval at 36f5919 withdrawn.
Re-check at 962714f
This push rebases on main (v2.5.5). It also changes the first commit: a cancelled create now keeps the row when stop_reader returns False. That matches dismantle_terminal_runtime, and test/services/test_session_teardown_atomic.py gives 59 passed.
The second commit (delete_terminal lock) is the same as before, so P2-1 is still open. My probe still fails on this head: hook_saw=[('post_kill_terminal', False)] and same_session_lock_within_2s=False (2 failed).
Vote: ⛔ Hold (score 3: one P2)
independently reviewed by Kiro Crew
f93e902 to
36f5919
Compare
|
Thank you, @fanhongy, for the review and for the probe. P3-2: fixed in P3-1: agreed. A single-terminal delete still takes no lifecycle lock, and your probe shows the same leak on I checked the callers for reentrancy, as you suggested:
Co-authored-by: Kiro Agent 244629292+kiro-agent@users.noreply.github.com |
|
@fanhongy, an update on P3-1 from your review: it is now in this PR as a second commit, The reason is a race test that pauses a create in
New tests cover:
Would you take another look at the second commit when you have time? |
…slabs#1468) A create commits its row first and then registers its FIFO reader and provider. delete_terminal took no lock, so a delete by id that ran in that gap stopped nothing, dropped the row and returned; the create then registered a reader and a provider for a row that was gone. - delete_terminal now takes session_lifecycle_lock for the terminal's session and re-reads the row once it holds it, as delete_session does. With awslabs#1463 a create keeps that lock until its reader and provider are registered, so the delete waits and then tears them down. - The teardown itself moves to _delete_terminal_locked. Two callers already hold the lock, which is not reentrant, so they call the inner function: herdr_app_inbox_service._teardown and the herdr closed-workspace cleanup (herdr_inbox_service._cleanup_closed_session), whose rows are all listed for the session it has locked. - Every other caller (DELETE /terminals/{id}, agent_step, script_runner, the deferred-init failure path and herdr pane.closed) holds no lock and keeps the public one. Tests: a deterministic test pauses a create in create_reader and deletes the new terminal by id from another thread; it fails on main, on main with this change alone and on awslabs#1463 alone, and passes with both. Two herdr tests drive _teardown and the closed-workspace cleanup under their own lock through the real inner teardown and fail by timeout if either deadlocks. Unit tests pin the re-read under the lock, a row removed while waiting (True, no second teardown) and the no-row fallthrough. Depends on awslabs#1463. Closes awslabs#1468 Co-authored-by: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
28fbb3a to
962714f
Compare
… lifecycle lock (awslabs#1458) create_terminal committed its registry row inside session_lifecycle_lock, then released the lock and only afterwards started the FIFO reader and registered the provider. A same-name delete_session waiting on the lock could run in that gap: it saw the new row, stopped a reader and cleaned up a provider that did not exist yet, and returned. The create then registered both for a terminal whose row was gone. - Move attach_output_pipeline (the FIFO reader and pipe-pane attach), the prompt nudge and provider_manager.create_provider into the locked critical section, after the row write. provider.initialize() still runs after the lock is released, so a teardown never waits behind an agent launch. - A registration failure is handed out with the created-flags and re-raised, so the same _roll_back_failed_create runs as before. - _roll_back_cancelled_create now also stops the reader, clears the status buffer and releases the provider, because a cancelled create's worker has registered them by the time it returns. The row is kept when the provider defers its cleanup or the reader does not stop (stop_reader returns False), as dismantle_terminal_runtime keeps it; otherwise it is dropped. Tests: a deterministic test pauses the create at create_reader and fails on main every time; the cancelled-create test now checks no reader, status buffer or provider is left; two tests that took the lock from inside create_provider now inject at the first step after the lock is released. A pipe-pane failure inside the lock rolls the create back with no reader or provider left. The cancelled-create compensation is tested with a failing reader stop, a raising provider cleanup (row dropped) and a deferred one (row kept). Closes awslabs#1458 Co-authored-by: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
…slabs#1468) A create commits its row first and then registers its FIFO reader and provider. delete_terminal took no lock, so a delete by id that ran in that gap stopped nothing, dropped the row and returned; the create then registered a reader and a provider for a row that was gone. - delete_terminal now takes session_lifecycle_lock for the terminal's session and re-reads the row once it holds it, as delete_session does. With awslabs#1463 a create keeps that lock until its reader and provider are registered, so the delete waits and then tears them down. - The teardown itself moves to _delete_terminal_locked. Two callers already hold the lock, which is not reentrant, so they call the inner function: herdr_app_inbox_service._teardown and the herdr closed-workspace cleanup (herdr_inbox_service._cleanup_closed_session), whose rows are all listed for the session it has locked. - Every other caller (DELETE /terminals/{id}, agent_step, script_runner, the deferred-init failure path and herdr pane.closed) holds no lock and keeps the public one. Tests: a deterministic test pauses a create in create_reader and deletes the new terminal by id from another thread; it fails on main, on main with this change alone and on awslabs#1463 alone, and passes with both. Two herdr tests drive _teardown and the closed-workspace cleanup under their own lock through the real inner teardown and fail by timeout if either deadlocks. Unit tests pin the re-read under the lock, a row removed while waiting (True, no second teardown) and the no-row fallthrough. Depends on awslabs#1463. Closes awslabs#1468 Co-authored-by: Kiro Agent <244629292+kiro-agent@users.noreply.github.com>
962714f to
7a8a281
Compare
Closes #1458
Closes #1468
This PR has two commits. The two fixes close the leak only together, so they ship together:
session_lifecycle_lock.delete_terminaltakes that same lock. This answers @fanhongy's P3-1 from the review of commit 1, which found the same leak throughDELETE /terminals/{id}.Commit 1: the create side (#1458)
create_terminalcommitted its registry row insidesession_lifecycle_lockand then released the lock. Only after that did it start the FIFO reader and register the provider. Adelete_sessionfor the same name that was waiting on the lock could run in that gap. It saw the new row, stopped a reader and cleaned up a provider that did not exist yet, and returned. The create then registered both for a terminal whose row was gone.attach_output_pipeline(the FIFO reader and pipe-pane attach, factored out by fix: re-attach output pipelines and seed status on server restart (#1438) #1444), the prompt nudge andprovider_manager.create_providernow run inside the locked section, after the row write.provider.initialize()still runs after the lock is released, so a teardown never waits behind an agent launch. Only short work moved: a reader thread start, two tmux subprocess calls (pipe_paneandsend_special_key) and a provider constructor. The same section already holds the lock acrosscreate_session/create_window, which are tmux subprocess calls too._roll_back_failed_createruns as before. Whenpipe_paneraises,attach_output_pipelinestops the reader it started, and the rollback then kills the session (or only the new window), drops the row, and leaves no reader or provider. A new test covers both cases. If a reader already exists, the helper returns early, as it does onmain._roll_back_cancelled_createnow also stops the reader, clears the status buffer and releases the provider, because a cancelled create's worker has registered them by the time it returns. The row is kept only when the provider defers its cleanup, matching the failed-create path.Before / after for commit 1
The evidence is a new deterministic test,
test_teardown_cannot_slip_between_create_lock_release_and_runtime_registration. It pauses the create insidecreate_readeron an event and releases it once the teardown has either finished (the bug) or is waiting on the lock (the fix). It needs no load and no sleeps.Failure on main:
The flaky test from the issue,
test_teardown_blocked_by_in_flight_create_same_name, is a rare flake. With 10 busy-loop processes on 10 CPUs I observed 3 / 40 failures on main and 0 / 40 on this branch, on my machine only. A second run on another machine saw 0 / 30 on both trees, so treat that comparison as weak. Rerun on79aa1a36under the same load, on my machine: 0 / 40 onmainand 0 / 40 on this branch, so that run did not reproduce the flake at all.Existing tests that changed:
create_providerstub, which only worked because construction ran after the lock was released. Their injection moved to the next step after release:provider.initialize()in one,_schedule_deferred_initin the other. They check the same things and pass on main and on this branch.Commit 2: the delete side (#1468)
A create commits its row first and then registers its reader and provider.
delete_terminaltook no lock, so a delete by id in that gap stopped nothing, dropped the row and returned. The create then registered a reader and a provider for a row that was gone.delete_terminalnow takessession_lifecycle_lock(row["tmux_session"])and re-reads the row once it holds it, asdelete_sessiondoes. If the row was removed while it waited, it returnsTrueand does not run a second teardown. With no row, or a row with no session, it runs the old teardown, since there is nothing a create can race with._delete_terminal_locked. The lock is not reentrant (session_lock.py). Two callers already hold it, so they call the inner function:finished/losthandler,herdr_app_inbox_service._teardown;herdr_inbox_service._cleanup_closed_session. It tears down only rows listed for the session it has locked. With the public function it deadlocked on its own lock; review found this, and a test now pins it.The race, both commits together
A new deterministic test,
test_single_terminal_delete_cannot_slip_between_create_row_and_registration, pauses a create infifo_manager.create_readerand deletes the new terminal by id from another thread. No load, no sleeps. Twenty fresh processes per tree:main(79aa1a36)main+ commit 2 onlyNeither commit closes the leak alone:
main: the delete now waits for the lock, but onmainthe create releases it right after the row write, before it registers anything. The delete takes the free lock, sees a row with no reader and no provider, and drops it. The create then registers both.delete_terminalnever asks for it. The committed row is readable, so the delete runs inside the create's locked section.With both, the delete waits until the create's registration is done, then finds and removes the row, reader, status buffer and provider.
Callers of
terminal_service.delete_terminalBuilt from a search of all of
src/and checked independently in review:DELETE /terminals/{terminal_id}(api/main.py, viaasyncio.to_thread); the MCPdelete_terminaltool andcao agent cancel --deletereach it over HTTPagent_step(viaasyncio.to_thread)script_runner(stale cleanup)_notify_caller_of_deferred_failurepane.closed,herdr_inbox_service._handle_lifecycle_eventherdr_app_inbox_service._teardownherdr_inbox_service._cleanup_closed_session(workspace.closedand its retry)Not callers:
herdr_inbox_service._delete_ghost_terminal_rowcalls the database functionclients.database.delete_terminal. It is the only delete in herdr's startup cleanup and reconcile loops.keep_serviceusesdelete_terminal_rowdirectly.delete_sessionuses its own locked steps.Deferred-init failure path:
_notify_caller_of_deferred_failureis reached only throughawait asyncio.to_thread(...), from_surface_deferred_init_failureand_schedule_deferred_init. Both run on the deferred-init task aftercreate_terminal's locked section has returned, and neither takes the lock. So the public function is correct there, and its wait happens on a worker thread.Event loop: herdr's
_handle_lifecycle_eventis synchronous and runs on the event loop, so itspane.closedteardown now waits for the lock there. I kept it that way:workspace.closedbranch already takes this lock on the loop onmain, through_cleanup_closed_session.Tests for commit 2
_teardownand_cleanup_closed_sessionunder their own lock through the real inner teardown, and fail by timeout on a deadlock. Switched to the publicdelete_terminal, both fail with "... deadlocked on its own lifecycle lock".Truewith no second teardown; the no-row and no-session fallthrough. A mutant that removes each of these, or the lock itself, fails a test.terminal_service.delete_terminalon the closed-workspace path. They now patch_delete_terminal_locked; nothing else in them changed.Rollback fix in commit 1 (local review pass)
_roll_back_cancelled_createused to ignorefifo_manager.stop_readerreturningFalse, then delete the row and its retry handle. Now it keeps the row when the reader or the provider cleanup is incomplete, so the existing retry paths can finish the cleanup. A test that fails without the change covers it. The_roll_back_backend_create_if_still_oursdocstring is corrected as well.Media
Real runs of the two deterministic race tests, 20 fresh processes per tree, rendered as a terminal page (the video replays the captured output; the runs took several minutes). Evidence commit
0aaa5a49on the fork branchevidence/pr1463-0aaa5a49.(The GIF links to the full-quality .webm.)
test_teardown_cannot_slip_between_create_lock_release_and_runtime_registrationonmain6234f1f5plus the new test file: 20 / 20 failed962714f2: 0 / 20 failedtest_single_terminal_delete_cannot_slip_between_create_row_and_registrationon3314952f(commit 1 only) plus the new test file: 20 / 20 failed962714f2(both commits): 0 / 20 failedCommand per run, in a fresh process, from a
git archiveextraction, temp HOME, isolatedCAO_HOME_DIR:python -m pytest <node id> -q --no-cov -p no:cacheprovider. Python 3.12, locked dev environment. Raw per-run logs are in the evidence branch underpr1463/raw/. The "main + commit 2 only" row of the table above was not re-recorded.Gates
At head
962714f2(commit 13314952f), onmainat6234f1f5: the targeted teardown, restart, herdr and rollback set passed (294), and the race test failed 0/20 with both commits.Earlier, at
28fbb3a0onmainat79aa1a36:pytest test/services test/api -n auto: 10562 passed, 12 skipped, 2 xfailed. This includestest_restart_reattach.pyfrom fix: re-attach output pipelines and seed status on server restart (#1438) #1444.test_session_teardown_atomic.py: 58 passed.test_restart_reattach.py, the herdr inbox tests (services and backends) andtest_creator_rollback_keeps_peers.py: 293 passed.pytest test/backends -k herdr: 379 passed, plus 3 environmental failures intest_herdr_web_view.py(AF_UNIX path too long) that fail the same way without these commits.mypy_ratchet.pypass.Coverage: Codecov first reported 6 changed lines in
terminal_service.pyas uncovered. A local--covrun of the unit suite showed that all six are error paths in_roll_back_cancelled_create:cleanup_providerraising;cleanup_providerdeferring, which keeps the row.Three tests now call the real function on a seeded incarnation and cover those lines, with no
pragma: no cover. A mutant on each line fails its test. One of them pins the existing contract shared with_roll_back_failed_create: whencleanup_providerraises, the row is dropped, and only an explicitFalsekeeps it.The full unit suite was run locally for that coverage check at commit 1 (29695 passed; 4 environmental failures in
test_herdr_web_view.pyandtest_no_ffi_guard.pythat are unrelated to this change). It was not rerun at28fbb3a0. e2e and live-provider tests were not run locally.Related, not changed:
reattach_surviving_terminals()(#1444) also callsattach_output_pipeline. It runs once at startup before requests are served and takes no lifecycle lock; this PR does not change it.Co-authored-by: Kiro Agent 244629292+kiro-agent@users.noreply.github.com