Skip to content

fix(terminal): close the create and delete teardown races under the lifecycle lock (#1458, #1468) - #1463

Open
plauzy wants to merge 2 commits into
awslabs:mainfrom
plauzy:fix/1458-create-terminal-teardown-race
Open

plauzy wants to merge 2 commits into
awslabs:mainfrom
plauzy:fix/1458-create-terminal-teardown-race

Conversation

@plauzy

@plauzy plauzy commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1458
Closes #1468

This PR has two commits. The two fixes close the leak only together, so they ship together:

Commit 1: the create side (#1458)

create_terminal committed its registry row inside session_lifecycle_lock and then released the lock. Only after that did it start the FIFO reader and register the provider. A delete_session for 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 and provider_manager.create_provider now 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_pane and send_special_key) and a provider constructor. The same section already holds the lock across create_session / create_window, which are tmux subprocess calls too.
  • If a registration step fails, the error leaves the section with the created-flags and is re-raised, so the same _roll_back_failed_create runs as before. When pipe_pane raises, attach_output_pipeline stops 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 on main.
  • _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 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 inside create_reader on 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.

new test, 20 fresh processes
main (79aa1a3) 20 / 20 failed
this branch 0 / 20 failed

Failure on main:

E       AssertionError: a same-name teardown ran between the create's lock release and its registration
E       assert False
E        +  where False = is_fully_gone('15f8b850')

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 on 79aa1a36 under the same load, on my machine: 0 / 40 on main and 0 / 40 on this branch, so that run did not reproduce the flake at all.

Existing tests that changed:

  • The cancelled-create row-write test now also asserts that no reader, status buffer or provider is left. It passes on main and on this branch.
  • Two tests took the lifecycle lock from inside a create_provider stub, 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_init in 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_terminal took 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_terminal now takes session_lifecycle_lock(row["tmux_session"]) and re-reads the row once it holds it, as delete_session does. If the row was removed while it waited, it returns True and 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.
  • The teardown itself moves to the unlocked _delete_terminal_locked. The lock is not reentrant (session_lock.py). Two callers already hold it, so they call the inner function:
    • the herdr finished/lost handler, herdr_app_inbox_service._teardown;
    • the herdr closed-workspace cleanup, 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 in fifo_manager.create_reader and deletes the new terminal by id from another thread. No load, no sleeps. Twenty fresh processes per tree:

tree failed
main (79aa1a36) 20 / 20
main + commit 2 only 20 / 20
commit 1 only 20 / 20
both commits 0 / 20
E       AssertionError: a single-terminal delete ran between the create's row write and its registration

Neither commit closes the leak alone:

  • Commit 2 on main: the delete now waits for the lock, but on main the 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.
  • Commit 1 alone: the create holds the lock until its reader and provider are registered, but delete_terminal never 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_terminal

Built from a search of all of src/ and checked independently in review:

caller holds the lock? uses
DELETE /terminals/{terminal_id} (api/main.py, via asyncio.to_thread); the MCP delete_terminal tool and cao agent cancel --delete reach it over HTTP no public
agent_step (via asyncio.to_thread) no public
script_runner (stale cleanup) no public
deferred-init failure, _notify_caller_of_deferred_failure no public
herdr pane.closed, herdr_inbox_service._handle_lifecycle_event no public
herdr_app_inbox_service._teardown yes inner
herdr_inbox_service._cleanup_closed_session (workspace.closed and its retry) yes inner

Not callers:

  • herdr_inbox_service._delete_ghost_terminal_row calls the database function clients.database.delete_terminal. It is the only delete in herdr's startup cleanup and reconcile loops.
  • keep_service uses delete_terminal_row directly.
  • delete_session uses its own locked steps.

Deferred-init failure path: _notify_caller_of_deferred_failure is reached only through await asyncio.to_thread(...), from _surface_deferred_init_failure and _schedule_deferred_init. Both run on the deferred-init task after create_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_event is synchronous and runs on the event loop, so its pane.closed teardown now waits for the lock there. I kept it that way:

  • The same handler's workspace.closed branch already takes this lock on the loop on main, through _cleanup_closed_session.
  • Its teardown already runs blocking tmux and DB calls there.
  • The wait lasts only as long as a create's or a teardown's short locked section.
  • Moving herdr lifecycle handling off the loop would change event ordering and is a separate change.

Tests for commit 2

  • The race test above.
  • Two herdr tests drive _teardown and _cleanup_closed_session under their own lock through the real inner teardown, and fail by timeout on a deadlock. Switched to the public delete_terminal, both fail with "... deadlocked on its own lifecycle lock".
  • Unit tests pin the lock wrapper: the teardown runs under the lock; a row removed while waiting returns True with no second teardown; the no-row and no-session fallthrough. A mutant that removes each of these, or the lock itself, fails a test.
  • Three existing herdr tests patched terminal_service.delete_terminal on 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_create used to ignore fifo_manager.stop_reader returning False, 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_ours docstring 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 0aaa5a49 on the fork branch evidence/pr1463-0aaa5a49.

Create-side race test and delete-side race test: both fail 20 of 20 on the old trees and pass 20 of 20 on the PR head

(The GIF links to the full-quality .webm.)

Screenshot What it shows
Create-side test on main: 20 of 20 runs fail with "a same-name teardown ran between the create's lock release and its registration" test_teardown_cannot_slip_between_create_lock_release_and_runtime_registration on main 6234f1f5 plus the new test file: 20 / 20 failed
Create-side test on the PR head: 0 of 20 runs fail The same test on 962714f2: 0 / 20 failed
Delete-side test on commit 1 only: 20 of 20 runs fail with "a single-terminal delete ran between the create's row write and its registration" test_single_terminal_delete_cannot_slip_between_create_row_and_registration on 3314952f (commit 1 only) plus the new test file: 20 / 20 failed
Delete-side test on the PR head: 0 of 20 runs fail The same test on 962714f2 (both commits): 0 / 20 failed

Command per run, in a fresh process, from a git archive extraction, temp HOME, isolated CAO_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 under pr1463/raw/. The "main + commit 2 only" row of the table above was not re-recorded.

Gates

At head 962714f2 (commit 1 3314952f), on main at 6234f1f5: the targeted teardown, restart, herdr and rollback set passed (294), and the race test failed 0/20 with both commits.

Earlier, at 28fbb3a0 on main at 79aa1a36:

  • pytest test/services test/api -n auto: 10562 passed, 12 skipped, 2 xfailed. This includes test_restart_reattach.py from fix: re-attach output pipelines and seed status on server restart (#1438) #1444.
  • test_session_teardown_atomic.py: 58 passed.
  • That file plus test_restart_reattach.py, the herdr inbox tests (services and backends) and test_creator_rollback_keeps_peers.py: 293 passed.
  • pytest test/backends -k herdr: 379 passed, plus 3 environmental failures in test_herdr_web_view.py (AF_UNIX path too long) that fail the same way without these commits.
  • black, isort, ruff and mypy_ratchet.py pass.

Coverage: Codecov first reported 6 changed lines in terminal_service.py as uncovered. A local --cov run of the unit suite showed that all six are error paths in _roll_back_cancelled_create:

  • a failing reader stop or status clear;
  • cleanup_provider raising;
  • cleanup_provider deferring, 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: when cleanup_provider raises, the row is dropped, and only an explicit False keeps 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.py and test_no_ffi_guard.py that are unrelated to this change). It was not rerun at 28fbb3a0. e2e and live-provider tests were not run locally.

Related, not changed: reattach_surviving_terminals() (#1444) also calls attach_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

@plauzy plauzy self-assigned this Nov 23, 2026
@codecov-commenter

codecov-commenter commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@6234f1f). Learn more about missing BASE report.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1463   +/-   ##
=======================================
  Coverage        ?   94.41%           
=======================================
  Files           ?      309           
  Lines           ?    60715           
  Branches        ?     9881           
=======================================
  Hits            ?    57323           
  Misses          ?     3392           
  Partials        ?        0           
Flag Coverage Δ
unittests 94.41% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@plauzy
plauzy force-pushed the fix/1458-create-terminal-teardown-race branch from e9001c6 to f93e902 Compare November 23, 2026 19:10
@plauzy
plauzy marked this pull request as ready for review November 23, 2026 19:57
@plauzy
plauzy requested review from fanhongy and haofeif November 23, 2026 19:57
@fanhongy

fanhongy commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Review at f93e902

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 delete_session now waits and then takes them all down. provider.initialize() stays outside the lock. I found no lock-order deadlock: the new code under the lock takes only fifo_manager._lock (and provider_manager has no lock), and neither of those ever takes the lifecycle lock. Failed and cancelled creates leave nothing behind, and a deferred provider cleanup keeps the row. The new race test fails on main every time and passes here every time. Two small notes below, no blockers.

P3

P3-1. A single-terminal delete can still slip into the same gap.

  • Where: delete_terminal() in src/cli_agent_orchestrator/services/terminal_service.py (used by DELETE /terminals/{id}).
  • Problem: delete_terminal does not take session_lifecycle_lock. The create commits its row inside the lock, so the row is visible before the reader and provider exist. A delete by id in that moment stops nothing, drops the row, and the create then registers a reader and a provider for a row that is gone. This is the create_terminal registers its FIFO reader and provider after releasing the session lifecycle lock, so a same-name teardown can leave them behind #1458 leak through a different door. It is the same on main, so this PR does not make it worse. A follow-up issue is enough.
  • Evidence (validated: yes). A probe test copies the new test's pause in create_reader, then calls terminal_service.delete_terminal(tid, end_reason="terminal_deleted") from a thread while the create is paused:
    timeout 120 uv run -q pytest test/services/test_probe_1463.py -q -s --no-cov -p no:cacheprovider
    main (79aa1a36):  row: False reader: True provider: True
                      AssertionError: delete_terminal ran inside the create's locked section
    this PR (f93e902): row: False reader: True provider: True
                      AssertionError: delete_terminal ran inside the create's locked section
    
  • Fix: in a follow-up, have the single-terminal delete take session_lifecycle_lock(row["tmux_session"]) around its teardown, as delete_session does. The lock is not reentrant, so check the callers first.

P3-2. One docstring still says FIFO setup runs after the lock.

  • Where: _roll_back_backend_create_if_still_ours, terminal_service.py lines 1236-1237.
  • Problem: it says "Provider initialisation, FIFO setup and the rest of create_terminal run after the lifecycle lock was released". After this PR, FIFO setup and provider registration run inside the lock. Only initialize() and later steps run after it.
  • Evidence: grep -n "FIFO setup" src/cli_agent_orchestrator/services/terminal_service.py gives 1236: Provider initialisation, FIFO setup and the rest of ``create_terminal`` run.
  • Fix: change it to "Provider initialisation and the rest of create_terminal run after ...".

Checked by running

All runs used env -i with an empty HOME, under timeout 300. main means 79aa1a36 with this PR's test file copied in.

Check main this PR
New race test test_teardown_cannot_slip_between_create_lock_release_and_runtime_registration, 5 fresh processes each 5/5 failed (a same-name teardown ran between the create's lock release and its registration) 5/5 passed, about 1.0 s each
test_session_teardown_atomic.py, test_terminal_service.py, _coverage, _full, _inbox_registration, test_restart_reattach.py, test_fifo_reader.py, test_herdr_inbox_registry.py, test_session_service.py, -n 4, 3 runs each 4 failed, 466 passed (the race test and the 3 new cancelled-rollback tests, as expected) 470 passed, 3/3 runs
Issue's flaky test test_teardown_blocked_by_in_flight_create_same_name, 10 runs with 6 busy loops on 16 CPUs 0/10 failed 0/10 failed
Real tmux (isolated TMUX_TMPDIR): how long create_terminal holds the lock, 8 creates median 28.3 ms, max 50.2 ms median 47.3 ms, max 68.9 ms
Real tmux: create plus a same-name delete_session started the moment the row appears, real FifoManager, 10 rounds no hang, nothing left (reader, provider, row, session) no hang, nothing left
  • The new race test is deterministic. It pauses the create inside create_reader and lets go only once the teardown has finished (bug) or is waiting on the lock (fix). No sleeps decide the result.
  • Lock hold time grows by about 19 ms per create, for the same session name only. Other names never wait on it. pipe_pane and send_special_key are libtmux calls with no timeout, but create_session and create_window were already under the same lock, so a hung tmux already stalled this name on main.
  • Restart re-attach (fix: re-attach output pipelines and seed status on server restart (#1438) #1444): reattach_surviving_terminals() still calls attach_output_pipeline(..., replace_existing=True) with no lock, at startup. This PR does not change it, and test_restart_reattach.py passes.
  • herdr and other event-inbox backends: the FIFO step is still skipped. Only create_provider moved under the lock for them. svc.register_terminal still runs after initialize(), outside the lock, as on main.
  • Not checked: a real-tmux create that gets all the way through. In this sandbox the shell never became ready (Shell initialization timed out after 10 seconds) on main and on this PR alike, so the real-tmux rounds only cover lock hold time, rollback and teardown. Also not checked: a real herdr backend, e2e tests and live providers.

CI is green at f93e902 (all 29 checks pass).

Re-check at 36f5919

P3-2 is fixed: the docstring now says only provider initialisation runs after the lock. Nothing else changed in the patch. P3-1 (single-terminal delete takes no lock) stays as a follow-up.

CI is green on this head (29 checks).

Re-check at 28fbb3a

The new commit makes delete_terminal take the session lifecycle lock. That closes our P3-1: a delete by id now waits for the create and then takes everything down. The two herdr callers that already hold the lock now call the unlocked inner teardown, so they do not deadlock. I found one new problem: the post_kill_terminal plugin hook now runs inside the lock.

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) in src/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_lock guards that. This commit wraps the single-terminal teardown in the same lock, and that teardown still dispatches post_kill_terminal. DELETE /terminals/{id} and agent_step call it through asyncio.to_thread, so dispatch_plugin_event finds 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.md says plugins "cannot block ... CAO operations". The docstring of delete_terminal_row (line 7504) still says "the single-terminal delete_terminal path 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 dispatch post_kill_terminal after the lock is released, as session_service.delete_session does. Then update the line 7504 docstring. A test like test_no_plugin_code_runs_inside_the_lifecycle_lock, but through delete_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_terminal was traced. The API route, agent_step and both deferred-init failure paths call it through asyncio.to_thread, outside the lock. herdr pane.closed and script_runner._reconcile_orphans call 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 call delete_terminal.
  • Lock order: under the lock, the teardown takes fifo_manager._lock, the herdr-app _state_lock and _DEFERRED_INIT_SIDECAR_LOCK. None of them ever takes the lifecycle lock. The FIFO reader publishes through call_soon_threadsafe, and nothing in src/ waits on the loop with run_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

@plauzy

plauzy commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Thank you, @fanhongy, for the review and for the probe.

P3-2: fixed in 36f59192. The _roll_back_backend_create_if_still_ours docstring now reads "Provider initialisation and the rest of create_terminal run after the lifecycle lock was released". "FIFO setup" is removed, since FIFO setup and provider registration now run inside the lock. That is the only change in the commit. black, isort and ruff are clean, and test_session_teardown_atomic.py plus test_restart_reattach.py pass (82 passed).

P3-1: agreed. A single-terminal delete still takes no lifecycle lock, and your probe shows the same leak on main and here. I'll handle it in a follow-up issue rather than in this PR, filed as #1468. The fix is to take session_lifecycle_lock(row["tmux_session"]) in delete_terminal.

I checked the callers for reentrancy, as you suggested:

  • herdr_app_inbox_service.py:61-66 already holds the lock when it calls delete_terminal, so it needs an unlocked inner variant or it would self-deadlock.
  • The API route, agent_step and script_runner do not hold it.
  • I have not yet traced every path into the deferred-init failure caller.

Co-authored-by: Kiro Agent 244629292+kiro-agent@users.noreply.github.com

@plauzy
plauzy enabled auto-merge (squash) November 24, 2026 01:00
@plauzy

plauzy commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@fanhongy, an update on P3-1 from your review: it is now in this PR as a second commit, 28fbb3a0, rather than a follow-up (#1468).

The reason is a race test that pauses a create in create_reader and deletes the new terminal by id from another thread. It fails 20/20 on main, 20/20 with only the delete-side lock, and 20/20 with only the first commit; it fails 0/20 with both. On main the create releases the lock before it registers anything, so locking the delete alone does not help.

delete_terminal now takes session_lifecycle_lock and re-reads the row under it; the teardown moved to an unlocked _delete_terminal_locked. Two herdr callers already hold the lock and use the inner function:

  • herdr_app_inbox_service._teardown;
  • herdr_inbox_service._cleanup_closed_session, which was a self-deadlock with the public function. We found it in review.

New tests cover:

  • the race;
  • both herdr paths under their own lock, which fail by timeout on a deadlock;
  • the wrapper's re-read, the case of a row removed while waiting, and the no-row fallthrough.

Would you take another look at the second commit when you have time?

@plauzy plauzy changed the title fix(terminal): register a create's FIFO reader and provider under the lifecycle lock (#1458) fix(terminal): close the create and delete teardown races under the lifecycle lock (#1458, #1468) Nov 24, 2026
plauzy added a commit to plauzy/cli-agent-orchestrator that referenced this pull request Nov 24, 2026
…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>
@plauzy
plauzy force-pushed the fix/1458-create-terminal-teardown-race branch from 28fbb3a to 962714f Compare November 24, 2026 05:53
plauzy and others added 2 commits November 24, 2026 01:01
… 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>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants