fix(api): bound the Linear sweep's lock hold and its QStash publishes

Merged
SA
3mo ago
+90-5

Problem

jobs/sweep-abandoned (#7289) runs its whole body inside
singleFlight("linear.sweep-abandoned", …), and inside that transaction it
loops over up to MAX_REQUEUES (50) deliveries making one QStash publish per
row, writing the retryCount increments only after the loop. Nothing bounded
that loop in wall clock.

The failure is not the lock being held a bit long. It is what the lost commit
does to the attempt counter: deliveries that were handed to QStash go
uncounted, so every later sweep re-queues them again without ever spending one
of their five attempts. A delivery that can never be given up on is the exact
opposite of what MAX_ATTEMPTS exists for, and it also means a fresh duplicate
fan-out each run.

The route is currently inert — the QStash schedule that would call it does not
exist yet — so this is a correctness fix ahead of that schedule, not an
incident.

Root cause

Two separate missing bounds, and the second is why bounding only the loop would
not have been enough.

1. The loop has no wall-clock bound. singleFlight holds its advisory lock
inside a transaction on tx, and every publish is made off that connection, so
the connection sits idle in transaction for as long as the loop runs. Two
clocks end an overrunning run and both end it the same way — maxDuration = 60
on this route kills the invocation at sixty seconds, and Postgres closes an
idle-in-transaction connection at five minutes and takes the lock with it
mid-run (the shape #7330 documents on singleFlight itself). For this route the
sixty-second kill lands first, so the exposure is more likely than the
five-minute story, not less. Either way the write-back after the loop never
commits.

MAX_CONSECUTIVE_PUBLISH_FAILURES does not cover this. It catches publishes
that fail; a publish that merely goes slow never increments it. Slow is
the case that runs out the clock. #7289's own comment on that breaker already
names this harm ("can outrun maxDuration and kill the run before the
write-back below commits") — the breaker just only closes the fast-failure half
of it.

2. A single publish has no bound at all, so a loop bound alone would still
let one hung publish hold the lock past both clocks. Verified against the
installed client rather than the docs — @upstash/qstash@2.10.1:

  • ClientConfig has baseUrl, token, retry, headers, telemetry. No
    timeout.
  • UpstashRequest has no signal field, and HttpClient.processRequest builds
    its fetch options as { method, headers, body, keepalive } — an
    AbortSignal has nowhere to go even if one were passed.
  • publishJSON does take a timeout, which is a trap: its own doc says it is
    "the HTTP timeout value to use while calling the destination URL" — QStash's
    ceiling on calling our consumer, not a ceiling on this call.
  • retry: { retries: 1 } maps to attempts: 1 and a for (index = 0; index <= attempts) loop, so two fetch attempts — and the retry only catches a fetch
    that throws, so a hang is waited out in full and then waited out again.

So a publish is bounded only by the platform's fetch defaults. Against a server
that accepts the connection and never answers, using this file's exact client
config, one publish was still outstanding at 65s — past this route's whole
maxDuration:

[server] request 1 received; never responding
[watch] still pending at 10s (server saw 1 request(s))
[watch] still pending at 20s (server saw 1 request(s))
[watch] still pending at 30s (server saw 1 request(s))
[watch] still pending at 40s (server saw 1 request(s))
[watch] still pending at 50s (server saw 1 request(s))
[watch] still pending at 60s (server saw 1 request(s))
[result] after 65003ms the publish is still outstanding; server saw 1 request(s)

Fix

PUBLISH_BUDGET_MS = 30_000 on the sweep's loop, following #7330's shape —
measured from the top of the singleFlight callback (where the lock is taken,
so the band query counts against it), checked at the top of each iteration,
leaving the remainder to the next run. Thirty seconds plus at most one publish
timeout of overshoot ends a run by thirty-three of maxDuration's sixty, so the
write-back and the commit always get the rest.

I checked the "stopping early is safe" claim against the band arithmetic rather
than assuming it, since leaving rows unexamined is what that reasoning is about:

  • The band is [now-75min, now-60min), 15 minutes wide, against an intended
    5-minute cadence — each delivery passes under three runs.
  • The query is ORDER BY received_at ascending and planSweep preserves
    that order, so the loop publishes oldest first. Rows dropped by an early stop
    are therefore the band's youngest — the ones that entered most recently and
    still have later runs ahead of them. The stop drops the rows with the most
    chances left, which is the right direction.
  • Leaving rows is a trade the route already makes twice, via MAX_ROWS (500)
    and MAX_REQUEUES (50), and once more via the failure breaker.
  • Rows not reached are not written to at all, so the next run finds them
    unchanged. The abandoned give-up marking runs before the loop, so the
    budget never delays a give-up.

Compared with today the budget strictly reduces mis-handled rows: today a run
that overruns loses the counts for everything it published, which is worse than
not publishing those rows at all.

PUBLISH_TIMEOUT_MS = 3_000 in enqueueLinearDelivery. Yes, the publish
needs its own bound — a loop bound alone still lets one hung publish hold the
lock indefinitely, as the 65s trace above shows. Since the client accepts no
signal, the call is raced against a timer at the one place the publish is made.
Putting it there rather than in the sweep also fixes the same hole on the other
caller: the webhook route publishes against Linear's five-second clock, and a
hung publish there is a delivery Linear times out on and eventually a webhook
Linear disables. That is the lighter shape — one bound where the publish is,
not a guard per caller. Three seconds is an order of magnitude above a healthy
publish and leaves the webhook route most of Linear's five, consistent with the
existing decision in that file to cut the client's default 4.3s of backoff down
to 150ms for the same reason.

The race leaves the underlying fetch running, since nothing can cancel it, so
the abandoned promise gets a .catch() to keep a late rejection off the
unhandled-rejection path. A late success costs one duplicate, which is the
cost the deduplicationId comment right above already prices.

Verified the wrapper does the job, does not mask real errors, and does not leak
rejections:

[ok] hanging server: threw after 3006ms: QStash publish exceeded 3000ms
[ok] failing server: threw after 9ms: nope
[ok] budgeted loop: attempted 10/50, stopped at 30027ms
[ok] no unhandled rejections

deferred in the result. Planned re-queues a run never attempted, from
either exit. Without it a run that stopped early is indistinguishable from one
that found nothing more to do, and the run is logged when it is non-zero.

The retryCount ordering: kept as #7289 has it (publish, then count)

I did not reverse it. Counting before publishing would make every failed or
timed-out publish spend one of a delivery's five attempts — during a QStash
outage five sweeps would mark deliveries abandoned that were never actually
retried, which is silent webhook loss and unrecoverable. The current order's
cost is the opposite and much cheaper: a re-queue that happened but was not
committed gets re-queued again, costing a duplicate the consumer dedupes for one
query. #7289 chose correctly.

The ordering was never the bug. The unbounded hold was: it took the residual
risk in that trade — "the process dies between publish and commit" — and made it
reachable on any slow run. With the run bounded to ~33s of a 60s ceiling and
~11% of the idle-in-transaction limit, that window is back to being an
infrastructure failure rather than a routine outcome.

Deliberately not in this change

  • singleFlight.ts untouched. #7330 owns it and is still open.
  • No per-row write-back. Incrementing retryCount inside the loop would
    survive an infra kill and would keep the connection from going idle, but it
    costs a statement per row and breaks the existing grouped write-back
    (at most MAX_ATTEMPTS statements, fenced on the observed count). Not worth
    it now that the run is bounded.
  • MAX_CONSECUTIVE_PUBLISH_FAILURES kept. It is not made redundant by the
    budget: in a fast-failure outage 50 doomed publishes take well under thirty
    seconds, so the budget would never fire and the breaker is the only thing
    stopping them. The two cover disjoint cases — fast failures, slow successes —
    and the constant's doc now says which is which.
  • Not replacing the QStash SDK with raw fetch + AbortSignal.timeout.
    It would cancel the socket properly instead of abandoning it, but it means
    reimplementing auth, headers and error typing for one call. The abandoned
    fetch is harmless in a function that is about to end.
  • No new tests. planSweep holds the pure decision logic and is already
    covered; the two new bounds are wall-clock behaviour of a route with no
    harness, and the repros above cover them better than a mocked clock would.
  • The QStash schedule is still not created. Out of scope here; this is the
    correctness work that had to land before it exists.

Verification

$ bunx biome check apps/api/src/app/api/integrations/linear/
Checked 20 files in 10ms. No fixes applied.
$ cd apps/api && bun run typecheck
$ tsc --noEmit

Full apps/api package suite, not just the touched files:

$ cd apps/api && bun test src

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

No failures, so nothing needed the revert-and-rerun check. The stderr lines the
run prints ([linear/webhook] failed to queue delivery: … qstash unavailable
and friends) are the deliberate console.error output of the negative tests,
not failures. webhook/route.test.ts mocks ./queue wholesale, so it exercises
the caller contract and is unaffected by the timeout added inside it.

Refs API-18.

https://claude.ai/code/session_016ETgyauAQyxzHRSKq7ox7K


Summary by cubic

Bounds the Linear sweep's QStash publish loop at 30 seconds and each publish at 3 seconds, so a run can no longer overrun its time budget and lose the retry-count write-back. The old unbounded loop could run into the route's 60-second kill or Postgres's idle-in-transaction limit, leaving published deliveries uncounted and re-queued on every later run.

  • Adds a PUBLISH_BUDGET_MS check measured on a monotonic clock; stopped runs log a deferred count so they are distinguishable from empty runs.
  • Races enqueueLinearDelivery publishes against a timer and rejects on timeout, with a .catch() on the abandoned fetch to avoid unhandled rejections.
  • Keeps the publish-then-count ordering; counting first would spend delivery attempts on failed publishes and risk silent webhook loss.
  • The QStash schedule for this route still does not exist, so this is pre-rollout correctness work. Refs API-18.

Summary by CodeRabbit

  • Bug Fixes
    • Webhook delivery publishing now times out when the publishing service does not respond, preventing requests from waiting indefinitely.
    • Abandoned-delivery cleanup now observes a 30-second processing window and stops scheduling additional retries after the limit is reached.
    • Results and logs now clearly indicate when planned retries were deferred for later processing.