Skip to content

12.35.0

Choose a tag to compare

@timgit timgit released this 26 Sep 14:25
· 321 commits to master since this release

Schema version: 43. A migration runs on upgrade; see Upgrading.

  • A worker whose claim on a job lapsed can no longer complete, fail or heartbeat the attempt that replaced it, and its handler's signal is aborted when a heartbeat finds the claim gone.
  • Queue stats now count throughput: how many jobs arrived, completed and failed between monitor passes, not just how many are sitting there.
  • redrive() no longer loses a job the destination refuses. It stays in the dead letter queue, failed, with the reason.
  • A dead-lettered job's output starts empty. The failed original's output is now sourceOutput.
  • sourceRootId links every trip through a dead letter queue back to the original job id.

Highlights

A lapsed worker can't settle the retry

When a worker's claim on a job lapses, because the job expired or missed its heartbeat and was retried, that worker is often still running its handler. Until now its complete() or fail() landed on whichever attempt held the job by then. A completion could settle a retry another worker had just started, and a failure deleted that live attempt and re-created it as a retry.

Settling is now fenced to the attempt a worker claimed, identified by the job's retryCount. work() does this for every completion, failure and heartbeat, including a transactional handler's own complete(), so workers need no change. A settle from a lapsed claim leaves the job alone.

Pass the job, not its id, when you settle by hand. complete(), fail(), touch(), cancel() and deleteJob() now accept the jobs fetch() returned, or any { id, retryCount }, in place of ids. The call then only applies to the attempt that was fetched:

const [job] = await boss.fetch('report-generation')
const report = await generateReport(job.data)
// { affected: 0 } if the job was retried elsewhere in the meantime
const { affected } = await boss.complete('report-generation', job, { reportUrl: report.url })

A plain id still applies to whatever attempt holds the job now, which is what an operator acting on a job wants.

Handlers are told when they lost the job. On a queue with heartbeatSeconds, a heartbeat that finds a job no longer active under the worker's claim aborts that job's signal. The rest of the batch keeps running. Whatever the handler returns for a job it no longer holds is discarded, so stopping early only saves the work. A job can still run twice when a worker only looked dead, during a network partition or a stalled event loop, so don't get too excited that we somehow solved the CAP theorem here.

Thanks to @DivMode for reporting #925.

Throughput in the queue stats history

The stats previously stored in the queue table are technically gauges: how many jobs are queued, active or failed right now. No arrangement of gauges answers "how many jobs did this queue get through". Five hundred arriving and five hundred leaving looks exactly like a queue where nothing happened, and a backlog that is growing because more work is arriving looks identical to one growing because less work is finishing, although the two need different mitigations.

With persistQueueStats on, every snapshot the monitor records now carries three counters (deltas), and the window they cover, alongside the gauges:

  • createdDelta: jobs created since the previous pass
  • completedDelta: jobs completed since the previous pass
  • failedDelta: jobs that failed terminally since the previous pass. A job that will be retried has not finished, so it is not counted.
  • deltaSeconds: how many seconds those three counts cover.
  • deltaOn: when that interval ends, 10 seconds before the snapshot's capturedOn; see below.
const series = await boss.getQueueStats('email-send', {
  from: new Date(Date.now() - 60 * 60 * 1000),
  maxDataPoints: 60
})

for (const { deltaOn, createdDelta, completedDelta, deltaSeconds } of series) {
  if (!deltaSeconds) continue // not counted yet, or the queue's first counted pass
  const perMinute = (n) => (n * 60) / deltaSeconds
  console.log(deltaOn, perMinute(createdDelta), perMinute(completedDelta))
}

In order to deal with the real world of transactional activity, deltas run 10 seconds behind the gauges. Rows become visible when a transaction commits, so each window ends 10 seconds before the pass that counts it. It's a bit of an implementation detail to include in release notes, but just be aware that deltaOn is for deltas and capturedOn is for gauges. Memorize that? Great.

The last hour of history is provisional. But what happens when we experience a super long transaction, you ask? A transactional worker whose handler runs longer than 10 seconds, or a send() inside a long transaction, commits a job after deltas have been written. A later pass notices the late commit and adds it to the snapshot it belongs to, as long as it commits within an hour of starting, or within the queue's deleteAfterSeconds or retentionSeconds if either is shorter. So a delta could technically be altered via a true-up pass if it's within the last hour. All of that to say, deltas are best effort, never 100% accurate, and not immutable. This was a judgment call, because super long transactions should be considered an edge case. If I'm wrong about that, hit me up with an issue and we can get Claude to somehow escape out of this painted-in corner.

I think this is probably going on too long and you're likely no longer reading about deltas, but if you are concerned about these new stats, keep deleteAfterSeconds above a few minutes if you want them to be reliable. A job that maintenance has already deleted is a job not counted. A job sent with a shorter deleteAfterSeconds or retentionSeconds of its own than its queue's can still be removed inside it.

Dead Letter enhancements

sourceOutput on dead-lettered jobs

A dead-lettered job is a new job, so its output now starts empty and belongs to its own run. The failed original's output, usually its error, is sourceOutput, beside sourceName, sourceId, sourceCreatedOn and sourceRetryCount.

sourceRootId: a job's whole history from one id

sourceId names the job that just failed, which after a redrive is the redriven copy, not the original job id. Each round trip through a dead letter queue adds a hop, and retention deletes the failed jobs in between. sourceRootId is the id of the first job in the chain. It is set on every dead-lettered job and carried onto every redriven job after it, so one id finds them all, however many trips it took. For example, this query will return the entire lineage of a failed job that was redriven, even if it has made several "road trips".

