Skip to content

fix(swarm): make stop quiesce queued and active worker turns (#1352) - #1362

Closed
ianalitis wants to merge 5 commits into
1jehuang:masterfrom
ianalitis:pr/swarm-stop-quiesce
Closed

ianalitis wants to merge 5 commits into
1jehuang:masterfrom
ianalitis:pr/swarm-stop-quiesce

Conversation

@ianalitis

Copy link
Copy Markdown
Contributor

Fixes #1352.

Problem

swarm stop acknowledged success while the stopped worker kept working. In the
reproduction recorded on #1352, a completed-then-woken scout executed
apply_patch and test invocations after stop returned Stopped agent for
its exact session id, and its subsequent completion report could not reach the
already-removed membership.

handle_comm_stop removed the session entry and interrupt queue and then tried
agent_arc.try_lock() to mark the session closed. That path never requested
cancellation, so a busy turn kept streaming, and a wake reserved before the stop
could still start provider work afterwards.

Fix

Stop now, in this order:

  1. marks the member stopping and closes the per-session interrupt-delivery
    gate, so already-admitted queue producers drain and later live or persisted
    enqueues are refused until an explicit resume;
  2. acquires and retains the terminal Agent guard while repeatedly firing the
    session's registered cancel signals, bounded at 5s, so a turn that registers
    its cancellation signal after stop began cannot miss it;
  3. performs verified live and persisted queue clears, mark_closed, interrupt
    queue teardown, membership removal and the terminal Done with that guard
    still held.

A stop that cannot quiesce leaves membership, Agent and the closed gate intact
and returns a retryable error instead of Done, so a later stop resumes rather
than reporting an unknown session. stopping members are also excluded from
headless startup recovery, and the gate follows session renames and is reopened
by queue registration for a new or resumed lifecycle.

This reuses existing primitives instead of adding a second cancellation
registry: SessionControlHandle::request_cancel (whose turn-cancel registry
already reaches server-initiated turns), the per-session soft-interrupt queues,
and Agent::mark_closed. The guarantee is local turn and tool-dispatch
quiescence; it does not retroactively undo an external effect that began before
cancellation reached a safe point.

Tests

New comm_session_stop_tests module (4 tests) covering the concrete races:

  • a live worker turn streaming while a live and a persisted follow-up are queued:
    stop must end the turn, empty both queues, leave no active-turn signal, avoid a
    second provider call, and preserve an unrelated session;
  • idle_live_agent reserving the Agent before a turn registers its cancel
    signal: the late wake is discarded before provider dispatch;
  • live and persisted queue producers that enter before stop and append after the
    gate closes: stop waits for them, performs a final verified clear, and rejects
    all post-stop enqueues;
  • an uncooperative Agent lock beyond the 5s bound: the target stays registered as
    stopping and a later retry succeeds instead of returning Unknown session.

Evidence (cargo test -p jcode-app-core --lib -- --test-threads=1):

Run Result
comm_session_stop_tests with this change 4 passed, 0 failed
The same 4 tests with the handler reverted to its pre-fix shape 0 passed, 4 failed

Each negative-control failure is the intended reason: the busy turn keeps
streaming after Done, the delivery gate is never closed, and a stop that cannot
quiesce still reports Done instead of a retryable state. cargo fmt -p jcode-app-core -- --check is clean.

Notes and limitations

  • Stop error responses go through one helper; the pre-existing Unknown session
    and ownership-refusal messages are unchanged.
  • Stopped-session delivery-gate tombstones are process-local until an explicit
    resume or a daemon restart.
  • The E1 config-cache fixture fix from our own tree is not included: this
    repository has no E1 receipt tests.
  • The #[expect(clippy::too_many_arguments, ...)] attribute above
    resolve_swarm_spawn_effort is moved back onto spawn_swarm_agent, which is
    the function that takes the 21 arguments. As written on master the
    expectation is unfulfilled, so cargo clippy -p jcode-app-core --lib -- -D warnings fails on that line before reaching anything this change touches. I
    can split that one-line cleanup out if you prefer it separate.
  • jcode-app-core currently cannot pass cargo clippy --all-targets --all-features -- -D warnings on master for two unrelated reasons: nine
    never-constructed items in tool/goal.rs (the tool was disabled by removing
    only its registry line) and two unused imports in test modules. I left both
    alone; happy to send them as separate focused PRs.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High impact] The reviewed changes are safe to merge. Both numbered previous findings are addressed, and no blocking issues remain.

Summary

swarm stop now cancels active work and drains queued work before reporting success. A stop that times out keeps the worker available for another stop attempt.

  • Stopping a worker waits until its turns and queued work are quiet.
  • A stopping worker refuses new turns and interrupt messages.

Reviews (7) · Last reviewed commit: "fix(server): reserve admitted turns and ..." · Reviewed by Greptile

