fix(harness): recover interrupted session version moves after daemon restart
What could go wrong
After a harness update succeeds, AO can separately move an eligible idle session to the new release. If AO stops the old process and its replacement fails, then the daemon restarts before retry, the user may be left with a session that did not resume. A controlled manager recreation reproduced the loss of an automatic TUI retry; a separate real SQLite reopen confirmed that durable failure markers exclude both Chat and TUI from the normal sweep. It is not a measured Windows incident, a full daemon-crash reproduction, or a claim that installation always waits for migration.
Expected: After restart AO either resumes the same native session safely, or surfaces an actionable, recoverable failure. The completed harness update stays completed. No duplicate host, fresh conversation fallback, or loss of queued work.
Environment and agent investigation
Source audited at AO 9b99c47565d312c5c2bbc9b24b1f132611163ee2. Two paths need coverage:
| Path | What persists | What restarts can lose |
|---|---|---|
| Automatic managed version move | switch_failed_at, which ordinary Chat/TUI candidates exclude |
Per-session retry IDs and budgets consumed by the retry sweep |
| In-place stop/update/resume batch | Installer job state; startup interrupts unfinished jobs | Stopped-session IDs retained in memory until resume |
#6745 documents successful OMP moves and reconnect after a completed move. #7055 documents Claude Code Chat recovering when the daemon restarts before the move, and addresses eligibility/banner behavior. These are positive controls, not evidence that a stopped session survives restart after a failed replacement.
Controlled runtime evidence: TUI retry across manager recreation
The agent first traced an in-memory retry and a durable failure flag, then exercised them separately: recreate the manager to isolate lost memory, and reopen SQLite to verify that persisted failure rows remain outside the normal sweep.
TestReproVersionRetryLostAcrossManagerRecreation, Linux, same pinned commit, real RefreshStaleTerminals and RetryVersionMoves, retained fixture session store, fake Pi TUI runtime. A replacement was injected to die before it became healthy. Then a fresh manager was initialized from the same retained store, with no injected failure in its runtime:
after injected replacement failure: switch_failed=true pending_retries=1 restart_attempts=1 launch=launch-old native_session=agent-x
after new manager and automatic retry sweep: switch_failed=true pending_retries=0 restart_attempts=0 launch=launch-old native_session=agent-x
The persisted failure is visible to the new manager, but the sweep makes no replacement attempt and leaves the original launch reference unchanged. The fixture covers manager-memory loss in the TUI path only. It does not kill a real daemon, use a native Windows harness, or prove equivalent Chat and in-place behavior.
Independent SQLite control
TestReproFailedSwitchStaysOutsideCandidateSweepAfterSQLiteReopen uses the actual SQLite store and eligible synthetic idle Chat/TUI rows. Record both failures, close and reopen the database, then call the production candidate queries:
before recording failure: chat_candidates=1 tui_candidates=1
after closing and reopening SQLite: retained_failure_markers=2 chat_candidates=0 tui_candidates=0
This independently confirms the SQL filter across a physical database reopen. It is not evidence of a complete Chat session move.
How to confirm the end-to-end case
- In a disposable AO profile, establish an idle resumable session and record AO session ID, native session ID, source release and launch generation. Use a synthetic conversation with queued work, not a user's live session.
- Activate the new release. Let AO stop the old process; fail the exact-native replacement before it is confirmed. Capture the failure, durable flags, and retry decision.
- Run one control with the daemon alive and one with a restart after the failed replacement but before the next retry. Compare the resulting host count, old/new executable version, same-native-identity resume, and queued work. Repeat for Chat/TUI and the separate in-place batch.
- Report pass/fail and preserve the exact source revision, provider, versions, and monotonic event sequence. Full-process restart results and the Windows/Chat/in-place cases are still open.
Proposed change and acceptance
Persist move intent before stopping a process: session identity, source launch generation, target release, stage and retry state. Reconcile it on daemon startup without rerunning the installer or launching if liveness is uncertain. Preserve existing busy/approval/defer safeguards. Test the stop-to-replacement crash window and ensure install completion, migration status and user recovery are distinct.
Runnable fixtures
Run at the pinned revision from backend/ on Linux (verified with Go 1.27.4). The Go overlay adds a temporary test without editing the checkout. These assertions pass when the behavior is reproduced.
TestReproVersionRetryLostAcrossManagerRecreation: source and command
Save as /tmp/restart_test.go:
package sessionmanager
import (
"context"
"testing"
"time"
"github.com/aoagents/agent-orchestrator/backend/internal/domain"
"github.com/aoagents/agent-orchestrator/backend/internal/ports"
)
// Two manager instances share a fixture store, modelling recovered records.
// This exercises manager retry logic but does not start a real AO daemon.
func TestReproVersionRetryLostAcrossManagerRecreation(t *testing.T) {
ctx := context.Background()
now := time.Now()
rt := &refreshTestRuntime{fakeRestartRuntime: &fakeRestartRuntime{fakeRuntime: &fakeRuntime{
aliveByHandle: map[string]bool{"tmux-mer-1": true},
fencedResult: ports.FencedProbeResult{Liveness: ports.FencedDead},
}}}
agent := refreshTestAgent{supervisedLaunchAgent{launchArgvAgent{argv: []string{"pi", "--session", "agent-x"}}}}
before, base, _ := newExitedResumeManager(t, rt, agent)
before.launchStartWait = time.Millisecond
store := &refreshTestStore{fakeStore: base}
before.store = store
before.SetTerminalInputGate(&refreshInputGate{})
rec := base.sessions["mer-1"]
rec.Harness = domain.HarnessPi
rec.Activity = domain.Activity{State: domain.ActivityIdle, LastActivityAt: now.Add(-time.Hour)}
rec.Metadata.AgentSessionIDLaunchID = rec.Metadata.RuntimeLaunchID
rec.StaleBinary = &domain.SessionStaleBinary{Version: "new", Since: now.Add(-time.Hour)}
base.sessions[rec.ID] = rec
if err := before.RefreshStaleTerminals(ctx, 10*time.Minute); err == nil {
t.Fatal("fixture did not exercise failed replacement")
}
failed := base.sessions[rec.ID]
retriesBefore := len(before.versionRetries.pending())
if failed.StaleBinary == nil || failed.StaleBinary.SwitchFailedAt == nil || retriesBefore != 1 || rt.restarted != 1 {
t.Fatalf("did not establish failure fixture: retries=%d restart attempts=%d", retriesBefore, rt.restarted)
}
t.Logf("after injected replacement failure: switch_failed=true pending_retries=%d restart_attempts=%d launch=%s native_session=%s", retriesBefore, rt.restarted, failed.Metadata.RuntimeLaunchID, failed.Metadata.AgentSessionID)
newRT := &refreshTestRuntime{fakeRestartRuntime: &fakeRestartRuntime{fakeRuntime: &fakeRuntime{
aliveByHandle: map[string]bool{"tmux-mer-1": true},
}}}
after, _, _ := newExitedResumeManager(t, newRT, agent)
after.store = store
retriesAfter := len(after.versionRetries.pending())
if err := after.RetryVersionMoves(ctx); err != nil {
t.Fatal(err)
}
got := base.sessions[rec.ID]
if got.StaleBinary == nil || got.StaleBinary.SwitchFailedAt == nil || retriesAfter != 0 || newRT.restarted != 0 {
t.Fatalf("loss not reproduced: retries=%d restart attempts=%d", retriesAfter, newRT.restarted)
}
t.Logf("after new manager and automatic retry sweep: switch_failed=true pending_retries=%d restart_attempts=%d launch=%s native_session=%s", retriesAfter, newRT.restarted, got.Metadata.RuntimeLaunchID, got.Metadata.AgentSessionID)
}
overlay=$(mktemp)
printf '{"Replace":{"%s/internal/session_manager/ao_issue_restart_test.go":"/tmp/restart_test.go"}}\n' "$PWD" > "$overlay"
go test -overlay "$overlay" ./internal/session_manager -run '^TestReproVersionRetryLostAcrossManagerRecreation$' -v
rm -f "$overlay"
TestReproFailedSwitchStaysOutsideCandidateSweepAfterSQLiteReopen: source and command
Save as /tmp/sqlite_test.go:
package store_test
import (
"context"
"slices"
"testing"
"time"
"github.com/aoagents/agent-orchestrator/backend/internal/domain"
"github.com/aoagents/agent-orchestrator/backend/internal/storage/sqlite"
)
// Real SQLite reopen, distinct from the separate manager-recreation fixture.
func TestReproFailedSwitchStaysOutsideCandidateSweepAfterSQLiteReopen(t *testing.T) {
ctx := context.Background()
path := t.TempDir()
s, err := sqlite.Open(path)
if err != nil {
t.Fatal(err)
}
defer func() {
if s != nil {
_ = s.Close()
}
}()
seedProject(t, s, "mer")
now := time.Now().UTC().Truncate(time.Second)
modeIDs := map[domain.SessionMode]domain.SessionID{}
for _, mode := range []domain.SessionMode{domain.SessionModeChat, domain.SessionModeTUI} {
rec := sampleRecord("mer")
rec.Mode = mode
rec.Activity = domain.Activity{State: domain.ActivityIdle, LastActivityAt: now.Add(-time.Hour)}
rec.Metadata.ControllerGeneration = "gen-1"
rec.Metadata.ProviderConversationID = "native-chat"
rec.Metadata.RuntimeLaunchID = "launch-1"
rec.Metadata.RuntimeHandleID = "handle-1"
rec.Metadata.AgentSessionID = "native-tui"
created, err := s.CreateSession(ctx, rec)
if err != nil {
t.Fatal(err)
}
modeIDs[mode] = created.ID
}
if n, err := s.MarkHarnessSessionsStale(ctx, domain.HarnessClaudeCode, "v2", now); err != nil || n != 2 {
t.Fatalf("mark rows=%d error=%v", n, err)
}
candidates := func() {
t.Helper()
chat, err := s.ListVersionRefreshChatCandidates(ctx, now.Add(-10*time.Minute))
if err != nil || !slices.Equal(chat, []domain.SessionID{modeIDs[domain.SessionModeChat]}) {
t.Fatalf("chat control candidates=%v error=%v", chat, err)
}
tui, err := s.ListVersionRefreshTerminalCandidates(ctx, now.Add(-10*time.Minute))
if err != nil || !slices.Equal(tui, []domain.SessionID{modeIDs[domain.SessionModeTUI]}) {
t.Fatalf("TUI control candidates=%v error=%v", tui, err)
}
}
candidates()
t.Log("before recording failure: chat_candidates=1 tui_candidates=1")
for _, id := range modeIDs {
if err := s.SetSessionVersionSwitchFailed(ctx, id, "v2", now); err != nil {
t.Fatal(err)
}
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
s = nil
s, err = sqlite.Open(path)
if err != nil {
t.Fatal(err)
}
failures := 0
for _, id := range modeIDs {
r, found, err := s.GetSession(ctx, id)
if !found || err != nil || r.StaleBinary == nil || r.StaleBinary.SwitchFailedAt == nil {
t.Fatalf("failure marker not retained: found=%v error=%v stale=%+v", found, err, r.StaleBinary)
}
failures++
}
chat, err := s.ListVersionRefreshChatCandidates(ctx, now.Add(-10*time.Minute))
if err != nil || len(chat) != 0 {
t.Fatalf("chat candidates after reopen=%v error=%v", chat, err)
}
tui, err := s.ListVersionRefreshTerminalCandidates(ctx, now.Add(-10*time.Minute))
if err != nil || len(tui) != 0 {
t.Fatalf("TUI candidates after reopen=%v error=%v", tui, err)
}
t.Logf("after closing and reopening SQLite: retained_failure_markers=%d chat_candidates=%d tui_candidates=%d", failures, len(chat), len(tui))
}
overlay=$(mktemp)
printf '{"Replace":{"%s/internal/storage/sqlite/store/ao_issue_sqlite_test.go":"/tmp/sqlite_test.go"}}\n' "$PWD" > "$overlay"
go test -overlay "$overlay" ./internal/storage/sqlite/store -run '^TestReproFailedSwitchStaysOutsideCandidateSweepAfterSQLiteReopen$' -v
rm -f "$overlay"
Native Windows fixture evidence (2026-11-19)
Ran on native Windows amd64 (build 26200, NTFS, Go 1.27.4) at 9b99c47565d312c5c2bbc9b24b1f132611163ee2 in a disposable checkout. The test assertions describe the reported behavior, so PASS means the fixture reproduced it, not that it is fixed.
TestReproVersionRetryLostAcrossManagerRecreation passed (0.16 s): after the injected TUI replacement failure, switch_failed=true pending_retries=1 restart_attempts=1; after recreating the manager and running its automatic sweep, switch_failed=true pending_retries=0 restart_attempts=0, with the old synthetic launch and native session IDs retained. TestReproFailedSwitchStaysOutsideCandidateSweepAfterSQLiteReopen passed (1.40 s): Chat/TUI candidate counts went from 1/1 to 0/0 after recording the failures and reopening SQLite; both durable failure markers remained. This isolates retry loss and candidate exclusion; it does not verify an actual daemon restart, real provider resume, or an interrupted in-place batch.