Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilots): don't meter Run now started by a member (MUL-9486) (#10876)
Multica Evedbb29028274f
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 854796c17b..0c68b3cc0a 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -137,7 +137,8 @@"resets_at": "Resets {{date}}","usage_unavailable": "Usage is temporarily unavailable","members": "Members",- "members_pending": "Pending invitations: {{pending}}"+ "members_pending": "Pending invitations: {{pending}}",+ "metering": "Runs from schedules, webhooks, and agents count. Runs a member starts with Run now don't."},"seats": {"title": "Seats",diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 9cee88e23b..febf6dfd24 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -137,7 +137,8 @@"resets_at": "Se reinicia el {{date}}","usage_unavailable": "El uso no está disponible temporalmente","members": "Miembros",- "members_pending": "Invitaciones pendientes: {{pending}}"+ "members_pending": "Invitaciones pendientes: {{pending}}",+ "metering": "Cuentan las ejecuciones de programaciones, webhooks y agentes. Las que un miembro inicia con Ejecutar ahora no cuentan."},"seats": {"title": "Puestos",diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex 82dab2cabf..7fc571285d 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -137,7 +137,8 @@"resets_at": "Réinitialisation {{date}}","usage_unavailable": "La consommation est temporairement indisponible","members": "Membres",- "members_pending": "Invitations en attente : {{pending}}"+ "members_pending": "Invitations en attente : {{pending}}",+ "metering": "Les exécutions lancées par une planification, un webhook ou un agent sont comptées. Celles qu'un membre lance avec Exécuter maintenant ne le sont pas."},"seats": {"title": "Sièges",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex e50e0007ff..390789baca 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -136,7 +136,8 @@"resets_at": "{{date}} にリセット","usage_unavailable": "使用量は一時的に利用できません","members": "メンバー",- "members_pending": "保留中の招待:{{pending}} 件"+ "members_pending": "保留中の招待:{{pending}} 件",+ "metering": "スケジュール、Webhook、エージェントによる実行はカウントされます。メンバーが「今すぐ実行」で開始した実行はカウントされません。"},"seats": {"title": "席数",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 4d15fbbd25..9ce5e39c6a 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -136,7 +136,8 @@"resets_at": "{{date}}에 초기화","usage_unavailable": "사용량을 일시적으로 불러올 수 없습니다","members": "멤버",- "members_pending": "대기 중인 초대: {{pending}}건"+ "members_pending": "대기 중인 초대: {{pending}}건",+ "metering": "일정, Webhook, 에이전트로 시작된 실행은 집계됩니다. 멤버가 지금 실행으로 시작한 실행은 집계되지 않습니다."},"seats": {"title": "좌석",diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex 7b4dc9be93..44bde6c878 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -139,7 +139,8 @@"resets_at": "Сброс {{date}}","usage_unavailable": "Данные об использовании временно недоступны","members": "Участники",- "members_pending": "Ожидающие приглашения: {{pending}}"+ "members_pending": "Ожидающие приглашения: {{pending}}",+ "metering": "Учитываются запуски по расписанию, через вебхук и агентами. Запуски, которые участник начинает кнопкой «Запустить сейчас», не учитываются."},"seats": {"title": "Места",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex a627c25c24..b723e9dd5d 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -136,7 +136,8 @@"resets_at": "{{date}} 重置","usage_unavailable": "用量暂时不可用","members": "成员",- "members_pending": "待接受的邀请:{{pending}}"+ "members_pending": "待接受的邀请:{{pending}}",+ "metering": "时间表、Webhook 和智能体发起的运行计入额度,成员点击\"立即运行\"不计入。"},"seats": {"title": "席位",diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex 426d044186..e76dea0d30 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -136,7 +136,8 @@"resets_at": "{{date}} 重置","usage_unavailable": "用量暫時不可用","members": "成員",- "members_pending": "待接受的邀請:{{pending}}"+ "members_pending": "待接受的邀請:{{pending}}",+ "metering": "時間表、Webhook 和 AI 代理發起的執行計入額度,成員點擊\"立即執行\"不計入。"},"seats": {"title": "席位",diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex 7f476de1ec..8ee9072381 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -99,17 +99,41 @@ describe("resolveAutopilotUsage", () => {false,),).toEqual({ kind: "unavailable" });+ });++ it("shows observed usage without ever reading the limit as reached", () => {expect(resolveAutopilotUsage(freeEntitlements,{...quotaUsage,action: "observe",- total: quotaUsage.limit,+ used: 9,+ reserved: 0,+ total: 9,reached: null,},false,),+ ).toEqual({+ kind: "metered",+ used: 9,+ reserved: 0,+ total: 9,+ limit: 7,+ progress: 100,+ reached: false,+ resetAt: "2030-02-01T00:00:00Z",+ });+ });++ it("treats an enforced usage without a reached decision as unavailable", () => {+ expect(+ resolveAutopilotUsage(+ freeEntitlements,+ { ...quotaUsage, reached: null },+ false,+ ),).toEqual({ kind: "unavailable" });});diff --git a/packages/views/settings/components/billing-state.ts b/packages/views/settings/components/billing-state.tsindex 890872d5cf..a40c4f7baf 100644--- a/packages/views/settings/components/billing-state.ts+++ b/packages/views/settings/components/billing-state.ts@@ -24,7 +24,8 @@ export type AutopilotUsageView =* Quota admission counts completed and reserved runs. Keep reserved work* visible so the progress bar matches the server's blocking decision for a* limited workspace. Limit mode and the reached decision are server facts;- * this helper only prepares presentation values.+ * this helper only prepares presentation values. Observe never blocks a run,+ * so the server sends no reached decision and the limit never reads as hit.*/export function resolveAutopilotUsage(entitlements: WorkspaceSubscriptionEntitlements,@@ -36,7 +37,8 @@ export function resolveAutopilotUsage(}if (!failed && usage !== undefined && usage.action !== "off") {- const { used, reserved, total, limit, reached, reset_at: resetAt } = usage;+ const { used, reserved, total, limit, reset_at: resetAt } = usage;+ const reached = usage.action === "observe" ? false : usage.reached;if (used !== null &&reserved !== null &&diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex a152802644..de0ae5bb4c 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -1049,6 +1049,7 @@ describe("BillingTab", () => {expect(screen.getByText("Pro is active")).toBeInTheDocument();expect(screen.getByText("Unlimited")).toBeInTheDocument();expect(screen.queryByText("5 / 7")).not.toBeInTheDocument();+ expect(screen.queryByText(/Runs a member starts with Run now/)).not.toBeInTheDocument();} finally {vi.useRealTimers();}@@ -1592,6 +1593,31 @@ describe("BillingTab", () => {expect(screen.getByText("Limit reached")).toBeInTheDocument();expect(screen.getByText("7 / 7")).toBeInTheDocument();expect(screen.getByText("5 completed · 2 in progress")).toBeInTheDocument();+ expect(+ screen.getByText(+ "Runs from schedules, webhooks, and agents count. Runs a member starts with Run now don't.",+ ),+ ).toBeInTheDocument();+ });++ it("shows observed usage over the limit without reporting it reached", () => {+ Object.assign(mocks.usage, {+ action: "observe",+ used: 9,+ reserved: 0,+ total: 9,+ limit: 7,+ reached: null,+ });++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("9 / 7")).toBeInTheDocument();+ expect(screen.getByText("Current usage")).toBeInTheDocument();+ expect(screen.queryByText("Limit reached")).not.toBeInTheDocument();+ expect(+ screen.queryByText("Usage is temporarily unavailable"),+ ).not.toBeInTheDocument();});it("does not render missing limited usage as zero or unlimited", async () => {diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 65823ff595..8bd6337ba7 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -1886,6 +1886,11 @@ function BillingTabContent() {<SettingsCard><SettingsRowlabel={t(($) => $.workspace.limits.autopilots)}+ description={+ quotaUsage.kind === "unlimited"+ ? undefined+ : t(($) => $.workspace.limits.metering)+ }>{quotaUsage.kind === "unlimited" ? (<span className="tabular-nums">diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex defa69583e..e05f835436 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -153,6 +153,7 @@ var concurrentIndexCleanups = map[string]string{"693_doc_workspace_idx": "doc_workspace_idx","694_doc_version_workspace_idx": "doc_version_workspace_idx","696_inbox_item_active_shown_idx": "idx_inbox_active_shown",+ "698_autopilot_run_idempotency_key_idx": "uq_autopilot_run_idempotency_key","671_weixin_account_state_unique_index": "weixin_account_state_pkey","669_weixin_login_session_unique_index": "weixin_login_session_pkey","666_weixin_login_expiry_idx": "weixin_login_expiry_idx",diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 39d8489d55..0b6ffe284a 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -2445,7 +2445,11 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {if idempotencyKey == "" {idempotencyKey = service.NewRequestIdempotencyKey()}- run, reasonCode, err := h.AutopilotService.DispatchAutopilotManualWithKey(r.Context(), autopilot, pgtype.UUID{}, nil, invokerUserID, idempotencyKey)+ startedBy := service.ManualRunStartedByMember+ if actorType, _ := h.resolveActor(r, requestUserID(r), workspaceID); actorType == "agent" {+ startedBy = service.ManualRunStartedByAgent+ }+ run, reasonCode, err := h.AutopilotService.DispatchAutopilotManualWithKey(r.Context(), autopilot, pgtype.UUID{}, nil, invokerUserID, idempotencyKey, startedBy)if err != nil {var quotaErr *service.AutopilotQuotaExceededErrorif errors.As(err, "aErr) {diff --git a/server/internal/handler/autopilot_quota_handler_test.go b/server/internal/handler/autopilot_quota_handler_test.goindex 1dfac24184..f54e3bf0c1 100644--- a/server/internal/handler/autopilot_quota_handler_test.go+++ b/server/internal/handler/autopilot_quota_handler_test.go@@ -9,10 +9,15 @@ import ("time""github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/testutil")+// A member pressing "Run now" is a run a person started, which is never+// metered. The same press made by an agent on a member's behalf, and every+// webhook delivery, count and are refused once the period is full.func TestAutopilotQuotaManualAndWebhookEnforcement(t *testing.T) {workspaceUUID := uuid.MustParse(testWorkspaceID)start := time.Now().UTC().Truncate(time.Second)@@ -36,21 +41,50 @@ func TestAutopilotQuotaManualAndWebhookEnforcement(t *testing.T) {agentID := createWebhookTestAgent(t, "Quota Handler Agent")autopilotID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE autopilot_run_id IN (SELECT id FROM autopilot_run WHERE autopilot_id = $1)`, autopilotID)+ dbfx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, autopilotID)- manual := httptest.NewRecorder()- manualReq := newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil)- manualReq.Header.Set("Idempotency-Key", "manual-over-limit")- manualReq = withURLParam(manualReq, "id", autopilotID)- testHandler.TriggerAutopilot(manual, manualReq)- if manual.Code != http.StatusTooManyRequests {- t.Fatalf("manual status = %d body=%s, want 429", manual.Code, manual.Body.String())+ memberReq := newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil)+ memberReq.Header.Set("Idempotency-Key", "member-over-limit")+ memberReq = withURLParam(memberReq, "id", autopilotID)+ var memberRun AutopilotRunResponse+ testutil.Call(t, testHandler.TriggerAutopilot, memberReq).Want(http.StatusOK).JSON(&memberRun)+ if memberRun.Status == "skipped" {+ t.Fatalf("member run now was skipped (reason_code %v), want it admitted past a full quota", derefStr(memberRun.ReasonCode))}- if manual.Header().Get("Retry-After") == "" {- t.Fatal("manual quota refusal must include Retry-After")+ var reservationID pgtype.UUID+ if err := testPool.QueryRow(context.Background(), `SELECT quota_reservation_id FROM autopilot_run WHERE id = $1`, memberRun.ID).Scan(&reservationID); err != nil {+ t.Fatalf("load member run: %v", err)}- var manualBody map[string]any- if err := json.Unmarshal(manual.Body.Bytes(), &manualBody); err != nil || manualBody["reason_code"] != "quota_exceeded" {- t.Fatalf("manual body = %#v, err=%v", manualBody, err)+ if reservationID.Valid {+ t.Fatal("member run now reserved quota, want an unmetered run")+ }+ // Retrying the same request reuses the run instead of executing twice.+ retryReq := newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil)+ retryReq.Header.Set("Idempotency-Key", "member-over-limit")+ retryReq = withURLParam(retryReq, "id", autopilotID)+ var retriedRun AutopilotRunResponse+ testutil.Call(t, testHandler.TriggerAutopilot, retryReq).Want(http.StatusOK).JSON(&retriedRun)+ if retriedRun.ID != memberRun.ID {+ t.Fatalf("retried run now = %s, want the original run %s", retriedRun.ID, memberRun.ID)+ }+ var taskCount int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE autopilot_run_id = $1`, memberRun.ID).Scan(&taskCount); err != nil {+ t.Fatalf("count member run tasks: %v", err)+ }+ if taskCount != 1 {+ t.Fatalf("member run has %d tasks after a retry, want 1", taskCount)+ }++ agentResp := triggerAsAgent(t, autopilotID, agentID, callerTask(t, agentID, testUserID))+ agentResp.Want(http.StatusTooManyRequests)+ if agentResp.Header().Get("Retry-After") == "" {+ t.Fatal("agent quota refusal must include Retry-After")+ }+ var agentBody map[string]any+ agentResp.JSON(&agentBody)+ if agentBody["reason_code"] != "quota_exceeded" {+ t.Fatalf("agent body = %#v, want quota_exceeded", agentBody)}trigger := createWebhookTriggerViaHandler(t, autopilotID)@@ -67,8 +101,8 @@ func TestAutopilotQuotaManualAndWebhookEnforcement(t *testing.T) {if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM autopilot_run WHERE autopilot_id = $1`, autopilotID).Scan(&runCount); err != nil {t.Fatalf("count runs: %v", err)}- if runCount != 0 {- t.Fatalf("blocked manual/webhook requests created %d runs, want zero", runCount)+ if runCount != 1 {+ t.Fatalf("autopilot has %d runs, want only the member's unmetered run", runCount)}usageRecorder := httptest.NewRecorder()@@ -82,6 +116,107 @@ func TestAutopilotQuotaManualAndWebhookEnforcement(t *testing.T) {t.Fatalf("decode usage response: %v", err)}if usage.BlockedCounts["manual"] != 1 || usage.BlockedCounts["webhook"] != 1 {- t.Fatalf("blocked counts = %#v, want one manual and one webhook", usage.BlockedCounts)+ t.Fatalf("blocked counts = %#v, want the agent's manual run and one webhook", usage.BlockedCounts)+ }+ if usage.Used == nil || usage.Reserved == nil || *usage.Used != 0 || *usage.Reserved != 0 {+ t.Fatalf("usage used=%v reserved=%v, want nothing counted", usage.Used, usage.Reserved)+ }+}++// A request key is one request whichever path admitted it. Before member presses+// were unmetered, every "Run now" went through the metered path and kept its key+// only on the quota reservation, so a retry that reaches an upgraded server must+// still find it. The reverse holds too: an agent retry of a key a member's+// unmetered run already used must not start a second run.+func TestAutopilotQuotaRequestKeySharedAcrossMeteredAndUnmeteredRuns(t *testing.T) {+ for _, action := range []entitlement.Action{entitlement.ActionObserve, entitlement.ActionEnforce} {+ t.Run(string(action), func(t *testing.T) {+ workspaceUUID := uuid.MustParse(testWorkspaceID)+ start := time.Now().UTC().Truncate(time.Second)+ end := start.Add(17 * time.Hour)+ limit := 5+ stub := entitlementtest.New()+ stub.Set(workspaceUUID, entitlement.GateAutopilotRuns, entitlement.Decision{+ Gate: entitlement.Gate{+ Action: action, Limit: &limit,+ PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,+ },+ PolicyRevision: 3, SubscriptionVersion: 5,+ })+ priorProvider := testHandler.AutopilotService.Entitlements+ testHandler.AutopilotService.Entitlements = stub+ t.Cleanup(func() {+ testHandler.AutopilotService.Entitlements = priorProvider+ testPool.Exec(context.Background(), `DELETE FROM autopilot_quota_reservation WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, testWorkspaceID)+ })++ agentID := createWebhookTestAgent(t, "Quota Key Agent "+string(action))+ autopilotID := createWebhookTestAutopilot(t, agentID, "active", "run_only")+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE autopilot_run_id IN (SELECT id FROM autopilot_run WHERE autopilot_id = $1)`, autopilotID)+ dbfx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, autopilotID)+ taskID := callerTask(t, agentID, testUserID)++ asMember := func(key string) AutopilotRunResponse {+ t.Helper()+ r := newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil)+ r.Header.Set("Idempotency-Key", key)+ r = withURLParam(r, "id", autopilotID)+ var run AutopilotRunResponse+ testutil.Call(t, testHandler.TriggerAutopilot, r).Want(http.StatusOK).JSON(&run)+ return run+ }+ asAgent := func(key string) AutopilotRunResponse {+ t.Helper()+ r := newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger?workspace_id="+testWorkspaceID, nil)+ r.Header.Set("Idempotency-Key", key)+ r.Header.Set("X-Actor-Source", "task_token")+ r.Header.Set("X-Agent-ID", agentID)+ r.Header.Set("X-Task-ID", taskID)+ r = withURLParam(r, "id", autopilotID)+ var run AutopilotRunResponse+ testutil.Call(t, testHandler.TriggerAutopilot, r).Want(http.StatusOK).JSON(&run)+ return run+ }+ tasksFor := func(runID string) int {+ t.Helper()+ var n int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE autopilot_run_id = $1`, runID).Scan(&n); err != nil {+ t.Fatalf("count tasks: %v", err)+ }+ return n+ }++ metered := asAgent("metered-first")+ if retried := asMember("metered-first"); retried.ID != metered.ID {+ t.Fatalf("member retry of a metered request = run %s, want the original run %s", retried.ID, metered.ID)+ }+ if n := tasksFor(metered.ID); n != 1 {+ t.Fatalf("metered request has %d tasks after a member retry, want 1", n)+ }++ unmetered := asMember("unmetered-first")+ if retried := asAgent("unmetered-first"); retried.ID != unmetered.ID {+ t.Fatalf("agent retry of an unmetered request = run %s, want the original run %s", retried.ID, unmetered.ID)+ }+ if n := tasksFor(unmetered.ID); n != 1 {+ t.Fatalf("unmetered request has %d tasks after an agent retry, want 1", n)+ }++ var runs int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM autopilot_run WHERE autopilot_id = $1`, autopilotID).Scan(&runs); err != nil {+ t.Fatalf("count runs: %v", err)+ }+ if runs != 2 {+ t.Fatalf("autopilot has %d runs, want 2", runs)+ }+ var reserved int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM autopilot_quota_reservation WHERE workspace_id = $1 AND state <> 'released'`, testWorkspaceID).Scan(&reserved); err != nil {+ t.Fatalf("count reservations: %v", err)+ }+ if reserved != 1 {+ t.Fatalf("workspace holds %d reservations, want only the agent's metered run", reserved)+ }+ })}}diff --git a/server/internal/handler/autopilot_trigger_error_test.go b/server/internal/handler/autopilot_trigger_error_test.goindex bf693c100e..6db2f5f620 100644--- a/server/internal/handler/autopilot_trigger_error_test.go+++ b/server/internal/handler/autopilot_trigger_error_test.go@@ -65,9 +65,14 @@ func TestTriggerAutopilot_InternalFailureDoesNotEchoError(t *testing.T) {"state": "consumed",})+ // Only a metered run reaches the quota tables, so the press comes from an+ // agent acting for testUserID; a member's own press is never metered.req := testutil.WithHeaders(newRequest("POST", "/api/autopilots/"+autopilotID+"/trigger", nil),"Idempotency-Key", idempotencyKey,+ "X-Actor-Source", "task_token",+ "X-Agent-ID", agentID,+ "X-Task-ID", callerTask(t, agentID, testUserID),)res := testutil.Call(t, testHandler.TriggerAutopilot, withURLParam(req, "id", autopilotID)).Want(http.StatusInternalServerError)diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex eb22da7b79..2057a9db70 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -134,7 +134,7 @@ func (s *AutopilotService) DispatchAutopilot(// dropped.// webhookDeliveryID is invalid here — durable webhook deliveries admit through// AdmitAutopilotWebhookDelivery instead of this entry point.- run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{}, pgtype.UUID{}, source+":"+newAutopilotIdempotencyKey())+ run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{}, pgtype.UUID{}, source+":"+newAutopilotIdempotencyKey(), meteredRun)return run, err}@@ -159,11 +159,23 @@ func (s *AutopilotService) DispatchAutopilotManual(payload []byte,actorUserID pgtype.UUID,) (*db.AutopilotRun, dispatch.ReasonCode, error) {- return s.DispatchAutopilotManualWithKey(ctx, autopilot, triggerID, payload, actorUserID, newAutopilotIdempotencyKey())+ return s.DispatchAutopilotManualWithKey(ctx, autopilot, triggerID, payload, actorUserID, newAutopilotIdempotencyKey(), ManualRunStartedByMember)}+// ManualRunStarter is who pressed "run now". A run a member starts directly is+// not metered against the workspace's autopilot run quota. A run an agent starts+// on a member's behalf is metered, because an agent can repeat the call with+// nobody watching.+type ManualRunStarter int++const (+ ManualRunStartedByMember ManualRunStarter = iota+ ManualRunStartedByAgent+)+// DispatchAutopilotManualWithKey preserves a caller-supplied request key so-// retrying the same HTTP request cannot reserve or execute twice.+// retrying the same HTTP request cannot reserve or execute twice, whether or not+// the run is metered.func (s *AutopilotService) DispatchAutopilotManualWithKey(ctx context.Context,autopilot db.Autopilot,@@ -171,12 +183,17 @@ func (s *AutopilotService) DispatchAutopilotManualWithKey(payload []byte,actorUserID pgtype.UUID,idempotencyKey string,+ startedBy ManualRunStarter,) (*db.AutopilotRun, dispatch.ReasonCode, error) {// The manual path is the one surface that shows a per-run outcome to a human,// so it returns the typed reason code decided at the admission source. No// webhook delivery on the manual path.key := "manual:" + util.UUIDToString(autopilot.ID) + ":" + idempotencyKey- return s.dispatchAutopilot(ctx, autopilot, triggerID, "manual", payload, pgtype.Timestamptz{}, pgtype.UUID{}, actorUserID, key)+ metering := meteredRun+ if startedBy == ManualRunStartedByMember {+ metering = unmeteredRun+ }+ return s.dispatchAutopilot(ctx, autopilot, triggerID, "manual", payload, pgtype.Timestamptz{}, pgtype.UUID{}, actorUserID, key, metering)}// AdmitAutopilotWebhookDelivery creates or reuses the idempotent run for a@@ -535,7 +552,7 @@ func (s *AutopilotService) DispatchAutopilotForPlan(// principal (trigger_owner, MUL-6951), and has no human surface for a per-run reason// code, so it is dropped. No webhook delivery on the scheduled-plan path.key := "schedule:" + util.UUIDToString(triggerID) + ":" + plannedAt.UTC().Format(time.RFC3339Nano)- run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{}, pgtype.UUID{}, key)+ run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{}, pgtype.UUID{}, key, meteredRun)return run, err}@@ -589,6 +606,7 @@ func (s *AutopilotService) dispatchAutopilot(webhookDeliveryID pgtype.UUID,actorUserID pgtype.UUID,idempotencyKey string,+ metering autopilotRunMetering,) (*db.AutopilotRun, dispatch.ReasonCode, error) {if reason, code, skip := s.shouldSkipDispatch(ctx, autopilot, actorUserID, triggerID); skip {run, err := s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)@@ -601,7 +619,11 @@ func (s *AutopilotService) dispatchAutopilot(initialStatus = "running"}- run, reused, err := s.createAutopilotRunWithQuota(ctx, autopilot.WorkspaceID, source, idempotencyKey, db.CreateAutopilotRunParams{+ createRun := s.createAutopilotRunWithQuota+ if metering == unmeteredRun {+ createRun = s.createUnmeteredAutopilotRun+ }+ run, reused, err := createRun(ctx, autopilot.WorkspaceID, source, idempotencyKey, db.CreateAutopilotRunParams{ID: dbid.NewV7(),AutopilotID: autopilot.ID,TriggerID: triggerID,diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.goindex 36d08e5c63..68be1c9a71 100644--- a/server/internal/service/autopilot_quota.go+++ b/server/internal/service/autopilot_quota.go@@ -9,6 +9,7 @@ import ("github.com/google/uuid""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/entitlement"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -105,6 +106,107 @@ func (s *AutopilotService) quotaPolicy(ctx context.Context, workspaceID pgtype.U}, true}+// autopilotRunMetering says whether a run counts toward the workspace's+// autopilot run quota. Runs a person starts are not metered.+type autopilotRunMetering bool++const (+ meteredRun autopilotRunMetering = true+ unmeteredRun autopilotRunMetering = false+)++// createUnmeteredAutopilotRun inserts a run that never counts toward the quota,+// whatever the policy, and never writes the quota tables. Request dedupe stays:+// the idempotency key is stored on the run, so a retried request reuses its run+// instead of executing twice. A key the metered path already admitted, such as+// one a server from before unmetered runs reserved, lives only on its quota+// reservation, so that is checked too. It shares createAutopilotRunWithQuota's+// signature so dispatch can pick either one.+func (s *AutopilotService) createUnmeteredAutopilotRun(+ ctx context.Context,+ workspaceID pgtype.UUID,+ source, idempotencyKey string,+ params db.CreateAutopilotRunParams,+) (db.AutopilotRun, bool, error) {+ if !validAutopilotExecutionSource(source) {+ return db.AutopilotRun{}, false, fmt.Errorf("invalid autopilot execution source %q", source)+ }+ key := db.GetAutopilotRunByIdempotencyKeyParams{+ AutopilotID: params.AutopilotID,+ IdempotencyKey: pgtype.Text{String: idempotencyKey, Valid: idempotencyKey != ""},+ }+ policy, quotaEnabled := s.quotaPolicy(ctx, workspaceID)+ if key.IdempotencyKey.Valid {+ existing, err := s.Queries.GetAutopilotRunByIdempotencyKey(ctx, key)+ if err == nil {+ return existing, true, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return db.AutopilotRun{}, false, fmt.Errorf("lookup idempotent run: %w", err)+ }+ if quotaEnabled {+ existing, found, err := s.meteredRunForRequestKey(ctx, workspaceID, policy, idempotencyKey)+ if err != nil {+ return db.AutopilotRun{}, false, err+ }+ if found {+ s.recordAutopilotQuotaDecision(policy.action, source, "reused")+ return existing, true, nil+ }+ }+ }+ params.IdempotencyKey = key.IdempotencyKey+ run, err := s.Queries.CreateAutopilotRun(ctx, params)+ var pgErr *pgconn.PgError+ if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "uq_autopilot_run_idempotency_key" {+ // A concurrent request with the same key inserted first.+ existing, lookupErr := s.Queries.GetAutopilotRunByIdempotencyKey(ctx, key)+ if lookupErr != nil {+ return db.AutopilotRun{}, false, fmt.Errorf("load concurrent idempotent run: %w", lookupErr)+ }+ return existing, true, nil+ }+ if err != nil {+ return db.AutopilotRun{}, false, err+ }+ if quotaEnabled {+ s.recordAutopilotQuotaDecision(policy.action, source, "unmetered")+ }+ return run, false, nil+}++// meteredRunForRequestKey finds the run the metered path admitted for a request+// key in the current quota period. Like that path's own retry lookup, it ignores+// released reservations and reads without taking the period lock.+func (s *AutopilotService) meteredRunForRequestKey(+ ctx context.Context,+ workspaceID pgtype.UUID,+ policy autopilotQuotaPolicy,+ idempotencyKey string,+) (db.AutopilotRun, bool, error) {+ reservation, err := s.Queries.GetAutopilotQuotaReservationByKey(ctx, db.GetAutopilotQuotaReservationByKeyParams{+ WorkspaceID: workspaceID,+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},+ IdempotencyKey: idempotencyKey,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return db.AutopilotRun{}, false, nil+ }+ if err != nil {+ return db.AutopilotRun{}, false, fmt.Errorf("lookup metered request key: %w", err)+ }+ run, err := s.Queries.GetAutopilotRunByQuotaReservation(ctx, reservation.ID)+ if errors.Is(err, pgx.ErrNoRows) {+ // An orphaned reservation has no run to reuse; the metered path releases it.+ return db.AutopilotRun{}, false, nil+ }+ if err != nil {+ return db.AutopilotRun{}, false, fmt.Errorf("load metered request run: %w", err)+ }+ return run, true, nil+}+// createAutopilotRunWithQuota reserves and links a run in one transaction.// When policy is off, it intentionally uses the legacy direct INSERT so a// self-hosted deployment never touches the quota tables.@@ -139,6 +241,25 @@ func (s *AutopilotService) createAutopilotRunWithQuota(return db.AutopilotRun{}, false, fmt.Errorf("lock quota period: %w", err)}+ if source == "manual" {+ // A member's unmetered run keeps its request key on the run, not on a+ // reservation. Reuse it so the same request is not admitted twice.+ run, err := qtx.GetAutopilotRunByIdempotencyKey(ctx, db.GetAutopilotRunByIdempotencyKeyParams{+ AutopilotID: params.AutopilotID,+ IdempotencyKey: pgtype.Text{String: idempotencyKey, Valid: idempotencyKey != ""},+ })+ if err == nil {+ if err := tx.Commit(ctx); err != nil {+ return db.AutopilotRun{}, false, fmt.Errorf("commit idempotent unmetered reuse: %w", err)+ }+ s.recordAutopilotQuotaDecision(policy.action, source, "reused")+ return run, true, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ return db.AutopilotRun{}, false, fmt.Errorf("lookup unmetered request key: %w", err)+ }+ }+existing, err := qtx.GetAutopilotQuotaReservationByKey(ctx, db.GetAutopilotQuotaReservationByKeyParams{WorkspaceID: workspaceID,PeriodStart: periodArgs.PeriodStart,@@ -323,6 +444,7 @@ func autopilotRunFromTerminalRow(row db.UpdateAutopilotRunTerminalWithQuotaRow)Result: row.Result, CreatedAt: row.CreatedAt, SquadID: row.SquadID,PlannedAt: row.PlannedAt, WebhookDeliveryID: row.WebhookDeliveryID,QuotaReservationID: row.QuotaReservationID, ReasonCode: row.ReasonCode,+ IdempotencyKey: row.IdempotencyKey,}}diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.goindex 82cab33442..a8a6ef8508 100644--- a/server/internal/service/autopilot_quota_test.go+++ b/server/internal/service/autopilot_quota_test.go@@ -175,6 +175,76 @@ func TestAutopilotQuotaRejectsUnknownExecutionSource(t *testing.T) {}}+func TestAutopilotQuotaUnmeteredRunIgnoresFullQuota(t *testing.T) {+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 0)+ metrics := &autopilotQuotaMetricsRecorder{}+ fixture.service.QuotaMetrics = metrics+ ctx := context.Background()+ params := fixture.createRunArgs+ params.Source = "manual"++ run, reused, err := fixture.service.createUnmeteredAutopilotRun(ctx, fixture.workspaceID, "manual", "member-run-now", params)+ if err != nil || reused {+ t.Fatalf("unmetered admission = reused %v, %v; want a fresh run", reused, err)+ }+ if run.QuotaReservationID.Valid {+ t.Fatal("unmetered run reserved quota")+ }+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)+ if err != nil || *usage.Used != 0 || *usage.Reserved != 0 || len(usage.BlockedCounts) != 0 {+ t.Fatalf("usage after unmetered run = %+v, %v; want nothing counted or blocked", usage, err)+ }+ if got := metrics.count("enforce", "manual", "unmetered"); got != 1 {+ t.Fatalf("unmetered decisions = %d, want 1", got)+ }++ // A retried request reuses its run; a new request gets a new one.+ again, reused, err := fixture.service.createUnmeteredAutopilotRun(ctx, fixture.workspaceID, "manual", "member-run-now", params)+ if err != nil || !reused || again.ID != run.ID {+ t.Fatalf("retried unmetered admission = %s reused %v, %v; want %s reused", util.UUIDToString(again.ID), reused, err, util.UUIDToString(run.ID))+ }+ other, reused, err := fixture.service.createUnmeteredAutopilotRun(ctx, fixture.workspaceID, "manual", "member-run-now-2", params)+ if err != nil || reused || other.ID == run.ID {+ t.Fatalf("second unmetered admission = %s reused %v, %v; want a new run", util.UUIDToString(other.ID), reused, err)+ }++ // The same source stays metered when it is not a member's own press.+ if _, _, err := fixture.service.createAutopilotRunWithQuota(ctx, fixture.workspaceID, "manual", "agent-run-now", params); !errors.As(err, new(*AutopilotQuotaExceededError)) {+ t.Fatalf("metered manual admission error = %v, want quota exceeded", err)+ }++ if _, _, err := fixture.service.createUnmeteredAutopilotRun(ctx, fixture.workspaceID, "manul", "invalid-source", params); err == nil ||+ !strings.Contains(err.Error(), "invalid autopilot execution source") {+ t.Fatalf("unknown source error = %v, want application validation", err)+ }+}++func TestAutopilotQuotaUnmeteredConcurrentRetriesShareOneRun(t *testing.T) {+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 0)+ ctx := context.Background()+ params := fixture.createRunArgs+ params.Source = "manual"++ const attempts = 8+ ids := make([]pgtype.UUID, attempts)+ errs := make([]error, attempts)+ var wg sync.WaitGroup+ for i := range attempts {+ wg.Add(1)+ go func() {+ defer wg.Done()+ run, _, err := fixture.service.createUnmeteredAutopilotRun(ctx, fixture.workspaceID, "manual", "concurrent-run-now", params)+ ids[i], errs[i] = run.ID, err+ }()+ }+ wg.Wait()+ for i := range attempts {+ if errs[i] != nil || ids[i] != ids[0] {+ t.Fatalf("attempt %d = %s, %v; want every attempt to share %s", i, util.UUIDToString(ids[i]), errs[i], util.UUIDToString(ids[0]))+ }+ }+}+func TestAutopilotQuotaEnforcesBoundaryAndFinalizesIdempotently(t *testing.T) {pool := newResolveOriginatorPool(t)ctx := context.Background()diff --git a/server/migrations/697_autopilot_run_idempotency_key.down.sql b/server/migrations/697_autopilot_run_idempotency_key.down.sqlnew file mode 100644index 0000000000..6f8ea69591--- /dev/null+++ b/server/migrations/697_autopilot_run_idempotency_key.down.sql@@ -0,0 +1 @@+ALTER TABLE autopilot_run DROP COLUMN IF EXISTS idempotency_key;diff --git a/server/migrations/697_autopilot_run_idempotency_key.up.sql b/server/migrations/697_autopilot_run_idempotency_key.up.sqlnew file mode 100644index 0000000000..530ed8556b--- /dev/null+++ b/server/migrations/697_autopilot_run_idempotency_key.up.sql@@ -0,0 +1,5 @@+-- The caller's request key for a run that is not metered against the autopilot+-- run quota, such as a member's own "run now". Metered runs keep theirs on+-- autopilot_quota_reservation; this column lets an unmetered retry reuse its run+-- without touching the quota tables.+ALTER TABLE autopilot_run ADD COLUMN IF NOT EXISTS idempotency_key TEXT;diff --git a/server/migrations/698_autopilot_run_idempotency_key_idx.down.sql b/server/migrations/698_autopilot_run_idempotency_key_idx.down.sqlnew file mode 100644index 0000000000..9a3cda0783--- /dev/null+++ b/server/migrations/698_autopilot_run_idempotency_key_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_autopilot_run_idempotency_key;diff --git a/server/migrations/698_autopilot_run_idempotency_key_idx.up.sql b/server/migrations/698_autopilot_run_idempotency_key_idx.up.sqlnew file mode 100644index 0000000000..cf1bf44617--- /dev/null+++ b/server/migrations/698_autopilot_run_idempotency_key_idx.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_autopilot_run_idempotency_key ON autopilot_run (autopilot_id, idempotency_key) WHERE idempotency_key IS NOT NULL;diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex ff090b54bd..5555ed6a7a 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -207,13 +207,14 @@ const createAutopilotRun = `-- name: CreateAutopilotRun :oneINSERT INTO autopilot_run (autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,- webhook_delivery_id, quota_reservation_id, reason_code, id+ webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key, id) VALUES ($1, $4, $2, $3, $5,$6, $7,$8, $9,- $10, COALESCE($11::uuid, gen_random_uuid())-) 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, webhook_delivery_id, quota_reservation_id, reason_code+ $10, $11,+ COALESCE($12::uuid, gen_random_uuid())+) 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key`type CreateAutopilotRunParams struct {@@ -227,6 +228,7 @@ type CreateAutopilotRunParams struct {WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`ReasonCode pgtype.Text `json:"reason_code"`+ IdempotencyKey pgtype.Text `json:"idempotency_key"`ID pgtype.UUID `json:"id"`}@@ -244,6 +246,10 @@ type CreateAutopilotRunParams struct {// 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).+//+// idempotency_key is set only for a run that is not metered against the+// autopilot run quota; uq_autopilot_run_idempotency_key makes a retried+// request reuse its run.func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunParams) (AutopilotRun, error) {row := q.db.QueryRow(ctx, createAutopilotRun,arg.AutopilotID,@@ -256,6 +262,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRunarg.WebhookDeliveryID,arg.QuotaReservationID,arg.ReasonCode,+ arg.IdempotencyKey,arg.ID,)var i AutopilotRun@@ -278,6 +285,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -575,7 +583,7 @@ WITH updated_runs AS (SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'WHERE issue_id = $1AND status IN ('issue_created', 'running')- 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, webhook_delivery_id, quota_reservation_id, reason_code+ 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key), locked_reservations AS MATERIALIZED (SELECT qr.id, qr.workspace_id, qr.period_start, qr.period_end, qr.policy_revision, qr.subscription_version, qr.source, qr.idempotency_key, qr.state, qr.created_at, qr.finalized_atFROM autopilot_quota_reservation qr@@ -608,7 +616,7 @@ WITH updated_runs AS (AND p.period_end = released.period_endRETURNING p.workspace_id)-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, webhook_delivery_id, quota_reservation_id, reason_code FROM updated_runs+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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM updated_runs`type FailAutopilotRunsByIssueRow struct {@@ -630,6 +638,7 @@ type FailAutopilotRunsByIssueRow struct {WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`ReasonCode pgtype.Text `json:"reason_code"`+ IdempotencyKey pgtype.Text `json:"idempotency_key"`}// Fails active autopilot runs linked to a given issue.@@ -664,6 +673,7 @@ func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.U&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,); err != nil {return nil, err}@@ -769,7 +779,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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE id = $1`@@ -795,13 +805,52 @@ func (q *Queries) GetAutopilotRun(ctx context.Context, id pgtype.UUID) (Autopilo&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,+ )+ return i, err+}++const getAutopilotRunByIdempotencyKey = `-- name: GetAutopilotRunByIdempotencyKey :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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_run+WHERE autopilot_id = $1+ AND idempotency_key = $2+`++type GetAutopilotRunByIdempotencyKeyParams struct {+ AutopilotID pgtype.UUID `json:"autopilot_id"`+ IdempotencyKey pgtype.Text `json:"idempotency_key"`+}++func (q *Queries) GetAutopilotRunByIdempotencyKey(ctx context.Context, arg GetAutopilotRunByIdempotencyKeyParams) (AutopilotRun, error) {+ row := q.db.QueryRow(ctx, getAutopilotRunByIdempotencyKey, arg.AutopilotID, arg.IdempotencyKey)+ 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,+ &i.WebhookDeliveryID,+ &i.QuotaReservationID,+ &i.ReasonCode,+ &i.IdempotencyKey,)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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE issue_id = $1 AND status IN ('issue_created', 'running')LIMIT 1`@@ -831,12 +880,13 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}const getAutopilotRunByQuotaReservation = `-- name: GetAutopilotRunByQuotaReservation :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, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE quota_reservation_id = $1LIMIT 1`@@ -863,12 +913,13 @@ func (q *Queries) GetAutopilotRunByQuotaReservation(ctx context.Context, quotaRe&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)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, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE trigger_id = $1AND planned_at = $2LIMIT 1@@ -909,12 +960,13 @@ func (q *Queries) GetAutopilotRunByTriggerAndPlanned(ctx context.Context, arg Ge&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}const getAutopilotRunByWebhookDelivery = `-- name: GetAutopilotRunByWebhookDelivery :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, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE webhook_delivery_id = $1OR id = (SELECT autopilot_run_id FROM webhook_delivery WHERE id = $1)LIMIT 1@@ -942,6 +994,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -1103,7 +1156,7 @@ func (q *Queries) GetAutopilotTriggerForAutopilot(ctx context.Context, arg GetAu}const getLatestAutopilotRunForIssueAttribution = `-- name: GetLatestAutopilotRunForIssueAttribution :one-SELECT r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code FROM autopilot_run r+SELECT r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code, r.idempotency_key FROM autopilot_run rJOIN autopilot a ON a.id = r.autopilot_idWHERE r.issue_id = $1 AND r.autopilot_id = $2AND a.workspace_id = $3@@ -1140,6 +1193,7 @@ func (q *Queries) GetLatestAutopilotRunForIssueAttribution(ctx context.Context,&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -1291,7 +1345,7 @@ func (q *Queries) ListAutopilotIDsForCollaborator(ctx context.Context, userID pg}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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code 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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM autopilot_runWHERE autopilot_id = $1ORDER BY created_at DESCLIMIT $2 OFFSET $3@@ -1331,6 +1385,7 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPa&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,); err != nil {return nil, err}@@ -1940,7 +1995,7 @@ SET webhook_delivery_id = candidate.retry_id,reason_code = CASE WHEN candidate.reopen THEN NULL ELSE r.reason_code ENDFROM candidateWHERE r.webhook_delivery_id = candidate.prior_id-RETURNING r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code+RETURNING r.id, r.autopilot_id, r.trigger_id, r.source, r.status, r.issue_id, r.task_id, r.triggered_at, r.completed_at, r.failure_reason, r.trigger_payload, r.result, r.created_at, r.squad_id, r.planned_at, r.webhook_delivery_id, r.quota_reservation_id, r.reason_code, r.idempotency_key`// Keep the original run, issue, and consumed quota. The old delivery retains@@ -1967,6 +2022,7 @@ func (q *Queries) ResumeFailedWebhookIssueDelivery(ctx context.Context, id pgtyp&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -2389,7 +2445,7 @@ const updateAutopilotRunIssueCreated = `-- name: UpdateAutopilotRunIssueCreatedUPDATE autopilot_runSET status = 'issue_created', issue_id = $2WHERE 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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code+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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key`type UpdateAutopilotRunIssueCreatedParams struct {@@ -2419,6 +2475,7 @@ func (q *Queries) UpdateAutopilotRunIssueCreated(ctx context.Context, arg Update&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -2427,7 +2484,7 @@ const updateAutopilotRunRunning = `-- name: UpdateAutopilotRunRunning :oneUPDATE autopilot_runSET status = 'running', task_id = $2WHERE 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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code+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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key`type UpdateAutopilotRunRunningParams struct {@@ -2457,6 +2514,7 @@ func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutop&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -2466,7 +2524,7 @@ UPDATE autopilot_runSET status = 'skipped', completed_at = now(), failure_reason = $2,reason_code = $3WHERE 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, planned_at, webhook_delivery_id, quota_reservation_id, reason_code+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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key`type UpdateAutopilotRunSkippedParams struct {@@ -2505,6 +2563,7 @@ func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutop&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}@@ -2527,7 +2586,7 @@ WITH updated_run AS (ELSE ar.reason_codeENDWHERE ar.id = $5- RETURNING ar.id, ar.autopilot_id, ar.trigger_id, ar.source, ar.status, ar.issue_id, ar.task_id, ar.triggered_at, ar.completed_at, ar.failure_reason, ar.trigger_payload, ar.result, ar.created_at, ar.squad_id, ar.planned_at, ar.webhook_delivery_id, ar.quota_reservation_id, ar.reason_code+ RETURNING ar.id, ar.autopilot_id, ar.trigger_id, ar.source, ar.status, ar.issue_id, ar.task_id, ar.triggered_at, ar.completed_at, ar.failure_reason, ar.trigger_payload, ar.result, ar.created_at, ar.squad_id, ar.planned_at, ar.webhook_delivery_id, ar.quota_reservation_id, ar.reason_code, ar.idempotency_key), locked_reservation AS MATERIALIZED (SELECT qr.id, qr.workspace_id, qr.period_start, qr.period_end, qr.policy_revision, qr.subscription_version, qr.source, qr.idempotency_key, qr.state, qr.created_at, qr.finalized_atFROM autopilot_quota_reservation qr@@ -2558,7 +2617,7 @@ WITH updated_run AS (AND p.period_end = finalized.period_endRETURNING p.workspace_id)-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, webhook_delivery_id, quota_reservation_id, reason_code FROM updated_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, webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key FROM updated_run`type UpdateAutopilotRunTerminalWithQuotaParams struct {@@ -2589,6 +2648,7 @@ type UpdateAutopilotRunTerminalWithQuotaRow struct {WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`ReasonCode pgtype.Text `json:"reason_code"`+ IdempotencyKey pgtype.Text `json:"idempotency_key"`}// Finalizes a run and its still-reserved quota slot in one statement. Runs@@ -2628,6 +2688,7 @@ func (q *Queries) UpdateAutopilotRunTerminalWithQuota(ctx context.Context, arg U&i.WebhookDeliveryID,&i.QuotaReservationID,&i.ReasonCode,+ &i.IdempotencyKey,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex be2bb3d104..954aeacac8 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -371,6 +371,7 @@ type AutopilotRun struct {WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`ReasonCode pgtype.Text `json:"reason_code"`+ IdempotencyKey pgtype.Text `json:"idempotency_key"`}type AutopilotSubscriber struct {diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 3e03b43cb5..986b019ee9 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -329,16 +329,26 @@ RETURNING *;-- 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).+--+-- idempotency_key is set only for a run that is not metered against the+-- autopilot run quota; uq_autopilot_run_idempotency_key makes a retried+-- request reuse its run.INSERT INTO autopilot_run (autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,- webhook_delivery_id, quota_reservation_id, reason_code, id+ webhook_delivery_id, quota_reservation_id, reason_code, idempotency_key, id) VALUES ($1, sqlc.narg('trigger_id'), $2, $3, sqlc.narg('trigger_payload'),sqlc.narg('squad_id'), sqlc.narg('planned_at'),sqlc.narg('webhook_delivery_id'), sqlc.narg('quota_reservation_id'),- sqlc.narg('reason_code'), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())+ sqlc.narg('reason_code'), sqlc.narg('idempotency_key'),+ COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())) RETURNING *;+-- name: GetAutopilotRunByIdempotencyKey :one+SELECT * FROM autopilot_run+WHERE autopilot_id = $1+ AND idempotency_key = $2;+-- name: GetAutopilotRunByTriggerAndPlanned :one-- Idempotent lookup used by DispatchAutopilotForPlan to detect a-- crash-during-dispatch retry: if a row already exists for this