Release native chat runtimes on lifecycle changes
Ensure /new and chat close stop native foreground and background work before changing registry state. Preserve transcripts while surfacing release and recovery cleanup failures instead of reporting false success, with focused adapter and server regressions.
This commit is contained in:
@@ -2,7 +2,6 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
@@ -53,19 +52,26 @@ func handleChatClose(ctx context.Context, request protocol.Message, broker chatB
|
||||
}
|
||||
resetCompaction()
|
||||
}
|
||||
if err := registry.CloseOperatorSession(ctx, sessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
// A closed chat takes no more turns: prompts it still held are dropped.
|
||||
// Drop queued work before releasing the native runtime so a queued prompt
|
||||
// cannot restart background work after the release succeeds.
|
||||
hub.clearQueue(ctx, sessionID)
|
||||
hub.invalidateRecovery(sessionID)
|
||||
// A harness that keeps the agent alive across restarts (Claude Code's
|
||||
// host) stops it now; the transcript stays and a later prompt resumes it.
|
||||
if releaser, ok := broker.(chatSessionReleaser); ok {
|
||||
if err := releaser.ReleaseSession(ctx, sessionID); err != nil {
|
||||
log.Printf("chat session %s: release after close: %v", sessionID, err)
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " could not be released: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := hub.clearRecovery(ctx, sessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " recovery state could not be cleared: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if err := registry.CloseOperatorSession(ctx, sessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
session, found, err := registry.OperatorSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -43,6 +44,9 @@ func TestChatCloseRecordsClosedState(t *testing.T) {
|
||||
if _, interrupts, _ := broker.counts(); interrupts != 0 {
|
||||
t.Fatalf("idle close interrupted a turn: %d", interrupts)
|
||||
}
|
||||
if released, _ := broker.releaseQuery(); len(released) != 1 || released[0] != "ses_1" {
|
||||
t.Fatalf("released sessions = %v", released)
|
||||
}
|
||||
rows, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -67,6 +71,27 @@ func TestChatCloseRecordsClosedState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCloseReportsReleaseFailureAndKeepsOpenState(t *testing.T) {
|
||||
store := newOperatorStore(t)
|
||||
broker := scriptedChat()
|
||||
broker.releaseErr = errors.New("native runtime unavailable")
|
||||
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := readMessage(t, ctx, conn)
|
||||
if reply.Type != protocol.Error || !strings.Contains(reply.Error, "could not be released") {
|
||||
t.Fatalf("release failure reply = %+v", reply)
|
||||
}
|
||||
row, found, err := store.OperatorSession(ctx, "ses_1")
|
||||
if err != nil || !found || row.ClosedAt != 0 {
|
||||
t.Fatalf("release failure changed registry: row=%+v found=%v err=%v", row, found, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCloseStopsRunningTurn is the close-stops-a-running-turn evidence: a
|
||||
// prompt holds the session (its stream is live), and chat_close from another
|
||||
// connection interrupts it through the existing broker interrupt and reports that
|
||||
|
||||
@@ -206,7 +206,7 @@ func (m *chatManager) Close() {
|
||||
func (m *chatManager) ReleaseSession(ctx context.Context, sessionID string) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
if releaser, ok := adapter.(chatSessionReleaser); ok {
|
||||
return releaser.ReleaseSession(ctx, sessionID)
|
||||
|
||||
@@ -23,8 +23,9 @@ type chatSessionReplacer interface {
|
||||
// The registry is the only place that knows "this chat": every other layer
|
||||
// (rooms, queues, transcripts, shells, exports, resume commands) is keyed by
|
||||
// the native id, so the row is re-keyed in one transaction rather than mapped.
|
||||
// The previous native session is not touched and remains resumable in a
|
||||
// terminal. A running turn is refused rather than abandoned. Every other
|
||||
// The previous native session is released after the fresh session is created;
|
||||
// its transcript remains resumable, but its agent and background work do not
|
||||
// continue. A running turn is refused rather than abandoned. Every other
|
||||
// connection receives the new row as chat_session_changed with PreviousID set,
|
||||
// so its list swaps the row in place and an open conversation follows it.
|
||||
func handleChatNewSession(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, clientID string, write func(protocol.Message) error) {
|
||||
@@ -85,6 +86,20 @@ func handleChatNewSession(ctx context.Context, request protocol.Message, broker
|
||||
fail("session " + created.ID + " was started but manager bootstrap failed while activating pipelines-manager: " + err.Error())
|
||||
return
|
||||
}
|
||||
// Nothing queued for the old context may run after its native runtime is
|
||||
// released, even if the registry move below fails.
|
||||
hub.clearQueue(ctx, oldID)
|
||||
hub.invalidateRecovery(oldID)
|
||||
if releaser, ok := broker.(chatSessionReleaser); ok {
|
||||
if err := releaser.ReleaseSession(ctx, oldID); err != nil {
|
||||
fail("session " + oldID + " could not be released: " + err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := hub.clearRecovery(ctx, oldID); err != nil {
|
||||
fail("session " + oldID + " recovery state could not be cleared: " + err.Error())
|
||||
return
|
||||
}
|
||||
if err := replacer.ReplaceOperatorSession(ctx, oldID, created.ID); err != nil {
|
||||
if errors.Is(err, pipeline.ErrOperatorSessionReplaced) {
|
||||
fail(err.Error() + "; reopen the chat to continue it")
|
||||
@@ -93,9 +108,6 @@ func handleChatNewSession(ctx context.Context, request protocol.Message, broker
|
||||
fail("session " + created.ID + " was started but the chat could not move to it: " + err.Error())
|
||||
return
|
||||
}
|
||||
// Nothing queued for the old context may run in the new one; with no turn
|
||||
// in flight this is normally already empty.
|
||||
hub.clearQueue(ctx, oldID)
|
||||
row, found, err := registry.OperatorSession(ctx, created.ID)
|
||||
if err != nil || !found {
|
||||
fail("session " + created.ID + " was recorded but could not be read back")
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -85,6 +86,9 @@ func TestChatNewSessionKeepsTheChatOnEveryHarness(t *testing.T) {
|
||||
if calls, title, directory := owner.createQuery(); calls != 1 || title != "Feature" || directory != "/work/a" {
|
||||
t.Fatalf("harness create = %d %q %q", calls, title, directory)
|
||||
}
|
||||
if released, _ := owner.releaseQuery(); len(released) != 1 || released[0] != tc.oldID {
|
||||
t.Fatalf("released sessions = %v, want [%s]", released, tc.oldID)
|
||||
}
|
||||
pushed := readMessage(t, ctx, conns[1])
|
||||
if pushed.Type != protocol.ChatSessionChanged || pushed.ChatSession == nil ||
|
||||
pushed.ChatSession.ID != tc.newID || pushed.ChatSession.PreviousID != tc.oldID {
|
||||
@@ -108,6 +112,27 @@ func TestChatNewSessionKeepsTheChatOnEveryHarness(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatNewSessionDoesNotMoveChatWhenReleaseFails(t *testing.T) {
|
||||
store := newOperatorStore(t)
|
||||
broker := scriptedChat()
|
||||
broker.created = protocol.ChatSession{ID: "ses_fresh"}
|
||||
broker.releaseErr = errors.New("native runtime unavailable")
|
||||
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := store.RecordOperatorSession(ctx, "ses_old", "/work", "A", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, chatNewSessionRequest("new", "ses_old")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := readMessage(t, ctx, conn)
|
||||
if reply.Type != protocol.Error || !strings.Contains(reply.Error, "could not be released") {
|
||||
t.Fatalf("release failure reply = %+v", reply)
|
||||
}
|
||||
if row, found, _ := store.OperatorSession(ctx, "ses_old"); !found || row.ID != "ses_old" {
|
||||
t.Fatalf("old row moved after release failure: %+v found=%v", row, found)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatNewSessionRefusesWithoutCreating proves a refused /new never starts
|
||||
// a native session: a foreign id, a running turn, and a second /new on a chat
|
||||
// already moved on.
|
||||
|
||||
@@ -59,6 +59,28 @@ func (h *chatHub) touchRecoveryLocked(id string) {
|
||||
h.recoveryGeneration[id]++
|
||||
}
|
||||
|
||||
// invalidateRecovery makes in-flight recovery probes stale before an explicit
|
||||
// release. The durable record is retained until the native release succeeds,
|
||||
// so a failed release remains recoverable.
|
||||
func (h *chatHub) invalidateRecovery(id string) {
|
||||
h.mu.Lock()
|
||||
h.touchRecoveryLocked(id)
|
||||
h.mu.Unlock()
|
||||
}
|
||||
|
||||
// clearRecovery removes the durable liveness record after an explicit native
|
||||
// release succeeds. The native transcript is untouched.
|
||||
func (h *chatHub) clearRecovery(ctx context.Context, id string) error {
|
||||
h.invalidateRecovery(id)
|
||||
h.mu.Lock()
|
||||
delete(h.liveJournal, id)
|
||||
h.mu.Unlock()
|
||||
if h.liveStore == nil {
|
||||
return nil
|
||||
}
|
||||
return h.liveStore.ForgetChatLiveSession(ctx, id)
|
||||
}
|
||||
|
||||
// Probe results are older than any lifecycle that arrived while they were in
|
||||
// flight. Hold the same lock as lifecycle journaling through the final delete.
|
||||
func (h *chatHub) forgetLive(ctx context.Context, id string, generation uint64) {
|
||||
|
||||
@@ -44,6 +44,8 @@ type fakeChat struct {
|
||||
promptCalls int
|
||||
promptFiles []opencode.PromptFile
|
||||
interrupts int
|
||||
releases []string
|
||||
releaseErr error
|
||||
replies int
|
||||
replyRequest protocol.ChatReplyRequest
|
||||
replyErr error
|
||||
@@ -209,6 +211,19 @@ func (f *fakeChat) Interrupt(context.Context, string) error {
|
||||
return f.interruptErr
|
||||
}
|
||||
|
||||
func (f *fakeChat) ReleaseSession(_ context.Context, sessionID string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.releases = append(f.releases, sessionID)
|
||||
return f.releaseErr
|
||||
}
|
||||
|
||||
func (f *fakeChat) releaseQuery() ([]string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.releases...), f.releaseErr
|
||||
}
|
||||
|
||||
func (f *fakeChat) Messages(_ context.Context, sessionID string, limit int, cursor string) (protocol.ChatHistoryPage, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
Reference in New Issue
Block a user