@greptile-apps

This comment has been minimized.

@ianalitis

Copy link
Copy Markdown
Contributor Author

Addressed the review finding in 2a8c4e8dc.

What was wrong: after a stop times out, the target stays resolvable with an open Agent (that is deliberate, so a retry can finish). Interrupt delivery is already closed by then, but queue_interrupt: / queue_interrupt_urgent: called Agent::queue_soft_interrupt directly, which only rejects a closed Agent. So the command reported queued while the session was stopping, leaving an interrupt pending across the failed-stop interval.

Fix: DebugInterruptContext now carries the session map, and both commands queue through the gate-aware queue_soft_interrupt_for_session path when a context is present, returning an error instead of queued while delivery is closed. The direct-Agent fallback is untouched for callers with no session context.

Regression: stopped_but_unquiesced_worker_rejects_debug_queued_interrupts holds the Agent lock so the stop times out, then asserts delivery is closed, the debug command errors rather than returning queued, and neither the live nor persisted queue holds anything. The debug call is time-bounded so the pre-fix behaviour fails on timeout instead of wedging the suite.

Run Result
comm_session_stop_tests with this change 5 passed, 0 failed
The new test with the gate routing reverted 1 failed in 7s, a stopping session must not block a debug-queued interrupt on the busy Agent: Elapsed(())

Also checked the neighbouring suites: server::comm_session 37 passed / 4 failed, server::debug_* 30 passed / 1 failed, server::queue_tests 2 passed / 1 failed. Every one of those five failures also fails on a checkout without this change, so none is a regression. cargo fmt -p jcode-app-core -- --check is clean.

@ianalitis

Copy link
Copy Markdown
Contributor Author

