Repository navigation
fix(server): drain metadata writes on detach and scope registrations to the attachment - #4930
pcbeingused33 wants to merge 4 commits into
Conversation
aheritier
left a comment
There was a problem hiding this comment.
Spawned tabs now leave the active-session list without deleting the stored session, but the fix does not yet cover the full lifecycle in #4909. #4931 addresses the same issue and is a useful comparison for the detach wiring.
Validation: On this commit, the server, TUI, supervisor, and root command package tests passed. Server and supervisor race tests and targeted go vet also passed. Two focused regression tests reproduced the server findings below. The initial-tab finding was verified by tracing the cleanup callbacks, not by an interactive TUI run.
Prior threads: No reviews or review threads; there is no prior human-reviewed commit to compare against.
| // (see recallCoordinatorOpt); release it when the tab goes away so | ||
| // the runtime, event log and injector are not retained. | ||
| if f.listenSM != nil { | ||
| f.listenSM.DetachRuntime(newSess.ID) |
There was a problem hiding this comment.
[blocking] This only detaches tabs created by createSessionSpawner. The initial tab is attached separately by startSessionCoordinator (run_listen.go:75–80), but runOrExec still passes the backend's cleanup directly to the TUI (run.go:559–616). Open a second tab under --listen and close the initial one: the supervisor removes the tab, but its runtime and follow-up injector remain registered and /api/sessions still lists it as active. Wire detachment into the initial tab's cleanup too, and cover both paths with a tab-close regression test.
| if rs.cancel != nil { | ||
| rs.cancel() | ||
| } | ||
| sm.runtimeSessions.Delete(sessionID) |
There was a problem hiding this comment.
[blocking] Removing the runtime from the manager does not undo the recall handler installed by AttachRuntime (session_manager.go:459–460). An embedder that keeps the detached runtime still holds a callback into this manager; an idle recall is routed back to the detached session and rejected instead of falling back to the runtime's steer queue (runtime.go:1492–1514). A focused test with a runtime that implements SetRecallHandler confirmed the handler remains set after detach. Clear the handler installed for that attachment.
| rs.cancel() | ||
| } | ||
| sm.runtimeSessions.Delete(sessionID) | ||
| sm.dropEventLog(sessionID) |
There was a problem hiding this comment.
[blocking] dropEventLog permanently tombstones the session ID (session_manager.go:329–341). The stored session survives, but reattaching that same ID succeeds while RegisterEventSource silently refuses to register its new source (session_manager.go:256–261), so /api/sessions/:id/events returns 404. A focused attach → detach → reload → reattach test reproduced the rejected registration. Tear down the attachment's event log without marking the session deleted, and add a same-ID reattachment test.
|
Thanks for the detailed review. Pushed b59a330 (on top of a merge of current main), addressing the three blocking points:
This comment was drafted with the help of an AI assistant (Claude Code) and the change was tested locally. |
There was a problem hiding this comment.
🟡 Changes recommended
Detachment can reset event IDs and race with reattachment or metadata writes, causing silent event loss, deletion of replacement registrations, and overwritten session updates.
3 open issues
What changed in this PR
This PR addresses retained TUI sessions in --listen mode by adding a detach lifecycle that releases session-manager state without deleting persisted sessions.
Changes:
- Add runtime detachment that cancels attachment state and clears event logs, recall handlers, and follow-up registrations.
- Wire detachment into cleanup for both initial and spawned TUI tabs.
- Add tests for state release, persisted-session preservation, reattachment, and cleanup behavior.
| File | Description |
|---|---|
pkg/server/session_manager.go |
Add runtime detachment and event-log release without tombstoning the session ID. |
pkg/server/server_attached_test.go |
Test detachment, recall-handler cleanup, and reattachment. |
cmd/root/run.go |
Detach initial and spawned sessions during TUI cleanup. |
cmd/root/run_listen.go |
Add a detach-aware cleanup wrapper. |
cmd/root/run_listen_test.go |
Test cleanup with and without a listening session manager. |
Review effort: Balanced
| if pe, ok := sm.eventLogs.Load(sessionID); ok { | ||
| pe.cancel() | ||
| sm.eventLogs.Delete(sessionID) |
| if rs.cancel != nil { | ||
| rs.cancel() | ||
| } | ||
| sm.runtimeSessions.Delete(sessionID) |
| if rs.cancel != nil { | ||
| rs.cancel() | ||
| } | ||
| sm.runtimeSessions.Delete(sessionID) |
|
Please mark this PR ready for review once you’ve addressed the copilot feedback. |
|
Addressed the three Copilot findings in e8ad8b0:
The new tests fail on the previous head and This comment was drafted with AI assistance. |
aheritier
left a comment
There was a problem hiding this comment.
Thanks for wiring cleanup into both the initial and spawned tabs. The detach needs to isolate the session being closed so it cannot stall unrelated tabs.
Prior threads:
- #discussion_r4651151919, #discussion_r4651151920, and #discussion_r4651151921 are addressed: the initial tab now detaches, detach clears the recall handler, and the same session ID can register a new event source.
- #discussion_r4695401080 is addressed: the replacement log continues the old sequence and signals a gap to clients whose cursor predates detach.
- #discussion_r4695401162 is still open when DELETE fails concurrently.
deleteSessionclearsrs.deletingon a store error even if detach has also set it. An active metadata write can then passruntimeActiveafter detach drainsmodelSwitchbut before it removes the entry, reopening the stale-write window. A failed delete must not clear the detach marker. - #discussion_r4695401249 is still open for the ancillary registrations. An embedder can finish
AttachRuntime, race with detach, then callRegisterEventSourceorRegisterFollowUpInjectorafter teardown. Both still accept the session ID without checking attachment ownership, so they can recreate the event pump or retain the injector for a detached runtime.
| // Unlike [SessionManager.DeleteSession], the stored session is kept and the | ||
| // session ID is not tombstoned, so it can be attached again (e.g. a reopened tab). It is a no-op for unknown sessions. | ||
| func (sm *SessionManager) DetachRuntime(sessionID string) { | ||
| sm.attachMu.Lock() |
There was a problem hiding this comment.
[blocking] attachMu is manager-wide and stays held while detach waits on rs.modelSwitch. That lock also covers provider setup for an HTTP run with a model override (session_manager.go:1199–1216), which can wait on a Docker Model Runner pull. If the user closes that tab during setup, opening a different tab blocks the TUI update loop in AttachRuntime. Closing the last tab hits this immediately because the TUI synchronously spawns a replacement (pkg/tui/tui.go:2230–2241). Scope the lifecycle wait to the session ID, and extend the gated-write test to verify that a different ID can attach while same-ID reattachment still waits.
|
Addressed the three points in e8e141b:
This comment was drafted with AI assistance. |
aheritier
left a comment
There was a problem hiding this comment.
One blocker remains: a late registration can overwrite a replacement attachment’s event source and follow-up handler. Please mark the PR ready for review again once this is fixed.
Prior threads:
- #discussion_r4695401249: The detached-ID guard rejects late calls until the same ID is reattached. After the replacement registers its event source and injector, a delayed call from the old attachment can still overwrite either one, so SSE can serve the old runtime’s events and follow-ups can go to the closed tab. Scope both registrations to the attachment that owns them, and add a regression test that attempts both stale registrations after the replacement is fully registered.
|
Pushed a fix for the remaining blocker.
This comment was drafted with AI assistance. |
|
👋 This PR has merge conflicts with the base branch. Please rebase or merge the latest base branch and resolve them. I've added ; it'll be picked back up automatically once the conflicts are cleared. |
|
Thanks, @aheritier. #4931 has landed on main and covers detaching both the initial and newly opened This comment was drafted with Claude Code. |
…to the attachment RuntimeAttachment.Detach dropped the runtimeSessions entry as soon as no stream held the guard, even while a metadata write (title, model override) that passed its runtimeActive check before the detach was still persisting. A later update then took the stored-session path and could be overwritten by the in-flight write. finishDetach now also waits for modelSwitch, retrying from a goroutine so it still never blocks. The --listen wiring registered a tab's event source and follow-up injector by session ID, so a late registration from a closed tab could recreate state for a detached session or overwrite a same-ID replacement. RuntimeAttachment gains RegisterEventSource and RegisterFollowUpInjector, which are no-ops unless the attachment is still the live one, and run_listen.go uses them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Alex <alex.castillog33@gmail.com>
1d2dadd to
868592a
Compare
|
Since #4931 landed, main already detaches the runtime when a This comment was drafted with AI assistance. |
Signed-off-by: Alex <alex.castillog33@gmail.com>
aheritier
left a comment
There was a problem hiding this comment.
Two blockers remain in the metadata drain: the retry can leave a closed attachment registered, and a same-ID replacement can still lose a successful write.
| go func() { | ||
| rs.modelSwitch.Lock() | ||
| rs.modelSwitch.Unlock() //nolint:gocritic,staticcheck // empty critical section: drain only | ||
| sm.finishDetach(sessionID, rs) |
There was a problem hiding this comment.
[blocking] The retry can run before this invocation releases rs.streaming. If the writer releases modelSwitch just after the failed TryLock, the goroutine can acquire and release it, then fail the streaming TryLock at line 613. The original invocation subsequently does a plain rs.streaming.Unlock() at line 616, so neither invocation retries. With no later stream or probe, the closed attachment stays registered and title updates keep returning ErrSessionNotRunning. Ensure the retry cannot run until this invocation has released the streaming guard.
| rs.modelSwitch.Unlock() //nolint:gocritic,staticcheck // empty critical section: drain only | ||
| sm.finishDetach(sessionID, rs) | ||
| }() | ||
| return |
There was a problem hiding this comment.
[blocking] The stale-write window from #discussion_r4695401162 is still reachable through same-ID reattachment. While the old title write is parked in UpdateSession, Detach returns and AttachRuntime can replace the entry with one that has a fresh modelSwitch (lines 476–489). A title update on the replacement can then persist successfully before the old write resumes and overwrites it. Keep writes for the same ID behind the drain even when the attachment is replaced, without blocking other IDs. Extend the gated-write test to cover reattachment and assert that the newer title survives.
|
Please mark this PR ready for review once you’ve addressed the requested changes. Thanks! |
finishDetach now releases the streaming guard before it starts the modelSwitch drain retry, so the retry can no longer fail its TryLock on the guard that the invocation which spawned it still holds. AttachRuntime holds the replacement's modelSwitch until a write still in flight on the previous attachment for the same ID has finished, so a newer write on the replacement cannot persist first and then be overwritten. Other session IDs are not affected and AttachRuntime does not block. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Signed-off-by: Alex <alex.castillog33@gmail.com>
|
Thanks. Both blockers are fixed in acd2db3:
This comment was drafted with Claude Code. |
aheritier
left a comment
There was a problem hiding this comment.
Two blocking issues in the same-ID handoff: a replacement can discard a committed metadata change or recreate a deleted session.
| go func() { | ||
| prev.modelSwitch.Lock() | ||
| prev.modelSwitch.Unlock() //nolint:gocritic,staticcheck // empty critical section: drain only | ||
| rs.modelSwitch.Unlock() |
There was a problem hiding this comment.
[blocking] Waiting for the old write doesn't refresh the replacement's session. If SetSessionAgentModel is parked in UpdateSession, reattach with a clone of the old live session, then rename the replacement. The clone still has the previous override because SetSessionAgentModel updates the live session only after persistence (session_manager.go:2522–2533). Once the drain releases this lock, the rename persists the whole replacement snapshot (:1818–1826), reverting the model change even though both calls succeed. Preserve the drained write's committed fields before the replacement persists, and add a gated test that changes different fields and checks that both survive.
| sm.mux.Lock() | ||
| prev, replaced := sm.runtimeSessions.Load(sessionID) | ||
| rs.modelSwitch.Lock() | ||
| sm.runtimeSessions.Store(sessionID, rs) |
There was a problem hiding this comment.
[blocking] The replacement is published as writable even if the previous attachment is being deleted. If DELETE holds the old modelSwitch just before removing the row, a same-ID reattach publishes rs and a title update queues behind the drain. Once DELETE removes the row and releases the old lock, the queued update passes runtimeActive on rs and upserts the row back. Deletion's identity check leaves the replacement registered (session_manager.go:1167–1180,1202–1204). Carry the deletion result through the handoff so a successful DELETE rejects the queued update. Add a gated regression that verifies the row stays deleted.
…ndoff Carry committed metadata mutations and DeleteSession outcomes across same-ID AttachRuntime replacements while the replacement's modelSwitch drain is held: - Committed metadata updates (model overrides, title, safety policy, permissions) from an in-flight write on the replaced attachment are applied to the replacement's session before its own writes persist, preventing a stale clone from reverting a committed field when updating a different field. - An in-flight or completed DeleteSession on the replaced attachment is propagated through the replacement chain so a successful DELETE tears down the replacement and rejects queued updates with ErrSessionNotRunning instead of upserting the deleted row back, while a failed DELETE still lets queued updates proceed. Signed-off-by: Alex <alex.castillog33@gmail.com>
|
Thanks for catching both handoff races. Fixed in 92b285e:
Added three gated regressions:
This comment was drafted with AI assistance. |

Refs #4909 (follow-up to #4931, which closed it)
#4931 added
RuntimeAttachment.Detachfor closed--listenTUI tabs. This PR covers two gaps it leaves.Detach and same-ID handoff can race an in-flight metadata write or deletion.
Detachmarks the attachment closing, so new writes are rejected, while a write that already passed that check (UpdateSessionTitle,SetSessionAgentModel, and similar undermodelSwitch) may still be persisting.finishDetachnow also checksmodelSwitch: if held, it releases the streaming guard and drainsmodelSwitchin a goroutine before retrying teardown soDetachandfinishDetachstill never block. WhenAttachRuntimereplaces an attachment for the same session ID while a metadata write orDeleteSessionis still in flight, it holds the replacement'smodelSwitchuntil the prior operation finishes:DeleteSessionsucceeds (or has already removed the row), the deletion outcome is carried across the replacement chain so the replacement is torn down and queued updates fail withErrSessionNotRunninginstead of upserting the deleted row back. IfDeleteSessionfails, queued updates on the replacement proceed normally.Only that session ID waits, and
AttachRuntimeitself does not block.Registrations are not tied to the attachment. The
--listenwiring registered the tab's event source and follow-up injector by session ID. If anapp.Optruns late for a tab that was already closed, it recreates an event log and injector for a detached session; if a same-ID attachment replaced it, the late call overwrites the replacement's registrations.RuntimeAttachmentnow hasRegisterEventSourceandRegisterFollowUpInjector, which are no-ops unless that attachment is still the live, non-closing, non-deleting one for its ID undersm.mux.cmd/root/run_listen.gouses them; theSessionManagermethods are unchanged.Tests
TestDetachRuntime_WaitsForInFlightMetadataWriteholds a title write in the store and checks that the session stays registered until the write is persisted.TestDetachRuntime_ReattachWaitsForInFlightMetadataWriteparks a title write on the old attachment, detaches, reattaches the same ID, and writes a newer title on the replacement: the newer title survives, and another session ID can still be written meanwhile.TestDetachRuntime_ReattachPreservesDrainedMetadataFieldsparksSetSessionAgentModelinUpdateSession, reattaches a clone, and renames the replacement: both the model override and the new title survive.TestDetachRuntime_ReattachDuringDeleteRejectsQueuedUpdateandTestDetachRuntime_ReattachDuringFailedDeleteAllowsQueuedUpdateparkDeleteSession, reattach the same ID, and queue a title update: a successful delete rejects the update withErrSessionNotRunningand leaves the row deleted, while a failed delete lets the update succeed.TestRuntimeAttachment_RegistrationsAreScopedToTheAttachmentchecks that a detached attachment registers nothing, and that a stale one cannot replace the event source or injector of a same-ID replacement.go test -race ./pkg/server/andgo test -race ./pkg/session/pass.This change was prepared with the help of an AI coding assistant and submitted by a human contributor.