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:
2026-11-04 16:17:08 +00:00
parent 9351cd7d74
commit aa8eddd686
26 changed files with 2318 additions and 99 deletions
+63 -19
View File
@@ -27,6 +27,23 @@ type AgentClient struct {
WorkStarted bool
}
// resumeConnection reopens the retained execution service a previous server
// process recorded for a session, refusing a different backend or directory.
func resumeConnection(reference, backend, directory string) (*opencode.Connection, error) {
if reference == "" {
return nil, fmt.Errorf("retained OpenCode session has no execution-service reference")
}
connection, err := opencode.FromReference(reference)
if err != nil {
return nil, err
}
if (backend != "" && connection.Backend != backend) || connection.Directory != directory {
connection.Close()
return nil, fmt.Errorf("retained OpenCode execution context mismatch")
}
return connection, nil
}
func (c OpenCodeClient) Interrupt(ctx context.Context, id string) error {
return c.interrupt(ctx, id, false)
}
@@ -80,7 +97,18 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if c.Operations != nil {
c.Operations.Provider, c.Operations.Model = config.Provider, config.Model
}
if c.command == nil {
// A re-adopted session was admitted by a previous server process: attach
// to its retained service and wait for it; never create or prompt again.
resume := TakeResumeSession(ctx)
if resume != "" && c.command == nil {
connection, err := resumeConnection(c.Reference, c.Backend, c.Directory)
if err != nil {
return "", err
}
defer connection.Close()
c.connection = connection
c.Backend = connection.Backend
} else if c.command == nil {
connection, err := opencode.OpenStage(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
// Connecting to the service failed before any session existed.
@@ -101,24 +129,31 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if err != nil {
return "", err
}
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": model, "permissions": rules})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
if resume != "" {
if c.Backend != "v2" || !sessionIDPattern.MatchString(resume) {
return "", fmt.Errorf("retained OpenCode session %.128s cannot be re-adopted on backend %q", RedactEvidence(resume), c.Backend)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
c.SessionID = resume
} else {
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": model, "permissions": rules})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if json.Unmarshal(data, &created) != nil || !sessionIDPattern.MatchString(created.Data.ID) {
return "", fmt.Errorf("invalid agent session")
}
c.SessionID = created.Data.ID
}
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if json.Unmarshal(data, &created) != nil || !sessionIDPattern.MatchString(created.Data.ID) {
return "", fmt.Errorf("invalid agent session")
}
c.SessionID = created.Data.ID
if c.connection != nil && c.Backend == "v1" {
c.Reference, err = c.connection.Reference()
if err != nil {
@@ -134,6 +169,12 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
defer func() {
watch.stopWatch(ctx, &err)
defer watch.finish(ctx, &err)
if err != nil && Detached(ctx) {
// The server is restarting: leave the admitted session running and
// its ownership recorded, so the next process re-adopts it.
err = fmt.Errorf("%w: retained OpenCode session %s left running", ErrDetached, c.SessionID)
return
}
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
defer cancel()
if err != nil {
@@ -181,8 +222,10 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
return "", err
}
c.WorkStarted = true
if _, err = c.call(ctx, "post", "/api/session/"+c.SessionID+"/prompt", generationBody("text", prompt, config, c.Backend)); err != nil {
return "", err
if resume == "" {
if _, err = c.call(ctx, "post", "/api/session/"+c.SessionID+"/prompt", generationBody("text", prompt, config, c.Backend)); err != nil {
return "", err
}
}
if c.Backend == "v1" {
// Native V1 prompts block until completion; keep the existing settlement
@@ -193,6 +236,7 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
} else if err = c.waitForSessionIdle(ctx, c.SessionID); err != nil {
return "", err
}
var data []byte
data, text, err = c.readFinalAgentResult(ctx, c.SessionID)
if len(data) > 0 {
c.Transcript = string(data)
+61
View File
@@ -0,0 +1,61 @@
package stage
import (
"context"
"errors"
"sync"
)
// A Pipelines server restart must not stop harness work. The runner cancels a
// run's context with ErrServerShutdown as its cause when the server process is
// stopping (as opposed to an operator cancel, whose cause is context.Canceled).
// A stage client that sees this cause leaves its admitted session running: it
// neither interrupts it nor clears its recorded ownership, and returns an error
// wrapping ErrDetached. The next server process re-adopts the session through
// WithResumeSession and waits for it instead of prompting again.
// ErrServerShutdown is the cancellation cause of a run context whose server is
// stopping or restarting.
var ErrServerShutdown = errors.New("pipelines server is shutting down; harness sessions are left running")
// ErrDetached reports that a stage left its admitted harness session running
// for the next server process to re-adopt.
var ErrDetached = errors.New("stage session detached for server restart")
// Detached reports whether ctx was canceled because the server is stopping.
func Detached(ctx context.Context) bool {
return ctx.Err() != nil && errors.Is(context.Cause(ctx), ErrServerShutdown)
}
type resumeKey struct{}
type resumeHolder struct {
mu sync.Mutex
session string
}
// WithResumeSession marks the next model generation under ctx as a re-adoption
// of an already admitted session: the client attaches to sessionID, waits for it
// to settle and reads its final result, without creating a session or sending a
// prompt. The mark is consumed by the first generation, so a later retry or
// repair attempt starts fresh as usual.
func WithResumeSession(ctx context.Context, sessionID string) context.Context {
if sessionID == "" {
return ctx
}
return context.WithValue(ctx, resumeKey{}, &resumeHolder{session: sessionID})
}
// TakeResumeSession returns and consumes the session marked by
// WithResumeSession, or "" when the generation is a fresh one.
func TakeResumeSession(ctx context.Context) string {
holder, _ := ctx.Value(resumeKey{}).(*resumeHolder)
if holder == nil {
return ""
}
holder.mu.Lock()
defer holder.mu.Unlock()
id := holder.session
holder.session = ""
return id
}
+159
View File
@@ -0,0 +1,159 @@
package stage
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
)
// fakeV2Session answers the V2 calls a stage makes for one session, records
// every request, and reports the session running until finish is closed.
type fakeV2Session struct {
t *testing.T
id string
finish chan struct{}
mu sync.Mutex
calls []string
}
func (f *fakeV2Session) command(_ context.Context, _ string, args ...string) ([]byte, error) {
f.mu.Lock()
f.calls = append(f.calls, args[1]+" "+args[2])
f.mu.Unlock()
switch path := args[2]; {
case path == "/api/session":
return []byte(`{"data":{"id":"` + f.id + `"}}`), nil
case strings.HasSuffix(path, "/prompt"), strings.HasSuffix(path, "/interrupt"):
return []byte(`{}`), nil
case path == "/api/session/active":
select {
case <-f.finish:
return []byte(`{"data":{}}`), nil
default:
return []byte(`{"data":{"` + f.id + `":{"type":"running"}}}`), nil
}
case path == "/api/session/"+f.id+finalAssistantReadback:
return []byte(`{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n\nreattached reply\n"}]}]}`), nil
}
return nil, fmt.Errorf("unexpected request %v", args)
}
func (f *fakeV2Session) called(prefix string) bool {
f.mu.Lock()
defer f.mu.Unlock()
for _, call := range f.calls {
if strings.HasPrefix(call, prefix) {
return true
}
}
return false
}
// TestAgentDetachesOnServerShutdown: a server shutdown (not an operator cancel)
// leaves the admitted session running and owned: no interrupt, no release.
func TestAgentDetachesOnServerShutdown(t *testing.T) {
fake := &fakeV2Session{t: t, id: "ses_detach", finish: make(chan struct{})}
var released []string
client := &AgentClient{OnSession: func(id string, active bool) error {
if !active {
released = append(released, id)
}
return nil
}}
client.Backend, client.Directory, client.command, client.sessionPollInterval = "v2", "/work", fake.command, time.Millisecond
ctx, cancel := context.WithCancelCause(context.Background())
go func() {
for !fake.called("post /api/session/ses_detach/prompt") {
time.Sleep(time.Millisecond)
}
cancel(ErrServerShutdown)
}()
_, err := client.Generate(ctx, ModelConfig{}, "work")
if !errors.Is(err, ErrDetached) {
t.Fatalf("shutdown did not detach: %v", err)
}
if fake.called("post /api/session/ses_detach/interrupt") {
t.Fatal("a server shutdown interrupted the stage session")
}
if len(released) != 0 {
t.Fatalf("a detached session's ownership was released: %v", released)
}
}
// TestAgentOperatorCancelStillInterrupts keeps the explicit stop path.
func TestAgentOperatorCancelStillInterrupts(t *testing.T) {
fake := &fakeV2Session{t: t, id: "ses_cancel", finish: make(chan struct{})}
client := &AgentClient{}
client.Backend, client.Directory, client.command, client.sessionPollInterval = "v2", "/work", fake.command, time.Millisecond
ctx, cancel := context.WithCancel(context.Background())
go func() {
for !fake.called("post /api/session/ses_cancel/prompt") {
time.Sleep(time.Millisecond)
}
cancel()
// Interrupt confirmation waits for the session to settle.
for !fake.called("post /api/session/ses_cancel/interrupt") {
time.Sleep(time.Millisecond)
}
close(fake.finish)
}()
if _, err := client.Generate(ctx, ModelConfig{}, "work"); err == nil || errors.Is(err, ErrDetached) {
t.Fatalf("operator cancel did not fail the stage: %v", err)
}
if !fake.called("post /api/session/ses_cancel/interrupt") {
t.Fatal("operator cancel did not interrupt the session")
}
}
// TestAgentResumeAttachesWithoutPrompting: a re-adopted session is waited on
// and read back; it is never created or prompted again, and the resume mark is
// consumed so a retry starts fresh.
func TestAgentResumeAttachesWithoutPrompting(t *testing.T) {
fake := &fakeV2Session{t: t, id: "ses_adopted", finish: make(chan struct{})}
var owned []bool
client := &AgentClient{OnSession: func(id string, active bool) error {
if id != "ses_adopted" {
t.Errorf("ownership for %s", id)
}
owned = append(owned, active)
return nil
}}
client.Backend, client.Directory, client.command, client.sessionPollInterval = "v2", "/work", fake.command, time.Millisecond
ctx := WithResumeSession(context.Background(), "ses_adopted")
go func() {
time.Sleep(20 * time.Millisecond)
close(fake.finish)
}()
text, err := client.Generate(ctx, ModelConfig{}, "work")
if err != nil || !strings.Contains(text, "reattached reply") {
t.Fatalf("resume = %q, %v", text, err)
}
if fake.called("post /api/session ") || fake.called("post /api/session/ses_adopted/prompt") {
t.Fatalf("a re-adopted session was created or prompted again: %v", fake.calls)
}
if len(owned) != 2 || !owned[0] || owned[1] {
t.Fatalf("ownership was not re-asserted then released: %v", owned)
}
if TakeResumeSession(ctx) != "" {
t.Fatal("the resume mark was not consumed")
}
}
// TestPlainResumeReadsResultReachedWhileDown: a text-only session that ended
// during the downtime is folded in from its final assistant message.
func TestPlainResumeReadsResultReachedWhileDown(t *testing.T) {
fake := &fakeV2Session{t: t, id: "ses_plain", finish: make(chan struct{})}
close(fake.finish)
client := &OpenCodeClient{Backend: "v2", Directory: "/work", command: fake.command, sessionPollInterval: time.Millisecond}
text, err := client.Generate(WithResumeSession(context.Background(), "ses_plain"), ModelConfig{}, "prompt")
if err != nil || !strings.Contains(text, "reattached reply") {
t.Fatalf("resume = %q, %v", text, err)
}
if fake.called("post /api/session/ses_plain/prompt") || fake.called("post /api/session ") {
t.Fatalf("a re-adopted session was prompted again: %v", fake.calls)
}
}
+44 -19
View File
@@ -273,7 +273,18 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
if c.Operations != nil {
c.Operations.Provider, c.Operations.Model = config.Provider, config.Model
}
if c.command == nil {
// A re-adopted session was admitted by a previous server process (see
// WithResumeSession): wait for it and read its result, never prompt again.
resume := TakeResumeSession(ctx)
if resume != "" && c.command == nil {
connection, err := resumeConnection(c.Reference, c.Backend, c.Directory)
if err != nil {
return "", err
}
defer connection.Close()
c.connection = connection
c.Backend = connection.Backend
} else if c.command == nil {
connection, err := opencode.OpenStage(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
// Connecting to the service failed before any session existed.
@@ -313,33 +324,45 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
if err != nil {
return "", err
}
created, err := c.call(ctx, "post", "/api/session", map[string]any{
"title": "Pipeline stage generation",
"location": map[string]string{"directory": directory},
"model": model,
"permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}},
})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
var session struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if err := json.Unmarshal(created, &session); err != nil || !sessionIDPattern.MatchString(session.Data.ID) {
return "", fmt.Errorf("OpenCode returned an invalid session ID")
if resume != "" {
if c.Backend != "v2" || !sessionIDPattern.MatchString(resume) {
return "", fmt.Errorf("retained OpenCode session %.128s cannot be re-adopted on backend %q", RedactEvidence(resume), c.Backend)
}
session.Data.ID = resume
} else {
created, err := c.call(ctx, "post", "/api/session", map[string]any{
"title": "Pipeline stage generation",
"location": map[string]string{"directory": directory},
"model": model,
"permissions": []map[string]string{{"action": "*", "resource": "*", "effect": "deny"}},
})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
if err := json.Unmarshal(created, &session); err != nil || !sessionIDPattern.MatchString(session.Data.ID) {
return "", fmt.Errorf("OpenCode returned an invalid session ID")
}
}
var watch *budgetWatch
promptStarted := false
defer func() {
watch.stopWatch(ctx, &err)
defer watch.finish(ctx, &err)
if err != nil && Detached(ctx) {
// The server is restarting: leave the session running and owned.
err = fmt.Errorf("%w: retained OpenCode session %s left running", ErrDetached, session.Data.ID)
return
}
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err != nil {
@@ -392,8 +415,10 @@ func (c *OpenCodeClient) Generate(ctx context.Context, config ModelConfig, promp
// including unbudgeted text-only stages, so its exact native turns survive.
if c.Backend == "v2" {
promptStarted = true
if _, err = c.call(ctx, "post", "/api/session/"+session.Data.ID+"/prompt", body); err != nil {
return "", err
if resume == "" {
if _, err = c.call(ctx, "post", "/api/session/"+session.Data.ID+"/prompt", body); err != nil {
return "", err
}
}
if err = c.waitForSessionIdle(ctx, session.Data.ID); err != nil {
return "", err