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
+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 {