Skip to content

fix(platform): trigger uniqueness, fair scan, idempotent webhooks - #3167

Merged
larryro merged 4 commits into
mainfrom
fix/automation-trigger-webhook
Sep 3, 2026
Merged

larryro merged 4 commits into
mainfrom
fix/automation-trigger-webhook

Conversation

@larryro

@larryro larryro commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Fixes the verified trigger + webhook review class in services/platform/backend/domains/automations/: triggers could duplicate and double-fire, webhook deliveries had no replay protection, and the schedule scanner starved triggers past an arbitrary cap. Base is e5748f9a9 (includes the run-lifecycle fix #3158, which this PR builds on and does not redo).

Per finding

1. Concurrent setTrigger creates duplicate rows that double-fire and cannot be disabled — fixed

  • Was live on base: setTrigger did SELECT … LIMIT 1 then INSERT/UPDATE in a transaction with no lock; 0019 had only a plain index on (org_id, name). Base probe: 10 rows after 12 concurrent binds, and after disabling through the HTTP door the scan still fired 9 runs.
  • Fix: migration 0068_automation_triggers_unique_name.sql — deterministic de-dup first (per (org_id, name) keep the last-edited row = the user's latest intent, ORDER BY updated_at_ms DESC, created_at_ms DESC, id DESC; merge the group's newest last_fired_at_ms onto it so it cannot re-fire an occurrence a phantom already fired; delete the phantoms), then CREATE UNIQUE INDEX … (org_id, name) and drop the redundant plain index. Trigger rows are configuration, not history (started_by = 'trigger:<id>' is text, nothing cascades). Rolling-deploy safe: the old image's SELECT-then-INSERT keeps working for non-racing binds; the race becomes a unique-violation on the loser instead of a silent duplicate (same rationale as 0059).
  • setTrigger is now one INSERT … ON CONFLICT (org_id, name) DO UPDATE; the webhook token keep/rotate decision is a CASE on the existing row and the plaintext is handed out only when the minted hash is the one RETURNING shows landed. There is no violation left to map to a 409: both racing writers succeed and the last commit wins, exactly as sequential saves would — a 409 would tell a user their save failed when it did not.
  • Tests: store.set-trigger.test.ts (single statement, no SELECT, token hand-out on landed hash, rotate flag, validation before SQL); integration probes concurrent trigger binds converge on one row; disabling it stops every fire and migration 0068 keeps the last-edited trigger row and restores the unique index (drops the index, plants 3 duplicates with distinct edit/fire stamps, re-applies the file, asserts the kept row, the merged stamp, the index — also proves the file is re-runnable).

2. Webhook deliveries have no replay/retry dedupe — fixed

  • Was live on base: each POST started a run; base probe: same X-GitHub-Delivery twice → two runs, same body twice → two runs (6 runs from 6 deliveries, want 4). Body cap counted UTF-16 units after buffering everything: 300 KB of two-byte characters answered 202.
  • Fix: core/automations/webhook_delivery.ts derives a delivery identity — header lane (first present of Idempotency-Key, X-Idempotency-Key, Standard Webhooks webhook-id, X-GitHub-Delivery, X-Gitlab-Event-UUID, X-Shopify-Webhook-Id, Linear-Delivery, X-Atlassian-Webhook-Identifier, X-Request-UUID, I-Twilio-Idempotency-Token, X-Webhook-Id), remembered 24 h; body lane = SHA-256 of the raw bytes, remembered 2 min (a heartbeat posting the same body every few minutes keeps working); projectId is part of both keys. Migration 0069_automation_webhook_deliveries.sql adds the ledger (PK (trigger_id, delivery_key), FK cascade from the trigger, expiry index). The door claims the identity inside the transaction that starts the run (INSERT … ON CONFLICT DO UPDATE … WHERE expired RETURNING), so a concurrent repeat waits on the row lock and answers 202 { runId, duplicate: true } with the first run; no deployed version rolls the claim back (409 as before); expired rows are swept lazily per trigger (no cron). Existing dedupe infrastructure was considered and did not fit: pg-boss singletonKey only dedupes while queued; app.rate_limits cannot carry the original run id nor roll back with a failed start.
  • Body cap: readWebhookBody reads the stream counting bytes; a declared Content-Length over the cap is refused before the first byte, a growing body where it crosses; an over-cap body is drained up to 1 MiB so the sender reads a clean 413 (Hono's bodyLimit closes the socket mid-upload and clients see a reset instead of the 413 — observed in the first branch run).
  • Tests: webhook_delivery.test.ts (header precedence/case/blank fallthrough, lane keys and windows, project in key, bounded keys, bounded reader: bytes-not-code-units, Content-Length refusal + drain, hostile body cancelled at the drain cap); integration probes webhook redelivery is idempotent; distinct deliveries each run and webhook body cap counts bytes and refuses oversize deliveries.

3. Trigger scan LIMIT 200 with no ORDER BY starves triggers forever — fixed

  • Was live on base: base probe with 205 planted enabled schedules: 191/205 stamped, examined=200. Also found while here: the stamp was an unconditional UPDATE, so overlapping scans (the job has retryLimit: 1, expireInSeconds: 120; or two workers) double-fired — base probe: 27 runs from 3 concurrent scans over one due trigger.
  • Fix: keyset walk ORDER BY id, 200 rows per page, until exhausted — every enabled schedule is examined every tick (no cap, so nothing to defer or log as deferred); triggers already stamped at or past the current minute are filtered in SQL. The due stamp is a conditional claim (… WHERE last_fired_at_ms IS NULL OR last_fired_at_ms < due RETURNING id) so exactly one scanner starts the run. Undeployed schedules are summarised in one log line per scan (not one per trigger); the job log reports pages walked.
  • Tests: triggers.scan.test.ts (paging with cursor + ORDER BY id, lost claim never reaches beginRun, one summary line, bad cron skipped); integration probes schedule scan walks every enabled trigger (no LIMIT-shaped starvation) (205/205) and overlapping schedule scans fire one occurrence exactly once.

Already fixed in base (not redone)

Docs (en/de/fr, natively authored)

  • platform/automations/triggers.md: the page said an automation "may carry several [triggers] at once" — the model is one per name (editor reads data[0], PUT replaces) and is now schema-enforced; plus the redelivery paragraph.
  • develop/webhooks.md: response vocabulary gains 202 { runId, duplicate: true }; the "Idempotency and retries" section (which promised no de-duplication) rewritten with the header list, windows, and a curl example.
  • tutorials/developer/trigger-automation-via-webhook.md: the retry paragraph.

Gates (observed)

  • Unit: bunx vitest --run --project server on the 4 trigger/webhook test files — 30/30.
  • bunx tsc --noEmit (platform) — clean. bunx oxlint --type-aware (platform) — clean. bun run --filter @tale/docs test — 194/194. oxfmt --check on touched files — clean.
  • backend:integration on a throwaway tale-db + MinIO (fresh containers per run):
    • base + new probes: 356/365 — the 9 failures are the 6 new probes (red with the numbers above) plus 3 sandbox-agent lanes that need SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD (unset in that run; unrelated to this class).
    • branch: 365/365 (same probes; SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD set to a dummy value, which clears those 3 lanes).

Cross-class notes

  • backend/README.md's integration recipe does not mention SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD; without it three sandbox-agent lanes fail.
  • The object-store boot probe is sensitive to MinIO reuse across runs (dropped=false when the bucket still holds a previous run's blobs) — harness hygiene, not a product defect.

app.automation_triggers had only a plain index on (org_id, name) and
setTrigger bound with SELECT-then-INSERT inside a transaction with no lock,
so two concurrent binds of one name (two tabs, a retried request, MCP
set_trigger racing the editor) both saw "no row" and both inserted. The
schedule scan then fired every row per occurrence, and a later edit or
disable updated only the LIMIT 1 row it read, leaving the phantom enabled
and firing behind a switch that said off.

Migration 0068 de-duplicates existing rows deterministically — per (org,
name) the last-edited row is kept, the group's newest fire stamp is merged
onto it, the phantoms are deleted — then adds UNIQUE (org_id, name) and
drops the redundant plain index. setTrigger becomes a single INSERT … ON
CONFLICT DO UPDATE: racing writers converge on one row, the token
keep/rotate decision moves into the CASE on the existing row, and the
plaintext is handed out only when the minted hash is the one that landed.
scanScheduledTriggers selected enabled schedules with LIMIT 200 and no
ORDER BY: past 200 triggers platform-wide Postgres returned an arbitrary
heap-order subset every minute and the rest never fired, silently. The
stamp was also an unconditional UPDATE, so two overlapping scans (an
expired job's retry, two workers) both fired the same occurrence.

The scan is now a keyset walk in id order, 200 rows per page, until every
enabled schedule has been examined; triggers already stamped at or past
the current minute are filtered in SQL. The due stamp is a conditional
claim (… WHERE last_fired_at_ms IS NULL OR < due RETURNING id), so exactly
one scanner starts the run. Undeployed schedules are summarised in one log
line per scan instead of one per trigger, and the job log reports the
pages walked.
The webhook door started a fresh live run per POST while vendors deliver
at least once, so a retry after a slow response or a manual redelivery
double-ran the automation. The 256 KB cap was checked on
c.req.text().length after buffering the whole body — UTF-16 code units,
not bytes — so a 300 KB body of two-byte characters passed.

Each delivery now has an identity (core/automations/webhook_delivery.ts):
the sender's delivery id when one is present (Idempotency-Key, the
Standard Webhooks webhook-id, X-GitHub-Delivery, X-Gitlab-Event-UUID,
X-Shopify-Webhook-Id, Linear-Delivery, X-Atlassian-Webhook-Identifier,
X-Request-UUID, I-Twilio-Idempotency-Token, X-Webhook-Id), remembered for
24 hours; otherwise the SHA-256 of the raw body, remembered for two
minutes. The requested project is part of the key. Migration 0069 adds
the ledger app.automation_webhook_deliveries; the door claims the identity
INSIDE the transaction that starts the run (INSERT … ON CONFLICT DO UPDATE
… WHERE expired RETURNING), so a concurrent repeat waits on the row lock
and then answers 202 { runId, duplicate: true } with the first run. A
start with no deployed version rolls the claim back (409 as before);
expired rows are swept lazily per trigger; the ledger cascades with the
trigger.

The body is read as it streams and counted in bytes: a declared
Content-Length over the cap is refused before the first byte, a body that
grows past it is refused where it crosses, and an over-cap body is drained
up to 1 MiB so the sender reads a clean 413 instead of a reset.

Docs (en/de/fr): the triggers page said an automation may carry several
triggers at once — the model is one per name, now schema-enforced — and
the developer webhooks page and tutorial promised no de-duplication; both
now describe the delivery identity, the windows, and the duplicate answer.
Real-Postgres probes for the trigger + webhook class: twelve concurrent
setTrigger calls converge on one row and a disable stops every fire;
three overlapping scans over one due trigger fire exactly one run; 205
enabled schedules are all stamped by one scan; a redelivery (same delivery
id, or same body) answers with the first run while distinct deliveries
each run; a 300 KB multibyte body is refused with 413; and migration 0068
re-applied over planted duplicates keeps the last-edited row, merges the
fire stamp, and restores the unique index.

On the unfixed base these read: 10 rows after 12 binds and 9 fires while
disabled; 27 runs from 3 scans; 191/205 stamped (examined=200); 6 runs
from 6 deliveries; 202 for the multibyte body; no 0068 file.
@larryro
larryro marked this pull request as ready for review September 3, 2026 08:11
@larryro
larryro merged commit 9d67774 into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/automation-trigger-webhook branch September 3, 2026 08:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant