Skip to content

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

Go

refactor(autopilot): remove broken concurrency policies and fix multiple bugs (#1048)

Jiayuan Zhangf94b0100cdaa
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index 86c96ca9d4..a73c013ccd 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -2,11 +2,9 @@ export type AutopilotStatus = "active" | "paused" | "archived";
export type AutopilotExecutionMode = "create_issue" | "run_only";
-export type AutopilotConcurrencyPolicy = "skip" | "queue" | "replace";
-
export type AutopilotTriggerKind = "schedule" | "webhook" | "api";
-export type AutopilotRunStatus = "pending" | "issue_created" | "running" | "skipped" | "completed" | "failed";
+export type AutopilotRunStatus = "issue_created" | "running" | "completed" | "failed";
export type AutopilotRunSource = "schedule" | "manual" | "webhook" | "api";
@@ -21,7 +19,6 @@ export interface Autopilot {
status: AutopilotStatus;
execution_mode: AutopilotExecutionMode;
issue_title_template: string | null;
- concurrency_policy: AutopilotConcurrencyPolicy;
created_by_type: string;
created_by_id: string;
last_run_at: string | null;
@@ -67,7 +64,6 @@ export interface CreateAutopilotRequest {
project_id?: string;
priority?: string;
execution_mode: AutopilotExecutionMode;
- concurrency_policy?: AutopilotConcurrencyPolicy;
issue_title_template?: string;
}
@@ -79,7 +75,6 @@ export interface UpdateAutopilotRequest {
priority?: string;
status?: AutopilotStatus;
execution_mode?: AutopilotExecutionMode;
- concurrency_policy?: AutopilotConcurrencyPolicy;
issue_title_template?: string | null;
}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 28e81ccbe4..0ce0f9904a 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -38,7 +38,6 @@ export type {
Autopilot,
AutopilotStatus,
AutopilotExecutionMode,
- AutopilotConcurrencyPolicy,
AutopilotTrigger,
AutopilotTriggerKind,
AutopilotRun,
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index e0ace0128f..d107eed3bc 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
-import { Zap, Play, Pause, Clock, Plus, Trash2, CheckCircle2, XCircle, SkipForward, Loader2, Pencil } from "lucide-react";
+import { Zap, Play, Pause, Clock, Plus, Trash2, CheckCircle2, XCircle, Loader2, Pencil } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { autopilotDetailOptions, autopilotRunsOptions } from "@multica/core/autopilots/queries";
import {
@@ -50,16 +50,14 @@ function formatDate(date: string): string {
}
const RUN_STATUS_CONFIG: Record<string, { label: string; color: string; icon: typeof CheckCircle2 }> = {
- pending: { label: "Pending", color: "text-blue-500", icon: Clock },
issue_created: { label: "Issue Created", color: "text-blue-500", icon: Clock },
running: { label: "Running", color: "text-blue-500", icon: Loader2 },
completed: { label: "Completed", color: "text-emerald-500", icon: CheckCircle2 },
failed: { label: "Failed", color: "text-destructive", icon: XCircle },
- skipped: { label: "Skipped", color: "text-muted-foreground", icon: SkipForward },
};
function RunRow({ run }: { run: AutopilotRun }) {
- const cfg = (RUN_STATUS_CONFIG[run.status] ?? RUN_STATUS_CONFIG["pending"])!;
+ const cfg = (RUN_STATUS_CONFIG[run.status] ?? RUN_STATUS_CONFIG["issue_created"])!;
const StatusIcon = cfg.icon;
return (
@@ -474,10 +472,6 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
{autopilot.execution_mode === "create_issue" ? "Create Issue" : "Run Only"}
</div>
</div>
- <div>
- <label className="text-xs text-muted-foreground">Concurrency</label>
- <div className="mt-1 capitalize">{autopilot.concurrency_policy}</div>
- </div>
{autopilot.description && (
<div className="col-span-2">
<label className="text-xs text-muted-foreground">Prompt</label>
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index 771c955e3a..b098cdfee3 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -229,7 +229,6 @@ function CreateAutopilotDialog({
description: description.trim() || undefined,
assignee_id: assigneeId,
execution_mode: "create_issue",
- concurrency_policy: "skip",
});
// Attach schedule trigger
diff --git a/server/cmd/server/autopilot_listeners.go b/server/cmd/server/autopilot_listeners.go
index e3e328e192..fae3dd7101 100644
--- a/server/cmd/server/autopilot_listeners.go
+++ b/server/cmd/server/autopilot_listeners.go
@@ -30,8 +30,8 @@ func registerAutopilotListeners(bus *events.Bus, svc *service.AutopilotService)
if !ok {
return
}
- // Only handle terminal statuses.
- if issue.Status != "done" && issue.Status != "cancelled" && issue.Status != "blocked" {
+ // Only handle statuses that finalize an autopilot run.
+ if issue.Status != "done" && issue.Status != "in_review" && issue.Status != "cancelled" && issue.Status != "blocked" {
return
}
// Load the full issue from DB to check origin_type.
diff --git a/server/cmd/server/autopilot_scheduler.go b/server/cmd/server/autopilot_scheduler.go
index 9c74da9515..0f0f463e23 100644
--- a/server/cmd/server/autopilot_scheduler.go
+++ b/server/cmd/server/autopilot_scheduler.go
@@ -15,6 +15,9 @@ 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()
@@ -28,6 +31,43 @@ func runAutopilotScheduler(ctx context.Context, queries *db.Queries, svc *servic
}
}
+// 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 := "UTC"
+ 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)
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index 19cf9c29d8..720eb48ee0 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -32,7 +32,6 @@ type AutopilotResponse struct {
Status string `json:"status"`
ExecutionMode string `json:"execution_mode"`
IssueTitleTemplate *string `json:"issue_title_template"`
- ConcurrencyPolicy string `json:"concurrency_policy"`
CreatedByType string `json:"created_by_type"`
CreatedByID string `json:"created_by_id"`
LastRunAt *string `json:"last_run_at"`
@@ -85,7 +84,6 @@ func autopilotToResponse(a db.Autopilot) AutopilotResponse {
Status: a.Status,
ExecutionMode: a.ExecutionMode,
IssueTitleTemplate: textToPtr(a.IssueTitleTemplate),
- ConcurrencyPolicy: a.ConcurrencyPolicy,
CreatedByType: a.CreatedByType,
CreatedByID: uuidToString(a.CreatedByID),
LastRunAt: timestampToPtr(a.LastRunAt),
@@ -146,7 +144,6 @@ type CreateAutopilotRequest struct {
ProjectID *string `json:"project_id"`
Priority string `json:"priority"`
ExecutionMode string `json:"execution_mode"`
- ConcurrencyPolicy string `json:"concurrency_policy"`
IssueTitleTemplate *string `json:"issue_title_template"`
}
@@ -158,7 +155,6 @@ type UpdateAutopilotRequest struct {
Priority *string `json:"priority"`
Status *string `json:"status"`
ExecutionMode *string `json:"execution_mode"`
- ConcurrencyPolicy *string `json:"concurrency_policy"`
IssueTitleTemplate *string `json:"issue_title_template"`
}
@@ -276,10 +272,6 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
if priority == "" {
priority = "none"
}
- concurrencyPolicy := req.ConcurrencyPolicy
- if concurrencyPolicy == "" {
- concurrencyPolicy = "skip"
- }
var projectID pgtype.UUID
if req.ProjectID != nil {
@@ -293,7 +285,6 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {
Priority: priority,
Status: "active",
ExecutionMode: req.ExecutionMode,
- ConcurrencyPolicy: concurrencyPolicy,
CreatedByType: "member",
CreatedByID: parseUUID(userID),
ProjectID: projectID,
@@ -360,9 +351,6 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {
if req.ExecutionMode != nil {
params.ExecutionMode = pgtype.Text{String: *req.ExecutionMode, Valid: true}
}
- if req.ConcurrencyPolicy != nil {
- params.ConcurrencyPolicy = pgtype.Text{String: *req.ConcurrencyPolicy, Valid: true}
- }
if _, ok := rawFields["description"]; ok {
params.Description = ptrToText(req.Description)
}
@@ -452,6 +440,13 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
return
}
+ if req.Timezone != nil && *req.Timezone != "" {
+ if err := service.ValidateTimezone(*req.Timezone); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ }
+
var nextRunAt pgtype.Timestamptz
if req.Kind == "schedule" && req.CronExpression != nil {
tz := "UTC"
@@ -460,7 +455,7 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
}
t, err := computeNextRun(*req.CronExpression, tz)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid cron expression: "+err.Error())
+ writeError(w, http.StatusBadRequest, err.Error())
return
}
nextRunAt = pgtype.Timestamptz{Time: t, Valid: true}
@@ -529,6 +524,12 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
params.CronExpression = pgtype.Text{String: *req.CronExpression, Valid: true}
}
if req.Timezone != nil {
+ if *req.Timezone != "" {
+ if err := service.ValidateTimezone(*req.Timezone); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ }
params.Timezone = pgtype.Text{String: *req.Timezone, Valid: true}
}
if req.Label != nil {
@@ -550,7 +551,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
if prev.Kind == "schedule" && cronExpr != "" {
t, err := computeNextRun(cronExpr, tz)
if err != nil {
- writeError(w, http.StatusBadRequest, "invalid cron expression: "+err.Error())
+ writeError(w, http.StatusBadRequest, err.Error())
return
}
params.NextRunAt = pgtype.Timestamptz{Time: t, Valid: true}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 2fcea202ec..67344b218d 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -1219,6 +1219,8 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
}
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
+ // Fail any linked autopilot runs before delete (ON DELETE SET NULL clears issue_id).
+ h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)
// Collect all attachment URLs (issue-level + comment-level) before CASCADE delete.
attachmentURLs, _ := h.Queries.ListAttachmentURLsByIssueOrComments(r.Context(), issue.ID)
@@ -1463,6 +1465,7 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
}
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
+ h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)
// Collect attachment URLs before CASCADE delete to clean up S3 objects.
attachmentURLs, _ := h.Queries.ListAttachmentURLsByIssueOrComments(r.Context(), issue.ID)
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index d53f09ba55..648401fca2 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -32,8 +32,8 @@ func NewAutopilotService(q *db.Queries, tx TxStarter, bus *events.Bus, taskSvc *
}
// DispatchAutopilot is the core execution entry point.
-// It checks concurrency policy, creates a run, and either creates an issue
-// or enqueues a direct agent task depending on execution_mode.
+// It creates a run and either creates an issue or enqueues a direct agent task
+// depending on execution_mode.
func (s *AutopilotService) DispatchAutopilot(
ctx context.Context,
autopilot db.Autopilot,
@@ -41,39 +41,17 @@ func (s *AutopilotService) DispatchAutopilot(
source string,
payload []byte,
) (*db.AutopilotRun, error) {
- // Check concurrency policy.
- allowed, err := s.checkConcurrency(ctx, autopilot)
- if err != nil {
- return nil, fmt.Errorf("concurrency check: %w", err)
- }
- if !allowed {
- // Create a skipped run record.
- run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
- AutopilotID: autopilot.ID,
- TriggerID: triggerID,
- Source: source,
- Status: "skipped",
- TriggerPayload: payload,
- })
- if err != nil {
- return nil, fmt.Errorf("create skipped run: %w", err)
- }
- if _, err := s.Queries.UpdateAutopilotRunSkipped(ctx, db.UpdateAutopilotRunSkippedParams{
- ID: run.ID,
- FailureReason: pgtype.Text{String: "skipped: active run exists", Valid: true},
- }); err != nil {
- slog.Warn("failed to finalize skipped run", "run_id", util.UUIDToString(run.ID), "error", err)
- }
- slog.Info("autopilot run skipped", "autopilot_id", util.UUIDToString(autopilot.ID), "source", source)
- return &run, nil
+ // Determine initial status based on execution mode.
+ initialStatus := "issue_created"
+ if autopilot.ExecutionMode == "run_only" {
+ initialStatus = "running"
}
- // Create a pending run.
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: source,
- Status: "pending",
+ Status: initialStatus,
TriggerPayload: payload,
})
if err != nil {
@@ -166,10 +144,9 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
IssueID: issue.ID,
})
if err != nil {
- slog.Warn("failed to update run with issue_id", "run_id", util.UUIDToString(run.ID), "error", err)
- } else {
- *run = updatedRun
+ return fmt.Errorf("link run to issue: %w", err)
}
+ *run = updatedRun
// Publish issue:created so the existing event chain fires
// (subscriber listeners, activity listeners, notification listeners).
@@ -186,7 +163,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
// Enqueue agent task via the existing flow.
if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
- slog.Warn("autopilot: failed to enqueue task for issue", "issue_id", util.UUIDToString(issue.ID), "error", err)
+ return fmt.Errorf("enqueue task for issue: %w", err)
}
slog.Info("autopilot dispatched (create_issue)",
@@ -317,31 +294,6 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
}
}
-// checkConcurrency enforces the autopilot's concurrency policy.
-// Returns true if a new run is allowed, false otherwise.
-func (s *AutopilotService) checkConcurrency(ctx context.Context, ap db.Autopilot) (bool, error) {
- switch ap.ConcurrencyPolicy {
- case "queue":
- return true, nil // always allow
- case "skip":
- _, err := s.Queries.FindActiveAutopilotRun(ctx, ap.ID)
- if err == nil {
- return false, nil // active run exists
- }
- if err == pgx.ErrNoRows {
- return true, nil
- }
- return false, err
- case "replace":
- // Cancel existing active runs, then allow.
- if err := s.Queries.CancelActiveAutopilotRuns(ctx, ap.ID); err != nil {
- slog.Warn("failed to cancel active runs for replace policy", "autopilot_id", util.UUIDToString(ap.ID), "error", err)
- }
- return true, nil
- default:
- return true, nil
- }
-}
func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reason string) {
if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
diff --git a/server/internal/service/cron.go b/server/internal/service/cron.go
index 0970cad31d..e2cc6b4f61 100644
--- a/server/internal/service/cron.go
+++ b/server/internal/service/cron.go
@@ -11,7 +11,7 @@ import (
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 (falls back to UTC on error).
+// in the given timezone.
func ComputeNextRun(cronExpr, timezone string) (time.Time, error) {
sched, err := cronParser.Parse(cronExpr)
if err != nil {
@@ -19,7 +19,16 @@ func ComputeNextRun(cronExpr, timezone string) (time.Time, error) {
}
loc, err := time.LoadLocation(timezone)
if err != nil {
- loc = time.UTC
+ return time.Time{}, fmt.Errorf("invalid timezone %q: %w", timezone, err)
}
return sched.Next(time.Now().In(loc)), nil
}
+
+// ValidateTimezone returns an error if the timezone string is not recognized.
+func ValidateTimezone(timezone string) error {
+ _, err := time.LoadLocation(timezone)
+ if err != nil {
+ return fmt.Errorf("invalid timezone %q: %w", timezone, err)
+ }
+ return nil
+}
diff --git a/server/migrations/043_fix_orphaned_autopilot_runs.down.sql b/server/migrations/043_fix_orphaned_autopilot_runs.down.sql
new file mode 100644
index 0000000000..3042dd101c
--- /dev/null
+++ b/server/migrations/043_fix_orphaned_autopilot_runs.down.sql
@@ -0,0 +1,16 @@
+-- Drop the issue_id index added in the up migration.
+DROP INDEX IF EXISTS idx_autopilot_run_issue;
+
+-- Restore the original partial status index.
+DROP INDEX IF EXISTS idx_autopilot_run_status;
+CREATE INDEX IF NOT EXISTS idx_autopilot_run_status ON autopilot_run(autopilot_id, status)
+ WHERE status IN ('pending', 'issue_created', 'running');
+
+-- Restore concurrency_policy column.
+ALTER TABLE autopilot ADD COLUMN IF NOT EXISTS concurrency_policy TEXT NOT NULL DEFAULT 'skip'
+ CHECK (concurrency_policy IN ('skip', 'queue', 'replace'));
+
+-- Restore the original status CHECK constraint.
+ALTER TABLE autopilot_run DROP CONSTRAINT IF EXISTS autopilot_run_status_check;
+ALTER TABLE autopilot_run ADD CONSTRAINT autopilot_run_status_check
+ CHECK (status IN ('pending', 'issue_created', 'running', 'skipped', 'completed', 'failed'));
diff --git a/server/migrations/043_fix_orphaned_autopilot_runs.up.sql b/server/migrations/043_fix_orphaned_autopilot_runs.up.sql
new file mode 100644
index 0000000000..f2df0d8b2b
--- /dev/null
+++ b/server/migrations/043_fix_orphaned_autopilot_runs.up.sql
@@ -0,0 +1,35 @@
+-- Remove concurrency_policy from autopilot (was broken: skip had orphan bug,
+-- queue didn't actually queue, replace didn't cancel running tasks).
+
+-- 1. Clean up orphaned runs (issue deleted → issue_id NULL, status stuck).
+UPDATE autopilot_run
+SET status = 'failed',
+ completed_at = now(),
+ failure_reason = 'linked issue was deleted'
+WHERE status = 'issue_created'
+ AND issue_id IS NULL;
+
+-- 2. Migrate skipped/pending runs to failed (these statuses are removed).
+UPDATE autopilot_run
+SET status = 'failed',
+ completed_at = COALESCE(completed_at, now()),
+ failure_reason = COALESCE(failure_reason, 'migrated from legacy status')
+WHERE status IN ('skipped', 'pending');
+
+-- 3. Update the status CHECK constraint to remove skipped and pending.
+ALTER TABLE autopilot_run DROP CONSTRAINT IF EXISTS autopilot_run_status_check;
+ALTER TABLE autopilot_run ADD CONSTRAINT autopilot_run_status_check
+ CHECK (status IN ('issue_created', 'running', 'completed', 'failed'));
+
+-- 4. Drop concurrency_policy column.
+ALTER TABLE autopilot DROP COLUMN IF EXISTS concurrency_policy;
+
+-- 5. Update the partial index on status to match new allowed values.
+DROP INDEX IF EXISTS idx_autopilot_run_status;
+CREATE INDEX IF NOT EXISTS idx_autopilot_run_status ON autopilot_run(autopilot_id, status)
+ WHERE status IN ('issue_created', 'running');
+
+-- 6. Add index for issue-linked run lookups (used by FailAutopilotRunsByIssue
+-- and GetAutopilotRunByIssue before issue deletion).
+CREATE INDEX IF NOT EXISTS idx_autopilot_run_issue ON autopilot_run(issue_id)
+ WHERE issue_id IS NOT NULL;
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index ad946e623b..bcf025f873 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -29,19 +29,6 @@ func (q *Queries) AdvanceTriggerNextRun(ctx context.Context, arg AdvanceTriggerN
return err
}
-const cancelActiveAutopilotRuns = `-- name: CancelActiveAutopilotRuns :exec
-UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = 'replaced by new run'
-WHERE autopilot_id = $1
- AND status IN ('pending', 'issue_created', 'running')
-`
-
-// Used by the 'replace' concurrency policy to cancel existing runs.
-func (q *Queries) CancelActiveAutopilotRuns(ctx context.Context, autopilotID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, cancelActiveAutopilotRuns, autopilotID)
- return err
-}
-
const claimDueScheduleTriggers = `-- name: ClaimDueScheduleTriggers :many
UPDATE autopilot_trigger t
@@ -115,12 +102,12 @@ const createAutopilot = `-- name: CreateAutopilot :one
INSERT INTO autopilot (
workspace_id, project_id, title, description, assignee_id,
priority, status, execution_mode, issue_title_template,
- concurrency_policy, created_by_type, created_by_id
+ created_by_type, created_by_id
) VALUES (
- $1, $10, $2, $11, $3,
- $4, $5, $6, $12,
- $7, $8, $9
-) RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at
+ $1, $9, $2, $10, $3,
+ $4, $5, $6, $11,
+ $7, $8
+) RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at
`
type CreateAutopilotParams struct {
@@ -130,7 +117,6 @@ type CreateAutopilotParams struct {
Priority string `json:"priority"`
Status string `json:"status"`
ExecutionMode string `json:"execution_mode"`
- ConcurrencyPolicy string `json:"concurrency_policy"`
CreatedByType string `json:"created_by_type"`
CreatedByID pgtype.UUID `json:"created_by_id"`
ProjectID pgtype.UUID `json:"project_id"`
@@ -146,7 +132,6 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
arg.Priority,
arg.Status,
arg.ExecutionMode,
- arg.ConcurrencyPolicy,
arg.CreatedByType,
arg.CreatedByID,
arg.ProjectID,
@@ -165,7 +150,6 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
&i.Status,
&i.ExecutionMode,
&i.IssueTitleTemplate,
- &i.ConcurrencyPolicy,
&i.CreatedByType,
&i.CreatedByID,
&i.LastRunAt,
@@ -338,42 +322,22 @@ func (q *Queries) DeleteAutopilotTrigger(ctx context.Context, id pgtype.UUID) er
return err
}
-const findActiveAutopilotRun = `-- name: FindActiveAutopilotRun :one
-
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run
-WHERE autopilot_id = $1
- AND status IN ('pending', 'issue_created', 'running')
-ORDER BY created_at DESC
-LIMIT 1
+const failAutopilotRunsByIssue = `-- name: FailAutopilotRunsByIssue :exec
+UPDATE autopilot_run
+SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
+WHERE issue_id = $1
+ AND status IN ('issue_created', 'running')
`
-// =====================
-// Concurrency Check
-// =====================
-// Returns an active (non-terminal) run for the given autopilot, if any.
-func (q *Queries) FindActiveAutopilotRun(ctx context.Context, autopilotID pgtype.UUID) (AutopilotRun, error) {
- row := q.db.QueryRow(ctx, findActiveAutopilotRun, autopilotID)
- var i AutopilotRun
- err := row.Scan(
- &i.ID,
- &i.AutopilotID,
- &i.TriggerID,
- &i.Source,
- &i.Status,
- &i.IssueID,
- &i.TaskID,
- &i.TriggeredAt,
- &i.CompletedAt,
- &i.FailureReason,
- &i.TriggerPayload,
- &i.Result,
- &i.CreatedAt,
- )
- return i, err
+// Fails active autopilot runs linked to a given issue.
+// Must be called BEFORE issue deletion (ON DELETE SET NULL clears issue_id).
+func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, failAutopilotRunsByIssue, issueID)
+ return err
}
const getAutopilot = `-- name: GetAutopilot :one
-SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
+SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
WHERE id = $1
`
@@ -391,7 +355,6 @@ func (q *Queries) GetAutopilot(ctx context.Context, id pgtype.UUID) (Autopilot,
&i.Status,
&i.ExecutionMode,
&i.IssueTitleTemplate,
- &i.ConcurrencyPolicy,
&i.CreatedByType,
&i.CreatedByID,
&i.LastRunAt,
@@ -402,7 +365,7 @@ func (q *Queries) GetAutopilot(ctx context.Context, id pgtype.UUID) (Autopilot,
}
const getAutopilotInWorkspace = `-- name: GetAutopilotInWorkspace :one
-SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
+SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
WHERE id = $1 AND workspace_id = $2
`
@@ -425,7 +388,6 @@ func (q *Queries) GetAutopilotInWorkspace(ctx context.Context, arg GetAutopilotI
&i.Status,
&i.ExecutionMode,
&i.IssueTitleTemplate,
- &i.ConcurrencyPolicy,
&i.CreatedByType,
&i.CreatedByID,
&i.LastRunAt,
@@ -492,33 +454,6 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI
return i, err
}
-const getAutopilotRunByTask = `-- name: GetAutopilotRunByTask :one
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at FROM autopilot_run
-WHERE task_id = $1
-LIMIT 1
-`
-
-func (q *Queries) GetAutopilotRunByTask(ctx context.Context, taskID pgtype.UUID) (AutopilotRun, error) {
- row := q.db.QueryRow(ctx, getAutopilotRunByTask, taskID)
- var i AutopilotRun
- err := row.Scan(
- &i.ID,
- &i.AutopilotID,
- &i.TriggerID,
- &i.Source,
- &i.Status,
- &i.IssueID,
- &i.TaskID,
- &i.TriggeredAt,
- &i.CompletedAt,
- &i.FailureReason,
- &i.TriggerPayload,
- &i.Result,
- &i.CreatedAt,
- )
- return i, err
-}
-
const getAutopilotTrigger = `-- name: GetAutopilotTrigger :one
SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at FROM autopilot_trigger
WHERE id = $1
@@ -636,7 +571,7 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
const listAutopilots = `-- name: ListAutopilots :many
-SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
+SELECT id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at FROM autopilot
WHERE workspace_id = $1
AND ($2::text IS NULL OR status = $2)
ORDER BY created_at DESC
@@ -670,7 +605,6 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
&i.Status,
&i.ExecutionMode,
&i.IssueTitleTemplate,
- &i.ConcurrencyPolicy,
&i.CreatedByType,
&i.CreatedByID,
&i.LastRunAt,
@@ -687,6 +621,74 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
return items, nil
}
+const recoverLostTriggers = `-- name: RecoverLostTriggers :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, 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'
+`
+
+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"`
+ AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
+}
+
+// =====================
+// Scheduler Recovery
+// =====================
+// 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)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []RecoverLostTriggersRow{}
+ for rows.Next() {
+ var i RecoverLostTriggersRow
+ 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.AutopilotWorkspaceID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const updateAutopilot = `-- name: UpdateAutopilot :one
UPDATE autopilot SET
title = COALESCE($2, title),
@@ -697,10 +699,9 @@ UPDATE autopilot SET
status = COALESCE($7, status),
execution_mode = COALESCE($8, execution_mode),
issue_title_template = $9,
- concurrency_policy = COALESCE($10, concurrency_policy),
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, concurrency_policy, created_by_type, created_by_id, last_run_at, created_at, updated_at
+RETURNING id, workspace_id, project_id, title, description, assignee_id, priority, status, execution_mode, issue_title_template, created_by_type, created_by_id, last_run_at, created_at, updated_at
`
type UpdateAutopilotParams struct {
@@ -713,7 +714,6 @@ type UpdateAutopilotParams struct {
Status pgtype.Text `json:"status"`
ExecutionMode pgtype.Text `json:"execution_mode"`
IssueTitleTemplate pgtype.Text `json:"issue_title_template"`
- ConcurrencyPolicy pgtype.Text `json:"concurrency_policy"`
}
func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams) (Autopilot, error) {
@@ -727,7 +727,6 @@ func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams
arg.Status,
arg.ExecutionMode,
arg.IssueTitleTemplate,
- arg.ConcurrencyPolicy,
)
var i Autopilot
err := row.Scan(
@@ -741,7 +740,6 @@ func (q *Queries) UpdateAutopilot(ctx context.Context, arg UpdateAutopilotParams
&i.Status,
&i.ExecutionMode,
&i.IssueTitleTemplate,
- &i.ConcurrencyPolicy,
&i.CreatedByType,
&i.CreatedByID,
&i.LastRunAt,
@@ -893,39 +891,6 @@ func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutop
return i, err
}
-const updateAutopilotRunSkipped = `-- name: UpdateAutopilotRunSkipped :one
-UPDATE autopilot_run
-SET status = 'skipped', completed_at = now(), failure_reason = $2
-WHERE id = $1
-RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at
-`
-
-type UpdateAutopilotRunSkippedParams struct {
- ID pgtype.UUID `json:"id"`
- FailureReason pgtype.Text `json:"failure_reason"`
-}
-
-func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutopilotRunSkippedParams) (AutopilotRun, error) {
- row := q.db.QueryRow(ctx, updateAutopilotRunSkipped, arg.ID, arg.FailureReason)
- var i AutopilotRun
- err := row.Scan(
- &i.ID,
- &i.AutopilotID,
- &i.TriggerID,
- &i.Source,
- &i.Status,
- &i.IssueID,
- &i.TaskID,
- &i.TriggeredAt,
- &i.CompletedAt,
- &i.FailureReason,
- &i.TriggerPayload,
- &i.Result,
- &i.CreatedAt,
- )
- return i, err
-}
-
const updateAutopilotTrigger = `-- name: UpdateAutopilotTrigger :one
UPDATE autopilot_trigger SET
enabled = COALESCE($2::boolean, enabled),
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index cc297f9ae3..b35dbbe51d 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -108,7 +108,6 @@ type Autopilot struct {
Status string `json:"status"`
ExecutionMode string `json:"execution_mode"`
IssueTitleTemplate pgtype.Text `json:"issue_title_template"`
- ConcurrencyPolicy string `json:"concurrency_policy"`
CreatedByType string `json:"created_by_type"`
CreatedByID pgtype.UUID `json:"created_by_id"`
LastRunAt pgtype.Timestamptz `json:"last_run_at"`
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 338111cf35..057cda6935 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -20,11 +20,11 @@ WHERE id = $1 AND workspace_id = $2;
INSERT INTO autopilot (
workspace_id, project_id, title, description, assignee_id,
priority, status, execution_mode, issue_title_template,
- concurrency_policy, created_by_type, created_by_id
+ created_by_type, created_by_id
) VALUES (
$1, sqlc.narg('project_id'), $2, sqlc.narg('description'), $3,
$4, $5, $6, sqlc.narg('issue_title_template'),
- $7, $8, $9
+ $7, $8
) RETURNING *;
-- name: UpdateAutopilot :one
@@ -37,7 +37,6 @@ UPDATE autopilot SET
status = COALESCE(sqlc.narg('status'), status),
execution_mode = COALESCE(sqlc.narg('execution_mode'), execution_mode),
issue_title_template = sqlc.narg('issue_title_template'),
- concurrency_policy = COALESCE(sqlc.narg('concurrency_policy'), concurrency_policy),
updated_at = now()
WHERE id = $1
RETURNING *;
@@ -125,12 +124,6 @@ SET status = 'running', task_id = $2
WHERE id = $1
RETURNING *;
--- name: UpdateAutopilotRunSkipped :one
-UPDATE autopilot_run
-SET status = 'skipped', completed_at = now(), failure_reason = sqlc.narg('failure_reason')
-WHERE id = $1
-RETURNING *;
-
-- name: UpdateAutopilotRunCompleted :one
UPDATE autopilot_run
SET status = 'completed', completed_at = now(), result = sqlc.narg('result')
@@ -161,25 +154,6 @@ WHERE t.autopilot_id = a.id
AND a.status = 'active'
RETURNING t.*, a.workspace_id AS autopilot_workspace_id;
--- =====================
--- Concurrency Check
--- =====================
-
--- name: FindActiveAutopilotRun :one
--- Returns an active (non-terminal) run for the given autopilot, if any.
-SELECT * FROM autopilot_run
-WHERE autopilot_id = $1
- AND status IN ('pending', 'issue_created', 'running')
-ORDER BY created_at DESC
-LIMIT 1;
-
--- name: CancelActiveAutopilotRuns :exec
--- Used by the 'replace' concurrency policy to cancel existing runs.
-UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = 'replaced by new run'
-WHERE autopilot_id = $1
- AND status IN ('pending', 'issue_created', 'running');
-
-- =====================
-- Task Queue (run_only mode)
-- =====================
@@ -198,7 +172,27 @@ SELECT * FROM autopilot_run
WHERE issue_id = $1 AND status IN ('issue_created', 'running')
LIMIT 1;
--- name: GetAutopilotRunByTask :one
-SELECT * FROM autopilot_run
-WHERE task_id = $1
-LIMIT 1;
+-- name: FailAutopilotRunsByIssue :exec
+-- Fails active autopilot runs linked to a given issue.
+-- Must be called BEFORE issue deletion (ON DELETE SET NULL clears issue_id).
+UPDATE autopilot_run
+SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
+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';