Skip to content

fix(server): drain metadata writes on detach and scope registrations to the attachment - #4930

Draft
pcbeingused33 wants to merge 4 commits into
docker:mainfrom
pcbeingused33:fix/listen-tab-close-detach
Draft

pcbeingused33 wants to merge 4 commits into
docker:mainfrom
pcbeingused33:fix/listen-tab-close-detach

Conversation

@pcbeingused33

@pcbeingused33 pcbeingused33 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Refs #4909 (follow-up to #4931, which closed it)

#4931 added RuntimeAttachment.Detach for closed --listen TUI tabs. This PR covers two gaps it leaves.

Detach and same-ID handoff can race an in-flight metadata write or deletion. Detach marks the attachment closing, so new writes are rejected, while a write that already passed that check (UpdateSessionTitle, SetSessionAgentModel, and similar under modelSwitch) may still be persisting. finishDetach now also checks modelSwitch: if held, it releases the streaming guard and drains modelSwitch in a goroutine before retrying teardown so Detach and finishDetach still never block. When AttachRuntime replaces an attachment for the same session ID while a metadata write or DeleteSession is still in flight, it holds the replacement's modelSwitch until the prior operation finishes:

  • If the previous attachment committed metadata updates, those committed fields are applied to the replacement's session (and forwarded across chained replacements) before the replacement's own writes persist, so a clone taken before persistence cannot revert a different field.
  • If a racing DeleteSession succeeds (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 with ErrSessionNotRunning instead of upserting the deleted row back. If DeleteSession fails, queued updates on the replacement proceed normally.

Only that session ID waits, and AttachRuntime itself does not block.

Registrations are not tied to the attachment. The --listen wiring registered the tab's event source and follow-up injector by session ID. If an app.Opt runs 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. RuntimeAttachment now has RegisterEventSource and RegisterFollowUpInjector, which are no-ops unless that attachment is still the live, non-closing, non-deleting one for its ID under sm.mux. cmd/root/run_listen.go uses them; the SessionManager methods are unchanged.

Tests

  • TestDetachRuntime_WaitsForInFlightMetadataWrite holds a title write in the store and checks that the session stays registered until the write is persisted.
  • TestDetachRuntime_ReattachWaitsForInFlightMetadataWrite parks 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_ReattachPreservesDrainedMetadataFields parks SetSessionAgentModel in UpdateSession, reattaches a clone, and renames the replacement: both the model override and the new title survive.
  • TestDetachRuntime_ReattachDuringDeleteRejectsQueuedUpdate and TestDetachRuntime_ReattachDuringFailedDeleteAllowsQueuedUpdate park DeleteSession, reattach the same ID, and queue a title update: a successful delete rejects the update with ErrSessionNotRunning and leaves the row deleted, while a failed delete lets the update succeed.
  • TestRuntimeAttachment_RegistrationsAreScopedToTheAttachment checks 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/ and go test -race ./pkg/session/ pass.

This change was prepared with the help of an AI coding assistant and submitted by a human contributor.

@pcbeingused33
pcbeingused33 requested a review from a team as a code owner November 14, 2026 01:41
@aheritier aheritier added area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/fix PR fixes a bug (maps to fix:). Use on PRs only. labels Nov 14, 2026

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread cmd/root/run.go Outdated
// (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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread pkg/server/session_manager.go Outdated
if rs.cancel != nil {
rs.cancel()
}
sm.runtimeSessions.Delete(sessionID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread pkg/server/session_manager.go Outdated
rs.cancel()
}
sm.runtimeSessions.Delete(sessionID)
sm.dropEventLog(sessionID)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@aheritier
aheritier marked this pull request as draft November 21, 2026 06:41
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review. Pushed b59a330 (on top of a merge of current main), addressing the three blocking points:

  • Initial tab: runOrExec now wraps the TUI cleanup with detachOnCleanup, so closing the initial --listen tab detaches it like spawned tabs. Covered by TestDetachOnCleanupReleasesListenSession.
  • Recall handler: DetachRuntime now clears the handler installed by AttachRuntime (TestSessionManager_DetachRuntimeClearsRecallHandler).
  • Event log tombstone: detach now uses a new releaseEventLog that tears down the log without tombstoning the ID, so the same session ID can be reattached and register a new source (TestSessionManager_DetachRuntimeAllowsReattach).

go test ./pkg/server/ -race passes; in ./cmd/root/, TestBannerAnimationCapability fails identically without our change, everything else passes.

This comment was drafted with the help of an AI assistant (Claude Code) and the change was tested locally.

@aheritier
aheritier self-requested a review November 25, 2026 13:07
@aheritier
aheritier marked this pull request as ready for review November 25, 2026 13:07
Copilot AI balanced review requested due to automatic review settings November 25, 2026 13:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment on lines +351 to +353
if pe, ok := sm.eventLogs.Load(sessionID); ok {
pe.cancel()
sm.eventLogs.Delete(sessionID)
Comment thread pkg/server/session_manager.go Outdated
Comment on lines +493 to +496
if rs.cancel != nil {
rs.cancel()
}
sm.runtimeSessions.Delete(sessionID)
Comment thread pkg/server/session_manager.go Outdated
Comment on lines +493 to +496
if rs.cancel != nil {
rs.cancel()
}
sm.runtimeSessions.Delete(sessionID)
@aheritier

Copy link
Copy Markdown
Collaborator

Please mark this PR ready for review once you’ve addressed the copilot feedback.

@aheritier aheritier closed this Nov 25, 2026
@aheritier aheritier reopened this Nov 27, 2026
@aheritier
aheritier marked this pull request as draft November 27, 2026 11:13
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Addressed the three Copilot findings in e8ad8b0:

  • Event IDs: a detach now keeps the last sequence number, so a reattached session continues from it, and a client resuming from before the detach gets a gap.
  • Metadata writes: DetachRuntime waits for an in-flight modelSwitch transaction, outside sm.mux as deleteSession does, before the session looks inactive. An update arriving during that wait gets ErrSessionNotRunning, as during deletion.
  • Attach/detach race: both now go through one lifecycle mutex.

The new tests fail on the previous head and go test ./pkg/server/ -race passes with the change.

This comment was drafted with AI assistance.

@pcbeingused33
pcbeingused33 marked this pull request as ready for review November 27, 2026 13:58

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. deleteSession clears rs.deleting on a store error even if detach has also set it. An active metadata write can then pass runtimeActive after detach drains modelSwitch but 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 call RegisterEventSource or RegisterFollowUpInjector after 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.

Comment thread pkg/server/session_manager.go Outdated
// 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()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Addressed the three points in e8e141b:

  • Lock scope: the attach/detach lock is now per session ID. The gated-write test also checks that another ID can attach while a same-ID reattach still waits.
  • Failed DELETE: detach has its own marker, which the delete error path does not reset.
  • Late registrations: RegisterEventSource and RegisterFollowUpInjector are no-ops for a detached session until it is attached again. This is keyed on the session ID, so it does not tell an old owner's call apart from the new one after a same-ID reattach; that would need an ownership handle in the API, which I can add if you prefer.

go test ./pkg/server/ -race passes. In ./cmd/root/, only TestBannerAnimationCapability fails, as it did before this change.

This comment was drafted with AI assistance.

@aheritier
aheritier self-requested a review November 28, 2026 22:39

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@aheritier
aheritier marked this pull request as draft November 30, 2026 17:12
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Pushed a fix for the remaining blocker. AttachRuntime now returns an *Attachment: it is still the session's stream lock, and it carries RegisterEventSource and RegisterFollowUpInjector scoped to that attachment. Both are no-ops once it has been detached, deleted or replaced, and the --listen tab wiring uses them.

TestAttachment_StaleRegistrationsDoNotOverwriteReplacement makes both stale calls after the replacement is fully registered; with the ownership check disabled, both overwrite it. The Register* methods on SessionManager are unchanged and still target the current attachment, so an embedder whose owner can outlive its attachment should use the handle.

go test ./pkg/server/ -race passes. In ./cmd/root/, only TestBannerAnimationCapability fails, as before.

This comment was drafted with AI assistance.

@aheritier aheritier added the status/needs-rebase PR has merge conflicts or is out of date with main label Dec 1, 2026
@aheritier

Copy link
Copy Markdown
Collaborator

👋 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.

@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks, @aheritier. #4931 has landed on main and covers detaching both the initial and newly opened --listen tabs. Would you prefer that we rebase this PR to keep just the two remaining safeguards (waiting for in-flight metadata writes before marking the session inactive, and scoping event source and follow-up injector registration to the owning attachment), or should we close it as superseded by #4931?

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>
@pcbeingused33
pcbeingused33 force-pushed the fix/listen-tab-close-detach branch from 1d2dadd to 868592a Compare December 2, 2026 22:36
@pcbeingused33 pcbeingused33 changed the title fix(server): detach the attached runtime when a --listen TUI tab closes fix(server): drain metadata writes on detach and scope registrations to the attachment Dec 2, 2026
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Since #4931 landed, main already detaches the runtime when a --listen tab closes, so I rebuilt this branch on top of it and trimmed it to the two things #4931 doesn't cover. First, a detach now waits for an in-flight metadata write, such as a title or model change, before the session can look inactive. The wait happens in finishDetach, which still never blocks. Second, RuntimeAttachment gains RegisterEventSource and RegisterFollowUpInjector, which do nothing once that attachment has been detached or replaced. The rest of the old branch is gone: the per-ID lifecycle lock, the detached-session set and the event-sequence bookkeeping duplicated what #4931 does. That's why this is a force-push.

This comment was drafted with AI assistance.

@aheritier aheritier removed the status/needs-rebase PR has merge conflicts or is out of date with main label Dec 2, 2026
@pcbeingused33
pcbeingused33 marked this pull request as ready for review December 3, 2026 11:42
Signed-off-by: Alex <alex.castillog33@gmail.com>

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@aheritier
aheritier marked this pull request as draft December 4, 2026 12:44
@aheritier

Copy link
Copy Markdown
Collaborator

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>
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks. Both blockers are fixed in acd2db3:

  • Retry vs. the streaming guard: when finishDetach finds modelSwitch held, it now releases rs.streaming before starting the drain goroutine. If the retry then fails its TryLock on the guard, the holder took it after that release, so its unlockStream calls finishDetach again and the attachment cannot be left registered.
  • Same-ID reattachment: AttachRuntime swaps the entry in with the replacement's modelSwitch held, then checks the previous attachment's modelSwitch. If a write is still in flight there, a goroutine waits for it before releasing the replacement's lock; otherwise it is released right away. The check happens after the swap, when no new write can pass runtimeActive on the old attachment. Only that session ID waits, and AttachRuntime does not block.

TestDetachRuntime_ReattachWaitsForInFlightMetadataWrite extends the gated-write test: it parks the old title write, detaches, reattaches the same ID and writes a newer title on the replacement. On the previous head the newer write returns at once and the stored title ends up old; with the change it waits and new survives. It also checks that another session ID can be written while the old write is parked. go test -race ./pkg/server/ passes.

This comment was drafted with Claude Code.

@pcbeingused33
pcbeingused33 marked this pull request as ready for review December 4, 2026 13:00

@aheritier aheritier left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two blocking issues in the same-ID handoff: a replacement can discard a committed metadata change or recreate a deleted session.

Comment thread pkg/server/session_manager.go Outdated
go func() {
prev.modelSwitch.Lock()
prev.modelSwitch.Unlock() //nolint:gocritic,staticcheck // empty critical section: drain only
rs.modelSwitch.Unlock()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@aheritier
aheritier marked this pull request as draft December 4, 2026 15:12
…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>
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks for catching both handoff races. Fixed in 92b285e:

  • Committed metadata from the drained write: activeRuntimes now records committed metadata updates (model overrides, title, safety policy, permissions) on modelSwitch release when a same-ID replacement is draining it. drainReplacedAttachment applies those committed fields to the replacement's session (and forwards them if another replacement is chained behind it) before releasing the replacement's modelSwitch, so a clone taken before the old write persisted cannot revert a different field.
  • Deletion result through the handoff: deleteSession tracks in-flight deletions (deleteDone) and monotonic completion (deleted), and AttachRuntime links same-ID replacements onto the deleting attachment's chain. If DELETE succeeds, finishSessionDeletion tears down the replacement chain (cancelling it, dropping registrations, and marking it deleted) before waking the drain, so queued updates fail with ErrSessionNotRunning and the row stays deleted. If DELETE fails, the chain is cleared and queued updates on the replacement proceed.

Added three gated regressions:

  • TestDetachRuntime_ReattachPreservesDrainedMetadataFields parks SetSessionAgentModel in UpdateSession, reattaches a clone, and renames the replacement; both the model override and the new title survive in the store and live session.
  • TestDetachRuntime_ReattachDuringDeleteRejectsQueuedUpdate parks DeleteSession, reattaches the same ID, and queues a title update; after DELETE succeeds, the queued update gets ErrSessionNotRunning, the replacement is unregistered, and the row stays deleted.
  • TestDetachRuntime_ReattachDuringFailedDeleteAllowsQueuedUpdate covers the failed-DELETE counterpart so the replacement still becomes writable.

go test ./pkg/server/ -race and go test ./pkg/session/ -race pass.

This comment was drafted with AI assistance.

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

area/runtime Runtime engine, agent loop execution, tool dispatch, loop detection kind/fix PR fixes a bug (maps to fix:). Use on PRs only.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants