Preserve independent background sessions through owner shutdown and idle cleanup

This commit is contained in:
2026-11-07 16:23:20 +00:00
parent 4ead2abdbf
commit b15597662f
9 changed files with 360 additions and 51 deletions
+49
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -150,3 +151,51 @@ func TestProcessExitEndsBackgroundTasks(t *testing.T) {
t.Fatal("no shell exit was published")
}
}
func TestObserverReleaseDoesNotForgetOrReapRunningNativeTasks(t *testing.T) {
chat, s := backgroundSession(t)
defer chat.Close()
s.handleLine(nil, toolUse(t, "toolu_bg", "Bash", map[string]any{"command": "quiet background work", "run_in_background": true}))
s.handleLine(nil, toolResult(t, "toolu_bg", "Command running in background with ID: native-bg"))
s.handleLine(nil, toolUse(t, "toolu_done", "Bash", map[string]any{"command": "completed foreground"}))
s.handleLine(nil, toolResult(t, "toolu_done", "done"))
proc := newProcess(s, "")
proc.markReady()
s.mu.Lock()
s.proc = proc
s.running = false
s.lastUsed = time.Now().Add(-time.Hour)
s.mu.Unlock()
chat.ReleaseShells(s.id)
if shells := running(t, chat); len(shells) != 1 || shells[0].ID != shellID("toolu_bg") {
t.Fatalf("observer expiry lost task identity: %+v", shells)
}
chat.reapIdleAt(time.Now())
s.mu.Lock()
same := s.proc == proc
s.proc = nil
s.mu.Unlock()
if !same {
t.Fatal("idle cache eviction stopped active background work")
}
}
func TestLegacyHostRemainsAttachedDuringIdleCacheEviction(t *testing.T) {
chat, s := backgroundSession(t)
defer chat.Close()
proc := newProcess(s, "")
proc.markReady()
proc.link = &hostLink{} // No authoritative task snapshot capability.
s.mu.Lock()
s.proc = proc
s.lastUsed = time.Now().Add(-time.Hour)
s.mu.Unlock()
chat.reapIdleAt(time.Now())
s.mu.Lock()
same := s.proc == proc
s.proc = nil
s.mu.Unlock()
if !same {
t.Fatal("legacy host was detached despite unknown background liveness")
}
}
+87 -31
View File
@@ -161,13 +161,27 @@ func (c *Chat) Close() {
}
}
// ReleaseShells drops a session's retained shell snapshot after the last
// observer leaves. A later attach re-reads the authoritative transcript.
// ReleaseShells releases completed display snapshots, never liveness for
// running tasks. A room/observer expiry is not permission to stop native work.
func (c *Chat) ReleaseShells(id string) {
if s := c.session(id); s != nil {
s.mu.Lock()
s.shells = map[string]*shellSnapshot{}
s.shellOrder = nil
kept := make(map[string]*shellSnapshot)
ids := map[string]bool{}
for key, task := range s.shells {
if task.shell.Status == protocol.ChatShellRunning {
kept[key] = task
ids[task.shell.ID] = true
}
}
var order []string
for _, id := range s.shellOrder {
if ids[id] {
order = append(order, id)
}
}
s.shells, s.shellOrder = kept, order
s.mu.Unlock()
}
}
@@ -250,37 +264,46 @@ func (c *Chat) reapIdle() {
return
case <-ticker.C:
}
now := time.Now()
type candidate struct {
s *session
used time.Time
alive bool
c.reapIdleAt(time.Now())
}
}
func (c *Chat) reapIdleAt(now time.Time) {
type candidate struct {
s *session
used time.Time
}
var live []candidate
c.mu.Lock()
for _, s := range c.sessions {
s.mu.Lock()
alive := s.proc != nil
used := s.lastUsed
s.mu.Unlock()
if alive {
live = append(live, candidate{s: s, used: used})
}
var live []candidate
c.mu.Lock()
for _, s := range c.sessions {
s.mu.Lock()
alive := s.proc != nil
used := s.lastUsed
s.mu.Unlock()
if alive {
live = append(live, candidate{s: s, used: used})
}
}
c.mu.Unlock()
sort.Slice(live, func(i, j int) bool { return live[i].used.Before(live[j].used) })
for _, entry := range live {
entry.s.mu.Lock()
excess := len(live) > maxLiveProcesses && !entry.s.running
idle := !entry.s.running && len(entry.s.subs) == 0 && now.Sub(entry.used) > idleProcessExpiry
entry.s.mu.Unlock()
if excess || idle {
entry.s.closeProcess()
// Recompute the live count on the next tick after a close.
live = live[1:]
}
c.mu.Unlock()
sort.Slice(live, func(i, j int) bool { return live[i].used.Before(live[j].used) })
for _, entry := range live {
entry.s.mu.Lock()
busy := entry.s.running
for _, task := range entry.s.shells {
if task.shell.Status == protocol.ChatShellRunning {
busy = true
break
}
}
excess := len(live) > maxLiveProcesses && !busy
idle := !busy && len(entry.s.subs) == 0 && now.Sub(entry.used) > idleProcessExpiry
entry.s.mu.Unlock()
if excess || idle {
entry.s.releaseIdleProcess()
// Recompute the live count on the next tick after a close.
live = live[1:]
break
}
}
}
@@ -443,6 +466,39 @@ func (s *session) unsubscribe(ch chan protocol.ChatEventFrame) {
s.mu.Unlock()
}
// The cache reaper may relinquish an idle control connection, not stop a
// hosted session. Only the host knows authoritative tasks beyond spool replay;
// an explicit operator close remains the hard-close path below.
func (s *session) releaseIdleProcess() {
s.mu.Lock()
if s.running || len(s.subs) > 0 {
s.mu.Unlock()
return
}
for _, task := range s.shells {
if task.shell.Status == protocol.ChatShellRunning {
s.mu.Unlock()
return
}
}
p := s.proc
// Older hosts have no authoritative task capability and their detached idle
// timer ignores background work. Keep their connection until explicit close.
if p != nil && p.link != nil && !p.link.tasksKnown {
s.mu.Unlock()
return
}
s.proc = nil
s.mu.Unlock()
if p != nil {
if p.link != nil {
p.detach()
} else {
p.close()
}
}
}
func (s *session) closeProcess() {
s.mu.Lock()
p := s.proc