Recover incomplete session exports through durable runtime jobs
This commit is contained in:
@@ -118,6 +118,9 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
}
|
||||
}
|
||||
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}
|
||||
if err := r.startSessionExportJobs(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.schedulerWG.Add(1)
|
||||
go func() { defer r.schedulerWG.Done(); r.resumeRunNotifications() }()
|
||||
return r, nil
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// startSessionExportJobs is the only runner startup integration. Current main's
|
||||
// Store.Done stops the worker and in-flight readback even with Background callers.
|
||||
// The interface avoids duplicating that newer store implementation/server lock.
|
||||
func (r *runner) startSessionExportJobs() error {
|
||||
if err := r.store.ReconcileSessionExportJobs(r.ctx, time.Now()); err != nil {
|
||||
return err
|
||||
}
|
||||
var done <-chan struct{}
|
||||
if lifecycle, ok := any(r.store).(interface{ Done() <-chan struct{} }); ok {
|
||||
done = lifecycle.Done()
|
||||
}
|
||||
ctx, cancel := sessionExportWorkerContext(r.ctx, done)
|
||||
r.schedulerWG.Add(1)
|
||||
go func() {
|
||||
defer r.schedulerWG.Done()
|
||||
defer cancel()
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
nextReconcile := time.Now().Add(30 * time.Second)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-done:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
if time.Now().After(nextReconcile) {
|
||||
nextReconcile = time.Now().Add(30 * time.Second)
|
||||
if err := r.store.ReconcileSessionExportJobs(ctx, time.Now()); err != nil {
|
||||
if ctx.Err() != nil || strings.Contains(err.Error(), "database is closed") {
|
||||
return
|
||||
}
|
||||
log.Printf("session export recovery reconciliation failed: %v", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Serial bounded batches; each readback has a 10-second budget.
|
||||
for range 8 {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
worked, err := r.recoverSessionExportJob(ctx, time.Now())
|
||||
if err != nil {
|
||||
if ctx.Err() != nil || strings.Contains(err.Error(), "database is closed") {
|
||||
return
|
||||
}
|
||||
log.Printf("session export recovery failed: %v", err)
|
||||
break
|
||||
}
|
||||
if !worked {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func sessionExportWorkerContext(parent context.Context, done <-chan struct{}) (context.Context, context.CancelFunc) {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-done:
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
return ctx, cancel
|
||||
}
|
||||
|
||||
func (r *runner) recoverSessionExportJob(ctx context.Context, now time.Time) (bool, error) {
|
||||
job, err := r.store.ClaimSessionExportJob(ctx, now, 45*time.Second)
|
||||
if err != nil || job == nil {
|
||||
return false, err
|
||||
}
|
||||
r.mu.Lock()
|
||||
_, executing := r.active[job.RunID]
|
||||
r.mu.Unlock()
|
||||
if executing {
|
||||
return true, r.store.DeferSessionExportJob(ctx, job, now)
|
||||
}
|
||||
owner := &pipeline.SessionOwner{ID: job.SessionID, Backend: job.Backend, Directory: job.Directory, Reference: job.Reference, RunID: job.RunID}
|
||||
detail, repairErr := r.repairSessionExportOwned(ctx, job.RunID, job.Sequence, owner)
|
||||
diagnostic := ""
|
||||
if repairErr != nil {
|
||||
diagnostic = stage.RedactEvidence(repairErr.Error())
|
||||
} else if detail != nil {
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence == job.Sequence && len(step.SessionExportRepairs) > 0 {
|
||||
last := step.SessionExportRepairs[len(step.SessionExportRepairs)-1]
|
||||
diagnostic = last.Diagnostic
|
||||
if diagnostic == "" && last.Status != "complete" {
|
||||
diagnostic = "Automatic native session export remains " + last.Status
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Save acknowledgement even on shutdown after an attempt. A process kill
|
||||
// before this point leaves a recoverable, budgeted lease.
|
||||
save, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
return true, r.store.FinishSessionExportJob(save, job, time.Now(), diagnostic)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func recoveryRunner(t *testing.T) (*runHandler, *pipeline.Store, int64) {
|
||||
t.Helper()
|
||||
h, s, id := sessionExportRunner(t, "v2", func(stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
return stage.SessionExportResult{}, errors.New("initial readback unavailable")
|
||||
})
|
||||
// Synthetic executor has no agent process; model confirmed runtime cleanup.
|
||||
if err := s.ConfirmRecoveredSession(context.Background(), pipeline.SessionOwner{RunID: id, ID: "ses_run"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.runner.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
t.Error("export recovery reran a stage")
|
||||
return stage.Result{}, errors.New("forbidden rerun")
|
||||
}
|
||||
return h, s, id
|
||||
}
|
||||
|
||||
func TestAutomaticSessionExportRecoveryTransientThenComplete(t *testing.T) {
|
||||
h, s, id := recoveryRunner(t)
|
||||
ctx := context.Background()
|
||||
original, _ := s.GetRun(ctx, id)
|
||||
before, _ := json.Marshal(original.Steps[0].SessionExport)
|
||||
owner, _ := s.RepairSessionOwner(ctx, id, 1)
|
||||
var calls atomic.Int32
|
||||
h.runner.exportSession = func(ctx context.Context, request stage.SessionExportRequest) (stage.SessionExportResult, error) {
|
||||
if request.SessionID != owner.ID || request.Backend != owner.Backend || request.Directory != owner.Directory {
|
||||
t.Errorf("ownership changed: %+v", request)
|
||||
}
|
||||
if calls.Add(1) == 1 {
|
||||
return stage.SessionExportResult{}, errors.New("temporary upstream read failure")
|
||||
}
|
||||
body := []byte("<!doctype html><p>recorded messages</p>")
|
||||
if err := os.WriteFile(filepath.Join(request.ArtifactsDir, request.FileName), body, 0600); err != nil {
|
||||
return stage.SessionExportResult{}, err
|
||||
}
|
||||
return stage.SessionExportResult{Source: "native_export", Messages: 2, HTML: request.FileName, HTMLBytes: int64(len(body)), Attempts: 1}, nil
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
worked, err := h.runner.recoverSessionExportJob(ctx, time.UnixMilli(job.NextAt))
|
||||
if err != nil || !worked {
|
||||
t.Fatalf("attempt %d: %v %v", i, worked, err)
|
||||
}
|
||||
}
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
if job.Status != "complete" || job.Attempts != 2 || calls.Load() != 2 {
|
||||
t.Fatalf("recovery not complete: %+v calls=%d", job, calls.Load())
|
||||
}
|
||||
detail, _ := s.GetRun(ctx, id)
|
||||
after, _ := json.Marshal(detail.Steps[0].SessionExport)
|
||||
if string(before) != string(after) || detail.Status != original.Status || len(detail.Steps) != 1 || len(detail.Steps[0].SessionExportRepairs) != 2 {
|
||||
t.Fatalf("original evidence/execution changed: %+v", detail)
|
||||
}
|
||||
if detail.Steps[0].SessionExportRecovery == nil || detail.Steps[0].SessionExportRecovery.Status != "complete" {
|
||||
t.Fatal("recovery state not visible")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomaticSessionExportRecoveryWrongSessionExhaustsNeverClean(t *testing.T) {
|
||||
h, s, id := recoveryRunner(t)
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
calls := filepath.Join(dir, "calls")
|
||||
bin := filepath.Join(dir, "opencode")
|
||||
script := fmt.Sprintf("#!/bin/sh\necho read >> %q\necho '{\"info\":{\"id\":\"ses_wrong\"},\"messages\":[{\"info\":{\"role\":\"assistant\"},\"parts\":[{\"type\":\"text\",\"text\":\"wrong\"}]}]}'\n", calls)
|
||||
if err := os.WriteFile(bin, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PIPELINES_OPENCODE", bin)
|
||||
h.runner.exportSession = stage.ExportSession
|
||||
for range 3 {
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
if worked, err := h.runner.recoverSessionExportJob(ctx, time.UnixMilli(job.NextAt)); err != nil || !worked {
|
||||
t.Fatalf("job failed: %v %v", worked, err)
|
||||
}
|
||||
}
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
if job.Status != "exhausted" || job.Attempts != 3 || !strings.Contains(job.Diagnostic, "identity mismatch") {
|
||||
t.Fatalf("wrong session looks clean: %+v", job)
|
||||
}
|
||||
if worked, err := h.runner.recoverSessionExportJob(ctx, time.Now().Add(24*time.Hour)); err != nil || worked {
|
||||
t.Fatalf("unbounded recovery: %v %v", worked, err)
|
||||
}
|
||||
body, _ := os.ReadFile(calls)
|
||||
if strings.Count(string(body), "read") != 3 {
|
||||
t.Fatalf("wrong-session read was retried internally: %s", body)
|
||||
}
|
||||
detail, _ := s.GetRun(ctx, id)
|
||||
if len(detail.Steps) != 1 || len(detail.Steps[0].SessionExportRepairs) != 3 {
|
||||
t.Fatalf("lost failed attempts: %+v", detail.Steps)
|
||||
}
|
||||
for _, repair := range detail.Steps[0].SessionExportRepairs {
|
||||
if repair.Status != "failed" || repair.HTML != "" {
|
||||
t.Fatalf("wrong session marked clean: %+v", repair)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutomaticSessionExportRecoveryDefersRuntimeCleanup(t *testing.T) {
|
||||
h, s, id := recoveryRunner(t)
|
||||
ctx := context.Background()
|
||||
h.runner.mu.Lock()
|
||||
h.runner.active[id] = activeRun{}
|
||||
h.runner.mu.Unlock()
|
||||
defer func() { h.runner.mu.Lock(); delete(h.runner.active, id); h.runner.mu.Unlock() }()
|
||||
job, _ := s.SessionExportJob(ctx, id, 1)
|
||||
if worked, err := h.runner.recoverSessionExportJob(ctx, time.UnixMilli(job.NextAt)); err != nil || !worked {
|
||||
t.Fatalf("deferral failed: %v %v", worked, err)
|
||||
}
|
||||
job, _ = s.SessionExportJob(ctx, id, 1)
|
||||
if job.Status != "pending" || job.Attempts != 0 {
|
||||
t.Fatalf("cleanup spent attempt: %+v", job)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExportRecoveryWorkerStopsWithContextAndClosedStore(t *testing.T) {
|
||||
for _, closeStore := range []bool{false, true} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
s, err := pipeline.Open(filepath.Join(t.TempDir(), "worker.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := newRunner(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if closeStore {
|
||||
s.Close()
|
||||
} else {
|
||||
cancel()
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { r.schedulerWG.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("export worker did not stop")
|
||||
}
|
||||
cancel()
|
||||
s.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExportRecoveryReopensAndRepairsAutomaticallyWithoutStageRerun(t *testing.T) {
|
||||
h, s, id := recoveryRunner(t)
|
||||
root := h.runner.artifactsRoot
|
||||
path := filepath.Join(s.Directory(), "session.db")
|
||||
original, _ := s.GetRun(context.Background(), id)
|
||||
before, _ := json.Marshal(original.Steps[0].SessionExport)
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
sessionExportCLI(t) // read-only native CLI fixture, never a live model/run
|
||||
r, err := newRunner(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { cancel(); r.schedulerWG.Wait(); s.Close() }()
|
||||
r.artifactsRoot = root
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
t.Error("restart recovery reran a stage")
|
||||
return stage.Result{}, errors.New("forbidden rerun")
|
||||
}
|
||||
deadline := time.Now().Add(9 * time.Second)
|
||||
for {
|
||||
job, err := s.SessionExportJob(ctx, id, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if job != nil && job.Status == "complete" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("persisted job did not auto-recover: %+v", job)
|
||||
}
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
detail, err := s.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _ := json.Marshal(detail.Steps[0].SessionExport)
|
||||
if string(before) != string(after) || len(detail.Steps) != 1 || len(detail.Steps[0].SessionExportRepairs) != 1 || detail.Status != original.Status {
|
||||
t.Fatalf("recovery overwrote history or reran stage: %+v", detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExportWorkerStoreDoneCancelsInflightReadbackContext(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
ctx, cancel := sessionExportWorkerContext(context.Background(), done)
|
||||
defer cancel()
|
||||
exportCtx, stop := context.WithTimeout(ctx, stage.SessionExportTimeout)
|
||||
defer stop()
|
||||
close(done)
|
||||
select {
|
||||
case <-exportCtx.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("Store.Done did not cancel in-flight readback context")
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
@@ -17,6 +18,10 @@ import (
|
||||
// repairSessionExport is runtime-owned and read-only to OpenCode. It never
|
||||
// resumes a session, runs a stage, changes a definition, or overwrites evidence.
|
||||
func (r *runner) repairSessionExport(ctx context.Context, id int64, sequence int) (*protocol.RunDetail, error) {
|
||||
return r.repairSessionExportOwned(ctx, id, sequence, nil)
|
||||
}
|
||||
|
||||
func (r *runner) repairSessionExportOwned(ctx context.Context, id int64, sequence int, expected *pipeline.SessionOwner) (*protocol.RunDetail, error) {
|
||||
r.exportRepairMu.Lock()
|
||||
defer r.exportRepairMu.Unlock()
|
||||
if id <= 0 || sequence <= 0 {
|
||||
@@ -52,6 +57,9 @@ func (r *runner) repairSessionExport(ctx context.Context, id int64, sequence int
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("exact original session ownership metadata unavailable: %w", err)
|
||||
}
|
||||
if expected != nil && (owner.ID != expected.ID || owner.Backend != expected.Backend || owner.Directory != expected.Directory || owner.Reference != expected.Reference) {
|
||||
return nil, fmt.Errorf("original session ownership differs from durable recovery snapshot; export refused")
|
||||
}
|
||||
active, err := r.store.ActiveSessionOwners(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
Reference in New Issue
Block a user