Repository navigation
fix(platform): trigger uniqueness, fair scan, idempotent webhooks - #3167
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 ise5748f9a9(includes the run-lifecycle fix #3158, which this PR builds on and does not redo).Per finding
1. Concurrent
setTriggercreates duplicate rows that double-fire and cannot be disabled — fixedsetTriggerdidSELECT … LIMIT 1then 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.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 newestlast_fired_at_msonto it so it cannot re-fire an occurrence a phantom already fired; delete the phantoms), thenCREATE 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).setTriggeris now oneINSERT … ON CONFLICT (org_id, name) DO UPDATE; the webhook token keep/rotate decision is aCASEon the existing row and the plaintext is handed out only when the minted hash is the oneRETURNINGshows 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.store.set-trigger.test.ts(single statement, no SELECT, token hand-out on landed hash, rotate flag, validation before SQL); integration probesconcurrent trigger binds converge on one row; disabling it stops every fireandmigration 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
X-GitHub-Deliverytwice → 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.core/automations/webhook_delivery.tsderives a delivery identity — header lane (first present ofIdempotency-Key,X-Idempotency-Key, Standard Webhookswebhook-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);projectIdis part of both keys. Migration0069_automation_webhook_deliveries.sqladds 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 answers202 { 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-bosssingletonKeyonly dedupes while queued;app.rate_limitscannot carry the original run id nor roll back with a failed start.readWebhookBodyreads the stream counting bytes; a declaredContent-Lengthover 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'sbodyLimitcloses the socket mid-upload and clients see a reset instead of the 413 — observed in the first branch run).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 probeswebhook redelivery is idempotent; distinct deliveries each runandwebhook body cap counts bytes and refuses oversize deliveries.3. Trigger scan
LIMIT 200with noORDER BYstarves triggers forever — fixedretryLimit: 1, expireInSeconds: 120; or two workers) double-fired — base probe: 27 runs from 3 concurrent scans over one due trigger.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.triggers.scan.test.ts(paging with cursor +ORDER BY id, lost claim never reachesbeginRun, one summary line, bad cron skipped); integration probesschedule scan walks every enabled trigger (no LIMIT-shaped starvation)(205/205) andoverlapping schedule scans fire one occurrence exactly once.Already fixed in base (not redone)
assertTriggerValid(store.ts) withstore.trigger-validation.test.tsand the lifecycle probe; the disable/re-enable paths here go through that same door.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 readsdata[0], PUT replaces) and is now schema-enforced; plus the redelivery paragraph.develop/webhooks.md: response vocabulary gains202 { 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)
bunx vitest --run --project serveron 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 --checkon touched files — clean.backend:integrationon a throwaway tale-db + MinIO (fresh containers per run):SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD(unset in that run; unrelated to this class).SANDBOX_LLM_GATEWAY_ADMIN_PASSWORDset to a dummy value, which clears those 3 lanes).Cross-class notes
backend/README.md's integration recipe does not mentionSANDBOX_LLM_GATEWAY_ADMIN_PASSWORD; without it three sandbox-agent lanes fail.dropped=falsewhen the bucket still holds a previous run's blobs) — harness hygiene, not a product defect.