fix: keep cancellation pending until execution cleanup is confirmed

This commit is contained in:
2026-10-20 15:47:07 +01:00
parent 1cf5156c77
commit b96b9d94a6
26 changed files with 690 additions and 142 deletions
+120 -42
View File
@@ -23,8 +23,8 @@ import (
"git.a-wan.net/alan/pipelines/internal/turn"
)
// activeRun records one in-flight run's cancellation seam and the resolved
// workspace it is changing. A single map is the only active-run state, so the
// activeRun records an in-flight or cleanup-unconfirmed run's cancellation seam
// and resolved workspace reservation. A single map is the active-run state, so the
// workspace cannot drift from the cancel function.
type activeRun struct {
cancel context.CancelFunc
@@ -77,6 +77,9 @@ type runner struct {
}
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
if err := s.AcquireRunnerLock(); err != nil {
return nil, err
}
sessions, err := s.ActiveSessionOwners(ctx)
if err != nil {
return nil, err
@@ -101,7 +104,17 @@ func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
return nil, err
}
root := filepath.Join(s.Directory(), "artifacts")
r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: map[int64]activeRun{}, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession}
active := map[int64]activeRun{}
rows, err := s.ListRuns(ctx)
if err != nil {
return nil, err
}
for _, row := range rows {
if row.CleanupUnconfirmed {
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}
r.schedulerWG.Add(1)
go func() { defer r.schedulerWG.Done(); r.resumeRunNotifications() }()
return r, nil
@@ -331,24 +344,48 @@ 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(); delete(r.active, id); r.mu.Unlock() }()
defer func() {
r.mu.Lock()
defer r.mu.Unlock()
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)
}
}()
fn(ctx)
}()
}
// checkWorkspaceFree refuses a run when an active run is already changing the
// same resolved workspace. The workspace is the only scope a run reserves, and
// one active run per workspace keeps this scan finding at most one match, so the
// message is deterministic. Callers must hold r.mu.
// 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 {
for id, entry := range r.active {
if entry.workspace == workspace {
if workspacesOverlap(entry.workspace, workspace) {
return fmt.Errorf("run %d is already active in workspace %s; wait for it to finish or start this run in a different workspace (for example another checkout of the repository)", id, workspace)
}
}
return nil
}
func workspacesOverlap(a, b string) bool {
within := func(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
return within(a, b) || within(b, a)
}
func (r *runner) getRun(id int64) (*protocol.RunDetail, error) {
r.mu.Lock()
defer r.mu.Unlock()
@@ -675,32 +712,34 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
func (r *runner) cancel(id int64) error {
r.mu.Lock()
defer r.mu.Unlock()
entry, ok := r.active[id]
r.mu.Unlock()
// Persist the cancellation before asking the runner to stop. A stage that is
// stuck in a context-unaware provider call must not leave the run "running":
// the operator's Stop is a terminal decision, and the live row/step show it
// immediately. FinishStep/FinishRun only update active rows, so the late
// stage return cannot undo this.
if err := r.store.Cancel(r.ctx, id); err != nil {
return err
}
if ok {
entry.cancel()
} else {
// Only a parked human run is known to have no live executor.
if err := r.store.CancelWaiting(r.ctx, id); err != nil {
return err
}
}
r.forgetAttention(id)
if r.events != nil {
if detail, err := r.store.GetRun(r.ctx, id); err == nil && detail != nil {
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
r.emitRun(protocol.RunEventFrame{
RunID: id,
Workspace: detail.Workspace,
Status: detail.Status,
Outcome: detail.Outcome,
CurrentStage: detail.CurrentStage,
CompletedSteps: detail.CompletedSteps,
FinishedAt: detail.FinishedAt,
}, true)
RunID: id,
Workspace: detail.Workspace,
Status: detail.Status,
Outcome: detail.Outcome,
CurrentStage: detail.CurrentStage,
CompletedSteps: detail.CompletedSteps,
FinishedAt: detail.FinishedAt,
CancelRequested: detail.CancelRequested,
CleanupUnconfirmed: detail.CleanupUnconfirmed,
}, !ok)
}
}
return nil
@@ -1265,20 +1304,22 @@ 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()
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
// Cancel wins over a late stage result: the store already marked the run
// canceled and FinishRun only updates queued/running rows. Read the
// actual state so this turn emits and notifies canceled, never a failure
// caused by the canceled step's persistence guard.
if detail, getErr := r.store.GetRun(c, id); getErr == nil && detail != nil && detail.Status == protocol.RunStatusCanceled {
status = protocol.RunStatusCanceled
outcome = detail.Outcome
diagnostic = detail.Diagnostic
} else {
log.Printf("finish run %d: %v", id, err)
}
log.Printf("finish run %d: %v", id, err)
}
// The store atomically makes a stop request win over a late success.
detail, getErr := r.store.GetRun(c, id)
if getErr != nil || detail == nil {
r.mu.Unlock()
return
}
status, outcome, diagnostic = detail.Status, detail.Outcome, detail.Diagnostic
r.mu.Unlock()
if detail.FinishedAt == "" {
return // Cleanup is not confirmed: never emit a false terminal event.
}
// Push the terminal delta before the attention notification, so a slow ntfy
// never delays the live update the app folds.
@@ -1289,7 +1330,7 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
Outcome: outcome,
CurrentStage: currentStage,
CompletedSteps: completed,
FinishedAt: time.Now().UTC().Format(time.RFC3339),
FinishedAt: detail.FinishedAt,
}, true)
r.notifyRun(id, name, status, sequence, currentStage, diagnostic)
// The run is terminal: nothing more can notify for it.
@@ -1353,12 +1394,27 @@ func turnOutputOnly(output stage.Values) bool {
}
func (r *runner) finishStage(id int64, name, workspace string, selected protocol.Stage, state *runState, step protocol.RunStep) (status, outcome, diagnostic string, terminal bool, err error) {
r.mu.Lock()
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
detail, getErr := r.store.GetRun(save, id)
if getErr != nil {
cancel()
r.mu.Unlock()
return "", "", "", false, getErr
}
if detail.CancelRequested {
step.Status, step.Outcome, step.Target = "canceled", "", ""
step.Diagnostic = "Canceled by operator; execution returned"
}
persistErr := r.store.FinishStep(save, id, step)
cancel()
r.mu.Unlock()
if persistErr != nil {
return "", "", "", false, persistErr
}
if detail.CancelRequested {
return "canceled", "", step.Diagnostic, true, nil
}
if step.Status == "completed" {
values, copyErr := copyValues(stage.Values(step.Output))
if copyErr != nil {
@@ -1696,6 +1752,15 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
result, err = stage.DefaultRegistry().Run(stageCtx, def, input)
}
}()
ownershipCtx, ownershipCancel := context.WithTimeout(context.Background(), 10*time.Second)
activeSessions, ownershipErr := r.store.ActiveAgentSessionsForRun(ownershipCtx, id)
ownershipCancel()
if ownershipErr != nil || len(activeSessions) > 0 {
err = errors.Join(stage.ErrStageCleanup, err, ownershipErr)
}
if ctx.Err() != nil && !errors.Is(err, stage.ErrStageCleanup) {
err = ctx.Err() // Ignore a context-unaware executor's late success.
}
if stage.EffectiveType(def.Type) == stage.ModelType && err == nil {
ensureTurnOutput(visitTurn, result)
}
@@ -1707,6 +1772,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
if errors.Is(err, stage.ErrStageCleanup) {
changes.Status = "partial"
changes.Diagnostic = "Agent cleanup was not confirmed; files may still be changing."
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if markErr := r.store.MarkCleanupUnconfirmed(save, id); markErr != nil {
log.Printf("mark cleanup unconfirmed for run %d: %v", id, markErr)
}
cancel()
}
// Export the stage's session into its own artifacts directory before the
// bounded scan, so the existing listing and serving paths find the files
@@ -1790,6 +1860,17 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Transcript = stage.RetainSession(step.Transcript, stageSession)
}
step.Target = def.Edges[step.Outcome]
if errors.Is(err, stage.ErrStageCleanup) {
// Retain the partial evidence without pretending that the agent stopped.
step.Status, step.Outcome, step.Target = "running", "", ""
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
if saveErr := r.store.FinishStep(save, id, step); saveErr != nil {
log.Printf("save cleanup evidence for run %d: %v", id, saveErr)
}
cancel()
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
return
}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
for _, outcome := range selected.Limits.On {
@@ -1823,6 +1904,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
finish("failed", "error", finishErr.Error())
return
}
if ctx.Err() != nil {
finish("canceled", "", ctx.Err().Error())
return
}
// Advance the in-memory UI-surface evidence only after the step is
// persisted, so the skip guard agrees with what the store holds.
state.recordChanges(step.FileChanges, step.Artifacts)
@@ -1856,13 +1941,6 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
Artifacts: len(step.Artifacts),
},
}, false)
if useAgent || errors.Is(err, stage.ErrStageCleanup) {
sessions, checkErr := r.store.ActiveAgentSessionsForRun(context.Background(), id)
if checkErr != nil || len(sessions) > 0 {
finish("failed", "error", "agent quiescence not confirmed; inspect retained session before further work")
return
}
}
if ctx.Err() != nil {
finish("canceled", "", ctx.Err().Error())
return