Runner: no I/O under the runner lock; retry run settlement

- Run worktree creation happens outside r.mu; the source tree is protected
  from storage maintenance meanwhile and the reservation is re-checked under
  the lock before the run is recorded (a refused tree is discarded).
- getRun/listRuns read the store without r.mu; listRuns finds failed runs
  with an active cleanup agent in one query (partial index) instead of a
  detail read per failed run.
- finishRunState writes the deliverable and walks the run size without the
  lock; FinishRun retries transient failures with backoff (a refused
  transition is final).
- Launch teardown retries a failed read with backoff instead of keeping the
  reservation forever; a kept run that cannot be read at reattach is retried
  and then marked interrupted (stopping its adopted session first).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 00:42:25 +00:00
parent ab6b2bb632
commit 2ea7eb9db0
7 changed files with 567 additions and 70 deletions
+60 -2
View File
@@ -172,9 +172,10 @@ func (r *runner) reattachRun(plan reattachPlan) {
log.Printf("run %d: restart stage %s after server restart: %v", id, plan.step.Stage, err)
}
}
detail, err := r.store.GetRun(ctx, id)
detail, err := r.readForReattach(ctx, id)
if err != nil {
log.Printf("run %d: read for reattach: %v", id, err)
log.Printf("run %d: read for reattach: %v; marking it interrupted", id, err)
r.abandonReattach(plan, err)
return
}
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
@@ -199,6 +200,63 @@ func (r *runner) reattachRun(plan reattachPlan) {
}
}
// reattachReadBackoff bounds the retries of a reattach read; reattach runs
// before requests are served, so it stays short.
var reattachReadBackoff = []time.Duration{100 * time.Millisecond, 500 * time.Millisecond, 2 * time.Second}
// readForReattach reads a kept run, retrying a transient failure.
func (r *runner) readForReattach(ctx context.Context, id int64) (*protocol.RunDetail, error) {
for attempt := 0; ; attempt++ {
detail, err := runSettleRead(r, ctx, id)
if err == nil && detail != nil {
return detail, nil
}
if err == nil {
err = fmt.Errorf("run %d not found", id)
}
if attempt >= len(reattachReadBackoff) || ctx.Err() != nil {
return nil, err
}
if !r.sleepSettle(reattachReadBackoff[attempt]) {
return nil, err
}
}
}
// abandonReattach settles a kept run that cannot be continued, instead of
// leaving it "running" with nothing executing it: an adopted session is
// stopped first, then the run is marked interrupted. If the session cannot be
// stopped, the run keeps its workspace reserved as cleanup-unconfirmed, as
// start-up recovery does.
func (r *runner) abandonReattach(plan reattachPlan, cause error) {
id := plan.runID
if plan.kind == reattachAdopt {
stop, cancel := context.WithTimeout(r.ctx, 20*time.Second)
err := interruptRecoveredSession(stop, plan.owner)
if err == nil {
err = r.store.ConfirmRecoveredSession(stop, plan.owner)
}
cancel()
if err != nil {
log.Printf("run %d: stop session %s after a failed reattach: %v; workspace stays reserved", id, plan.owner.ID, err)
mark, done := context.WithTimeout(context.Background(), 10*time.Second)
if markErr := r.store.MarkCleanupUnconfirmed(mark, id); markErr != nil {
log.Printf("run %d: mark cleanup unconfirmed: %v", id, markErr)
}
done()
r.mu.Lock()
if _, ok := r.active[id]; !ok {
r.active[id] = activeRun{cancel: func() {}, workspace: plan.owner.Directory}
}
r.mu.Unlock()
return
}
}
r.finishRunWithRetry(id, "interrupted", "", "Server restarted; the run could not be reattached: "+cause.Error(), stage.Values{})
r.forgetAttention(id)
r.forgetNotifyMode(id)
}
// rebuildAdoptState restores the loop state at the planned visit: memory and
// visit counts from every other persisted step, the handoff input from the
// visit before it, and (for an adopted visit) the session to re-adopt.
+204 -67
View File
@@ -41,6 +41,9 @@ type runner struct {
artifactsRoot string
mu sync.Mutex
active map[int64]activeRun
// admitting counts admissions creating a run worktree from each source
// workspace outside r.mu; storage maintenance keeps those trees.
admitting map[string]int
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
// dirEnv resolves the run workspace's own environment (direnv/mise) at
// run start; nil uses workenv.Default.
@@ -178,7 +181,7 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot
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, detach: detach, reattach: plans}
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, admitting: map[string]int{}, 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
}
@@ -329,38 +332,57 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
}
r.mu.Lock()
defer r.mu.Unlock()
// Another run may have reserved this workspace while the title was
// generated, so re-check before reserving it; a race on the request key is
// handled by the store's idempotent insert.
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
return nil, err
}
}
// Storage maintenance may have removed a clean inactive tree while an
// admission was generating its title. Refuse that vanished workspace under
// the same lock used by removal instead of launching into a missing tree.
if info, err := os.Stat(workspace); err != nil || !info.IsDir() {
return nil, fmt.Errorf("run workspace is no longer available: %s", workspace)
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
r.mu.Unlock()
return nil, err
}
// A fresh run started from a repository's main checkout gets its own
// worktree and branch, so runs never share a tree with each other or with
// the operator's uncommitted work. A retry keeps its run's tree.
// the operator's uncommitted work. A retry keeps its run's tree. Creating
// the worktree can take up to a minute, so it runs without r.mu (listings,
// details and cancellation must not stall behind it); storage maintenance
// keeps the source tree meanwhile (r.admitting), and the reservation is
// re-checked under the lock before the run is recorded.
isolated := ""
if existing == 0 && request.RetrySource == 0 {
source := workspace
if r.admitting == nil {
r.admitting = map[string]int{}
}
r.admitting[source]++
r.mu.Unlock()
isolateCtx, isolateCancel := context.WithTimeout(r.ctx, time.Minute)
tree, isolateErr := isolateRunWorkspace(isolateCtx, workspace, runTitle.Text)
tree, isolateErr := isolateRunWorkspace(isolateCtx, source, runTitle.Text)
isolateCancel()
r.mu.Lock()
if r.admitting[source]--; r.admitting[source] <= 0 {
delete(r.admitting, source)
}
if isolateErr != nil {
r.mu.Unlock()
return nil, isolateErr
}
if tree != workspace {
if tree != source {
isolated = tree
}
workspace = tree
request.Input["pwd"] = workspace
recheck := r.ctx.Err()
if recheck == nil {
recheck = r.checkAdmissionWorkspace(workspace, existing)
}
if recheck != nil {
r.mu.Unlock()
if isolated != "" {
discardRunWorktree(isolated)
}
return nil, recheck
}
}
defer r.mu.Unlock()
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat, StageSkills: stageSkills}, runTitle, retryOf...)
if isolated != "" && (err != nil || !created) {
// The run was refused or an identical request won the race: the fresh
@@ -431,42 +453,100 @@ func (r *runner) launch(id int64, workspace string, fn func(context.Context)) {
go func() {
defer r.wg.Done()
defer cancel()
defer func() {
r.mu.Lock()
defer r.mu.Unlock()
if entry, ok := r.active[id]; !ok || entry.generation != generation {
return // A parked launch must not remove the resumed reservation.
}
check, done := context.WithTimeout(context.Background(), 10*time.Second)
defer done()
detail, err := r.store.GetRun(check, id)
if err != nil || detail.CleanupUnconfirmed {
return // Fail closed: execution/cleanup has not settled durably.
}
if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested {
if err := r.store.CancelWaiting(check, id); err != nil {
return
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
}
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
delete(r.active, id)
}
// A landed (or change-free) successful run's own worktree is no
// longer needed; anything unlanded or uncommitted is kept.
if detail.Status == "succeeded" && detail.FinishedAt != "" {
workspace := detail.Workspace
go func() {
if removeLandedRunWorktree(workspace) {
log.Printf("run %d: removed its landed worktree %s", id, workspace)
}
}()
}
}()
defer r.settleLaunch(id, generation)
fn(ctx)
}()
}
// settleLaunch releases a finished launch's reservation once its run has
// settled durably. A failed read is retried with backoff (the lock is not held
// while waiting); a run whose cleanup is unconfirmed, or that cannot be read
// even after the retries, keeps its reservation (fail closed).
func (r *runner) settleLaunch(id int64, generation *byte) {
for attempt := 0; ; attempt++ {
settled, err := r.settleLaunchOnce(id, generation)
if settled {
return
}
if attempt >= len(runSettleBackoff) {
log.Printf("run %d: launch teardown could not read the run; its workspace stays reserved: %v", id, err)
return
}
if !r.sleepSettle(runSettleBackoff[attempt]) {
return
}
}
}
// settleLaunchOnce is one teardown attempt under r.mu. It reports false only
// when the run could not be read.
func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
if entry, ok := r.active[id]; !ok || entry.generation != generation {
return true, nil // A parked launch must not remove the resumed reservation.
}
check, done := context.WithTimeout(context.Background(), 10*time.Second)
defer done()
detail, err := runSettleRead(r, check, id)
if err != nil || detail == nil {
return false, err
}
if detail.CleanupUnconfirmed {
return true, nil // Fail closed: execution/cleanup has not settled durably.
}
if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested {
if err := r.store.CancelWaiting(check, id); err != nil {
// A refused transition fails closed; anything else is retried.
return errors.Is(err, pipeline.ErrInvalidRunTransition), err
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
}
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
delete(r.active, id)
}
// A landed (or change-free) successful run's own worktree is no longer
// needed; anything unlanded or uncommitted is kept.
if detail.Status == "succeeded" && detail.FinishedAt != "" {
workspace := detail.Workspace
go func() {
if removeLandedRunWorktree(workspace) {
log.Printf("run %d: removed its landed worktree %s", id, workspace)
}
}()
}
return true, nil
}
// runFinishWrite persists a run's terminal state; tests replace it to inject
// transient store failures.
var runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error {
return r.store.FinishRun(ctx, id, status, outcome, diagnostic, input)
}
// runSettleRead reads a run for settlement; tests replace it to inject
// transient store failures.
var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) {
return r.store.GetRun(ctx, id)
}
// checkAdmissionWorkspace refuses admitting a fresh run (existing == 0) into a
// workspace another run reserves, and any admission into a vanished workspace:
// storage maintenance may have removed a clean inactive tree while an
// admission was generating its title, so it is checked under the same lock
// removal takes. Callers must hold r.mu.
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
return err
}
}
if info, err := os.Stat(workspace); err != nil || !info.IsDir() {
return fmt.Errorf("run workspace is no longer available: %s", workspace)
}
return nil
}
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
// reserves an overlapping resolved workspace. Callers must hold r.mu.
func (r *runner) checkWorkspaceFree(workspace string) error {
@@ -530,12 +610,15 @@ func repositoryRoot(dir string) string {
}
}
// getRun reads one run's detail. The store read runs without r.mu, so a
// detail never waits behind admission or settlement work; only the executing
// overlay reads the active set under the lock.
func (r *runner) getRun(id int64) (*protocol.RunDetail, error) {
r.mu.Lock()
defer r.mu.Unlock()
d, err := r.store.GetRun(r.ctx, id)
if d != nil {
r.mu.Lock()
_, d.Executing = r.active[id]
r.mu.Unlock()
if d.ExportPendingSequence > 0 {
d.Executing = false
}
@@ -579,28 +662,38 @@ func (r *runner) overlayEffectiveModels(d *protocol.RunDetail) {
}
}
// listRuns lists every run with its executing overlay. The store reads run
// without r.mu (a listing never waits behind admission or settlement), and a
// failed run whose cleanup agent is still active is found with one query
// rather than a detail read per failed run.
func (r *runner) listRuns() ([]protocol.RunSummary, error) {
r.mu.Lock()
defer r.mu.Unlock()
items, err := r.store.ListRuns(r.ctx)
if err != nil {
return items, err
}
var agents map[int64]bool
for _, item := range items {
if item.Status == "failed" {
if agents, err = r.store.RunsWithActiveAgents(r.ctx); err != nil {
return nil, err
}
break
}
}
r.mu.Lock()
for i := range items {
_, items[i].Executing = r.active[items[i].ID]
}
r.mu.Unlock()
for i := range items {
if items[i].ExportPendingSequence > 0 {
items[i].Executing = false
}
if items[i].Status == "failed" && !items[i].Executing {
d, err := r.store.GetRun(r.ctx, items[i].ID)
if err != nil {
return nil, err
}
for _, step := range d.Steps {
if step.AgentActive {
items[i].Executing = true
}
}
if items[i].Status == "failed" && !items[i].Executing && agents[items[i].ID] {
items[i].Executing = true
}
}
return items, err
return items, nil
}
type retryCheckpoint struct {
@@ -1503,23 +1596,26 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) {
}
func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) {
r.mu.Lock()
// The deliverable and the size walk touch files only: they run without r.mu,
// so listings and details do not stall behind a large run finishing. The
// run stays in r.active (its workspace reserved) until the launch teardown.
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if status == "succeeded" {
if err := r.finalizeDeliverable(c, id, sequence, input); err != nil {
status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error()
}
}
cancel()
// Measure the run's footprint while it is still recorded as active: its
// files are final, and measuring after the terminal status is written would
// widen the window in which a client sees the run finished but still owned.
// The status write re-marks the cache stale, so the background sizer then
// records the exact value including the final output row.
size := r.finishedSize(id)
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
log.Printf("finish run %d: %v", id, err)
}
r.finishRunWithRetry(id, status, outcome, diagnostic, input)
r.mu.Lock()
c, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// The store atomically makes a stop request win over a late success.
detail, getErr := r.store.GetRun(c, id)
if getErr != nil || detail == nil {
@@ -1555,6 +1651,47 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
r.forgetNotifyMode(id)
}
// runSettleBackoff is the retry schedule for durable run settlement writes
// (finishing a run, reading it back at launch teardown). A transient store
// failure (a busy or briefly unavailable database) must not leave a run
// "running" with its workspace reserved until restart.
var runSettleBackoff = []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second}
// sleepSettle waits out one backoff step; false when the server is stopping.
func (r *runner) sleepSettle(delay time.Duration) bool {
select {
case <-r.ctx.Done():
return false
case <-time.After(delay):
return true
}
}
// finishRunWithRetry persists a run's terminal state, retrying a transient
// failure with backoff (each attempt under r.mu, the waits without it). A
// refused transition (an agent still active, cleanup unconfirmed, a run
// already settled) is final and not retried.
func (r *runner) finishRunWithRetry(id int64, status, outcome, diagnostic string, input stage.Values) {
for attempt := 0; ; attempt++ {
r.mu.Lock()
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err := runFinishWrite(r, c, id, status, outcome, diagnostic, input)
cancel()
r.mu.Unlock()
if err == nil {
return
}
if errors.Is(err, pipeline.ErrInvalidRunTransition) || attempt >= len(runSettleBackoff) {
log.Printf("finish run %d: %v", id, err)
return
}
log.Printf("finish run %d (attempt %d, retrying): %v", id, attempt+1, err)
if !r.sleepSettle(runSettleBackoff[attempt]) {
return
}
}
}
// completedSteps counts the completed steps of a run detail; resume uses it to
// seed the terminal delta without another store read.
func completedSteps(steps []protocol.RunStep) int {
+274
View File
@@ -0,0 +1,274 @@
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)
})
}
+3
View File
@@ -190,6 +190,9 @@ func (m *storageManager) apply(ctx context.Context, preview protocol.StorageClea
for _, active := range m.runner.active {
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, active.workspace)
}
for source := range m.runner.admitting {
config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, source)
}
var tree storageWorktree
found := false
for _, known := range before.Worktrees {