Skip to content

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

Go

refactor(autopilot): autopilot_run.planned_at + DispatchAutopilotForPlan (2/3 MUL-3551) (#4443)

Multica Eveeca610236599
diff --git a/server/cmd/server/autopilot_dispatch_for_plan_test.go b/server/cmd/server/autopilot_dispatch_for_plan_test.go
new file mode 100644
index 0000000000..040b4f7c35
--- /dev/null
+++ b/server/cmd/server/autopilot_dispatch_for_plan_test.go
@@ -0,0 +1,359 @@
+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/service"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestDispatchAutopilotForPlanIsIdempotent locks in the
+// occurrence-level idempotency contract (MUL-3551):
+//
+// - A second DispatchAutopilotForPlan with the same (trigger_id,
+// planned_at) MUST return the SAME run row that the first call
+// created. No second autopilot_run, no second issue / task, no
+// second failure recorded.
+//
+// This is the dispatch-layer half of the two-defence design. The
+// primary defence lives in sys_cron_executions
+// (uq_sys_cron_execution). This one catches the stale-steal case
+// where a runner crashes between "create run" and "write SUCCESS in
+// sys_cron_executions": the next runner re-enters the dispatch and
+// must reuse the in-flight run instead of duplicating it.
+func TestDispatchAutopilotForPlanIsIdempotent(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)
+
+ 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: "Dispatch for plan idempotency",
+ Description: pgtype.Text{String: "Dispatch for plan 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)
+ }
+ t.Cleanup(func() {
+ if _, err := testPool.Exec(context.Background(),
+ `DELETE FROM autopilot WHERE id = $1`, ap.ID); err != nil {
+ t.Logf("cleanup autopilot: %v", err)
+ }
+ })
+
+ trigger, err := queries.CreateAutopilotTrigger(ctx, db.CreateAutopilotTriggerParams{
+ AutopilotID: ap.ID,
+ Kind: "schedule",
+ Enabled: true,
+ CronExpression: pgtype.Text{String: "*/5 * * * *", Valid: true},
+ Timezone: pgtype.Text{String: "UTC", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("CreateAutopilotTrigger: %v", err)
+ }
+
+ // Use a fixed planned_at so the partial unique index has something
+ // concrete to enforce against. Truncate to seconds — the column is
+ // TIMESTAMPTZ and pgx round-trips sub-microsecond, but we want the
+ // comparison to be byte-stable across the two calls.
+ plannedAt := time.Now().UTC().Truncate(time.Second).Add(-30 * time.Second)
+
+ first, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, trigger.ID, "schedule", nil, plannedAt,
+ )
+ if err != nil {
+ t.Fatalf("first DispatchAutopilotForPlan: %v", err)
+ }
+ if first == nil {
+ t.Fatalf("first call returned nil run")
+ }
+ if !first.PlannedAt.Valid {
+ t.Fatalf("first run should have planned_at set")
+ }
+ if !first.PlannedAt.Time.Equal(plannedAt) {
+ t.Fatalf("first run planned_at mismatch: got %s, want %s",
+ first.PlannedAt.Time.Format(time.RFC3339Nano),
+ plannedAt.Format(time.RFC3339Nano))
+ }
+
+ // Second call with the SAME (trigger, planned_at) must reuse the
+ // first run, not create a new one.
+ second, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, trigger.ID, "schedule", nil, plannedAt,
+ )
+ if err != nil {
+ t.Fatalf("second DispatchAutopilotForPlan: %v", err)
+ }
+ if second == nil {
+ t.Fatalf("second call returned nil run")
+ }
+ if second.ID != first.ID {
+ t.Fatalf("second call must reuse first run: first.ID=%s second.ID=%s",
+ util.UUIDToString(first.ID), util.UUIDToString(second.ID))
+ }
+
+ // Belt-and-suspenders: the partial unique index plus the lookup
+ // in DispatchAutopilotForPlan together guarantee exactly one row.
+ var rowCount int
+ if err := testPool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM autopilot_run WHERE autopilot_id = $1`, ap.ID,
+ ).Scan(&rowCount); err != nil {
+ t.Fatalf("count rows: %v", err)
+ }
+ if rowCount != 1 {
+ t.Fatalf("expected exactly 1 autopilot_run for the (trigger, planned_at) pair, got %d", rowCount)
+ }
+
+ // A different planned_at for the same trigger MUST be allowed —
+ // it represents the next scheduled occurrence, not a duplicate.
+ plannedAt2 := plannedAt.Add(5 * time.Minute)
+ third, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, trigger.ID, "schedule", nil, plannedAt2,
+ )
+ if err != nil {
+ t.Fatalf("third DispatchAutopilotForPlan with new planned_at: %v", err)
+ }
+ if third.ID == first.ID {
+ t.Fatalf("different planned_at must produce a different run, got reuse")
+ }
+
+ if err := testPool.QueryRow(ctx,
+ `SELECT COUNT(*) FROM autopilot_run WHERE autopilot_id = $1`, ap.ID,
+ ).Scan(&rowCount); err != nil {
+ t.Fatalf("count rows after 3rd call: %v", err)
+ }
+ if rowCount != 2 {
+ t.Fatalf("expected 2 autopilot_run rows after distinct planned_ats, got %d", rowCount)
+ }
+}
+
+// TestDispatchAutopilotForPlanRejectsZeroArgs locks in the
+// fail-loud contract: a caller that forgets to set trigger_id or
+// planned_at would silently disable the idempotency guard, and the
+// only safe answer is an error.
+func TestDispatchAutopilotForPlanRejectsZeroArgs(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)
+
+ ap := db.Autopilot{
+ ID: parseUUID(testWorkspaceID), // placeholder; will not be loaded since validation fails first
+ WorkspaceID: parseUUID(testWorkspaceID),
+ ExecutionMode: "run_only",
+ AssigneeType: "agent",
+ AssigneeID: parseUUID(testWorkspaceID), // arbitrary; we never get past the input guard
+ Status: "active",
+ }
+
+ t.Run("invalid trigger_id", func(t *testing.T) {
+ _, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, pgtype.UUID{}, "schedule", nil, time.Now().UTC(),
+ )
+ if err == nil {
+ t.Fatalf("expected error for invalid trigger_id")
+ }
+ })
+
+ t.Run("zero planned_at", func(t *testing.T) {
+ _, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, parseUUID(testWorkspaceID), "schedule", nil, time.Time{},
+ )
+ if err == nil {
+ t.Fatalf("expected error for zero planned_at")
+ }
+ })
+}
+
+// TestDispatchAutopilotForPlanRecoversPartialRun is the regression
+// for the #4443 review blocker:
+//
+// "DispatchAutopilotForPlan reuses existing run unconditionally,
+// will mark a half-written run as SUCCESS even when no
+// issue/task was ever created."
+//
+// We seed a partial-state autopilot_run for (trigger, planned_at) —
+// the run exists with a non-terminal status but the corresponding
+// downstream linkage (task_id for run_only, issue_id for create_issue)
+// is NULL. A subsequent DispatchAutopilotForPlan call at the same
+// (trigger, planned_at) MUST NOT return the partial row as-is;
+// instead it must mark the partial row FAILED + clear its planned_at
+// to release the partial-unique slot, then create a fresh dispatched
+// run with the downstream linkage actually populated.
+func TestDispatchAutopilotForPlanRecoversPartialRun(t *testing.T) {
+ for _, mode := range []string{"run_only", "create_issue"} {
+ t.Run(mode, func(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)
+
+ 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: "Partial recovery " + mode,
+ Description: pgtype.Text{String: "partial run recovery test", Valid: true},
+ AssigneeType: "agent",
+ AssigneeID: parseUUID(agentID),
+ Status: "active",
+ ExecutionMode: mode,
+ IssueTitleTemplate: pgtype.Text{String: "Partial recovery", Valid: true},
+ CreatedByType: "member",
+ CreatedByID: parseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("CreateAutopilot: %v", err)
+ }
+ t.Cleanup(func() {
+ if _, err := testPool.Exec(context.Background(),
+ `DELETE FROM autopilot WHERE id = $1`, ap.ID); err != nil {
+ t.Logf("cleanup autopilot: %v", err)
+ }
+ })
+
+ trigger, err := queries.CreateAutopilotTrigger(ctx, db.CreateAutopilotTriggerParams{
+ AutopilotID: ap.ID,
+ Kind: "schedule",
+ Enabled: true,
+ CronExpression: pgtype.Text{String: "*/5 * * * *", Valid: true},
+ Timezone: pgtype.Text{String: "UTC", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("CreateAutopilotTrigger: %v", err)
+ }
+
+ plannedAt := time.Now().UTC().Truncate(time.Second).Add(-2 * time.Minute)
+ plannedTS := pgtype.Timestamptz{Time: plannedAt, Valid: true}
+
+ // Seed a PARTIAL run: a prior attempt wrote the run row
+ // (status reflects the dispatch path's initial state) but
+ // crashed before creating the downstream resource —
+ // task_id is NULL for run_only, issue_id is NULL for
+ // create_issue.
+ initialStatus := "running"
+ if mode == "create_issue" {
+ initialStatus = "issue_created"
+ }
+ partial, err := queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
+ AutopilotID: ap.ID,
+ TriggerID: trigger.ID,
+ Source: "schedule",
+ Status: initialStatus,
+ TriggerPayload: nil,
+ PlannedAt: plannedTS,
+ })
+ if err != nil {
+ t.Fatalf("seed partial run: %v", err)
+ }
+ // Confirm the partial state: no downstream linkage.
+ if partial.TaskID.Valid {
+ t.Fatalf("seed partial run should have task_id=NULL, got %s", util.UUIDToString(partial.TaskID))
+ }
+ if partial.IssueID.Valid {
+ t.Fatalf("seed partial run should have issue_id=NULL, got %s", util.UUIDToString(partial.IssueID))
+ }
+
+ // Retry the dispatch — this is the stale-steal codepath.
+ fresh, err := autopilotSvc.DispatchAutopilotForPlan(
+ ctx, ap, trigger.ID, "schedule", nil, plannedAt,
+ )
+ if err != nil {
+ t.Fatalf("DispatchAutopilotForPlan retry: %v", err)
+ }
+ if fresh == nil {
+ t.Fatalf("retry returned nil run")
+ }
+ if fresh.ID == partial.ID {
+ t.Fatalf("retry must NOT reuse the partial run; got the same id %s", util.UUIDToString(fresh.ID))
+ }
+
+ // The partial row must now be FAILED with planned_at
+ // cleared, so the new row's planned_at is unique.
+ var partialStatus string
+ var partialPlannedAt pgtype.Timestamptz
+ var partialFailureReason pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, planned_at, failure_reason FROM autopilot_run WHERE id = $1`,
+ partial.ID,
+ ).Scan(&partialStatus, &partialPlannedAt, &partialFailureReason); err != nil {
+ t.Fatalf("read partial row after recovery: %v", err)
+ }
+ if partialStatus != "failed" {
+ t.Fatalf("partial run must be marked failed, got %q", partialStatus)
+ }
+ if partialPlannedAt.Valid {
+ t.Fatalf("partial run planned_at must be cleared to release partial-unique slot, still valid")
+ }
+ if !partialFailureReason.Valid || partialFailureReason.String == "" {
+ t.Fatalf("partial run must carry a recovery failure_reason for ops, got empty")
+ }
+
+ // The fresh row must carry the original planned_at and a
+ // real downstream linkage from the just-completed
+ // dispatch.
+ if !fresh.PlannedAt.Valid {
+ t.Fatalf("fresh run planned_at must be set")
+ }
+ if !fresh.PlannedAt.Time.Equal(plannedAt) {
+ t.Fatalf("fresh run planned_at mismatch: got %s want %s",
+ fresh.PlannedAt.Time.Format(time.RFC3339Nano),
+ plannedAt.Format(time.RFC3339Nano))
+ }
+ switch mode {
+ case "run_only":
+ if !fresh.TaskID.Valid {
+ t.Fatalf("run_only retry must produce a run with task_id set")
+ }
+ case "create_issue":
+ if !fresh.IssueID.Valid {
+ t.Fatalf("create_issue retry must produce a run with issue_id set")
+ }
+ }
+
+ // Verify the partial-unique constraint is happy: exactly
+ // one row per (trigger_id, planned_at) where both are
+ // non-NULL.
+ var liveRows int
+ if err := testPool.QueryRow(ctx, `
+ SELECT COUNT(*) FROM autopilot_run
+ WHERE trigger_id = $1 AND planned_at = $2
+ `, trigger.ID, plannedTS).Scan(&liveRows); err != nil {
+ t.Fatalf("count live (trigger, planned) rows: %v", err)
+ }
+ if liveRows != 1 {
+ t.Fatalf("expected exactly 1 live row at (trigger, planned_at) after recovery, got %d", liveRows)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index a1e8c6aa81..4b0ec50b9a 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -62,9 +62,143 @@ func (s *AutopilotService) DispatchAutopilot(
triggerID pgtype.UUID,
source string,
payload []byte,
+) (*db.AutopilotRun, error) {
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{})
+}
+
+// DispatchAutopilotForPlan is the entry point for scheduled triggers that
+// already know the canonical UTC plan_time of the occurrence they are
+// firing. The plan_time is persisted on autopilot_run.planned_at, and the
+// (trigger_id, planned_at) partial unique index — combined with this
+// method's idempotent lookup — guarantees that the SAME planned occurrence
+// cannot produce two SUCCESSFUL runs even if a stale-steal in
+// sys_cron_executions re-enters this method after a prior attempt.
+//
+// Semantics for an already-existing run at (trigger_id, planned_at):
+//
+// - If the existing run is COMPLETE (terminal status, or in-flight
+// with the appropriate downstream linkage — issue_id for
+// create_issue, task_id for run_only), it is returned unchanged.
+// The handler then writes SUCCESS in sys_cron_executions; no
+// duplicate issue/task is produced.
+// - If the existing run is in a PARTIAL state (a prior attempt
+// wrote the run row but crashed before creating its downstream
+// issue/task), it is marked FAILED with a recovery reason and
+// its planned_at is cleared, releasing the partial-unique slot.
+// Dispatch then proceeds normally and creates a fresh run at the
+// same plan_time. Without this branch, a crash-during-dispatch
+// would let a subsequent retry see the in-flight run, return it
+// unchanged, and let the scheduler mark the occurrence SUCCESS
+// without an actual issue/task ever being created (#4443 review).
+//
+// triggerID and plannedAt MUST both be valid; passing zero values
+// would silently disable the idempotency guard. Manual / webhook /
+// api callers should use DispatchAutopilot instead.
+func (s *AutopilotService) DispatchAutopilotForPlan(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ source string,
+ payload []byte,
+ plannedAt time.Time,
+) (*db.AutopilotRun, error) {
+ if !triggerID.Valid {
+ return nil, fmt.Errorf("dispatch for plan: trigger_id is required")
+ }
+ if plannedAt.IsZero() {
+ return nil, fmt.Errorf("dispatch for plan: planned_at is required")
+ }
+ plannedTS := pgtype.Timestamptz{Time: plannedAt.UTC(), Valid: true}
+
+ // Fast path: prior attempt already created a run for this exact
+ // occurrence. The partial unique index uq_autopilot_run_trigger_planned
+ // would also reject a duplicate INSERT, but doing the lookup up
+ // front lets us short-circuit on a complete run and gives us a
+ // chance to recover a partial run before retrying.
+ existing, err := s.Queries.GetAutopilotRunByTriggerAndPlanned(ctx, db.GetAutopilotRunByTriggerAndPlannedParams{
+ TriggerID: triggerID,
+ PlannedAt: plannedTS,
+ })
+ switch {
+ case err == nil && isAutopilotRunComplete(existing):
+ // A prior attempt produced a complete run. Hand it back so the
+ // handler can record SUCCESS in sys_cron_executions without
+ // duplicating any downstream side effect.
+ return &existing, nil
+
+ case err == nil:
+ // Partial-state run from a crashed attempt. Mark it failed
+ // (with a recovery reason) and release its partial-unique
+ // slot so the fresh dispatch below can create a new row.
+ slog.Warn("autopilot dispatch for plan: recovering partial run",
+ "run_id", util.UUIDToString(existing.ID),
+ "trigger_id", util.UUIDToString(triggerID),
+ "planned_at", plannedAt.UTC().Format(time.RFC3339),
+ "status", existing.Status,
+ "issue_set", existing.IssueID.Valid,
+ "task_set", existing.TaskID.Valid,
+ )
+ if err := s.Queries.RecoverPartialAutopilotRun(ctx, existing.ID); err != nil {
+ return nil, fmt.Errorf("dispatch for plan: recover partial run: %w", err)
+ }
+ // Fall through to a fresh dispatch below.
+
+ case !errors.Is(err, pgx.ErrNoRows):
+ return nil, fmt.Errorf("dispatch for plan: lookup existing run: %w", err)
+ }
+
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS)
+}
+
+// isAutopilotRunComplete decides whether an existing autopilot_run row
+// for (trigger_id, planned_at) is safe to reuse on a stale-steal retry.
+//
+// A run is "complete" if either:
+//
+// - It is in a terminal state (completed / failed / skipped). Nothing
+// more to do downstream; the caller can return it as-is.
+//
+// - It is in-flight in a state whose downstream side effect is
+// observable:
+//
+// * issue_created with a valid issue_id — the issue exists and
+// the issue-event listener owns task creation from here.
+//
+// * running with a valid task_id — the task is queued, the
+// listener will close the run when the task terminates.
+//
+// Anything else — most importantly issue_created/running with NULL
+// issue_id/task_id, or the brief 'pending' state — is a partial run:
+// the run row was inserted before the dispatch path could create the
+// downstream resource, and a stale-steal retry MUST NOT treat it as
+// complete (#4443 review).
+func isAutopilotRunComplete(run db.AutopilotRun) bool {
+ switch run.Status {
+ case "completed", "failed", "skipped":
+ return true
+ case "issue_created":
+ return run.IssueID.Valid
+ case "running":
+ return run.TaskID.Valid
+ default:
+ return false
+ }
+}
+
+// dispatchAutopilot is the shared core of the two public Dispatch entry
+// points. plannedAt is the canonical UTC plan_time for scheduled triggers;
+// for manual / webhook / api dispatch it is the zero pgtype.Timestamptz and
+// the resulting autopilot_run row has planned_at IS NULL.
+func (s *AutopilotService) dispatchAutopilot(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ source string,
+ payload []byte,
+ plannedAt pgtype.Timestamptz,
) (*db.AutopilotRun, error) {
if reason, skip := s.shouldSkipDispatch(ctx, autopilot); skip {
- return s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, reason)
+ return s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, reason)
}
// Determine initial status based on execution mode.
@@ -80,6 +214,7 @@ func (s *AutopilotService) DispatchAutopilot(
Status: initialStatus,
TriggerPayload: payload,
SquadID: autopilotSquadAttribution(autopilot),
+ PlannedAt: plannedAt,
})
if err != nil {
return nil, fmt.Errorf("create run: %w", err)
@@ -858,6 +993,7 @@ func (s *AutopilotService) recordSkippedRun(
triggerID pgtype.UUID,
source string,
payload []byte,
+ plannedAt pgtype.Timestamptz,
reason string,
) (*db.AutopilotRun, error) {
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
@@ -867,6 +1003,7 @@ func (s *AutopilotService) recordSkippedRun(
Status: "skipped",
TriggerPayload: payload,
SquadID: autopilotSquadAttribution(autopilot),
+ PlannedAt: plannedAt,
})
if err != nil {
return nil, fmt.Errorf("create skipped run: %w", err)
diff --git a/server/migrations/124_autopilot_run_planned_at.down.sql b/server/migrations/124_autopilot_run_planned_at.down.sql
new file mode 100644
index 0000000000..0cb3d3eb66
--- /dev/null
+++ b/server/migrations/124_autopilot_run_planned_at.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS uq_autopilot_run_trigger_planned;
+
+ALTER TABLE autopilot_run
+ DROP COLUMN IF EXISTS planned_at;
diff --git a/server/migrations/124_autopilot_run_planned_at.up.sql b/server/migrations/124_autopilot_run_planned_at.up.sql
new file mode 100644
index 0000000000..cec1dfc6e1
--- /dev/null
+++ b/server/migrations/124_autopilot_run_planned_at.up.sql
@@ -0,0 +1,36 @@
+-- Adds planned_at + a partial unique constraint on (trigger_id, planned_at) to
+-- autopilot_run. The column anchors each run to the canonical UTC planned fire
+-- time of its triggering occurrence; the unique index is the dispatch-layer
+-- idempotency guard for scheduled triggers.
+--
+-- Why we need it (MUL-3551):
+--
+-- * The primary idempotency for scheduled dispatch lives one layer up, in
+-- `sys_cron_executions` (job_name, scope_kind, scope_id, plan_time). A
+-- successful claim on that table is what gates running the handler.
+-- * BUT: if a runner claims a plan_time, starts dispatch (creating an
+-- autopilot_run row + an issue + an agent_task_queue row), then dies
+-- before writing terminal SUCCESS, the row goes stale → a sibling runner
+-- can steal the lease and re-enter the handler with the SAME plan_time.
+-- Without a row-level guard the second attempt would create a duplicate
+-- autopilot_run / issue / task.
+-- * This index makes that double-create a primary-key conflict, so the
+-- stale-steal path can detect "this plan_time already produced a run"
+-- and reuse it instead of creating a duplicate.
+--
+-- Partial-unique is correct here because:
+--
+-- * Manual triggers and webhook triggers leave planned_at NULL (they have
+-- no canonical fire time). The constraint must not apply to them.
+-- * Pre-existing autopilot_run rows are all (planned_at IS NULL) — no
+-- backfill needed, no migration risk.
+--
+-- The DEFAULT NULL keeps the existing trigger paths (manual / webhook / api
+-- source) untouched; only DispatchAutopilotForPlan writes a non-NULL value.
+
+ALTER TABLE autopilot_run
+ ADD COLUMN planned_at TIMESTAMPTZ;
+
+CREATE UNIQUE INDEX uq_autopilot_run_trigger_planned
+ ON autopilot_run (trigger_id, planned_at)
+ WHERE trigger_id IS NOT NULL AND planned_at IS NOT NULL;
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index d4acf0373d..5ea5d83b9f 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -185,20 +185,21 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
const createAutopilotRun = `-- name: CreateAutopilotRun :one
INSERT INTO autopilot_run (
- autopilot_id, trigger_id, source, status, trigger_payload, squad_id
+ autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at
) VALUES (
$1, $4, $2, $3, $5,
- $6
-) RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id
+ $6, $7
+) RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type CreateAutopilotRunParams struct {
- AutopilotID pgtype.UUID `json:"autopilot_id"`
- Source string `json:"source"`
- Status string `json:"status"`
- TriggerID pgtype.UUID `json:"trigger_id"`
- TriggerPayload []byte `json:"trigger_payload"`
- SquadID pgtype.UUID `json:"squad_id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ Source string `json:"source"`
+ Status string `json:"status"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ TriggerPayload []byte `json:"trigger_payload"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
}
// =====================
@@ -208,6 +209,13 @@ type CreateAutopilotRunParams struct {
// parent autopilot has assignee_type='squad', NULL otherwise. The executing
// agent_id on agent_task_queue still records who actually ran the work
// (the squad leader); squad_id lets reports group by squad without a join.
+//
+// planned_at carries the canonical UTC fire time for scheduled triggers
+// (source='schedule'); it stays NULL for manual / webhook / api sources
+// which have no canonical occurrence. Combined with the partial unique
+// index uq_autopilot_run_trigger_planned, this gives dispatch-layer
+// idempotency: a stale-steal retry at the same plan_time cannot create
+// a second run for the same (trigger_id, planned_at) pair (MUL-3551).
func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunParams) (AutopilotRun, error) {
row := q.db.QueryRow(ctx, createAutopilotRun,
arg.AutopilotID,
@@ -216,6 +224,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
arg.TriggerID,
arg.TriggerPayload,
arg.SquadID,
+ arg.PlannedAt,
)
var i AutopilotRun
err := row.Scan(
@@ -233,6 +242,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -462,7 +472,7 @@ func (q *Queries) GetAutopilotInWorkspace(ctx context.Context, arg GetAutopilotI
}
const getAutopilotRun = `-- name: GetAutopilotRun :one
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id FROM autopilot_run
+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_run
WHERE id = $1
`
@@ -484,13 +494,14 @@ func (q *Queries) GetAutopilotRun(ctx context.Context, id pgtype.UUID) (Autopilo
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
const getAutopilotRunByIssue = `-- name: GetAutopilotRunByIssue :one
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id FROM autopilot_run
+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_run
WHERE issue_id = $1 AND status IN ('issue_created', 'running')
LIMIT 1
`
@@ -516,6 +527,50 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
+ )
+ return i, err
+}
+
+const getAutopilotRunByTriggerAndPlanned = `-- name: GetAutopilotRunByTriggerAndPlanned :one
+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_run
+WHERE trigger_id = $1
+ AND planned_at = $2
+LIMIT 1
+`
+
+type GetAutopilotRunByTriggerAndPlannedParams struct {
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
+}
+
+// Idempotent lookup used by DispatchAutopilotForPlan to detect a
+// crash-during-dispatch retry: if a row already exists for this
+// (trigger_id, planned_at), the caller reuses it instead of creating a
+// duplicate. The partial unique index covers the same key, so a race
+// between "look up then insert" still resolves to a single row — this
+// query is just the fast path that lets us skip the INSERT when we
+// can see the prior row clearly. Returns no rows for the (much more
+// common) first-time dispatch.
+func (q *Queries) GetAutopilotRunByTriggerAndPlanned(ctx context.Context, arg GetAutopilotRunByTriggerAndPlannedParams) (AutopilotRun, error) {
+ row := q.db.QueryRow(ctx, getAutopilotRunByTriggerAndPlanned, arg.TriggerID, arg.PlannedAt)
+ 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,
+ &i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -605,7 +660,7 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgt
}
const listAutopilotRuns = `-- name: ListAutopilotRuns :many
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id FROM autopilot_run
+SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_run
WHERE autopilot_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
@@ -641,6 +696,7 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPa
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
); err != nil {
return nil, err
}
@@ -895,6 +951,30 @@ func (q *Queries) RecoverLostTriggers(ctx context.Context) ([]RecoverLostTrigger
return items, nil
}
+const recoverPartialAutopilotRun = `-- name: RecoverPartialAutopilotRun :exec
+UPDATE autopilot_run
+SET status = 'failed',
+ completed_at = now(),
+ failure_reason = 'recovered partial dispatch (crashed before downstream creation)',
+ planned_at = NULL
+WHERE id = $1
+`
+
+// Recovers a partial-state autopilot_run from a crashed first attempt
+// (the runner wrote the run row but died before creating the downstream
+// issue/task) so that a subsequent DispatchAutopilotForPlan call can
+// create a fresh run at the same (trigger_id, planned_at).
+//
+// Setting planned_at = NULL clears the partial-unique slot held by
+// uq_autopilot_run_trigger_planned, letting the new INSERT proceed.
+// The row stays in autopilot_run as a FAILED record (with a recovery
+// reason) so ops still see the abandoned attempt in the run history —
+// it is not silently deleted.
+func (q *Queries) RecoverPartialAutopilotRun(ctx context.Context, id pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, recoverPartialAutopilotRun, id)
+ return err
+}
+
const rotateAutopilotTriggerWebhookToken = `-- name: RotateAutopilotTriggerWebhookToken :one
UPDATE autopilot_trigger
SET webhook_token = $2,
@@ -1224,7 +1304,7 @@ const updateAutopilotRunCompleted = `-- name: UpdateAutopilotRunCompleted :one
UPDATE autopilot_run
SET status = 'completed', completed_at = now(), result = $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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunCompletedParams struct {
@@ -1250,6 +1330,7 @@ func (q *Queries) UpdateAutopilotRunCompleted(ctx context.Context, arg UpdateAut
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -1258,7 +1339,7 @@ const updateAutopilotRunFailed = `-- name: UpdateAutopilotRunFailed :one
UPDATE autopilot_run
SET status = 'failed', 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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunFailedParams struct {
@@ -1284,6 +1365,7 @@ func (q *Queries) UpdateAutopilotRunFailed(ctx context.Context, arg UpdateAutopi
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -1292,7 +1374,7 @@ const updateAutopilotRunIssueCreated = `-- name: UpdateAutopilotRunIssueCreated
UPDATE autopilot_run
SET status = 'issue_created', issue_id = $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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunIssueCreatedParams struct {
@@ -1318,6 +1400,7 @@ func (q *Queries) UpdateAutopilotRunIssueCreated(ctx context.Context, arg Update
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -1326,7 +1409,7 @@ const updateAutopilotRunRunning = `-- name: UpdateAutopilotRunRunning :one
UPDATE autopilot_run
SET status = 'running', task_id = $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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunRunningParams struct {
@@ -1352,6 +1435,7 @@ func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutop
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -1360,7 +1444,7 @@ 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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunSkippedParams struct {
@@ -1392,6 +1476,7 @@ func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutop
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
@@ -1403,7 +1488,7 @@ SET status = 'skipped',
failure_reason = $2,
result = $3
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, squad_id
+RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
`
type UpdateAutopilotRunSkippedWithResultParams struct {
@@ -1430,6 +1515,7 @@ func (q *Queries) UpdateAutopilotRunSkippedWithResult(ctx context.Context, arg U
&i.Result,
&i.CreatedAt,
&i.SquadID,
+ &i.PlannedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a49acd4703..39534c5be9 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -152,6 +152,7 @@ type AutopilotRun struct {
Result []byte `json:"result"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
SquadID pgtype.UUID `json:"squad_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
}
type AutopilotSubscriber struct {
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index ced68b1d03..4d5b4dbbb1 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -186,13 +186,52 @@ RETURNING *;
-- parent autopilot has assignee_type='squad', NULL otherwise. The executing
-- agent_id on agent_task_queue still records who actually ran the work
-- (the squad leader); squad_id lets reports group by squad without a join.
+--
+-- planned_at carries the canonical UTC fire time for scheduled triggers
+-- (source='schedule'); it stays NULL for manual / webhook / api sources
+-- which have no canonical occurrence. Combined with the partial unique
+-- index uq_autopilot_run_trigger_planned, this gives dispatch-layer
+-- idempotency: a stale-steal retry at the same plan_time cannot create
+-- a second run for the same (trigger_id, planned_at) pair (MUL-3551).
INSERT INTO autopilot_run (
- autopilot_id, trigger_id, source, status, trigger_payload, squad_id
+ autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at
) VALUES (
$1, sqlc.narg('trigger_id'), $2, $3, sqlc.narg('trigger_payload'),
- sqlc.narg('squad_id')
+ sqlc.narg('squad_id'), sqlc.narg('planned_at')
) RETURNING *;
+-- name: GetAutopilotRunByTriggerAndPlanned :one
+-- Idempotent lookup used by DispatchAutopilotForPlan to detect a
+-- crash-during-dispatch retry: if a row already exists for this
+-- (trigger_id, planned_at), the caller reuses it instead of creating a
+-- duplicate. The partial unique index covers the same key, so a race
+-- between "look up then insert" still resolves to a single row — this
+-- query is just the fast path that lets us skip the INSERT when we
+-- can see the prior row clearly. Returns no rows for the (much more
+-- common) first-time dispatch.
+SELECT * FROM autopilot_run
+WHERE trigger_id = $1
+ AND planned_at = $2
+LIMIT 1;
+
+-- name: RecoverPartialAutopilotRun :exec
+-- Recovers a partial-state autopilot_run from a crashed first attempt
+-- (the runner wrote the run row but died before creating the downstream
+-- issue/task) so that a subsequent DispatchAutopilotForPlan call can
+-- create a fresh run at the same (trigger_id, planned_at).
+--
+-- Setting planned_at = NULL clears the partial-unique slot held by
+-- uq_autopilot_run_trigger_planned, letting the new INSERT proceed.
+-- The row stays in autopilot_run as a FAILED record (with a recovery
+-- reason) so ops still see the abandoned attempt in the run history —
+-- it is not silently deleted.
+UPDATE autopilot_run
+SET status = 'failed',
+ completed_at = now(),
+ failure_reason = 'recovered partial dispatch (crashed before downstream creation)',
+ planned_at = NULL
+WHERE id = $1;
+
-- name: GetAutopilotRun :one
SELECT * FROM autopilot_run
WHERE id = $1;