Skip to content

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

Go

MUL-6342: enforce entitlement-backed autopilot quotas (#7194)

Multica Eve3460f9aeaf3f
diff --git a/.env.example b/.env.example
index 9935e72d3c..4aaca750a8 100644
--- a/.env.example
+++ b/.env.example
@@ -173,6 +173,21 @@ MULTICA_FEATURE_FLAGS_FILE=
# Configuring a workspace-specific URL instead would strand every other
# workspace on someone else's page.
+# Managed entitlement-policy consumer. Keep disabled for local development and
+# self-hosting: when false, the backend does not call Cloud or access quota
+# accounting tables. Managed deployments enable it only after multica-cloud's
+# private entitlement endpoint and service token are configured. The token must
+# be an independent random value of at least 32 bytes and match Cloud's
+# billing.subscriptions.policy.service_token_env secret.
+MULTICA_ENTITLEMENT_POLICY_ENABLED=false
+MULTICA_ENTITLEMENT_POLICY_URL=
+MULTICA_ENTITLEMENT_SERVICE_TOKEN=
+MULTICA_ENTITLEMENT_POLICY_TIMEOUT=3s
+MULTICA_ENTITLEMENT_STALE_GRACE=15m
+# Local down switch applied on the next service rollout/restart. true forces
+# all gates off without contacting Cloud; it cannot enable a policy.
+MULTICA_ENTITLEMENT_EMERGENCY_DISABLED=false
+
# Self-host image channel
# Default stable release channel. Pin to an exact release like v0.2.4 if you
# want to stay on a specific version. If the selected tag has not been
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index 7d2a8620c7..7c32be5c42 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -18,6 +18,11 @@ data:
ALLOWED_EMAIL_DOMAINS: {{ .Values.backend.config.allowedEmailDomains | quote }}
DISABLE_WORKSPACE_CREATION: {{ .Values.backend.config.disableWorkspaceCreation | quote }}
MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}
+ MULTICA_ENTITLEMENT_POLICY_ENABLED: {{ .Values.backend.config.entitlementPolicy.enabled | quote }}
+ MULTICA_ENTITLEMENT_POLICY_URL: {{ .Values.backend.config.entitlementPolicy.url | quote }}
+ MULTICA_ENTITLEMENT_POLICY_TIMEOUT: {{ .Values.backend.config.entitlementPolicy.timeout | quote }}
+ MULTICA_ENTITLEMENT_STALE_GRACE: {{ .Values.backend.config.entitlementPolicy.staleGrace | quote }}
+ MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: {{ .Values.backend.config.entitlementPolicy.emergencyDisabled | quote }}
GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}
GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}
S3_BUCKET: {{ .Values.backend.config.s3Bucket | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index a593b41e86..44dbbbff56 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -28,6 +28,7 @@ images:
# --from-literal=RESEND_API_KEY="" \
# --from-literal=GOOGLE_CLIENT_SECRET="" \
# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \
+# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \
# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""
#
# External postgres (postgres.external.enabled=true):
@@ -38,6 +39,7 @@ images:
# --from-literal=RESEND_API_KEY="" \
# --from-literal=GOOGLE_CLIENT_SECRET="" \
# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \
+# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \
# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""
#
# The chart references this Secret by name; it does not template it, so real
@@ -129,6 +131,17 @@ backend:
# MULTICA_VCS_SECRET_KEY through existingSecret before connections work.
# Set false to hide and reject the integration for this deployment.
vcsIntegrationEnabled: true
+ # Managed Cloud policy consumer. The public/self-host chart keeps this off
+ # by default, which also guarantees no quota-table access. To enable it,
+ # set enabled=true and url to multica-cloud's HTTPS internal base URL, then
+ # put a matching 32+ byte MULTICA_ENTITLEMENT_SERVICE_TOKEN in existingSecret.
+ entitlementPolicy:
+ enabled: false
+ url: ""
+ timeout: 3s
+ staleGrace: 15m
+ # Local down switch applied by the next chart rollout; it only forces off.
+ emergencyDisabled: false
googleClientId: ""
googleRedirectUri: http://multica.dev.lan/auth/callback
s3Bucket: ""
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index e15a6368c4..99cd7b03d5 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -102,6 +102,15 @@ services:
ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}
ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}
DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}
+ # Managed entitlement policy is explicitly opt-in. The false/empty
+ # defaults keep self-hosted installs on the legacy path with no Cloud
+ # request and no quota-table access.
+ MULTICA_ENTITLEMENT_POLICY_ENABLED: ${MULTICA_ENTITLEMENT_POLICY_ENABLED:-false}
+ MULTICA_ENTITLEMENT_POLICY_URL: ${MULTICA_ENTITLEMENT_POLICY_URL:-}
+ MULTICA_ENTITLEMENT_SERVICE_TOKEN: ${MULTICA_ENTITLEMENT_SERVICE_TOKEN:-}
+ MULTICA_ENTITLEMENT_POLICY_TIMEOUT: ${MULTICA_ENTITLEMENT_POLICY_TIMEOUT:-3s}
+ MULTICA_ENTITLEMENT_STALE_GRACE: ${MULTICA_ENTITLEMENT_STALE_GRACE:-15m}
+ MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: ${MULTICA_ENTITLEMENT_EMERGENCY_DISABLED:-false}
GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}
GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}
# Public URL the API is reachable at from the open internet, no
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 153f8cbc1d..9873fd4d09 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -892,6 +892,7 @@ describe("ApiClient", () => {
await client.updateAutopilot("ap-1", { status: "paused", project_id: null });
await client.deleteAutopilot("ap-1");
await client.triggerAutopilot("ap-1");
+ await client.getAutopilotQuotaUsage();
await client.listAutopilotRuns("ap-1", { limit: 10, offset: 20 });
await client.createAutopilotTrigger("ap-1", {
kind: "schedule",
@@ -906,6 +907,7 @@ describe("ApiClient", () => {
url,
method: init?.method ?? "GET",
body: init?.body,
+ idempotencyKey: (init?.headers as Record<string, string> | undefined)?.["Idempotency-Key"],
}));
expect(calls).toMatchObject([
@@ -927,7 +929,12 @@ describe("ApiClient", () => {
body: JSON.stringify({ status: "paused", project_id: null }),
},
{ url: "https://api.example.test/api/autopilots/ap-1", method: "DELETE" },
- { url: "https://api.example.test/api/autopilots/ap-1/trigger", method: "POST" },
+ {
+ url: "https://api.example.test/api/autopilots/ap-1/trigger",
+ method: "POST",
+ idempotencyKey: expect.any(String),
+ },
+ { url: "https://api.example.test/api/autopilots/usage", method: "GET" },
{ url: "https://api.example.test/api/autopilots/ap-1/runs?limit=10&offset=20", method: "GET" },
{
url: "https://api.example.test/api/autopilots/ap-1/triggers",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 99f5d18849..872b7b7ab2 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -134,6 +134,7 @@ import type {
Autopilot,
AutopilotTrigger,
AutopilotRun,
+ AutopilotQuotaUsage,
CreateAutopilotRequest,
UpdateAutopilotRequest,
CreateAutopilotTriggerRequest,
@@ -214,7 +215,7 @@ import type {
ListCloudRuntimeNodesParams,
} from "../runtimes/cloud-runtime";
import { type Logger, noopLogger } from "../logger";
-import { createRequestId } from "../utils";
+import { createRequestId, createSafeId } from "../utils";
import { getCurrentSlug } from "../platform/workspace-storage";
import { parseWithFallback } from "./schema";
import {
@@ -276,6 +277,7 @@ import {
ListAutopilotsResponseSchema,
EMPTY_LIST_AUTOPILOTS_RESPONSE,
AutopilotRunSchema,
+ AutopilotQuotaUsageSchema,
FALLBACK_AUTOPILOT_RUN,
CronPreviewResponseSchema,
UNREADABLE_CRON_PREVIEW_RESPONSE,
@@ -3705,15 +3707,37 @@ export class ApiClient {
}
async triggerAutopilot(id: string): Promise<AutopilotRun> {
- // Manual "run now" returns 200 even when admission blocks the run (status
- // skipped/failed). The UI branches on status/reason_code to avoid a
- // false-success toast (MUL-4525), so parse defensively rather than casting.
- const raw = await this.fetch<unknown>(`/api/autopilots/${id}/trigger`, { method: "POST" });
+ // Manual "run now" usually returns a run, including downstream admission
+ // failures. Quota rejection is the exception and returns 429. The UI
+ // handles both paths without presenting a false-success toast.
+ const raw = await this.fetch<unknown>(`/api/autopilots/${id}/trigger`, {
+ method: "POST",
+ headers: { "Idempotency-Key": createSafeId() },
+ });
return parseWithFallback(raw, AutopilotRunSchema, FALLBACK_AUTOPILOT_RUN, {
endpoint: "POST /api/autopilots/:id/trigger",
});
}
+ async getAutopilotQuotaUsage(): Promise<AutopilotQuotaUsage> {
+ const raw = await this.fetch<unknown>("/api/autopilots/usage");
+ return parseWithFallback(
+ raw,
+ AutopilotQuotaUsageSchema,
+ {
+ action: "off",
+ used: null,
+ reserved: null,
+ limit: null,
+ period_start: null,
+ period_end: null,
+ reset_at: null,
+ blocked_counts: null,
+ },
+ { endpoint: "GET /api/autopilots/usage" },
+ );
+ }
+
async listAutopilotRuns(id: string, params?: { limit?: number; offset?: number }): Promise<ListAutopilotRunsResponse> {
const search = new URLSearchParams();
if (params?.limit) search.set("limit", params.limit.toString());
@@ -3817,7 +3841,7 @@ export class ApiClient {
): Promise<WebhookDelivery> {
const raw = await this.fetch<unknown>(
`/api/autopilots/${autopilotId}/deliveries/${deliveryId}/replay`,
- { method: "POST" },
+ { method: "POST", headers: { "Idempotency-Key": createSafeId() } },
);
return parseWithFallback(
raw,
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 1df38515d0..301e655201 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -8,6 +8,7 @@ import {
EMPTY_LIST_WECOM_INSTALLATIONS_RESPONSE,
EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE,
AgentTaskListSchema,
+ AutopilotQuotaUsageSchema,
AutopilotRunSchema,
FALLBACK_AUTOPILOT_RUN,
CommentTriggerPreviewSchema,
@@ -1124,6 +1125,39 @@ describe("AutopilotRunSchema", () => {
});
});
+describe("AutopilotQuotaUsageSchema", () => {
+ const baseUsage = {
+ action: "enforce",
+ used: 12,
+ reserved: 2,
+ limit: 100,
+ period_start: "2026-08-01T00:00:00Z",
+ period_end: "2026-09-01T00:00:00Z",
+ reset_at: "2026-09-01T00:00:00Z",
+ };
+
+ it("preserves durable blocked counts by execution source", () => {
+ const parsed = AutopilotQuotaUsageSchema.parse({
+ ...baseUsage,
+ blocked_counts: { schedule: 3, webhook: 7 },
+ });
+ expect(parsed.blocked_counts).toEqual({ schedule: 3, webhook: 7 });
+ });
+
+ it("defaults blocked_counts to null for an older server", () => {
+ expect(AutopilotQuotaUsageSchema.parse(baseUsage).blocked_counts).toBeNull();
+ });
+
+ it("isolates a malformed blocked_counts field", () => {
+ const parsed = AutopilotQuotaUsageSchema.parse({
+ ...baseUsage,
+ blocked_counts: { webhook: "many" },
+ });
+ expect(parsed.used).toBe(12);
+ expect(parsed.blocked_counts).toBeNull();
+ });
+});
+
// The comment composer branches on preview.blocked to warn before sending
// (MUL-4525 §2), so the additive field must parse and degrade gracefully.
describe("CommentTriggerPreviewSchema.blocked", () => {
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f1b0459bc9..8464bd4c34 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1819,6 +1819,8 @@ const WebhookDeliverySchema = z.object({
autopilot_run_id: z.string().nullable(),
replayed_from_delivery_id: z.string().nullable(),
error: z.string().nullable(),
+ reason_code: z.string().nullable().default(null),
+ replay_idempotency_key: z.string().nullable().default(null),
received_at: z.string(),
last_attempt_at: z.string(),
created_at: z.string(),
@@ -1909,6 +1911,17 @@ export const AutopilotRunSchema = z.object({
created_at: z.string().default(""),
}).loose();
+export const AutopilotQuotaUsageSchema = z.object({
+ action: z.enum(["off", "observe", "enforce"]).default("off"),
+ used: z.number().nullable().default(null),
+ reserved: z.number().nullable().default(null),
+ limit: z.number().nullable().default(null),
+ period_start: z.string().nullable().default(null),
+ period_end: z.string().nullable().default(null),
+ reset_at: z.string().nullable().default(null),
+ blocked_counts: z.record(z.string(), z.number().int().nonnegative()).nullable().catch(null).default(null),
+}).loose();
+
export const FALLBACK_AUTOPILOT_RUN: AutopilotRun = {
id: "",
autopilot_id: "",
@@ -1956,6 +1969,8 @@ export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {
autopilot_run_id: null,
replayed_from_delivery_id: null,
error: null,
+ reason_code: null,
+ replay_idempotency_key: null,
received_at: "",
last_attempt_at: "",
created_at: "",
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index ade8be86fd..75b6b6560e 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -126,7 +126,7 @@ export interface AutopilotRun {
completed_at: string | null;
failure_reason: string | null;
// Stable, localizable, enumeration-safe classification of a non-success run
- // (skipped/failed), derived server-side from failure_reason (MUL-4525). The
+ // (skipped/failed), persisted at the server-side decision source. The
// "run now" UI localizes this instead of echoing the raw English reason.
// Older servers omit it.
reason_code?: string;
@@ -135,6 +135,17 @@ export interface AutopilotRun {
created_at: string;
}
+export interface AutopilotQuotaUsage {
+ action: "off" | "observe" | "enforce";
+ used: number | null;
+ reserved: number | null;
+ limit: number | null;
+ period_start: string | null;
+ period_end: string | null;
+ reset_at: string | null;
+ blocked_counts: Record<string, number> | null;
+}
+
export interface AutopilotSubscriberInput {
user_type: "member";
user_id: string;
@@ -249,6 +260,8 @@ export interface WebhookDelivery {
autopilot_run_id: string | null;
replayed_from_delivery_id: string | null;
error: string | null;
+ reason_code: string | null;
+ replay_idempotency_key: string | null;
received_at: string;
last_attempt_at: string;
created_at: string;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 2365ea7c64..3a1059beb3 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -243,6 +243,7 @@ export type {
AutopilotRun,
AutopilotRunStatus,
AutopilotRunSource,
+ AutopilotQuotaUsage,
WebhookEventFilter,
CreateAutopilotRequest,
UpdateAutopilotRequest,
diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsx
index 3fbdecae89..2414b8c8ae 100644
--- a/packages/views/autopilots/components/autopilot-detail-page.tsx
+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx
@@ -18,7 +18,7 @@ import {
useRotateAutopilotTriggerWebhookToken,
} from "@multica/core/autopilots/mutations";
import { buildAutopilotWebhookUrl } from "@multica/core/autopilots";
-import { api } from "@multica/core/api";
+import { api, dispatchReasonCode } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
@@ -741,7 +741,12 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {
toast.error(message);
}
} catch (e: any) {
- toast.error(e?.message || t(($) => $.detail.toast_trigger_failed));
+ const reason = dispatchReasonCode(e);
+ toast.error(
+ reason
+ ? t(($) => $.detail[runNowBlockedKey(reason)])
+ : e?.message || t(($) => $.detail.toast_trigger_failed),
+ );
}
};
diff --git a/packages/views/autopilots/components/run-now-toast.test.ts b/packages/views/autopilots/components/run-now-toast.test.ts
index 8a229c754b..c0aa588b9f 100644
--- a/packages/views/autopilots/components/run-now-toast.test.ts
+++ b/packages/views/autopilots/components/run-now-toast.test.ts
@@ -34,6 +34,7 @@ describe("runNowBlockedKey", () => {
expect(runNowBlockedKey("target_unavailable")).toBe("run_blocked_target_unavailable");
expect(runNowBlockedKey("attribution_blocked")).toBe("run_blocked_attribution");
expect(runNowBlockedKey("already_active")).toBe("run_blocked_already_active");
+ expect(runNowBlockedKey("quota_exceeded")).toBe("run_blocked_quota_exceeded");
});
it("degrades an unknown or absent code to the generic message", () => {
diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.ts
index 7412e4c315..2dd7bc95aa 100644
--- a/packages/views/autopilots/components/run-now-toast.ts
+++ b/packages/views/autopilots/components/run-now-toast.ts
@@ -36,6 +36,7 @@ export type RunNowBlockedKey =
| "run_blocked_target_unavailable"
| "run_blocked_attribution"
| "run_blocked_already_active"
+ | "run_blocked_quota_exceeded"
| "run_blocked_generic";
export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKey {
@@ -54,6 +55,8 @@ export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedK
return "run_blocked_attribution";
case "already_active":
return "run_blocked_already_active";
+ case "quota_exceeded":
+ return "run_blocked_quota_exceeded";
default:
return "run_blocked_generic";
}
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index dc9ca595af..1c2877ebfe 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -83,6 +83,7 @@
"run_blocked_target_unavailable": "Not triggered — the agent is unavailable",
"run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member",
"run_blocked_already_active": "Not triggered — a recent run already covers this",
+ "run_blocked_quota_exceeded": "Not triggered — the run limit for this period has been reached",
"run_blocked_generic": "Not triggered — the run was blocked",
"section_properties": "Properties",
"section_triggers": "Triggers",
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index 6e2b4f5522..a514225fd3 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -83,6 +83,7 @@
"run_blocked_target_unavailable": "実行されませんでした — エージェントを利用できません",
"run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした",
"run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています",
+ "run_blocked_quota_exceeded": "実行されませんでした — この期間の実行上限に達しました",
"run_blocked_generic": "実行されませんでした — 実行がブロックされました",
"section_properties": "プロパティ",
"section_triggers": "トリガー",
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index 99c0fe0811..501edfce5a 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -83,6 +83,7 @@
"run_blocked_target_unavailable": "실행되지 않음 — 에이전트를 사용할 수 없습니다",
"run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다",
"run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다",
+ "run_blocked_quota_exceeded": "실행되지 않음 — 이 기간의 실행 한도에 도달했습니다",
"run_blocked_generic": "실행되지 않음 — 실행이 차단되었습니다",
"section_properties": "속성",
"section_triggers": "트리거",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index 690453377a..247d9180fe 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -83,6 +83,7 @@
"run_blocked_target_unavailable": "未触发——该智能体不可用",
"run_blocked_attribution": "未触发——无法确定本次运行的负责成员",
"run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次",
+ "run_blocked_quota_exceeded": "未触发——本周期的运行额度已用尽",
"run_blocked_generic": "未触发——本次运行已被拦截",
"section_properties": "属性",
"section_triggers": "触发器",
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 9d73ee56ad..b48fe7bbe2 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -15,6 +15,17 @@ require_rendered_value() {
fi
}
+reject_rendered_value() {
+ local rendered=$1
+ local forbidden=$2
+
+ if grep -Fq "$forbidden" <<<"$rendered"; then
+ echo "Forbidden Helm-rendered config value:"
+ echo " $forbidden"
+ exit 1
+ fi
+}
+
helm lint "$CHART_DIR"
default_config="$(
@@ -22,6 +33,9 @@ default_config="$(
--show-only templates/configmap.yaml
)"
require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "true"'
+require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "false"'
+require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_URL: ""'
+reject_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'
disabled_config="$(
helm template multica "$CHART_DIR" \
@@ -30,4 +44,20 @@ disabled_config="$(
)"
require_rendered_value "$disabled_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "false"'
+entitlement_config="$(
+ helm template multica "$CHART_DIR" \
+ --show-only templates/configmap.yaml \
+ --set backend.config.entitlementPolicy.enabled=true \
+ --set-string backend.config.entitlementPolicy.url=https://multica-cloud.internal \
+ --set-string backend.config.entitlementPolicy.timeout=2s \
+ --set-string backend.config.entitlementPolicy.staleGrace=10m \
+ --set backend.config.entitlementPolicy.emergencyDisabled=false
+)"
+require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "true"'
+require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_URL: "https://multica-cloud.internal"'
+require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_TIMEOUT: "2s"'
+require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_STALE_GRACE: "10m"'
+require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: "false"'
+reject_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'
+
echo "helm config rendering ok"
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b8bdfc2ade..e39f0dde38 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -200,6 +200,12 @@ var concurrentIndexCleanups = map[string]string{
"347_plugin_secret_installation_key_index": "idx_plugin_secret_installation_key",
"349_agent_task_queue_chat_terminal_resume_index": "idx_agent_task_queue_chat_terminal_resume",
"350_agent_task_queue_chat_retired_session_index": "idx_agent_task_queue_chat_retired_session",
+ "353_autopilot_quota_period_scope_index": "uq_autopilot_quota_period_scope",
+ "354_autopilot_quota_reservation_id_index": "autopilot_quota_reservation_pkey_uidx",
+ "355_autopilot_quota_reservation_key_index": "uq_autopilot_quota_reservation_key",
+ "356_autopilot_run_quota_reservation_index": "uq_autopilot_run_quota_reservation",
+ "357_webhook_delivery_replay_idempotency_index": "uq_webhook_delivery_replay_idempotency",
+ "358_autopilot_quota_reservation_state_index": "idx_autopilot_quota_reservation_state",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/server/autopilot_quota_reconciler.go b/server/cmd/server/autopilot_quota_reconciler.go
new file mode 100644
index 0000000000..caf2865775
--- /dev/null
+++ b/server/cmd/server/autopilot_quota_reconciler.go
@@ -0,0 +1,44 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+const (
+ autopilotQuotaReconcileInterval = time.Minute
+ autopilotQuotaTerminalRecoveryAge = 10 * time.Minute
+ // Manual/API dispatches have no durable retry owner. Six hours is far
+ // beyond normal dispatch latency while still releasing a genuinely
+ // abandoned slot before the entitlement period rolls over.
+ autopilotQuotaPartialRecoveryAge = 6 * time.Hour
+ autopilotQuotaReconcileBatch = 100
+)
+
+func runAutopilotQuotaReconciler(ctx context.Context, svc *service.AutopilotService) {
+ ticker := time.NewTicker(autopilotQuotaReconcileInterval)
+ defer ticker.Stop()
+ for {
+ now := time.Now()
+ if settled, err := svc.ReconcileAutopilotQuotaReservations(
+ ctx,
+ now.Add(-autopilotQuotaTerminalRecoveryAge),
+ now.Add(-autopilotQuotaPartialRecoveryAge),
+ autopilotQuotaReconcileBatch,
+ ); err != nil {
+ if ctx.Err() == nil {
+ slog.Warn("autopilot quota reconciler failed", "error", err)
+ }
+ } else if settled > 0 {
+ slog.Info("autopilot quota reconciler settled reservations", "count", settled)
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 0378cc5c18..bca7f393ab 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -534,6 +534,9 @@ func main() {
go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus, runtimeReconnectGrace)
go heartbeatScheduler.Run(sweepCtx)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
+ if autopilotSvc.QuotaEnabled() {
+ go runAutopilotQuotaReconciler(autopilotCtx, autopilotSvc)
+ }
go runDBStatsLogger(sweepCtx, pool)
if h.WebhookDeliveryWorker != nil {
go h.WebhookDeliveryWorker.Run(sweepCtx)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 79a28ecd06..781c9f2194 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -22,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/cloudruntime"
"github.com/multica-ai/multica/server/internal/daemonws"
+ "github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/handler"
@@ -365,6 +366,22 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.TaskService.FeatureFlags = opts.FeatureFlags
h.TaskService.Metrics = opts.BusinessMetrics
h.IssueService.Metrics = opts.BusinessMetrics
+ entitlementClient, entitlementErr := entitlement.New(entitlement.Config{
+ Enabled: envBool("MULTICA_ENTITLEMENT_POLICY_ENABLED", false),
+ BaseURL: strings.TrimSpace(os.Getenv("MULTICA_ENTITLEMENT_POLICY_URL")),
+ ServiceToken: os.Getenv("MULTICA_ENTITLEMENT_SERVICE_TOKEN"),
+ Timeout: envDuration("MULTICA_ENTITLEMENT_POLICY_TIMEOUT", 3*time.Second),
+ StaleGrace: envNonNegativeDuration("MULTICA_ENTITLEMENT_STALE_GRACE", 15*time.Minute),
+ Observer: opts.BusinessMetrics,
+ })
+ if entitlementErr != nil {
+ slog.Error("entitlement policy client disabled by invalid configuration", "error", entitlementErr)
+ opts.BusinessMetrics.RecordEntitlementConfigError()
+ } else if entitlementClient.Enabled() {
+ entitlementClient.SetEmergencyDisabled(envBool("MULTICA_ENTITLEMENT_EMERGENCY_DISABLED", false))
+ h.AutopilotService.Entitlements = entitlementClient
+ h.AutopilotService.QuotaMetrics = opts.BusinessMetrics
+ }
if opts.BusinessMetrics != nil {
// Wire the BusinessMetrics receiver into the cloud runtime client
// so every outbound Fleet/Gateway request feeds the
@@ -1717,6 +1734,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.ListAutopilots)
r.Post("/", h.CreateAutopilot)
r.Get("/cron-preview", h.CronPreview)
+ r.Get("/usage", h.GetAutopilotQuotaUsage)
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetAutopilot)
r.Patch("/", h.UpdateAutopilot)
diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.go
index 067ecff00d..8fd7d90aab 100644
--- a/server/internal/dispatch/reason.go
+++ b/server/internal/dispatch/reason.go
@@ -60,6 +60,9 @@ const (
// success: nothing new runs. (Named to avoid implying the NEW comment was
// already processed.)
ReasonSelfTriggerSuppressed ReasonCode = "self_trigger_suppressed"
+ // ReasonQuotaExceeded is a policy-neutral refusal for an exhausted
+ // Cloud-provided autopilot interval.
+ ReasonQuotaExceeded ReasonCode = "quota_exceeded"
// ReasonInternalError: an unexpected server error prevented a clean decision.
ReasonInternalError ReasonCode = "internal_error"
)
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index dbb784825c..0903603ba6 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -5,10 +5,15 @@ enforcement-policy endpoint. Commercial inputs stay in Cloud: this package does
not contain plan names, subscription-state mapping, rollout dates, cohorts,
exemptions, limit values, or kill-switch policy.
-PR-2 intentionally has no production caller. `Config.Enabled` defaults to
-`false`, a disabled client performs no HTTP request, and all gates return `off`.
-Future SaaS wiring must explicitly enable and construct the client; self-hosted
-deployments remain disabled.
+Production wiring remains explicit and off by default. Set
+`MULTICA_ENTITLEMENT_POLICY_ENABLED=true`,
+`MULTICA_ENTITLEMENT_POLICY_URL`, and the independent
+`MULTICA_ENTITLEMENT_SERVICE_TOKEN` to enable the client. A disabled client
+performs no HTTP request, and the autopilot consumer does not access its quota
+tables; self-hosted deployments therefore retain the legacy dispatch path.
+Timeout, stale grace, and the emergency down switch are controlled by
+`MULTICA_ENTITLEMENT_POLICY_TIMEOUT`, `MULTICA_ENTITLEMENT_STALE_GRACE`, and
+`MULTICA_ENTITLEMENT_EMERGENCY_DISABLED`.
## Contract
@@ -45,8 +50,9 @@ also bounds Cloud request rate when an outage returns errors immediately; cold
failures are cached only as `off` and never as policy.
`SetEmergencyDisabled(true)` is the local immediate down switch. It only returns
-`off`; it cannot promote a Cloud action. No background goroutine, database
-state, migration, or startup dependency is introduced by this package.
+`off`; it cannot promote a Cloud action. The client itself has no background
+goroutine and introduces no startup dependency; the autopilot consumer owns its
+policy-neutral accounting and recovery lifecycle separately.
Future consumers should depend on the small `Provider` interface. Tests can use
`server/internal/entitlement/entitlementtest.Stub` without Cloud.
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index 746d34595d..c102a781bd 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -77,6 +77,17 @@ type AutopilotResponse struct {
CanManageAccess *bool `json:"can_manage_access,omitempty"`
}
+type AutopilotQuotaUsageResponse struct {
+ Action string `json:"action"`
+ Used *int64 `json:"used"`
+ Reserved *int64 `json:"reserved"`
+ Limit *int64 `json:"limit"`
+ PeriodStart *string `json:"period_start"`
+ PeriodEnd *string `json:"period_end"`
+ ResetAt *string `json:"reset_at"`
+ BlockedCounts map[string]int64 `json:"blocked_counts"`
+}
+
// AutopilotCollaboratorEntry is a member explicitly granted write access to an
// autopilot, surfaced on the detail response and the collaborator endpoints.
type AutopilotCollaboratorEntry struct {
@@ -156,10 +167,9 @@ type AutopilotRunResponse struct {
CompletedAt *string `json:"completed_at"`
FailureReason *string `json:"failure_reason"`
// ReasonCode is a stable, localizable, enumeration-safe classification of a
- // non-success run (skipped/failed), derived from FailureReason. The "run now"
- // UI localizes it instead of echoing the raw English reason (which may name a
- // private assignee agent). Additive: nil for success-path runs and ignored by
- // old clients (MUL-4525).
+ // non-success run (skipped/failed), persisted at the decision source. The UI
+ // localizes it instead of echoing the raw English reason (which may name a
+ // private assignee agent). Additive: nil for legacy/success-path runs.
ReasonCode *string `json:"reason_code,omitempty"`
TriggerPayload any `json:"trigger_payload"`
Result any `json:"result"`
@@ -279,20 +289,17 @@ func runToResponse(r db.AutopilotRun) AutopilotRunResponse {
json.Unmarshal(r.Result, &result)
}
return AutopilotRunResponse{
- ID: uuidToString(r.ID),
- AutopilotID: uuidToString(r.AutopilotID),
- TriggerID: uuidToPtr(r.TriggerID),
- Source: r.Source,
- Status: r.Status,
- IssueID: uuidToPtr(r.IssueID),
- TaskID: uuidToPtr(r.TaskID),
- TriggeredAt: timestampToString(r.TriggeredAt),
- CompletedAt: timestampToPtr(r.CompletedAt),
- FailureReason: textToPtr(r.FailureReason),
- // ReasonCode is left unset here: it is a decision-time value the manual
- // "run now" handler injects from the typed dispatch outcome (MUL-4525).
- // Persisted rows (list/history) surface the human failure_reason instead
- // of a code reverse-engineered from that text.
+ ID: uuidToString(r.ID),
+ AutopilotID: uuidToString(r.AutopilotID),
+ TriggerID: uuidToPtr(r.TriggerID),
+ Source: r.Source,
+ Status: r.Status,
+ IssueID: uuidToPtr(r.IssueID),
+ TaskID: uuidToPtr(r.TaskID),
+ TriggeredAt: timestampToString(r.TriggeredAt),
+ CompletedAt: timestampToPtr(r.CompletedAt),
+ FailureReason: textToPtr(r.FailureReason),
+ ReasonCode: textToPtr(r.ReasonCode),
TriggerPayload: payload,
Result: result,
CreatedAt: timestampToString(r.CreatedAt),
@@ -2085,8 +2092,30 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
}
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- run, reasonCode, err := h.AutopilotService.DispatchAutopilotManual(r.Context(), autopilot, pgtype.UUID{}, nil, memberActorUserID(actorType, actorID))
+ idempotencyKey := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
+ if len(idempotencyKey) > 255 {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key is too long")
+ return
+ }
+ if idempotencyKey == "" {
+ idempotencyKey = service.NewRequestIdempotencyKey()
+ }
+ run, reasonCode, err := h.AutopilotService.DispatchAutopilotManualWithKey(r.Context(), autopilot, pgtype.UUID{}, nil, memberActorUserID(actorType, actorID), idempotencyKey)
if err != nil {
+ var quotaErr *service.AutopilotQuotaExceededError
+ if errors.As(err, &quotaErr) {
+ retryAfter := int64(time.Until(quotaErr.ResetAt).Seconds())
+ if retryAfter < 1 {
+ retryAfter = 1
+ }
+ w.Header().Set("Retry-After", strconv.FormatInt(retryAfter, 10))
+ writeJSON(w, http.StatusTooManyRequests, map[string]any{
+ "reason_code": "quota_exceeded", "used": quotaErr.Used,
+ "reserved": quotaErr.Reserved, "limit": quotaErr.Limit,
+ "reset_at": quotaErr.ResetAt.UTC().Format(time.RFC3339),
+ })
+ return
+ }
writeError(w, http.StatusInternalServerError, "failed to trigger autopilot: "+err.Error())
return
}
@@ -2101,3 +2130,38 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, http.StatusOK, resp)
}
+
+// GetAutopilotQuotaUsage exposes Cloud-provided interval facts plus durable
+// server-owned blocked counts. When the gate is off or malformed, the service
+// returns before any quota-table read.
+func (h *Handler) GetAutopilotQuotaUsage(w http.ResponseWriter, r *http.Request) {
+ workspaceID, err := util.ParseUUID(h.resolveWorkspaceID(r))
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid workspace")
+ return
+ }
+ usage, err := h.AutopilotService.AutopilotQuotaUsage(r.Context(), workspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load autopilot quota usage")
+ return
+ }
+ resp := AutopilotQuotaUsageResponse{Action: "off"}
+ if usage.Enabled {
+ resp.Action = usage.Action
+ resp.Used, resp.Reserved, resp.Limit = usage.Used, usage.Reserved, usage.Limit
+ resp.BlockedCounts = usage.BlockedCounts
+ if usage.PeriodStart != nil {
+ v := usage.PeriodStart.UTC().Format(time.RFC3339)
+ resp.PeriodStart = &v
+ }
+ if usage.PeriodEnd != nil {
+ v := usage.PeriodEnd.UTC().Format(time.RFC3339)
+ resp.PeriodEnd = &v
+ }
+ if usage.ResetAt != nil {
+ v := usage.ResetAt.UTC().Format(time.RFC3339)
+ resp.ResetAt = &v
+ }
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
diff --git a/server/internal/handler/autopilot_quota_handler_test.go b/server/internal/handler/autopilot_quota_handler_test.go
new file mode 100644
index 0000000000..1dfac24184
--- /dev/null
+++ b/server/internal/handler/autopilot_quota_handler_test.go
@@ -0,0 +1,87 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
+)
+
+func TestAutopilotQuotaManualAndWebhookEnforcement(t *testing.T) {
+ workspaceUUID := uuid.MustParse(testWorkspaceID)
+ start := time.Now().UTC().Truncate(time.Second)
+ end := start.Add(17 * time.Hour)
+ limit := 0
+ stub := entitlementtest.New()
+ stub.Set(workspaceUUID, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, 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 Handler Agent")
+ autopilotID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ 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())
+ }
+ if manual.Header().Get("Retry-After") == "" {
+ t.Fatal("manual quota refusal must include Retry-After")
+ }
+ 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)
+ }
+
+ trigger := createWebhookTriggerViaHandler(t, autopilotID)
+ webhook := postWebhook(t, *trigger.WebhookToken, map[string]any{"event": "quota.test"}, nil)
+ if webhook.Code != http.StatusOK {
+ t.Fatalf("webhook status = %d body=%s, want 200 ignored", webhook.Code, webhook.Body.String())
+ }
+ var webhookBody map[string]any
+ if err := json.Unmarshal(webhook.Body.Bytes(), &webhookBody); err != nil ||
+ webhookBody["status"] != "ignored" || webhookBody["reason_code"] != "quota_exceeded" {
+ t.Fatalf("webhook body = %#v, err=%v", webhookBody, err)
+ }
+ var runCount int
+ 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)
+ }
+
+ usageRecorder := httptest.NewRecorder()
+ usageReq := newRequest("GET", "/api/autopilots/usage", nil)
+ testHandler.GetAutopilotQuotaUsage(usageRecorder, usageReq)
+ if usageRecorder.Code != http.StatusOK {
+ t.Fatalf("usage status = %d body=%s, want 200", usageRecorder.Code, usageRecorder.Body.String())
+ }
+ var usage AutopilotQuotaUsageResponse
+ if err := json.Unmarshal(usageRecorder.Body.Bytes(), &usage); err != nil {
+ 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)
+ }
+}
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index ae87ac6aef..1dd32c803b 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -24,6 +24,7 @@ import (
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -571,6 +572,16 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
delivery.ID,
)
if err != nil {
+ var quotaErr *service.AutopilotQuotaExceededError
+ if errors.As(err, &quotaErr) {
+ respBody := map[string]any{
+ "status": "ignored", "delivery_id": uuidToString(delivery.ID),
+ "reason_code": "quota_exceeded",
+ }
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, quotaErr.Error(), "quota_exceeded")
+ writeJSON(w, http.StatusOK, respBody)
+ return
+ }
slog.Warn("webhook admission failed",
"trigger_id", uuidToString(trigRow.ID),
"autopilot_id", uuidToString(autopilot.ID),
@@ -844,6 +855,7 @@ func (h *Handler) finaliseDeliveryTerminal(
httpStatus int,
responseBody any,
errMsg string,
+ reasonCode ...string,
) {
bodyJSON, _ := json.Marshal(responseBody)
params := db.UpdateWebhookDeliveryTerminalParams{
@@ -855,6 +867,9 @@ func (h *Handler) finaliseDeliveryTerminal(
if errMsg != "" {
params.Error = pgtype.Text{String: errMsg, Valid: true}
}
+ if len(reasonCode) > 0 && reasonCode[0] != "" {
+ params.ReasonCode = pgtype.Text{String: reasonCode[0], Valid: true}
+ }
if _, err := h.Queries.UpdateWebhookDeliveryTerminal(r.Context(), params); err != nil {
slog.Warn("webhook: finalise terminal failed",
"delivery_id", uuidToString(id),
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index d0becf1fcd..3ffa030228 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -3749,7 +3749,7 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
// Fail any linked autopilot runs before delete (ON DELETE SET NULL clears issue_id).
- h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)
+ _ = h.AutopilotService.FailAutopilotRunsByIssue(r.Context(), issue.ID)
attachmentURLs, err := h.deleteIssueAndCollectAttachmentURLs(r.Context(), issue)
if err != nil {
@@ -4215,7 +4215,7 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
}
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
- h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)
+ _ = h.AutopilotService.FailAutopilotRunsByIssue(r.Context(), issue.ID)
attachmentURLs, err := h.deleteIssueAndCollectAttachmentURLs(r.Context(), issue)
if err != nil {
diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.go
index 87adc6bc15..183b954fee 100644
--- a/server/internal/handler/webhook_delivery.go
+++ b/server/internal/handler/webhook_delivery.go
@@ -6,10 +6,12 @@ import (
"log/slog"
"net/http"
"strconv"
+ "strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -39,6 +41,8 @@ type WebhookDeliveryResponse struct {
AutopilotRunID *string `json:"autopilot_run_id"`
ReplayedFromDeliveryID *string `json:"replayed_from_delivery_id"`
Error *string `json:"error"`
+ ReasonCode *string `json:"reason_code"`
+ ReplayIdempotencyKey *string `json:"replay_idempotency_key"`
ReceivedAt string `json:"received_at"`
LastAttemptAt string `json:"last_attempt_at"`
CreatedAt string `json:"created_at"`
@@ -55,23 +59,25 @@ type WebhookDeliveryResponse struct {
// selected_headers / response_body) into the wire response shape.
func slimDeliveryToResponse(d db.ListWebhookDeliveriesByAutopilotRow) WebhookDeliveryResponse {
resp := WebhookDeliveryResponse{
- ID: uuidToString(d.ID),
- WorkspaceID: uuidToString(d.WorkspaceID),
- AutopilotID: uuidToString(d.AutopilotID),
- TriggerID: uuidToString(d.TriggerID),
- Provider: d.Provider,
- Event: d.Event,
- DedupeKey: textToPtr(d.DedupeKey),
- DedupeSource: textToPtr(d.DedupeSource),
- SignatureStatus: d.SignatureStatus,
- Status: d.Status,
- AttemptCount: d.AttemptCount,
- DispatchAttempts: d.DispatchAttempts,
- AvailableAt: timestampToString(d.AvailableAt),
- ContentType: textToPtr(d.ContentType),
- ReceivedAt: timestampToString(d.ReceivedAt),
- LastAttemptAt: timestampToString(d.LastAttemptAt),
- CreatedAt: timestampToString(d.CreatedAt),
+ ID: uuidToString(d.ID),
+ WorkspaceID: uuidToString(d.WorkspaceID),
+ AutopilotID: uuidToString(d.AutopilotID),
+ TriggerID: uuidToString(d.TriggerID),
+ Provider: d.Provider,
+ Event: d.Event,
+ DedupeKey: textToPtr(d.DedupeKey),
+ DedupeSource: textToPtr(d.DedupeSource),
+ SignatureStatus: d.SignatureStatus,
+ Status: d.Status,
+ AttemptCount: d.AttemptCount,
+ DispatchAttempts: d.DispatchAttempts,
+ AvailableAt: timestampToString(d.AvailableAt),
+ ContentType: textToPtr(d.ContentType),
+ ReceivedAt: timestampToString(d.ReceivedAt),
+ LastAttemptAt: timestampToString(d.LastAttemptAt),
+ CreatedAt: timestampToString(d.CreatedAt),
+ ReasonCode: textToPtr(d.ReasonCode),
+ ReplayIdempotencyKey: textToPtr(d.ReplayIdempotencyKey),
}
if d.ResponseStatus.Valid {
v := d.ResponseStatus.Int32
@@ -94,23 +100,25 @@ func slimDeliveryToResponse(d db.ListWebhookDeliveriesByAutopilotRow) WebhookDel
func deliveryToResponse(d db.WebhookDelivery, detail bool) WebhookDeliveryResponse {
resp := WebhookDeliveryResponse{
- ID: uuidToString(d.ID),
- WorkspaceID: uuidToString(d.WorkspaceID),
- AutopilotID: uuidToString(d.AutopilotID),
- TriggerID: uuidToString(d.TriggerID),
- Provider: d.Provider,
- Event: d.Event,
- DedupeKey: textToPtr(d.DedupeKey),
- DedupeSource: textToPtr(d.DedupeSource),
- SignatureStatus: d.SignatureStatus,
- Status: d.Status,
- AttemptCount: d.AttemptCount,
- DispatchAttempts: d.DispatchAttempts,
- AvailableAt: timestampToString(d.AvailableAt),
- ContentType: textToPtr(d.ContentType),
- ReceivedAt: timestampToString(d.ReceivedAt),
- LastAttemptAt: timestampToString(d.LastAttemptAt),
- CreatedAt: timestampToString(d.CreatedAt),
+ ID: uuidToString(d.ID),
+ WorkspaceID: uuidToString(d.WorkspaceID),
+ AutopilotID: uuidToString(d.AutopilotID),
+ TriggerID: uuidToString(d.TriggerID),
+ Provider: d.Provider,
+ Event: d.Event,
+ DedupeKey: textToPtr(d.DedupeKey),
+ DedupeSource: textToPtr(d.DedupeSource),
+ SignatureStatus: d.SignatureStatus,
+ Status: d.Status,
+ AttemptCount: d.AttemptCount,
+ DispatchAttempts: d.DispatchAttempts,
+ AvailableAt: timestampToString(d.AvailableAt),
+ ContentType: textToPtr(d.ContentType),
+ ReceivedAt: timestampToString(d.ReceivedAt),
+ LastAttemptAt: timestampToString(d.LastAttemptAt),
+ CreatedAt: timestampToString(d.CreatedAt),
+ ReasonCode: textToPtr(d.ReasonCode),
+ ReplayIdempotencyKey: textToPtr(d.ReplayIdempotencyKey),
}
if d.ResponseStatus.Valid {
v := d.ResponseStatus.Int32
@@ -213,17 +221,18 @@ func (h *Handler) GetAutopilotDelivery(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, deliveryToResponse(delivery, true))
}
-// ReplayAutopilotDelivery creates a NEW delivery row from a prior one and
-// dispatches the autopilot synchronously. The new row carries
+// ReplayAutopilotDelivery creates a NEW queued delivery row from a prior one;
+// the existing durable worker owns dispatch. The new row carries
// `replayed_from_delivery_id` so the operator can correlate. Replay is
// rejected for deliveries that originally failed signature verification —
// re-running an attack payload against the autopilot would defeat the
// rejection in the first place.
//
-// Replays bypass per-trigger dedupe by inserting with a NULL dedupe_key:
+// Replays bypass provider dedupe by inserting with a NULL dedupe_key:
// reusing the original key would silently collapse the replay onto the prior
// delivery (the partial unique index would fire). This is the intended
-// behaviour — a replay is explicitly "run this again".
+// behaviour — a replay is explicitly "run this again". API retries are
+// independently deduplicated by (original delivery, Idempotency-Key).
func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request) {
autopilotID := chi.URLParam(r, "id")
deliveryID := chi.URLParam(r, "deliveryId")
@@ -273,9 +282,24 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request
writeError(w, http.StatusBadRequest, "stored body no longer parses: "+err.Error())
return
}
- envelopeBytes, err := json.Marshal(envelope)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to encode envelope")
+ _ = envelope // the durable worker normalizes the stored payload again
+
+ idempotencyKey := strings.TrimSpace(r.Header.Get("Idempotency-Key"))
+ if len(idempotencyKey) > 255 {
+ writeError(w, http.StatusBadRequest, "Idempotency-Key is too long")
+ return
+ }
+ if idempotencyKey == "" {
+ idempotencyKey = service.NewRequestIdempotencyKey()
+ }
+ keyText := pgtype.Text{String: idempotencyKey, Valid: true}
+ if existing, lookupErr := h.Queries.GetWebhookReplayByIdempotencyKey(r.Context(), db.GetWebhookReplayByIdempotencyKeyParams{
+ ReplayedFromDeliveryID: original.ID, ReplayIdempotencyKey: keyText,
+ }); lookupErr == nil {
+ writeJSON(w, http.StatusAccepted, deliveryToResponse(existing, true))
+ return
+ } else if !errors.Is(lookupErr, pgx.ErrNoRows) {
+ writeError(w, http.StatusInternalServerError, "failed to inspect replay request")
return
}
@@ -295,8 +319,18 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request
ContentType: pgtype.Text{String: contentType, Valid: contentType != ""},
RawBody: original.RawBody,
ReplayedFromDeliveryID: original.ID,
+ ReplayIdempotencyKey: keyText,
})
if err != nil {
+ if isUniqueViolation(err) {
+ existing, lookupErr := h.Queries.GetWebhookReplayByIdempotencyKey(r.Context(), db.GetWebhookReplayByIdempotencyKeyParams{
+ ReplayedFromDeliveryID: original.ID, ReplayIdempotencyKey: keyText,
+ })
+ if lookupErr == nil {
+ writeJSON(w, http.StatusAccepted, deliveryToResponse(existing, true))
+ return
+ }
+ }
slog.Error("replay: insert delivery failed",
"error", err,
"original_delivery_id", uuidToString(original.ID),
@@ -305,56 +339,10 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request
return
}
- run, dispatchErr := h.AutopilotService.DispatchAutopilot(
- r.Context(),
- autopilot,
- trigRow.ID,
- "webhook",
- envelopeBytes,
- )
- if dispatchErr != nil {
- respBody := map[string]any{"error": "failed to dispatch autopilot"}
- // DispatchAutopilot may return a non-nil run alongside an error
- // (see HandleAutopilotWebhook for the same rationale). Link the
- // run on the failed delivery so Deliveries UI can surface it.
- if run != nil {
- h.finaliseDeliveryWithRun(r, replay.ID, deliveryStatusFailed, run.ID, http.StatusInternalServerError, respBody)
- } else {
- h.finaliseDeliveryTerminal(r, replay.ID, deliveryStatusFailed, http.StatusInternalServerError, respBody, dispatchErr.Error())
- }
- writeError(w, http.StatusInternalServerError, dispatchErr.Error())
- return
- }
-
- if err := h.Queries.TouchAutopilotTriggerFiredAt(r.Context(), trigRow.ID); err != nil {
- slog.Warn("replay: failed to touch last_fired_at", "trigger_id", uuidToString(trigRow.ID), "error", err)
- }
-
- // Delivery is always `dispatched` once a run is produced — even when
- // the run itself was skipped (e.g. runtime offline). See the comment
- // in HandleAutopilotWebhook for the rationale.
- respBody := map[string]any{
- "status": "accepted",
- "delivery_id": uuidToString(replay.ID),
- "run_id": uuidToString(run.ID),
- "autopilot_id": uuidToString(autopilot.ID),
- "trigger_id": uuidToString(trigRow.ID),
- "replayed_from_delivery_id": uuidToString(original.ID),
- }
- if run.Status == "skipped" {
- respBody["status"] = "skipped"
- if run.FailureReason.Valid {
- respBody["reason"] = run.FailureReason.String
- }
- }
- h.finaliseDeliveryWithRun(r, replay.ID, deliveryStatusDispatched, run.ID, http.StatusCreated, respBody)
-
- final, err := h.Queries.GetWebhookDelivery(r.Context(), replay.ID)
- if err != nil {
- writeJSON(w, http.StatusCreated, respBody)
- return
+ if h.WebhookDeliveryWorker != nil {
+ h.WebhookDeliveryWorker.Notify()
}
- writeJSON(w, http.StatusCreated, deliveryToResponse(final, true))
+ writeJSON(w, http.StatusAccepted, deliveryToResponse(replay, true))
}
// loadDeliveryForAutopilot returns the delivery row when it exists in the
diff --git a/server/internal/handler/webhook_delivery_test.go b/server/internal/handler/webhook_delivery_test.go
index 4afc6ccf50..37173c1194 100644
--- a/server/internal/handler/webhook_delivery_test.go
+++ b/server/internal/handler/webhook_delivery_test.go
@@ -379,7 +379,7 @@ func TestSigningSecret_EmptyClearsSecret(t *testing.T) {
requireAcceptedWebhookResponse(t, post)
}
-func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {
+func TestReplay_QueuesIdempotentDeliveryForDurableWorker(t *testing.T) {
agentID := createWebhookTestAgent(t, "Replay Agent")
apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
trig := createWebhookTriggerViaHandler(t, apID)
@@ -395,9 +395,10 @@ func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {
// Replay the original.
wr := httptest.NewRecorder()
req := newRequest("POST", fmt.Sprintf("/api/autopilots/%s/deliveries/%s/replay", apID, originalID), nil)
+ req.Header.Set("Idempotency-Key", "replay-request")
req = withURLParams(req, "id", apID, "deliveryId", originalID)
testHandler.ReplayAutopilotDelivery(wr, req)
- if wr.Code != http.StatusCreated {
+ if wr.Code != http.StatusAccepted {
t.Fatalf("replay: %d body=%s", wr.Code, wr.Body.String())
}
var replay map[string]any
@@ -408,13 +409,34 @@ func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {
if replay["replayed_from_delivery_id"] != originalID {
t.Fatalf("replayed_from_delivery_id: %v", replay["replayed_from_delivery_id"])
}
- if replay["autopilot_run_id"] == nil {
- t.Fatal("replay should dispatch a run")
+ if replay["status"] != deliveryStatusQueued || replay["autopilot_run_id"] != nil {
+ t.Fatalf("replay should be durably queued before worker dispatch: %#v", replay)
}
- if replay["autopilot_run_id"] == originalRunID {
+ replayID := replay["id"].(string)
+ replayedDelivery := processQueuedWebhookDelivery(t, replayID)
+ if !replayedDelivery.AutopilotRunID.Valid {
+ t.Fatal("worker should link the replay run")
+ }
+ if uuidToString(replayedDelivery.AutopilotRunID) == originalRunID {
t.Fatal("replay should produce a NEW run, not reuse the original")
}
+ // Retrying the replay request with the same key returns the same delivery
+ // and cannot enqueue or reserve a second run.
+ retryRecorder := httptest.NewRecorder()
+ retryReq := newRequest("POST", fmt.Sprintf("/api/autopilots/%s/deliveries/%s/replay", apID, originalID), nil)
+ retryReq.Header.Set("Idempotency-Key", "replay-request")
+ retryReq = withURLParams(retryReq, "id", apID, "deliveryId", originalID)
+ testHandler.ReplayAutopilotDelivery(retryRecorder, retryReq)
+ if retryRecorder.Code != http.StatusAccepted {
+ t.Fatalf("replay retry: %d body=%s", retryRecorder.Code, retryRecorder.Body.String())
+ }
+ var retried map[string]any
+ json.Unmarshal(retryRecorder.Body.Bytes(), &retried)
+ if retried["id"] != replayID {
+ t.Fatalf("replay retry id = %v, want %s", retried["id"], replayID)
+ }
+
deliveries := listDeliveries(t, apID)
if len(deliveries) != 2 {
t.Fatalf("expected 2 deliveries (original + replay), got %d", len(deliveries))
diff --git a/server/internal/handler/webhook_delivery_worker.go b/server/internal/handler/webhook_delivery_worker.go
index b131434943..1478fefcde 100644
--- a/server/internal/handler/webhook_delivery_worker.go
+++ b/server/internal/handler/webhook_delivery_worker.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -195,6 +196,10 @@ func (w *WebhookDeliveryWorker) ProcessNext(ctx context.Context) (bool, error) {
delivery.ID,
)
if dispatchErr != nil {
+ var quotaErr *service.AutopilotQuotaExceededError
+ if errors.As(dispatchErr, &quotaErr) {
+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, quotaErr.Error(), "quota_exceeded")
+ }
if run != nil {
return true, w.complete(ctx, delivery, deliveryStatusFailed, run.ID, dispatchErr.Error())
}
@@ -224,6 +229,7 @@ func (w *WebhookDeliveryWorker) complete(
status string,
runID pgtype.UUID,
reason string,
+ reasonCode ...string,
) error {
params := db.CompleteClaimedWebhookDeliveryParams{
ID: delivery.ID,
@@ -234,6 +240,9 @@ func (w *WebhookDeliveryWorker) complete(
if reason != "" {
params.Error = pgtype.Text{String: reason, Valid: true}
}
+ if len(reasonCode) > 0 && reasonCode[0] != "" {
+ params.ReasonCode = pgtype.Text{String: reasonCode[0], Valid: true}
+ }
_, err := w.h.Queries.CompleteClaimedWebhookDelivery(ctx, params)
lost, err := handleWebhookLeaseMutation("complete", delivery, err)
if err != nil {
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index bcf99572a0..96040b3394 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -1243,6 +1243,14 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
name: "delete autopilot runs",
run: func() error { return qtx.DeleteWorkspaceAutopilotRuns(ctx, requester.WorkspaceID) },
},
+ {
+ name: "delete autopilot quota reservations",
+ run: func() error { return qtx.DeleteWorkspaceAutopilotQuotaReservations(ctx, requester.WorkspaceID) },
+ },
+ {
+ name: "delete autopilot quota periods",
+ run: func() error { return qtx.DeleteWorkspaceAutopilotQuotaPeriods(ctx, requester.WorkspaceID) },
+ },
{
name: "delete chat messages",
run: func() error { return qtx.DeleteWorkspaceChatMessages(ctx, requester.WorkspaceID) },
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 8f42ae2ee5..b0972f3e00 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -30,6 +30,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"attachment": workspaceDelete,
"autopilot": workspaceDelete,
"autopilot_collaborator": workspaceDelete,
+ "autopilot_quota_period": workspaceDelete,
+ "autopilot_quota_reservation": workspaceDelete,
"autopilot_rule_version": workspaceDelete,
"autopilot_run": workspaceDelete,
"autopilot_subscriber": workspaceDelete,
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index 6b622a4a33..6a60d01a2d 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -42,6 +42,13 @@ type BusinessMetrics struct {
runtimeGCFailed prometheus.Counter
runtimeGCBlocked prometheus.Gauge
runtimeGCBlockedObservationFailed prometheus.Counter
+ entitlementConfigError prometheus.Counter
+ entitlementCache *prometheus.CounterVec
+ entitlementRefresh *prometheus.CounterVec
+ entitlementRefreshDuration *prometheus.HistogramVec
+ entitlementDecision *prometheus.CounterVec
+ entitlementVersionRegression *prometheus.CounterVec
+ autopilotQuotaDecision *prometheus.CounterVec
activeMu sync.Mutex
activeTasks map[string]activeTaskLabels
@@ -197,6 +204,34 @@ func NewBusinessMetrics() *BusinessMetrics {
Name: "blocked_observation_failed_total",
Help: "Total failures while observing stale runtimes blocked from garbage collection.",
}),
+ entitlementConfigError: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "config_error_total",
+ Help: "Total startup failures caused by explicitly enabled but invalid entitlement policy configuration.",
+ }),
+ entitlementCache: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "cache_total",
+ Help: "Total entitlement cache outcomes.",
+ }, metricLabels("multica_entitlement_cache_total")),
+ entitlementRefresh: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "refresh_total",
+ Help: "Total entitlement refresh outcomes.",
+ }, metricLabels("multica_entitlement_refresh_total")),
+ entitlementRefreshDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "refresh_duration_seconds",
+ Help: "Duration of entitlement refreshes.", Buckets: chatClaimResumeQueryDurationBuckets,
+ }, metricLabels("multica_entitlement_refresh_duration_seconds")),
+ entitlementDecision: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "decision_total",
+ Help: "Total entitlement decisions by bounded gate, action, and reason.",
+ }, metricLabels("multica_entitlement_decision_total")),
+ entitlementVersionRegression: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "entitlement", Name: "version_regression_total",
+ Help: "Total rejected entitlement version regressions.",
+ }, metricLabels("multica_entitlement_version_regression_total")),
+ autopilotQuotaDecision: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Namespace: "multica", Subsystem: "autopilot_quota", Name: "decision_total",
+ Help: "Total autopilot quota admission outcomes.",
+ }, metricLabels("multica_autopilot_quota_decision_total")),
activeTasks: map[string]activeTaskLabels{},
events: newBusinessEventMetrics(),
}
@@ -229,9 +264,60 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {
m.runtimeGCFailed,
m.runtimeGCBlocked,
m.runtimeGCBlockedObservationFailed,
+ m.entitlementConfigError,
+ m.entitlementCache,
+ m.entitlementRefresh,
+ m.entitlementRefreshDuration,
+ m.entitlementDecision,
+ m.entitlementVersionRegression,
+ m.autopilotQuotaDecision,
}, m.events.collectors()...)
}
+func (m *BusinessMetrics) RecordEntitlementConfigError() {
+ if m != nil {
+ m.entitlementConfigError.Inc()
+ }
+}
+
+func (m *BusinessMetrics) RecordEntitlementCache(outcome string) {
+ if m != nil {
+ m.entitlementCache.WithLabelValues(outcome).Inc()
+ }
+}
+
+func (m *BusinessMetrics) RecordEntitlementRefresh(outcome string, seconds float64) {
+ if m == nil {
+ return
+ }
+ m.entitlementRefresh.WithLabelValues(outcome).Inc()
+ m.entitlementRefreshDuration.WithLabelValues(outcome).Observe(seconds)
+}
+
+func (m *BusinessMetrics) RecordEntitlementDecision(gate, action, reason string) {
+ if m != nil {
+ m.entitlementDecision.WithLabelValues(gate, action, reason).Inc()
+ }
+}
+
+func (m *BusinessMetrics) RecordEntitlementVersionRegression(source string) {
+ if m != nil {
+ m.entitlementVersionRegression.WithLabelValues(source).Inc()
+ }
+}
+
+func (m *BusinessMetrics) RecordAutopilotQuotaDecision(action, source, result string) {
+ if m == nil {
+ return
+ }
+ switch source {
+ case "schedule", "webhook", "manual", "api":
+ default:
+ source = "other"
+ }
+ m.autopilotQuotaDecision.WithLabelValues(action, source, result).Inc()
+}
+
func (m *BusinessMetrics) RecordRuntimeGCDeleted() {
if m == nil {
return
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index 978ae47f70..14159fd3a9 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -176,6 +176,12 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
m.RecordCloudRuntimeRequest("provision", "ok", 0.5)
m.RecordDaemonWSMessageReceived("heartbeat")
m.RecordChatOutputLocalPath("file_url")
+ m.RecordEntitlementConfigError()
+ m.RecordEntitlementCache("hit")
+ m.RecordEntitlementRefresh("success", 0.01)
+ m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")
+ m.RecordEntitlementVersionRegression("refresh")
+ m.RecordAutopilotQuotaDecision("observe", "manual", "admitted")
families, err := registry.Gather()
if err != nil {
@@ -190,6 +196,9 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
t.Fatalf("registry did not expose metric family %s", metric)
}
}
+ if !seen["multica_entitlement_config_error_total"] {
+ t.Fatal("registry did not expose metric family multica_entitlement_config_error_total")
+ }
}
func TestBusinessMetricsRuntimeGC(t *testing.T) {
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 8f3911e02e..56db51f68e 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -33,6 +33,7 @@ const (
labelQuery = "query"
labelOp = "op"
labelGate = "gate"
+ labelOutcome = "outcome"
)
var businessMetricLabels = map[string][]string{
@@ -91,6 +92,12 @@ var businessMetricLabels = map[string][]string{
"multica_feedback_submitted_total": {labelKind, labelPlatform},
"multica_contact_sales_submitted_total": {labelSource},
"multica_chat_output_local_path_total": {labelKind},
+ "multica_entitlement_cache_total": {labelOutcome},
+ "multica_entitlement_refresh_total": {labelOutcome},
+ "multica_entitlement_refresh_duration_seconds": {labelOutcome},
+ "multica_entitlement_decision_total": {labelGate, labelAction, labelReason},
+ "multica_entitlement_version_regression_total": {labelSource},
+ "multica_autopilot_quota_decision_total": {labelAction, labelSource, labelResult},
}
var forbiddenMetricLabels = map[string]struct{}{
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 63360ab91b..8b8fc31625 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -16,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/attribution"
"github.com/multica-ai/multica/server/internal/dispatch"
+ "github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/issueposition"
@@ -32,10 +33,12 @@ type TxStarter interface {
}
type AutopilotService struct {
- Queries *db.Queries
- TxStarter TxStarter
- Bus *events.Bus
- TaskSvc *TaskService
+ Queries *db.Queries
+ TxStarter TxStarter
+ Bus *events.Bus
+ TaskSvc *TaskService
+ Entitlements entitlement.Provider
+ QuotaMetrics AutopilotQuotaMetrics
}
// DefaultAutopilotTriggerTimezone is the timezone used to render Autopilot
@@ -124,7 +127,7 @@ func (s *AutopilotService) DispatchAutopilot(
// callers don't surface a per-run reason code to a human, so it is 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{})
+ run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{}, pgtype.UUID{}, source+":"+newAutopilotIdempotencyKey())
return run, err
}
@@ -140,11 +143,25 @@ func (s *AutopilotService) DispatchAutopilotManual(
triggerID pgtype.UUID,
payload []byte,
actorUserID pgtype.UUID,
+) (*db.AutopilotRun, dispatch.ReasonCode, error) {
+ return s.DispatchAutopilotManualWithKey(ctx, autopilot, triggerID, payload, actorUserID, newAutopilotIdempotencyKey())
+}
+
+// DispatchAutopilotManualWithKey preserves a caller-supplied request key so
+// retrying the same HTTP request cannot reserve or execute twice.
+func (s *AutopilotService) DispatchAutopilotManualWithKey(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ payload []byte,
+ actorUserID pgtype.UUID,
+ idempotencyKey string,
) (*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.
- return s.dispatchAutopilot(ctx, autopilot, triggerID, "manual", payload, pgtype.Timestamptz{}, pgtype.UUID{}, actorUserID)
+ key := "manual:" + util.UUIDToString(autopilot.ID) + ":" + idempotencyKey
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, "manual", payload, pgtype.Timestamptz{}, pgtype.UUID{}, actorUserID, key)
}
// AdmitAutopilotWebhookDelivery creates or reuses the idempotent run for a
@@ -198,7 +215,7 @@ func (s *AutopilotService) AdmitAutopilotWebhookDelivery(
if autopilot.ExecutionMode == "run_only" {
initialStatus = "running"
}
- run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
+ run, _, err := s.createAutopilotRunWithQuota(ctx, autopilot.WorkspaceID, "webhook", "webhook:"+util.UUIDToString(deliveryID), db.CreateAutopilotRunParams{
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: "webhook",
@@ -268,20 +285,12 @@ func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(
// while linking task_id back to the run. Repair that linkage and wake the
// daemon; otherwise continue the same partial run below.
if autopilot.ExecutionMode == "run_only" && !run.TaskID.Valid {
- task, taskErr := s.Queries.GetAutopilotTaskByRun(ctx, run.ID)
- switch {
- case taskErr == nil:
- updated, updateErr := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{
- ID: run.ID,
- TaskID: task.ID,
- })
- if updateErr != nil {
- return run, fmt.Errorf("dispatch for webhook delivery: repair task linkage: %w", updateErr)
- }
- s.TaskSvc.NotifyTaskEnqueued(ctx, task)
- return &updated, nil
- case !errors.Is(taskErr, pgx.ErrNoRows):
- return run, fmt.Errorf("dispatch for webhook delivery: lookup linked task: %w", taskErr)
+ repaired, found, repairErr := s.repairAutopilotRunTaskLink(ctx, *run)
+ if repairErr != nil {
+ return run, fmt.Errorf("dispatch for webhook delivery: %w", repairErr)
+ }
+ if found {
+ return repaired, nil
}
}
// Webhook worker dispatch has no member actor and no human reason-code
@@ -326,6 +335,38 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, aut
return nil
}
+// repairAutopilotRunTaskLink closes the run_only crash window where task
+// creation committed but autopilot_run.task_id did not. Finding any task is
+// proof that downstream ownership already moved; active work is re-woken and
+// terminal work is replayed through the normal finalizer instead of duplicated.
+func (s *AutopilotService) repairAutopilotRunTaskLink(ctx context.Context, run db.AutopilotRun) (*db.AutopilotRun, bool, error) {
+ task, err := s.Queries.GetAutopilotTaskByRun(ctx, run.ID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, false, nil
+ }
+ if err != nil {
+ return nil, false, fmt.Errorf("lookup linked task: %w", err)
+ }
+ updated, err := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{
+ ID: run.ID,
+ TaskID: task.ID,
+ })
+ if err != nil {
+ return nil, false, fmt.Errorf("repair task linkage: %w", err)
+ }
+ switch task.Status {
+ case "completed", "failed", "cancelled":
+ s.SyncRunFromTask(ctx, task)
+ updated, err = s.Queries.GetAutopilotRun(ctx, run.ID)
+ if err != nil {
+ return nil, false, fmt.Errorf("reload terminal repaired run: %w", err)
+ }
+ default:
+ s.TaskSvc.NotifyTaskEnqueued(ctx, task)
+ }
+ return &updated, true, nil
+}
+
// 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
@@ -387,6 +428,15 @@ func (s *AutopilotService) DispatchAutopilotForPlan(
return &existing, nil
case err == nil:
+ if autopilot.ExecutionMode == "run_only" && !existing.TaskID.Valid {
+ repaired, found, repairErr := s.repairAutopilotRunTaskLink(ctx, existing)
+ if repairErr != nil {
+ return nil, fmt.Errorf("dispatch for plan: %w", repairErr)
+ }
+ if found {
+ return repaired, 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.
@@ -398,9 +448,13 @@ func (s *AutopilotService) DispatchAutopilotForPlan(
"issue_set", existing.IssueID.Valid,
"task_set", existing.TaskID.Valid,
)
- if err := s.Queries.RecoverPartialAutopilotRun(ctx, existing.ID); err != nil {
+ recovered, err := s.recoverPartialAutopilotRun(ctx, existing)
+ if err != nil {
return nil, fmt.Errorf("dispatch for plan: recover partial run: %w", err)
}
+ if !recovered {
+ return nil, fmt.Errorf("dispatch for plan: partial run changed concurrently; retry")
+ }
// Fall through to a fresh dispatch below.
case !errors.Is(err, pgx.ErrNoRows):
@@ -410,7 +464,8 @@ func (s *AutopilotService) DispatchAutopilotForPlan(
// Scheduled dispatch has no member actor → rule_owner attribution, and no
// human surface for a per-run reason code, so it is dropped. No webhook
// delivery on the scheduled-plan path.
- run, _, err := s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{}, pgtype.UUID{})
+ 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)
return run, err
}
@@ -463,6 +518,7 @@ func (s *AutopilotService) dispatchAutopilot(
plannedAt pgtype.Timestamptz,
webhookDeliveryID pgtype.UUID,
actorUserID pgtype.UUID,
+ idempotencyKey string,
) (*db.AutopilotRun, dispatch.ReasonCode, error) {
if reason, code, skip := s.shouldSkipDispatch(ctx, autopilot, actorUserID); skip {
run, err := s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)
@@ -475,7 +531,7 @@ func (s *AutopilotService) dispatchAutopilot(
initialStatus = "running"
}
- run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
+ run, reused, err := s.createAutopilotRunWithQuota(ctx, autopilot.WorkspaceID, source, idempotencyKey, db.CreateAutopilotRunParams{
AutopilotID: autopilot.ID,
TriggerID: triggerID,
Source: source,
@@ -486,8 +542,16 @@ func (s *AutopilotService) dispatchAutopilot(
WebhookDeliveryID: webhookDeliveryID,
})
if err != nil {
+ var quotaErr *AutopilotQuotaExceededError
+ if errors.As(err, &quotaErr) && source == "schedule" {
+ skipped, skipErr := s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, quotaErr.Error(), dispatch.ReasonQuotaExceeded)
+ return skipped, dispatch.ReasonQuotaExceeded, skipErr
+ }
return nil, dispatch.ReasonInternalError, fmt.Errorf("create run: %w", err)
}
+ if reused {
+ return &run, dispatch.ReasonCode(run.ReasonCode.String), nil
+ }
s.captureAutopilotRunStarted(autopilot, run, source)
return s.dispatchAutopilotRun(ctx, autopilot, triggerID, source, &run, actorUserID)
}
@@ -676,6 +740,9 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
return fmt.Errorf("link run to issue: %w", err)
}
*run = updatedRun
+ if _, err := settleAutopilotQuota(ctx, qtx, run.QuotaReservationID, true); err != nil {
+ return fmt.Errorf("consume quota reservation: %w", err)
+ }
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit tx: %w", err)
@@ -983,7 +1050,7 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
switch effectiveStatus {
case "done", "in_review":
- updatedRun, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
+ updatedRun, err := s.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{
ID: run.ID,
})
if err != nil {
@@ -994,7 +1061,7 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
s.publishRunDone(wsID, updatedRun, "completed")
case "cancelled", "blocked":
reason := "issue " + issue.Status
- updatedRun, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ updatedRun, err := s.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: true},
})
@@ -1026,7 +1093,7 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
switch task.Status {
case "completed":
- updatedRun, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
+ updatedRun, err := s.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{
ID: run.ID,
Result: task.Result,
})
@@ -1041,7 +1108,7 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
if task.Error.Valid {
reason = task.Error.String
}
- updatedRun, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ updatedRun, err := s.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: true},
})
@@ -1100,7 +1167,7 @@ func (s *AutopilotService) SyncRunFromLinkedIssueTask(ctx context.Context, task
}
reason := taskFailureReasonForAutopilotRun(task)
- updatedRun, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ updatedRun, err := s.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: reason != ""},
})
@@ -1141,9 +1208,10 @@ func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopil
if !errors.As(err, &skipErr) {
return nil, ""
}
- updated, uerr := s.Queries.UpdateAutopilotRunSkipped(ctx, db.UpdateAutopilotRunSkippedParams{
+ updated, uerr := s.skipAutopilotRun(ctx, db.UpdateAutopilotRunSkippedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: skipErr.reason, Valid: true},
+ ReasonCode: pgtype.Text{String: string(skipErr.code), Valid: skipErr.code != ""},
})
if uerr != nil {
slog.Warn("failed to mark dispatch as skipped",
@@ -1169,9 +1237,10 @@ func (s *AutopilotService) handleDispatchSkip(ctx context.Context, ap db.Autopil
}
func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reason string) {
- if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ if _, err := s.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
ID: runID,
FailureReason: pgtype.Text{String: reason, Valid: true},
+ ReasonCode: pgtype.Text{String: string(dispatch.ReasonInternalError), Valid: true},
}); err != nil {
slog.Warn("failed to mark autopilot run as failed", "run_id", util.UUIDToString(runID), "error", err)
}
@@ -1369,7 +1438,12 @@ func (s *AutopilotService) recordSkippedRun(
plannedAt pgtype.Timestamptz,
webhookDeliveryID pgtype.UUID,
reason string,
+ reasonCode ...dispatch.ReasonCode,
) (*db.AutopilotRun, error) {
+ code := pgtype.Text{}
+ if len(reasonCode) > 0 && reasonCode[0] != "" {
+ code = pgtype.Text{String: string(reasonCode[0]), Valid: true}
+ }
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
AutopilotID: autopilot.ID,
TriggerID: triggerID,
@@ -1379,6 +1453,7 @@ func (s *AutopilotService) recordSkippedRun(
SquadID: autopilotSquadAttribution(autopilot),
PlannedAt: plannedAt,
WebhookDeliveryID: webhookDeliveryID,
+ ReasonCode: code,
})
if err != nil {
return nil, fmt.Errorf("create skipped run: %w", err)
@@ -1387,6 +1462,7 @@ func (s *AutopilotService) recordSkippedRun(
updated, err := s.Queries.UpdateAutopilotRunSkipped(ctx, db.UpdateAutopilotRunSkippedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: true},
+ ReasonCode: code,
})
if err == nil {
run = updated
diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.go
new file mode 100644
index 0000000000..017a0b5b04
--- /dev/null
+++ b/server/internal/service/autopilot_quota.go
@@ -0,0 +1,396 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// AutopilotQuotaMetrics deliberately accepts only bounded labels. Workspace
+// identifiers and policy values must never be metric labels.
+type AutopilotQuotaMetrics interface {
+ RecordAutopilotQuotaDecision(action, source, result string)
+}
+
+// AutopilotQuotaExceededError is returned only for an enforce decision whose
+// Cloud-provided interval is full. HTTP callers can serialize the facts without
+// embedding commercial copy or plan names in OSS.
+type AutopilotQuotaExceededError struct {
+ Used int64
+ Reserved int64
+ Limit int64
+ ResetAt time.Time
+}
+
+func (e *AutopilotQuotaExceededError) Error() string {
+ return "autopilot run quota exceeded"
+}
+
+// AutopilotQuotaUsage is the workspace-scoped, policy-neutral API model.
+// A disabled/malformed decision returns Enabled=false and leaves all facts nil.
+type AutopilotQuotaUsage struct {
+ Enabled bool
+ Action string
+ Used *int64
+ Reserved *int64
+ Limit *int64
+ PeriodStart *time.Time
+ PeriodEnd *time.Time
+ ResetAt *time.Time
+ BlockedCounts map[string]int64
+}
+
+type autopilotQuotaPolicy struct {
+ action entitlement.Action
+ limit int64
+ periodStart time.Time
+ periodEnd time.Time
+ resetAt time.Time
+ policyRevision int64
+ subscriptionVersion int64
+}
+
+func newAutopilotIdempotencyKey() string { return uuid.NewString() }
+
+// NewRequestIdempotencyKey is used only when an HTTP caller omitted its key;
+// the generated value scopes idempotency to that single request.
+func NewRequestIdempotencyKey() string { return newAutopilotIdempotencyKey() }
+
+func validAutopilotExecutionSource(source string) bool {
+ switch source {
+ case "schedule", "manual", "webhook", "api":
+ return true
+ default:
+ return false
+ }
+}
+
+func (s *AutopilotService) quotaPolicy(ctx context.Context, workspaceID pgtype.UUID) (autopilotQuotaPolicy, bool) {
+ if s.Entitlements == nil || !workspaceID.Valid {
+ return autopilotQuotaPolicy{}, false
+ }
+ decision := s.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateAutopilotRuns)
+ gate := decision.Gate
+ if gate.Action == entitlement.ActionOff {
+ return autopilotQuotaPolicy{}, false
+ }
+ if (gate.Action != entitlement.ActionObserve && gate.Action != entitlement.ActionEnforce) ||
+ gate.Limit == nil || *gate.Limit < 0 || gate.PeriodStart == nil || gate.PeriodEnd == nil ||
+ gate.ResetAt == nil || !gate.PeriodStart.Before(*gate.PeriodEnd) {
+ // A malformed policy is fail-open and, critically, performs no quota-table
+ // access. Cloud remains the sole authority over interval construction.
+ return autopilotQuotaPolicy{}, false
+ }
+ return autopilotQuotaPolicy{
+ action: gate.Action,
+ limit: int64(*gate.Limit),
+ periodStart: gate.PeriodStart.UTC(),
+ periodEnd: gate.PeriodEnd.UTC(),
+ resetAt: gate.ResetAt.UTC(),
+ policyRevision: decision.PolicyRevision,
+ subscriptionVersion: decision.SubscriptionVersion,
+ }, true
+}
+
+// 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.
+func (s *AutopilotService) createAutopilotRunWithQuota(
+ 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)
+ }
+ policy, enabled := s.quotaPolicy(ctx, workspaceID)
+ if !enabled {
+ run, err := s.Queries.CreateAutopilotRun(ctx, params)
+ return run, false, err
+ }
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("begin quota admission: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.Queries.WithTx(tx)
+ periodArgs := db.EnsureAutopilotQuotaPeriodParams{
+ WorkspaceID: workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},
+ }
+ period, err := qtx.EnsureAutopilotQuotaPeriod(ctx, periodArgs)
+ if err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("lock quota period: %w", err)
+ }
+
+ existing, err := qtx.GetAutopilotQuotaReservationByKey(ctx, db.GetAutopilotQuotaReservationByKeyParams{
+ WorkspaceID: workspaceID,
+ PeriodStart: periodArgs.PeriodStart,
+ PeriodEnd: periodArgs.PeriodEnd,
+ IdempotencyKey: idempotencyKey,
+ })
+ if err == nil {
+ run, runErr := qtx.GetAutopilotRunByQuotaReservation(ctx, existing.ID)
+ if errors.Is(runErr, pgx.ErrNoRows) && existing.State == "reserved" {
+ // The reservation/run insert normally commits atomically. Recover a
+ // manually removed or otherwise orphaned reserved row so the stable
+ // idempotency key does not wedge every retry for the whole period.
+ if _, releaseErr := settleAutopilotQuota(ctx, qtx, existing.ID, false); releaseErr != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("release orphaned idempotency reservation: %w", releaseErr)
+ }
+ period.ReservedCount--
+ err = pgx.ErrNoRows // continue through the normal fresh-reservation path
+ } else if runErr != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("load idempotent quota run: %w", runErr)
+ } else {
+ if err := tx.Commit(ctx); err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("commit idempotent quota admission: %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 quota reservation: %w", err)
+ }
+
+ wouldBlock := period.UsedCount+period.ReservedCount >= policy.limit
+ if wouldBlock && policy.action == entitlement.ActionEnforce {
+ if _, err := qtx.IncrementAutopilotQuotaBlocked(ctx, db.IncrementAutopilotQuotaBlockedParams{
+ Source: source, WorkspaceID: workspaceID,
+ PeriodStart: periodArgs.PeriodStart, PeriodEnd: periodArgs.PeriodEnd,
+ }); err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("record blocked quota admission: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("commit blocked quota admission: %w", err)
+ }
+ s.recordAutopilotQuotaDecision(policy.action, source, "blocked")
+ return db.AutopilotRun{}, false, &AutopilotQuotaExceededError{
+ Used: period.UsedCount, Reserved: period.ReservedCount,
+ Limit: policy.limit, ResetAt: policy.resetAt,
+ }
+ }
+ // Observe-only would-blocks stay in the bounded decision metric. Durable
+ // blocked counts back the usage API only for decisions that reject work.
+ reservation, err := qtx.CreateAutopilotQuotaReservation(ctx, db.CreateAutopilotQuotaReservationParams{
+ WorkspaceID: workspaceID, PeriodStart: periodArgs.PeriodStart, PeriodEnd: periodArgs.PeriodEnd,
+ PolicyRevision: policy.policyRevision, SubscriptionVersion: policy.subscriptionVersion,
+ Source: source, IdempotencyKey: idempotencyKey,
+ })
+ if err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("create quota reservation: %w", err)
+ }
+ if _, err := qtx.IncrementAutopilotQuotaReserved(ctx, db.IncrementAutopilotQuotaReservedParams{
+ WorkspaceID: periodArgs.WorkspaceID, PeriodStart: periodArgs.PeriodStart, PeriodEnd: periodArgs.PeriodEnd,
+ }); err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("increment reserved quota: %w", err)
+ }
+ params.QuotaReservationID = reservation.ID
+ run, err := qtx.CreateAutopilotRun(ctx, params)
+ if err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("create quota-linked run: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.AutopilotRun{}, false, fmt.Errorf("commit quota admission: %w", err)
+ }
+ result := "admitted"
+ if wouldBlock {
+ result = "would_block"
+ }
+ s.recordAutopilotQuotaDecision(policy.action, source, result)
+ return run, false, nil
+}
+
+func (s *AutopilotService) recordAutopilotQuotaDecision(action entitlement.Action, source, result string) {
+ if s.QuotaMetrics != nil {
+ s.QuotaMetrics.RecordAutopilotQuotaDecision(string(action), source, result)
+ }
+}
+
+func settleAutopilotQuota(ctx context.Context, q *db.Queries, reservationID pgtype.UUID, consume bool) (bool, error) {
+ if !reservationID.Valid {
+ return false, nil
+ }
+ var err error
+ if consume {
+ _, err = q.ConsumeAutopilotQuotaReservation(ctx, reservationID)
+ } else {
+ _, err = q.ReleaseAutopilotQuotaReservation(ctx, reservationID)
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil // terminal replay: reservation already finalized
+ }
+ return err == nil, err
+}
+
+func (s *AutopilotService) completeAutopilotRun(ctx context.Context, params db.UpdateAutopilotRunCompletedParams) (db.AutopilotRun, error) {
+ row, err := s.Queries.UpdateAutopilotRunTerminalWithQuota(ctx, db.UpdateAutopilotRunTerminalWithQuotaParams{
+ TerminalStatus: "completed",
+ Result: params.Result,
+ RunID: params.ID,
+ Consume: true,
+ })
+ return autopilotRunFromTerminalRow(row), err
+}
+
+func (s *AutopilotService) failAutopilotRun(ctx context.Context, params db.UpdateAutopilotRunFailedParams) (db.AutopilotRun, error) {
+ row, err := s.Queries.UpdateAutopilotRunTerminalWithQuota(ctx, db.UpdateAutopilotRunTerminalWithQuotaParams{
+ TerminalStatus: "failed",
+ FailureReason: params.FailureReason,
+ ReasonCode: params.ReasonCode,
+ RunID: params.ID,
+ })
+ return autopilotRunFromTerminalRow(row), err
+}
+
+func (s *AutopilotService) skipAutopilotRun(ctx context.Context, params db.UpdateAutopilotRunSkippedParams) (db.AutopilotRun, error) {
+ row, err := s.Queries.UpdateAutopilotRunTerminalWithQuota(ctx, db.UpdateAutopilotRunTerminalWithQuotaParams{
+ TerminalStatus: "skipped",
+ FailureReason: params.FailureReason,
+ ReasonCode: params.ReasonCode,
+ RunID: params.ID,
+ })
+ return autopilotRunFromTerminalRow(row), err
+}
+
+func autopilotRunFromTerminalRow(row db.UpdateAutopilotRunTerminalWithQuotaRow) db.AutopilotRun {
+ return db.AutopilotRun{
+ ID: row.ID, AutopilotID: row.AutopilotID, TriggerID: row.TriggerID,
+ Source: row.Source, Status: row.Status, IssueID: row.IssueID, TaskID: row.TaskID,
+ TriggeredAt: row.TriggeredAt, CompletedAt: row.CompletedAt,
+ FailureReason: row.FailureReason, TriggerPayload: row.TriggerPayload,
+ Result: row.Result, CreatedAt: row.CreatedAt, SquadID: row.SquadID,
+ PlannedAt: row.PlannedAt, WebhookDeliveryID: row.WebhookDeliveryID,
+ QuotaReservationID: row.QuotaReservationID, ReasonCode: row.ReasonCode,
+ }
+}
+
+func (s *AutopilotService) recoverPartialAutopilotRun(ctx context.Context, run db.AutopilotRun) (bool, error) {
+ rows, err := s.Queries.RecoverPartialAutopilotRun(ctx, run.ID)
+ return rows > 0, err
+}
+
+// FailAutopilotRunsByIssue keeps create_issue consumption immutable while
+// releasing any still-reserved run_only slots before deletion clears issue_id.
+func (s *AutopilotService) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.UUID) error {
+ _, err := s.Queries.FailAutopilotRunsByIssue(ctx, issueID)
+ return err
+}
+
+func (s *AutopilotService) AutopilotQuotaUsage(ctx context.Context, workspaceID pgtype.UUID) (AutopilotQuotaUsage, error) {
+ policy, enabled := s.quotaPolicy(ctx, workspaceID)
+ if !enabled {
+ return AutopilotQuotaUsage{Enabled: false}, nil
+ }
+ period, err := s.Queries.GetAutopilotQuotaPeriod(ctx, db.GetAutopilotQuotaPeriodParams{
+ WorkspaceID: workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ period.UsedCount = 0
+ period.ReservedCount = 0
+ } else if err != nil {
+ return AutopilotQuotaUsage{}, fmt.Errorf("load autopilot quota usage: %w", err)
+ }
+ blockedCounts := make(map[string]int64)
+ if len(period.BlockedCounts) > 0 {
+ if err := json.Unmarshal(period.BlockedCounts, &blockedCounts); err != nil {
+ return AutopilotQuotaUsage{}, fmt.Errorf("decode autopilot quota blocked counts: %w", err)
+ }
+ if blockedCounts == nil {
+ blockedCounts = make(map[string]int64)
+ }
+ }
+ return AutopilotQuotaUsage{
+ Enabled: true, Action: string(policy.action),
+ Used: &period.UsedCount, Reserved: &period.ReservedCount, Limit: &policy.limit,
+ PeriodStart: &policy.periodStart, PeriodEnd: &policy.periodEnd, ResetAt: &policy.resetAt,
+ BlockedCounts: blockedCounts,
+ }, nil
+}
+
+func (s *AutopilotService) QuotaEnabled() bool { return s.Entitlements != nil }
+
+// ReconcileAutopilotQuotaReservations repairs crash windows left after a
+// reservation/run transaction but before the downstream side effect or normal
+// finalizer. The reservation transition remains CAS-based, so replicas may run
+// this concurrently without double-adjusting counters.
+func (s *AutopilotService) ReconcileAutopilotQuotaReservations(
+ ctx context.Context,
+ terminalCreatedBefore time.Time,
+ partialCreatedBefore time.Time,
+ limit int32,
+) (int, error) {
+ if !s.QuotaEnabled() || limit <= 0 {
+ return 0, nil
+ }
+ reservations, err := s.Queries.ListRecoverableAutopilotQuotaReservations(ctx, db.ListRecoverableAutopilotQuotaReservationsParams{
+ TerminalCreatedBefore: pgtype.Timestamptz{Time: terminalCreatedBefore.UTC(), Valid: true},
+ PartialCreatedBefore: pgtype.Timestamptz{Time: partialCreatedBefore.UTC(), Valid: true},
+ RowLimit: limit,
+ })
+ if err != nil {
+ return 0, fmt.Errorf("list recoverable quota reservations: %w", err)
+ }
+ settled := 0
+ for _, reservation := range reservations {
+ run, runErr := s.Queries.GetAutopilotRunByQuotaReservation(ctx, reservation.ID)
+ switch {
+ case errors.Is(runErr, pgx.ErrNoRows):
+ changed, err := settleAutopilotQuota(ctx, s.Queries, reservation.ID, false)
+ if err != nil {
+ return settled, fmt.Errorf("release orphan quota reservation: %w", err)
+ }
+ if !changed {
+ continue
+ }
+ case runErr != nil:
+ return settled, fmt.Errorf("load quota-linked run: %w", runErr)
+ case run.Status == "completed":
+ changed, err := settleAutopilotQuota(ctx, s.Queries, reservation.ID, true)
+ if err != nil {
+ return settled, fmt.Errorf("consume completed quota reservation: %w", err)
+ }
+ if !changed {
+ continue
+ }
+ case run.Status == "failed" || run.Status == "skipped":
+ changed, err := settleAutopilotQuota(ctx, s.Queries, reservation.ID, false)
+ if err != nil {
+ return settled, fmt.Errorf("release terminal quota reservation: %w", err)
+ }
+ if !changed {
+ continue
+ }
+ case (run.Source == "manual" || run.Source == "api") &&
+ !run.IssueID.Valid && !run.TaskID.Valid &&
+ (run.Status == "pending" || run.Status == "issue_created" || run.Status == "running"):
+ changed, err := s.recoverPartialAutopilotRun(ctx, run)
+ if err != nil {
+ return settled, fmt.Errorf("recover abandoned quota run: %w", err)
+ }
+ if !changed {
+ continue
+ }
+ default:
+ // Schedule and webhook retries own their partial-state recovery. The
+ // query excludes them so this branch is only a defensive guard.
+ continue
+ }
+ settled++
+ }
+ return settled, nil
+}
diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.go
new file mode 100644
index 0000000000..00f25b0d73
--- /dev/null
+++ b/server/internal/service/autopilot_quota_test.go
@@ -0,0 +1,640 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type autopilotQuotaFixture struct {
+ pool *pgxpool.Pool
+ queries *db.Queries
+ service *AutopilotService
+ stub *entitlementtest.Stub
+ workspace uuid.UUID
+ workspaceID pgtype.UUID
+ autopilotID pgtype.UUID
+ agentID pgtype.UUID
+ publisherID pgtype.UUID
+ issueID pgtype.UUID
+ periodStart time.Time
+ periodEnd time.Time
+ resetAt time.Time
+ policyLimit int
+ createRunArgs db.CreateAutopilotRunParams
+}
+
+type autopilotQuotaMetricsRecorder struct {
+ mu sync.Mutex
+ decisions map[string]int
+}
+
+func (m *autopilotQuotaMetricsRecorder) RecordAutopilotQuotaDecision(action, source, result string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.decisions == nil {
+ m.decisions = make(map[string]int)
+ }
+ m.decisions[action+"\x00"+source+"\x00"+result]++
+}
+
+func (m *autopilotQuotaMetricsRecorder) count(action, source, result string) int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return m.decisions[action+"\x00"+source+"\x00"+result]
+}
+
+func newAutopilotQuotaFixture(t *testing.T, action entitlement.Action, limit int) *autopilotQuotaFixture {
+ t.Helper()
+ pool := newResolveOriginatorPool(t)
+ q := db.New(pool)
+ workspaceIDString, publisherID, agentID, issueIDString := seedAttributionFixture(t, pool)
+ autopilotIDString, _ := seedRunOnlyAutopilot(t, pool, workspaceIDString, agentID, publisherID)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ workspace := uuid.UUID(workspaceID.Bytes)
+ periodStart := time.Now().UTC().Truncate(time.Second)
+ periodEnd := periodStart.Add(37 * time.Hour)
+ stub := entitlementtest.New()
+ fixture := &autopilotQuotaFixture{
+ pool: pool, queries: q, stub: stub, workspace: workspace,
+ workspaceID: workspaceID, autopilotID: util.MustParseUUID(autopilotIDString),
+ agentID: util.MustParseUUID(agentID), publisherID: util.MustParseUUID(publisherID),
+ issueID: util.MustParseUUID(issueIDString),
+ periodStart: periodStart, periodEnd: periodEnd, resetAt: periodEnd,
+ policyLimit: limit,
+ createRunArgs: db.CreateAutopilotRunParams{
+ AutopilotID: util.MustParseUUID(autopilotIDString), Source: "api", Status: "running",
+ },
+ }
+ fixture.service = &AutopilotService{
+ Queries: q, TxStarter: pool, Bus: events.New(), Entitlements: stub,
+ }
+ fixture.setPolicy(action, periodStart, periodEnd, limit)
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_reservation WHERE workspace_id = $1`, workspaceID)
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, workspaceID)
+ })
+ return fixture
+}
+
+func (f *autopilotQuotaFixture) setPolicy(action entitlement.Action, start, end time.Time, limit int) {
+ f.stub.Set(f.workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: action, Limit: &limit,
+ PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,
+ },
+ PolicyRevision: 7, SubscriptionVersion: 11,
+ })
+}
+
+func TestAutopilotQuotaDisabledDoesNotReadQuotaTables(t *testing.T) {
+ ctx := context.Background()
+ workspace := uuid.New()
+ workspaceID := pgtype.UUID{Bytes: workspace, Valid: true}
+
+ t.Run("off", func(t *testing.T) {
+ stub := entitlementtest.New()
+ stub.Set(workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionOff},
+ })
+ svc := &AutopilotService{Entitlements: stub} // Queries intentionally nil
+ usage, err := svc.AutopilotQuotaUsage(ctx, workspaceID)
+ if err != nil || usage.Enabled {
+ t.Fatalf("off usage = %+v, %v; want disabled", usage, err)
+ }
+ })
+
+ t.Run("malformed", func(t *testing.T) {
+ stub := entitlementtest.New()
+ limit := 2
+ stub.Set(workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},
+ })
+ svc := &AutopilotService{Entitlements: stub} // missing interval; Queries intentionally nil
+ usage, err := svc.AutopilotQuotaUsage(ctx, workspaceID)
+ if err != nil || usage.Enabled {
+ t.Fatalf("malformed usage = %+v, %v; want fail-open disabled", usage, err)
+ }
+ })
+}
+
+func TestAutopilotQuotaRejectsUnknownExecutionSource(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ context.Background(), fixture.workspaceID, "manul", "invalid-source", fixture.createRunArgs,
+ )
+ if err == nil || !strings.Contains(err.Error(), "invalid autopilot execution source") {
+ t.Fatalf("unknown source error = %v, want application validation", err)
+ }
+}
+
+func TestAutopilotQuotaEnforcesBoundaryAndFinalizesIdempotently(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceIDString, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+ autopilotIDString, _ := seedRunOnlyAutopilot(t, pool, workspaceIDString, agentID, publisherID)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ autopilotID := util.MustParseUUID(autopilotIDString)
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_reservation WHERE workspace_id = $1`, workspaceID)
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, workspaceID)
+ })
+
+ periodStart := time.Now().UTC().Truncate(time.Second)
+ periodEnd := periodStart.Add(37 * time.Hour) // opaque Cloud interval, deliberately not a calendar month
+ resetAt := periodEnd
+ limit := 2
+ stub := entitlementtest.New()
+ stub.Set(uuid.UUID(workspaceID.Bytes), entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, Limit: &limit,
+ PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &resetAt,
+ },
+ PolicyRevision: 7, SubscriptionVersion: 11,
+ })
+ svc := &AutopilotService{Queries: q, TxStarter: pool, Bus: events.New(), Entitlements: stub}
+ params := db.CreateAutopilotRunParams{
+ AutopilotID: autopilotID, Source: "api", Status: "running",
+ }
+
+ runs := make([]db.AutopilotRun, 0, limit)
+ for i, key := range []string{"boundary-1", "boundary-2"} {
+ run, _, err := svc.createAutopilotRunWithQuota(ctx, workspaceID, "api", key, params)
+ if err != nil {
+ t.Fatalf("admission %d: %v", i+1, err)
+ }
+ runs = append(runs, run)
+ }
+ reused, wasReused, err := svc.createAutopilotRunWithQuota(ctx, workspaceID, "api", "boundary-1", params)
+ if err != nil || !wasReused || reused.ID.Bytes != runs[0].ID.Bytes {
+ t.Fatalf("idempotent reuse = %s, %v; want %s", util.UUIDToString(reused.ID), err, util.UUIDToString(runs[0].ID))
+ }
+ _, _, err = svc.createAutopilotRunWithQuota(ctx, workspaceID, "api", "boundary-3", params)
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("N+1 admission error = %v, want quota exceeded", err)
+ }
+
+ usage, err := svc.AutopilotQuotaUsage(ctx, workspaceID)
+ if err != nil || usage.Used == nil || usage.Reserved == nil || *usage.Used != 0 || *usage.Reserved != int64(limit) {
+ t.Fatalf("reserved usage = %+v, %v", usage, err)
+ }
+ if got := usage.BlockedCounts["api"]; got != 1 {
+ t.Fatalf("blocked API count = %d, want 1", got)
+ }
+ if _, err := settleAutopilotQuota(ctx, q, runs[0].QuotaReservationID, true); err != nil {
+ t.Fatalf("consume: %v", err)
+ }
+ if _, err := settleAutopilotQuota(ctx, q, runs[0].QuotaReservationID, true); err != nil {
+ t.Fatalf("duplicate consume: %v", err)
+ }
+ if _, err := settleAutopilotQuota(ctx, q, runs[1].QuotaReservationID, false); err != nil {
+ t.Fatalf("release: %v", err)
+ }
+ // Consumed usage is monotonic: later issue cancellation/deletion cannot
+ // turn a successfully created issue back into quota.
+ if _, err := settleAutopilotQuota(ctx, q, runs[0].QuotaReservationID, false); err != nil {
+ t.Fatalf("release consumed reservation: %v", err)
+ }
+ usage, err = svc.AutopilotQuotaUsage(ctx, workspaceID)
+ if err != nil || *usage.Used != 1 || *usage.Reserved != 0 {
+ t.Fatalf("final usage = %+v, %v; want one immutable consumed unit", usage, err)
+ }
+}
+
+func TestAutopilotQuotaConcurrentAdmissionNeverExceedsLimit(t *testing.T) {
+ const attempts = 25
+ const limit = 5
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, limit)
+ ctx := context.Background()
+ start := make(chan struct{})
+ unexpected := make(chan error, attempts)
+ var admitted atomic.Int64
+ var blocked atomic.Int64
+ var wg sync.WaitGroup
+
+ for i := 0; i < attempts; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", fmt.Sprintf("concurrent-%d", i), fixture.createRunArgs,
+ )
+ if err == nil {
+ admitted.Add(1)
+ return
+ }
+ var quotaErr *AutopilotQuotaExceededError
+ if errors.As(err, &quotaErr) {
+ blocked.Add(1)
+ return
+ }
+ unexpected <- err
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ close(unexpected)
+ for err := range unexpected {
+ t.Errorf("unexpected concurrent admission error: %v", err)
+ }
+ if got := admitted.Load(); got != limit {
+ t.Fatalf("admitted = %d, want %d", got, limit)
+ }
+ if got := blocked.Load(); got != attempts-limit {
+ t.Fatalf("blocked = %d, want %d", got, attempts-limit)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || usage.Reserved == nil || *usage.Reserved != limit || *usage.Used != 0 {
+ t.Fatalf("concurrent usage = %+v, %v; want %d reserved", usage, err, limit)
+ }
+}
+
+func TestAutopilotQuotaObserveToEnforceAndOffFinalization(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionObserve, 1)
+ metrics := &autopilotQuotaMetricsRecorder{}
+ fixture.service.QuotaMetrics = metrics
+ ctx := context.Background()
+ runs := make([]db.AutopilotRun, 0, 2)
+ for i := 0; i < 2; i++ {
+ run, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", fmt.Sprintf("observe-%d", i), fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("observe admission %d: %v", i, err)
+ }
+ runs = append(runs, run)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || usage.Action != string(entitlement.ActionObserve) || *usage.Reserved != 2 {
+ t.Fatalf("observe usage = %+v, %v; want two reservations", usage, err)
+ }
+ if got := metrics.count("observe", "api", "would_block"); got != 1 {
+ t.Fatalf("observed would-block metric = %d, want 1", got)
+ }
+
+ fixture.setPolicy(entitlement.ActionEnforce, fixture.periodStart, fixture.periodEnd, 1)
+ _, _, err = fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "enforce-after-observe", fixture.createRunArgs,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("enforce after observe error = %v, want quota exceeded", err)
+ }
+
+ // Switching the current policy off must not strand reservations created
+ // under observe/enforce. Terminal finalization relies on the persisted slot.
+ fixture.setPolicy(entitlement.ActionOff, fixture.periodStart, fixture.periodEnd, 1)
+ for _, run := range runs {
+ if _, err := fixture.service.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
+ ID: run.ID, FailureReason: pgtype.Text{String: "test cleanup", Valid: true},
+ }); err != nil {
+ t.Fatalf("finalize while policy off: %v", err)
+ }
+ }
+ fixture.setPolicy(entitlement.ActionEnforce, fixture.periodStart, fixture.periodEnd, 1)
+ usage, err = fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || *usage.Used != 0 || *usage.Reserved != 0 {
+ t.Fatalf("usage after off finalization = %+v, %v; want zero", usage, err)
+ }
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "reopened-after-off", fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("admission after reopening policy: %v", err)
+ }
+}
+
+func TestAutopilotQuotaConsumedCreateIssueCannotBeRefunded(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 2)
+ ctx := context.Background()
+
+ cancelled, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "consumed-then-cancelled", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("admit cancelled run: %v", err)
+ }
+ if _, err := settleAutopilotQuota(ctx, fixture.queries, cancelled.QuotaReservationID, true); err != nil {
+ t.Fatalf("consume cancelled run: %v", err)
+ }
+ if _, err := fixture.service.failAutopilotRun(ctx, db.UpdateAutopilotRunFailedParams{
+ ID: cancelled.ID, FailureReason: pgtype.Text{String: "issue cancelled", Valid: true},
+ }); err != nil {
+ t.Fatalf("fail consumed run: %v", err)
+ }
+
+ deleted, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "consumed-then-deleted", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("admit deleted run: %v", err)
+ }
+ deleted, err = fixture.queries.UpdateAutopilotRunIssueCreated(ctx, db.UpdateAutopilotRunIssueCreatedParams{
+ ID: deleted.ID, IssueID: fixture.issueID,
+ })
+ if err != nil {
+ t.Fatalf("link issue-created run: %v", err)
+ }
+ if _, err := settleAutopilotQuota(ctx, fixture.queries, deleted.QuotaReservationID, true); err != nil {
+ t.Fatalf("consume deleted run: %v", err)
+ }
+ if err := fixture.service.FailAutopilotRunsByIssue(ctx, fixture.issueID); err != nil {
+ t.Fatalf("fail runs before issue deletion: %v", err)
+ }
+
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || *usage.Used != 2 || *usage.Reserved != 0 {
+ t.Fatalf("usage after cancellation/deletion = %+v, %v; want two consumed units", usage, err)
+ }
+}
+
+func TestAutopilotQuotaTerminalUpdateNeedsNoTransactionStarter(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionOff, 1)
+ ctx := context.Background()
+ run, err := fixture.queries.CreateAutopilotRun(ctx, fixture.createRunArgs)
+ if err != nil {
+ t.Fatalf("create off-path run: %v", err)
+ }
+ serviceWithoutTx := &AutopilotService{Queries: fixture.queries}
+ updated, err := serviceWithoutTx.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{ID: run.ID})
+ if err != nil {
+ t.Fatalf("complete off-path run: %v", err)
+ }
+ if updated.Status != "completed" || updated.QuotaReservationID.Valid {
+ t.Fatalf("completed off-path run = %+v", updated)
+ }
+}
+
+func TestAutopilotQuotaSettlementStaysInOriginalPeriod(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ ctx := context.Background()
+ run, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "cross-period", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("admit first-period run: %v", err)
+ }
+ secondStart := fixture.periodEnd
+ secondEnd := secondStart.Add(19 * time.Hour)
+ fixture.setPolicy(entitlement.ActionEnforce, secondStart, secondEnd, 1)
+ if _, err := fixture.service.completeAutopilotRun(ctx, db.UpdateAutopilotRunCompletedParams{ID: run.ID}); err != nil {
+ t.Fatalf("complete after period rollover: %v", err)
+ }
+
+ first, err := fixture.queries.GetAutopilotQuotaPeriod(ctx, db.GetAutopilotQuotaPeriodParams{
+ WorkspaceID: fixture.workspaceID,
+ PeriodStart: pgtype.Timestamptz{Time: fixture.periodStart, Valid: true},
+ PeriodEnd: pgtype.Timestamptz{Time: fixture.periodEnd, Valid: true},
+ })
+ if err != nil || first.UsedCount != 1 || first.ReservedCount != 0 {
+ t.Fatalf("first period = %+v, %v; want one consumed", first, err)
+ }
+ second, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || *second.Used != 0 || *second.Reserved != 0 {
+ t.Fatalf("second period usage = %+v, %v; want zero", second, err)
+ }
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "second-period", fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("admit second-period run: %v", err)
+ }
+}
+
+func TestAutopilotQuotaWorkspaceIsolation(t *testing.T) {
+ first := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ second := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ ctx := context.Background()
+ if _, _, err := first.service.createAutopilotRunWithQuota(
+ ctx, first.workspaceID, "api", "isolated", first.createRunArgs,
+ ); err != nil {
+ t.Fatalf("first workspace admission: %v", err)
+ }
+ _, _, err := first.service.createAutopilotRunWithQuota(
+ ctx, first.workspaceID, "api", "isolated-over-limit", first.createRunArgs,
+ )
+ var quotaErr *AutopilotQuotaExceededError
+ if !errors.As(err, &quotaErr) {
+ t.Fatalf("first workspace over-limit error = %v", err)
+ }
+ if _, _, err := second.service.createAutopilotRunWithQuota(
+ ctx, second.workspaceID, "api", "isolated", second.createRunArgs,
+ ); err != nil {
+ t.Fatalf("second workspace admission leaked first usage: %v", err)
+ }
+}
+
+func TestAutopilotQuotaReconcilerSettlesTerminalOnlyOnce(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 2)
+ ctx := context.Background()
+ terminal, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "reconcile-terminal", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("admit terminal run: %v", err)
+ }
+ active, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "reconcile-active", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("admit active run: %v", err)
+ }
+ // Simulate a crash after the run reached terminal state but before the old
+ // two-step finalizer settled its reservation.
+ if _, err := fixture.queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{ID: terminal.ID}); err != nil {
+ t.Fatalf("seed terminal crash window: %v", err)
+ }
+
+ type reconcileResult struct {
+ settled int
+ err error
+ }
+ results := make(chan reconcileResult, 2)
+ for i := 0; i < 2; i++ {
+ go func() {
+ settled, err := fixture.service.ReconcileAutopilotQuotaReservations(
+ ctx, time.Now().Add(time.Minute), time.Now().Add(-6*time.Hour), 10,
+ )
+ results <- reconcileResult{settled: settled, err: err}
+ }()
+ }
+ total := 0
+ for i := 0; i < 2; i++ {
+ result := <-results
+ if result.err != nil {
+ t.Fatalf("reconcile replica %d: %v", i, result.err)
+ }
+ total += result.settled
+ }
+ if total != 1 {
+ t.Fatalf("replicas reported %d settlements, want exactly 1", total)
+ }
+ activeAfter, err := fixture.queries.GetAutopilotRun(ctx, active.ID)
+ if err != nil || activeAfter.Status != "running" {
+ t.Fatalf("active run after reconcile = %+v, %v; want running", activeAfter, err)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || *usage.Used != 1 || *usage.Reserved != 1 {
+ t.Fatalf("reconciled usage = %+v, %v; want one used/one reserved", usage, err)
+ }
+}
+
+func TestAutopilotQuotaReconcilerReleasesOnlyAbandonedManualOrAPIRuns(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 4)
+ ctx := context.Background()
+ create := func(source, key string) db.AutopilotRun {
+ t.Helper()
+ params := fixture.createRunArgs
+ params.Source = source
+ run, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, source, key, params,
+ )
+ if err != nil {
+ t.Fatalf("admit %s partial run: %v", source, err)
+ }
+ return run
+ }
+
+ staleManual := create("manual", "stale-manual")
+ taskBackedAPI := create("api", "task-backed-api")
+ staleWebhook := create("webhook", "stale-webhook")
+ freshAPI := create("api", "fresh-api")
+ agent, err := fixture.queries.GetAgent(ctx, fixture.agentID)
+ if err != nil {
+ t.Fatalf("load task-backed run agent: %v", err)
+ }
+ if _, err := fixture.queries.CreateAutopilotTask(ctx, db.CreateAutopilotTaskParams{
+ AgentID: fixture.agentID,
+ RuntimeID: agent.RuntimeID,
+ AutopilotRunID: taskBackedAPI.ID,
+ OriginatorUserID: fixture.publisherID,
+ AccountableUserID: fixture.publisherID,
+ OriginatorSource: pgtype.Text{String: "direct_human", Valid: true},
+ TriggerEvidenceKind: pgtype.Text{String: "autopilot_run", Valid: true},
+ TriggerEvidenceRefID: taskBackedAPI.ID,
+ }); err != nil {
+ t.Fatalf("create unlinked task evidence: %v", err)
+ }
+ if _, err := fixture.pool.Exec(ctx, `
+ UPDATE autopilot_quota_reservation
+ SET created_at = now() - interval '24 hours'
+ WHERE id = ANY($1::uuid[])`, []uuid.UUID{
+ uuid.UUID(staleManual.QuotaReservationID.Bytes),
+ uuid.UUID(taskBackedAPI.QuotaReservationID.Bytes),
+ uuid.UUID(staleWebhook.QuotaReservationID.Bytes),
+ }); err != nil {
+ t.Fatalf("age partial reservations: %v", err)
+ }
+
+ now := time.Now()
+ settled, err := fixture.service.ReconcileAutopilotQuotaReservations(
+ ctx, now.Add(-10*time.Minute), now.Add(-6*time.Hour), 10,
+ )
+ if err != nil || settled != 1 {
+ t.Fatalf("reconcile abandoned partial runs = %d, %v; want one", settled, err)
+ }
+
+ manualAfter, err := fixture.queries.GetAutopilotRun(ctx, staleManual.ID)
+ if err != nil || manualAfter.Status != "failed" {
+ t.Fatalf("stale manual run = %+v, %v; want failed", manualAfter, err)
+ }
+ for name, run := range map[string]db.AutopilotRun{
+ "durable webhook": staleWebhook,
+ "task-backed api": taskBackedAPI,
+ "fresh api": freshAPI,
+ } {
+ after, err := fixture.queries.GetAutopilotRun(ctx, run.ID)
+ if err != nil || after.Status != "running" {
+ t.Fatalf("%s run = %+v, %v; want running", name, after, err)
+ }
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || usage.Reserved == nil || *usage.Reserved != 3 || *usage.Used != 0 {
+ t.Fatalf("usage after partial recovery = %+v, %v; want three reservations", usage, err)
+ }
+}
+
+func TestAutopilotQuotaIdempotencyRecoversOrphanedReservation(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ ctx := context.Background()
+ first, _, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "orphaned-key", fixture.createRunArgs,
+ )
+ if err != nil {
+ t.Fatalf("first admission: %v", err)
+ }
+ if _, err := fixture.pool.Exec(ctx, `DELETE FROM autopilot_run WHERE id = $1`, first.ID); err != nil {
+ t.Fatalf("remove quota-linked run: %v", err)
+ }
+ recovered, reused, err := fixture.service.createAutopilotRunWithQuota(
+ ctx, fixture.workspaceID, "api", "orphaned-key", fixture.createRunArgs,
+ )
+ if err != nil || reused || recovered.ID.Bytes == first.ID.Bytes {
+ t.Fatalf("orphan recovery = run %s reused=%v err=%v", util.UUIDToString(recovered.ID), reused, err)
+ }
+ usage, err := fixture.service.AutopilotQuotaUsage(ctx, fixture.workspaceID)
+ if err != nil || *usage.Used != 0 || *usage.Reserved != 1 {
+ t.Fatalf("orphan-recovered usage = %+v, %v; want one reservation", usage, err)
+ }
+}
+
+func TestAutopilotQuotaSchedulePersistsSkippedRun(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceIDString, publisherID, agentID, _ := seedAttributionFixture(t, pool)
+ autopilotIDString, _ := seedRunOnlyAutopilot(t, pool, workspaceIDString, agentID, publisherID)
+ workspaceID := util.MustParseUUID(workspaceIDString)
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_reservation WHERE workspace_id = $1`, workspaceID)
+ pool.Exec(context.Background(), `DELETE FROM autopilot_quota_period WHERE workspace_id = $1`, workspaceID)
+ })
+
+ start := time.Now().UTC().Truncate(time.Second)
+ end := start.Add(13 * time.Hour)
+ limit := 0
+ stub := entitlementtest.New()
+ stub.Set(uuid.UUID(workspaceID.Bytes), entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, Limit: &limit,
+ PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,
+ },
+ })
+ autopilot, err := q.GetAutopilot(ctx, util.MustParseUUID(autopilotIDString))
+ if err != nil {
+ t.Fatalf("load autopilot: %v", err)
+ }
+ var triggerID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO autopilot_trigger (autopilot_id, kind, enabled, cron_expression, timezone)
+ VALUES ($1, 'schedule', true, '0 * * * *', 'UTC') RETURNING id`, autopilot.ID).Scan(&triggerID); err != nil {
+ t.Fatalf("create schedule trigger: %v", err)
+ }
+ svc := &AutopilotService{
+ Queries: q, TxStarter: pool, Bus: events.New(),
+ TaskSvc: &TaskService{Queries: q, TxStarter: pool, Bus: events.New()},
+ Entitlements: stub,
+ }
+ run, err := svc.DispatchAutopilotForPlan(ctx, autopilot, triggerID, "schedule", nil, start.Add(time.Minute))
+ if err != nil {
+ t.Fatalf("scheduled dispatch: %v", err)
+ }
+ if run.Status != "skipped" || !run.ReasonCode.Valid || run.ReasonCode.String != "quota_exceeded" {
+ t.Fatalf("scheduled run = status %q reason %q, want skipped/quota_exceeded", run.Status, run.ReasonCode.String)
+ }
+}
diff --git a/server/migrations/352_autopilot_quota_execution.down.sql b/server/migrations/352_autopilot_quota_execution.down.sql
new file mode 100644
index 0000000000..db88b5d59f
--- /dev/null
+++ b/server/migrations/352_autopilot_quota_execution.down.sql
@@ -0,0 +1,10 @@
+ALTER TABLE webhook_delivery
+ DROP COLUMN IF EXISTS replay_idempotency_key,
+ DROP COLUMN IF EXISTS reason_code;
+
+ALTER TABLE autopilot_run
+ DROP COLUMN IF EXISTS reason_code,
+ DROP COLUMN IF EXISTS quota_reservation_id;
+
+DROP TABLE IF EXISTS autopilot_quota_reservation;
+DROP TABLE IF EXISTS autopilot_quota_period;
diff --git a/server/migrations/352_autopilot_quota_execution.up.sql b/server/migrations/352_autopilot_quota_execution.up.sql
new file mode 100644
index 0000000000..537dc4e461
--- /dev/null
+++ b/server/migrations/352_autopilot_quota_execution.up.sql
@@ -0,0 +1,39 @@
+-- Durable, policy-agnostic accounting for the autopilot_runs entitlement gate.
+-- Limits and period boundaries are supplied by Cloud at runtime; no commercial
+-- defaults or calendar assumptions live in this schema.
+
+CREATE TABLE autopilot_quota_period (
+ workspace_id UUID NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ period_end TIMESTAMPTZ NOT NULL,
+ used_count BIGINT NOT NULL DEFAULT 0 CHECK (used_count >= 0),
+ reserved_count BIGINT NOT NULL DEFAULT 0 CHECK (reserved_count >= 0),
+ blocked_counts JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CHECK (period_start < period_end)
+);
+
+CREATE TABLE autopilot_quota_reservation (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ period_start TIMESTAMPTZ NOT NULL,
+ period_end TIMESTAMPTZ NOT NULL,
+ policy_revision BIGINT NOT NULL,
+ subscription_version BIGINT NOT NULL,
+ source TEXT NOT NULL,
+ idempotency_key TEXT NOT NULL,
+ state TEXT NOT NULL DEFAULT 'reserved'
+ CHECK (state IN ('reserved', 'consumed', 'released')),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ finalized_at TIMESTAMPTZ,
+ CHECK (period_start < period_end)
+);
+
+ALTER TABLE autopilot_run
+ ADD COLUMN quota_reservation_id UUID,
+ ADD COLUMN reason_code TEXT;
+
+ALTER TABLE webhook_delivery
+ ADD COLUMN reason_code TEXT,
+ ADD COLUMN replay_idempotency_key TEXT;
diff --git a/server/migrations/353_autopilot_quota_period_scope_index.down.sql b/server/migrations/353_autopilot_quota_period_scope_index.down.sql
new file mode 100644
index 0000000000..8c3027e2ec
--- /dev/null
+++ b/server/migrations/353_autopilot_quota_period_scope_index.down.sql
@@ -0,0 +1,3 @@
+-- Dropping the constraint in migration 359 also drops the attached index, so
+-- this is normally a safe no-op.
+DROP INDEX CONCURRENTLY IF EXISTS uq_autopilot_quota_period_scope;
diff --git a/server/migrations/353_autopilot_quota_period_scope_index.up.sql b/server/migrations/353_autopilot_quota_period_scope_index.up.sql
new file mode 100644
index 0000000000..196603c4d0
--- /dev/null
+++ b/server/migrations/353_autopilot_quota_period_scope_index.up.sql
@@ -0,0 +1,3 @@
+-- Natural-key backing index for the primary key attached in migration 359.
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_autopilot_quota_period_scope
+ ON autopilot_quota_period(workspace_id, period_start, period_end);
diff --git a/server/migrations/354_autopilot_quota_reservation_id_index.down.sql b/server/migrations/354_autopilot_quota_reservation_id_index.down.sql
new file mode 100644
index 0000000000..d7426b4a98
--- /dev/null
+++ b/server/migrations/354_autopilot_quota_reservation_id_index.down.sql
@@ -0,0 +1,3 @@
+-- Dropping the constraint in migration 359 also drops the attached index, so
+-- this is normally a safe no-op.
+DROP INDEX CONCURRENTLY IF EXISTS autopilot_quota_reservation_pkey_uidx;
diff --git a/server/migrations/354_autopilot_quota_reservation_id_index.up.sql b/server/migrations/354_autopilot_quota_reservation_id_index.up.sql
new file mode 100644
index 0000000000..f7d6f9aa38
--- /dev/null
+++ b/server/migrations/354_autopilot_quota_reservation_id_index.up.sql
@@ -0,0 +1,2 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS autopilot_quota_reservation_pkey_uidx
+ ON autopilot_quota_reservation(id);
diff --git a/server/migrations/355_autopilot_quota_reservation_key_index.down.sql b/server/migrations/355_autopilot_quota_reservation_key_index.down.sql
new file mode 100644
index 0000000000..e6b6b9dd75
--- /dev/null
+++ b/server/migrations/355_autopilot_quota_reservation_key_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_autopilot_quota_reservation_key;
diff --git a/server/migrations/355_autopilot_quota_reservation_key_index.up.sql b/server/migrations/355_autopilot_quota_reservation_key_index.up.sql
new file mode 100644
index 0000000000..f585af49e5
--- /dev/null
+++ b/server/migrations/355_autopilot_quota_reservation_key_index.up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_autopilot_quota_reservation_key
+ ON autopilot_quota_reservation(workspace_id, period_start, period_end, idempotency_key)
+ WHERE state <> 'released';
diff --git a/server/migrations/356_autopilot_run_quota_reservation_index.down.sql b/server/migrations/356_autopilot_run_quota_reservation_index.down.sql
new file mode 100644
index 0000000000..fe9b098801
--- /dev/null
+++ b/server/migrations/356_autopilot_run_quota_reservation_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_autopilot_run_quota_reservation;
diff --git a/server/migrations/356_autopilot_run_quota_reservation_index.up.sql b/server/migrations/356_autopilot_run_quota_reservation_index.up.sql
new file mode 100644
index 0000000000..de65a95c4f
--- /dev/null
+++ b/server/migrations/356_autopilot_run_quota_reservation_index.up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_autopilot_run_quota_reservation
+ ON autopilot_run(quota_reservation_id)
+ WHERE quota_reservation_id IS NOT NULL;
diff --git a/server/migrations/357_webhook_delivery_replay_idempotency_index.down.sql b/server/migrations/357_webhook_delivery_replay_idempotency_index.down.sql
new file mode 100644
index 0000000000..1ecbaedd9c
--- /dev/null
+++ b/server/migrations/357_webhook_delivery_replay_idempotency_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_webhook_delivery_replay_idempotency;
diff --git a/server/migrations/357_webhook_delivery_replay_idempotency_index.up.sql b/server/migrations/357_webhook_delivery_replay_idempotency_index.up.sql
new file mode 100644
index 0000000000..1ba085f0a1
--- /dev/null
+++ b/server/migrations/357_webhook_delivery_replay_idempotency_index.up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_webhook_delivery_replay_idempotency
+ ON webhook_delivery(replayed_from_delivery_id, replay_idempotency_key)
+ WHERE replayed_from_delivery_id IS NOT NULL AND replay_idempotency_key IS NOT NULL;
diff --git a/server/migrations/358_autopilot_quota_reservation_state_index.down.sql b/server/migrations/358_autopilot_quota_reservation_state_index.down.sql
new file mode 100644
index 0000000000..fd97bd3716
--- /dev/null
+++ b/server/migrations/358_autopilot_quota_reservation_state_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_autopilot_quota_reservation_state;
diff --git a/server/migrations/358_autopilot_quota_reservation_state_index.up.sql b/server/migrations/358_autopilot_quota_reservation_state_index.up.sql
new file mode 100644
index 0000000000..cde37875e9
--- /dev/null
+++ b/server/migrations/358_autopilot_quota_reservation_state_index.up.sql
@@ -0,0 +1,3 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_autopilot_quota_reservation_state
+ ON autopilot_quota_reservation(state, created_at)
+ WHERE state = 'reserved';
diff --git a/server/migrations/359_autopilot_quota_primary_keys.down.sql b/server/migrations/359_autopilot_quota_primary_keys.down.sql
new file mode 100644
index 0000000000..136fd89894
--- /dev/null
+++ b/server/migrations/359_autopilot_quota_primary_keys.down.sql
@@ -0,0 +1,7 @@
+-- Dropping each constraint also drops its attached backing index. The down
+-- migrations for 353 and 354 therefore become safe no-ops.
+ALTER TABLE autopilot_quota_reservation
+ DROP CONSTRAINT IF EXISTS autopilot_quota_reservation_pkey;
+
+ALTER TABLE autopilot_quota_period
+ DROP CONSTRAINT IF EXISTS autopilot_quota_period_pkey;
diff --git a/server/migrations/359_autopilot_quota_primary_keys.up.sql b/server/migrations/359_autopilot_quota_primary_keys.up.sql
new file mode 100644
index 0000000000..e7afd9b52e
--- /dev/null
+++ b/server/migrations/359_autopilot_quota_primary_keys.up.sql
@@ -0,0 +1,9 @@
+-- Attach the concurrently-built unique indexes as primary keys. The quota
+-- period uses its actual lookup and locking key instead of an unused surrogate.
+ALTER TABLE autopilot_quota_period
+ ADD CONSTRAINT autopilot_quota_period_pkey
+ PRIMARY KEY USING INDEX uq_autopilot_quota_period_scope;
+
+ALTER TABLE autopilot_quota_reservation
+ ADD CONSTRAINT autopilot_quota_reservation_pkey
+ PRIMARY KEY USING INDEX autopilot_quota_reservation_pkey_uidx;
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index b848554e6d..11c76cd7e4 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -207,23 +207,26 @@ const createAutopilotRun = `-- name: CreateAutopilotRun :one
INSERT INTO autopilot_run (
autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,
- webhook_delivery_id
+ webhook_delivery_id, quota_reservation_id, reason_code
) VALUES (
$1, $4, $2, $3, $5,
$6, $7,
- $8
-) 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
+ $8, $9,
+ $10
+) 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
`
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"`
- PlannedAt pgtype.Timestamptz `json:"planned_at"`
- WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_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"`
+ WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
+ QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
// =====================
@@ -250,6 +253,8 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
arg.SquadID,
arg.PlannedAt,
arg.WebhookDeliveryID,
+ arg.QuotaReservationID,
+ arg.ReasonCode,
)
var i AutopilotRun
err := row.Scan(
@@ -269,6 +274,8 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
@@ -511,18 +518,110 @@ func (q *Queries) DeleteAutopilotTrigger(ctx context.Context, id pgtype.UUID) er
return err
}
-const failAutopilotRunsByIssue = `-- name: FailAutopilotRunsByIssue :exec
-UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
-WHERE issue_id = $1
- AND status IN ('issue_created', 'running')
+const failAutopilotRunsByIssue = `-- name: FailAutopilotRunsByIssue :many
+WITH updated_runs AS (
+ UPDATE autopilot_run
+ SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
+ WHERE issue_id = $1
+ AND status IN ('issue_created', 'running')
+ 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
+), 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_at
+ FROM autopilot_quota_reservation qr
+ JOIN updated_runs ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), released_reservations AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = 'released', finalized_at = now()
+ FROM locked_reservations AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), released_by_period AS (
+ SELECT workspace_id, period_start, period_end, count(*)::bigint AS released_count
+ FROM released_reservations
+ GROUP BY workspace_id, period_start, period_end
+), settled_periods AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - released.released_count,
+ updated_at = now()
+ FROM released_by_period AS released
+ WHERE p.workspace_id = released.workspace_id
+ AND p.period_start = released.period_start
+ AND p.period_end = released.period_end
+ RETURNING 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
`
+type FailAutopilotRunsByIssueRow struct {
+ ID pgtype.UUID `json:"id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Source string `json:"source"`
+ Status string `json:"status"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ TriggeredAt pgtype.Timestamptz `json:"triggered_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerPayload []byte `json:"trigger_payload"`
+ Result []byte `json:"result"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
+ WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
+ QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`
+ ReasonCode pgtype.Text `json:"reason_code"`
+}
+
// Fails active autopilot runs linked to a given issue.
// Must be called BEFORE issue deletion (ON DELETE SET NULL clears issue_id).
-func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, failAutopilotRunsByIssue, issueID)
- return err
+// Only still-reserved run_only slots are released. A create_issue slot was
+// consumed when the issue was created and remains counted after deletion.
+func (q *Queries) FailAutopilotRunsByIssue(ctx context.Context, issueID pgtype.UUID) ([]FailAutopilotRunsByIssueRow, error) {
+ rows, err := q.db.Query(ctx, failAutopilotRunsByIssue, issueID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []FailAutopilotRunsByIssueRow{}
+ for rows.Next() {
+ var i FailAutopilotRunsByIssueRow
+ if err := rows.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,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
}
const getActiveAutopilotRuleVersion = `-- name: GetActiveAutopilotRuleVersion :one
@@ -619,7 +718,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 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 FROM autopilot_run
WHERE id = $1
`
@@ -643,13 +742,15 @@ func (q *Queries) GetAutopilotRun(ctx context.Context, id pgtype.UUID) (Autopilo
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
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 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 FROM autopilot_run
WHERE issue_id = $1 AND status IN ('issue_created', 'running')
LIMIT 1
`
@@ -677,12 +778,46 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
+ )
+ 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
+WHERE quota_reservation_id = $1
+LIMIT 1
+`
+
+func (q *Queries) GetAutopilotRunByQuotaReservation(ctx context.Context, quotaReservationID pgtype.UUID) (AutopilotRun, error) {
+ row := q.db.QueryRow(ctx, getAutopilotRunByQuotaReservation, quotaReservationID)
+ 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,
)
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 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 FROM autopilot_run
WHERE trigger_id = $1
AND planned_at = $2
LIMIT 1
@@ -721,12 +856,14 @@ func (q *Queries) GetAutopilotRunByTriggerAndPlanned(ctx context.Context, arg Ge
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
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 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 FROM autopilot_run
WHERE webhook_delivery_id = $1
LIMIT 1
`
@@ -751,6 +888,8 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
@@ -997,7 +1136,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 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 FROM autopilot_run
WHERE autopilot_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
@@ -1035,6 +1174,8 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPa
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
); err != nil {
return nil, err
}
@@ -1444,13 +1585,55 @@ func (q *Queries) PauseAutopilotsByUnrunnableSquad(ctx context.Context, squadID
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
+const recoverPartialAutopilotRun = `-- name: RecoverPartialAutopilotRun :one
+WITH updated_run AS (
+ UPDATE autopilot_run AS ar
+ SET status = 'failed',
+ completed_at = now(),
+ failure_reason = 'recovered partial dispatch (crashed before downstream creation)',
+ reason_code = 'internal_error',
+ planned_at = NULL
+ WHERE ar.id = $1
+ AND (
+ ar.status = 'pending'
+ OR (ar.status = 'issue_created' AND ar.issue_id IS NULL)
+ OR (ar.status = 'running' AND ar.task_id IS NULL)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue task
+ WHERE task.autopilot_run_id = ar.id
+ )
+ RETURNING ar.quota_reservation_id
+), 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_at
+ FROM autopilot_quota_reservation qr
+ JOIN updated_run ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), released_reservation AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = 'released', finalized_at = now()
+ FROM locked_reservation AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), settled_period AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - 1,
+ updated_at = now()
+ FROM released_reservation AS released
+ WHERE p.workspace_id = released.workspace_id
+ AND p.period_start = released.period_start
+ AND p.period_end = released.period_end
+ RETURNING p.workspace_id
+)
+SELECT count(*)::bigint FROM updated_run
`
// Recovers a partial-state autopilot_run from a crashed first attempt
@@ -1463,9 +1646,11 @@ WHERE id = $1
// 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
+func (q *Queries) RecoverPartialAutopilotRun(ctx context.Context, id pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, recoverPartialAutopilotRun, id)
+ var column_1 int64
+ err := row.Scan(&column_1)
+ return column_1, err
}
const rotateAutopilotTriggerWebhookToken = `-- name: RotateAutopilotTriggerWebhookToken :one
@@ -1851,7 +2036,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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunCompletedParams struct {
@@ -1859,6 +2044,8 @@ type UpdateAutopilotRunCompletedParams struct {
Result []byte `json:"result"`
}
+// Quota safety: only use for a run known to have no reservation. Normal
+// terminal paths must call UpdateAutopilotRunTerminalWithQuota instead.
func (q *Queries) UpdateAutopilotRunCompleted(ctx context.Context, arg UpdateAutopilotRunCompletedParams) (AutopilotRun, error) {
row := q.db.QueryRow(ctx, updateAutopilotRunCompleted, arg.ID, arg.Result)
var i AutopilotRun
@@ -1879,24 +2066,30 @@ func (q *Queries) UpdateAutopilotRunCompleted(ctx context.Context, arg UpdateAut
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
const updateAutopilotRunFailed = `-- name: UpdateAutopilotRunFailed :one
UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = $2
+SET status = 'failed', completed_at = now(), failure_reason = $2,
+ reason_code = $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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunFailedParams struct {
ID pgtype.UUID `json:"id"`
FailureReason pgtype.Text `json:"failure_reason"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
+// Quota safety: only use for a run known to have no reservation. Normal
+// terminal paths must call UpdateAutopilotRunTerminalWithQuota instead.
func (q *Queries) UpdateAutopilotRunFailed(ctx context.Context, arg UpdateAutopilotRunFailedParams) (AutopilotRun, error) {
- row := q.db.QueryRow(ctx, updateAutopilotRunFailed, arg.ID, arg.FailureReason)
+ row := q.db.QueryRow(ctx, updateAutopilotRunFailed, arg.ID, arg.FailureReason, arg.ReasonCode)
var i AutopilotRun
err := row.Scan(
&i.ID,
@@ -1915,6 +2108,8 @@ func (q *Queries) UpdateAutopilotRunFailed(ctx context.Context, arg UpdateAutopi
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
@@ -1923,7 +2118,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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunIssueCreatedParams struct {
@@ -1951,6 +2146,8 @@ func (q *Queries) UpdateAutopilotRunIssueCreated(ctx context.Context, arg Update
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
@@ -1959,7 +2156,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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunRunningParams struct {
@@ -1987,22 +2184,28 @@ func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutop
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
const updateAutopilotRunSkipped = `-- name: UpdateAutopilotRunSkipped :one
UPDATE autopilot_run
-SET status = 'skipped', completed_at = now(), failure_reason = $2
+SET status = 'skipped', completed_at = now(), failure_reason = $2,
+ reason_code = $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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunSkippedParams struct {
ID pgtype.UUID `json:"id"`
FailureReason pgtype.Text `json:"failure_reason"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
+// Quota safety: this is only for pre-admission skipped rows, which never have
+// reservations. Post-admission skips use UpdateAutopilotRunTerminalWithQuota.
// Marks an autopilot_run as skipped without enqueueing any task. Used by the
// pre-flight admission check when the assignee agent's runtime is offline:
// creating an issue / task in that state would just pile a doomed job onto
@@ -2010,7 +2213,7 @@ type UpdateAutopilotRunSkippedParams struct {
// MUL-1899). Recording the skip + reason gives the UI / failure monitor / ops
// a paper trail without polluting the failure ratio.
func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutopilotRunSkippedParams) (AutopilotRun, error) {
- row := q.db.QueryRow(ctx, updateAutopilotRunSkipped, arg.ID, arg.FailureReason)
+ row := q.db.QueryRow(ctx, updateAutopilotRunSkipped, arg.ID, arg.FailureReason, arg.ReasonCode)
var i AutopilotRun
err := row.Scan(
&i.ID,
@@ -2029,6 +2232,8 @@ func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutop
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
)
return i, err
}
@@ -2040,7 +2245,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, planned_at, webhook_delivery_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, webhook_delivery_id, quota_reservation_id, reason_code
`
type UpdateAutopilotRunSkippedWithResultParams struct {
@@ -2049,6 +2254,8 @@ type UpdateAutopilotRunSkippedWithResultParams struct {
Result []byte `json:"result"`
}
+// Quota safety: legacy no-reservation helper. New terminal paths must call
+// UpdateAutopilotRunTerminalWithQuota instead.
func (q *Queries) UpdateAutopilotRunSkippedWithResult(ctx context.Context, arg UpdateAutopilotRunSkippedWithResultParams) (AutopilotRun, error) {
row := q.db.QueryRow(ctx, updateAutopilotRunSkippedWithResult, arg.ID, arg.FailureReason, arg.Result)
var i AutopilotRun
@@ -2069,6 +2276,131 @@ func (q *Queries) UpdateAutopilotRunSkippedWithResult(ctx context.Context, arg U
&i.SquadID,
&i.PlannedAt,
&i.WebhookDeliveryID,
+ &i.QuotaReservationID,
+ &i.ReasonCode,
+ )
+ return i, err
+}
+
+const updateAutopilotRunTerminalWithQuota = `-- name: UpdateAutopilotRunTerminalWithQuota :one
+WITH updated_run AS (
+ UPDATE autopilot_run AS ar
+ SET status = $1::text,
+ completed_at = now(),
+ result = CASE
+ WHEN $1::text = 'completed' THEN $2::jsonb
+ ELSE ar.result
+ END,
+ failure_reason = CASE
+ WHEN $1::text IN ('failed', 'skipped') THEN $3::text
+ ELSE ar.failure_reason
+ END,
+ reason_code = CASE
+ WHEN $1::text IN ('failed', 'skipped') THEN $4::text
+ ELSE ar.reason_code
+ END
+ WHERE 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
+), 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_at
+ FROM autopilot_quota_reservation qr
+ JOIN updated_run ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), finalized_reservation AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = CASE WHEN $6::boolean THEN 'consumed' ELSE 'released' END,
+ finalized_at = now()
+ FROM locked_reservation AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), settled_period AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - 1,
+ used_count = used_count + CASE WHEN $6::boolean THEN 1 ELSE 0 END,
+ updated_at = now()
+ FROM finalized_reservation AS finalized
+ WHERE p.workspace_id = finalized.workspace_id
+ AND p.period_start = finalized.period_start
+ AND p.period_end = finalized.period_end
+ RETURNING 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
+`
+
+type UpdateAutopilotRunTerminalWithQuotaParams struct {
+ TerminalStatus string `json:"terminal_status"`
+ Result []byte `json:"result"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ReasonCode pgtype.Text `json:"reason_code"`
+ RunID pgtype.UUID `json:"run_id"`
+ Consume bool `json:"consume"`
+}
+
+type UpdateAutopilotRunTerminalWithQuotaRow struct {
+ ID pgtype.UUID `json:"id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Source string `json:"source"`
+ Status string `json:"status"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ TriggeredAt pgtype.Timestamptz `json:"triggered_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerPayload []byte `json:"trigger_payload"`
+ Result []byte `json:"result"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
+ WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
+ QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`
+ ReasonCode pgtype.Text `json:"reason_code"`
+}
+
+// Finalizes a run and its still-reserved quota slot in one statement. Runs
+// created while the entitlement gate is off have a NULL reservation ID, so
+// the quota CTEs become empty without an extra BEGIN/COMMIT round trip.
+// Consumed slots are deliberately immutable: create_issue is chargeable once
+// the issue exists, even if that issue is later blocked, cancelled, or deleted.
+// The CTE sequence is: update the run, lock a still-reserved slot, finalize
+// that slot exactly once, then move one unit from reserved_count to either
+// used_count (consume) or nowhere (release). used_count never decreases.
+func (q *Queries) UpdateAutopilotRunTerminalWithQuota(ctx context.Context, arg UpdateAutopilotRunTerminalWithQuotaParams) (UpdateAutopilotRunTerminalWithQuotaRow, error) {
+ row := q.db.QueryRow(ctx, updateAutopilotRunTerminalWithQuota,
+ arg.TerminalStatus,
+ arg.Result,
+ arg.FailureReason,
+ arg.ReasonCode,
+ arg.RunID,
+ arg.Consume,
+ )
+ var i UpdateAutopilotRunTerminalWithQuotaRow
+ 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,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot_quota.sql.go b/server/pkg/db/generated/autopilot_quota.sql.go
new file mode 100644
index 0000000000..3d59b1e82d
--- /dev/null
+++ b/server/pkg/db/generated/autopilot_quota.sql.go
@@ -0,0 +1,393 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: autopilot_quota.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const consumeAutopilotQuotaReservation = `-- name: ConsumeAutopilotQuotaReservation :one
+WITH locked AS (
+ 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_at FROM autopilot_quota_reservation qr
+ WHERE qr.id = $1 AND qr.state = 'reserved'
+ FOR UPDATE
+), changed AS (
+ UPDATE autopilot_quota_reservation AS r
+ SET state = 'consumed', finalized_at = now()
+ FROM locked
+ WHERE r.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+)
+UPDATE autopilot_quota_period AS p
+SET reserved_count = reserved_count - 1,
+ used_count = used_count + 1,
+ updated_at = now()
+FROM changed
+WHERE p.workspace_id = changed.workspace_id
+ AND p.period_start = changed.period_start
+ AND p.period_end = changed.period_end
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at
+`
+
+// used_count is monotonic within a period: consuming a reserved slot is the
+// only write that changes it, and no release path decrements it.
+func (q *Queries) ConsumeAutopilotQuotaReservation(ctx context.Context, reservationID pgtype.UUID) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, consumeAutopilotQuotaReservation, reservationID)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const createAutopilotQuotaReservation = `-- name: CreateAutopilotQuotaReservation :one
+INSERT INTO autopilot_quota_reservation (
+ workspace_id, period_start, period_end, policy_revision,
+ subscription_version, source, idempotency_key
+) VALUES ($1, $2, $3, $4, $5, $6, $7)
+RETURNING id, workspace_id, period_start, period_end, policy_revision, subscription_version, source, idempotency_key, state, created_at, finalized_at
+`
+
+type CreateAutopilotQuotaReservationParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ PolicyRevision int64 `json:"policy_revision"`
+ SubscriptionVersion int64 `json:"subscription_version"`
+ Source string `json:"source"`
+ IdempotencyKey string `json:"idempotency_key"`
+}
+
+func (q *Queries) CreateAutopilotQuotaReservation(ctx context.Context, arg CreateAutopilotQuotaReservationParams) (AutopilotQuotaReservation, error) {
+ row := q.db.QueryRow(ctx, createAutopilotQuotaReservation,
+ arg.WorkspaceID,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ arg.PolicyRevision,
+ arg.SubscriptionVersion,
+ arg.Source,
+ arg.IdempotencyKey,
+ )
+ var i AutopilotQuotaReservation
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.PolicyRevision,
+ &i.SubscriptionVersion,
+ &i.Source,
+ &i.IdempotencyKey,
+ &i.State,
+ &i.CreatedAt,
+ &i.FinalizedAt,
+ )
+ return i, err
+}
+
+const ensureAutopilotQuotaPeriod = `-- name: EnsureAutopilotQuotaPeriod :one
+INSERT INTO autopilot_quota_period (workspace_id, period_start, period_end)
+VALUES ($1, $2, $3)
+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE
+SET updated_at = autopilot_quota_period.updated_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+`
+
+type EnsureAutopilotQuotaPeriodParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+// The no-op update is intentional: ON CONFLICT UPDATE locks the period row for
+// the caller's transaction, serialising admission for one workspace/period.
+func (q *Queries) EnsureAutopilotQuotaPeriod(ctx context.Context, arg EnsureAutopilotQuotaPeriodParams) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, ensureAutopilotQuotaPeriod, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getAutopilotQuotaPeriod = `-- name: GetAutopilotQuotaPeriod :one
+SELECT workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at FROM autopilot_quota_period
+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
+`
+
+type GetAutopilotQuotaPeriodParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+func (q *Queries) GetAutopilotQuotaPeriod(ctx context.Context, arg GetAutopilotQuotaPeriodParams) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, getAutopilotQuotaPeriod, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const getAutopilotQuotaReservationByKey = `-- name: GetAutopilotQuotaReservationByKey :one
+SELECT id, workspace_id, period_start, period_end, policy_revision, subscription_version, source, idempotency_key, state, created_at, finalized_at FROM autopilot_quota_reservation
+WHERE workspace_id = $1
+ AND period_start = $2
+ AND period_end = $3
+ AND idempotency_key = $4
+ AND state <> 'released'
+`
+
+type GetAutopilotQuotaReservationByKeyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ IdempotencyKey string `json:"idempotency_key"`
+}
+
+func (q *Queries) GetAutopilotQuotaReservationByKey(ctx context.Context, arg GetAutopilotQuotaReservationByKeyParams) (AutopilotQuotaReservation, error) {
+ row := q.db.QueryRow(ctx, getAutopilotQuotaReservationByKey,
+ arg.WorkspaceID,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ arg.IdempotencyKey,
+ )
+ var i AutopilotQuotaReservation
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.PolicyRevision,
+ &i.SubscriptionVersion,
+ &i.Source,
+ &i.IdempotencyKey,
+ &i.State,
+ &i.CreatedAt,
+ &i.FinalizedAt,
+ )
+ return i, err
+}
+
+const incrementAutopilotQuotaBlocked = `-- name: IncrementAutopilotQuotaBlocked :one
+UPDATE autopilot_quota_period
+SET blocked_counts = jsonb_set(
+ blocked_counts,
+ ARRAY[$1::text],
+ to_jsonb(COALESCE((blocked_counts ->> $1::text)::bigint, 0) + 1),
+ true
+ ),
+ updated_at = now()
+WHERE workspace_id = $2
+ AND period_start = $3
+ AND period_end = $4
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+`
+
+type IncrementAutopilotQuotaBlockedParams struct {
+ Source string `json:"source"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+func (q *Queries) IncrementAutopilotQuotaBlocked(ctx context.Context, arg IncrementAutopilotQuotaBlockedParams) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, incrementAutopilotQuotaBlocked,
+ arg.Source,
+ arg.WorkspaceID,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ )
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const incrementAutopilotQuotaReserved = `-- name: IncrementAutopilotQuotaReserved :one
+UPDATE autopilot_quota_period
+SET reserved_count = reserved_count + 1,
+ updated_at = now()
+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at
+`
+
+type IncrementAutopilotQuotaReservedParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+}
+
+func (q *Queries) IncrementAutopilotQuotaReserved(ctx context.Context, arg IncrementAutopilotQuotaReservedParams) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, incrementAutopilotQuotaReserved, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const listRecoverableAutopilotQuotaReservations = `-- name: ListRecoverableAutopilotQuotaReservations :many
+SELECT r.id, r.workspace_id, r.period_start, r.period_end, r.policy_revision, r.subscription_version, r.source, r.idempotency_key, r.state, r.created_at, r.finalized_at
+FROM autopilot_quota_reservation r
+LEFT JOIN autopilot_run ar ON ar.quota_reservation_id = r.id
+WHERE r.state = 'reserved'
+ AND (
+ (
+ r.created_at < $1
+ AND (ar.id IS NULL OR ar.status IN ('completed', 'failed', 'skipped'))
+ )
+ OR (
+ -- Manual/API requests have no durable retry owner. Reclaim only an
+ -- hours-old partial run with neither a linked side effect nor even
+ -- an unlinked task row; schedule and webhook retries repair their
+ -- own partial state and are deliberately excluded.
+ r.created_at < $2
+ AND ar.source IN ('manual', 'api')
+ AND (
+ ar.status = 'pending'
+ OR (ar.status = 'issue_created' AND ar.issue_id IS NULL)
+ OR (ar.status = 'running' AND ar.task_id IS NULL)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue task
+ WHERE task.autopilot_run_id = ar.id
+ )
+ )
+ )
+ORDER BY r.created_at
+LIMIT $3
+`
+
+type ListRecoverableAutopilotQuotaReservationsParams struct {
+ TerminalCreatedBefore pgtype.Timestamptz `json:"terminal_created_before"`
+ PartialCreatedBefore pgtype.Timestamptz `json:"partial_created_before"`
+ RowLimit int32 `json:"row_limit"`
+}
+
+func (q *Queries) ListRecoverableAutopilotQuotaReservations(ctx context.Context, arg ListRecoverableAutopilotQuotaReservationsParams) ([]AutopilotQuotaReservation, error) {
+ rows, err := q.db.Query(ctx, listRecoverableAutopilotQuotaReservations, arg.TerminalCreatedBefore, arg.PartialCreatedBefore, arg.RowLimit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AutopilotQuotaReservation{}
+ for rows.Next() {
+ var i AutopilotQuotaReservation
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.PolicyRevision,
+ &i.SubscriptionVersion,
+ &i.Source,
+ &i.IdempotencyKey,
+ &i.State,
+ &i.CreatedAt,
+ &i.FinalizedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const releaseAutopilotQuotaReservation = `-- name: ReleaseAutopilotQuotaReservation :one
+WITH locked AS (
+ 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_at FROM autopilot_quota_reservation qr
+ WHERE qr.id = $1 AND qr.state = 'reserved'
+ FOR UPDATE
+), changed AS (
+ UPDATE autopilot_quota_reservation AS r
+ SET state = 'released', finalized_at = now()
+ FROM locked
+ WHERE r.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+)
+UPDATE autopilot_quota_period AS p
+SET reserved_count = reserved_count - 1,
+ updated_at = now()
+FROM changed
+WHERE p.workspace_id = changed.workspace_id
+ AND p.period_start = changed.period_start
+ AND p.period_end = changed.period_end
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at
+`
+
+// Release is intentionally limited to still-reserved work. A consumed
+// create_issue slot remains counted after cancellation, blocking, or deletion.
+func (q *Queries) ReleaseAutopilotQuotaReservation(ctx context.Context, reservationID pgtype.UUID) (AutopilotQuotaPeriod, error) {
+ row := q.db.QueryRow(ctx, releaseAutopilotQuotaReservation, reservationID)
+ var i AutopilotQuotaPeriod
+ err := row.Scan(
+ &i.WorkspaceID,
+ &i.PeriodStart,
+ &i.PeriodEnd,
+ &i.UsedCount,
+ &i.ReservedCount,
+ &i.BlockedCounts,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 50ad5fa156..6ca2ce0eab 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -221,6 +221,31 @@ type AutopilotCollaborator struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type AutopilotQuotaPeriod struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ UsedCount int64 `json:"used_count"`
+ ReservedCount int64 `json:"reserved_count"`
+ BlockedCounts []byte `json:"blocked_counts"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type AutopilotQuotaReservation struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ PolicyRevision int64 `json:"policy_revision"`
+ SubscriptionVersion int64 `json:"subscription_version"`
+ Source string `json:"source"`
+ IdempotencyKey string `json:"idempotency_key"`
+ State string `json:"state"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ FinalizedAt pgtype.Timestamptz `json:"finalized_at"`
+}
+
// Append-only snapshot of autopilot rule publishes (MUL-4302 §3.4). One row per substantive publish (create / enable / resume / trigger-condition / target / instructions change), recording the publisher + effective-config summary. Dispatch resolves the latest row for an autopilot as the run's rule_owner accountable human. No FK, no cascade.
type AutopilotRuleVersion struct {
ID pgtype.UUID `json:"id"`
@@ -233,22 +258,24 @@ type AutopilotRuleVersion struct {
}
type AutopilotRun struct {
- ID pgtype.UUID `json:"id"`
- AutopilotID pgtype.UUID `json:"autopilot_id"`
- TriggerID pgtype.UUID `json:"trigger_id"`
- Source string `json:"source"`
- Status string `json:"status"`
- IssueID pgtype.UUID `json:"issue_id"`
- TaskID pgtype.UUID `json:"task_id"`
- TriggeredAt pgtype.Timestamptz `json:"triggered_at"`
- CompletedAt pgtype.Timestamptz `json:"completed_at"`
- FailureReason pgtype.Text `json:"failure_reason"`
- TriggerPayload []byte `json:"trigger_payload"`
- Result []byte `json:"result"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- SquadID pgtype.UUID `json:"squad_id"`
- PlannedAt pgtype.Timestamptz `json:"planned_at"`
- WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
+ ID pgtype.UUID `json:"id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Source string `json:"source"`
+ Status string `json:"status"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ TriggeredAt pgtype.Timestamptz `json:"triggered_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerPayload []byte `json:"trigger_payload"`
+ Result []byte `json:"result"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ PlannedAt pgtype.Timestamptz `json:"planned_at"`
+ WebhookDeliveryID pgtype.UUID `json:"webhook_delivery_id"`
+ QuotaReservationID pgtype.UUID `json:"quota_reservation_id"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
type AutopilotSubscriber struct {
@@ -1283,6 +1310,8 @@ type WebhookDelivery struct {
LeaseToken pgtype.UUID `json:"lease_token"`
LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
DispatchAttempts int32 `json:"dispatch_attempts"`
+ ReasonCode pgtype.Text `json:"reason_code"`
+ ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
}
type Workspace struct {
diff --git a/server/pkg/db/generated/webhook_delivery.sql.go b/server/pkg/db/generated/webhook_delivery.sql.go
index 94148209a2..174aa8cc3e 100644
--- a/server/pkg/db/generated/webhook_delivery.sql.go
+++ b/server/pkg/db/generated/webhook_delivery.sql.go
@@ -17,7 +17,7 @@ SET response_status = $2,
response_body = $3,
last_attempt_at = now()
WHERE id = $1
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type AcknowledgeWebhookDeliveryParams struct {
@@ -59,6 +59,8 @@ func (q *Queries) AcknowledgeWebhookDelivery(ctx context.Context, arg Acknowledg
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -68,7 +70,7 @@ UPDATE webhook_delivery
SET attempt_count = attempt_count + 1,
last_attempt_at = now()
WHERE id = $1
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
// On duplicate detection, bump attempt_count and refresh last_attempt_at on
@@ -104,6 +106,8 @@ func (q *Queries) BumpWebhookDeliveryAttempt(ctx context.Context, id pgtype.UUID
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -124,7 +128,7 @@ SET lease_token = gen_random_uuid(),
lease_expires_at = now() + interval '2 minutes'
FROM candidate
WHERE d.id = candidate.id
-RETURNING d.id, d.workspace_id, d.autopilot_id, d.trigger_id, d.provider, d.event, d.dedupe_key, d.dedupe_source, d.signature_status, d.status, d.attempt_count, d.selected_headers, d.content_type, d.raw_body, d.response_status, d.response_body, d.autopilot_run_id, d.replayed_from_delivery_id, d.error, d.received_at, d.last_attempt_at, d.created_at, d.available_at, d.lease_token, d.lease_expires_at, d.dispatch_attempts
+RETURNING d.id, d.workspace_id, d.autopilot_id, d.trigger_id, d.provider, d.event, d.dedupe_key, d.dedupe_source, d.signature_status, d.status, d.attempt_count, d.selected_headers, d.content_type, d.raw_body, d.response_status, d.response_body, d.autopilot_run_id, d.replayed_from_delivery_id, d.error, d.received_at, d.last_attempt_at, d.created_at, d.available_at, d.lease_token, d.lease_expires_at, d.dispatch_attempts, d.reason_code, d.replay_idempotency_key
`
// Claims one due delivery. SKIP LOCKED spreads work across replicas; the
@@ -162,6 +166,8 @@ func (q *Queries) ClaimQueuedWebhookDelivery(ctx context.Context) (WebhookDelive
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -172,13 +178,14 @@ SET status = $3,
autopilot_run_id = $4,
dispatch_attempts = dispatch_attempts + 1,
error = $5,
+ reason_code = $6,
lease_token = NULL,
lease_expires_at = NULL,
last_attempt_at = now()
WHERE id = $1
AND lease_token = $2
AND status = 'queued'
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type CompleteClaimedWebhookDeliveryParams struct {
@@ -187,6 +194,7 @@ type CompleteClaimedWebhookDeliveryParams struct {
Status string `json:"status"`
AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
Error pgtype.Text `json:"error"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
func (q *Queries) CompleteClaimedWebhookDelivery(ctx context.Context, arg CompleteClaimedWebhookDeliveryParams) (WebhookDelivery, error) {
@@ -196,6 +204,7 @@ func (q *Queries) CompleteClaimedWebhookDelivery(ctx context.Context, arg Comple
arg.Status,
arg.AutopilotRunID,
arg.Error,
+ arg.ReasonCode,
)
var i WebhookDelivery
err := row.Scan(
@@ -225,6 +234,8 @@ func (q *Queries) CompleteClaimedWebhookDelivery(ctx context.Context, arg Comple
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -235,13 +246,14 @@ INSERT INTO webhook_delivery (
workspace_id, autopilot_id, trigger_id, provider, event,
dedupe_key, dedupe_source, signature_status, status,
selected_headers, content_type, raw_body,
- replayed_from_delivery_id
+ replayed_from_delivery_id, replay_idempotency_key, reason_code
) VALUES (
$1, $2, $3, $4, $5,
$9, $10, $6, $7,
$8, $11, $12,
- $13
-) RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+ $13, $14,
+ $15
+) RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type CreateWebhookDeliveryParams struct {
@@ -258,6 +270,8 @@ type CreateWebhookDeliveryParams struct {
ContentType pgtype.Text `json:"content_type"`
RawBody []byte `json:"raw_body"`
ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
+ ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
+ ReasonCode pgtype.Text `json:"reason_code"`
}
// =====================
@@ -281,6 +295,8 @@ func (q *Queries) CreateWebhookDelivery(ctx context.Context, arg CreateWebhookDe
arg.ContentType,
arg.RawBody,
arg.ReplayedFromDeliveryID,
+ arg.ReplayIdempotencyKey,
+ arg.ReasonCode,
)
var i WebhookDelivery
err := row.Scan(
@@ -310,6 +326,8 @@ func (q *Queries) CreateWebhookDelivery(ctx context.Context, arg CreateWebhookDe
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -322,7 +340,7 @@ SET available_at = $3,
WHERE id = $1
AND lease_token = $2
AND status = 'queued'
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type DeferClaimedWebhookDeliveryParams struct {
@@ -363,12 +381,14 @@ func (q *Queries) DeferClaimedWebhookDelivery(ctx context.Context, arg DeferClai
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
const getWebhookDelivery = `-- name: GetWebhookDelivery :one
-SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts FROM webhook_delivery
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key FROM webhook_delivery
WHERE id = $1
`
@@ -402,12 +422,14 @@ func (q *Queries) GetWebhookDelivery(ctx context.Context, id pgtype.UUID) (Webho
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
const getWebhookDeliveryByTriggerAndDedupe = `-- name: GetWebhookDeliveryByTriggerAndDedupe :one
-SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts FROM webhook_delivery
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key FROM webhook_delivery
WHERE trigger_id = $1
AND dedupe_key = $2
ORDER BY (status IN ('rejected', 'failed')), created_at DESC
@@ -456,12 +478,14 @@ func (q *Queries) GetWebhookDeliveryByTriggerAndDedupe(ctx context.Context, arg
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
const getWebhookDeliveryInWorkspace = `-- name: GetWebhookDeliveryInWorkspace :one
-SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts FROM webhook_delivery
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key FROM webhook_delivery
WHERE id = $1 AND workspace_id = $2
`
@@ -501,6 +525,55 @@ func (q *Queries) GetWebhookDeliveryInWorkspace(ctx context.Context, arg GetWebh
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
+ )
+ return i, err
+}
+
+const getWebhookReplayByIdempotencyKey = `-- name: GetWebhookReplayByIdempotencyKey :one
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key FROM webhook_delivery
+WHERE replayed_from_delivery_id = $1 AND replay_idempotency_key = $2
+LIMIT 1
+`
+
+type GetWebhookReplayByIdempotencyKeyParams struct {
+ ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
+ ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
+}
+
+func (q *Queries) GetWebhookReplayByIdempotencyKey(ctx context.Context, arg GetWebhookReplayByIdempotencyKeyParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, getWebhookReplayByIdempotencyKey, arg.ReplayedFromDeliveryID, arg.ReplayIdempotencyKey)
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -512,7 +585,7 @@ SELECT
d.attempt_count, d.content_type, d.response_status,
d.autopilot_run_id, d.replayed_from_delivery_id, d.error,
d.received_at, d.last_attempt_at, d.created_at,
- d.available_at, d.dispatch_attempts
+ d.available_at, d.dispatch_attempts, d.reason_code, d.replay_idempotency_key
FROM webhook_delivery d
JOIN autopilot a ON a.id = d.autopilot_id
WHERE d.autopilot_id = $1
@@ -550,6 +623,8 @@ type ListWebhookDeliveriesByAutopilotRow struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
AvailableAt pgtype.Timestamptz `json:"available_at"`
DispatchAttempts int32 `json:"dispatch_attempts"`
+ ReasonCode pgtype.Text `json:"reason_code"`
+ ReplayIdempotencyKey pgtype.Text `json:"replay_idempotency_key"`
}
// Workspace-scoped via the join so a runId from another workspace cannot
@@ -596,6 +671,8 @@ func (q *Queries) ListWebhookDeliveriesByAutopilot(ctx context.Context, arg List
&i.CreatedAt,
&i.AvailableAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
); err != nil {
return nil, err
}
@@ -618,7 +695,7 @@ SET available_at = $3,
WHERE id = $1
AND lease_token = $2
AND status = 'queued'
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type RetryClaimedWebhookDeliveryParams struct {
@@ -666,6 +743,8 @@ func (q *Queries) RetryClaimedWebhookDelivery(ctx context.Context, arg RetryClai
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -678,7 +757,7 @@ SET status = $2,
response_body = $5,
last_attempt_at = now()
WHERE id = $1
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type UpdateWebhookDeliveryDispatchedParams struct {
@@ -728,6 +807,8 @@ func (q *Queries) UpdateWebhookDeliveryDispatched(ctx context.Context, arg Updat
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
@@ -736,17 +817,19 @@ const updateWebhookDeliveryTerminal = `-- name: UpdateWebhookDeliveryTerminal :o
UPDATE webhook_delivery
SET status = $2,
error = $3,
- response_status = $4,
- response_body = $5,
+ reason_code = $4,
+ response_status = $5,
+ response_body = $6,
last_attempt_at = now()
WHERE id = $1
-RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at, available_at, lease_token, lease_expires_at, dispatch_attempts, reason_code, replay_idempotency_key
`
type UpdateWebhookDeliveryTerminalParams struct {
ID pgtype.UUID `json:"id"`
Status string `json:"status"`
Error pgtype.Text `json:"error"`
+ ReasonCode pgtype.Text `json:"reason_code"`
ResponseStatus pgtype.Int4 `json:"response_status"`
ResponseBody pgtype.Text `json:"response_body"`
}
@@ -759,6 +842,7 @@ func (q *Queries) UpdateWebhookDeliveryTerminal(ctx context.Context, arg UpdateW
arg.ID,
arg.Status,
arg.Error,
+ arg.ReasonCode,
arg.ResponseStatus,
arg.ResponseBody,
)
@@ -790,6 +874,8 @@ func (q *Queries) UpdateWebhookDeliveryTerminal(ctx context.Context, arg UpdateW
&i.LeaseToken,
&i.LeaseExpiresAt,
&i.DispatchAttempts,
+ &i.ReasonCode,
+ &i.ReplayIdempotencyKey,
)
return i, err
}
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 4a8aea4b7d..c97c85aac9 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -125,6 +125,26 @@ func (q *Queries) DeleteWorkspaceAutopilotChildren(ctx context.Context, workspac
return err
}
+const deleteWorkspaceAutopilotQuotaPeriods = `-- name: DeleteWorkspaceAutopilotQuotaPeriods :exec
+DELETE FROM autopilot_quota_period
+WHERE autopilot_quota_period.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAutopilotQuotaPeriods(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAutopilotQuotaPeriods, workspaceID)
+ return err
+}
+
+const deleteWorkspaceAutopilotQuotaReservations = `-- name: DeleteWorkspaceAutopilotQuotaReservations :exec
+DELETE FROM autopilot_quota_reservation
+WHERE autopilot_quota_reservation.workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceAutopilotQuotaReservations(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceAutopilotQuotaReservations, workspaceID)
+ return err
+}
+
const deleteWorkspaceAutopilotRuns = `-- name: DeleteWorkspaceAutopilotRuns :exec
DELETE FROM autopilot_run
WHERE autopilot_id IN (
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 52895c3151..9a9c0f21d9 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -297,11 +297,12 @@ RETURNING *;
-- 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, planned_at,
- webhook_delivery_id
+ webhook_delivery_id, quota_reservation_id, reason_code
) 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('webhook_delivery_id'), sqlc.narg('quota_reservation_id'),
+ sqlc.narg('reason_code')
) RETURNING *;
-- name: GetAutopilotRunByTriggerAndPlanned :one
@@ -323,7 +324,12 @@ SELECT * FROM autopilot_run
WHERE webhook_delivery_id = $1
LIMIT 1;
--- name: RecoverPartialAutopilotRun :exec
+-- name: GetAutopilotRunByQuotaReservation :one
+SELECT * FROM autopilot_run
+WHERE quota_reservation_id = $1
+LIMIT 1;
+
+-- name: RecoverPartialAutopilotRun :one
-- 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
@@ -334,12 +340,54 @@ LIMIT 1;
-- 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;
+WITH updated_run AS (
+ UPDATE autopilot_run AS ar
+ SET status = 'failed',
+ completed_at = now(),
+ failure_reason = 'recovered partial dispatch (crashed before downstream creation)',
+ reason_code = 'internal_error',
+ planned_at = NULL
+ WHERE ar.id = $1
+ AND (
+ ar.status = 'pending'
+ OR (ar.status = 'issue_created' AND ar.issue_id IS NULL)
+ OR (ar.status = 'running' AND ar.task_id IS NULL)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue task
+ WHERE task.autopilot_run_id = ar.id
+ )
+ RETURNING ar.quota_reservation_id
+), locked_reservation AS MATERIALIZED (
+ SELECT qr.*
+ FROM autopilot_quota_reservation qr
+ JOIN updated_run ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), released_reservation AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = 'released', finalized_at = now()
+ FROM locked_reservation AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), settled_period AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - 1,
+ updated_at = now()
+ FROM released_reservation AS released
+ WHERE p.workspace_id = released.workspace_id
+ AND p.period_start = released.period_start
+ AND p.period_end = released.period_end
+ RETURNING p.workspace_id
+)
+SELECT count(*)::bigint FROM updated_run;
-- name: GetAutopilotRun :one
SELECT * FROM autopilot_run
@@ -364,18 +412,25 @@ WHERE id = $1
RETURNING *;
-- name: UpdateAutopilotRunCompleted :one
+-- Quota safety: only use for a run known to have no reservation. Normal
+-- terminal paths must call UpdateAutopilotRunTerminalWithQuota instead.
UPDATE autopilot_run
SET status = 'completed', completed_at = now(), result = sqlc.narg('result')
WHERE id = $1
RETURNING *;
-- name: UpdateAutopilotRunFailed :one
+-- Quota safety: only use for a run known to have no reservation. Normal
+-- terminal paths must call UpdateAutopilotRunTerminalWithQuota instead.
UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = $2
+SET status = 'failed', completed_at = now(), failure_reason = $2,
+ reason_code = sqlc.narg('reason_code')
WHERE id = $1
RETURNING *;
-- name: UpdateAutopilotRunSkipped :one
+-- Quota safety: this is only for pre-admission skipped rows, which never have
+-- reservations. Post-admission skips use UpdateAutopilotRunTerminalWithQuota.
-- Marks an autopilot_run as skipped without enqueueing any task. Used by the
-- pre-flight admission check when the assignee agent's runtime is offline:
-- creating an issue / task in that state would just pile a doomed job onto
@@ -383,11 +438,73 @@ RETURNING *;
-- MUL-1899). Recording the skip + reason gives the UI / failure monitor / ops
-- a paper trail without polluting the failure ratio.
UPDATE autopilot_run
-SET status = 'skipped', completed_at = now(), failure_reason = $2
+SET status = 'skipped', completed_at = now(), failure_reason = $2,
+ reason_code = sqlc.narg('reason_code')
WHERE id = $1
RETURNING *;
+-- name: UpdateAutopilotRunTerminalWithQuota :one
+-- Finalizes a run and its still-reserved quota slot in one statement. Runs
+-- created while the entitlement gate is off have a NULL reservation ID, so
+-- the quota CTEs become empty without an extra BEGIN/COMMIT round trip.
+-- Consumed slots are deliberately immutable: create_issue is chargeable once
+-- the issue exists, even if that issue is later blocked, cancelled, or deleted.
+-- The CTE sequence is: update the run, lock a still-reserved slot, finalize
+-- that slot exactly once, then move one unit from reserved_count to either
+-- used_count (consume) or nowhere (release). used_count never decreases.
+WITH updated_run AS (
+ UPDATE autopilot_run AS ar
+ SET status = @terminal_status::text,
+ completed_at = now(),
+ result = CASE
+ WHEN @terminal_status::text = 'completed' THEN sqlc.narg('result')::jsonb
+ ELSE ar.result
+ END,
+ failure_reason = CASE
+ WHEN @terminal_status::text IN ('failed', 'skipped') THEN sqlc.narg('failure_reason')::text
+ ELSE ar.failure_reason
+ END,
+ reason_code = CASE
+ WHEN @terminal_status::text IN ('failed', 'skipped') THEN sqlc.narg('reason_code')::text
+ ELSE ar.reason_code
+ END
+ WHERE ar.id = @run_id
+ RETURNING ar.*
+), locked_reservation AS MATERIALIZED (
+ SELECT qr.*
+ FROM autopilot_quota_reservation qr
+ JOIN updated_run ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), finalized_reservation AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = CASE WHEN @consume::boolean THEN 'consumed' ELSE 'released' END,
+ finalized_at = now()
+ FROM locked_reservation AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), settled_period AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - 1,
+ used_count = used_count + CASE WHEN @consume::boolean THEN 1 ELSE 0 END,
+ updated_at = now()
+ FROM finalized_reservation AS finalized
+ WHERE p.workspace_id = finalized.workspace_id
+ AND p.period_start = finalized.period_start
+ AND p.period_end = finalized.period_end
+ RETURNING p.workspace_id
+)
+SELECT * FROM updated_run;
+
-- name: UpdateAutopilotRunSkippedWithResult :one
+-- Quota safety: legacy no-reservation helper. New terminal paths must call
+-- UpdateAutopilotRunTerminalWithQuota instead.
UPDATE autopilot_run
SET status = 'skipped',
completed_at = now(),
@@ -484,13 +601,50 @@ SELECT * FROM autopilot_run
WHERE issue_id = $1 AND status IN ('issue_created', 'running')
LIMIT 1;
--- name: FailAutopilotRunsByIssue :exec
+-- name: FailAutopilotRunsByIssue :many
-- Fails active autopilot runs linked to a given issue.
-- Must be called BEFORE issue deletion (ON DELETE SET NULL clears issue_id).
-UPDATE autopilot_run
-SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
-WHERE issue_id = $1
- AND status IN ('issue_created', 'running');
+-- Only still-reserved run_only slots are released. A create_issue slot was
+-- consumed when the issue was created and remains counted after deletion.
+WITH updated_runs AS (
+ UPDATE autopilot_run
+ SET status = 'failed', completed_at = now(), failure_reason = 'linked issue was deleted'
+ WHERE issue_id = $1
+ AND status IN ('issue_created', 'running')
+ RETURNING *
+), locked_reservations AS MATERIALIZED (
+ SELECT qr.*
+ FROM autopilot_quota_reservation qr
+ JOIN updated_runs ar ON ar.quota_reservation_id = qr.id
+ WHERE qr.state = 'reserved'
+ FOR UPDATE
+), released_reservations AS (
+ UPDATE autopilot_quota_reservation AS qr
+ SET state = 'released', finalized_at = now()
+ FROM locked_reservations AS locked
+ WHERE qr.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+), released_by_period AS (
+ SELECT workspace_id, period_start, period_end, count(*)::bigint AS released_count
+ FROM released_reservations
+ GROUP BY workspace_id, period_start, period_end
+), settled_periods AS (
+ UPDATE autopilot_quota_period AS p
+ SET reserved_count = reserved_count - released.released_count,
+ updated_at = now()
+ FROM released_by_period AS released
+ WHERE p.workspace_id = released.workspace_id
+ AND p.period_start = released.period_start
+ AND p.period_end = released.period_end
+ RETURNING p.workspace_id
+)
+SELECT * FROM updated_runs;
-- =====================
-- Failure-rate auto-pause
diff --git a/server/pkg/db/queries/autopilot_quota.sql b/server/pkg/db/queries/autopilot_quota.sql
new file mode 100644
index 0000000000..30f45d2954
--- /dev/null
+++ b/server/pkg/db/queries/autopilot_quota.sql
@@ -0,0 +1,139 @@
+-- name: EnsureAutopilotQuotaPeriod :one
+-- The no-op update is intentional: ON CONFLICT UPDATE locks the period row for
+-- the caller's transaction, serialising admission for one workspace/period.
+INSERT INTO autopilot_quota_period (workspace_id, period_start, period_end)
+VALUES ($1, $2, $3)
+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE
+SET updated_at = autopilot_quota_period.updated_at
+RETURNING *;
+
+-- name: GetAutopilotQuotaPeriod :one
+SELECT * FROM autopilot_quota_period
+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3;
+
+-- name: GetAutopilotQuotaReservationByKey :one
+SELECT * FROM autopilot_quota_reservation
+WHERE workspace_id = $1
+ AND period_start = $2
+ AND period_end = $3
+ AND idempotency_key = $4
+ AND state <> 'released';
+
+-- name: CreateAutopilotQuotaReservation :one
+INSERT INTO autopilot_quota_reservation (
+ workspace_id, period_start, period_end, policy_revision,
+ subscription_version, source, idempotency_key
+) VALUES ($1, $2, $3, $4, $5, $6, $7)
+RETURNING *;
+
+-- name: IncrementAutopilotQuotaReserved :one
+UPDATE autopilot_quota_period
+SET reserved_count = reserved_count + 1,
+ updated_at = now()
+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
+RETURNING *;
+
+-- name: IncrementAutopilotQuotaBlocked :one
+UPDATE autopilot_quota_period
+SET blocked_counts = jsonb_set(
+ blocked_counts,
+ ARRAY[@source::text],
+ to_jsonb(COALESCE((blocked_counts ->> @source::text)::bigint, 0) + 1),
+ true
+ ),
+ updated_at = now()
+WHERE workspace_id = @workspace_id
+ AND period_start = @period_start
+ AND period_end = @period_end
+RETURNING *;
+
+-- name: ConsumeAutopilotQuotaReservation :one
+-- used_count is monotonic within a period: consuming a reserved slot is the
+-- only write that changes it, and no release path decrements it.
+WITH locked AS (
+ SELECT qr.* FROM autopilot_quota_reservation qr
+ WHERE qr.id = @reservation_id AND qr.state = 'reserved'
+ FOR UPDATE
+), changed AS (
+ UPDATE autopilot_quota_reservation AS r
+ SET state = 'consumed', finalized_at = now()
+ FROM locked
+ WHERE r.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+)
+UPDATE autopilot_quota_period AS p
+SET reserved_count = reserved_count - 1,
+ used_count = used_count + 1,
+ updated_at = now()
+FROM changed
+WHERE p.workspace_id = changed.workspace_id
+ AND p.period_start = changed.period_start
+ AND p.period_end = changed.period_end
+RETURNING p.*;
+
+-- name: ReleaseAutopilotQuotaReservation :one
+-- Release is intentionally limited to still-reserved work. A consumed
+-- create_issue slot remains counted after cancellation, blocking, or deletion.
+WITH locked AS (
+ SELECT qr.* FROM autopilot_quota_reservation qr
+ WHERE qr.id = @reservation_id AND qr.state = 'reserved'
+ FOR UPDATE
+), changed AS (
+ UPDATE autopilot_quota_reservation AS r
+ SET state = 'released', finalized_at = now()
+ FROM locked
+ WHERE r.id = locked.id
+ AND EXISTS (
+ SELECT 1 FROM autopilot_quota_period p
+ WHERE p.workspace_id = locked.workspace_id
+ AND p.period_start = locked.period_start
+ AND p.period_end = locked.period_end
+ )
+ RETURNING locked.workspace_id, locked.period_start, locked.period_end
+)
+UPDATE autopilot_quota_period AS p
+SET reserved_count = reserved_count - 1,
+ updated_at = now()
+FROM changed
+WHERE p.workspace_id = changed.workspace_id
+ AND p.period_start = changed.period_start
+ AND p.period_end = changed.period_end
+RETURNING p.*;
+
+-- name: ListRecoverableAutopilotQuotaReservations :many
+SELECT r.*
+FROM autopilot_quota_reservation r
+LEFT JOIN autopilot_run ar ON ar.quota_reservation_id = r.id
+WHERE r.state = 'reserved'
+ AND (
+ (
+ r.created_at < @terminal_created_before
+ AND (ar.id IS NULL OR ar.status IN ('completed', 'failed', 'skipped'))
+ )
+ OR (
+ -- Manual/API requests have no durable retry owner. Reclaim only an
+ -- hours-old partial run with neither a linked side effect nor even
+ -- an unlinked task row; schedule and webhook retries repair their
+ -- own partial state and are deliberately excluded.
+ r.created_at < @partial_created_before
+ AND ar.source IN ('manual', 'api')
+ AND (
+ ar.status = 'pending'
+ OR (ar.status = 'issue_created' AND ar.issue_id IS NULL)
+ OR (ar.status = 'running' AND ar.task_id IS NULL)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue task
+ WHERE task.autopilot_run_id = ar.id
+ )
+ )
+ )
+ORDER BY r.created_at
+LIMIT @row_limit;
diff --git a/server/pkg/db/queries/webhook_delivery.sql b/server/pkg/db/queries/webhook_delivery.sql
index 6f3795ba2c..fe365b4656 100644
--- a/server/pkg/db/queries/webhook_delivery.sql
+++ b/server/pkg/db/queries/webhook_delivery.sql
@@ -10,14 +10,20 @@ INSERT INTO webhook_delivery (
workspace_id, autopilot_id, trigger_id, provider, event,
dedupe_key, dedupe_source, signature_status, status,
selected_headers, content_type, raw_body,
- replayed_from_delivery_id
+ replayed_from_delivery_id, replay_idempotency_key, reason_code
) VALUES (
$1, $2, $3, $4, $5,
sqlc.narg('dedupe_key'), sqlc.narg('dedupe_source'), $6, $7,
$8, sqlc.narg('content_type'), sqlc.narg('raw_body'),
- sqlc.narg('replayed_from_delivery_id')
+ sqlc.narg('replayed_from_delivery_id'), sqlc.narg('replay_idempotency_key'),
+ sqlc.narg('reason_code')
) RETURNING *;
+-- name: GetWebhookReplayByIdempotencyKey :one
+SELECT * FROM webhook_delivery
+WHERE replayed_from_delivery_id = $1 AND replay_idempotency_key = $2
+LIMIT 1;
+
-- name: GetWebhookDelivery :one
SELECT * FROM webhook_delivery
WHERE id = $1;
@@ -119,6 +125,7 @@ SET status = $3,
autopilot_run_id = sqlc.narg('autopilot_run_id'),
dispatch_attempts = dispatch_attempts + 1,
error = sqlc.narg('error'),
+ reason_code = sqlc.narg('reason_code'),
lease_token = NULL,
lease_expires_at = NULL,
last_attempt_at = now()
@@ -147,6 +154,7 @@ RETURNING *;
UPDATE webhook_delivery
SET status = $2,
error = sqlc.narg('error'),
+ reason_code = sqlc.narg('reason_code'),
response_status = sqlc.narg('response_status'),
response_body = sqlc.narg('response_body'),
last_attempt_at = now()
@@ -168,7 +176,7 @@ SELECT
d.attempt_count, d.content_type, d.response_status,
d.autopilot_run_id, d.replayed_from_delivery_id, d.error,
d.received_at, d.last_attempt_at, d.created_at,
- d.available_at, d.dispatch_attempts
+ d.available_at, d.dispatch_attempts, d.reason_code, d.replay_idempotency_key
FROM webhook_delivery d
JOIN autopilot a ON a.id = d.autopilot_id
WHERE d.autopilot_id = $1
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index aa31b2df33..1f7ad4602d 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -533,6 +533,14 @@ WHERE autopilot_id IN (
SELECT id FROM autopilot WHERE autopilot.workspace_id = $1
);
+-- name: DeleteWorkspaceAutopilotQuotaReservations :exec
+DELETE FROM autopilot_quota_reservation
+WHERE autopilot_quota_reservation.workspace_id = $1;
+
+-- name: DeleteWorkspaceAutopilotQuotaPeriods :exec
+DELETE FROM autopilot_quota_period
+WHERE autopilot_quota_period.workspace_id = $1;
+
-- name: DeleteWorkspaceAutopilotChildren :exec
WITH
deleted_triggers AS (