Claude stages survive server restarts; non-repo folders don't falsely overlap; busy scheduled runs wait

- Claude stage CLIs now run in their own session (setsid) with the prompt from
  a file and stream-json written straight to cli-<n>.out in the evidence
  directory; owner.json records pid/pgid, session, invocation and output. A
  server shutdown leaves the CLI running and owned (ErrDetached). Start-up
  recovery re-adopts it (stage.ClaudeStageReattachable): the next process
  re-reads the output, follows the live CLI until it exits, or reads the
  result it left while the server was down; one that ended without a result
  marks the run interrupted with a clear reason. The outcome repair follow-up
  is re-adopted too (or asked again if its CLI died without a reply).
- Workspace overlap: two folders outside any repository overlap only when
  they are the same folder or the inner one lies within the outer run's
  declared write paths; nested-repository rules are unchanged.
- Scheduled admissions refused for a busy workspace are recorded as
  "delayed" and retried every 5 min for up to 2 h (env-configurable), then
  started or skipped with the reason; the operator gets a low-priority app
  notice (and ntfy when enabled) when a scheduled run is delayed or skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:55:12 +00:00
parent c4de1de27b
commit f061675fc1
20 changed files with 1344 additions and 180 deletions
+75 -2
View File
@@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
_, r, pipelineID := concurrentStore(t)
// One repository: its folder and a folder inside it are one shared tree.
workspace := t.TempDir()
child := filepath.Join(workspace, "child")
if err := os.Mkdir(child, 0700); err != nil {
t.Fatal(err)
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
if err := os.Mkdir(dir, 0700); err != nil {
t.Fatal(err)
}
}
alias := filepath.Join(t.TempDir(), "alias")
if err := os.Symlink(child, alias); err != nil {
@@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
}
}
}
// Two folders outside any repository (the operator's ~/caplens and a sibling
// project folder under it) are not one tree merely because neither is in a
// repository: nested, they overlap only where the outer run's declared write
// paths reach the inner folder. The same folder always overlaps.
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
hub := t.TempDir()
brief := filepath.Join(hub, "brief")
notes := filepath.Join(hub, "notes", "deep")
for _, dir := range []string{brief, notes} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
paths := func(p ...string) func() []string { return func() []string { return p } }
for _, test := range []struct {
a, b string
aPaths, bPaths func() []string
want bool
}{
{hub, hub, nil, nil, true},
{brief, brief, nil, nil, true},
{hub, brief, nil, nil, false},
{brief, hub, nil, nil, false},
{brief, notes, nil, nil, false},
{hub, brief, paths("notes"), nil, false},
{hub, brief, paths("brief"), nil, true},
{hub, notes, paths("notes"), nil, true},
{hub, notes, paths("notes/deep/file.md"), nil, true},
{notes, hub, nil, paths("notes"), true},
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
{hub, brief, paths("."), nil, true},
} {
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
}
}
// Nested repository rules stay: a repository inside a plain folder is its
// own tree whatever the folder's write paths.
repo := filepath.Join(hub, "repo")
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
t.Fatal(err)
}
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
t.Fatal("a repository inside a plain folder overlaps it")
}
// End to end: a scheduled brief in the hub is admitted while a run works in
// a sibling folder below it, and refused only when it declares a write
// path reaching that folder.
_, r, pipelineID := concurrentStore(t)
release := make(chan struct{})
defer close(release)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success"}, nil
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal(err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
t.Fatal("a hub run writing into the active folder was admitted:", err)
}
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
t.Fatal("a hub run was refused for a sibling folder's run:", err)
}
}
+25 -6
View File
@@ -23,12 +23,19 @@ import (
// re-enters that visit, attaches to the session, waits for it to settle (or
// reads the result it reached while the server was down) and continues the
// graph as if it had watched it;
// - a running Claude Code visit is re-adopted the same way: its CLI runs in
// its own session writing stream-json to a file (see
// stage.ClaudeStageClient), so the next process keeps reading that file
// where the CLI is, waits for it to exit, or reads the result it left
// while the server was down (an interrupted outcome repair follow-up is
// asked again);
// - a visit begun but never handed to a harness is marked interrupted and the
// same stage starts again (nothing was admitted, so nothing replays);
// - a run between visits continues with its next stage;
// - a session whose harness process is gone, or that belongs to a harness the
// server owned as a child (Pi, OpenCode V1), falls back to the previous
// behaviour: the run is interrupted, with the reason in its diagnostic.
// - a session whose harness process is gone (a Claude Code CLI that ended
// without a result), or that belongs to a harness the server owned as a
// child (Pi, OpenCode V1), falls back to the previous behaviour: the run
// is interrupted, with the reason in its diagnostic.
//
// Only an operator cancel (cancel_run) stops a stage session.
@@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e
return opencode.ReferenceAlive(ctx, owner.Reference)
}
// claudeStageReattachable reports why a retained Claude Code stage session
// cannot be re-adopted (nil when it can). It is a seam for tests.
var claudeStageReattachable = stage.ClaudeStageReattachable
// interruptRecoveredSession stops a previously active session that start-up
// recovery does not re-adopt. It is a seam for tests.
var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error {
@@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i
return nil, nil, nil, err
}
owner.RunID = row.ID
if owner.Backend == stage.ClaudeBackend {
// Claude Code stage CLIs run detached from the server: re-adopt
// one still running, or one that left its result while the
// server was down.
if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil {
reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason)
continue
}
plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner})
continue
}
if owner.Backend != "v2" {
name := "OpenCode V1"
if owner.Backend == "pi" {
name = "Pi"
}
if owner.Backend == stage.ClaudeBackend {
name = "Claude Code"
}
reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage)
continue
}
+91
View File
@@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) {
t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final)
}
}
// ownedClaudeStage is a first-process stage one whose Claude Code CLI
// (session claude-live) is still running, detached, at shutdown.
func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
<-ctx.Done()
if stage.Detached(ctx) {
return stage.Result{}, stage.ErrDetached
}
return stage.Result{}, ctx.Err()
}
func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value {
t.Helper()
asked := &atomic.Value{}
previous := claudeStageReattachable
claudeStageReattachable = func(reference, session string) error {
asked.Store(reference + " " + session)
return reason
}
t.Cleanup(func() { claudeStageReattachable = previous })
return asked
}
// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a
// restart is re-adopted from its retained session (never re-prompted, never
// interrupted) and the run continues to the next stage.
func TestClaudeStageRunContinuesAfterRestart(t *testing.T) {
interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude"))
asked := seamClaudeReattachable(t, nil)
f := stopMidStage(t, ownedClaudeStage)
var resumed atomic.Value
r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) {
if def.Key == "one" {
resumed.Store(stage.TakeResumeSession(ctx))
if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil
})
if interrupts.Load() != 0 {
t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart")
}
if got, _ := asked.Load().(string); got != "ref-claude claude-live" {
t.Fatalf("reattachability asked about %q", got)
}
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if got, _ := resumed.Load().(string); got != "claude-live" {
t.Fatalf("stage one was not re-adopted from its Claude session: %q", got)
}
if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" {
t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d)
}
}
// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI
// that ended without a result while the server was down is not replayed; the
// run is interrupted, saying why.
func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) {
interrupts := seamRestartRecovery(t, nil)
seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result"))
f := stopMidStage(t, ownedClaudeStage)
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
t.Error("a Claude stage without a result executed again")
return stage.Result{}, nil
})
r.reattachRuns()
r.wg.Wait()
d, err := s.GetRun(context.Background(), f.runID)
if err != nil {
t.Fatal(err)
}
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") {
t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
}
if interrupts.Load() != 1 {
t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load())
}
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
t.Fatalf("the lost session still blocks recovery: %+v", owners)
}
}
+83 -22
View File
@@ -319,7 +319,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
return nil, err
}
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -343,7 +343,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
// 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 err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -380,7 +380,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
request.Input["pwd"] = workspace
recheck := r.ctx.Err()
if recheck == nil {
recheck = r.checkAdmissionWorkspace(workspace, existing)
recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...)
}
if recheck != nil {
r.mu.Unlock()
@@ -543,9 +543,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru
// 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 {
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error {
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil {
return err
}
}
@@ -557,14 +557,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error
// 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 {
return r.checkWorkspaceFreeExcept(workspace, 0)
// writePaths are the new run's declared write paths (they decide an overlap
// only between nested folders outside any repository).
func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error {
return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...)
}
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error {
own := func() []string { return writePaths }
// pathsOf reads a reserving run's declared write paths only when needed.
pathsOf := func(id int64) func() []string {
return func() []string {
read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
defer cancel()
paths, err := r.store.RunWritePaths(read, id)
if err != nil {
// Unknown scope: keep the whole folder reserved (fail closed).
return []string{"."}
}
return paths
}
}
for id, entry := range r.active {
if workspacesOverlap(entry.workspace, workspace) {
return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)
if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)}
}
}
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
@@ -574,35 +590,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error
return fmt.Errorf("read pending export workspace reservations: %w", err)
}
for id, reserved := range reservations {
if id != ownGate && workspacesOverlap(reserved, workspace) {
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) {
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)}
}
}
return nil
}
// workspaceBusyError refuses an admission because another run (runID)
// reserves an overlapping workspace; waiting can clear it.
type workspaceBusyError struct {
runID int64
message string
}
func (e *workspaceBusyError) Error() string { return e.message }
// workspacesOverlap reports whether two resolved workspaces are the same
// tree or nested in one another within the same repository. A folder that
// merely holds separate repositories (a hub such as ~/project with clones
// under repos/) does not overlap a run inside one of those repositories, and
// neither do two different repositories nested in one another: each run
// works in its own repository.
// works in its own repository. Two folders outside any repository are not one
// shared tree either: nested, they overlap only where the outer run declared
// write paths reaching the inner folder (see workspaceScopesOverlap).
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 workspaceScopesOverlap(a, b, nil, nil)
}
// workspaceScopesOverlap is workspacesOverlap with each workspace's declared
// write paths (relative to it). They matter only for two nested folders
// outside any repository; a nil lookup means "declared none".
func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool {
switch {
case filepath.Clean(a) == filepath.Clean(b):
return true
case within(a, b):
return repositoryRoot(b) == repositoryRoot(a)
case within(b, a):
return repositoryRoot(a) == repositoryRoot(b)
case pathAtOrBelow(a, b):
return nestedWorkspacesOverlap(a, b, aPaths)
case pathAtOrBelow(b, a):
return nestedWorkspacesOverlap(b, a, bPaths)
}
return false
}
// nestedWorkspacesOverlap decides for an inner workspace below outer.
func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool {
root := repositoryRoot(outer)
if repositoryRoot(inner) != root {
return false // Different repositories: each run works in its own.
}
if root != "" {
return true // The same repository is one shared tree.
}
if outerPaths == nil {
return false
}
for _, path := range outerPaths() {
target := filepath.Join(outer, path)
if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) {
return true
}
}
return false
}
// pathAtOrBelow reports whether child is parent or below it.
func pathAtOrBelow(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
// repositoryRoot is the nearest directory at or above dir holding a .git
// entry (a repository or a linked worktree), or "" outside any repository.
func repositoryRoot(dir string) string {
@@ -1055,7 +1112,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID)
}
if detail.Status == protocol.RunStatusWaiting {
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil {
r.mu.Unlock()
return nil, err
}
@@ -2237,6 +2294,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
client.Transcript = piClient.Transcript
} else if modelConfig.Harness == stage.ClaudeBackend {
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills}
if adopted != nil {
// Follow the CLI the previous process left (see run_reattach.go).
claudeClient.Reference = adopted.owner.Reference
}
claudeClient.OnOwnership = func(session, reference string, active bool) error {
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
+109 -8
View File
@@ -1,12 +1,16 @@
package server
import (
"context"
"errors"
"fmt"
"log"
"os"
"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 (r *runner) scheduleLoop() {
@@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
if err != nil {
return err
}
if claimed && status == "skipped_missed" {
name := scheduleLabel(item)
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
}
if !claimed || status != "claimed" {
return nil
}
@@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
return nil
}
// admitScheduled starts one claimed schedule's run and records the outcome.
// scheduleBusyRetry is how often, and for how long after its due time, a
// scheduled admission whose workspace another run holds is tried again
// (the limit counts from the first attempt).
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
// (Go durations; FOR=0 disables waiting) override the defaults.
var scheduleBusyRetry = func() (every, limit time.Duration) {
every, limit = 5*time.Minute, 2*time.Hour
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
every = value
}
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
limit = value
}
return every, limit
}
// scheduleNoticePriority is ntfy's "low" priority.
const scheduleNoticePriority = 2
// admitScheduled starts one claimed schedule's run and records the outcome in
// the schedule's history. A workspace another run holds delays the admission
// instead of skipping it: it is tried again every few minutes for a bounded
// time, recorded as "delayed" meanwhile. The operator is told, at low
// priority, when a scheduled run is delayed and when one is skipped.
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
every, limit := scheduleBusyRetry()
started := time.Now()
deadline := started.Add(limit)
name := scheduleLabel(item)
diagnostic := ""
status := "started"
var runID int64
if err != nil {
status = "skipped"
diagnostic = err.Error()
} else if run != nil {
runID = run.ID
for attempt := 1; ; attempt++ {
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
if err == nil {
status, diagnostic = "started", ""
if run != nil {
runID = run.ID
}
if attempt > 1 {
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
}
break
}
status, diagnostic = "skipped", err.Error()
var busy *workspaceBusyError
if !errors.As(err, &busy) {
break
}
if time.Now().Add(every).After(deadline) {
if attempt > 1 {
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
}
break
}
if attempt == 1 {
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
}
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
log.Printf("schedule id=%d record delay: %v", item.ID, err)
}
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
timer := time.NewTimer(every)
select {
case <-timer.C:
continue
case <-r.ctx.Done():
timer.Stop()
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
}
break
}
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
log.Printf("schedule id=%d record admission: %v", item.ID, err)
}
cancel()
if status == "skipped" {
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
}
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
}
// scheduleLabel names a schedule in a notice.
func scheduleLabel(item protocol.SavedSchedule) string {
if name := singleLine(item.Name); name != "" {
return truncateUTF8(name, 120)
}
return fmt.Sprintf("Schedule %d", item.ID)
}
// scheduleNotice tells the operator, at low priority, through the app
// notification stream and (when enabled) ntfy, that a scheduled run was
// delayed or skipped.
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
defer cancel()
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
return
}
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
}
}
+136
View File
@@ -0,0 +1,136 @@
package server
import (
"context"
"strings"
"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 scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification {
t.Helper()
active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now())
if err != nil {
t.Fatal(err)
}
var notices []protocol.AppNotification
for _, n := range active {
if n.Kind == protocol.NotificationSchedule {
notices = append(notices, n)
}
}
return notices
}
func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due)
if err == nil && status == want {
return diagnostic, run
}
if time.Now().After(deadline) {
t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want)
}
time.Sleep(5 * time.Millisecond)
}
}
// A scheduled run whose workspace another run holds is delayed, not skipped:
// it is recorded as delayed, the operator is told at low priority, and it
// starts once the workspace is free.
func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
entered <- struct{}{}
if prompt, _ := input["prompt"].(string); prompt == "busy" {
<-release
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if err := r.scheduleTick(due, false); err != nil {
t.Fatal(err)
}
diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed")
if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") {
t.Fatalf("delay diagnostic %q", diagnostic)
}
notices := scheduleNotices(t, s)
if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") {
t.Fatalf("delay notices %+v", notices)
}
close(release)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started")
r.scheduleAdmissions.Wait()
r.wg.Wait()
if run == 0 || !strings.Contains(diagnostic, "started after waiting") {
t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic)
}
runs, err := s.ListRuns(ctx)
if err != nil || len(runs) != 2 {
t.Fatalf("runs %+v %v", runs, err)
}
}
// Waiting is bounded: past the limit the occurrence is skipped, saying why,
// and the operator is told.
func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) {
seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond)
ctx, s, r, pid := scheduleFixture(t)
r.notes = newAppNotifier(s)
workspace := t.TempDir()
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
release := make(chan struct{})
defer close(release)
entered := make(chan struct{}, 2)
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
entered <- struct{}{}
select {
case <-release:
case <-ctx.Done():
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
}
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
t.Fatal(err)
}
<-entered
due := dueOf(t, brief)
if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed {
t.Fatal(claimed, err)
}
r.admitScheduled(*brief, due)
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped")
if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") {
t.Fatalf("skip diagnostic %q run=%d", diagnostic, run)
}
notices := scheduleNotices(t, s)
var titles []string
for _, n := range notices {
titles = append(titles, n.Title)
if n.Priority != 2 {
t.Fatalf("schedule notice is not low priority: %+v", n)
}
}
if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") {
t.Fatalf("notices %v", titles)
}
}
+10
View File
@@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
}
}
// seamScheduleBusyRetry sets how a scheduled admission waits for a busy
// workspace (limit 0: it is skipped at once, as before delays existed).
func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) {
t.Helper()
previous := scheduleBusyRetry
scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit }
t.Cleanup(func() { scheduleBusyRetry = previous })
}
func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
seamScheduleBusyRetry(t, time.Minute, 0)
ctx, s, r, pid := scheduleFixture(t)
item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now())
due := dueOf(t, item)
+1 -1
View File
@@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error {
r.mu.Unlock()
return err
}
if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil {
if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil {
r.mu.Unlock()
continue
}