Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

refactor(autopilot): migrate scheduled dispatch to scheduler.Manager (3/3 MUL-3551) (#4444)

Multica Eve131ca80a6c3d
diff --git a/server/cmd/server/autopilot_schedule_job_test.go b/server/cmd/server/autopilot_schedule_job_test.go
new file mode 100644
index 0000000000..0e92812be2
--- /dev/null
+++ b/server/cmd/server/autopilot_schedule_job_test.go
@@ -0,0 +1,590 @@
+package main
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/scheduler"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// setupAutopilotScheduleJob creates the test fixture for the
+// autopilot_schedule_dispatch JobSpec: an active autopilot, a
+// schedule trigger with the given cron, and a *scheduler.Manager with
+// the JobSpec registered. Cleanup is registered on t.
+//
+// Returns the trigger and the manager so the test can call mgr.runOnce
+// directly (no goroutine — we want deterministic ticks).
+func setupAutopilotScheduleJob(t *testing.T, cron string) (db.AutopilotTrigger, *scheduler.Manager, *service.AutopilotService) {
+ t.Helper()
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)
+ autopilotSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)
+
+ var agentID string
+ if err := testPool.QueryRow(ctx,
+ `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,
+ testWorkspaceID,
+ ).Scan(&agentID); err != nil {
+ t.Fatalf("load fixture agent: %v", err)
+ }
+
+ ap, err := queries.CreateAutopilot(ctx, db.CreateAutopilotParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ Title: "Schedule dispatch fixture",
+ Description: pgtype.Text{String: "schedule dispatch test", Valid: true},
+ AssigneeType: "agent",
+ AssigneeID: parseUUID(agentID),
+ Status: "active",
+ ExecutionMode: "run_only",
+ IssueTitleTemplate: pgtype.Text{},
+ CreatedByType: "member",
+ CreatedByID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("CreateAutopilot: %v", err)
+ }
+
+ trigger, err := queries.CreateAutopilotTrigger(ctx, db.CreateAutopilotTriggerParams{
+ AutopilotID: ap.ID,
+ Kind: "schedule",
+ Enabled: true,
+ CronExpression: pgtype.Text{String: cron, Valid: true},
+ Timezone: pgtype.Text{String: "UTC", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("CreateAutopilotTrigger: %v", err)
+ }
+
+ // Anchor trigger.created_at to one minute ago so even an
+ // every-minute cron is guaranteed to have at least one occurrence
+ // in (created_at, dbNow] on the first tick. Without this the test
+ // occasionally races the cron evaluator's minute boundary and the
+ // first tick produces zero plans.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE autopilot_trigger SET created_at = now() - INTERVAL '2 minute' WHERE id = $1`,
+ trigger.ID,
+ ); err != nil {
+ t.Fatalf("backdate trigger.created_at: %v", err)
+ }
+
+ t.Cleanup(func() {
+ bg := context.Background()
+ _, _ = testPool.Exec(bg,
+ `DELETE FROM sys_cron_executions WHERE scope_kind = $1 AND scope_id = $2`,
+ scheduler.ScopeKindAutopilotTrigger, util.UUIDToString(trigger.ID),
+ )
+ _, _ = testPool.Exec(bg, `DELETE FROM autopilot WHERE id = $1`, ap.ID)
+ })
+
+ mgr := scheduler.NewManager(testPool, scheduler.Options{
+ RunnerID: "autopilot-job-test",
+ })
+ if err := mgr.Register(scheduler.AutopilotScheduleDispatchJob(testPool, queries, autopilotSvc)); err != nil {
+ t.Fatalf("register autopilot_schedule_dispatch job: %v", err)
+ }
+
+ return trigger, mgr, autopilotSvc
+}
+
+// TestAutopilotScheduleJobDispatchesOnce verifies the end-to-end
+// happy path: one tick of the JobSpec produces exactly one
+// sys_cron_executions row (SUCCESS) and exactly one autopilot_run
+// row tagged with the canonical UTC planned_at. This is the
+// occurrence-level idempotency contract from MUL-3551 §1.
+func TestAutopilotScheduleJobDispatchesOnce(t *testing.T) {
+ ctx := context.Background()
+
+ // `*/1 * * * *` fires every minute. Trigger.created_at is
+ // backdated 2 minutes in the fixture so there is always at least
+ // one due occurrence.
+ trigger, mgr, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("first tick: %v", err)
+ }
+
+ // Exactly one sys_cron_executions row for this scope, status SUCCESS.
+ var execRows int
+ var status string
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*), COALESCE(MAX(status), '')
+ FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execRows, &status); err != nil {
+ t.Fatalf("count exec rows: %v", err)
+ }
+ if execRows != 1 || status != "SUCCESS" {
+ t.Fatalf("expected 1 SUCCESS exec row, got %d rows with status %q", execRows, status)
+ }
+
+ // Exactly one autopilot_run with planned_at set.
+ var runRows int
+ var plannedAtValid bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*), bool_or(planned_at IS NOT NULL)
+ FROM autopilot_run
+ WHERE trigger_id = $1
+ `, trigger.ID).Scan(&runRows, &plannedAtValid); err != nil {
+ t.Fatalf("count run rows: %v", err)
+ }
+ if runRows != 1 || !plannedAtValid {
+ t.Fatalf("expected 1 autopilot_run with planned_at set, got %d rows planned_at_valid=%v", runRows, plannedAtValid)
+ }
+
+ // A second tick must NOT create another row at the same plan_time
+ // (idempotency via uq_sys_cron_execution). Because the trigger
+ // fires every minute, the second tick may produce a NEW row at
+ // the next minute boundary if a minute passed between the two
+ // runOnce calls — that is fine, the test just asserts that the
+ // existing row is not duplicated and the COUNT doesn't decrease.
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("second tick: %v", err)
+ }
+ var execRowsAfter int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execRowsAfter); err != nil {
+ t.Fatalf("count exec rows after 2nd tick: %v", err)
+ }
+ if execRowsAfter < execRows {
+ t.Fatalf("second tick should never delete rows; before=%d after=%d", execRows, execRowsAfter)
+ }
+}
+
+// TestAutopilotScheduleJobMissedSchedulesCollapse covers MUL-3551 §4:
+// when many occurrences are due (e.g. server was offline for a long
+// stretch), the CatchUpLatestOnly hook should fire ONCE per tick — not
+// replay every missed occurrence.
+func TestAutopilotScheduleJobMissedSchedulesCollapse(t *testing.T) {
+ ctx := context.Background()
+
+ trigger, mgr, _ := setupAutopilotScheduleJob(t, "*/5 * * * *")
+
+ // Force a large historical window: the trigger thinks it was
+ // registered an hour ago, so without collapse the hook would
+ // emit 12 occurrences.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE autopilot_trigger SET created_at = now() - INTERVAL '1 hour' WHERE id = $1`,
+ trigger.ID,
+ ); err != nil {
+ t.Fatalf("backdate trigger.created_at: %v", err)
+ }
+
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("tick: %v", err)
+ }
+
+ var rows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&rows); err != nil {
+ t.Fatalf("count exec rows: %v", err)
+ }
+ if rows != 1 {
+ t.Fatalf("CatchUpLatestOnly must collapse missed fires to 1 row per tick, got %d", rows)
+ }
+
+ var runRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM autopilot_run WHERE trigger_id = $1
+ `, trigger.ID).Scan(&runRows); err != nil {
+ t.Fatalf("count run rows: %v", err)
+ }
+ if runRows != 1 {
+ t.Fatalf("missed schedules must collapse to a single autopilot_run, got %d", runRows)
+ }
+}
+
+// TestAutopilotScheduleJobCrashRecovery covers MUL-3551 §5: a runner
+// that crashes after claiming a plan_time and creating its
+// downstream issue/task — but before writing terminal SUCCESS — must
+// be recovered on the next tick. The stale lease is swept to FAILED
+// (error_code='stale_timeout'), the planner returns the SAME
+// plan_time (because latest.RetryEligible(now) is true), tryClaim's
+// FAILED-with-retry branch fires (incrementing attempt), the
+// dispatch path is re-entered, DispatchAutopilotForPlan sees the
+// already-complete run from the first attempt and reuses it, and
+// the row finally transitions to SUCCESS — all without duplicating
+// the autopilot_run.
+func TestAutopilotScheduleJobCrashRecovery(t *testing.T) {
+ ctx := context.Background()
+
+ trigger, mgr, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ // Tick 1: dispatch creates run + task; sys_cron_executions row
+ // reaches SUCCESS.
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("tick 1: %v", err)
+ }
+ var execID, leaseToken string
+ var planTime time.Time
+ var attempt int
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, lease_token, plan_time, attempt
+ FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execID, &leaseToken, &planTime, &attempt); err != nil {
+ t.Fatalf("read first exec row: %v", err)
+ }
+ if attempt != 1 {
+ t.Fatalf("first attempt must be attempt=1, got %d", attempt)
+ }
+
+ // The first-tick run carries planned_at + a real task linkage —
+ // that's the "complete" snapshot the retry must reuse, not
+ // duplicate.
+ var firstRunID pgtype.UUID
+ var firstRunTaskValid bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, task_id IS NOT NULL FROM autopilot_run WHERE trigger_id = $1
+ `, trigger.ID).Scan(&firstRunID, &firstRunTaskValid); err != nil {
+ t.Fatalf("read first run: %v", err)
+ }
+ if !firstRunTaskValid {
+ t.Fatalf("first attempt must have created a real downstream task; task_id is NULL")
+ }
+
+ // Simulate a crash AFTER the first attempt's terminal write
+ // would have been ignored: rewrite the exec row to RUNNING with
+ // an expired stale_after AND a different (ghost) lease_token, so
+ // it looks exactly like the post-crash state where the runner
+ // died before its terminal UPDATE landed. The autopilot_run row
+ // from tick 1 stays as the "complete" snapshot — that is what
+ // DispatchAutopilotForPlan must reuse on the retry.
+ if _, err := testPool.Exec(ctx, `
+ UPDATE sys_cron_executions
+ SET status = 'RUNNING',
+ runner_id = 'ghost-runner',
+ lease_token = gen_random_uuid(),
+ stale_after = now() - INTERVAL '10 minutes',
+ finished_at = NULL,
+ duration_ms = NULL,
+ updated_at = now()
+ WHERE id = $1
+ `, execID); err != nil {
+ t.Fatalf("simulate crash mid-dispatch: %v", err)
+ }
+
+ // Tick 2: stale sweep + retry + dispatch + final SUCCESS.
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("tick 2 (recovery): %v", err)
+ }
+
+ // The exec row must now be SUCCESS at attempt=2, still at the
+ // SAME plan_time (proving the retry path fired and the planner
+ // did not silently advance past the FAILED bucket — the canonical
+ // bug from the #4444 review).
+ var recoveredStatus string
+ var recoveredAttempt int
+ var recoveredPlan time.Time
+ if err := testPool.QueryRow(ctx, `
+ SELECT status, attempt, plan_time
+ FROM sys_cron_executions
+ WHERE id = $1
+ `, execID).Scan(&recoveredStatus, &recoveredAttempt, &recoveredPlan); err != nil {
+ t.Fatalf("read recovered exec row: %v", err)
+ }
+ if !recoveredPlan.Equal(planTime) {
+ t.Fatalf("retry must stay on the same plan_time: tick1=%s tick2=%s",
+ planTime.Format(time.RFC3339), recoveredPlan.Format(time.RFC3339))
+ }
+ if recoveredAttempt != 2 {
+ t.Fatalf("retry must increment attempt (the FAILED-retry branch fired); got attempt=%d", recoveredAttempt)
+ }
+ if recoveredStatus != "SUCCESS" {
+ t.Fatalf("retry must reach terminal SUCCESS on the same row; got status=%q", recoveredStatus)
+ }
+
+ // Exactly one autopilot_run, and it is the SAME one tick 1
+ // created — DispatchAutopilotForPlan's idempotency + the
+ // complete-run reuse path in isAutopilotRunComplete prevent a
+ // duplicate.
+ rows, err := testPool.Query(ctx, `SELECT id FROM autopilot_run WHERE trigger_id = $1`, trigger.ID)
+ if err != nil {
+ t.Fatalf("list run rows: %v", err)
+ }
+ defer rows.Close()
+ var seenIDs []pgtype.UUID
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan: %v", err)
+ }
+ seenIDs = append(seenIDs, id)
+ }
+ if len(seenIDs) != 1 {
+ t.Fatalf("crash recovery must keep autopilot_run at exactly one row, got %d", len(seenIDs))
+ }
+ if seenIDs[0] != firstRunID {
+ t.Fatalf("retry must reuse tick-1's run row; got new id %s",
+ util.UUIDToString(seenIDs[0]))
+ }
+}
+
+// TestAutopilotScheduleJobTwoRunnersSingleWinner covers the
+// multi-replica claim race from MUL-3551 §1. Two scheduler.Manager
+// instances tick concurrently against the same trigger; exactly one
+// should win the claim, the other no-ops via the sys_cron_executions
+// uniqueness key.
+func TestAutopilotScheduleJobTwoRunnersSingleWinner(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)
+ autopilotSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)
+
+ trigger, _, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ mgrA := scheduler.NewManager(testPool, scheduler.Options{RunnerID: "runner-A"})
+ mgrB := scheduler.NewManager(testPool, scheduler.Options{RunnerID: "runner-B"})
+ if err := mgrA.Register(scheduler.AutopilotScheduleDispatchJob(testPool, queries, autopilotSvc)); err != nil {
+ t.Fatalf("register A: %v", err)
+ }
+ if err := mgrB.Register(scheduler.AutopilotScheduleDispatchJob(testPool, queries, autopilotSvc)); err != nil {
+ t.Fatalf("register B: %v", err)
+ }
+
+ type result struct {
+ err error
+ }
+ results := make(chan result, 2)
+ go func() { results <- result{err: mgrA.RunOnce(ctx)} }()
+ go func() { results <- result{err: mgrB.RunOnce(ctx)} }()
+
+ for range 2 {
+ r := <-results
+ if r.err != nil {
+ t.Fatalf("runOnce: %v", r.err)
+ }
+ }
+
+ // At most one sys_cron_executions row for this plan_time, and
+ // exactly one autopilot_run.
+ var execRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execRows); err != nil {
+ t.Fatalf("count exec rows: %v", err)
+ }
+ if execRows < 1 || execRows > 2 {
+ // At most one per plan_time, but two ticks racing across a
+ // minute boundary could produce up to 2 distinct plan_times.
+ // Anything outside [1,2] means the uniqueness guarantee broke.
+ t.Fatalf("expected 1 or 2 exec rows (one per plan_time), got %d", execRows)
+ }
+ // Per plan_time: exactly one runner_id should ever be recorded.
+ rowsByPlan, err := testPool.Query(ctx, `
+ SELECT plan_time, runner_id FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ ORDER BY plan_time
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID))
+ if err != nil {
+ t.Fatalf("query per-plan rows: %v", err)
+ }
+ defer rowsByPlan.Close()
+ seen := map[string]string{}
+ for rowsByPlan.Next() {
+ var plan time.Time
+ var runner string
+ if err := rowsByPlan.Scan(&plan, &runner); err != nil {
+ t.Fatalf("scan: %v", err)
+ }
+ key := plan.Format(time.RFC3339Nano)
+ if prev, ok := seen[key]; ok && prev != runner {
+ t.Fatalf("plan_time %s claimed by both %s and %s — uniqueness broke", key, prev, runner)
+ }
+ seen[key] = runner
+ }
+
+ var runRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM autopilot_run WHERE trigger_id = $1
+ `, trigger.ID).Scan(&runRows); err != nil {
+ t.Fatalf("count run rows: %v", err)
+ }
+ if runRows != execRows {
+ t.Fatalf("expected 1 autopilot_run per exec row, got exec=%d run=%d", execRows, runRows)
+ }
+}
+
+// TestAutopilotScheduleJobDisabledTriggerSkips locks in that a
+// trigger toggled off between scope-list and handler run is treated
+// as a SUCCESS no-op — no autopilot_run created. This protects
+// against the race the legacy goroutine could not prove safe (it
+// reloaded the autopilot, but never re-checked the trigger's
+// enabled flag in-handler).
+func TestAutopilotScheduleJobDisabledTriggerSkips(t *testing.T) {
+ ctx := context.Background()
+
+ trigger, mgr, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ // Disable the trigger AFTER the manager is wired but before tick.
+ // scope provider's SQL will not include it, so no plan_time is
+ // produced. (The handler-side belt-and-suspenders guard is
+ // covered by the unit-level autopilot_inactive case below.)
+ if _, err := testPool.Exec(ctx,
+ `UPDATE autopilot_trigger SET enabled = FALSE WHERE id = $1`, trigger.ID,
+ ); err != nil {
+ t.Fatalf("disable trigger: %v", err)
+ }
+
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("tick: %v", err)
+ }
+
+ var execRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execRows); err != nil {
+ t.Fatalf("count exec rows: %v", err)
+ }
+ if execRows != 0 {
+ t.Fatalf("disabled trigger must not produce sys_cron_executions rows, got %d", execRows)
+ }
+}
+
+// TestAutopilotScheduleJobPausedAutopilotSkipsAtHandler covers the
+// in-handler race window: scope-list says "active" at tick start,
+// but the autopilot is paused before the per-scope handler runs
+// (e.g. by an HTTP PUT that landed between scope-list and dispatch).
+// The handler MUST re-read autopilot.status and treat the run as a
+// SUCCESS no-op (skipped_reason: "autopilot_inactive") instead of
+// firing a real dispatch.
+//
+// Driving this via `mgr.RunOnce` would not exercise the guard —
+// scope-list's SQL filter already excludes paused autopilots so the
+// handler is never reached. Instead we invoke `job.Handler` directly
+// with a stub HandlerInput, which is exactly how the manager calls
+// it after a successful claim. JobSpec.Handler is a public field on
+// the JobSpec, so no test-only export is needed.
+func TestAutopilotScheduleJobPausedAutopilotSkipsAtHandler(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ bus := events.New()
+ taskSvc := service.NewTaskService(queries, testPool, nil, bus)
+ autopilotSvc := service.NewAutopilotService(queries, testPool, bus, taskSvc)
+
+ trigger, _, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ // Pause the parent autopilot AFTER setup — simulates the
+ // "paused after scope-list" race the in-handler guard exists for.
+ if _, err := queries.UpdateAutopilot(ctx, db.UpdateAutopilotParams{
+ ID: trigger.AutopilotID,
+ Status: pgtype.Text{String: "paused", Valid: true},
+ }); err != nil {
+ t.Fatalf("pause autopilot: %v", err)
+ }
+
+ job := scheduler.AutopilotScheduleDispatchJob(testPool, queries, autopilotSvc)
+
+ // Drive the handler directly. plan_time is arbitrary — what we
+ // are asserting is that the handler re-reads autopilot.status
+ // and returns a SUCCESS no-op WITHOUT calling DispatchAutopilotForPlan.
+ planTime := time.Now().UTC().Truncate(time.Minute)
+ result, err := job.Handler(ctx, scheduler.HandlerInput{
+ Job: &job,
+ Scope: scheduler.Scope{Kind: scheduler.ScopeKindAutopilotTrigger, ID: util.UUIDToString(trigger.ID)},
+ PlanTime: planTime,
+ Attempt: 1,
+ RunnerID: "handler-guard-test",
+ Heartbeat: func(ctx context.Context) error { return nil },
+ })
+ if err != nil {
+ t.Fatalf("handler returned error: %v", err)
+ }
+ if result.RowsAffected != 0 {
+ t.Fatalf("paused autopilot must produce a no-op (rows_affected=0), got %d", result.RowsAffected)
+ }
+ if got, _ := result.Result["skipped_reason"].(string); got != "autopilot_inactive" {
+ t.Fatalf("expected skipped_reason=autopilot_inactive, got %q", got)
+ }
+
+ // And — critically — no autopilot_run should have been created
+ // by this handler invocation. (Dispatch would have produced one.)
+ var runRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM autopilot_run WHERE trigger_id = $1
+ `, trigger.ID).Scan(&runRows); err != nil {
+ t.Fatalf("count run rows: %v", err)
+ }
+ if runRows != 0 {
+ t.Fatalf("paused-autopilot handler guard must not create a run, got %d", runRows)
+ }
+}
+
+// TestAutopilotScheduleJobBadCronStaysSilent locks in the failure
+// surface for malformed cron expressions: the trigger create/update
+// handlers reject bad cron at HTTP time (so this is a defence in
+// depth), but if a corrupt expression ever lands in
+// autopilot_trigger.cron_expression, the planner hook must fail
+// without dispatching anything.
+//
+// The hook returns its parse error to manager.runJob, which logs a
+// warning and SKIPS this scope for the tick. No row is inserted
+// into sys_cron_executions because nothing was ever claimed —
+// `tryClaim` only writes when a plan_time is offered. This is the
+// right shape: a parse error is a permanent configuration problem,
+// not a transient lease failure, so the retry-with-FAILED-row
+// machinery does not apply. The audit signal is the manager
+// warning log instead.
+//
+// The contract this test pins is therefore: NO dispatch, NO exec
+// row, and NO autopilot_run created. The bad cron MUST NOT silently
+// look like a SUCCESS.
+func TestAutopilotScheduleJobBadCronStaysSilent(t *testing.T) {
+ ctx := context.Background()
+
+ trigger, mgr, _ := setupAutopilotScheduleJob(t, "*/1 * * * *")
+
+ if _, err := testPool.Exec(ctx,
+ `UPDATE autopilot_trigger SET cron_expression = $2 WHERE id = $1`,
+ trigger.ID, "garbage not a cron",
+ ); err != nil {
+ t.Fatalf("set bad cron: %v", err)
+ }
+
+ if err := mgr.RunOnce(ctx); err != nil {
+ t.Fatalf("tick: %v", err)
+ }
+
+ var execRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM sys_cron_executions
+ WHERE job_name = $1 AND scope_kind = $2 AND scope_id = $3
+ `, scheduler.JobNameAutopilotScheduleDispatch, scheduler.ScopeKindAutopilotTrigger,
+ util.UUIDToString(trigger.ID)).Scan(&execRows); err != nil {
+ t.Fatalf("count exec rows: %v", err)
+ }
+ if execRows != 0 {
+ t.Fatalf("bad cron must not produce sys_cron_executions rows (no claim happens), got %d", execRows)
+ }
+
+ var runRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM autopilot_run WHERE trigger_id = $1
+ `, trigger.ID).Scan(&runRows); err != nil {
+ t.Fatalf("count run rows: %v", err)
+ }
+ if runRows != 0 {
+ t.Fatalf("bad cron must not fire dispatch, got %d run rows", runRows)
+ }
+}
diff --git a/server/cmd/server/autopilot_scheduler.go b/server/cmd/server/autopilot_scheduler.go
deleted file mode 100644
index e16b1f13e9..0000000000
--- a/server/cmd/server/autopilot_scheduler.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package main
-
-import (
- "context"
- "log/slog"
- "time"
-
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/service"
- "github.com/multica-ai/multica/server/internal/util"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
-)
-
-const schedulerInterval = 30 * time.Second
-
-// runAutopilotScheduler polls for due schedule triggers and dispatches them.
-func runAutopilotScheduler(ctx context.Context, queries *db.Queries, svc *service.AutopilotService) {
- // Recover triggers that were claimed but never advanced (e.g. after a crash).
- recoverLostTriggers(ctx, queries)
-
- ticker := time.NewTicker(schedulerInterval)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- tickScheduledAutopilots(ctx, queries, svc)
- }
- }
-}
-
-// recoverLostTriggers finds schedule triggers whose next_run_at is NULL
-// (claimed but never advanced, typically after a crash) and recomputes it.
-func recoverLostTriggers(ctx context.Context, queries *db.Queries) {
- triggers, err := queries.RecoverLostTriggers(ctx)
- if err != nil {
- slog.Warn("autopilot scheduler: failed to recover lost triggers", "error", err)
- return
- }
- if len(triggers) == 0 {
- return
- }
-
- slog.Info("autopilot scheduler: recovering lost triggers", "count", len(triggers))
- for _, t := range triggers {
- if !t.CronExpression.Valid || t.CronExpression.String == "" {
- continue
- }
- tz := service.DefaultAutopilotTriggerTimezone
- if t.Timezone.Valid && t.Timezone.String != "" {
- tz = t.Timezone.String
- }
- next, err := service.ComputeNextRun(t.CronExpression.String, tz)
- if err != nil {
- slog.Warn("autopilot scheduler: failed to compute next run for recovery",
- "trigger_id", util.UUIDToString(t.ID), "error", err)
- continue
- }
- if err := queries.AdvanceTriggerNextRun(ctx, db.AdvanceTriggerNextRunParams{
- ID: t.ID,
- NextRunAt: pgtype.Timestamptz{Time: next, Valid: true},
- }); err != nil {
- slog.Warn("autopilot scheduler: failed to recover trigger",
- "trigger_id", util.UUIDToString(t.ID), "error", err)
- }
- }
-}
-
-// tickScheduledAutopilots claims all due triggers and dispatches each one.
-func tickScheduledAutopilots(ctx context.Context, queries *db.Queries, svc *service.AutopilotService) {
- triggers, err := queries.ClaimDueScheduleTriggers(ctx)
- if err != nil {
- slog.Warn("autopilot scheduler: failed to claim due triggers", "error", err)
- return
- }
- if len(triggers) == 0 {
- return
- }
-
- slog.Info("autopilot scheduler: claimed due triggers", "count", len(triggers))
-
- for _, t := range triggers {
- autopilot, err := queries.GetAutopilot(ctx, t.AutopilotID)
- if err != nil {
- slog.Warn("autopilot scheduler: failed to load autopilot",
- "trigger_id", util.UUIDToString(t.ID),
- "autopilot_id", util.UUIDToString(t.AutopilotID),
- "error", err,
- )
- continue
- }
-
- // Dispatch the autopilot run.
- if _, err := svc.DispatchAutopilot(ctx, autopilot, t.ID, "schedule", nil); err != nil {
- slog.Warn("autopilot scheduler: dispatch failed",
- "autopilot_id", util.UUIDToString(autopilot.ID),
- "trigger_id", util.UUIDToString(t.ID),
- "error", err,
- )
- }
-
- // Advance next_run_at for this trigger.
- advanceNextRun(ctx, queries, t)
- }
-}
-
-// advanceNextRun computes the next fire time and updates the trigger.
-func advanceNextRun(ctx context.Context, queries *db.Queries, t db.ClaimDueScheduleTriggersRow) {
- if !t.CronExpression.Valid || t.CronExpression.String == "" {
- return
- }
-
- tz := service.DefaultAutopilotTriggerTimezone
- if t.Timezone.Valid && t.Timezone.String != "" {
- tz = t.Timezone.String
- }
-
- next, err := service.ComputeNextRun(t.CronExpression.String, tz)
- if err != nil {
- slog.Warn("autopilot scheduler: failed to compute next run",
- "trigger_id", util.UUIDToString(t.ID),
- "cron", t.CronExpression.String,
- "error", err,
- )
- return
- }
-
- if err := queries.AdvanceTriggerNextRun(ctx, db.AdvanceTriggerNextRunParams{
- ID: t.ID,
- NextRunAt: pgtype.Timestamptz{Time: next, Valid: true},
- }); err != nil {
- slog.Warn("autopilot scheduler: failed to advance next_run_at",
- "trigger_id", util.UUIDToString(t.ID),
- "error", err,
- )
- }
-}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 5fe9e31893..5f0f8881d4 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -347,7 +347,6 @@ func main() {
// Start background sweeper to mark stale runtimes as offline.
go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus)
go heartbeatScheduler.Run(sweepCtx)
- go runAutopilotScheduler(autopilotCtx, queries, autopilotSvc)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
go runDBStatsLogger(sweepCtx, pool)
@@ -378,11 +377,19 @@ func main() {
schedulerMgr := scheduler.NewManager(pool, scheduler.Options{})
if err := schedulerMgr.Register(scheduler.TaskUsageHourlyJob(pool)); err != nil {
slog.Warn("scheduler: failed to register task_usage_hourly rollup job", "error", err)
- } else {
- go func() {
- _ = schedulerMgr.Run(sweepCtx)
- }()
}
+ // MUL-3551: scheduled-Autopilot dispatch runs on the same DB-backed
+ // scheduler. The job owns its plan_times via PlansForScope (each
+ // trigger has its own cron expression, so the Cadence planner does
+ // not fit). Crash recovery, occurrence-level idempotency, lease
+ // theft, and retry are all reused from the manager + sys_cron_executions
+ // — there is no separate goroutine for scheduled Autopilot anymore.
+ if err := schedulerMgr.Register(scheduler.AutopilotScheduleDispatchJob(pool, queries, autopilotSvc)); err != nil {
+ slog.Warn("scheduler: failed to register autopilot_schedule_dispatch job", "error", err)
+ }
+ go func() {
+ _ = schedulerMgr.Run(sweepCtx)
+ }()
if metricsServer != nil {
go func() {
diff --git a/server/internal/scheduler/every_plan_retry_test.go b/server/internal/scheduler/every_plan_retry_test.go
index 081312c21b..a5713c2eea 100644
--- a/server/internal/scheduler/every_plan_retry_test.go
+++ b/server/internal/scheduler/every_plan_retry_test.go
@@ -72,7 +72,7 @@ func TestManagerEveryPlanRetriesFailedSamePlanTime(t *testing.T) {
defer cancel()
// Tick 1: handler fails at plan_time T attempt 1.
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("first runOnce: %v", err)
}
@@ -107,7 +107,7 @@ func TestManagerEveryPlanRetriesFailedSamePlanTime(t *testing.T) {
// Tick 2: planner must keep cursor on plan_time T so tryClaim's
// FAILED-with-retry branch fires.
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("second runOnce: %v", err)
}
diff --git a/server/internal/scheduler/jobs_autopilot.go b/server/internal/scheduler/jobs_autopilot.go
new file mode 100644
index 0000000000..c943a87fe0
--- /dev/null
+++ b/server/internal/scheduler/jobs_autopilot.go
@@ -0,0 +1,350 @@
+package scheduler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// JobNameAutopilotScheduleDispatch is the canonical job name written
+// to sys_cron_executions audit rows. Stable across releases — renaming
+// it would orphan historic rows.
+const JobNameAutopilotScheduleDispatch = "autopilot_schedule_dispatch"
+
+// ScopeKindAutopilotTrigger labels the scope dimension. Each enabled
+// schedule trigger is one scope; scope_id is the trigger UUID.
+const ScopeKindAutopilotTrigger = "autopilot_trigger"
+
+// DefaultAutopilotScheduleTimezone is the fallback when a trigger's
+// timezone column is NULL / empty. Matches
+// service.DefaultAutopilotTriggerTimezone.
+const DefaultAutopilotScheduleTimezone = "UTC"
+
+// AutopilotScheduleDispatcher is the narrow contract this job needs
+// from service.AutopilotService. Defined here so unit tests in this
+// package (and the cmd/server integration tests) can stub it without
+// pulling in the rest of the service layer.
+type AutopilotScheduleDispatcher interface {
+ DispatchAutopilotForPlan(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ source string,
+ payload []byte,
+ plannedAt time.Time,
+ ) (*db.AutopilotRun, error)
+}
+
+// AutopilotScheduleDispatchJob returns the JobSpec that drives
+// scheduled Autopilot dispatch through the existing scheduler +
+// sys_cron_executions lease infrastructure. Replaces the legacy
+// cmd/server/autopilot_scheduler.go goroutine (MUL-3551).
+//
+// Design highlights:
+//
+// - Each enabled schedule trigger is its own scope
+// (scope_kind = "autopilot_trigger", scope_id = trigger.id).
+// - plan_time is a canonical UTC cron occurrence computed from the
+// trigger's cron expression + timezone against DB time. The
+// PlansForScope hook enumerates occurrences in (lastPlan, dbNow]
+// and returns only the most recent one (collapsing missed fires —
+// same policy as the legacy goroutine).
+// - The handler calls AutopilotService.DispatchAutopilotForPlan, which
+// is itself idempotent on (trigger_id, planned_at) via the partial
+// unique index from migration 124. Together with the
+// sys_cron_executions unique key on (job, scope, plan_time), the
+// same planned occurrence cannot produce duplicate runs even under
+// stale-steal retries.
+//
+// Restart semantics:
+//
+// - Triggers are recovered from the autopilot_trigger table on the
+// next tick — no in-memory timer table is maintained. The
+// scope provider runs every tick and re-derives the eligible set
+// from `kind='schedule' AND enabled AND a.status='active'`.
+// - If the previous incarnation crashed after claiming a plan_time
+// but before writing terminal status, the stale-lease sweep in
+// manager.runJob promotes that row to FAILED with
+// error_code='stale_timeout'. AllowStaleReentry=true +
+// attempts < MaxAttempts lets the next tick steal the lease and
+// re-enter dispatch — DispatchAutopilotForPlan's idempotent lookup
+// then returns the already-created run rather than duplicating it.
+func AutopilotScheduleDispatchJob(
+ pool *pgxpool.Pool,
+ queries *db.Queries,
+ dispatcher AutopilotScheduleDispatcher,
+) JobSpec {
+ cache := newAutopilotScheduleCache()
+
+ return JobSpec{
+ Name: JobNameAutopilotScheduleDispatch,
+ Cadence: 0, // hook-driven; cron expressions are arbitrary
+ ScheduleDelay: 0,
+ CatchUpMode: CatchUpLatestOnly, // ignored when hook is set, but documents intent
+ CatchUpWindow: 24 * time.Hour,
+ RunTimeout: 2 * time.Minute,
+ StaleTimeout: 5 * time.Minute,
+ HeartbeatInterval: 30 * time.Second,
+ AllowStaleReentry: true,
+ MaxAttempts: 3,
+ RetryBackoff: []time.Duration{
+ 1 * time.Minute,
+ 5 * time.Minute,
+ 15 * time.Minute,
+ },
+ // Belt-and-suspenders: 5 plan_times is more than CatchUpLatestOnly
+ // ever needs; the cap matters only if a future caller flips the
+ // hook to every_plan semantics.
+ MaxPlansPerTick: 5,
+
+ Scopes: autopilotScopes(pool, queries, cache),
+ PlansForScope: autopilotPlansForScope(cache),
+ Handler: autopilotHandler(queries, dispatcher),
+ }
+}
+
+// autopilotTriggerConfig is the per-tick view of one trigger that the
+// planner hook needs (cron + timezone + bootstrap floor).
+type autopilotTriggerConfig struct {
+ TriggerID string
+ CronExpression string
+ Timezone string
+ CreatedAt time.Time
+}
+
+// autopilotScheduleCache holds the per-tick map of trigger configs.
+// The scope provider rewrites it at the top of each tick; the planner
+// hook reads it once per scope. Reader-writer synchronisation lets us
+// safely add parallel per-scope planning in the future.
+type autopilotScheduleCache struct {
+ mu sync.RWMutex
+ triggers map[string]autopilotTriggerConfig
+}
+
+func newAutopilotScheduleCache() *autopilotScheduleCache {
+ return &autopilotScheduleCache{triggers: make(map[string]autopilotTriggerConfig)}
+}
+
+func (c *autopilotScheduleCache) replace(next map[string]autopilotTriggerConfig) {
+ c.mu.Lock()
+ c.triggers = next
+ c.mu.Unlock()
+}
+
+func (c *autopilotScheduleCache) get(id string) (autopilotTriggerConfig, bool) {
+ c.mu.RLock()
+ v, ok := c.triggers[id]
+ c.mu.RUnlock()
+ return v, ok
+}
+
+// autopilotScopes lists every schedule trigger eligible to fire this
+// tick and populates the cache used by the planner hook. Disabled
+// triggers and paused/archived autopilots fall out naturally because
+// the SQL filter excludes them.
+func autopilotScopes(
+ pool *pgxpool.Pool,
+ queries *db.Queries,
+ cache *autopilotScheduleCache,
+) ScopeProvider {
+ _ = pool // reserved for future tx-bounded reads
+ return func(ctx context.Context, now time.Time) ([]Scope, error) {
+ rows, err := queries.ListSchedulableAutopilotTriggers(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("autopilot scope: list schedulable triggers: %w", err)
+ }
+ next := make(map[string]autopilotTriggerConfig, len(rows))
+ scopes := make([]Scope, 0, len(rows))
+ for _, r := range rows {
+ id := util.UUIDToString(r.ID)
+ if id == "" {
+ continue
+ }
+ tz := DefaultAutopilotScheduleTimezone
+ if r.Timezone.Valid && r.Timezone.String != "" {
+ tz = r.Timezone.String
+ }
+ cron := ""
+ if r.CronExpression.Valid {
+ cron = r.CronExpression.String
+ }
+ if cron == "" {
+ continue
+ }
+ createdAt := time.Time{}
+ if r.CreatedAt.Valid {
+ createdAt = r.CreatedAt.Time.UTC()
+ }
+ next[id] = autopilotTriggerConfig{
+ TriggerID: id,
+ CronExpression: cron,
+ Timezone: tz,
+ CreatedAt: createdAt,
+ }
+ scopes = append(scopes, Scope{Kind: ScopeKindAutopilotTrigger, ID: id})
+ }
+ cache.replace(next)
+ return scopes, nil
+ }
+}
+
+// autopilotPlansForScope returns the PlansForScope hook that computes
+// every cron occurrence in (lastPlan, dbNow] and keeps only the most
+// recent one. This matches the legacy goroutine's "collapse missed
+// fires" semantics; a future per-trigger catch_up_mode column can flip
+// the policy without touching scheduler internals.
+//
+// Retry-eligible state is handled specially: when the most recent
+// stored plan_time is a FAILED row with attempts remaining and
+// next_retry_at <= now, the hook returns THAT plan_time unchanged so
+// tryClaim's FAILED-with-retry branch can fire. Without this branch,
+// the half-open (latest.PlanTime, now] enumeration below would skip
+// past the failed bucket and the occurrence would be lost — the
+// canonical bug from the #4444 review where a claim+crash sequence
+// could leak a scheduled occurrence (MUL-3551 acceptance ③).
+func autopilotPlansForScope(cache *autopilotScheduleCache) func(
+ ctx context.Context, scope Scope, now time.Time, latest LatestPlanInfo,
+) ([]time.Time, error) {
+ const replayWindow = 24 * time.Hour
+ return func(ctx context.Context, scope Scope, now time.Time, latest LatestPlanInfo) ([]time.Time, error) {
+ cfg, ok := cache.get(scope.ID)
+ if !ok {
+ // Trigger disappeared between scope-list and plan-compute,
+ // or was filtered out. Nothing to plan — silent no-op is
+ // correct.
+ return nil, nil
+ }
+
+ // Retry path: the manager's stale-lease sweep has already
+ // promoted any abandoned RUNNING row to FAILED. If that
+ // FAILED row still has attempts remaining and its
+ // next_retry_at has passed, the same plan_time is eligible
+ // for another claim. tryClaim's retry-from-FAILED branch only
+ // fires when the planner returns that exact plan_time, so we
+ // MUST surface it here — moving forward to a newer occurrence
+ // would strand the FAILED row at attempt < max_attempts
+ // forever and leak the missed dispatch.
+ if latest.RetryEligible(now) {
+ return []time.Time{latest.PlanTime}, nil
+ }
+
+ // Anchor on the most recent stored plan_time so the cron evaluator
+ // only enumerates new occurrences. Before the first run we anchor
+ // on the trigger's created_at — never replay history.
+ after := cfg.CreatedAt
+ if latest.Found && latest.PlanTime.After(after) {
+ after = latest.PlanTime
+ }
+ // Bound replay by CatchUpWindow so a long pause / dormant
+ // trigger does not enumerate millions of historical buckets.
+ if oldest := now.Add(-replayWindow); after.Before(oldest) {
+ after = oldest
+ }
+
+ occs, err := service.NextOccurrencesUTC(cfg.CronExpression, cfg.Timezone, after, now)
+ if err != nil {
+ return nil, fmt.Errorf("autopilot plans: cron eval for trigger %s: %w", scope.ID, err)
+ }
+ if len(occs) == 0 {
+ return nil, nil
+ }
+ // CatchUpLatestOnly: collapse missed fires to the most recent.
+ return occs[len(occs)-1:], nil
+ }
+}
+
+// autopilotHandler dispatches one (trigger, planTime) attempt and
+// returns the lease-affecting outcome. It re-loads the trigger +
+// autopilot inside the handler so a between-tick state change (e.g.
+// trigger disabled, autopilot paused) takes effect immediately
+// without waiting for the next scope-list.
+func autopilotHandler(
+ queries *db.Queries,
+ dispatcher AutopilotScheduleDispatcher,
+) Handler {
+ return func(ctx context.Context, in HandlerInput) (HandlerResult, error) {
+ triggerID, err := parseScopeUUID(in.Scope.ID)
+ if err != nil {
+ return HandlerResult{}, fmt.Errorf("autopilot handler: scope id is not a valid uuid: %w", err)
+ }
+
+ trigger, err := queries.GetAutopilotTrigger(ctx, triggerID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // Trigger was deleted between scope-list and run.
+ // A SUCCESS row in sys_cron_executions for a vanished
+ // trigger is fine — there is nothing to dispatch and
+ // no future tick will return this scope.
+ return HandlerResult{RowsAffected: 0, Result: map[string]any{
+ "skipped_reason": "trigger_not_found",
+ }}, nil
+ }
+ return HandlerResult{}, fmt.Errorf("load trigger: %w", err)
+ }
+ if !trigger.Enabled || trigger.Kind != "schedule" {
+ return HandlerResult{RowsAffected: 0, Result: map[string]any{
+ "skipped_reason": "trigger_disabled",
+ }}, nil
+ }
+
+ autopilot, err := queries.GetAutopilot(ctx, trigger.AutopilotID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return HandlerResult{RowsAffected: 0, Result: map[string]any{
+ "skipped_reason": "autopilot_not_found",
+ }}, nil
+ }
+ return HandlerResult{}, fmt.Errorf("load autopilot: %w", err)
+ }
+ if autopilot.Status != "active" {
+ return HandlerResult{RowsAffected: 0, Result: map[string]any{
+ "skipped_reason": "autopilot_inactive",
+ "status": autopilot.Status,
+ }}, nil
+ }
+
+ run, err := dispatcher.DispatchAutopilotForPlan(
+ ctx, autopilot, trigger.ID, "schedule", nil, in.PlanTime,
+ )
+ if err != nil {
+ return HandlerResult{}, fmt.Errorf("dispatch for plan: %w", err)
+ }
+
+ // Bump the display-only last_fired_at so the trigger UI shows
+ // the most recent fire time. Errors are not fatal — the
+ // canonical record is autopilot_run.created_at.
+ _ = queries.TouchAutopilotTriggerFiredAt(ctx, trigger.ID)
+
+ return HandlerResult{
+ RowsAffected: 1,
+ Result: map[string]any{
+ "run_id": util.UUIDToString(run.ID),
+ "run_status": run.Status,
+ },
+ }, nil
+ }
+}
+
+// parseScopeUUID converts a scope.ID string back into pgtype.UUID.
+// We accept both the standard hyphenated form and the unhyphenated
+// raw 32-hex form to keep the contract forgiving.
+func parseScopeUUID(s string) (pgtype.UUID, error) {
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ return pgtype.UUID{}, err
+ }
+ if !u.Valid {
+ return pgtype.UUID{}, errors.New("invalid uuid")
+ }
+ return u, nil
+}
diff --git a/server/internal/scheduler/manager.go b/server/internal/scheduler/manager.go
index af12873ee3..05a86aa4ef 100644
--- a/server/internal/scheduler/manager.go
+++ b/server/internal/scheduler/manager.go
@@ -99,7 +99,7 @@ func (m *Manager) Run(ctx context.Context) error {
// First tick immediately so a fresh start does not wait a full
// interval; backoff to TickInterval thereafter.
- if err := m.runOnce(ctx); err != nil && !errors.Is(err, context.Canceled) {
+ if err := m.RunOnce(ctx); err != nil && !errors.Is(err, context.Canceled) {
m.logger.Warn("scheduler tick error", "error", err)
}
@@ -111,15 +111,17 @@ func (m *Manager) Run(ctx context.Context) error {
m.logger.Info("scheduler stopped", "reason", ctx.Err())
return ctx.Err()
case <-t.C:
- if err := m.runOnce(ctx); err != nil && !errors.Is(err, context.Canceled) {
+ if err := m.RunOnce(ctx); err != nil && !errors.Is(err, context.Canceled) {
m.logger.Warn("scheduler tick error", "error", err)
}
}
}
}
-// runOnce executes a single tick across every registered job.
-func (m *Manager) runOnce(ctx context.Context) error {
+// RunOnce executes a single tick across every registered job. Exposed
+// for tests, one-shot CLIs, and any caller that wants to drive the
+// scheduler without owning a goroutine.
+func (m *Manager) RunOnce(ctx context.Context) error {
now, err := dbNow(ctx, m.pool)
if err != nil {
return err
diff --git a/server/internal/scheduler/manager_tick_test.go b/server/internal/scheduler/manager_tick_test.go
index ad605bc5a0..f9ee6ff0db 100644
--- a/server/internal/scheduler/manager_tick_test.go
+++ b/server/internal/scheduler/manager_tick_test.go
@@ -74,7 +74,7 @@ func TestManagerTickClosesAbandonedRunning(t *testing.T) {
if err := mgr.Register(*job); err != nil {
t.Fatalf("register: %v", err)
}
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("runOnce: %v", err)
}
@@ -140,7 +140,7 @@ func TestManagerHandlerPanicWritesFailed(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("runOnce: %v", err)
}
diff --git a/server/internal/scheduler/plans_for_scope_test.go b/server/internal/scheduler/plans_for_scope_test.go
index b4c7086f8a..3b944cfeeb 100644
--- a/server/internal/scheduler/plans_for_scope_test.go
+++ b/server/internal/scheduler/plans_for_scope_test.go
@@ -156,7 +156,7 @@ func TestManagerPlansForScopeHookDrivesPlans(t *testing.T) {
// Tick 1: no prior plan, hook returns all 4 plans, MaxPlansPerTick
// truncates to {t0, t1}.
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("runOnce tick 1: %v", err)
}
if hookCalls.Load() == 0 {
@@ -189,7 +189,7 @@ func TestManagerPlansForScopeHookDrivesPlans(t *testing.T) {
// latest plan_time (t1, picked by latestPlan ORDER BY plan_time
// DESC).
hookCalls.Store(0)
- if err := mgr.runOnce(ctx); err != nil {
+ if err := mgr.RunOnce(ctx); err != nil {
t.Fatalf("runOnce tick 2: %v", err)
}
if hookCalls.Load() == 0 {
@@ -238,7 +238,7 @@ func TestManagerPlansForScopeHookEmptyIsNoOp(t *testing.T) {
if err := mgr.Register(*job); err != nil {
t.Fatalf("register: %v", err)
}
- if err := mgr.runOnce(context.Background()); err != nil {
+ if err := mgr.RunOnce(context.Background()); err != nil {
t.Fatalf("runOnce: %v", err)
}
if hookCalls.Load() == 0 {
diff --git a/server/internal/service/cron.go b/server/internal/service/cron.go
index e2cc6b4f61..d570b2681c 100644
--- a/server/internal/service/cron.go
+++ b/server/internal/service/cron.go
@@ -10,18 +10,67 @@ import (
// cronParser accepts standard 5-field cron expressions.
var cronParser = cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
-// ComputeNextRun parses a cron expression and returns the next fire time
-// in the given timezone.
-func ComputeNextRun(cronExpr, timezone string) (time.Time, error) {
- sched, err := cronParser.Parse(cronExpr)
+// NextOccurrenceAfterUTC parses cronExpr in the named IANA timezone and
+// returns the next activation strictly after `after`. The result is always
+// in UTC and represents the canonical fire time of the next occurrence.
+//
+// `after` is interpreted as an absolute instant; callers should pass DB
+// time (e.g. `SELECT now()`) rather than `time.Now()` so that two
+// app instances with skewed clocks still produce the same answer.
+//
+// This is the building block the new scheduler.AutopilotScheduleDispatchJob
+// uses to compute plan_times; the handler / UI write paths use it via
+// ComputeNextRunFromUTC to fill in the display-only
+// autopilot_trigger.next_run_at column.
+func NextOccurrenceAfterUTC(cronExpr, timezone string, after time.Time) (time.Time, error) {
+ sched, loc, err := parseCronSchedule(cronExpr, timezone)
if err != nil {
- return time.Time{}, fmt.Errorf("parse cron: %w", err)
+ return time.Time{}, err
}
- loc, err := time.LoadLocation(timezone)
+ return sched.Next(after.In(loc)).UTC(), nil
+}
+
+// NextOccurrencesUTC parses cronExpr in `timezone` and returns every
+// activation in the half-open interval `(after, until]`, in canonical
+// UTC order (ascending). Used by the Autopilot schedule dispatch job to
+// enumerate every plan_time that became due between the last stored
+// occurrence and DB now().
+//
+// The slice is capped at 1024 entries — a safety net against an
+// accidental "every second" cron over a multi-day catch-up window.
+// The scheduler manager additionally caps the returned slice at
+// JobSpec.MaxPlansPerTick.
+func NextOccurrencesUTC(cronExpr, timezone string, after, until time.Time) ([]time.Time, error) {
+ sched, loc, err := parseCronSchedule(cronExpr, timezone)
if err != nil {
- return time.Time{}, fmt.Errorf("invalid timezone %q: %w", timezone, err)
+ return nil, err
}
- return sched.Next(time.Now().In(loc)), nil
+ const hardCap = 1024
+ out := make([]time.Time, 0, 8)
+ cursor := after.In(loc)
+ untilLocal := until.In(loc)
+ for len(out) < hardCap {
+ next := sched.Next(cursor)
+ if next.After(untilLocal) {
+ break
+ }
+ out = append(out, next.UTC())
+ cursor = next
+ }
+ return out, nil
+}
+
+// ComputeNextRun is the legacy wrapper used by the trigger create/update
+// handlers and the failure monitor. It evaluates the cron at the app's
+// local now() — kept for the display-only autopilot_trigger.next_run_at
+// column so we do not have to thread DB time through every UI write
+// path in this same change. Scheduling decisions MUST go through
+// NextOccurrencesUTC against DB time instead.
+//
+// MUL-3551: this function is on its way out; new callers should use
+// NextOccurrenceAfterUTC with a db_now() input instead.
+func ComputeNextRun(cronExpr, timezone string) (time.Time, error) {
+ return NextOccurrenceAfterUTC(cronExpr, timezone, time.Now())
}
// ValidateTimezone returns an error if the timezone string is not recognized.
@@ -32,3 +81,15 @@ func ValidateTimezone(timezone string) error {
}
return nil
}
+
+func parseCronSchedule(cronExpr, timezone string) (cron.Schedule, *time.Location, error) {
+ sched, err := cronParser.Parse(cronExpr)
+ if err != nil {
+ return nil, nil, fmt.Errorf("parse cron: %w", err)
+ }
+ loc, err := time.LoadLocation(timezone)
+ if err != nil {
+ return nil, nil, fmt.Errorf("invalid timezone %q: %w", timezone, err)
+ }
+ return sched, loc, nil
+}
diff --git a/server/internal/service/cron_test.go b/server/internal/service/cron_test.go
new file mode 100644
index 0000000000..e6d5454e19
--- /dev/null
+++ b/server/internal/service/cron_test.go
@@ -0,0 +1,136 @@
+package service
+
+import (
+ "testing"
+ "time"
+)
+
+// TestNextOccurrencesUTCEnumeratesInTimezone verifies the cron evaluator
+// is timezone-aware on input but always returns UTC on output, and that
+// the half-open (after, until] window is respected.
+func TestNextOccurrencesUTCEnumeratesInTimezone(t *testing.T) {
+ // Every Mon-Fri at 09:00 in Asia/Shanghai (UTC+8). 09:00 CST is
+ // 01:00 UTC the same day.
+ cron := "0 9 * * MON-FRI"
+ tz := "Asia/Shanghai"
+
+ // 2026-06-23 is a Tuesday. Pick a Monday-Friday span:
+ // Monday 2026-06-22 09:00 CST = 2026-06-22T01:00:00Z
+ // Tuesday 2026-06-23 09:00 CST = 2026-06-23T01:00:00Z
+ // Wednesday 2026-06-24 09:00 CST = 2026-06-24T01:00:00Z
+ after := time.Date(2026, 6, 21, 0, 0, 0, 0, time.UTC) // Sunday — before Mon's first fire
+ until := time.Date(2026, 6, 24, 1, 0, 0, 0, time.UTC) // exactly Wed 09:00 CST
+
+ got, err := NextOccurrencesUTC(cron, tz, after, until)
+ if err != nil {
+ t.Fatalf("NextOccurrencesUTC: %v", err)
+ }
+
+ want := []time.Time{
+ time.Date(2026, 6, 22, 1, 0, 0, 0, time.UTC),
+ time.Date(2026, 6, 23, 1, 0, 0, 0, time.UTC),
+ time.Date(2026, 6, 24, 1, 0, 0, 0, time.UTC),
+ }
+ if len(got) != len(want) {
+ t.Fatalf("expected %d occurrences, got %d: %v", len(want), len(got), got)
+ }
+ for i, g := range got {
+ if !g.Equal(want[i]) {
+ t.Fatalf("occurrence[%d]: got %s, want %s",
+ i, g.Format(time.RFC3339), want[i].Format(time.RFC3339))
+ }
+ if g.Location() != time.UTC {
+ t.Fatalf("occurrence[%d] must be UTC, got %s", i, g.Location())
+ }
+ }
+}
+
+// TestNextOccurrencesUTCEmptyWindow asserts that an `after` >= `until`
+// returns nothing without erroring — the planner relies on this for
+// the "nothing due yet" branch.
+func TestNextOccurrencesUTCEmptyWindow(t *testing.T) {
+ cron := "*/5 * * * *"
+ tz := "UTC"
+
+ // after AFTER until: no occurrences should be returned.
+ after := time.Date(2026, 6, 23, 12, 0, 0, 0, time.UTC)
+ until := after.Add(-time.Minute)
+
+ got, err := NextOccurrencesUTC(cron, tz, after, until)
+ if err != nil {
+ t.Fatalf("NextOccurrencesUTC: %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("expected no occurrences for empty window, got %v", got)
+ }
+}
+
+// TestNextOccurrencesUTCExclusiveAfter verifies that a plan_time equal
+// to `after` is NOT re-emitted. This is essential for the planner: when
+// the most recent stored plan_time is X, the next tick must NOT
+// produce X again.
+func TestNextOccurrencesUTCExclusiveAfter(t *testing.T) {
+ cron := "*/5 * * * *"
+ tz := "UTC"
+
+ // after sits exactly on a cron tick. The next emitted plan must
+ // be the SUBSEQUENT tick, not the same one.
+ after := time.Date(2026, 6, 23, 12, 0, 0, 0, time.UTC)
+ until := time.Date(2026, 6, 23, 12, 10, 0, 0, time.UTC)
+
+ got, err := NextOccurrencesUTC(cron, tz, after, until)
+ if err != nil {
+ t.Fatalf("NextOccurrencesUTC: %v", err)
+ }
+ want := []time.Time{
+ time.Date(2026, 6, 23, 12, 5, 0, 0, time.UTC),
+ time.Date(2026, 6, 23, 12, 10, 0, 0, time.UTC),
+ }
+ if len(got) != len(want) {
+ t.Fatalf("expected %d occurrences, got %d: %v", len(want), len(got), got)
+ }
+ for i, g := range got {
+ if !g.Equal(want[i]) {
+ t.Fatalf("occurrence[%d]: got %s want %s",
+ i, g.Format(time.RFC3339), want[i].Format(time.RFC3339))
+ }
+ }
+}
+
+// TestNextOccurrencesUTCInvalidInputs surfaces parse errors loudly so
+// a bad cron expression cannot silently disable a trigger.
+func TestNextOccurrencesUTCInvalidInputs(t *testing.T) {
+ t.Run("bad cron", func(t *testing.T) {
+ _, err := NextOccurrencesUTC("not a cron", "UTC", time.Now(), time.Now().Add(time.Hour))
+ if err == nil {
+ t.Fatal("expected error for bad cron expression")
+ }
+ })
+ t.Run("bad timezone", func(t *testing.T) {
+ _, err := NextOccurrencesUTC("* * * * *", "Mars/Olympus", time.Now(), time.Now().Add(time.Hour))
+ if err == nil {
+ t.Fatal("expected error for invalid timezone")
+ }
+ })
+}
+
+// TestNextOccurrenceAfterUTCIgnoresWallClock verifies that the helper
+// uses the explicit `after` argument, not time.Now(). This is the key
+// property the scheduler relies on: callers pass dbNow() and get
+// answers consistent across app instances with skewed clocks.
+func TestNextOccurrenceAfterUTCIgnoresWallClock(t *testing.T) {
+ cron := "30 14 * * *" // 14:30 daily in UTC
+
+ // Pretend "DB now" is at midnight UTC. The next fire is 14:30 UTC
+ // the same day — independent of whatever the host clock says.
+ after := time.Date(2026, 6, 23, 0, 0, 0, 0, time.UTC)
+ want := time.Date(2026, 6, 23, 14, 30, 0, 0, time.UTC)
+
+ got, err := NextOccurrenceAfterUTC(cron, "UTC", after)
+ if err != nil {
+ t.Fatalf("NextOccurrenceAfterUTC: %v", err)
+ }
+ if !got.Equal(want) {
+ t.Fatalf("got %s, want %s", got.Format(time.RFC3339), want.Format(time.RFC3339))
+ }
+}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 5ea5d83b9f..98d070e0c3 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -46,81 +46,6 @@ func (q *Queries) AdvanceTriggerNextRun(ctx context.Context, arg AdvanceTriggerN
return err
}
-const claimDueScheduleTriggers = `-- name: ClaimDueScheduleTriggers :many
-
-UPDATE autopilot_trigger t
-SET next_run_at = NULL
-FROM autopilot a
-WHERE t.autopilot_id = a.id
- AND t.kind = 'schedule'
- AND t.enabled = true
- AND t.next_run_at IS NOT NULL
- AND t.next_run_at <= now()
- AND a.status = 'active'
-RETURNING t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, a.workspace_id AS autopilot_workspace_id
-`
-
-type ClaimDueScheduleTriggersRow struct {
- ID pgtype.UUID `json:"id"`
- AutopilotID pgtype.UUID `json:"autopilot_id"`
- Kind string `json:"kind"`
- Enabled bool `json:"enabled"`
- CronExpression pgtype.Text `json:"cron_expression"`
- Timezone pgtype.Text `json:"timezone"`
- NextRunAt pgtype.Timestamptz `json:"next_run_at"`
- WebhookToken pgtype.Text `json:"webhook_token"`
- Label pgtype.Text `json:"label"`
- LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- Provider string `json:"provider"`
- SigningSecret pgtype.Text `json:"signing_secret"`
- EventFilters []byte `json:"event_filters"`
- AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
-}
-
-// =====================
-// Scheduler Queries
-// =====================
-// Atomically claim all due schedule triggers to prevent concurrent execution.
-// Joins the autopilot table to ensure only active autopilots are fired.
-func (q *Queries) ClaimDueScheduleTriggers(ctx context.Context) ([]ClaimDueScheduleTriggersRow, error) {
- rows, err := q.db.Query(ctx, claimDueScheduleTriggers)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ClaimDueScheduleTriggersRow{}
- for rows.Next() {
- var i ClaimDueScheduleTriggersRow
- if err := rows.Scan(
- &i.ID,
- &i.AutopilotID,
- &i.Kind,
- &i.Enabled,
- &i.CronExpression,
- &i.Timezone,
- &i.NextRunAt,
- &i.WebhookToken,
- &i.Label,
- &i.LastFiredAt,
- &i.CreatedAt,
- &i.UpdatedAt,
- &i.Provider,
- &i.SigningSecret,
- &i.EventFilters,
- &i.AutopilotWorkspaceID,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const createAutopilot = `-- name: CreateAutopilot :one
INSERT INTO autopilot (
workspace_id, title, description, assignee_type, assignee_id,
@@ -877,69 +802,54 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
return items, nil
}
-const recoverLostTriggers = `-- name: RecoverLostTriggers :many
+const listSchedulableAutopilotTriggers = `-- name: ListSchedulableAutopilotTriggers :many
-SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, t.event_filters, a.workspace_id AS autopilot_workspace_id
+SELECT t.id, t.autopilot_id, t.cron_expression, t.timezone, t.created_at
FROM autopilot_trigger t
-JOIN autopilot a ON t.autopilot_id = a.id
+JOIN autopilot a ON a.id = t.autopilot_id
WHERE t.kind = 'schedule'
- AND t.enabled = true
- AND t.next_run_at IS NULL
- AND t.cron_expression IS NOT NULL
+ AND t.enabled = TRUE
AND a.status = 'active'
+ AND t.cron_expression IS NOT NULL
+ AND t.cron_expression <> ''
+ORDER BY t.id
`
-type RecoverLostTriggersRow struct {
- ID pgtype.UUID `json:"id"`
- AutopilotID pgtype.UUID `json:"autopilot_id"`
- Kind string `json:"kind"`
- Enabled bool `json:"enabled"`
- CronExpression pgtype.Text `json:"cron_expression"`
- Timezone pgtype.Text `json:"timezone"`
- NextRunAt pgtype.Timestamptz `json:"next_run_at"`
- WebhookToken pgtype.Text `json:"webhook_token"`
- Label pgtype.Text `json:"label"`
- LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- Provider string `json:"provider"`
- SigningSecret pgtype.Text `json:"signing_secret"`
- EventFilters []byte `json:"event_filters"`
- AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
+type ListSchedulableAutopilotTriggersRow struct {
+ ID pgtype.UUID `json:"id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ CronExpression pgtype.Text `json:"cron_expression"`
+ Timezone pgtype.Text `json:"timezone"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
}
// =====================
-// Scheduler Recovery
+// Scheduler Queries
// =====================
-// Finds schedule triggers that were claimed (next_run_at = NULL) but never
-// advanced — typically due to a scheduler crash. Returns them so the scheduler
-// can recompute next_run_at.
-func (q *Queries) RecoverLostTriggers(ctx context.Context) ([]RecoverLostTriggersRow, error) {
- rows, err := q.db.Query(ctx, recoverLostTriggers)
+// Lists every schedule trigger the autopilot_schedule_dispatch JobSpec
+// should consider this tick. Returns just the columns the scheduler's
+// scope provider + PlansForScope hook need; the full trigger row is
+// re-loaded by the handler so a trigger update between scope-list and
+// handler-run sees the latest enabled / cron values.
+//
+// Filters out webhook / api triggers, disabled triggers, paused/archived
+// autopilots, and any trigger missing its cron expression. ORDER BY id
+// keeps the per-tick scope list stable across replicas.
+func (q *Queries) ListSchedulableAutopilotTriggers(ctx context.Context) ([]ListSchedulableAutopilotTriggersRow, error) {
+ rows, err := q.db.Query(ctx, listSchedulableAutopilotTriggers)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []RecoverLostTriggersRow{}
+ items := []ListSchedulableAutopilotTriggersRow{}
for rows.Next() {
- var i RecoverLostTriggersRow
+ var i ListSchedulableAutopilotTriggersRow
if err := rows.Scan(
&i.ID,
&i.AutopilotID,
- &i.Kind,
- &i.Enabled,
&i.CronExpression,
&i.Timezone,
- &i.NextRunAt,
- &i.WebhookToken,
- &i.Label,
- &i.LastFiredAt,
&i.CreatedAt,
- &i.UpdatedAt,
- &i.Provider,
- &i.SigningSecret,
- &i.EventFilters,
- &i.AutopilotWorkspaceID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 4d5b4dbbb1..6108806947 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -291,19 +291,25 @@ RETURNING *;
-- Scheduler Queries
-- =====================
--- name: ClaimDueScheduleTriggers :many
--- Atomically claim all due schedule triggers to prevent concurrent execution.
--- Joins the autopilot table to ensure only active autopilots are fired.
-UPDATE autopilot_trigger t
-SET next_run_at = NULL
-FROM autopilot a
-WHERE t.autopilot_id = a.id
- AND t.kind = 'schedule'
- AND t.enabled = true
- AND t.next_run_at IS NOT NULL
- AND t.next_run_at <= now()
+-- name: ListSchedulableAutopilotTriggers :many
+-- Lists every schedule trigger the autopilot_schedule_dispatch JobSpec
+-- should consider this tick. Returns just the columns the scheduler's
+-- scope provider + PlansForScope hook need; the full trigger row is
+-- re-loaded by the handler so a trigger update between scope-list and
+-- handler-run sees the latest enabled / cron values.
+--
+-- Filters out webhook / api triggers, disabled triggers, paused/archived
+-- autopilots, and any trigger missing its cron expression. ORDER BY id
+-- keeps the per-tick scope list stable across replicas.
+SELECT t.id, t.autopilot_id, t.cron_expression, t.timezone, t.created_at
+FROM autopilot_trigger t
+JOIN autopilot a ON a.id = t.autopilot_id
+WHERE t.kind = 'schedule'
+ AND t.enabled = TRUE
AND a.status = 'active'
-RETURNING t.*, a.workspace_id AS autopilot_workspace_id;
+ AND t.cron_expression IS NOT NULL
+ AND t.cron_expression <> ''
+ORDER BY t.id;
-- =====================
-- Task Queue (run_only mode)
@@ -331,23 +337,6 @@ SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was
WHERE issue_id = $1
AND status IN ('issue_created', 'running');
--- =====================
--- Scheduler Recovery
--- =====================
-
--- name: RecoverLostTriggers :many
--- Finds schedule triggers that were claimed (next_run_at = NULL) but never
--- advanced — typically due to a scheduler crash. Returns them so the scheduler
--- can recompute next_run_at.
-SELECT t.*, a.workspace_id AS autopilot_workspace_id
-FROM autopilot_trigger t
-JOIN autopilot a ON t.autopilot_id = a.id
-WHERE t.kind = 'schedule'
- AND t.enabled = true
- AND t.next_run_at IS NULL
- AND t.cron_expression IS NOT NULL
- AND a.status = 'active';
-
-- =====================
-- Failure-rate auto-pause
-- =====================