package server import ( "context" "database/sql" "errors" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing" "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" ) func fastRunSettle(t *testing.T) { t.Helper() settle, reattach := runSettleBackoff, reattachReadBackoff runSettleBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} reattachReadBackoff = []time.Duration{time.Millisecond, time.Millisecond} t.Cleanup(func() { runSettleBackoff, reattachReadBackoff = settle, reattach }) } func reliabilityRunner(t *testing.T) (context.Context, *pipeline.Store, *runner, int64) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) s, err := pipeline.Open(filepath.Join(t.TempDir(), "reliability.db")) if err != nil { t.Fatal(err) } if _, err := s.Submit(ctx, "workflow", pipeline.Template([]string{"one"}, true)); err != nil { t.Fatal(err) } items, _ := s.List(ctx) r, err := newRunner(ctx, s) if err != nil { t.Fatal(err) } r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil } t.Cleanup(func() { cancel(); r.wg.Wait(); r.schedulerWG.Wait(); s.Close() }) return ctx, s, r, items[0].ID } // A transient failure persisting a run's end is retried: the run settles and // its workspace is released instead of staying "running" and reserved. func TestFinishRunTransientFailureIsRetried(t *testing.T) { fastRunSettle(t) ctx, s, r, pid := reliabilityRunner(t) var attempts atomic.Int32 original := runFinishWrite runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error { if attempts.Add(1) <= 2 { return errors.New("database is locked") } return original(r, ctx, id, status, outcome, diagnostic, input) } t.Cleanup(func() { runFinishWrite = original }) workspace := t.TempDir() d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "transient", Workspace: workspace, Input: map[string]any{"prompt": "task"}}) if err != nil { t.Fatal(err) } r.wg.Wait() detail, err := s.GetRun(ctx, d.ID) if err != nil || detail.Status != "succeeded" || detail.FinishedAt == "" { t.Fatalf("run not settled after a transient failure: %+v %v", detail, err) } if attempts.Load() != 3 { t.Fatalf("finish attempts = %d, want 3", attempts.Load()) } r.mu.Lock() _, reserved := r.active[d.ID] r.mu.Unlock() if reserved { t.Fatal("settled run still reserves its workspace") } } // A refused transition is final: it is not retried. func TestFinishRunRefusedTransitionIsNotRetried(t *testing.T) { fastRunSettle(t) _, _, r, pid := reliabilityRunner(t) var attempts atomic.Int32 original := runFinishWrite runFinishWrite = func(*runner, context.Context, int64, string, string, string, stage.Values) error { attempts.Add(1) return pipeline.ErrInvalidRunTransition } t.Cleanup(func() { runFinishWrite = original }) if _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "refused", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}); err != nil { t.Fatal(err) } r.wg.Wait() if attempts.Load() != 1 { t.Fatalf("refused transition attempted %d times", attempts.Load()) } } // The launch teardown retries a failed read instead of keeping the // reservation forever. func TestLaunchTeardownRetriesAFailedRead(t *testing.T) { fastRunSettle(t) _, _, r, pid := reliabilityRunner(t) var reads atomic.Int32 original := runSettleRead runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) { if reads.Add(1) <= 2 { return nil, errors.New("database is locked") } return original(r, ctx, id) } t.Cleanup(func() { runSettleRead = original }) d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "teardown", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}) if err != nil { t.Fatal(err) } r.wg.Wait() r.mu.Lock() _, reserved := r.active[d.ID] r.mu.Unlock() if reserved || reads.Load() < 3 { t.Fatalf("reservation kept after a transient teardown read failure (reads=%d)", reads.Load()) } } // A run kept for reattachment that cannot be read is not left "running": // its adopted session is stopped and the run is marked interrupted. func TestReattachReadFailureMarksTheRunInterrupted(t *testing.T) { fastRunSettle(t) interrupts := seamRestartRecovery(t, nil) f := stopMidStage(t, ownedLiveStage) r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { t.Error("an unreadable run executed") return stage.Result{}, nil }) original := runSettleRead runSettleRead = func(*runner, context.Context, int64) (*protocol.RunDetail, error) { return nil, errors.New("database is unavailable") } t.Cleanup(func() { runSettleRead = original }) r.reattachRuns() r.wg.Wait() runSettleRead = original d, err := s.GetRun(context.Background(), f.runID) if err != nil { t.Fatal(err) } if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be reattached") { t.Fatalf("unreadable reattached run left as %s: %q", d.Status, d.Diagnostic) } if interrupts.Load() != 1 { t.Fatalf("adopted session interrupted %d times, want 1", interrupts.Load()) } if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { t.Fatalf("session still recorded active: %+v", owners) } } // A failed run whose cleanup agent is still active is listed as executing, // found with one query rather than a detail read per failed run. func TestListRunsMarksFailedRunsWithActiveAgentsExecuting(t *testing.T) { ctx, s, r, pid := reliabilityRunner(t) d, _ := s.Get(ctx, pid, 1) var ids []int64 for _, key := range []string{"a", "b"} { id, _, err := s.CreateRun(ctx, d, key, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) if err != nil { t.Fatal(err) } if err := s.BeginStep(ctx, id, 1, "one", map[string]any{}); err != nil { t.Fatal(err) } if err := s.FinishRun(ctx, id, "failed", "error", "boom", nil); err != nil { t.Fatal(err) } ids = append(ids, id) } db, err := sql.Open("sqlite", s.DatabasePath()) if err != nil { t.Fatal(err) } defer db.Close() if _, err := db.ExecContext(ctx, `UPDATE run_steps SET agent_active=1 WHERE run_id=?`, ids[0]); err != nil { t.Fatal(err) } runs, err := r.listRuns() if err != nil { t.Fatal(err) } executing := map[int64]bool{} for _, run := range runs { executing[run.ID] = run.Executing } if !executing[ids[0]] || executing[ids[1]] { t.Fatalf("executing = %v", executing) } } // Creating a run's worktree (a git hook can make it arbitrarily slow) no // longer holds the runner lock: listings, details and another admission in a // different workspace proceed meanwhile. func TestRunWorktreeCreationDoesNotBlockListings(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git not installed") } _, _, r, pid := reliabilityRunner(t) repo := filepath.Join(t.TempDir(), "repo") git := func(args ...string) { t.Helper() cmd := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"}, args...)...) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("git %v: %v: %s", args, err, out) } } if err := os.MkdirAll(repo, 0o755); err != nil { t.Fatal(err) } git("init", "-q") git("commit", "-q", "--allow-empty", "-m", "root") started, release := filepath.Join(t.TempDir(), "started"), filepath.Join(t.TempDir(), "release") hook := "#!/bin/sh\ntouch '" + started + "'\nfor i in $(seq 1 200); do [ -e '" + release + "' ] && exit 0; sleep 0.05; done\n" if err := os.WriteFile(filepath.Join(repo, ".git", "hooks", "post-checkout"), []byte(hook), 0o755); err != nil { t.Fatal(err) } admitted := make(chan error, 1) go func() { _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "slow-tree", Title: "slow tree", Workspace: repo, Input: map[string]any{"prompt": "task"}}) admitted <- err }() waitFor(t, "worktree hook running", func() bool { _, err := os.Stat(started); return err == nil }) done := make(chan error, 1) go func() { if _, err := r.listRuns(); err != nil { done <- err return } _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "elsewhere", Title: "elsewhere", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}) done <- err }() select { case err := <-done: if err != nil { t.Fatal(err) } case <-time.After(5 * time.Second): t.Fatal("listing or another admission blocked behind worktree creation") } if err := os.WriteFile(release, nil, 0o644); err != nil { t.Fatal(err) } if err := <-admitted; err != nil { t.Fatal(err) } r.wg.Wait() runs, err := r.listRuns() if err != nil || len(runs) != 2 { t.Fatalf("runs = %+v %v", runs, err) } for _, run := range runs { if run.Workspace == repo { t.Fatalf("run used the main checkout instead of its own worktree: %+v", run) } } t.Cleanup(func() { // Remove the run worktree sibling the admission created. os.RemoveAll(repo + runWorktreesDirSuffix) }) }