fix(api): bound the redispatch sweep's advisory-lock transaction

Merged
SA
3mo ago
+49-11

Problem

The minute-cadence automations evaluate tick ends by running the undispatched-event sweep under singleFlight, which holds a transaction-scoped advisory lock. The sweep selects up to 200 stuck rows and does a network publish per row — all on other connections (db is neon-http, the lock is on the dbWs websocket pool). So the lock connection sits idle in transaction for the entire loop.

Confirmed on the same Neon platform as production: idle_in_transaction_session_timeout = 5min (idle_session_timeout = 0, statement_timeout = 0). At five minutes Postgres terminates that backend. Two things follow, one per issue:

  • The driver receives the termination with no listener attached → fatal uncaught exception (API-2N, handled: no, onuncaughtexception).
  • Drizzle's transaction wrapper then fails its commit and fails the rollback behind it → Failed query: rollback escapes POST (API-2P).

Both fire on the same trace, same second, 7 pairs between 13:45 and 16:05 UTC on 2026-09-08.

The user-visible harm is not the Sentry entry. The sweep's own work survives — it runs on connections the kill does not touch. What dies is the guard: an advisory xact lock is released when Postgres aborts its transaction, so from the five-minute mark the sweep is running unprotected, and every subsequent minute-tick takes the now-free lock and starts another concurrent sweep over the same still-unmarked rows. That is exactly the stacking singleFlight was introduced to stop (#7114 — the doc records 24 concurrent copies of this sweep, "every one pinning a backend for minutes"). The guard fails open on precisely the slow run it exists to bound, and customers get an API whose backends are pinned by duplicate sweeps.

Root cause

automations.redispatch was the only singleFlight caller that ignored the tx it was handed and did its work on the global client instead, so nothing kept the lock transaction short. singleFlight's doc already stated the contract — "Batch work should run on the transaction handed to fn" and "each batch transaction short, which is what their batch sizes were chosen for" — but a batch size of 200 does not bound a transaction when each row costs a network round trip.

Fix

  • The batch select runs on tx, so the lock and the statement share a connection.
  • The row loop stops at TIME_BUDGET_MS = 60_000 — the same ceiling the Linear sweep publishes under (maxDuration = 60), leaving 5× headroom under the five-minute timeout.
  • The result gains more, matching the pruner's "stopped on a limit rather than running out of work".
  • SingleFlightTx is exported so the extracted callback can name the type; this removes a duplicated any triple rather than adding one.

A sweep interrupted mid-batch stays safe. Rows are marked by dispatchMatchingTriggers only once the publish lands, so anything the budget did not reach is still unmarked, still inside the lookback window, and selected again by the next tick. Partial progress is never lost and never double-counted; a row that half-published is absorbed by the existing QStash dedup on trigger+event.

Why the loop was not moved outside the lock

The obvious reading — take the lock per batch and publish outside it — would have removed single-flight rather than fixed it. The ran: false handoff works for the pruner and the retention job because all of their work is the one statement inside the lock, so a competing tick reliably finds the lock taken. Publishing outside would leave the lock held for the microseconds of a select, i.e. ~1% of the run, so every stacked tick would win it and run concurrently — reopening #7114. There is no claim column on automation_events to fence rows with instead, and claiming by marking before publishing would lose a row outright if the run died between the two (the Linear sweep documents the same publish-then-count ordering deliberately). Bounding the in-transaction time is what keeps both properties.

Still reporting

Per-row publish failures still console.error and count into failed, unchanged. A genuinely broken lock connection still throws from singleFlight. No throw site was added, removed, or reclassified — so no typed cause: nothing reads a kind here, and adding one would be code maintained for nothing.

Verification

bunx biome check on the three changed files:

Checked 3 files in 5ms. No fixes applied.

cd apps/api && bun run typecheck:

$ tsc --noEmit

(clean, no diagnostics)

cd apps/api && bun test src (full package, not just the touched directory):

 69 pass
 0 fail
 124 expect() calls
Ran 69 tests across 9 files. [62.00ms]

No desktop git code touched, so no-main-process-blocking.test.ts does not apply. No new test: the change adds no classifier or matcher, and these two files have no existing suite to extend — covering the budget would mean mocking the dispatcher and a fake transaction.

Adjacent, deliberately not fixed

  • dbWs (packages/db/src/client.ts) is a Pool with no error listener, which is why a dying connection surfaces as a fatal uncaught exception rather than a rejected promise. Any future connection death — a Neon restart, a deploy — has the same shape. Real, but a separate defect from this root cause, and not evidenced by anything beyond these two issues.
  • /api/automations/evaluate declares no maxDuration, unlike every comparable job route (dispatch 60, prune 300, Linear sweep 60).

Refs API-2N
Refs API-2P

https://claude.ai/code/session_01FFtxjCk7tRaYmjvB4svJcW


Summary by cubic

Fixes the redispatch sweep so the advisory lock singleFlight holds can't be dropped mid-run by Postgres's idle-in-transaction timeout: the sweep previously ran its 200-row select and publish loop on the global client while the lock sat idle on a separate connection, so slow runs lost the lock at five minutes and concurrent sweeps stacked. The select now runs on the lock transaction and the loop stops after 60 seconds, leaving the rest for the next tick.

Bug Fixes

  • A budget-interrupted sweep stays safe: rows are marked only once their publish lands, so unmarked rows are picked up by the next tick.
  • The result now reports more when the run stopped on the limit rather than running out of work.

Summary by CodeRabbit

  • Bug Fixes
    • Improved automation recovery processing to run safely within its transaction window.
    • Prevented long-running recovery sweeps from exceeding database connection limits.
    • Improved handling of partially completed recovery work so remaining items can be processed in subsequent runs.
    • Ensured recovery attempts are tracked accurately during each processing cycle.