Friendly ping: the review finding is addressed at the current head (see my reply above), the branch is still mergeable against master, and the linked issue (#1352) still reproduces on 691c6f526. Happy to rebase or adjust if you'd like a different approach.

@ianalitis

Copy link
Copy Markdown
Contributor Author

@greptile review

`swarm stop` acknowledged success while a completed-then-woken scout kept
patching and testing (#1352): the handler removed routing and membership and
then only `try_lock`ed the Agent to mark it closed, so a busy turn was never
cancelled and a reserved wake could still start provider work afterwards.

Stop now closes interrupt delivery before clearing, marks the member
`stopping`, drains already-admitted queue producers, and re-fires the
registered cancel signals while it acquires and retains the terminal Agent
guard (5s bound), so a turn that registers its cancellation signal after stop
began cannot miss it. Verified live and persisted clears, `mark_closed`, the
interrupt-queue teardown, membership removal and the terminal `Done` happen
with that guard held. A stop that cannot quiesce leaves membership, Agent and
the closed gate intact and reports a retryable error instead of `Done`, and
`stopping` members are excluded from headless startup recovery.

The guarantee is local turn and tool-dispatch quiescence. It does not
retroactively undo an external effect that began before cancellation reached a
safe point.

Reuses existing primitives rather than adding a second cancellation registry:
`SessionControlHandle::request_cancel` (whose turn_cancel_registry already
reaches server-initiated turns), the per-session soft-interrupt queues, and
`Agent::mark_closed`.

Validation (`cargo test -p jcode-app-core --lib -- --test-threads=1`):
- `comm_session_stop_tests`: 4 passed (busy turn with a queued wake, reserved
  late wake, in-flight queue producers, and a stop timeout retry)
- With the handler reverted to the pre-fix shape, the same 4 tests fail 4/4 for
  the intended reasons (work continues after `Done`, the gate is never closed,
  a timeout reports `Done` instead of a retryable state).
- `cargo fmt -p jcode-app-core -- --check` clean.

Limitation: stopped-session delivery-gate tombstones are process-local until an
explicit resume or a daemon restart.
Review follow-up on the stop-quiescence change (Greptile, PR #1362).

A stop that cannot quiesce deliberately leaves the target resolvable and its
Agent open so a later stop can retry. Interrupt delivery is already closed at
that point, but the debug `queue_interrupt:` and `queue_interrupt_urgent:`
commands called `Agent::queue_soft_interrupt` directly, which only rejects a
closed Agent. They therefore reported `queued` while the session was stopping,
leaving an interrupt pending across the failed-stop interval; if the session was
resumed or reused before the retry, that interrupt could still run.

`DebugInterruptContext` now carries the session map, and both commands queue
through the gate-aware `queue_soft_interrupt_for_session` path when a context is
present, returning an error instead of `queued` while delivery is closed. The
direct-Agent fallback is unchanged for callers without a session context, so the
existing single-shot debug paths keep their behaviour.

New regression `stopped_but_unquiesced_worker_rejects_debug_queued_interrupts`
holds the Agent lock so the stop times out, then asserts delivery is closed, the
debug command errors rather than blocking on the busy Agent or returning
`queued`, and neither the live nor the persisted queue holds anything. The debug
call is time-bounded so the pre-fix behaviour fails on timeout instead of
wedging the suite; with the gate routing removed the test fails in 7s for
exactly that reason.

Validation (`cargo test -p jcode-app-core --lib -- --test-threads=1`):
- `comm_session_stop_tests`: 5 passed, 0 failed
- `server::comm_session`: 37 passed, 4 failed; `server::debug_*`: 30 passed,
  1 failed; `server::queue_tests`: 2 passed, 1 failed. All five failures also
  fail on a checkout without this change (they need a physical path outside the
  source-extracted scratch tree, or are pre-existing on master), so none is a
  regression.
- `cargo fmt -p jcode-app-core -- --check` clean.
`comm_session.rs` crossed the 1494 LOC ratchet entry on this branch, so the
stop/quiesce plumbing shared by `handle_comm_stop` and the live turn loop now
lives in `server/live_turn.rs`, next to the live-turn code it drives, and
`Agent::is_closed` moves to `agent/status.rs`. `comm_session.rs` drops to 1451
LOC and the now-unused interrupt-stop imports are dropped from `server.rs`.

The stop tests keep their own file, declared from `comm_session.rs` with the
same `#[path]` sibling pattern `client_lifecycle.rs` uses, and the two fixtures
they share with `comm_session_tests.rs` are widened to `pub(super)`, which
keeps that test file at its 1415 LOC baseline.

The queued soft-interrupt fixtures also declare `client_id`, which the rebase
onto the mid-turn message work made mandatory.
Closes the two remaining findings on #1362.

- server/live_turn.rs: the tracked-turn end path marked the swarm member
  "ready"/"failed" even when a stop had already set "stopping", so a turn that
  outlived the stop timeout overwrote the stop state. The end status is now
  written only when the member is not stopping; the turn still reports Done.
- server/live_turn.rs + server/client_lifecycle.rs: a client keeps its own
  Agent handle after a stop removed the worker from routing, so a later client
  turn could dispatch provider work for a stopped session. Turn admission now
  runs under the agent lock before the message is recorded or run, rejects a
  closed agent with the same error shape the connection already uses, and owns
  the skill validation so both rejections are decided in one lock acquisition.

Tests: tracked_turn_that_outlived_the_stop_timeout_keeps_the_stopping_status
(comm_session_stop_tests.rs) and
stopped_session_rejects_a_client_turn_before_it_starts (new
client_lifecycle_stop_tests.rs). Both were verified to fail before the fix and
pass after it.
@ianalitis

Copy link
Copy Markdown
Contributor Author

CI follow-up for 5542950: the completed Format job fails only on the two upstream import/module ordering hunks already tracked in #1796. Windows Cross-Target Check fails with the upstream jcode-companion listener E0596 at server.rs:209 tracked in #1803. These are not in this follow-up commit. Linux/macOS/Windows build jobs are still running. Run: https://github.com/1jehuang/jcode/actions/runs/38209936042

xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Use the existing stop marker to fence queue writers. Drain admitted writes before clearing live and persisted queues for each stopped worker.

Ports 1jehuang#1362

Co-authored-by: Iraklis Analitis <[email protected]>
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Upstream-PR: 1jehuang#1357
Upstream-PR-Commit: 1jehuang#1357 0da5e81
Upstream-PR: 1jehuang#1362
Upstream-PR-Commit: 1jehuang#1362 5962058
Upstream-PR: 1jehuang#1486
Upstream-PR-Commit: 1jehuang#1486 fadc624
Upstream-PR: 1jehuang#1733
Upstream-PR-Commit: 1jehuang#1733 01f3415
Upstream-PR: 1jehuang#1750
Upstream-PR-Commit: 1jehuang#1750 1ac0c82
Upstream-PR: 1jehuang#1822
Upstream-PR-Commit: 1jehuang#1822 73f85fc
Upstream-PR: 1jehuang#1912
Upstream-PR-Commit: 1jehuang#1912 36d7682
Upstream-PR: 1jehuang#1978
Upstream-PR-Commit: 1jehuang#1978 0f55643
Upstream-PR: 1jehuang#2007
Upstream-PR-Commit: 1jehuang#2007 638f87c
Upstream-PR: 1jehuang#2213
Upstream-PR-Commit: 1jehuang#2213 c5e1487
Upstream-PR: 1jehuang#2234
Upstream-PR-Commit: 1jehuang#2234 0d4d5d4
Upstream-PR: 1jehuang#2266
Upstream-PR-Commit: 1jehuang#2266 217ddc2
Upstream-PR: 1jehuang#2267
Upstream-PR-Commit: 1jehuang#2267 e98c40b
@ianalitis ianalitis closed this by deleting the head repository Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

swarm stop acknowledges before queued and active owned work is cancelled

1 participant