Keep OpenCode/Codex chat and stage sessions running across server restarts
A stopping server no longer interrupts harness sessions. Runs are canceled with a shutdown cause, so stage clients leave admitted sessions running and owned; start-up recovery re-adopts live OpenCode V2 stage sessions (wait, read back the result, continue the graph), restarts unadmitted visits, continues runs between stages, and falls back to interrupted with a reason when the harness is gone. Chats with live work are recorded on shutdown and reattached on start; turns that ended during the downtime are folded in from history. The server-spawned V2 chat serve is now a detached owned service. PIPELINES_SHUTDOWN_SESSIONS=stop restores the old behaviour.
This commit is contained in:
+90
-23
@@ -84,6 +84,10 @@ type runner struct {
|
||||
// sizeKick wakes the background run-size backfill (sizeLoop); nil when the
|
||||
// loop is not running (a runner built directly in a test).
|
||||
sizeKick chan struct{}
|
||||
// detach leaves harness sessions running when the server stops; reattach
|
||||
// holds the runs start-up recovery kept for reattachRuns to continue.
|
||||
detach bool
|
||||
reattach []reattachPlan
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
@@ -96,6 +100,14 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
// starts and is never written afterwards, so those goroutines read it without
|
||||
// locking.
|
||||
func newRunnerAt(ctx context.Context, s *pipeline.Store, artifactsRoot string) (*runner, error) {
|
||||
return newRunnerReattaching(ctx, s, artifactsRoot, false)
|
||||
}
|
||||
|
||||
// newRunnerReattaching builds the runner. With detach set, a server shutdown
|
||||
// leaves stage sessions running (see stage.ErrServerShutdown) and start-up
|
||||
// recovery re-adopts the runs a previous process left in flight instead of
|
||||
// interrupting them; reattachRuns then continues them.
|
||||
func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot string, detach bool) (*runner, error) {
|
||||
if err := s.AcquireRunnerLock(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -109,19 +121,30 @@ func newRunnerAt(ctx context.Context, s *pipeline.Store, artifactsRoot string) (
|
||||
if err = s.BindLegacyScheduleWorkspace(ctx, workspace); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var plans []reattachPlan
|
||||
keep, reasons, gone := map[int64]bool{}, map[int64]string{}, map[int64]bool{}
|
||||
if detach {
|
||||
if plans, reasons, gone, err = planReattach(ctx, s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, plan := range plans {
|
||||
keep[plan.runID] = true
|
||||
}
|
||||
}
|
||||
sessions, err := s.ActiveSessionOwners(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, owner := range sessions {
|
||||
stop, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
var err error
|
||||
if owner.Backend == "pi" {
|
||||
err = stage.InterruptPi(stop, owner.Reference)
|
||||
} else {
|
||||
err = (stage.OpenCodeClient{Backend: owner.Backend, Directory: owner.Directory, Reference: owner.Reference}).InterruptAndConfirm(stop, owner.ID)
|
||||
if keep[owner.RunID] {
|
||||
continue // Re-adopted below: never interrupt work that survived.
|
||||
}
|
||||
var err error
|
||||
if !gone[owner.RunID] {
|
||||
stop, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
err = interruptRecoveredSession(stop, owner)
|
||||
cancel()
|
||||
}
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err)
|
||||
}
|
||||
@@ -129,7 +152,7 @@ func newRunnerAt(ctx context.Context, s *pipeline.Store, artifactsRoot string) (
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.RecoverRuns(ctx); err != nil {
|
||||
if err := s.RecoverRunsKeeping(ctx, keep, reasons); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root := artifactsRoot
|
||||
@@ -146,7 +169,7 @@ func newRunnerAt(ctx context.Context, s *pipeline.Store, artifactsRoot string) (
|
||||
active[row.ID] = activeRun{cancel: func() {}, workspace: row.Workspace}
|
||||
}
|
||||
}
|
||||
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession}
|
||||
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans}
|
||||
if err := r.startSessionExportJobs(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -341,7 +364,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
// the registration when it returns. A fresh run and a resumed decision both go
|
||||
// through it, so registration and teardown live once. Callers must hold r.mu.
|
||||
func (r *runner) launch(id int64, workspace string, fn func(context.Context)) {
|
||||
ctx, cancel := context.WithCancel(r.ctx)
|
||||
ctx, cancel := r.runContext()
|
||||
generation := new(byte)
|
||||
r.active[id] = activeRun{cancel: cancel, workspace: workspace, generation: generation}
|
||||
r.wg.Add(1)
|
||||
@@ -980,6 +1003,9 @@ type runState struct {
|
||||
// have been resolved. It is intentionally not part of run input or memory.
|
||||
retryOverride stage.Values
|
||||
priorBudgets map[string]stage.BudgetSnapshot
|
||||
// adopt names the visit to re-adopt from a previous server process instead
|
||||
// of starting it; it is consumed by the loop's first iteration.
|
||||
adopt *adoptedVisit
|
||||
}
|
||||
|
||||
func newRunState(key string, input stage.Values) *runState {
|
||||
@@ -1528,6 +1554,15 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input)
|
||||
}
|
||||
// canceled settles an operator cancel. A server shutdown is not a cancel:
|
||||
// the run is left exactly as persisted for the next process to continue.
|
||||
canceled := func() {
|
||||
if stage.Detached(ctx) {
|
||||
log.Printf("run %d: server stopping; run left in flight for the next start to continue", id)
|
||||
return
|
||||
}
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
finish("failed", "error", "stage execution panicked")
|
||||
@@ -1554,7 +1589,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
for sequence := state.nextSequence; sequence <= 30; sequence++ {
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
key := state.key
|
||||
@@ -1600,8 +1635,15 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
return
|
||||
}
|
||||
}
|
||||
// adopted is the visit a previous server process began and left running
|
||||
// across its restart: its step row, turn files and session already exist.
|
||||
adopted := state.adopt
|
||||
if adopted != nil && adopted.sequence != sequence {
|
||||
adopted = nil
|
||||
}
|
||||
state.adopt = nil
|
||||
_, declaresSkip := def.Edges["skipped"]
|
||||
skip := !isHuman && declaresSkip && autoSkipEligible(def.Configs, state)
|
||||
skip := adopted == nil && !isHuman && declaresSkip && autoSkipEligible(def.Configs, state)
|
||||
state.nextSequence = sequence + 1
|
||||
state.visits[key]++
|
||||
// Publish the run's server-captured changed paths into the input memory
|
||||
@@ -1643,13 +1685,15 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
retryInput = input
|
||||
state.retryOverride = nil
|
||||
}
|
||||
if err := r.store.BeginStep(ctx, id, sequence, key, input); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
if adopted == nil {
|
||||
if err := r.store.BeginStep(ctx, id, sequence, key, input); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
return
|
||||
}
|
||||
// queued -> running: report the new current stage and the step start.
|
||||
r.emitRun(protocol.RunEventFrame{
|
||||
@@ -1668,7 +1712,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
if err := r.store.MarkWaiting(ctx, id, sequence, key, evidence); err != nil {
|
||||
r.mu.Unlock()
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
finish("failed", "error", err.Error())
|
||||
@@ -1744,9 +1788,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
var publicBefore map[string]bool
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
visitTurn = r.turnPaths(id, sequence, key)
|
||||
if turnErr := r.prepareTurn(visitTurn, state, retryInput); turnErr != nil {
|
||||
finish("failed", "error", turnErr.Error())
|
||||
return
|
||||
if adopted == nil {
|
||||
if turnErr := r.prepareTurn(visitTurn, state, retryInput); turnErr != nil {
|
||||
finish("failed", "error", turnErr.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
artifactsDir = visitTurn.TurnDir
|
||||
def.ArtifactsDir = artifactsDir
|
||||
@@ -1779,6 +1825,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
var piClient *stage.PiClient
|
||||
var err error
|
||||
stageCtx := ctx
|
||||
if adopted != nil {
|
||||
// Attach to the surviving session instead of prompting again.
|
||||
client.Backend, client.Reference = adopted.owner.Backend, adopted.owner.Reference
|
||||
stageCtx = stage.WithResumeSession(stageCtx, adopted.owner.ID)
|
||||
}
|
||||
var modelConfig stage.ModelConfig
|
||||
var budgetBefore stage.BudgetSnapshot
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
@@ -1846,6 +1897,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
stageSession = client.SessionID
|
||||
} else if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
plain := &stage.OpenCodeClient{Directory: workspace, Operations: operations, ArtifactsDir: artifactsDir}
|
||||
if adopted != nil {
|
||||
plain.Backend, plain.Reference = adopted.owner.Backend, adopted.owner.Reference
|
||||
}
|
||||
plain.OnGenerationSession = func(session, backend, reference string, active bool) error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
@@ -1860,6 +1914,13 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
result, err = stage.DefaultRegistry().Run(stageCtx, def, input)
|
||||
}
|
||||
}()
|
||||
if r.detach && stage.Detached(ctx) {
|
||||
// The server is stopping. The stage left its session running and
|
||||
// owned (or never admitted one); nothing about this visit is settled
|
||||
// here. The next process re-adopts the session and continues.
|
||||
log.Printf("run %d stage %s #%d: server stopping; stage left running for the next start to reattach", id, key, sequence)
|
||||
return
|
||||
}
|
||||
ownershipCtx, ownershipCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
activeSessions, ownershipErr := r.store.ActiveAgentSessionsForRun(ownershipCtx, id)
|
||||
ownershipCancel()
|
||||
@@ -1877,6 +1938,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
after := filediff.Capture(snapshotCtx, workspace, before)
|
||||
snapshotCancel()
|
||||
changes := filediff.Compare(before, after)
|
||||
if adopted != nil && changes.Status == "complete" {
|
||||
// The pre-visit snapshot belonged to the stopped process; only the
|
||||
// changes made after reattaching were compared.
|
||||
changes.Status = "partial"
|
||||
changes.Diagnostic = "Server restarted during this stage; changes made before the restart are not listed."
|
||||
}
|
||||
if errors.Is(err, stage.ErrStageCleanup) {
|
||||
changes.Status = "partial"
|
||||
changes.Diagnostic = "Agent cleanup was not confirmed; files may still be changing."
|
||||
@@ -2062,7 +2129,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
return
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
// Advance the in-memory UI-surface evidence only after the step is
|
||||
@@ -2099,7 +2166,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
},
|
||||
}, false)
|
||||
if ctx.Err() != nil {
|
||||
finish("canceled", "", ctx.Err().Error())
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
if terminal {
|
||||
|
||||
Reference in New Issue
Block a user