Skip to content

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

Go

MUL-4502: make autopilot webhook admission durable (#5386)

Multica Evee07b5403ab9d
diff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdx
index 493e9ab19c..4b4706cffe 100644
--- a/apps/docs/content/docs/autopilots.ja.mdx
+++ b/apps/docs/content/docs/autopilots.ja.mdx
@@ -58,7 +58,7 @@ multica autopilot trigger <autopilot-id>
https://<your-multica-host>/api/webhooks/autopilots/awt_…
```
-その URL に任意の JSON を POST してください — Multica は `source = webhook` で実行を記録し、本文を実行の `trigger_payload` として保存し、schedule トリガーとまったく同じ方法でエージェントをディスパッチします。
+その URL に任意の JSON を POST してください。Multica はまず配信を永続化して `202 Accepted` を返し、その後データベース-backed worker が `source = webhook` の実行を記録してエージェントをディスパッチします。受付とディスパッチの間にサーバーが再起動しても、キュー済みの配信は失われません。
```bash
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -90,6 +90,11 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
GitHub のようなソースを構成するときは、content type を `application/json` に設定してください — フォームエンコードされた webhook payload は受け付けられません。
+GitHub の配信は `X-GitHub-Delivery` で重複排除されます。汎用の送信元は
+`Idempotency-Key` を指定できます。同じキーで再試行すると、元のキュー済み配信と
+run が再利用されます。どちらのヘッダーもない場合は安定したイベント ID がないため、
+重複排除はベストエフォートになります。
+
### イベントフィルター
新しい webhook トリガーはインバウンドの POST ごとに発火します。単一用途の URL には問題ありませんが、多数のイベントタイプをファンアウトするソース(GitHub が代表的です — 単一のリポジトリ webhook 一つが `push`、`pull_request`、`workflow_run`、`check_suite` などを配信できます)にはノイズになります。webhook トリガーの**イベントフィルター(Event filters)**セクションを使うと、実際に実行をディスパッチするイベントを制限でき、それ以外のすべては `status = ignored`、`reason = event_filtered` で配信履歴に記録され、実行もイシューも作成されません。
@@ -168,7 +173,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
-H 'X-GitHub-Event: workflow_run' \
-H 'Content-Type: application/json' \
-d '{"action":"completed"}'
-# → 200 {"status":"accepted", ...}
+# → 202 {"status":"queued", "delivery_id":"…", ...}
# Filtered — same event, action not in allowlist
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -189,10 +194,9 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
### ステータスコードの意味
-Multica は正常な no-op の結果に対して `status` フィールド付きで `200 OK` を返すため、プロバイダーの webhook 再試行メカニズムが URL を叩き続けることはありません。
+有効でアクティブな配信は、永続化された後に `202 Accepted` で確認されます。`{"status":"queued","delivery_id":"…"}` は worker がディスパッチを所有したことを示します。no-op と重複は `200 OK` を返します。
-- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}` — 実行がディスパッチされました。
-- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}` — `run_only` オートパイロットでは、割り当て先のランタイムがオフラインのためタスクはキューに入りません。`create_issue` オートパイロットは追跡可能な issue を作成し、ランタイム復帰後に引き継げるようにします。
+- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 同じ冪等キーの配信は既に受け付け済みです。元の配信がまだキュー中なら `run_id` はありません。
- `{"status":"ignored","reason":"trigger_disabled"}` — トリガーが無効になっています。
- `{"status":"ignored","reason":"autopilot_paused"}` — オートパイロットが一時停止しています。
- `{"status":"ignored","reason":"autopilot_archived"}` — オートパイロットがアーカイブされています。
@@ -200,9 +204,10 @@ Multica は正常な no-op の結果に対して `status` フィールド付き
2xx 以外の応答は実際の失敗を扱います。
- `400` — 無効な JSON、スカラー本文、空の本文。
+- `401` — 設定済みの webhook 署名がないか無効です。
- `404` — 不明なトークン(`{"error":"webhook not found"}`)。
- `413` — payload が 256 KiB を超えました。
-- `429` — トークンごとのレート制限超過(デフォルトは 60 req/min)。
+- `429` — IP の絶対上限、または不明なトークン / 無効な署名の試行上限を超えました。応答には `Retry-After` が含まれます。有効な配信は worker のトリガー別予算によって拒否されず、予算が戻るまでキューに残ります。
### セルフホスト: 公開 URL を構成する
diff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdx
index 8b8e33d312..5428f2c860 100644
--- a/apps/docs/content/docs/autopilots.ko.mdx
+++ b/apps/docs/content/docs/autopilots.ko.mdx
@@ -58,7 +58,7 @@ multica autopilot trigger <autopilot-id>
https://<your-multica-host>/api/webhooks/autopilots/awt_…
```
-그 URL로 아무 JSON이나 POST하세요 — Multica는 `source = webhook`로 실행을 기록하고, 본문을 실행의 `trigger_payload`로 저장한 다음, schedule 트리거와 정확히 동일한 방식으로 에이전트를 디스패치합니다.
+그 URL로 아무 JSON이나 POST하세요. Multica는 먼저 전달을 영구 저장하고 `202 Accepted`를 반환한 뒤, 데이터베이스-backed worker가 `source = webhook` 실행을 기록하고 에이전트를 디스패치합니다. 수신과 디스패치 사이에 서버가 재시작되어도 큐에 저장된 전달은 유실되지 않습니다.
```bash
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -90,6 +90,11 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
GitHub 같은 소스를 구성할 때는 content type을 `application/json`으로 설정하세요 — 폼 인코딩된 webhook payload는 허용되지 않습니다.
+GitHub 전달은 `X-GitHub-Delivery`로 중복 제거됩니다. 일반 발신자는
+`Idempotency-Key`를 제공할 수 있습니다. 같은 키로 재시도하면 기존에 큐에 저장된
+전달과 run을 재사용합니다. 두 헤더가 모두 없으면 안정적인 이벤트 ID가 없으므로
+중복 제거는 최선 노력 방식으로만 제공됩니다.
+
### 이벤트 필터
새 webhook 트리거는 인바운드 POST마다 발화합니다. 단일 용도 URL에는 괜찮지만, 여러 이벤트 타입을 팬아웃하는 소스(GitHub가 대표적입니다 — 단일 저장소 webhook 하나가 `push`, `pull_request`, `workflow_run`, `check_suite` 등을 전달할 수 있습니다)에는 시끄럽습니다. webhook 트리거의 **이벤트 필터(Event filters)** 섹션을 사용하면 실제로 실행을 디스패치할 이벤트를 제한할 수 있으며, 그 외의 모든 것은 `status = ignored`, `reason = event_filtered`로 전달 히스토리에 기록되고 실행이나 이슈는 생성되지 않습니다.
@@ -168,7 +173,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
-H 'X-GitHub-Event: workflow_run' \
-H 'Content-Type: application/json' \
-d '{"action":"completed"}'
-# → 200 {"status":"accepted", ...}
+# → 202 {"status":"queued", "delivery_id":"…", ...}
# Filtered — same event, action not in allowlist
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -189,10 +194,9 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
### 상태 코드 의미
-Multica는 정상적인 no-op 결과에 대해 `status` 필드와 함께 `200 OK`를 반환하므로, 제공자의 webhook 재시도 메커니즘이 URL을 계속 두드리지 않습니다.
+유효하고 활성 상태인 전달은 영구 저장된 뒤 `202 Accepted`로 확인됩니다. `{"status":"queued","delivery_id":"…"}`는 worker가 디스패치를 맡았음을 뜻합니다. no-op과 중복은 `200 OK`를 반환합니다.
-- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}` — 실행이 디스패치되었습니다.
-- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}` — `run_only` 오토파일럿에서는 수신 대상의 런타임이 오프라인이어서 작업을 큐에 넣지 않습니다. `create_issue` 오토파일럿은 추적 가능한 이슈를 계속 생성하므로 런타임이 돌아오면 작업을 이어받을 수 있습니다.
+- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — 같은 멱등 키의 전달이 이미 수신되었습니다. 원본 전달이 아직 큐에 있으면 `run_id`는 생략됩니다.
- `{"status":"ignored","reason":"trigger_disabled"}` — 트리거가 비활성화되어 있습니다.
- `{"status":"ignored","reason":"autopilot_paused"}` — 오토파일럿이 일시 정지되어 있습니다.
- `{"status":"ignored","reason":"autopilot_archived"}` — 오토파일럿이 보관되어 있습니다.
@@ -200,9 +204,10 @@ Multica는 정상적인 no-op 결과에 대해 `status` 필드와 함께 `200 OK
2xx가 아닌 응답은 실제 실패를 다룹니다.
- `400` — 유효하지 않은 JSON, 스칼라 본문, 빈 본문.
+- `401` — 설정된 webhook 서명이 없거나 유효하지 않습니다.
- `404` — 알 수 없는 토큰(`{"error":"webhook not found"}`).
- `413` — payload가 256 KiB를 초과했습니다.
-- `429` — 토큰별 속도 제한 초과(기본값 60 req/min).
+- `429` — IP 절대 상한 또는 알 수 없는 토큰 / 잘못된 서명 시도 한도를 초과했습니다. 응답에는 `Retry-After`가 포함됩니다. 유효한 전달은 worker의 트리거별 예산 때문에 거부되지 않고, 예산이 복구될 때까지 큐에 남습니다.
### 자체 호스팅: 공개 URL 구성하기
diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdx
index cc8cf87a2b..f60dd438ea 100644
--- a/apps/docs/content/docs/autopilots.mdx
+++ b/apps/docs/content/docs/autopilots.mdx
@@ -59,9 +59,11 @@ on the autopilot detail page; Multica generates a unique URL of the shape:
https://<your-multica-host>/api/webhooks/autopilots/awt_…
```
-POST any JSON to that URL — Multica records a run with `source = webhook`,
-stores the body as the run's `trigger_payload`, and dispatches the agent
-exactly the way a schedule trigger would.
+POST any JSON to that URL. Multica first stores a durable delivery and returns
+`202 Accepted`, then a database-backed worker records a run with
+`source = webhook`, stores the body as the run's `trigger_payload`, and
+dispatches the agent exactly the way a schedule trigger would. A server restart
+between admission and dispatch does not lose the queued delivery.
```bash
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -99,6 +101,11 @@ nothing matches, the event is `webhook.received`.
When configuring GitHub or similar sources, set the content type to
`application/json` — form-encoded webhook payloads are not accepted.
+GitHub deliveries are deduplicated by `X-GitHub-Delivery`; generic senders can
+provide `Idempotency-Key`. Retries with the same key reuse the original queued
+delivery and run. Without either header, delivery remains best-effort because
+there is no stable event identity to deduplicate.
+
### Event filters
A new webhook trigger fires on every inbound POST, which is fine for a
@@ -209,7 +216,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
-H 'X-GitHub-Event: workflow_run' \
-H 'Content-Type: application/json' \
-d '{"action":"completed"}'
-# → 200 {"status":"accepted", ...}
+# → 202 {"status":"queued", "delivery_id":"…", ...}
# Filtered — same event, action not in allowlist
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -235,15 +242,18 @@ autopilot. Treat it like a token:
### Status-code semantics
-Multica returns `200 OK` with a `status` field for normal no-op outcomes so
-your provider's webhook-retry machinery doesn't keep hammering the URL:
+Multica acknowledges an active, valid delivery only after it is durable:
+
+- `202 {"status":"queued","delivery_id":"…","autopilot_id":"…","trigger_id":"…"}`
+ — the delivery is stored and the worker owns dispatch. The eventual run and
+ any admission skip are visible in delivery/run history.
+
+Normal no-op and deduplication outcomes return `200 OK` so providers do not
+retry them indefinitely:
-- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}`
- — a run was dispatched.
-- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}`
- — for `run_only` autopilots, the assignee's runtime is offline and no task
- was queued. `create_issue` autopilots still create the tracked issue so the
- work stays visible and can be claimed when the runtime returns.
+- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` — the provider's
+ idempotency key was already admitted. `run_id` is omitted while the original
+ delivery is still queued.
- `{"status":"ignored","reason":"trigger_disabled"}` — the trigger is disabled.
- `{"status":"ignored","reason":"autopilot_paused"}` — the autopilot is paused.
- `{"status":"ignored","reason":"autopilot_archived"}` — the autopilot is archived.
@@ -251,9 +261,13 @@ your provider's webhook-retry machinery doesn't keep hammering the URL:
Non-2xx responses cover real failures:
- `400` — invalid JSON, scalar body, or empty body.
+- `401` — a configured webhook signature is missing or invalid.
- `404` — unknown token (`{"error":"webhook not found"}`).
- `413` — payload exceeded 256 KiB.
-- `429` — per-token rate limit exceeded (defaults to 60 req/min).
+- `429` — the high absolute IP ceiling was exceeded, or the IP accumulated too
+ many unknown-token/invalid-signature attempts. Responses include
+ `Retry-After`. Valid admitted deliveries are not rejected by the worker's
+ per-trigger budget; they remain queued until that budget is available.
### Self-hosted: configure your public URL
diff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdx
index 4c48be6dd2..81b08f25cc 100644
--- a/apps/docs/content/docs/autopilots.zh.mdx
+++ b/apps/docs/content/docs/autopilots.zh.mdx
@@ -59,9 +59,10 @@ Autopilot 也可以由入站 HTTP webhook 触发。在详情页添加一个 **We
https://<你的 Multica host>/api/webhooks/autopilots/awt_…
```
-向这个 URL POST 任意 JSON——Multica 会记录一条 `source = webhook` 的
-run,把请求体保存为 run 的 `trigger_payload`,然后按和 schedule 触发器
-完全一致的方式派发给智能体。
+向这个 URL POST 任意 JSON。Multica 会先持久化投递并返回
+`202 Accepted`,再由数据库 worker 记录一条 `source = webhook` 的 run,
+把请求体保存为 run 的 `trigger_payload`,然后按和 schedule 触发器完全
+一致的方式派发给智能体。接收与派发之间即使服务重启,已排队的投递也不会丢失。
```bash
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -98,6 +99,10 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
配置 GitHub 之类的来源时,请把 content type 设为 `application/json`——
表单编码的 webhook payload 在 v1 里不接受。
+GitHub 投递用 `X-GitHub-Delivery` 去重;通用发送方可以提供
+`Idempotency-Key`。同一个 key 的重试会复用原来的排队投递和 run。不带
+这两个 header 时,因为没有稳定的事件标识,投递只能提供尽力而为的语义。
+
### 事件过滤
新建的 webhook 触发器对每一条入站 POST 都会触发,这在单一用途的 URL
@@ -198,7 +203,7 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
-H 'X-GitHub-Event: workflow_run' \
-H 'Content-Type: application/json' \
-d '{"action":"completed"}'
-# → 200 {"status":"accepted", ...}
+# → 202 {"status":"queued", "delivery_id":"…", ...}
# 被过滤 —— 同样的事件,但 action 不在白名单
curl -X POST "$MULTICA_WEBHOOK_URL" \
@@ -223,14 +228,16 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
### 状态码语义
-正常的 no-op 路径都返回 `200 OK` 加 `status` 字段,避免外部 webhook 重试
-机制反复打:
+有效且活跃的投递只有持久化后才会确认:
+
+- `202 {"status":"queued","delivery_id":"…","autopilot_id":"…","trigger_id":"…"}`
+ —— 投递已经持久化,后续派发由 worker 接管。最终 run 和准入跳过原因可以在
+ 投递 / run 历史里查看。
+
+正常 no-op 和去重路径返回 `200 OK`,避免外部 webhook 无限重试:
-- `{"status":"accepted","run_id":"…","autopilot_id":"…","trigger_id":"…"}`
- —— 已派发一次 run。
-- `{"status":"skipped","run_id":"…","reason":"agent runtime is offline at dispatch time"}`
- —— 对 `run_only` Autopilot,受派智能体的 runtime 离线且不会入队;
- `create_issue` Autopilot 仍会创建可追踪 issue,等 runtime 回来后继续认领。
+- `{"status":"duplicate","delivery_id":"…","run_id":"…"}` —— 发送方的
+ 幂等 key 已经接收;原投递仍排队时不带 `run_id`。
- `{"status":"ignored","reason":"trigger_disabled"}` —— 触发器已禁用。
- `{"status":"ignored","reason":"autopilot_paused"}` —— Autopilot 已暂停。
- `{"status":"ignored","reason":"autopilot_archived"}` —— Autopilot 已归档。
@@ -238,9 +245,12 @@ curl -X POST "$MULTICA_WEBHOOK_URL" \
非 2xx 是真正的失败:
- `400` —— 无效 JSON、scalar body、空 body。
+- `401` —— 已配置的 webhook 签名缺失或无效。
- `404` —— 未知 token(`{"error":"webhook not found"}`)。
- `413` —— 请求体超过 256 KiB。
-- `429` —— 单 token 速率限制(默认 60 次 / 分钟)。
+- `429` —— 命中高位 IP 绝对上限,或者该 IP 累积了过多未知 token / 无效
+ 签名请求;响应会带 `Retry-After`。worker 的单触发器预算不会拒绝已经接收的
+ 有效投递,只会让它继续排队,等预算恢复后再派发。
### 自托管:配置公开 URL
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 213a99ec6f..605e12b955 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -355,6 +355,8 @@ describe("ApiClient schema fallback", () => {
const res = await client.listAutopilotDeliveries("ap-1");
expect(res.deliveries).toHaveLength(1);
expect(res.deliveries[0]?.status).toBe("quarantined");
+ expect(res.deliveries[0]?.dispatch_attempts).toBe(0);
+ expect(res.deliveries[0]?.available_at).toBe("");
});
});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 84d8c38f53..1872bac1e9 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -918,6 +918,10 @@ const WebhookDeliverySchema = z.object({
signature_status: z.string(),
status: z.string(),
attempt_count: z.number().default(0),
+ // Older servers predate the durable dispatch queue. Defaults preserve
+ // compatibility while the UI rolls out alongside the new worker.
+ dispatch_attempts: z.number().default(0),
+ available_at: z.string().default(""),
content_type: z.string().nullable(),
response_status: z.number().nullable(),
autopilot_run_id: z.string().nullable(),
@@ -1002,6 +1006,8 @@ export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {
signature_status: "not_required",
status: "queued",
attempt_count: 0,
+ dispatch_attempts: 0,
+ available_at: "",
content_type: null,
response_status: null,
autopilot_run_id: null,
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index 0d52bdbb47..e26c2b2a04 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -226,6 +226,8 @@ export interface WebhookDelivery {
signature_status: WebhookSignatureStatus;
status: WebhookDeliveryStatus;
attempt_count: number;
+ dispatch_attempts: number;
+ available_at: string;
content_type: string | null;
response_status: number | null;
autopilot_run_id: string | null;
diff --git a/packages/views/autopilots/components/webhook-deliveries-section.tsx b/packages/views/autopilots/components/webhook-deliveries-section.tsx
index e32b9c91bc..7c2448b364 100644
--- a/packages/views/autopilots/components/webhook-deliveries-section.tsx
+++ b/packages/views/autopilots/components/webhook-deliveries-section.tsx
@@ -293,6 +293,16 @@ function DeliveryDetailDialog({
label={t(($) => $.deliveries.detail.attempt_count)}
value={String(full.attempt_count)}
/>
+ <MetaRow
+ label={t(($) => $.deliveries.detail.dispatch_attempts)}
+ value={String(full.dispatch_attempts)}
+ />
+ {full.status === "queued" && (
+ <MetaRow
+ label={t(($) => $.deliveries.detail.available_at)}
+ value={formatDate(full.available_at)}
+ />
+ )}
<MetaRow
label={t(($) => $.deliveries.detail.response_status)}
value={full.response_status != null ? String(full.response_status) : "—"}
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 09d83a4603..347ae66e48 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -203,6 +203,8 @@
"received_at": "Received",
"last_attempt_at": "Last attempt",
"attempt_count": "Attempts",
+ "dispatch_attempts": "Dispatch attempts",
+ "available_at": "Next dispatch",
"response_status": "Response",
"dedupe_key": "Dedupe key",
"dedupe_source": "Dedupe source",
diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.json
index 6e73b8a7a9..514ebea7a9 100644
--- a/packages/views/locales/ja/autopilots.json
+++ b/packages/views/locales/ja/autopilots.json
@@ -203,6 +203,8 @@
"received_at": "受信",
"last_attempt_at": "最終試行",
"attempt_count": "試行回数",
+ "dispatch_attempts": "ディスパッチ試行回数",
+ "available_at": "次回ディスパッチ",
"response_status": "レスポンス",
"dedupe_key": "重複排除キー",
"dedupe_source": "重複排除ソース",
diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.json
index 27bf73035b..ddeb199015 100644
--- a/packages/views/locales/ko/autopilots.json
+++ b/packages/views/locales/ko/autopilots.json
@@ -203,6 +203,8 @@
"received_at": "수신",
"last_attempt_at": "마지막 시도",
"attempt_count": "시도 횟수",
+ "dispatch_attempts": "디스패치 시도 횟수",
+ "available_at": "다음 디스패치",
"response_status": "응답",
"dedupe_key": "중복 제거 키",
"dedupe_source": "중복 제거 소스",
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index 63a5be3aa1..b514d31963 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -203,6 +203,8 @@
"received_at": "接收时间",
"last_attempt_at": "最近一次尝试",
"attempt_count": "尝试次数",
+ "dispatch_attempts": "分发尝试次数",
+ "available_at": "下次分发时间",
"response_status": "响应状态码",
"dedupe_key": "去重 Key",
"dedupe_source": "去重来源",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 5d0caf0771..1d753f6b19 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -389,6 +389,9 @@ func main() {
go heartbeatScheduler.Run(sweepCtx)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
go runDBStatsLogger(sweepCtx, pool)
+ if h.WebhookDeliveryWorker != nil {
+ go h.WebhookDeliveryWorker.Run(sweepCtx)
+ }
// Channel inbound supervisor (MUL-3620): holds the §4.4 WS lease per
// installation and drives each channel.Channel. It is built
@@ -472,6 +475,9 @@ func main() {
// final batch of queued heartbeat bumps.
sweepCancel()
heartbeatScheduler.Stop()
+ if h.WebhookDeliveryWorker != nil && !h.WebhookDeliveryWorker.WaitWithTimeout(5*time.Second) {
+ slog.Warn("webhook delivery worker did not exit within shutdown timeout")
+ }
// Join the channel supervisor's per-installation goroutines so the
// lease renewer can issue a final release before process exit;
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 5596e602c6..9104609121 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -210,6 +210,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.LivenessStore = handler.NewRedisLivenessStore(rdb)
h.WebhookRateLimiter = handler.NewRedisWebhookRateLimiter(rdb, handler.DefaultWebhookRateLimit())
h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())
+ h.WebhookAbsoluteIPRateLimiter = handler.NewRedisWebhookAbsoluteIPRateLimiter(rdb, handler.DefaultWebhookAbsoluteIPRateLimit())
}
// Channel engine (MUL-3620): the platform-agnostic inbound runtime.
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index ce3f0dde4d..ba8ed66a9b 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -14,6 +14,7 @@ import (
"log/slog"
"net/http"
"net/netip"
+ "strconv"
"strings"
"time"
@@ -21,6 +22,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -306,39 +308,37 @@ func selectedHeadersJSON(headers http.Header) []byte {
// autopilots. It runs OUTSIDE the authenticated route group: the bearer
// token in the URL path IS the credential.
//
-// Flow (persist-first, sync-dispatch):
+// Flow (persist-first, durable async dispatch):
//
-// 1. Per-IP rate limit (gate before any DB I/O).
+// 1. High absolute per-IP ceiling plus a non-consuming check for prior
+// bad-credential debt (both before DB I/O).
// 2. Token lookup. ErrNoRows → 404; other DB errors → 500.
-// 3. Per-token rate limit.
-// 4. Read raw body (capped). Oversized → 413.
-// 5. Normalize JSON envelope. Invalid → 400 (no persistence — there is no
+// 3. Read raw body (capped). Oversized → 413.
+// 4. Normalize JSON envelope. Invalid → 400 (no persistence — there is no
// dedupe identifier we can trust from an unparsable body).
-// 6. Extract dedupe key from headers per provider.
-// 7. Verify signature (or `not_required` when no secret is configured).
-// 8. INSERT webhook_delivery row (status=queued). On dedupe collision (23505
+// 5. Extract dedupe key from headers per provider.
+// 6. Verify signature (or `not_required` when no secret is configured).
+// 7. INSERT webhook_delivery row (status=queued). On dedupe collision (23505
// against `(trigger_id, dedupe_key)`) treat as duplicate: bump
// attempt_count on the existing row and return its delivery_id +
// autopilot_run_id with 200.
-// 9. If signature invalid/missing: UPDATE delivery → rejected, return 401.
-// 10. If trigger disabled / autopilot paused / archived: UPDATE delivery →
+// 8. If signature invalid/missing: charge bad-credential debt, UPDATE
+// delivery → rejected, return 401.
+// 9. If trigger disabled / autopilot paused / archived: UPDATE delivery →
// ignored, return 200.
-// 11. Dispatch the autopilot synchronously. UPDATE delivery → dispatched
-// (with autopilot_run_id) or failed. Return 200 (skipped runs surface
-// their `reason`).
-// 12. Bump last_fired_at after dispatch — even on the skipped path — so the
-// trigger's "last seen" is accurate.
+// 10. Persist the 202 acknowledgement and wake the database-leased worker.
+// The worker re-checks state/filter scope, dispatches idempotently, and
+// bumps last_fired_at after it owns a run.
//
// Response shapes:
-// - 200 {"status":"accepted", "delivery_id", "run_id", "autopilot_id", "trigger_id"}
-// - 200 {"status":"skipped", "delivery_id", "run_id", "reason"}
+// - 202 {"status":"queued", "delivery_id", "autopilot_id", "trigger_id"}
// - 200 {"status":"ignored", "delivery_id", "reason"}
// - 200 {"status":"duplicate", "delivery_id", "run_id?"}
// - 400 {"error":"..."} — invalid JSON / scalar / empty
// - 401 {"status":"rejected", "delivery_id", "reason":"..."} — signature failure
// - 404 {"error":"webhook not found"} — unknown token
// - 413 {"error":"payload too large"} — body exceeded cap
-// - 429 {"error":"rate limit exceeded"} — over per-IP/token budget
+// - 429 {"error":"rate limit exceeded"} — IP safety/debt gate
// - 500 {"error":"..."} — internal failure
func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request) {
token := chi.URLParam(r, "token")
@@ -347,16 +347,17 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 1. Per-IP rate limit BEFORE we hit Postgres. Bounds the DB-probe blast
- // radius for an attacker spraying random tokens. A spray of bad
- // signatures still counts here — fast-path 429 stops budget burn.
- if h.WebhookIPRateLimiter != nil {
- if ip := h.clientIPForRateLimit(r); ip != "" {
- if !h.WebhookIPRateLimiter.Allow(r.Context(), ip) {
- writeError(w, http.StatusTooManyRequests, "rate limit exceeded")
- return
- }
- }
+ // 1. Always retain a high absolute ceiling. The lower shared-IP limiter
+ // tracks only requests already classified as bad credentials, so a NAT
+ // full of legitimate GitHub hooks does not consume its budget.
+ ip := h.clientIPForRateLimit(r)
+ if ip != "" && h.WebhookAbsoluteIPRateLimiter != nil && !h.WebhookAbsoluteIPRateLimiter.Allow(r.Context(), ip) {
+ writeWebhookRateLimit(w, r, h.WebhookAbsoluteIPRateLimiter, ip, "absolute_ip", h.Metrics)
+ return
+ }
+ if ip != "" && h.WebhookIPRateLimiter != nil && !webhookLimiterCheck(r.Context(), h.WebhookIPRateLimiter, ip) {
+ writeWebhookRateLimit(w, r, h.WebhookIPRateLimiter, ip, "bad_credential_ip", h.Metrics)
+ return
}
// 2. Token lookup. Distinguish "no row" from "DB error": collapsing both
@@ -366,6 +367,9 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
trigRow, err := h.Queries.GetWebhookTriggerByToken(r.Context(), pgtype.Text{String: token, Valid: true})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
+ if ip != "" && h.WebhookIPRateLimiter != nil {
+ h.WebhookIPRateLimiter.Allow(r.Context(), ip)
+ }
writeError(w, http.StatusNotFound, "webhook not found")
return
}
@@ -376,15 +380,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
middleware.SetWebhookTriggerID(r, uuidToString(trigRow.ID))
- // 3. Per-token rate limit.
- if h.WebhookRateLimiter != nil {
- if !h.WebhookRateLimiter.Allow(r.Context(), token) {
- writeError(w, http.StatusTooManyRequests, "rate limit exceeded")
- return
- }
- }
-
- // 4. Body size cap + JSON validation. http.MaxBytesReader stops the read
+ // 3. Body size cap + JSON validation. http.MaxBytesReader stops the read
// mid-stream once the cap is exceeded so an oversized payload is
// rejected before being fully buffered.
r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBodyBytes)
@@ -399,7 +395,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 5. Cross-check autopilot/workspace consistency BEFORE we persist the
+ // 4. Cross-check autopilot/workspace consistency BEFORE we persist the
// delivery — webhook_delivery.workspace_id is NOT NULL and a stale FK
// row would otherwise fail INSERT after we've already paid the body
// read. Same ErrNoRows-vs-DB-error split as token lookup.
@@ -425,7 +421,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 6. Normalize body. Invalid JSON → 400 without persistence: we have no
+ // 5. Normalize body. Invalid JSON → 400 without persistence: we have no
// dedupe identifier from the body, and replaying an unparsable payload
// is not useful.
envelope, err := normalizeWebhookPayload(body, r.Header)
@@ -433,13 +429,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusBadRequest, err.Error())
return
}
- envelopeBytes, err := json.Marshal(envelope)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to encode envelope")
- return
- }
-
- // 7. Provider + dedupe + signature.
+ // 6. Provider + dedupe + signature.
provider := trigRow.Provider
if provider == "" {
provider = "generic"
@@ -447,7 +437,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
dedupeKey, dedupeSource := extractDedupeKey(provider, r.Header)
sigStatus := verifyWebhookSignatureForProvider(provider, trigRow.SigningSecret.String, r.Header, body)
- // 8. Persist (INSERT delivery). Dedupe collision → bump existing row.
+ // 7. Persist (INSERT delivery). Dedupe collision → bump existing row.
delivery, dup, err := h.persistInboundDelivery(r, persistDeliveryInput{
WorkspaceID: autopilot.WorkspaceID,
AutopilotID: autopilot.ID,
@@ -480,11 +470,14 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
if delivery.AutopilotRunID.Valid {
resp["run_id"] = uuidToString(delivery.AutopilotRunID)
}
+ if delivery.Status == deliveryStatusQueued && h.WebhookDeliveryWorker != nil {
+ h.WebhookDeliveryWorker.Notify()
+ }
writeJSON(w, http.StatusOK, resp)
return
}
- // 9. Signature failure → rejected delivery + 401. No dispatch, no replay.
+ // 8. Signature failure → rejected delivery + 401. No dispatch, no replay.
// Providers will look for 4xx feedback when their secret is wrong.
if sigStatus == sigStatusInvalid || sigStatus == sigStatusMissing {
reason := "invalid_signature"
@@ -496,12 +489,15 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
"delivery_id": uuidToString(delivery.ID),
"reason": reason,
}
+ if ip != "" && h.WebhookIPRateLimiter != nil {
+ h.WebhookIPRateLimiter.Allow(r.Context(), ip)
+ }
h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusRejected, http.StatusUnauthorized, respBody, reason)
writeJSON(w, http.StatusUnauthorized, respBody)
return
}
- // 10. Trigger disabled / autopilot paused / archived → ignored. We return
+ // 9. Trigger disabled / autopilot paused / archived → ignored. We return
// 200 so the sender's webhook-retry machinery doesn't keep hammering
// us; the "ignored" status + delivery row makes the no-op visible if
// the operator inspects the delivery log.
@@ -524,7 +520,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 11. Event filter scope → ignored. If the trigger declares a concrete
+ // 10. Event filter scope → ignored. If the trigger declares a concrete
// event_filters list and the incoming event is outside that scope,
// record an ignored delivery without creating an expensive run/task.
if !webhookEventAllowedByTriggerScope(trigRow.EventFilters, envelope) {
@@ -539,74 +535,31 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 12. Dispatch synchronously. DispatchAutopilot publishes WS events,
- // persists trigger_payload on autopilot_run, runs the admission
- // check (offline runtime → skipped), and bumps last_run_at.
- run, err := h.AutopilotService.DispatchAutopilot(
- r.Context(),
- autopilot,
- trigRow.ID,
- "webhook",
- envelopeBytes,
- )
- if err != nil {
- slog.Warn("webhook dispatch failed",
- "trigger_id", uuidToString(trigRow.ID),
- "autopilot_id", uuidToString(autopilot.ID),
- "error", err,
- )
- respBody := map[string]any{"error": "failed to dispatch autopilot"}
- // DispatchAutopilot may return a non-nil run alongside an error
- // (e.g. when the run row was created but the downstream dispatch
- // failed). Link the run on the delivery anyway so the Deliveries
- // UI can show which run row corresponds to the failure.
- if run != nil {
- h.finaliseDeliveryWithRun(r, delivery.ID, deliveryStatusFailed, run.ID, http.StatusInternalServerError, respBody)
- } else {
- h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusFailed, http.StatusInternalServerError, respBody, err.Error())
- }
- writeJSON(w, http.StatusInternalServerError, respBody)
- return
- }
-
- // 13. Bump last_fired_at after dispatch returns — including the skipped
- // path — so paused early-returns above don't corrupt "last fired".
- if err := h.Queries.TouchAutopilotTriggerFiredAt(r.Context(), trigRow.ID); err != nil {
- slog.Warn("webhook: failed to touch last_fired_at",
- "trigger_id", uuidToString(trigRow.ID),
- "error", err,
- )
- }
-
- // 14. Persist the linkage delivery → run.
- //
- // The delivery row is always `dispatched` once we reach here: from the
- // ingress's perspective we handed the payload off to the autopilot
- // machinery and got a run id back. The autopilot may have skipped the
- // run (e.g. runtime offline) — that's reflected in the response status
- // + reason and in the linked run row, not in the delivery status. This
- // keeps the delivery enum tight and the Deliveries UI unambiguous
- // (`run.status` is the source of truth for what the run did).
+ // 11. The queued INSERT above is the durable admission point. Best-effort
+ // persist the exact acknowledgement for operator correlation, then wake
+ // the worker. An acknowledgement metadata write failure must not turn an
+ // already-durable delivery into an HTTP failure.
respBody := map[string]any{
- "status": "accepted",
+ "status": "queued",
"delivery_id": uuidToString(delivery.ID),
- "run_id": uuidToString(run.ID),
"autopilot_id": uuidToString(autopilot.ID),
"trigger_id": uuidToString(trigRow.ID),
}
- if run.Status == "skipped" {
- respBody = map[string]any{
- "status": "skipped",
- "delivery_id": uuidToString(delivery.ID),
- "run_id": uuidToString(run.ID),
- }
- if run.FailureReason.Valid {
- respBody["reason"] = run.FailureReason.String
- }
+ bodyJSON, _ := json.Marshal(respBody)
+ if _, err := h.Queries.AcknowledgeWebhookDelivery(r.Context(), db.AcknowledgeWebhookDeliveryParams{
+ ID: delivery.ID,
+ ResponseStatus: pgtype.Int4{Int32: http.StatusAccepted, Valid: true},
+ ResponseBody: pgtype.Text{String: string(bodyJSON), Valid: true},
+ }); err != nil {
+ slog.Warn("webhook: persist acknowledgement metadata failed",
+ "delivery_id", uuidToString(delivery.ID),
+ "error", err,
+ )
}
- h.finaliseDeliveryWithRun(r, delivery.ID, deliveryStatusDispatched, run.ID, http.StatusOK, respBody)
-
- writeJSON(w, http.StatusOK, respBody)
+ if h.WebhookDeliveryWorker != nil {
+ h.WebhookDeliveryWorker.Notify()
+ }
+ writeJSON(w, http.StatusAccepted, respBody)
}
// ── Event filter helpers ────────────────────────────────────────────────────
@@ -902,6 +855,22 @@ func (h *Handler) deliveryProvider(ctx context.Context, id pgtype.UUID) string {
// ── Rate-limit / IP plumbing ────────────────────────────────────────────────
+func writeWebhookRateLimit(w http.ResponseWriter, r *http.Request, limiter WebhookRateLimiter, key, gate string, metrics *obsmetrics.BusinessMetrics) {
+ retryAfter := time.Second
+ if limiter != nil {
+ if retry := webhookLimiterRetryAfter(r.Context(), limiter, key); retry > 0 {
+ retryAfter = retry
+ }
+ }
+ seconds := int64((retryAfter + time.Second - 1) / time.Second)
+ if seconds < 1 {
+ seconds = 1
+ }
+ w.Header().Set("Retry-After", strconv.FormatInt(seconds, 10))
+ metrics.RecordWebhookRateLimited(gate)
+ writeError(w, http.StatusTooManyRequests, "rate limit exceeded")
+}
+
// clientIPForRateLimit returns the IP used as a rate-limit bucket key.
//
// Default behaviour: use the host portion of r.RemoteAddr. Forwarded
diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.go
index 32d790f8d0..d8cda5bd5a 100644
--- a/server/internal/handler/autopilot_webhook_handler_test.go
+++ b/server/internal/handler/autopilot_webhook_handler_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -111,7 +112,7 @@ func TestWebhookHandler_FiltersUndeclaredEvent(t *testing.T) {
})
w := postWebhook(t, *trig.WebhookToken, map[string]any{
- "action": "in_progress",
+ "action": "in_progress",
"workflow_run": map[string]any{"id": 123},
}, map[string]string{"X-GitHub-Event": "workflow_run"})
if w.Code != http.StatusOK {
@@ -149,18 +150,12 @@ func TestWebhookHandler_AllowsDeclaredEvent(t *testing.T) {
})
w := postWebhook(t, *trig.WebhookToken, map[string]any{
- "action": "completed",
+ "action": "completed",
"workflow_run": map[string]any{"id": 123},
}, map[string]string{"X-GitHub-Event": "workflow_run"})
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- if resp["status"] != "accepted" && resp["status"] != "skipped" {
- t.Fatalf("expected accepted or skipped, got %#v", resp)
+ delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
+ if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {
+ t.Fatalf("expected worker dispatch, got status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)
}
}
@@ -170,18 +165,12 @@ func TestWebhookHandler_EmptyFiltersAllowsAll(t *testing.T) {
trig := createWebhookTriggerViaHandler(t, apID)
w := postWebhook(t, *trig.WebhookToken, map[string]any{
- "action": "in_progress",
+ "action": "in_progress",
"workflow_run": map[string]any{"id": 123},
}, map[string]string{"X-GitHub-Event": "workflow_run"})
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- if resp["status"] != "accepted" && resp["status"] != "skipped" {
- t.Fatalf("expected accepted or skipped, got %#v", resp)
+ delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
+ if delivery.Status != deliveryStatusDispatched || !delivery.AutopilotRunID.Valid {
+ t.Fatalf("expected worker dispatch, got status=%s run=%v", delivery.Status, delivery.AutopilotRunID.Valid)
}
}
@@ -411,6 +400,48 @@ func postWebhook(t *testing.T, token string, body any, headers map[string]string
return w
}
+func requireQueuedWebhookResponse(t *testing.T, w *httptest.ResponseRecorder) string {
+ t.Helper()
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("expected 202 queued, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode queued response: %v", err)
+ }
+ if resp["status"] != "queued" {
+ t.Fatalf("expected queued status, got %#v", resp)
+ }
+ deliveryID, _ := resp["delivery_id"].(string)
+ if deliveryID == "" {
+ t.Fatalf("queued response missing delivery_id: %#v", resp)
+ }
+ return deliveryID
+}
+
+func processQueuedWebhookDelivery(t *testing.T, deliveryID string) db.WebhookDelivery {
+ t.Helper()
+ ctx := context.Background()
+ for i := 0; i < 20; i++ {
+ delivery, err := testHandler.Queries.GetWebhookDelivery(ctx, parseUUID(deliveryID))
+ if err != nil {
+ t.Fatalf("load queued delivery: %v", err)
+ }
+ if delivery.Status != deliveryStatusQueued {
+ return delivery
+ }
+ worked, err := testHandler.WebhookDeliveryWorker.ProcessNext(ctx)
+ if err != nil {
+ t.Fatalf("process queued delivery: %v", err)
+ }
+ if !worked {
+ t.Fatalf("delivery %s remained queued with no claimable work", deliveryID)
+ }
+ }
+ t.Fatalf("delivery %s did not reach a terminal state", deliveryID)
+ return db.WebhookDelivery{}
+}
+
// ── Tests ───────────────────────────────────────────────────────────────────
func TestCreateWebhookTrigger_GeneratesToken(t *testing.T) {
@@ -570,20 +601,8 @@ func TestWebhookHandler_ActiveDispatchesRunWithPayload(t *testing.T) {
"event": "demo.received",
"eventPayload": map[string]any{"k": "v"},
}, nil)
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- if resp["status"] != "accepted" {
- t.Fatalf("expected accepted, got %v body=%s", resp["status"], w.Body.String())
- }
- runID, _ := resp["run_id"].(string)
- if runID == "" {
- t.Fatal("run_id missing from response")
- }
+ delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
+ runID := uuidToString(delivery.AutopilotRunID)
// Validate the persisted run carries the normalized envelope.
run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))
@@ -631,12 +650,8 @@ func TestWebhookHandler_GitHubHeaderInferredEvent(t *testing.T) {
"number": 42,
},
}, map[string]string{"X-GitHub-Event": "pull_request"})
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- json.Unmarshal(w.Body.Bytes(), &resp)
- runID := resp["run_id"].(string)
+ delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
+ runID := uuidToString(delivery.AutopilotRunID)
run, err := testHandler.Queries.GetAutopilotRun(context.Background(), parseUUID(runID))
if err != nil {
t.Fatalf("load run: %v", err)
@@ -650,24 +665,23 @@ func TestWebhookHandler_GitHubHeaderInferredEvent(t *testing.T) {
}
}
-func TestWebhookHandler_RateLimitReturns429(t *testing.T) {
+func TestWebhookHandler_ValidBurstPersistsWithoutHTTP429(t *testing.T) {
agentID := createWebhookTestAgent(t, "WebhookRate Agent")
- apID := createWebhookTestAutopilot(t, agentID, "paused", "run_only") // paused → cheap ignored path
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
trig := createWebhookTriggerViaHandler(t, apID)
prev := testHandler.WebhookRateLimiter
testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})
t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })
- for i := 0; i < 2; i++ {
+ for i := 0; i < 3; i++ {
w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": i}, nil)
- if w.Code != http.StatusOK {
- t.Fatalf("request %d: expected 200, got %d", i, w.Code)
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("request %d: expected durable 202, got %d body=%s", i, w.Code, w.Body.String())
}
}
- w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": "third"}, nil)
- if w.Code != http.StatusTooManyRequests {
- t.Fatalf("expected 429, got %d body=%s", w.Code, w.Body.String())
+ if got := len(listDeliveries(t, apID)); got != 3 {
+ t.Fatalf("all valid burst deliveries must be persisted, got %d", got)
}
}
@@ -697,8 +711,8 @@ func TestRotateWebhookToken_ReplacesOldToken(t *testing.T) {
}
// New token should accept.
resNew := postWebhook(t, *rotated.WebhookToken, map[string]any{"x": 1}, nil)
- if resNew.Code != http.StatusOK {
- t.Fatalf("new token should be 200, got %d body=%s", resNew.Code, resNew.Body.String())
+ if resNew.Code != http.StatusAccepted {
+ t.Fatalf("new token should be 202, got %d body=%s", resNew.Code, resNew.Body.String())
}
}
@@ -804,6 +818,27 @@ func TestWebhookHandler_IPRateLimitNotBypassedByXFFSpoof(t *testing.T) {
}
}
+func TestWebhookHandler_AbsoluteIPRateLimitRetainsEmergencyCeiling(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WebhookAbsoluteLimit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ prev := testHandler.WebhookAbsoluteIPRateLimiter
+ testHandler.WebhookAbsoluteIPRateLimiter = NewMemoryWebhookAbsoluteIPRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})
+ t.Cleanup(func() { testHandler.WebhookAbsoluteIPRateLimiter = prev })
+
+ if first := postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, nil); first.Code != http.StatusAccepted {
+ t.Fatalf("first valid request: expected 202, got %d", first.Code)
+ }
+ second := postWebhook(t, *trig.WebhookToken, map[string]any{"n": 2}, nil)
+ if second.Code != http.StatusTooManyRequests {
+ t.Fatalf("absolute ceiling: expected 429, got %d body=%s", second.Code, second.Body.String())
+ }
+ if second.Header().Get("Retry-After") == "" {
+ t.Fatal("absolute ceiling 429 must include Retry-After")
+ }
+}
+
func TestWebhookHandler_DBErrorOnTokenLookupReturns500(t *testing.T) {
// Inject a fake Queries-like wrapper via a shadow type isn't simple
// here because Handler.Queries is a *db.Queries struct, not an
@@ -930,12 +965,8 @@ func TestGetAutopilotRun_ReturnsFullPayload(t *testing.T) {
"event": "demo.x",
"eventPayload": map[string]any{"answer": 42},
}, nil)
- if post.Code != http.StatusOK {
- t.Fatalf("seed webhook: %d body=%s", post.Code, post.Body.String())
- }
- var seedResp map[string]any
- json.Unmarshal(post.Body.Bytes(), &seedResp)
- runID := seedResp["run_id"].(string)
+ delivery := processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, post))
+ runID := uuidToString(delivery.AutopilotRunID)
// LIST: trigger_payload should be omitted (slim response).
wList := httptest.NewRecorder()
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 9dd8a1a8bd..6399e8b460 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -149,13 +149,15 @@ type Handler struct {
// May be nil in tests / self-hosted with the metrics listener disabled;
// every Record* method is nil-safe and obsmetrics.RecordEvent treats a
// nil Metrics as "PostHog only".
- Metrics *obsmetrics.BusinessMetrics
- PATCache *auth.PATCache
- DaemonTokenCache *auth.DaemonTokenCache
- MembershipCache *auth.MembershipCache
- WebhookRateLimiter WebhookRateLimiter
- WebhookIPRateLimiter WebhookRateLimiter
- CloudRuntime cloudRuntimeProxy
+ Metrics *obsmetrics.BusinessMetrics
+ PATCache *auth.PATCache
+ DaemonTokenCache *auth.DaemonTokenCache
+ MembershipCache *auth.MembershipCache
+ WebhookRateLimiter WebhookRateLimiter
+ WebhookIPRateLimiter WebhookRateLimiter
+ WebhookAbsoluteIPRateLimiter WebhookRateLimiter
+ WebhookDeliveryWorker *WebhookDeliveryWorker
+ CloudRuntime cloudRuntimeProxy
// Lark integration. All three are nil when the Lark master key
// (MULTICA_LARK_SECRET_KEY) is unset; the corresponding HTTP
// handlers return 503 in that case so a misconfigured self-host
@@ -256,30 +258,31 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)
taskSvc.Analytics = analyticsClient
- return &Handler{
- Queries: queries,
- DB: executor,
- TxStarter: txStarter,
- Hub: hub,
- DaemonHub: daemonHub,
- DaemonProfileRefresh: daemonProfileRefresh,
- DaemonWorkspaceRefresh: daemonWorkspaceRefresh,
- Bus: bus,
- TaskService: taskSvc,
- IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),
- AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),
- EmailService: emailService,
- UpdateStore: NewInMemoryUpdateStore(),
- ModelListStore: NewInMemoryModelListStore(),
- LocalSkillListStore: NewInMemoryLocalSkillListStore(),
- LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),
- LivenessStore: NewNoopLivenessStore(),
- HeartbeatScheduler: NewPassthroughHeartbeatScheduler(queries),
- Storage: store,
- CFSigner: cfSigner,
- Analytics: analyticsClient,
- WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),
- WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),
+ h := &Handler{
+ Queries: queries,
+ DB: executor,
+ TxStarter: txStarter,
+ Hub: hub,
+ DaemonHub: daemonHub,
+ DaemonProfileRefresh: daemonProfileRefresh,
+ DaemonWorkspaceRefresh: daemonWorkspaceRefresh,
+ Bus: bus,
+ TaskService: taskSvc,
+ IssueService: service.NewIssueService(queries, txStarter, bus, analyticsClient, taskSvc),
+ AutopilotService: service.NewAutopilotService(queries, txStarter, bus, taskSvc),
+ EmailService: emailService,
+ UpdateStore: NewInMemoryUpdateStore(),
+ ModelListStore: NewInMemoryModelListStore(),
+ LocalSkillListStore: NewInMemoryLocalSkillListStore(),
+ LocalSkillImportStore: NewInMemoryLocalSkillImportStore(),
+ LivenessStore: NewNoopLivenessStore(),
+ HeartbeatScheduler: NewPassthroughHeartbeatScheduler(queries),
+ Storage: store,
+ CFSigner: cfSigner,
+ Analytics: analyticsClient,
+ WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),
+ WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),
+ WebhookAbsoluteIPRateLimiter: NewMemoryWebhookAbsoluteIPRateLimiter(DefaultWebhookAbsoluteIPRateLimit()),
CloudRuntime: cloudruntime.NewClient(cloudruntime.Config{
BaseURL: cfg.CloudRuntimeFleetURL,
Timeout: cfg.CloudRuntimeFleetTimeout,
@@ -291,6 +294,8 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
}),
cfg: cfg,
}
+ h.WebhookDeliveryWorker = NewWebhookDeliveryWorker(h)
+ return h
}
func writeJSON(w http.ResponseWriter, status int, v any) {
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 1162c26430..d18357759b 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -68,6 +68,7 @@ func TestMain(m *testing.M) {
// the rest of the suite hermetic.
testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
+ testHandler.WebhookAbsoluteIPRateLimiter = NewMemoryWebhookAbsoluteIPRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
testPool = pool
testUserID, testWorkspaceID, err = setupHandlerTestFixture(ctx, pool)
diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.go
index 9a78d8c20e..87adc6bc15 100644
--- a/server/internal/handler/webhook_delivery.go
+++ b/server/internal/handler/webhook_delivery.go
@@ -32,6 +32,8 @@ type WebhookDeliveryResponse struct {
SignatureStatus string `json:"signature_status"`
Status string `json:"status"`
AttemptCount int32 `json:"attempt_count"`
+ DispatchAttempts int32 `json:"dispatch_attempts"`
+ AvailableAt string `json:"available_at"`
ContentType *string `json:"content_type"`
ResponseStatus *int32 `json:"response_status"`
AutopilotRunID *string `json:"autopilot_run_id"`
@@ -53,21 +55,23 @@ 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,
- 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),
}
if d.ResponseStatus.Valid {
v := d.ResponseStatus.Int32
@@ -90,21 +94,23 @@ 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,
- 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),
}
if d.ResponseStatus.Valid {
v := d.ResponseStatus.Int32
diff --git a/server/internal/handler/webhook_delivery_test.go b/server/internal/handler/webhook_delivery_test.go
index 0ce1773b8c..17b348fcbc 100644
--- a/server/internal/handler/webhook_delivery_test.go
+++ b/server/internal/handler/webhook_delivery_test.go
@@ -11,6 +11,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
"github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -47,6 +48,38 @@ func signBody(secret string, body []byte) string {
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
}
+func installWebhookAcknowledgementFailure(t *testing.T) {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ functionName := fmt.Sprintf("webhook_ack_fail_fn_%d", suffix)
+ triggerName := fmt.Sprintf("webhook_ack_fail_%d", suffix)
+ t.Cleanup(func() {
+ testPool.Exec(ctx, fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON webhook_delivery`, triggerName))
+ testPool.Exec(ctx, fmt.Sprintf(`DROP FUNCTION IF EXISTS %s()`, functionName))
+ })
+
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE FUNCTION %s() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF NEW.event = 'test.ack_failure' AND NEW.response_status = 202 THEN
+ RAISE EXCEPTION 'forced webhook acknowledgement metadata failure';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+`, functionName)); err != nil {
+ t.Fatalf("install acknowledgement failure function: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, fmt.Sprintf(`
+CREATE TRIGGER %s
+BEFORE UPDATE ON webhook_delivery
+FOR EACH ROW EXECUTE FUNCTION %s();
+`, triggerName, functionName)); err != nil {
+ t.Fatalf("install acknowledgement failure trigger: %v", err)
+ }
+}
+
// listDeliveries calls ListAutopilotDeliveries and decodes the body.
func listDeliveries(t *testing.T, apID string) []map[string]any {
t.Helper()
@@ -74,17 +107,7 @@ func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {
trig := createWebhookTriggerViaHandler(t, apID)
w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, nil)
- if w.Code != http.StatusOK {
- t.Fatalf("status: %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- json.Unmarshal(w.Body.Bytes(), &resp)
- if resp["delivery_id"] == nil {
- t.Fatal("response should include delivery_id")
- }
- if resp["status"] != "accepted" {
- t.Fatalf("status: %v", resp["status"])
- }
+ processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
deliveries := listDeliveries(t, apID)
if len(deliveries) != 1 {
@@ -97,11 +120,41 @@ func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {
if d["autopilot_run_id"] == nil {
t.Fatal("delivery should link to run")
}
+ if got := int(d["response_status"].(float64)); got != http.StatusAccepted {
+ t.Fatalf("terminal delivery must retain ingress 202 acknowledgement, got %d", got)
+ }
+ if got := int(d["dispatch_attempts"].(float64)); got != 1 {
+ t.Fatalf("expected one worker dispatch attempt, got %d", got)
+ }
if d["signature_status"] != "not_required" {
t.Fatalf("expected signature_status=not_required, got %v", d["signature_status"])
}
}
+func TestWebhookHandler_AcknowledgementMetadataFailureStillReturns202(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "AckMetadataFailure Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ installWebhookAcknowledgementFailure(t)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "test.ack_failure"}, map[string]string{
+ "Idempotency-Key": "ack-metadata-failure",
+ })
+ deliveryID := requireQueuedWebhookResponse(t, w)
+ delivery, err := testHandler.Queries.GetWebhookDelivery(context.Background(), parseUUID(deliveryID))
+ if err != nil {
+ t.Fatalf("load durably queued delivery: %v", err)
+ }
+ if delivery.ResponseStatus.Valid || delivery.ResponseBody.Valid {
+ t.Fatalf("forced acknowledgement metadata write unexpectedly succeeded: %#v", delivery)
+ }
+
+ completed := processQueuedWebhookDelivery(t, deliveryID)
+ if completed.Status != deliveryStatusDispatched || !completed.AutopilotRunID.Valid {
+ t.Fatalf("durable delivery did not dispatch after metadata failure: status=%s run=%v", completed.Status, completed.AutopilotRunID.Valid)
+ }
+}
+
func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {
agentID := createWebhookTestAgent(t, "DeliveryIdem Agent")
apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
@@ -111,16 +164,9 @@ func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {
headers := map[string]string{"Idempotency-Key": "demo-key-1"}
w1 := postWebhook(t, *trig.WebhookToken, body, headers)
- if w1.Code != http.StatusOK {
- t.Fatalf("first: %d body=%s", w1.Code, w1.Body.String())
- }
- var r1 map[string]any
- json.Unmarshal(w1.Body.Bytes(), &r1)
- if r1["status"] != "accepted" {
- t.Fatalf("first status: %v", r1["status"])
- }
- firstDeliveryID := r1["delivery_id"].(string)
- firstRunID := r1["run_id"].(string)
+ firstDeliveryID := requireQueuedWebhookResponse(t, w1)
+ firstDelivery := processQueuedWebhookDelivery(t, firstDeliveryID)
+ firstRunID := uuidToString(firstDelivery.AutopilotRunID)
// Second identical delivery should be a duplicate.
w2 := postWebhook(t, *trig.WebhookToken, body, headers)
@@ -162,14 +208,7 @@ func TestWebhookHandler_DedupeViaGitHubDelivery(t *testing.T) {
}
w1 := postWebhook(t, *trig.WebhookToken, body, headers)
- if w1.Code != http.StatusOK {
- t.Fatalf("first: %d", w1.Code)
- }
- var r1 map[string]any
- json.Unmarshal(w1.Body.Bytes(), &r1)
- if r1["status"] != "accepted" {
- t.Fatalf("first status: %v", r1["status"])
- }
+ processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w1))
w2 := postWebhook(t, *trig.WebhookToken, body, headers)
var r2 map[string]any
@@ -257,14 +296,7 @@ func TestWebhookHandler_ValidSignatureDispatches(t *testing.T) {
w := postWebhook(t, *trig.WebhookToken, bodyBytes, map[string]string{
"X-Hub-Signature-256": sig,
})
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
- }
- var resp map[string]any
- json.Unmarshal(w.Body.Bytes(), &resp)
- if resp["status"] != "accepted" {
- t.Fatalf("status: %v", resp["status"])
- }
+ processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, w))
deliveries := listDeliveries(t, apID)
if len(deliveries) != 1 {
t.Fatalf("expected 1 delivery, got %d", len(deliveries))
@@ -333,7 +365,7 @@ func TestSigningSecret_EmptyClearsSecret(t *testing.T) {
}
// Unsigned request should now go through (back to not_required).
post := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)
- if post.Code != http.StatusOK {
+ if post.Code != http.StatusAccepted {
t.Fatalf("post after clear: %d body=%s", post.Code, post.Body.String())
}
}
@@ -347,13 +379,9 @@ func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {
w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, map[string]string{
"Idempotency-Key": "replay-original",
})
- if w.Code != http.StatusOK {
- t.Fatalf("original: %d body=%s", w.Code, w.Body.String())
- }
- var orig map[string]any
- json.Unmarshal(w.Body.Bytes(), &orig)
- originalID := orig["delivery_id"].(string)
- originalRunID := orig["run_id"].(string)
+ originalID := requireQueuedWebhookResponse(t, w)
+ originalDelivery := processQueuedWebhookDelivery(t, originalID)
+ originalRunID := uuidToString(originalDelivery.AutopilotRunID)
// Replay the original.
wr := httptest.NewRecorder()
@@ -417,12 +445,7 @@ func TestGetDelivery_ReturnsFullPayload(t *testing.T) {
trig := createWebhookTriggerViaHandler(t, apID)
w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "demo", "eventPayload": map[string]any{"answer": 42}}, nil)
- if w.Code != http.StatusOK {
- t.Fatalf("seed: %d", w.Code)
- }
- var seed map[string]any
- json.Unmarshal(w.Body.Bytes(), &seed)
- deliveryID := seed["delivery_id"].(string)
+ deliveryID := requireQueuedWebhookResponse(t, w)
// List response should NOT include raw_body / selected_headers.
wList := httptest.NewRecorder()
@@ -541,9 +564,10 @@ func TestWebhookHandler_RunOnlyDedupeOnGitHubDelivery(t *testing.T) {
}
body := map[string]any{"action": "opened"}
+ first := postWebhook(t, *trig.WebhookToken, body, headers)
postWebhook(t, *trig.WebhookToken, body, headers)
postWebhook(t, *trig.WebhookToken, body, headers)
- postWebhook(t, *trig.WebhookToken, body, headers)
+ processQueuedWebhookDelivery(t, requireQueuedWebhookResponse(t, first))
// Count autopilot_run rows linked to this trigger.
rows, err := testHandler.Queries.ListAutopilotRuns(context.Background(), db.ListAutopilotRunsParams{
@@ -563,20 +587,242 @@ func TestWebhookHandler_RunOnlyDedupeOnGitHubDelivery(t *testing.T) {
if runCount != 1 {
t.Fatalf("expected exactly 1 run from 3 retried deliveries, got %d", runCount)
}
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 || deliveries[0]["status"] != deliveryStatusDispatched {
+ t.Fatalf("queued duplicate should be dispatched exactly once: %#v", deliveries)
+ }
+ if got := int(deliveries[0]["attempt_count"].(float64)); got != 3 {
+ t.Fatalf("redeliveries should bump attempt_count to 3, got %d", got)
+ }
+}
+
+func TestWebhookDeliveryWorker_PerTriggerLimitDefersWithoutDropping(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WorkerPacing Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ prev := testHandler.WebhookRateLimiter
+ testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})
+ t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })
+
+ firstID := requireQueuedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 1}, map[string]string{
+ "Idempotency-Key": "worker-pacing-1",
+ }))
+ secondID := requireQueuedWebhookResponse(t, postWebhook(t, *trig.WebhookToken, map[string]any{"n": 2}, map[string]string{
+ "Idempotency-Key": "worker-pacing-2",
+ }))
+
+ worked, err := testHandler.WebhookDeliveryWorker.ProcessNext(context.Background())
+ if err != nil || !worked {
+ t.Fatalf("first dispatch: worked=%v err=%v", worked, err)
+ }
+ deliveries := make([]db.WebhookDelivery, 2)
+ for i, id := range []string{firstID, secondID} {
+ deliveries[i], err = testHandler.Queries.GetWebhookDelivery(context.Background(), parseUUID(id))
+ if err != nil {
+ t.Fatalf("load delivery %s: %v", id, err)
+ }
+ }
+ queuedIndex := -1
+ for i, delivery := range deliveries {
+ if delivery.Status == deliveryStatusQueued {
+ queuedIndex = i
+ }
+ }
+ if queuedIndex < 0 {
+ t.Fatalf("expected one delivery to remain queued: %#v", deliveries)
+ }
+
+ worked, err = testHandler.WebhookDeliveryWorker.ProcessNext(context.Background())
+ if err != nil || !worked {
+ t.Fatalf("defer paced delivery: worked=%v err=%v", worked, err)
+ }
+ deferred, err := testHandler.Queries.GetWebhookDelivery(context.Background(), deliveries[queuedIndex].ID)
+ if err != nil {
+ t.Fatalf("load deferred delivery: %v", err)
+ }
+ if deferred.Status != deliveryStatusQueued || deferred.DispatchAttempts != 0 {
+ t.Fatalf("pacing must preserve queued work without counting an attempt: status=%s attempts=%d", deferred.Status, deferred.DispatchAttempts)
+ }
+ if deferred.LeaseToken.Valid || deferred.LeaseExpiresAt.Valid || !deferred.AvailableAt.Valid || !deferred.AvailableAt.Time.After(time.Now()) {
+ t.Fatalf("paced delivery was not released with a future availability: %#v", deferred)
+ }
+
+ var runCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM autopilot_run WHERE webhook_delivery_id IN ($1, $2)
+ `, firstID, secondID).Scan(&runCount); err != nil {
+ t.Fatalf("count paced runs: %v", err)
+ }
+ if runCount != 1 {
+ t.Fatalf("pacing should dispatch one run and retain one delivery, got %d runs", runCount)
+ }
+}
+
+func TestWebhookDeliveryWorker_RecoversExpiredLeaseAndReusesRun(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WorkerRecovery Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "recovery"}, map[string]string{
+ "Idempotency-Key": "worker-recovery",
+ })
+ deliveryID := requireQueuedWebhookResponse(t, post)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE webhook_delivery
+ SET lease_token = gen_random_uuid(), lease_expires_at = now() - interval '1 second'
+ WHERE id = $1
+ `, deliveryID); err != nil {
+ t.Fatalf("seed expired lease: %v", err)
+ }
+
+ first := processQueuedWebhookDelivery(t, deliveryID)
+ if first.Status != deliveryStatusDispatched || !first.AutopilotRunID.Valid {
+ t.Fatalf("expired lease was not recovered: status=%s run=%v", first.Status, first.AutopilotRunID.Valid)
+ }
+ firstRunID := uuidToString(first.AutopilotRunID)
+
+ // Simulate a crash after the run/task side effect committed but before a
+ // delivery terminal update was durable. Requeueing must reuse the run's
+ // webhook_delivery_id anchor and must not create a second task.
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE webhook_delivery
+ SET status = 'queued', autopilot_run_id = NULL, available_at = now(),
+ lease_token = NULL, lease_expires_at = NULL
+ WHERE id = $1
+ `, deliveryID); err != nil {
+ t.Fatalf("requeue delivery: %v", err)
+ }
+ second := processQueuedWebhookDelivery(t, deliveryID)
+ if got := uuidToString(second.AutopilotRunID); got != firstRunID {
+ t.Fatalf("worker did not reuse idempotent run: got %s want %s", got, firstRunID)
+ }
+
+ var runCount, taskCount int
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM autopilot_run WHERE webhook_delivery_id = $1
+ `, deliveryID).Scan(&runCount); err != nil {
+ t.Fatalf("count runs: %v", err)
+ }
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT count(*) FROM agent_task_queue WHERE autopilot_run_id = $1
+ `, firstRunID).Scan(&taskCount); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ if runCount != 1 || taskCount != 1 {
+ t.Fatalf("recovery duplicated side effects: runs=%d tasks=%d", runCount, taskCount)
+ }
+}
+
+func TestWebhookDeliveryWorker_LeaseOwnershipChangeIsBenign(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WorkerLeaseChange Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "lease-change"}, map[string]string{
+ "Idempotency-Key": "worker-lease-change",
+ })
+ deliveryID := requireQueuedWebhookResponse(t, post)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE webhook_delivery
+ SET lease_token = gen_random_uuid(), lease_expires_at = now() + interval '2 minutes'
+ WHERE id = $1
+ `, deliveryID); err != nil {
+ t.Fatalf("seed first lease: %v", err)
+ }
+ staleClaim, err := testHandler.Queries.GetWebhookDelivery(context.Background(), parseUUID(deliveryID))
+ if err != nil {
+ t.Fatalf("load first lease: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE webhook_delivery SET lease_token = gen_random_uuid() WHERE id = $1
+ `, deliveryID); err != nil {
+ t.Fatalf("replace lease owner: %v", err)
+ }
+
+ worker := NewWebhookDeliveryWorker(testHandler)
+ if err := worker.complete(context.Background(), staleClaim, deliveryStatusDispatched, pgtype.UUID{}, ""); err != nil {
+ t.Fatalf("stale complete should be benign: %v", err)
+ }
+ if err := worker.retryOrFail(context.Background(), staleClaim, fmt.Errorf("forced transient failure")); err != nil {
+ t.Fatalf("stale retry should be benign: %v", err)
+ }
+ current, err := testHandler.Queries.GetWebhookDelivery(context.Background(), parseUUID(deliveryID))
+ if err != nil {
+ t.Fatalf("load current owner: %v", err)
+ }
+ if current.Status != deliveryStatusQueued || current.LeaseToken == staleClaim.LeaseToken {
+ t.Fatalf("stale worker mutated the new owner's delivery: %#v", current)
+ }
+}
+
+func TestWebhookDeliveryWorker_RunStopsBoundedPool(t *testing.T) {
+ worker := NewWebhookDeliveryWorker(testHandler)
+ ctx, cancel := context.WithCancel(context.Background())
+ go worker.Run(ctx)
+ cancel()
+ if !worker.WaitWithTimeout(time.Second) {
+ t.Fatal("bounded worker pool did not stop after cancellation")
+ }
+}
+
+func TestWebhookDeliveryWorker_RepairsCreateIssueTaskCrashWindow(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WorkerIssueRecovery Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "create_issue")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ post := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "issue-recovery"}, map[string]string{
+ "Idempotency-Key": "worker-issue-recovery",
+ })
+ deliveryID := requireQueuedWebhookResponse(t, post)
+ first := processQueuedWebhookDelivery(t, deliveryID)
+ run, err := testHandler.Queries.GetAutopilotRun(context.Background(), first.AutopilotRunID)
+ if err != nil || !run.IssueID.Valid {
+ t.Fatalf("load create_issue run: run=%#v err=%v", run, err)
+ }
+ issueID := uuidToString(run.IssueID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+
+ // Remove the task to model a process exit after the issue/run transaction
+ // but before task enqueue, then make the delivery recoverable again.
+ if _, err := testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID); err != nil {
+ t.Fatalf("remove issue task: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE webhook_delivery
+ SET status = 'queued', autopilot_run_id = NULL, available_at = now(),
+ lease_token = NULL, lease_expires_at = NULL
+ WHERE id = $1
+ `, deliveryID); err != nil {
+ t.Fatalf("requeue delivery: %v", err)
+ }
+ second := processQueuedWebhookDelivery(t, deliveryID)
+ if got := uuidToString(second.AutopilotRunID); got != uuidToString(first.AutopilotRunID) {
+ t.Fatalf("repair should reuse run: got %s want %s", got, uuidToString(first.AutopilotRunID))
+ }
+ var taskCount int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE issue_id = $1`, issueID).Scan(&taskCount); err != nil {
+ t.Fatalf("count repaired task: %v", err)
+ }
+ if taskCount != 1 {
+ t.Fatalf("expected one repaired issue task, got %d", taskCount)
+ }
}
func TestWebhookHandler_InvalidSignatureCountsAgainstRateLimit(t *testing.T) {
- // A stream of bad-signature attempts must not let an attacker bypass
- // per-token rate limiting; the limiter increment happens before
- // signature check.
+ // Only requests classified as bad credentials consume the shared-IP debt
+ // budget; valid traffic behind the same NAT does not.
agentID := createWebhookTestAgent(t, "SigRateLimit Agent")
apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
trig := createWebhookTriggerViaHandler(t, apID)
setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
- prev := testHandler.WebhookRateLimiter
- testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})
- t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })
+ prev := testHandler.WebhookIPRateLimiter
+ testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})
+ t.Cleanup(func() { testHandler.WebhookIPRateLimiter = prev })
bad := map[string]string{"X-Hub-Signature-256": "sha256=baad"}
for i := 0; i < 2; i++ {
@@ -589,6 +835,9 @@ func TestWebhookHandler_InvalidSignatureCountsAgainstRateLimit(t *testing.T) {
if w.Code != http.StatusTooManyRequests {
t.Fatalf("third request expected 429 (rate-limited despite bad sig), got %d", w.Code)
}
+ if w.Header().Get("Retry-After") == "" {
+ t.Fatal("429 must include Retry-After")
+ }
}
func TestWebhookHandler_IgnoredPathStillPersistsDelivery(t *testing.T) {
diff --git a/server/internal/handler/webhook_delivery_worker.go b/server/internal/handler/webhook_delivery_worker.go
new file mode 100644
index 0000000000..fec12852b3
--- /dev/null
+++ b/server/internal/handler/webhook_delivery_worker.go
@@ -0,0 +1,281 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ webhookWorkerPollInterval = time.Second
+ webhookWorkerMaxAttempts = 5
+ webhookWorkerConcurrency = 4
+)
+
+// WebhookDeliveryWorker owns queued webhook delivery dispatch. Its queue and
+// lease both live in Postgres, so a process restart or replica failover simply
+// reclaims expired rows; the in-memory notification is only a latency hint.
+type WebhookDeliveryWorker struct {
+ h *Handler
+ notify chan struct{}
+ done chan struct{}
+}
+
+func NewWebhookDeliveryWorker(h *Handler) *WebhookDeliveryWorker {
+ return &WebhookDeliveryWorker{
+ h: h,
+ notify: make(chan struct{}, webhookWorkerConcurrency),
+ done: make(chan struct{}),
+ }
+}
+
+func (w *WebhookDeliveryWorker) Notify() {
+ if w == nil {
+ return
+ }
+ select {
+ case w.notify <- struct{}{}:
+ default:
+ }
+}
+
+// Run owns a bounded per-process worker pool. SKIP LOCKED distributes queued
+// deliveries across both these workers and other server replicas. ProcessNext
+// is public to the package so handler tests can drive the durable queue
+// synchronously without starting a goroutine.
+func (w *WebhookDeliveryWorker) Run(ctx context.Context) {
+ if w == nil {
+ return
+ }
+ defer close(w.done)
+ if w.h == nil || w.h.Queries == nil {
+ return
+ }
+
+ var workers sync.WaitGroup
+ workers.Add(webhookWorkerConcurrency)
+ for range webhookWorkerConcurrency {
+ go func() {
+ defer workers.Done()
+ w.runLoop(ctx)
+ }()
+ }
+ workers.Wait()
+}
+
+// runLoop polls as a recovery sweeper and also wakes immediately after local
+// ingress. Each loop has its own ticker so an idle pool can fan back out even
+// when burst notifications coalesce.
+func (w *WebhookDeliveryWorker) runLoop(ctx context.Context) {
+ ticker := time.NewTicker(webhookWorkerPollInterval)
+ defer ticker.Stop()
+ for {
+ worked, err := w.ProcessNext(ctx)
+ if err != nil && !errors.Is(err, context.Canceled) {
+ slog.Error("webhook worker: process delivery", "error", err)
+ }
+ if worked {
+ continue
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-w.notify:
+ case <-ticker.C:
+ }
+ }
+}
+
+func (w *WebhookDeliveryWorker) WaitWithTimeout(timeout time.Duration) bool {
+ if w == nil {
+ return true
+ }
+ timer := time.NewTimer(timeout)
+ defer timer.Stop()
+ select {
+ case <-w.done:
+ return true
+ case <-timer.C:
+ return false
+ }
+}
+
+func (w *WebhookDeliveryWorker) ProcessNext(ctx context.Context) (bool, error) {
+ delivery, err := w.h.Queries.ClaimQueuedWebhookDelivery(ctx)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, nil
+ }
+ if err != nil {
+ return false, fmt.Errorf("claim queued delivery: %w", err)
+ }
+
+ if w.h.WebhookRateLimiter != nil {
+ key := uuidToString(delivery.TriggerID)
+ if !w.h.WebhookRateLimiter.Allow(ctx, key) {
+ w.h.Metrics.RecordWebhookRateLimited("worker_trigger")
+ retryAfter := webhookLimiterRetryAfter(ctx, w.h.WebhookRateLimiter, key)
+ if retryAfter <= 0 {
+ retryAfter = time.Second
+ }
+ _, err := w.h.Queries.DeferClaimedWebhookDelivery(ctx, db.DeferClaimedWebhookDeliveryParams{
+ ID: delivery.ID,
+ LeaseToken: delivery.LeaseToken,
+ AvailableAt: pgtype.Timestamptz{Time: time.Now().Add(retryAfter), Valid: true},
+ })
+ _, err = handleWebhookLeaseMutation("defer", delivery, err)
+ return true, err
+ }
+ }
+
+ trigger, err := w.h.Queries.GetAutopilotTrigger(ctx, delivery.TriggerID)
+ if err != nil {
+ return true, w.retryOrFail(ctx, delivery, fmt.Errorf("load trigger: %w", err))
+ }
+ autopilot, err := w.h.Queries.GetAutopilot(ctx, delivery.AutopilotID)
+ if err != nil {
+ return true, w.retryOrFail(ctx, delivery, fmt.Errorf("load autopilot: %w", err))
+ }
+ if uuidToString(trigger.AutopilotID) != uuidToString(delivery.AutopilotID) ||
+ uuidToString(autopilot.WorkspaceID) != uuidToString(delivery.WorkspaceID) {
+ return true, w.complete(ctx, delivery, deliveryStatusFailed, pgtype.UUID{}, "delivery ownership mismatch")
+ }
+
+ headers := headersFromSelected(delivery.SelectedHeaders)
+ if delivery.ContentType.Valid {
+ headers.Set("Content-Type", delivery.ContentType.String)
+ }
+ envelope, err := normalizeWebhookPayload(delivery.RawBody, headers)
+ if err != nil {
+ return true, w.complete(ctx, delivery, deliveryStatusFailed, pgtype.UUID{}, "normalize stored body: "+err.Error())
+ }
+ if delivery.ReceivedAt.Valid {
+ envelope.Request.ReceivedAt = delivery.ReceivedAt.Time.UTC().Format(time.RFC3339)
+ }
+ payload, err := json.Marshal(envelope)
+ if err != nil {
+ return true, w.retryOrFail(ctx, delivery, fmt.Errorf("encode envelope: %w", err))
+ }
+
+ switch {
+ case !trigger.Enabled:
+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "trigger_disabled")
+ case autopilot.Status == "archived":
+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_archived")
+ case autopilot.Status != "active":
+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "autopilot_paused")
+ case !webhookEventAllowedByTriggerScope(trigger.EventFilters, envelope):
+ return true, w.complete(ctx, delivery, deliveryStatusIgnored, pgtype.UUID{}, "event_filtered")
+ }
+
+ run, dispatchErr := w.h.AutopilotService.DispatchAutopilotForWebhookDelivery(
+ ctx,
+ autopilot,
+ trigger.ID,
+ payload,
+ delivery.ID,
+ )
+ if dispatchErr != nil {
+ if run != nil {
+ return true, w.complete(ctx, delivery, deliveryStatusFailed, run.ID, dispatchErr.Error())
+ }
+ return true, w.retryOrFail(ctx, delivery, dispatchErr)
+ }
+ if run.Status == "failed" {
+ reason := "autopilot run failed"
+ if run.FailureReason.Valid {
+ reason = run.FailureReason.String
+ }
+ return true, w.complete(ctx, delivery, deliveryStatusFailed, run.ID, reason)
+ }
+
+ if err := w.h.Queries.TouchAutopilotTriggerFiredAt(ctx, trigger.ID); err != nil {
+ slog.Warn("webhook worker: touch last_fired_at",
+ "delivery_id", uuidToString(delivery.ID),
+ "trigger_id", uuidToString(trigger.ID),
+ "error", err,
+ )
+ }
+ return true, w.complete(ctx, delivery, deliveryStatusDispatched, run.ID, "")
+}
+
+func (w *WebhookDeliveryWorker) complete(
+ ctx context.Context,
+ delivery db.WebhookDelivery,
+ status string,
+ runID pgtype.UUID,
+ reason string,
+) error {
+ params := db.CompleteClaimedWebhookDeliveryParams{
+ ID: delivery.ID,
+ LeaseToken: delivery.LeaseToken,
+ Status: status,
+ AutopilotRunID: runID,
+ }
+ if reason != "" {
+ params.Error = pgtype.Text{String: reason, Valid: true}
+ }
+ _, err := w.h.Queries.CompleteClaimedWebhookDelivery(ctx, params)
+ lost, err := handleWebhookLeaseMutation("complete", delivery, err)
+ if err != nil {
+ return err
+ }
+ if lost {
+ return nil
+ }
+ w.h.Metrics.RecordWebhookDelivery(delivery.Provider, status)
+ return nil
+}
+
+func (w *WebhookDeliveryWorker) retryOrFail(ctx context.Context, delivery db.WebhookDelivery, cause error) error {
+ if delivery.DispatchAttempts+1 >= webhookWorkerMaxAttempts {
+ return w.complete(ctx, delivery, deliveryStatusFailed, pgtype.UUID{}, cause.Error())
+ }
+ backoff := time.Second * time.Duration(1<<min(delivery.DispatchAttempts, 6))
+ _, err := w.h.Queries.RetryClaimedWebhookDelivery(ctx, db.RetryClaimedWebhookDeliveryParams{
+ ID: delivery.ID,
+ LeaseToken: delivery.LeaseToken,
+ AvailableAt: pgtype.Timestamptz{Time: time.Now().Add(backoff), Valid: true},
+ Error: pgtype.Text{String: cause.Error(), Valid: true},
+ })
+ lost, mutationErr := handleWebhookLeaseMutation("retry", delivery, err)
+ if mutationErr != nil {
+ return fmt.Errorf("retry claimed delivery after %v: %w", cause, mutationErr)
+ }
+ if lost {
+ return nil
+ }
+ slog.Warn("webhook worker: delivery deferred",
+ "delivery_id", uuidToString(delivery.ID),
+ "attempt", delivery.DispatchAttempts+1,
+ "backoff", backoff,
+ "error", cause,
+ )
+ return nil
+}
+
+// handleWebhookLeaseMutation normalizes the expected race where a slow worker
+// outlives its lease and a new owner has already claimed or completed the row.
+// The new owner is responsible for the terminal transition, so the stale
+// worker must neither emit an error nor record completion metrics.
+func handleWebhookLeaseMutation(operation string, delivery db.WebhookDelivery, err error) (bool, error) {
+ if err == nil {
+ return false, nil
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ slog.Debug("webhook worker: lease ownership changed",
+ "operation", operation,
+ "delivery_id", uuidToString(delivery.ID),
+ )
+ return true, nil
+ }
+ return false, fmt.Errorf("%s claimed delivery: %w", operation, err)
+}
diff --git a/server/internal/handler/webhook_rate_limiter.go b/server/internal/handler/webhook_rate_limiter.go
index 804536708e..94e4f65593 100644
--- a/server/internal/handler/webhook_rate_limiter.go
+++ b/server/internal/handler/webhook_rate_limiter.go
@@ -33,13 +33,44 @@ func DefaultWebhookIPRateLimit() WebhookRateLimit {
return WebhookRateLimit{Limit: 30, Window: time.Minute}
}
+// DefaultWebhookAbsoluteIPRateLimit is the high emergency ceiling applied to
+// every webhook request before token lookup. Normal valid traffic should sit
+// far below this budget; unlike the lower bad-credential debt limiter it is
+// intentionally consumed by successful deliveries too.
+func DefaultWebhookAbsoluteIPRateLimit() WebhookRateLimit {
+ return WebhookRateLimit{Limit: 600, Window: time.Minute}
+}
+
// WebhookRateLimiter is the contract implemented by both the in-memory and
// Redis-backed limiters.
//
-// Allow returns true when the request is within budget for the given key,
-// false when it should be rejected (HTTP 429).
+// Check is non-consuming and is used to reject an IP that has already built
+// up bad-credential debt. Allow consumes one unit. RetryAfter returns a safe
+// client retry interval after either gate rejects.
type WebhookRateLimiter interface {
Allow(ctx context.Context, key string) bool
+ // Implementations may also satisfy webhookRateLimiterInspector. Keeping
+ // the base contract at Allow preserves compatibility with billing and
+ // tests that inject simple one-method safety gates.
+}
+
+type webhookRateLimiterInspector interface {
+ Check(ctx context.Context, key string) bool
+ RetryAfter(ctx context.Context, key string) time.Duration
+}
+
+func webhookLimiterCheck(ctx context.Context, limiter WebhookRateLimiter, key string) bool {
+ if inspector, ok := limiter.(webhookRateLimiterInspector); ok {
+ return inspector.Check(ctx, key)
+ }
+ return true
+}
+
+func webhookLimiterRetryAfter(ctx context.Context, limiter WebhookRateLimiter, key string) time.Duration {
+ if inspector, ok := limiter.(webhookRateLimiterInspector); ok {
+ return inspector.RetryAfter(ctx, key)
+ }
+ return time.Minute
}
// ── In-memory implementation ────────────────────────────────────────────────
@@ -59,6 +90,14 @@ func NewMemoryWebhookRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {
}
func (l *memoryWebhookRateLimiter) Allow(_ context.Context, key string) bool {
+ return l.evaluate(key, true)
+}
+
+func (l *memoryWebhookRateLimiter) Check(_ context.Context, key string) bool {
+ return l.evaluate(key, false)
+}
+
+func (l *memoryWebhookRateLimiter) evaluate(key string, consume bool) bool {
if l.cfg.Limit <= 0 {
return true
}
@@ -80,11 +119,30 @@ func (l *memoryWebhookRateLimiter) Allow(_ context.Context, key string) bool {
l.hit[key] = keep
return false
}
- keep = append(keep, now)
+ if consume {
+ keep = append(keep, now)
+ }
l.hit[key] = keep
return true
}
+func (l *memoryWebhookRateLimiter) RetryAfter(_ context.Context, key string) time.Duration {
+ if l.cfg.Limit <= 0 {
+ return 0
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ hits := l.hit[key]
+ if len(hits) == 0 {
+ return l.cfg.Window
+ }
+ retry := time.Until(hits[0].Add(l.cfg.Window))
+ if retry <= 0 {
+ return time.Second
+ }
+ return retry
+}
+
// ── Redis implementation ────────────────────────────────────────────────────
// webhookLimiterKey:<token> is the ZSET we keep timestamps in. The score is
@@ -94,8 +152,9 @@ func (l *memoryWebhookRateLimiter) Allow(_ context.Context, key string) bool {
// same nanosecond would otherwise collide on an identical member, ZADD would
// update-in-place instead of inserting, and the window would under-count.
const (
- webhookLimiterKeyPrefix = "mul:webhook:rate:"
- webhookIPLimiterKeyPrefix = "mul:webhook:ip:"
+ webhookLimiterKeyPrefix = "mul:webhook:rate:"
+ webhookIPLimiterKeyPrefix = "mul:webhook:ip:"
+ webhookAbsoluteIPLimiterKeyPrefix = "mul:webhook:absolute-ip:"
)
// webhookLimiterAllowSrc runs the slide-window check atomically on Redis:
@@ -131,6 +190,20 @@ return 1
var webhookLimiterAllowScript = redis.NewScript(webhookLimiterAllowSrc)
+const webhookLimiterCheckSrc = `
+local key = KEYS[1]
+local cutoff = tonumber(ARGV[1])
+local limit = tonumber(ARGV[2])
+redis.call('ZREMRANGEBYSCORE', key, '-inf', cutoff)
+local count = redis.call('ZCARD', key)
+if count >= limit then
+ return 0
+end
+return 1
+`
+
+var webhookLimiterCheckScript = redis.NewScript(webhookLimiterCheckSrc)
+
// webhookLimiterAllowSource exposes the script body for tests that want to
// assert structural invariants (e.g. trim before count before insert)
// without spinning up a real Redis. Lower-cased "Source" makes the
@@ -153,6 +226,10 @@ func NewRedisWebhookIPRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) Webho
return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookIPLimiterKeyPrefix}
}
+func NewRedisWebhookAbsoluteIPRateLimiter(rdb *redis.Client, cfg WebhookRateLimit) WebhookRateLimiter {
+ return &redisWebhookRateLimiter{cfg: cfg, rdb: rdb, keyPrefix: webhookAbsoluteIPLimiterKeyPrefix}
+}
+
// NewMemoryWebhookIPRateLimiter is the in-memory per-IP variant used when no
// Redis client is configured. Same per-key semantics as the per-token memory
// limiter — single-node only.
@@ -160,6 +237,10 @@ func NewMemoryWebhookIPRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {
return NewMemoryWebhookRateLimiter(cfg)
}
+func NewMemoryWebhookAbsoluteIPRateLimiter(cfg WebhookRateLimit) WebhookRateLimiter {
+ return NewMemoryWebhookRateLimiter(cfg)
+}
+
func (l *redisWebhookRateLimiter) Allow(ctx context.Context, key string) bool {
if l.cfg.Limit <= 0 || l.rdb == nil {
return true
@@ -192,3 +273,33 @@ func (l *redisWebhookRateLimiter) Allow(ctx context.Context, key string) bool {
}
return res == 1
}
+
+func (l *redisWebhookRateLimiter) Check(ctx context.Context, key string) bool {
+ if l.cfg.Limit <= 0 || l.rdb == nil {
+ return true
+ }
+ cutoff := time.Now().Add(-l.cfg.Window).UnixNano()
+ prefix := l.keyPrefix
+ if prefix == "" {
+ prefix = webhookLimiterKeyPrefix
+ }
+ res, err := webhookLimiterCheckScript.Run(
+ ctx,
+ l.rdb,
+ []string{prefix + key},
+ cutoff, l.cfg.Limit,
+ ).Int()
+ if err != nil {
+ return true
+ }
+ return res == 1
+}
+
+func (l *redisWebhookRateLimiter) RetryAfter(_ context.Context, _ string) time.Duration {
+ if l.cfg.Window <= 0 {
+ return time.Second
+ }
+ // A full window is conservative and remains correct across replicas even
+ // if the oldest ZSET member changes between rejection and this response.
+ return l.cfg.Window
+}
diff --git a/server/internal/handler/webhook_rate_limiter_test.go b/server/internal/handler/webhook_rate_limiter_test.go
index f2ef1d7bbd..df43497e0d 100644
--- a/server/internal/handler/webhook_rate_limiter_test.go
+++ b/server/internal/handler/webhook_rate_limiter_test.go
@@ -60,6 +60,23 @@ func TestMemoryWebhookRateLimiter_ZeroLimitDisabled(t *testing.T) {
}
}
+func TestMemoryWebhookRateLimiter_CheckDoesNotConsumeBudget(t *testing.T) {
+ l := NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1, Window: time.Minute})
+ ctx := context.Background()
+ if !webhookLimiterCheck(ctx, l, "shared-ip") || !webhookLimiterCheck(ctx, l, "shared-ip") {
+ t.Fatal("non-consuming checks should remain allowed before bad debt is charged")
+ }
+ if !l.Allow(ctx, "shared-ip") {
+ t.Fatal("check unexpectedly consumed the only budget slot")
+ }
+ if webhookLimiterCheck(ctx, l, "shared-ip") {
+ t.Fatal("check should reject after bad debt reaches the limit")
+ }
+ if retry := webhookLimiterRetryAfter(ctx, l, "shared-ip"); retry <= 0 || retry > time.Minute {
+ t.Fatalf("unexpected retry interval: %v", retry)
+ }
+}
+
// TestWebhookLimiterLuaScript_StructureGuard pins the Lua script so any future
// edit that reorders trim/count/insert (or drops EXPIRE) is caught even when
// no live Redis is available to the test process. The per-pod race the script
diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.go
index 2e352f3771..10ee90f1bf 100644
--- a/server/internal/metrics/business_events.go
+++ b/server/internal/metrics/business_events.go
@@ -54,6 +54,7 @@ type businessEventMetrics struct {
autopilotRunTerminal *prometheus.CounterVec
autopilotRunSkipped *prometheus.CounterVec
webhookDelivery *prometheus.CounterVec
+ webhookRateLimited *prometheus.CounterVec
githubEventReceived *prometheus.CounterVec
githubPRReview *prometheus.CounterVec
githubPRMergeSeconds prometheus.Histogram
@@ -162,6 +163,10 @@ func newBusinessEventMetrics() *businessEventMetrics {
Name: "multica_webhook_delivery_total",
Help: "Total inbound webhook deliveries by provider and outcome.",
}, metricLabels("multica_webhook_delivery_total")),
+ webhookRateLimited: prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "multica_webhook_rate_limited_total",
+ Help: "Total webhook admissions or worker dispatches delayed by a bounded safety gate.",
+ }, metricLabels("multica_webhook_rate_limited_total")),
githubEventReceived: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "multica_github_event_received_total",
Help: "Total GitHub webhook events received by event kind and action.",
@@ -224,6 +229,7 @@ func (e *businessEventMetrics) collectors() []prometheus.Collector {
e.autopilotRunTerminal,
e.autopilotRunSkipped,
e.webhookDelivery,
+ e.webhookRateLimited,
e.githubEventReceived,
e.githubPRReview,
e.githubPRMergeSeconds,
@@ -381,6 +387,13 @@ func (m *BusinessMetrics) RecordWebhookDelivery(provider, status string) {
).Inc()
}
+func (m *BusinessMetrics) RecordWebhookRateLimited(gate string) {
+ if m == nil || m.events == nil {
+ return
+ }
+ m.events.webhookRateLimited.WithLabelValues(NormalizeWebhookRateLimitGate(gate)).Inc()
+}
+
// RecordGithubEventReceived counts a GitHub webhook event by event kind / action.
func (m *BusinessMetrics) RecordGithubEventReceived(eventKind, action string) {
if m == nil || m.events == nil {
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index 73aab0bfb6..70b8f32542 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -139,6 +139,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
// Direct Record* helpers (no PostHog event source).
m.RecordAutopilotRunSkipped("manual", "throttled")
m.RecordWebhookDelivery("github", "dispatched")
+ m.RecordWebhookRateLimited("absolute_ip")
m.RecordGithubEventReceived("pull_request", "opened")
m.RecordGithubPRReview("approved")
m.ObserveGithubPRMergeSeconds(120)
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index a9260e75a6..3404e9f8f1 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -31,6 +31,7 @@ const (
labelAction = "action"
labelResult = "result"
labelOp = "op"
+ labelGate = "gate"
)
var businessMetricLabels = map[string][]string{
@@ -76,6 +77,7 @@ var businessMetricLabels = map[string][]string{
"multica_autopilot_run_terminal_total": {labelCadence, labelTriggerKind, labelTerminalStatus},
"multica_autopilot_run_skipped_total": {labelCadence, labelReason},
"multica_webhook_delivery_total": {labelProvider, labelStatus},
+ "multica_webhook_rate_limited_total": {labelGate},
"multica_github_event_received_total": {labelEventKind, labelAction},
"multica_github_pr_review_total": {labelResult},
"multica_cloudruntime_request_total": {labelOp, labelStatus},
diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.go
index 2e086534a2..71d3753621 100644
--- a/server/internal/metrics/labels_pr3.go
+++ b/server/internal/metrics/labels_pr3.go
@@ -120,6 +120,13 @@ var (
"other": "other",
}
+ knownWebhookRateLimitGates = map[string]string{
+ "absolute_ip": "absolute_ip",
+ "bad_credential_ip": "bad_credential_ip",
+ "worker_trigger": "worker_trigger",
+ "other": "other",
+ }
+
knownGithubEventKinds = map[string]string{
"pull_request": "pull_request",
"pull_request_review": "pull_request_review",
@@ -328,6 +335,10 @@ func NormalizeWebhookDeliveryStatus(value string) string {
return normalizeFromAllowList(value, knownWebhookDeliveryStatuses, "other")
}
+func NormalizeWebhookRateLimitGate(value string) string {
+ return normalizeFromAllowList(value, knownWebhookRateLimitGates, "other")
+}
+
func NormalizeGithubEventKind(value string) string {
return normalizeFromAllowList(value, knownGithubEventKinds, "other")
}
diff --git a/server/internal/metrics/labels_pr3_test.go b/server/internal/metrics/labels_pr3_test.go
index 3f759e5b08..f1c066d7c3 100644
--- a/server/internal/metrics/labels_pr3_test.go
+++ b/server/internal/metrics/labels_pr3_test.go
@@ -36,6 +36,7 @@ func TestNormalizePR3LabelsCollapseUnknownValues(t *testing.T) {
{"autopilot_skip_reason_unknown", metrics.NormalizeAutopilotSkipReason, "lunar_phase", "other", "other"},
{"webhook_provider_unknown", metrics.NormalizeWebhookProvider, "internal-billing", "other", "other"},
{"webhook_status_unknown", metrics.NormalizeWebhookDeliveryStatus, "exotic", "other", "other"},
+ {"webhook_gate_unknown", metrics.NormalizeWebhookRateLimitGate, "exotic", "other", "other"},
{"github_event_unknown", metrics.NormalizeGithubEventKind, "deploy_status", "other", "other"},
{"github_action_empty", metrics.NormalizeGithubAction, "", "none", "none"},
{"github_action_unknown", metrics.NormalizeGithubAction, "rerequested_by_user", "other", "other"},
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 49dac019ad..357129bf95 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -71,7 +71,96 @@ func (s *AutopilotService) DispatchAutopilot(
source string,
payload []byte,
) (*db.AutopilotRun, error) {
- return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{})
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, pgtype.Timestamptz{}, pgtype.UUID{})
+}
+
+// DispatchAutopilotForWebhookDelivery is the durable webhook worker entry
+// point. webhook_delivery_id is persisted on the run and protected by a
+// partial unique index, so reclaiming a queued delivery after a process crash
+// reuses the original run instead of creating a second issue or task.
+func (s *AutopilotService) DispatchAutopilotForWebhookDelivery(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ payload []byte,
+ deliveryID pgtype.UUID,
+) (*db.AutopilotRun, error) {
+ if !deliveryID.Valid {
+ return nil, fmt.Errorf("dispatch for webhook delivery: delivery_id is required")
+ }
+
+ existing, err := s.Queries.GetAutopilotRunByWebhookDelivery(ctx, deliveryID)
+ switch {
+ case err == nil && isAutopilotRunComplete(existing):
+ if autopilot.ExecutionMode == "create_issue" && existing.IssueID.Valid {
+ if repairErr := s.ensureWebhookCreateIssueTask(ctx, autopilot, existing); repairErr != nil {
+ return &existing, repairErr
+ }
+ }
+ return &existing, nil
+ case err == nil:
+ // A run_only task may have committed immediately before the process
+ // died 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" && !existing.TaskID.Valid {
+ task, taskErr := s.Queries.GetAutopilotTaskByRun(ctx, existing.ID)
+ switch {
+ case taskErr == nil:
+ updated, updateErr := s.Queries.UpdateAutopilotRunRunning(ctx, db.UpdateAutopilotRunRunningParams{
+ ID: existing.ID,
+ TaskID: task.ID,
+ })
+ if updateErr != nil {
+ return &existing, 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 &existing, fmt.Errorf("dispatch for webhook delivery: lookup linked task: %w", taskErr)
+ }
+ }
+ return s.dispatchAutopilotRun(ctx, autopilot, triggerID, "webhook", &existing)
+ case !errors.Is(err, pgx.ErrNoRows):
+ return nil, fmt.Errorf("dispatch for webhook delivery: lookup existing run: %w", err)
+ }
+
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, "webhook", payload, pgtype.Timestamptz{}, deliveryID)
+}
+
+// ensureWebhookCreateIssueTask repairs the create_issue crash window after the
+// issue/run transaction commits but before the ordinary task enqueue commits.
+// Any existing issue task is sufficient evidence that ownership has already
+// moved downstream; otherwise enqueue exactly the same assignee path used by
+// the original dispatch.
+func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, autopilot db.Autopilot, run db.AutopilotRun) error {
+ tasks, err := s.Queries.ListTasksByIssue(ctx, run.IssueID)
+ if err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: inspect issue tasks: %w", err)
+ }
+ if len(tasks) > 0 {
+ return nil
+ }
+ issue, err := s.Queries.GetIssue(ctx, run.IssueID)
+ if err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: load linked issue: %w", err)
+ }
+ if issue.Status != "todo" && issue.Status != "in_progress" {
+ return nil
+ }
+ if autopilot.AssigneeType == "squad" {
+ leader, _, err := s.resolveAutopilotLeader(ctx, autopilot)
+ if err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: resolve squad leader: %w", err)
+ }
+ if _, err := s.TaskSvc.EnqueueTaskForSquadLeader(ctx, issue, leader.ID, autopilot.AssigneeID, pgtype.UUID{}); err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: repair squad task: %w", err)
+ }
+ return nil
+ }
+ if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: repair issue task: %w", err)
+ }
+ return nil
}
// DispatchAutopilotForPlan is the entry point for scheduled triggers that
@@ -155,7 +244,7 @@ func (s *AutopilotService) DispatchAutopilotForPlan(
return nil, fmt.Errorf("dispatch for plan: lookup existing run: %w", err)
}
- return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS)
+ return s.dispatchAutopilot(ctx, autopilot, triggerID, source, payload, plannedTS, pgtype.UUID{})
}
// isAutopilotRunComplete decides whether an existing autopilot_run row
@@ -196,7 +285,8 @@ func isAutopilotRunComplete(run db.AutopilotRun) bool {
// dispatchAutopilot is the shared core of the two public Dispatch entry
// points. plannedAt is the canonical UTC plan_time for scheduled triggers;
// for manual / webhook / api dispatch it is the zero pgtype.Timestamptz and
-// the resulting autopilot_run row has planned_at IS NULL.
+// the resulting autopilot_run row has planned_at IS NULL. webhookDeliveryID
+// is set only by the durable webhook worker.
func (s *AutopilotService) dispatchAutopilot(
ctx context.Context,
autopilot db.Autopilot,
@@ -204,9 +294,10 @@ func (s *AutopilotService) dispatchAutopilot(
source string,
payload []byte,
plannedAt pgtype.Timestamptz,
+ webhookDeliveryID pgtype.UUID,
) (*db.AutopilotRun, error) {
if reason, skip := s.shouldSkipDispatch(ctx, autopilot); skip {
- return s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, reason)
+ return s.recordSkippedRun(ctx, autopilot, triggerID, source, payload, plannedAt, webhookDeliveryID, reason)
}
// Determine initial status based on execution mode.
@@ -216,43 +307,57 @@ func (s *AutopilotService) dispatchAutopilot(
}
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
- AutopilotID: autopilot.ID,
- TriggerID: triggerID,
- Source: source,
- Status: initialStatus,
- TriggerPayload: payload,
- SquadID: autopilotSquadAttribution(autopilot),
- PlannedAt: plannedAt,
+ AutopilotID: autopilot.ID,
+ TriggerID: triggerID,
+ Source: source,
+ Status: initialStatus,
+ TriggerPayload: payload,
+ SquadID: autopilotSquadAttribution(autopilot),
+ PlannedAt: plannedAt,
+ WebhookDeliveryID: webhookDeliveryID,
})
if err != nil {
return nil, fmt.Errorf("create run: %w", err)
}
s.captureAutopilotRunStarted(autopilot, run, source)
+ return s.dispatchAutopilotRun(ctx, autopilot, triggerID, source, &run)
+}
+// dispatchAutopilotRun performs the downstream side effect for an already
+// persisted run. Keeping creation separate lets the webhook worker resume the
+// same idempotency-anchored run after a crash between run creation and issue
+// or task creation.
+func (s *AutopilotService) dispatchAutopilotRun(
+ ctx context.Context,
+ autopilot db.Autopilot,
+ triggerID pgtype.UUID,
+ source string,
+ run *db.AutopilotRun,
+) (*db.AutopilotRun, error) {
switch autopilot.ExecutionMode {
case "create_issue":
triggerTimezone := s.resolveAutopilotTriggerTimezone(ctx, triggerID)
- if err := s.dispatchCreateIssue(ctx, autopilot, &run, triggerTimezone); err != nil {
- if skipped := s.handleDispatchSkip(ctx, autopilot, &run, err); skipped != nil {
+ if err := s.dispatchCreateIssue(ctx, autopilot, run, triggerTimezone); err != nil {
+ if skipped := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
return skipped, nil
}
s.failRun(ctx, run.ID, err.Error())
- s.captureAutopilotRunFailed(autopilot, run, source, err.Error())
- return &run, fmt.Errorf("dispatch create_issue: %w", err)
+ s.captureAutopilotRunFailed(autopilot, *run, source, err.Error())
+ return run, fmt.Errorf("dispatch create_issue: %w", err)
}
case "run_only":
- if err := s.dispatchRunOnly(ctx, autopilot, &run); err != nil {
- if skipped := s.handleDispatchSkip(ctx, autopilot, &run, err); skipped != nil {
+ if err := s.dispatchRunOnly(ctx, autopilot, run); err != nil {
+ if skipped := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {
return skipped, nil
}
s.failRun(ctx, run.ID, err.Error())
- s.captureAutopilotRunFailed(autopilot, run, source, err.Error())
- return &run, fmt.Errorf("dispatch run_only: %w", err)
+ s.captureAutopilotRunFailed(autopilot, *run, source, err.Error())
+ return run, fmt.Errorf("dispatch run_only: %w", err)
}
default:
s.failRun(ctx, run.ID, "unknown execution_mode: "+autopilot.ExecutionMode)
- s.captureAutopilotRunFailed(autopilot, run, source, "unknown execution_mode: "+autopilot.ExecutionMode)
- return &run, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)
+ s.captureAutopilotRunFailed(autopilot, *run, source, "unknown execution_mode: "+autopilot.ExecutionMode)
+ return run, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)
}
// Update last_run_at on the autopilot.
@@ -271,7 +376,7 @@ func (s *AutopilotService) dispatchAutopilot(
},
})
- return &run, nil
+ return run, nil
}
// dispatchCreateIssue creates an issue and enqueues a task for the agent.
@@ -1005,16 +1110,18 @@ func (s *AutopilotService) recordSkippedRun(
source string,
payload []byte,
plannedAt pgtype.Timestamptz,
+ webhookDeliveryID pgtype.UUID,
reason string,
) (*db.AutopilotRun, error) {
run, err := s.Queries.CreateAutopilotRun(ctx, db.CreateAutopilotRunParams{
- AutopilotID: autopilot.ID,
- TriggerID: triggerID,
- Source: source,
- Status: "skipped",
- TriggerPayload: payload,
- SquadID: autopilotSquadAttribution(autopilot),
- PlannedAt: plannedAt,
+ AutopilotID: autopilot.ID,
+ TriggerID: triggerID,
+ Source: source,
+ Status: "skipped",
+ TriggerPayload: payload,
+ SquadID: autopilotSquadAttribution(autopilot),
+ PlannedAt: plannedAt,
+ WebhookDeliveryID: webhookDeliveryID,
})
if err != nil {
return nil, fmt.Errorf("create skipped run: %w", err)
diff --git a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md b/server/internal/service/builtin_skills/multica-autopilots/SKILL.md
index 110788bb2e..aae5b89080 100644
--- a/server/internal/service/builtin_skills/multica-autopilots/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-autopilots/SKILL.md
@@ -23,7 +23,7 @@ Do not run `trigger`, `delete`, `trigger-delete`, or `trigger-rotate-url` to tes
An autopilot is not an agent. It is a rule that dispatches work to an agent, or to a squad's leader agent.
-The chain is: trigger fires (`schedule`, `webhook`, or `manual`) -> `autopilot_run` row -> `execution_mode` decides output -> assignee readiness check -> issue/task execution -> run status sync.
+The chain is: trigger fires (`schedule`, `webhook`, or `manual`) -> `autopilot_run` row -> `execution_mode` decides output -> assignee readiness check -> issue/task execution -> run status sync. Webhooks have a durable admission step in front: HTTP ingress stores a queued `webhook_delivery` and returns `202`; a database-leased worker creates or reuses the delivery's idempotent run.
Execution modes:
@@ -59,7 +59,8 @@ For "why didn't it run":
2. `multica autopilot runs <id> --output json` — run status and failure reason.
3. If assigned to a squad, inspect the squad: `multica squad get <squad-id> --output json`; execution goes to the leader.
4. Inspect the target agent/runtime: `multica agent get <agent-id> --output json` and `multica runtime list --output json`.
-5. For `create_issue`, inspect the created issue if the run records one.
+5. For webhooks, inspect delivery status: `queued` means the worker has not completed dispatch; `failed` carries the worker error. A provider retry with the same `X-GitHub-Delivery` / `Idempotency-Key` reuses the original delivery.
+6. For `create_issue`, inspect the created issue if the run records one.
## Side effects
diff --git a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md
index d394eb0601..434dd611af 100644
--- a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md
+++ b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md
@@ -2,10 +2,11 @@
- `server/cmd/multica/cmd_autopilot.go` registers `list`, `get`, `create`, `update`, `delete`, `trigger`, `runs`, `trigger-add`, `trigger-update`, `trigger-delete`, and `trigger-rotate-url`.
- The CLI maps reads/writes to `/api/autopilots`, `/api/autopilots/{id}`, `/api/autopilots/{id}/trigger`, `/api/autopilots/{id}/runs`, and trigger subroutes.
-- `server/internal/service/autopilot.go` has `DispatchAutopilot`, creates `autopilot_run`, and switches on `execution_mode`.
+- `server/internal/service/autopilot.go` has `DispatchAutopilot` plus the delivery-idempotent `DispatchAutopilotForWebhookDelivery`, creates `autopilot_run`, and switches on `execution_mode`.
- `create_issue` calls `dispatchCreateIssue`; `run_only` calls `dispatchRunOnly`.
- `resolveAutopilotLeader` resolves squad-assigned autopilots to the squad leader.
- `AgentReadiness` blocks archived/runtime-unready agents before enqueue.
- `server/cmd/server/router.go` exposes authenticated `/api/autopilots` routes and unauthenticated webhook ingress `/api/webhooks/autopilots/{token}`.
+- `server/internal/handler/webhook_delivery_worker.go` claims queued deliveries with expiring database leases, applies per-trigger dispatch pacing, and resumes them using `autopilot_run.webhook_delivery_id` so recovery cannot duplicate a run/task.
- Write/execute authorization lives in `autopilotWriteByOwnership` / `memberCanWriteAutopilot` / `requireAutopilotWrite` (`server/internal/handler/autopilot.go`): editing, deleting, triggering, replaying deliveries, and managing triggers/webhook secrets require the autopilot's creator, a workspace owner/admin, or an explicit collaborator. Reads (list/get/runs/deliveries) stay open to any workspace member, but `GetAutopilot` redacts `webhook_token`/`webhook_path`/`webhook_url` for callers who lack write access, since the token alone can trigger the autopilot. Creating a new autopilot is still open to any member (they become its creator). This is the autopilot-level View/Write layer; it is independent of, and ANDed with, the private-assignee-agent gate enforced at dispatch time in `shouldSkipDispatch`.
- Explicit write grants ("collaborators") are stored in the `autopilot_collaborator` table (migration 128, members-only, no FK — deleted alongside the autopilot in the delete transaction). Endpoints: `POST /api/autopilots/{id}/collaborators` (body `{user_id}`) and `DELETE /api/autopilots/{id}/collaborators/{userId}`, both gated by the NARROWER `requireAutopilotAccessManagement` (creator or workspace owner/admin only — a granted collaborator keeps write/execute but cannot re-grant or revoke peers, preventing privilege escalation), both returning the updated `{collaborators}` list. `GetAutopilot` embeds the `collaborators` array and stamps two per-caller booleans: `can_write` (gates edit/run/trigger controls) and the narrower `can_manage_access` (gates the "Manage access" entry). The web/desktop "Manage access" UI lives in `packages/views/autopilots/components/manage-access-dialog.tsx`.
diff --git a/server/migrations/175_webhook_delivery_worker.down.sql b/server/migrations/175_webhook_delivery_worker.down.sql
new file mode 100644
index 0000000000..a853f9f307
--- /dev/null
+++ b/server/migrations/175_webhook_delivery_worker.down.sql
@@ -0,0 +1,8 @@
+ALTER TABLE autopilot_run
+ DROP COLUMN IF EXISTS webhook_delivery_id;
+
+ALTER TABLE webhook_delivery
+ DROP COLUMN IF EXISTS dispatch_attempts,
+ DROP COLUMN IF EXISTS lease_expires_at,
+ DROP COLUMN IF EXISTS lease_token,
+ DROP COLUMN IF EXISTS available_at;
diff --git a/server/migrations/175_webhook_delivery_worker.up.sql b/server/migrations/175_webhook_delivery_worker.up.sql
new file mode 100644
index 0000000000..cdcca04729
--- /dev/null
+++ b/server/migrations/175_webhook_delivery_worker.up.sql
@@ -0,0 +1,14 @@
+-- Durable webhook dispatch state. The HTTP handler only admits the delivery;
+-- a database-leased worker owns downstream autopilot dispatch.
+--
+-- Keep the idempotency anchor deliberately free of a foreign key. The code
+-- already validates the referenced delivery, while avoiding a new FK keeps
+-- deploys and rollback independent of existing webhook_delivery cascades.
+ALTER TABLE webhook_delivery
+ ADD COLUMN available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ ADD COLUMN lease_token UUID,
+ ADD COLUMN lease_expires_at TIMESTAMPTZ,
+ ADD COLUMN dispatch_attempts INTEGER NOT NULL DEFAULT 0;
+
+ALTER TABLE autopilot_run
+ ADD COLUMN webhook_delivery_id UUID;
diff --git a/server/migrations/176_autopilot_run_webhook_delivery_index.down.sql b/server/migrations/176_autopilot_run_webhook_delivery_index.down.sql
new file mode 100644
index 0000000000..8160c88421
--- /dev/null
+++ b/server/migrations/176_autopilot_run_webhook_delivery_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_autopilot_run_webhook_delivery;
diff --git a/server/migrations/176_autopilot_run_webhook_delivery_index.up.sql b/server/migrations/176_autopilot_run_webhook_delivery_index.up.sql
new file mode 100644
index 0000000000..7aaeeb67d9
--- /dev/null
+++ b/server/migrations/176_autopilot_run_webhook_delivery_index.up.sql
@@ -0,0 +1,3 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_autopilot_run_webhook_delivery
+ ON autopilot_run(webhook_delivery_id)
+ WHERE webhook_delivery_id IS NOT NULL;
diff --git a/server/migrations/177_webhook_delivery_queue_index.down.sql b/server/migrations/177_webhook_delivery_queue_index.down.sql
new file mode 100644
index 0000000000..f6f072a189
--- /dev/null
+++ b/server/migrations/177_webhook_delivery_queue_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_webhook_delivery_queue;
diff --git a/server/migrations/177_webhook_delivery_queue_index.up.sql b/server/migrations/177_webhook_delivery_queue_index.up.sql
new file mode 100644
index 0000000000..ef8f519bb3
--- /dev/null
+++ b/server/migrations/177_webhook_delivery_queue_index.up.sql
@@ -0,0 +1,3 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_webhook_delivery_queue
+ ON webhook_delivery(available_at, created_at)
+ WHERE status = 'queued';
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index fb91cbaa74..108a199af9 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -156,21 +156,24 @@ func (q *Queries) CreateAutopilot(ctx context.Context, arg CreateAutopilotParams
const createAutopilotRun = `-- name: CreateAutopilotRun :one
INSERT INTO autopilot_run (
- autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at
+ autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,
+ webhook_delivery_id
) VALUES (
$1, $4, $2, $3, $5,
- $6, $7
-) RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
+ $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
`
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"`
+ 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"`
}
// =====================
@@ -196,6 +199,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
arg.TriggerPayload,
arg.SquadID,
arg.PlannedAt,
+ arg.WebhookDeliveryID,
)
var i AutopilotRun
err := row.Scan(
@@ -214,6 +218,7 @@ func (q *Queries) CreateAutopilotRun(ctx context.Context, arg CreateAutopilotRun
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -470,7 +475,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 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 FROM autopilot_run
WHERE id = $1
`
@@ -493,13 +498,14 @@ func (q *Queries) GetAutopilotRun(ctx context.Context, id pgtype.UUID) (Autopilo
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
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 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 FROM autopilot_run
WHERE issue_id = $1 AND status IN ('issue_created', 'running')
LIMIT 1
`
@@ -526,12 +532,13 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
const getAutopilotRunByTriggerAndPlanned = `-- name: GetAutopilotRunByTriggerAndPlanned :one
-SELECT id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at FROM autopilot_run
+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
WHERE trigger_id = $1
AND planned_at = $2
LIMIT 1
@@ -569,6 +576,92 @@ func (q *Queries) GetAutopilotRunByTriggerAndPlanned(ctx context.Context, arg Ge
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
+ )
+ 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
+WHERE webhook_delivery_id = $1
+LIMIT 1
+`
+
+func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookDeliveryID pgtype.UUID) (AutopilotRun, error) {
+ row := q.db.QueryRow(ctx, getAutopilotRunByWebhookDelivery, webhookDeliveryID)
+ 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,
+ )
+ return i, err
+}
+
+const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
+WHERE autopilot_run_id = $1
+ORDER BY created_at
+LIMIT 1
+`
+
+// Repairs the narrow run_only crash window where the task INSERT committed
+// but the following autopilot_run.task_id update did not.
+func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, getAutopilotTaskByRun, autopilotRunID)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -740,7 +833,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 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 FROM autopilot_run
WHERE autopilot_id = $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
@@ -777,6 +870,7 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPa
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
); err != nil {
return nil, err
}
@@ -1385,7 +1479,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
+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
`
type UpdateAutopilotRunCompletedParams struct {
@@ -1412,6 +1506,7 @@ func (q *Queries) UpdateAutopilotRunCompleted(ctx context.Context, arg UpdateAut
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -1420,7 +1515,7 @@ const updateAutopilotRunFailed = `-- name: UpdateAutopilotRunFailed :one
UPDATE autopilot_run
SET status = 'failed', completed_at = now(), failure_reason = $2
WHERE id = $1
-RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
+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
`
type UpdateAutopilotRunFailedParams struct {
@@ -1447,6 +1542,7 @@ func (q *Queries) UpdateAutopilotRunFailed(ctx context.Context, arg UpdateAutopi
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -1455,7 +1551,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
+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
`
type UpdateAutopilotRunIssueCreatedParams struct {
@@ -1482,6 +1578,7 @@ func (q *Queries) UpdateAutopilotRunIssueCreated(ctx context.Context, arg Update
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -1490,7 +1587,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
+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
`
type UpdateAutopilotRunRunningParams struct {
@@ -1517,6 +1614,7 @@ func (q *Queries) UpdateAutopilotRunRunning(ctx context.Context, arg UpdateAutop
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -1525,7 +1623,7 @@ const updateAutopilotRunSkipped = `-- name: UpdateAutopilotRunSkipped :one
UPDATE autopilot_run
SET status = 'skipped', completed_at = now(), failure_reason = $2
WHERE id = $1
-RETURNING id, autopilot_id, trigger_id, source, status, issue_id, task_id, triggered_at, completed_at, failure_reason, trigger_payload, result, created_at, squad_id, planned_at
+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
`
type UpdateAutopilotRunSkippedParams struct {
@@ -1558,6 +1656,7 @@ func (q *Queries) UpdateAutopilotRunSkipped(ctx context.Context, arg UpdateAutop
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
@@ -1569,7 +1668,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
+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
`
type UpdateAutopilotRunSkippedWithResultParams struct {
@@ -1597,6 +1696,7 @@ func (q *Queries) UpdateAutopilotRunSkippedWithResult(ctx context.Context, arg U
&i.CreatedAt,
&i.SquadID,
&i.PlannedAt,
+ &i.WebhookDeliveryID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 5aed9919cb..487a07f6fc 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -183,21 +183,22 @@ type AutopilotCollaborator 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"`
+ 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"`
}
type AutopilotSubscriber struct {
@@ -963,6 +964,10 @@ type WebhookDelivery struct {
ReceivedAt pgtype.Timestamptz `json:"received_at"`
LastAttemptAt pgtype.Timestamptz `json:"last_attempt_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ AvailableAt pgtype.Timestamptz `json:"available_at"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
+ DispatchAttempts int32 `json:"dispatch_attempts"`
}
type Workspace struct {
diff --git a/server/pkg/db/generated/webhook_delivery.sql.go b/server/pkg/db/generated/webhook_delivery.sql.go
index f2b8ff133b..bf17096d05 100644
--- a/server/pkg/db/generated/webhook_delivery.sql.go
+++ b/server/pkg/db/generated/webhook_delivery.sql.go
@@ -11,12 +11,64 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const acknowledgeWebhookDelivery = `-- name: AcknowledgeWebhookDelivery :one
+UPDATE webhook_delivery
+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
+`
+
+type AcknowledgeWebhookDeliveryParams struct {
+ ID pgtype.UUID `json:"id"`
+ ResponseStatus pgtype.Int4 `json:"response_status"`
+ ResponseBody pgtype.Text `json:"response_body"`
+}
+
+// Best-effort operator metadata for the HTTP acknowledgement. Admission is
+// already durable once the initial queued row exists, so callers still return
+// 202 if this metadata-only update fails.
+func (q *Queries) AcknowledgeWebhookDelivery(ctx context.Context, arg AcknowledgeWebhookDeliveryParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, acknowledgeWebhookDelivery, arg.ID, arg.ResponseStatus, arg.ResponseBody)
+ 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,
+ )
+ return i, err
+}
+
const bumpWebhookDeliveryAttempt = `-- name: BumpWebhookDeliveryAttempt :one
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
+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
`
// On duplicate detection, bump attempt_count and refresh last_attempt_at on
@@ -48,6 +100,131 @@ func (q *Queries) BumpWebhookDeliveryAttempt(ctx context.Context, id pgtype.UUID
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
+ )
+ return i, err
+}
+
+const claimQueuedWebhookDelivery = `-- name: ClaimQueuedWebhookDelivery :one
+WITH candidate AS (
+ SELECT id
+ FROM webhook_delivery
+ WHERE status = 'queued'
+ AND available_at <= now()
+ AND (lease_expires_at IS NULL OR lease_expires_at <= now())
+ ORDER BY available_at, created_at
+ FOR UPDATE SKIP LOCKED
+ LIMIT 1
+)
+UPDATE webhook_delivery AS d
+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
+`
+
+// Claims one due delivery. SKIP LOCKED spreads work across replicas; the
+// expiring token makes a crashed claim visible to a later sweeper pass.
+// The lease is a scheduling optimization, not the exactly-once guard: if a
+// slow dispatch outlives it, uq_autopilot_run_webhook_delivery remains the
+// final protection against duplicate downstream runs.
+func (q *Queries) ClaimQueuedWebhookDelivery(ctx context.Context) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, claimQueuedWebhookDelivery)
+ 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,
+ )
+ return i, err
+}
+
+const completeClaimedWebhookDelivery = `-- name: CompleteClaimedWebhookDelivery :one
+UPDATE webhook_delivery
+SET status = $3,
+ autopilot_run_id = $4,
+ dispatch_attempts = dispatch_attempts + 1,
+ error = $5,
+ 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
+`
+
+type CompleteClaimedWebhookDeliveryParams struct {
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ Status string `json:"status"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Error pgtype.Text `json:"error"`
+}
+
+func (q *Queries) CompleteClaimedWebhookDelivery(ctx context.Context, arg CompleteClaimedWebhookDeliveryParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, completeClaimedWebhookDelivery,
+ arg.ID,
+ arg.LeaseToken,
+ arg.Status,
+ arg.AutopilotRunID,
+ arg.Error,
+ )
+ 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,
)
return i, err
}
@@ -64,7 +241,7 @@ INSERT INTO webhook_delivery (
$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
+) 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
`
type CreateWebhookDeliveryParams struct {
@@ -129,12 +306,69 @@ func (q *Queries) CreateWebhookDelivery(ctx context.Context, arg CreateWebhookDe
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
+ )
+ return i, err
+}
+
+const deferClaimedWebhookDelivery = `-- name: DeferClaimedWebhookDelivery :one
+UPDATE webhook_delivery
+SET available_at = $3,
+ lease_token = NULL,
+ lease_expires_at = NULL
+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
+`
+
+type DeferClaimedWebhookDeliveryParams struct {
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ AvailableAt pgtype.Timestamptz `json:"available_at"`
+}
+
+// Releases a claim without counting a dispatch attempt. Used when the
+// per-trigger worker budget is exhausted before downstream dispatch begins.
+func (q *Queries) DeferClaimedWebhookDelivery(ctx context.Context, arg DeferClaimedWebhookDeliveryParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, deferClaimedWebhookDelivery, arg.ID, arg.LeaseToken, arg.AvailableAt)
+ 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,
)
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 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 FROM webhook_delivery
WHERE id = $1
`
@@ -164,12 +398,16 @@ func (q *Queries) GetWebhookDelivery(ctx context.Context, id pgtype.UUID) (Webho
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
)
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 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 FROM webhook_delivery
WHERE trigger_id = $1
AND dedupe_key = $2
ORDER BY (status IN ('rejected', 'failed')), created_at DESC
@@ -214,12 +452,16 @@ func (q *Queries) GetWebhookDeliveryByTriggerAndDedupe(ctx context.Context, arg
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
)
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 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 FROM webhook_delivery
WHERE id = $1 AND workspace_id = $2
`
@@ -255,6 +497,10 @@ func (q *Queries) GetWebhookDeliveryInWorkspace(ctx context.Context, arg GetWebh
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
)
return i, err
}
@@ -265,7 +511,8 @@ SELECT
d.dedupe_key, d.dedupe_source, d.signature_status, d.status,
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.received_at, d.last_attempt_at, d.created_at,
+ d.available_at, d.dispatch_attempts
FROM webhook_delivery d
JOIN autopilot a ON a.id = d.autopilot_id
WHERE d.autopilot_id = $1
@@ -301,6 +548,8 @@ type ListWebhookDeliveriesByAutopilotRow struct {
ReceivedAt pgtype.Timestamptz `json:"received_at"`
LastAttemptAt pgtype.Timestamptz `json:"last_attempt_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ AvailableAt pgtype.Timestamptz `json:"available_at"`
+ DispatchAttempts int32 `json:"dispatch_attempts"`
}
// Workspace-scoped via the join so a runId from another workspace cannot
@@ -345,6 +594,8 @@ func (q *Queries) ListWebhookDeliveriesByAutopilot(ctx context.Context, arg List
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.DispatchAttempts,
); err != nil {
return nil, err
}
@@ -356,6 +607,69 @@ func (q *Queries) ListWebhookDeliveriesByAutopilot(ctx context.Context, arg List
return items, nil
}
+const retryClaimedWebhookDelivery = `-- name: RetryClaimedWebhookDelivery :one
+UPDATE webhook_delivery
+SET available_at = $3,
+ dispatch_attempts = dispatch_attempts + 1,
+ error = $4,
+ 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
+`
+
+type RetryClaimedWebhookDeliveryParams struct {
+ ID pgtype.UUID `json:"id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ AvailableAt pgtype.Timestamptz `json:"available_at"`
+ Error pgtype.Text `json:"error"`
+}
+
+// Records a transient worker failure and makes the delivery eligible after
+// its bounded backoff. HTTP response fields intentionally remain the 202
+// acknowledgement already returned to the provider.
+func (q *Queries) RetryClaimedWebhookDelivery(ctx context.Context, arg RetryClaimedWebhookDeliveryParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, retryClaimedWebhookDelivery,
+ arg.ID,
+ arg.LeaseToken,
+ arg.AvailableAt,
+ arg.Error,
+ )
+ 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,
+ )
+ return i, err
+}
+
const updateWebhookDeliveryDispatched = `-- name: UpdateWebhookDeliveryDispatched :one
UPDATE webhook_delivery
SET status = $2,
@@ -364,7 +678,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
+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
`
type UpdateWebhookDeliveryDispatchedParams struct {
@@ -410,6 +724,10 @@ func (q *Queries) UpdateWebhookDeliveryDispatched(ctx context.Context, arg Updat
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
)
return i, err
}
@@ -422,7 +740,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
+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
`
type UpdateWebhookDeliveryTerminalParams struct {
@@ -468,6 +786,10 @@ func (q *Queries) UpdateWebhookDeliveryTerminal(ctx context.Context, arg UpdateW
&i.ReceivedAt,
&i.LastAttemptAt,
&i.CreatedAt,
+ &i.AvailableAt,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.DispatchAttempts,
)
return i, err
}
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index fa7a98cdfd..f04a9ad82c 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -199,10 +199,12 @@ RETURNING *;
-- idempotency: a stale-steal retry at the same plan_time cannot create
-- a second run for the same (trigger_id, planned_at) pair (MUL-3551).
INSERT INTO autopilot_run (
- autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at
+ autopilot_id, trigger_id, source, status, trigger_payload, squad_id, planned_at,
+ webhook_delivery_id
) VALUES (
$1, sqlc.narg('trigger_id'), $2, $3, sqlc.narg('trigger_payload'),
- sqlc.narg('squad_id'), sqlc.narg('planned_at')
+ sqlc.narg('squad_id'), sqlc.narg('planned_at'),
+ sqlc.narg('webhook_delivery_id')
) RETURNING *;
-- name: GetAutopilotRunByTriggerAndPlanned :one
@@ -219,6 +221,11 @@ WHERE trigger_id = $1
AND planned_at = $2
LIMIT 1;
+-- name: GetAutopilotRunByWebhookDelivery :one
+SELECT * FROM autopilot_run
+WHERE webhook_delivery_id = $1
+LIMIT 1;
+
-- name: RecoverPartialAutopilotRun :exec
-- Recovers a partial-state autopilot_run from a crashed first attempt
-- (the runner wrote the run row but died before creating the downstream
@@ -336,6 +343,14 @@ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority,
VALUES ($1, $2, NULL, 'queued', $3, $4, sqlc.narg(trigger_summary))
RETURNING *;
+-- name: GetAutopilotTaskByRun :one
+-- Repairs the narrow run_only crash window where the task INSERT committed
+-- but the following autopilot_run.task_id update did not.
+SELECT * FROM agent_task_queue
+WHERE autopilot_run_id = $1
+ORDER BY created_at
+LIMIT 1;
+
-- =====================
-- Run lookup by linked entities
-- =====================
diff --git a/server/pkg/db/queries/webhook_delivery.sql b/server/pkg/db/queries/webhook_delivery.sql
index 1d96ddf3b1..1de65216a1 100644
--- a/server/pkg/db/queries/webhook_delivery.sql
+++ b/server/pkg/db/queries/webhook_delivery.sql
@@ -51,6 +51,82 @@ SET attempt_count = attempt_count + 1,
WHERE id = $1
RETURNING *;
+-- name: AcknowledgeWebhookDelivery :one
+-- Best-effort operator metadata for the HTTP acknowledgement. Admission is
+-- already durable once the initial queued row exists, so callers still return
+-- 202 if this metadata-only update fails.
+UPDATE webhook_delivery
+SET response_status = $2,
+ response_body = $3,
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: ClaimQueuedWebhookDelivery :one
+-- Claims one due delivery. SKIP LOCKED spreads work across replicas; the
+-- expiring token makes a crashed claim visible to a later sweeper pass.
+-- The lease is a scheduling optimization, not the exactly-once guard: if a
+-- slow dispatch outlives it, uq_autopilot_run_webhook_delivery remains the
+-- final protection against duplicate downstream runs.
+WITH candidate AS (
+ SELECT id
+ FROM webhook_delivery
+ WHERE status = 'queued'
+ AND available_at <= now()
+ AND (lease_expires_at IS NULL OR lease_expires_at <= now())
+ ORDER BY available_at, created_at
+ FOR UPDATE SKIP LOCKED
+ LIMIT 1
+)
+UPDATE webhook_delivery AS d
+SET lease_token = gen_random_uuid(),
+ lease_expires_at = now() + interval '2 minutes'
+FROM candidate
+WHERE d.id = candidate.id
+RETURNING d.*;
+
+-- name: DeferClaimedWebhookDelivery :one
+-- Releases a claim without counting a dispatch attempt. Used when the
+-- per-trigger worker budget is exhausted before downstream dispatch begins.
+UPDATE webhook_delivery
+SET available_at = $3,
+ lease_token = NULL,
+ lease_expires_at = NULL
+WHERE id = $1
+ AND lease_token = $2
+ AND status = 'queued'
+RETURNING *;
+
+-- name: RetryClaimedWebhookDelivery :one
+-- Records a transient worker failure and makes the delivery eligible after
+-- its bounded backoff. HTTP response fields intentionally remain the 202
+-- acknowledgement already returned to the provider.
+UPDATE webhook_delivery
+SET available_at = $3,
+ dispatch_attempts = dispatch_attempts + 1,
+ error = $4,
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ last_attempt_at = now()
+WHERE id = $1
+ AND lease_token = $2
+ AND status = 'queued'
+RETURNING *;
+
+-- name: CompleteClaimedWebhookDelivery :one
+UPDATE webhook_delivery
+SET status = $3,
+ autopilot_run_id = sqlc.narg('autopilot_run_id'),
+ dispatch_attempts = dispatch_attempts + 1,
+ error = sqlc.narg('error'),
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ last_attempt_at = now()
+WHERE id = $1
+ AND lease_token = $2
+ AND status = 'queued'
+RETURNING *;
+
-- name: UpdateWebhookDeliveryDispatched :one
-- Finalises a delivery that successfully created (or skipped to) an
-- autopilot_run. response_status is the HTTP status we returned, recorded
@@ -91,7 +167,8 @@ SELECT
d.dedupe_key, d.dedupe_source, d.signature_status, d.status,
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.received_at, d.last_attempt_at, d.created_at,
+ d.available_at, d.dispatch_attempts
FROM webhook_delivery d
JOIN autopilot a ON a.id = d.autopilot_id
WHERE d.autopilot_id = $1