fix: keep cancellation pending until execution cleanup is confirmed
This commit is contained in:
@@ -514,9 +514,8 @@ func waitEnteredString(t *testing.T, entered <-chan string) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOwnActiveSessionStillFailsRun proves a run still fails when one of its OWN
|
||||
// agent sessions is left active after the stage completes.
|
||||
func TestOwnActiveSessionStillFailsRun(t *testing.T) {
|
||||
// Active ownership is not a terminal failure: the agent might still mutate files.
|
||||
func TestOwnActiveSessionKeepsRunUnsettled(t *testing.T) {
|
||||
_, r, pipelineID := agentStore(t)
|
||||
workspace := t.TempDir()
|
||||
ready := make(chan struct{})
|
||||
@@ -539,7 +538,7 @@ func TestOwnActiveSessionStillFailsRun(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "failed" || !strings.Contains(detail.Diagnostic, "agent quiescence not confirmed") {
|
||||
t.Fatalf("own active session did not fail the run: %+v", detail)
|
||||
if detail.Status != "running" || !detail.CleanupUnconfirmed || detail.FinishedAt != "" {
|
||||
t.Fatalf("own active session falsely settled the run: %+v", detail)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"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 TestCancelWaitsForContextIgnoringExecutor(t *testing.T) {
|
||||
ctx, r, pipelineID := concurrentStore(t)
|
||||
entered, release := make(chan struct{}, 1), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
stopExecutor := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
<-release // Deliberately ignore the canceled context.
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
defer func() { stopExecutor(); r.wg.Wait() }()
|
||||
workspace := t.TempDir()
|
||||
request := protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "blocking", Workspace: workspace, Input: map[string]any{"prompt": "task"}}
|
||||
run, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitEntered(t, entered)
|
||||
if err := r.cancel(run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.cancel(run.ID); err != nil {
|
||||
t.Fatal("repeated stop must be idempotent", err)
|
||||
}
|
||||
detail, err := r.getRun(run.ID)
|
||||
if err != nil || detail.Status != "running" || !detail.Executing || !detail.CancelRequested || detail.FinishedAt != "" || detail.Steps[0].Status != "running" || detail.Steps[0].FinishedAt != "" {
|
||||
t.Fatalf("stop request falsely settled execution: %+v %v", detail, err)
|
||||
}
|
||||
request.RequestKey = "conflict"
|
||||
if _, err := r.start(request); err == nil {
|
||||
t.Fatal("stopping workspace was released")
|
||||
}
|
||||
// An actual second server must fail before recovery can touch this live row.
|
||||
other, err := pipeline.Open(filepath.Join(r.store.Directory(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer other.Close()
|
||||
if _, err := newRunner(ctx, other); err == nil || !strings.Contains(err.Error(), "another server owns") {
|
||||
t.Fatalf("second server did not fail before recovery: %v", err)
|
||||
}
|
||||
detail, _ = r.store.GetRun(ctx, run.ID)
|
||||
if detail.Status != "running" || detail.Steps[0].Status != "running" {
|
||||
t.Fatal("second server recovered live execution", detail)
|
||||
}
|
||||
stopExecutor()
|
||||
r.wg.Wait()
|
||||
detail, err = r.store.GetRun(ctx, run.ID)
|
||||
if err != nil || detail.Status != "canceled" || detail.Outcome != "" || detail.FinishedAt == "" || detail.Steps[0].Status != "canceled" {
|
||||
t.Fatalf("late success beat stop: %+v %v", detail, err)
|
||||
}
|
||||
r.mu.Lock()
|
||||
err = r.checkWorkspaceFree(workspace)
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
t.Fatal("confirmed stop did not release workspace", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
r, store, pipelineID := submitRunner(t, ctx, pipeline.Template([]string{"one"}, true))
|
||||
path := filepath.Join(store.Directory(), "test.db")
|
||||
defer func() { store.Close() }()
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{}, stage.ErrStageCleanup
|
||||
}
|
||||
workspace := t.TempDir()
|
||||
request := protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "cleanup", Workspace: workspace, Input: map[string]any{"prompt": "task"}}
|
||||
run, err := r.start(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
if err := r.cancel(run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, err := r.getRun(run.ID)
|
||||
if err != nil || detail.Status != "running" || !detail.CleanupUnconfirmed || detail.FinishedAt != "" || !detail.Executing {
|
||||
t.Fatalf("cleanup failure became terminal: %+v %v", detail, err)
|
||||
}
|
||||
request.RequestKey = "blocked"
|
||||
if _, err := r.start(request); err == nil {
|
||||
t.Fatal("unconfirmed cleanup released workspace")
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No recoverable session pointer exists in this fixture: fail closed rather
|
||||
// than claiming a restart proved an external process stopped.
|
||||
if _, err := recovered.start(request); err == nil {
|
||||
t.Fatal("restart released unconfirmed workspace without stop evidence")
|
||||
}
|
||||
detail, _ = recovered.getRun(run.ID)
|
||||
if !detail.CleanupUnconfirmed || detail.Status != "running" || detail.FinishedAt != "" {
|
||||
t.Fatal("recovery invented stop confirmation", detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
|
||||
_, r, pipelineID := concurrentStore(t)
|
||||
workspace := t.TempDir()
|
||||
child := filepath.Join(workspace, "child")
|
||||
if err := os.Mkdir(child, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alias := filepath.Join(t.TempDir(), "alias")
|
||||
if err := os.Symlink(child, alias); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
// Admission resolves aliases; the overlap check must cover both directions.
|
||||
for _, pair := range [][2]string{{workspace, child}, {child, workspace}, {workspace, alias}} {
|
||||
r.mu.Lock()
|
||||
resolved, _ := filepath.EvalSymlinks(pair[0])
|
||||
r.active[99] = activeRun{cancel: func() {}, workspace: resolved}
|
||||
r.mu.Unlock()
|
||||
_, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "overlap", Workspace: pair[1], Input: map[string]any{"prompt": "task"}})
|
||||
if err == nil || !strings.Contains(err.Error(), "already active") {
|
||||
t.Fatal("overlapping workspace admission", pair, err)
|
||||
}
|
||||
}
|
||||
for _, pair := range [][2]string{{"/repo", "/repo-other"}, {"/repo/a", "/repo/b"}} {
|
||||
if workspacesOverlap(pair[0], pair[1]) {
|
||||
t.Fatal("sibling/prefix falsely overlaps", pair)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,12 @@ func TestRetainedStageDiffsAcrossVisitsAndFailures(t *testing.T) {
|
||||
if ending == "cancel" {
|
||||
want = "canceled"
|
||||
}
|
||||
if ending == "cleanup" {
|
||||
want = "running"
|
||||
if !detail.CleanupUnconfirmed || detail.FinishedAt != "" {
|
||||
t.Fatal("unconfirmed cleanup reported as settled", detail)
|
||||
}
|
||||
}
|
||||
if detail.Status != want {
|
||||
t.Fatal("diff changed verdict", detail.Status, want)
|
||||
}
|
||||
|
||||
@@ -427,6 +427,8 @@ func mergeRunEventFrame(into, in *protocol.RunEventFrame) {
|
||||
if in.NotifyMode != "" {
|
||||
into.NotifyMode = in.NotifyMode
|
||||
}
|
||||
into.CancelRequested = into.CancelRequested || in.CancelRequested
|
||||
into.CleanupUnconfirmed = into.CleanupUnconfirmed || in.CleanupUnconfirmed
|
||||
if in.Workspace != "" {
|
||||
into.Workspace = in.Workspace
|
||||
}
|
||||
@@ -503,19 +505,21 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner
|
||||
continue
|
||||
}
|
||||
frame := protocol.RunEventFrame{
|
||||
NotifyMode: summary.NotifyMode,
|
||||
RunID: summary.ID,
|
||||
Workspace: summary.Workspace,
|
||||
PipelineID: summary.PipelineID,
|
||||
Name: summary.Name,
|
||||
Title: summary.Title,
|
||||
Version: summary.Version,
|
||||
Status: summary.Status,
|
||||
Outcome: summary.Outcome,
|
||||
CurrentStage: summary.CurrentStage,
|
||||
CompletedSteps: summary.CompletedSteps,
|
||||
CreatedAt: summary.CreatedAt,
|
||||
FinishedAt: summary.FinishedAt,
|
||||
NotifyMode: summary.NotifyMode,
|
||||
RunID: summary.ID,
|
||||
Workspace: summary.Workspace,
|
||||
PipelineID: summary.PipelineID,
|
||||
Name: summary.Name,
|
||||
Title: summary.Title,
|
||||
Version: summary.Version,
|
||||
Status: summary.Status,
|
||||
Outcome: summary.Outcome,
|
||||
CurrentStage: summary.CurrentStage,
|
||||
CompletedSteps: summary.CompletedSteps,
|
||||
CreatedAt: summary.CreatedAt,
|
||||
FinishedAt: summary.FinishedAt,
|
||||
CancelRequested: summary.CancelRequested,
|
||||
CleanupUnconfirmed: summary.CleanupUnconfirmed,
|
||||
}
|
||||
if !sub.writeSnapshot(protocol.Message{Type: protocol.RunEvent, RunEvent: &frame}) {
|
||||
// The connection write failed; the subscription is closed and the
|
||||
|
||||
+120
-42
@@ -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
|
||||
|
||||
@@ -135,7 +135,12 @@ func TestHandlerWiresRunTitleGenerator(t *testing.T) {
|
||||
}
|
||||
defer store.Close()
|
||||
configured := HandlerWithOptions(ctx, Options{RunTitles: summarise.GenerateTitle}, store).(*runHandler)
|
||||
bare := HandlerWithOptions(ctx, Options{}, store).(*runHandler)
|
||||
bareStore, err := pipeline.Open(filepath.Join(t.TempDir(), "bare.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer bareStore.Close()
|
||||
bare := HandlerWithOptions(ctx, Options{}, bareStore).(*runHandler)
|
||||
defer func() { cancel(); WaitRuns(configured); WaitRuns(bare) }()
|
||||
if configured.runner.title == nil {
|
||||
t.Fatal("configured RunTitles was not applied to the runner")
|
||||
@@ -461,7 +466,12 @@ func TestHandlerWiresStepVerdictGenerator(t *testing.T) {
|
||||
}
|
||||
defer store.Close()
|
||||
configured := HandlerWithOptions(ctx, Options{StepVerdicts: summarise.GenerateVerdictReason}, store).(*runHandler)
|
||||
bare := HandlerWithOptions(ctx, Options{}, store).(*runHandler)
|
||||
bareStore, err := pipeline.Open(filepath.Join(t.TempDir(), "bare.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer bareStore.Close()
|
||||
bare := HandlerWithOptions(ctx, Options{}, bareStore).(*runHandler)
|
||||
defer func() { cancel(); WaitRuns(configured); WaitRuns(bare) }()
|
||||
if configured.runner.verdict == nil {
|
||||
t.Fatal("configured StepVerdicts was not applied to the runner")
|
||||
|
||||
@@ -71,7 +71,7 @@ func sessionExportRunner(t *testing.T, backend string, seam func(stage.SessionEx
|
||||
var runID int64
|
||||
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
<-ready
|
||||
if err := handler.runner.store.RunSession(ctx, runID, 1, "ses_run", true, backend, ""); err != nil {
|
||||
if err := handler.runner.store.RunSession(ctx, runID, 1, "ses_run", false, backend, ""); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
|
||||
Reference in New Issue
Block a user