SELECT * FROM pgboss.job WHERE id = $1 OR source_root_id = $1 ORDER BY created_on

A new index, job_i12, covers that lookup. On the first failure sourceRootId equals sourceId. A job dead-lettered before the upgrade has none, and its first redrive takes sourceId as the root, which is correct for a job that has only been through once.

Redrive collisions are kept, not discarded

A redriven job is re-created on its destination, and a destination with a short, stately or exclusive policy refuses a job whose singletonKey is already there (or earlier in the same batch). Until now redrive() deleted that job from the dead letter queue anyway and did not count it, so it was simply gone.

It now stays in the dead letter queue, failed, with an output saying why:

{ reason: 'redrive_conflict', destination: 'email-send', policy: 'short', singletonKey: 'user-42',
  message: 'Not redriven: queue email-send already has a job with singletonKey user-42 under its short policy' }

See why we had to make that change for sourceOutput now? Failed jobs are never redriven, so a draining loop moves on. Retry the job once whatever it collided with has finished, and the next redrive picks it up. Otherwise the dead letter queue's deleteAfterSeconds removes it like any other failed job, so nothing piles up. There is no option to get the old behavior back, on purpose: it lost jobs without saying so, and keeping them should not be something you have to opt in to. If you want them gone sooner, delete the failed jobs.

key_strict_fifo dead letter queues. Only the oldest collision per singletonKey is failed, since the policy allows one failed job per key. The rest stay queued behind it, and a job whose key is held by an active, retrying or failed job is not a redrive candidate until that job is resolved, the same rule fetch follows.

A draining loop should not stop on 0. The return value counts jobs re-created, so a batch that collided completely returns 0 with jobs still waiting. The docs' example now loops on previewRedrive() instead.

TestClock waits for pg-boss

tick() used to fire timers and return without waiting for the I/O they started, so a test often needed a real delay after it before the poll it fired had fetched anything. tick() now waits until pg-boss has no statement in flight: before it starts, after each timer it fires, and once it reaches the target. Queries you run through boss.getDb() are counted, since that is pg-boss's own connection. Don't tick while your test holds a transaction open: a pg-boss statement waiting on its lock keeps tick() waiting too. A tick() or setTime() called while either is in progress now rejects, including a tick() during setTime(), which used to run.

Thanks to @bhamiltoncx for #924.

Fixes

  • When more than one instance supervised the same schema, the monitor claim, the maintenance claim and the queue stats refresh could lock queue rows in opposite orders and deadlock. Each deadlock waited out deadlock_timeout and was emitted as a 40P01 error, and under load they did not stop. All three now lock their rows in name order, and on PostgreSQL the claims skip rows another instance holds (unless noSkipLocked is set). Thanks to @DaveTheWebDev for reporting #926 and fixing it.
  • When a cron or supervise pass ran longer than its interval, the attempt that fired during it, which skips, cleared the flag marking the pass in flight. The attempt after that started a second pass alongside the first, and stop() could return while the first was still running. The new isTimekeeping() reports a cron pass in flight, as isMaintaining() does for maintenance. Thanks to @toruiwasa for finding and fixing it in #932.
  • A supervise() call could run alongside the background supervisor's pass, and stop() did not wait for it. resolveFlow() already waited its turn, but with supervise: false stop() did not wait for it either. Both now run one pass at a time with the background pass, stop() waits for a call in flight, and isMaintaining() is true while a supervise() call runs, as the docs said. After stop() they resolve without running. With supervise: false they used to run a pass against the closed pool and fail.
  • Some CockroachDB fixes, for all you cockroaches out there: fail() given a batch that included an already completed or cancelled job no longer deletes that job. getQueueStats() with bucketSeconds or maxDataPoints no longer throws. getQueue() and getQueues() now return readyCount and failedCount as numbers.

Upgrading

Schema 43 adds five columns to queue and to queue_stats: the three counters, delta_seconds (int) and delta_on, plus two nullable columns on job: source_output jsonb and source_root_id uuid. On queue, the three counters are NOT NULL DEFAULT 0, and delta_seconds and delta_on, the counting window, are nullable. On queue_stats, all five are nullable with no default, so the snapshots already recorded read as "not counted" rather than as an idle queue. None of them rewrites a table on PostgreSQL, which matters on queue_stats: it is partitioned and large on exactly the installations that keep history.

Job now declares retryCount. It moved from JobWithMetadata onto Job, since it identifies the attempt a worker holds. Code that builds Job objects by hand, such as test fixtures, needs to add it.

If you read job.output on a dead-lettered job to get the original error, you will now need to use sourceOutput. Jobs already in a dead letter queue before the upgrade keep the output they were copied with; if one of them collides on redrive, that output is moved to sourceOutput before the reason is written.

PRs

  • allow signals to abort based on fencing by @timgit in #928
  • fix: lock queue rows in name order in the supervisor claims and cacheQueueStats by @DaveTheWebDev in #931
  • Queue throughput metrics by @timgit in #929
  • fix: generalize pg-boss settling in TestClock tick() and setTime() by @bhamiltoncx in #924
  • fix: a skipped attempt clears the in-flight flag stop() waits on by @toruiwasa in #932

New Contributors

Full Changelog: 12.34.0...12.35.0