Files
pipelines/internal/server/scheduler.go
T
alan f061675fc1 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>
2026-12-03 12:55:12 +00:00

222 lines
8.4 KiB
Go

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() {
defer r.schedulerWG.Done()
// Admissions run beside the loop; shutdown waits for the ones it started.
defer r.scheduleAdmissions.Wait()
if err := r.scheduleTick(time.Now(), true); err != nil {
log.Printf("scheduler startup: %v", err)
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-r.ctx.Done():
return
case <-r.store.Done():
return
case <-ticker.C:
// Lateness is measured against the time of the claim, not the
// (possibly delayed) tick.
if err := r.scheduleTick(time.Now(), false); err != nil {
log.Printf("scheduler: %v", err)
}
}
}
}
// scheduleTick claims every enabled schedule due at now. A schedule that
// cannot be read or claimed is logged and skipped, never stopping the others.
// A claimed run is admitted on its own goroutine (scheduleAdmissions): run
// admission can take up to a minute (git worktree creation), and an inline
// start would make the next due schedule look missed by the time it is seen.
func (r *runner) scheduleTick(now time.Time, recovery bool) error {
items, err := r.store.ListSchedules(r.ctx, 0)
if err != nil {
return err
}
for _, item := range items {
if !item.Enabled {
continue
}
if err := r.claimSchedule(item, now, recovery); err != nil {
log.Printf("schedule id=%d pipeline=%d: %v", item.ID, item.PipelineID, err)
}
}
return nil
}
func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recovery bool) error {
due, err := time.Parse(time.RFC3339Nano, item.NextDue)
if err != nil {
return fmt.Errorf("next due %q: %w", item.NextDue, err)
}
if due.After(now) {
return nil
}
next, err := pipeline.NextSchedule(item.Rule, now)
if err != nil {
return err
}
if item.Rule.Every != "" {
interval, err := time.ParseDuration(item.Rule.Every)
if err != nil || interval <= 0 {
return fmt.Errorf("interval %q is invalid", item.Rule.Every)
}
next = due.Add((now.Sub(due)/interval + 1) * interval)
}
status := "claimed"
if recovery || now.Sub(due) > 5*time.Second {
status = "skipped_missed"
}
loc, err := pipeline.ScheduleLocation(item.Rule)
if err != nil {
return err
}
if !pipeline.ScheduleDay(item.Rule, due.In(loc)) {
status = "skipped_day"
}
claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status)
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
}
r.scheduleAdmissions.Add(1)
go func() {
defer r.scheduleAdmissions.Done()
r.admitScheduled(item, due)
}()
return nil
}
// 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}
every, limit := scheduleBusyRetry()
started := time.Now()
deadline := started.Add(limit)
name := scheduleLabel(item)
diagnostic := ""
status := "started"
var runID int64
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
}
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)
}
}