From 616f5d5e4a215f62e77c60845b5b6453dfa76333 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 10:16:46 -0300 Subject: [PATCH 01/20] perf(claim): lock only claimed jobs and serialize claims with a claim lock - Claim query selects first and locks last: per eligible group its oldest free-slot jobs (no locks), then LIMIT batch FOR UPDATE SKIP LOCKED in global creation order. Full groups never block younger jobs of other groups. Group limits via hash aggregation instead of a table sort. 50k backlog: 140-173 ms / 2.8 MB WAL per claim -> 17-57 ms / 12-19 KB. - New empty claim_lock table (migration). Each claim takes LOCK TABLE claim_lock IN EXCLUSIVE MODE before its statement (no snapshot), so built-in claims run one at a time and do not abort each other with 40001. lock_timeout 1 s; 55P03 is an empty claim (debug log, no retry, no cooldown). SERIALIZABLE + 40001 retries stay as safety net. - Worker discovery no longer follows up a short claim that returned jobs (redundant with settlement wakes); empty-claim follow-ups stay. - Docs: claim admission, discovery, claim_lock migration note. --- packages/docs/content/docs/adapters.mdx | 39 ++- packages/docs/content/docs/client-api.mdx | 4 +- packages/docs/content/docs/multi-worker.mdx | 12 +- .../migration.sql | 3 + .../snapshot.json | 32 ++ packages/duron/src/adapters/postgres/base.ts | 179 ++++++---- .../src/adapters/postgres/schema.default.ts | 2 + .../duron/src/adapters/postgres/schema.ts | 10 + packages/duron/src/worker-discovery.ts | 71 ++-- packages/duron/test/claim-isolation.test.ts | 326 +++++++++++++----- .../duron/test/claim-lock-migration.test.ts | 111 ++++++ packages/duron/test/claim-selection.test.ts | 20 ++ .../duron/test/discovery-throughput.test.ts | 22 +- 13 files changed, 627 insertions(+), 204 deletions(-) create mode 100644 packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/migration.sql create mode 100644 packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/snapshot.json create mode 100644 packages/duron/test/claim-lock-migration.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index fadc607..2b0ecb3 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -157,6 +157,10 @@ Stores step information. - `finished_at` - Timestamp (nullable) - `updated_at` - Timestamp +### `claim_lock` Table + +An empty table without columns. Each claim transaction locks it (`LOCK TABLE ... IN EXCLUSIVE MODE`) so that the claims of all workers on the schema run one at a time; it never holds rows. See [Claim Admission and Group Capacity](/docs/multi-worker#claim-admission-and-group-capacity). + ### Migrations Duron automatically runs migrations on startup if `migrateOnStart` is enabled. Migrations are located in the `migrations/postgres` directory. @@ -225,6 +229,19 @@ migration contains plain `CREATE INDEX` statements in your schema: the same lock you can pre-build the indexes the same way in your schema and add `IF NOT EXISTS` to your migration. +#### Upgrading to the claim lock + +The migration `20261202120334_silent_thunderbolt` creates the empty `claim_lock` table. It +touches no existing table and takes no lock on the job tables, so it applies at once on any +table size and needs no preparation or maintenance window (no concurrent pre-build). Upgraded +instances lock this table in every claim; instances of the previous version do not, so during +a rolling upgrade their claims are protected only by `SERIALIZABLE` (claims of both versions can +abort each other with `40001` and are retried) until every instance is upgraded. + +If you manage Duron's tables with your own Drizzle migrations, export `claimLockTable` from +`createSchema()` too (see below) and generate a migration: the adapter locks the +`claim_lock` table of its schema in every claim, so claims fail until that table exists. + ## Integrating Duron Schema into Your Own Drizzle Schema If you're already using Drizzle ORM in your project and want to manage all migrations together, you can include Duron's schema in your own Drizzle schema instead of using Duron's automatic migrations. @@ -237,10 +254,24 @@ In your Drizzle schema file (e.g., `schema.ts`), import `createSchema` from Duro import createSchema from 'duron/adapters/postgres/schema' // Create Duron's schema with your desired schema name -const { jobsTable, jobStepsTable } = createSchema('public') - -// Export the tables so they can be used by Drizzle Kit -export { jobsTable, jobStepsTable } +const { + jobsActiveTable, + jobsArchiveTable, + jobStepsActiveTable, + jobStepsArchiveTable, + clientsTable, + claimLockTable, +} = createSchema('public') + +// Export all of them so Drizzle Kit creates every table the adapter uses +export { + jobsActiveTable, + jobsArchiveTable, + jobStepsActiveTable, + jobStepsArchiveTable, + clientsTable, + claimLockTable, +} // Also export your other tables export const users = pgTable('users', { diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index c7317d4..7f527a3 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -115,7 +115,7 @@ const client = new Client({ database, waitReadTimeout: 3000 }) For both schedules, a positive finite interval is floored and clamped to `1–2,147,483,647`; other accepted values use `5000`. `getConfig()` still returns the value you passed. -Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure from a concurrent claim that persisted through the claim's 5 retries; see [Claim Admission and Group Capacity](/docs/multi-worker#claim-admission-and-group-capacity)), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. +Periodic discovery is not reset or postponed by notifications or `fetch()` calls. Missed ticks are not replayed: while a discovery is running, further demand is merged into one pending request. After any discovery failure (for example, a `40001` serialization failure that persisted through the claim's 5 retries, from a concurrent claim of an older Duron version or a concurrent cancel; see [Claim Admission and Group Capacity](/docs/multi-worker#claim-admission-and-group-capacity)), every trigger waits one interval before the next claim, including notifications and queued `fetch()` calls. The failed claim is not replayed; the next claim is a new one. ```ts { @@ -127,7 +127,7 @@ Periodic discovery is not reset or postponed by notifications or `fetch()` calls **Optional.** Defaults to `10`. Two meanings: -- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. A claim that returned fewer jobs than it asked for, while notifications are still uncovered, is followed up once after a random 10–50 ms delay: with several workers, the other rows are usually held by another worker's claim, which locks every eligible row it sees (`SKIP LOCKED`) until it commits, so a concurrent claim can even return nothing. After a claim that returned nothing, this happens only for more than one uncovered notification and at most twice in a row (the second time after 50–250 ms): a third empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. A new notification or a claim that returns jobs allows them again. While this Client's last automatic claim left jobs uncovered (for example because their SQL group was full), every job that settles on this Client starts an open-ended automatic request, because its settlement can free a group slot; a job from a claim that did not cover its own request does so too. A backlog limited by a group that this Client's jobs fill therefore drains about as fast as those jobs finish, not at the group limit per `pullInterval`. A slot that another worker frees is found by that worker's own claims or by the next periodic check. A claim that covers its request, or an open-ended claim that finds nothing, ends this, so sparse traffic costs at most one extra claim, after a notification another worker won. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. +- **Automatic claim ceiling (B).** Automatic discovery claims at most B jobs per request, and only while this Client has fewer than B claimed jobs outstanding. A job counts from its claim until it has actually settled: queued locally, running, writing its result, and also while a timed-out or cancelled handler is still running. Notifications add up: the first one starts an automatic request for one job, and each later notification adds one job to it while it waits (behind a running discovery, for a cooldown, or for room). Startup and periodic checks make the request open-ended. Each claim takes at most B jobs and at most the remaining room. When a claim returns as many jobs as it asked for but did not cover the whole request (more notifications than one claim could take, or an open-ended request), another automatic request for the rest follows at once, so a backlog or a burst of jobs keeps draining without waiting for the next periodic check. That follow-up waits for room and for a cooldown like any automatic request, and a due recovery runs before it claims. A claim that covered all of its notifications, such as one job for one notification, is not followed up. Claims of all workers run one at a time (see [Claim Admission](/docs/multi-worker#claim-admission-and-group-capacity)), so a claim that returned fewer jobs than it asked for found no more claimable jobs at that moment; it is not followed up. A claim that returned nothing (for example after waiting 1 second for the claim lock) while more than one notification is still uncovered is followed up after a random 10–50 ms delay, at most twice in a row (the second time after 50–250 ms): a third empty claim in a row ends these follow-ups, so an empty queue is not polled, and a lone notification whose job another worker claimed is not retried. A new notification or a claim that returns jobs allows them again. While this Client's last automatic claim left jobs uncovered (for example because their SQL group was full), every job that settles on this Client starts an open-ended automatic request, because its settlement can free a group slot; a job from a claim that did not cover its own request does so too. A backlog limited by a group that this Client's jobs fill therefore drains about as fast as those jobs finish, not at the group limit per `pullInterval`. A slot that another worker frees is found by that worker's own claims or by the next periodic check. A claim that covers its request, or an open-ended claim that finds nothing, ends this, so sparse traffic costs at most one extra claim, after a notification another worker won. For this ceiling, a positive finite value is floored and clamped to `1–Number.MAX_SAFE_INTEGER`; other accepted values use `10`. - **Default `fetch()` batch.** `fetch()` without `batchSize` passes this value unchanged. B is not the number of handlers that run at once. That is `actionConcurrencyLimit` per action, so with the defaults (B = 10, `actionConcurrencyLimit` = 100) at most ten automatically claimed jobs are outstanding. SQL group admission (`groupConcurrencyLimit` or `groups.concurrency`) is a separate limit across all workers. Jobs claimed by `fetch()` count toward B, and a `fetch()` batch can exceed B; automatic claiming then pauses until enough work settles. B limits claim admission only. It does not bound the rows that recovery examines, the backlog that manual calls create, or the total query rate. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 3337405..c98c36b 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -224,16 +224,18 @@ process.on('SIGINT', async () => { ## Claim Admission and Group Capacity -The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The claim query itself is unchanged: the latest unexpired job for each action name and group key supplies the concurrency limit, candidates are row-locked with `SKIP LOCKED`, and the oldest eligible jobs are claimed first. Claimed jobs are returned, and their handlers can start, only after the transaction commits. +The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The latest unexpired job for each action name and group key supplies the concurrency limit. The claim first selects, without row locks, the oldest created jobs of each group that fit in its free slots (its limit minus its active jobs), so the older jobs of a full group never keep younger jobs of other groups from being claimed. It then row-locks those candidates, oldest first, with `SKIP LOCKED` until the batch is full. A claim therefore locks only the jobs it claims, not the whole backlog. A candidate that another transaction holds (for example a concurrent cancel) is skipped and still uses its group's slot in that claim. Claimed jobs are returned, and their handlers can start, only after the transaction commits. -When concurrent claims from different workers would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible, for example when every worker claims at the same time after a notification. +Before its claim statement, each claim transaction locks the schema's `claim_lock` table, an empty table that only serves this purpose (`LOCK TABLE ... IN EXCLUSIVE MODE`). The claims of all workers on a schema therefore run one at a time, in the order they asked for the lock. A claim holds the lock for a few milliseconds (about 60 ms with a backlog of 50,000 jobs). Taking the lock does not start the transaction's snapshot, so each claim sees the jobs that the previous claims took: concurrent workers do not claim the same jobs, do not claim more than a group's limit, and do not abort each other's claims. A claim waits at most 1 second for the lock (`SET LOCAL lock_timeout`; the timeout also bounds any other lock wait of the claim transaction). This leaves room for more than 15 claims queued ahead of it even with a large backlog, while a claim whose connection stops responding with the lock held delays other claims by at most 1 second each and stays well within the shutdown budgets. When the wait times out (SQLSTATE `55P03`), the transaction rolls back and the fetch returns no jobs. This is logged at debug level, is not retried, and is not a failure: automatic discovery treats it as an empty claim, without a cooldown. + +The `SERIALIZABLE` isolation remains a safety net for claims that do not take the claim lock, such as a worker running an older Duron version. When such a claim and a built-in claim would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible. The fetch retries a claim rejected with `40001` up to 5 times. Each retry is a new transaction, so it sees the claims that committed in the meantime. It starts after a random delay that grows with each retry (exponential backoff with full jitter): up to 10, 20, 40, 80 and then 160 ms, so the waits add at most 310 ms to a claim, plus the time of the retried transactions themselves. Retried conflicts are logged at debug level. Only when the last retry also fails does the fetch reject with the original error: a manual `client.fetch()` or `adapter.fetch()` call rejects, and automatic discovery logs the failure once, waits one `pullInterval`, and then makes a new claim; notifications and queued `client.fetch()` calls also wait for that cooldown. Once `stop()` has begun, no new retry starts and a pending wait ends at once: the claim rejects with its conflict, and that shutdown failure is logged at debug level instead of error. Other claim errors are not retried. Handle the rejection of a `fetch()` you start without awaiting. Limits of this protection: -- Only built-in claims participate. A worker running an older Duron version, a custom `_fetch` override or direct SQL that claims under `READ COMMITTED` can still exceed a limit when it runs concurrently. -- SQL `now()` in a claim is the claim transaction's start time, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. +- Only built-in claims participate. A worker running an older Duron version (which does not take the claim lock), a custom `_fetch` override or direct SQL that claims under `READ COMMITTED` can still exceed a limit when it runs concurrently. During a rolling upgrade, claims of older workers can also conflict (`40001`) with claims of upgraded workers, as before. +- SQL `now()` in a claim is the claim transaction's start time, before any wait for the claim lock, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. - The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior. - If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. - Driver version: Duron is tested with postgres.js 4.2.0 and supports 4.1.1 or later. Two driver failures reproduced with postgres.js 3.4.9 do not occur with 4.1.1 for the reproduced triggers; those reproductions were not repeated on 4.2.0, where the native test suite passes. Applications that pin postgres.js 3.x keep both: @@ -250,7 +252,7 @@ Each Client with actions coordinates its own job discovery: - **One discovery at a time.** The startup pass, periodic checks, notifications and `client.fetch()` calls share one queue and are served one at a time in arrival order. Notifications and periodic checks that arrive while a discovery is running are merged into one pending request. - **Safety in every mode.** With `syncPattern` `'push'`, `'hybrid'` or `'pull'`, the Client discovers work immediately after startup and then every `pullInterval`. Notifications only make discovery faster. Work whose notification was lost, work requeued by recovery, and work that becomes claimable after a job expires or after another worker frees a group slot is found by the next periodic check. -- **Bursts and group-limited backlogs.** A claim that returns fewer than the notified jobs, typically because another worker's claim holds the other rows until it commits, is followed up after a random 10–50 ms delay; empty claims are followed up at most twice in a row. While this Client's claims leave jobs uncovered (for example because their group is full), each of its jobs that settles makes it look for work again, so a backlog limited by a group that this Client's jobs fill drains about as fast as they finish instead of at the group limit per `pullInterval`. A group slot freed by another worker is found by that worker or by the next periodic check. See [`batchSize`](/docs/client-api#batchsize). +- **Bursts and group-limited backlogs.** Claims of all workers run one at a time, and the workers that took the rest of a burst received the same notifications, so a claim that returns some but fewer than the notified jobs is not followed up. An empty claim (for example after a claim lock timeout) while more than one notification is uncovered is followed up after a random 10–50 ms delay, at most twice in a row. While this Client's claims leave jobs uncovered (for example because their group is full), each of its jobs that settles makes it look for work again, so a backlog limited by a group that this Client's jobs fill drains about as fast as they finish instead of at the group limit per `pullInterval`. A group slot freed by another worker is found by that worker or by the next periodic check. See [`batchSize`](/docs/client-api#batchsize). - **Automatic claim ceiling.** Automatic claims stop while this Client has `batchSize` claimed jobs outstanding (claimed, queued, running or finishing). See [`batchSize`](/docs/client-api#batchsize) for how this differs from `actionConcurrencyLimit` and SQL group limits. - **Recovery does not pause claiming.** When periodic recovery is due, it runs in the next discovery turn, also while this Client's jobs are running or the automatic claim ceiling is full, and that turn then claims as usual. Recovery and a claim never run at the same time in one Client. Periodic recovery rescues other workers' abandoned jobs and never touches this Client's own running jobs (see [Job Recovery](#job-recovery)). - **Failures.** After a failed discovery or recovery attempt, all discovery waits one `pullInterval`. Failed claims are never replayed. diff --git a/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/migration.sql b/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/migration.sql new file mode 100644 index 0000000..47b408a --- /dev/null +++ b/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/migration.sql @@ -0,0 +1,3 @@ +CREATE TABLE "duron"."claim_lock" ( + +); diff --git a/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/snapshot.json b/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/snapshot.json new file mode 100644 index 0000000..07ecb6d --- /dev/null +++ b/packages/duron/migrations/postgres/20261202120334_silent_thunderbolt/snapshot.json @@ -0,0 +1,32 @@ +{ + "type": "diff", + "version": "10", + "dialect": "postgres", + "id": "3de32736-2926-4cd9-9a27-99ddbaac5da3", + "prevIds": ["c4593ee7-008a-498f-9118-be27682c978e"], + "footprints": [ + { + "statementType": "create_table", + "statementTarget": ["table", "duron", "claim_lock"], + "writes": [ + "s|tbl|duron.claim_lock", + "n|tbl|duron.claim_lock", + "e|tbl|duron.claim_lock", + "n|rel|duron.claim_lock", + "n|type|duron.claim_lock" + ], + "reads": ["n|sch|duron"] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "duron", + "name": "claim_lock", + "isRlsEnabled": false, + "entityType": "tables" + } + } + ] +} diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index c5e319a..a6273cf 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -85,6 +85,14 @@ function jsonParam(value: unknown, column: PgColumn): SQL { : sql`${sql.param(value, column)}::jsonb` } +/** + * How long a claim waits for the claim lock (SQLSTATE 55P03 after it). A claim holds the lock + * for one claim statement and its COMMIT: a few ms, about 60 ms at a 50,000-job backlog. So + * 1 s covers a queue of more than 15 such claims ahead of it, while a holder that does not + * finish (a stuck connection) costs a claim at most 1 s, well within the 5 s stop budgets. + */ +const CLAIM_LOCK_TIMEOUT = '1s' + /** Retries of a claim after a serialization failure (SQLSTATE 40001). */ const CLAIM_CONFLICT_RETRIES = 5 /** Backoff before retry n (1-based): a random 1..min(cap, base * 2^n) ms ("full jitter"). */ @@ -98,11 +106,16 @@ function claimRetryDelay(retry: number): number { /** `error` or its first cause with SQLSTATE 40001 (serialization_failure), if any. */ function serializationFailure(error: unknown): Error | undefined { + return sqlStateError(error, '40001') +} + +/** The driver error with `code` in a (possibly wrapped) error chain. */ +function sqlStateError(error: unknown, code: string): Error | undefined { const seen = new Set() let cause = error while (cause instanceof Error && !seen.has(cause)) { seen.add(cause) - if ('code' in cause && cause.code === '40001') return cause + if ('code' in cause && cause.code === code) return cause cause = cause.cause } return undefined @@ -1379,10 +1392,20 @@ export abstract class PostgresBaseAdapter< * Internal method to fetch jobs from the database respecting concurrency limits per group. * Uses the concurrency limit from the latest job created for each action name and group key. * - * Each claim runs the unchanged row-locking claim query in its own SERIALIZABLE + * Each claim runs the row-locking claim query (see `_claimQuery`) in its own SERIALIZABLE * transaction, so concurrent claimants cannot both commit admissions from a stale * group count. Claimed jobs are returned only after COMMIT succeeds. SQL `now()` is - * the transaction's BEGIN time. + * the transaction's BEGIN time (before any wait for the claim lock). + * + * Before its claim statement, the transaction locks the schema's empty `claim_lock` table + * (EXCLUSIVE mode), so the claims of all workers on this schema run one at a time. + * LOCK TABLE takes no snapshot: the claim statement's snapshot starts after the previous + * claim committed and sees its jobs, so built-in claims do not conflict with each other + * (concurrent claims used to abort each other with 40001). A claim waits at most + * {@link CLAIM_LOCK_TIMEOUT} for any lock in its transaction (`SET LOCAL lock_timeout`); + * after it (SQLSTATE 55P03, for example while another claim's connection is stuck) the + * transaction rolls back and the fetch returns no jobs, logged at debug level, without a + * retry: an ordinary empty claim for the caller, not a failure. * * A serialization failure (SQLSTATE 40001, from the claim statement or COMMIT) always * rolls the whole transaction back, so the claim is retried up to @@ -1402,6 +1425,14 @@ export abstract class PostgresBaseAdapter< try { return await this._claim(batch) } catch (error) { + const lockTimeout = sqlStateError(error, '55P03') + if (lockTimeout) { + this.logger?.debug( + { err: lockTimeout, timeout: CLAIM_LOCK_TIMEOUT }, + 'Claim lock not available (SQLSTATE 55P03): no jobs claimed', + ) + return [] + } const conflict = serializationFailure(error) const lifecycle = lifecycleFor(this) if (attempt > CLAIM_CONFLICT_RETRIES || !conflict || !lifecycle.accepting) throw error @@ -1434,13 +1465,19 @@ export abstract class PostgresBaseAdapter< }) } - /** One claim attempt in its own SERIALIZABLE transaction. */ + /** One claim attempt in its own SERIALIZABLE transaction, after the claim lock. */ private async _claim(batch: number): Promise { let claim: Promise | undefined try { return await this.db.transaction( (tx) => { - claim = tx.execute(this._claimQuery(batch)).then((rows) => this._map(rows)) + // Neither statement takes a snapshot: the claim statement's snapshot begins after + // the lock is granted. + claim = tx + .execute(sql.raw(`SET LOCAL lock_timeout = '${CLAIM_LOCK_TIMEOUT}'`)) + .then(() => tx.execute(sql`LOCK TABLE ${this.tables.claimLockTable} IN EXCLUSIVE MODE`)) + .then(() => tx.execute(this._claimQuery(batch))) + .then((rows) => this._map(rows)) return claim }, { isolationLevel: 'serializable' }, @@ -1453,80 +1490,86 @@ export abstract class PostgresBaseAdapter< } /** - * The claim statement. Note: `candidate_jobs` locks every eligible created row (FOR UPDATE - * SKIP LOCKED without a LIMIT; `ranked_jobs` needs the whole set), and the LIMIT applies only - * in `next_job`. So one claim, even of one job, locks the whole eligible backlog until it - * commits: concurrent claims of other workers return few or no jobs meanwhile (worker - * discovery follows such claims up), and each claim writes a row lock on every eligible - * row. Locking only the rows a claim can take, without head-of-line blocking by full - * groups, is a possible follow-up. + * The claim statement. It selects first and locks last, so a claim locks only the jobs it + * takes, not the eligible backlog: + * + * - `group_stats` and `group_concurrency` find, for each action name and group key, the + * active count and the concurrency limit of the latest unexpired job (ties: the highest + * id), with a hash aggregation instead of a sort of the whole table. + * - `candidate_jobs` reads, without locks, each group below its limit and keeps its oldest + * `limit - active` created jobs (its free slots). A full group, or the jobs of a group + * beyond its free slots, therefore never take batch room from a younger job of another + * group (no head-of-line blocking). + * - `next_job` locks those candidates in global creation order with FOR UPDATE SKIP + * LOCKED and stops at `batch` locked rows (PostgreSQL applies the LIMIT after the row + * locks). A candidate that another transaction holds (built-in claims run one at a + * time, see `_fetch`, so for example a cancel, a time travel or a claimant without the + * claim lock) is skipped and the next candidate is tried. A skipped candidate still uses + * its group slot: no job beyond the group's free slots replaces it in this claim. + * + * The reads still scan the active table; the row locks (and their WAL) are proportional to + * the batch. Group limits rely on the claim lock and the SERIALIZABLE transaction (see + * `_fetch`). */ private _claimQuery(batch: number): SQL { return sql` - WITH group_concurrency AS ( - -- Get the concurrency limit from the latest job for each group - SELECT DISTINCT ON (j.group_key, j.action_name) - j.group_key as group_key, - j.action_name as action_name, - j.concurrency_limit as concurrency_limit + WITH group_stats AS ( + -- One pass over the unexpired jobs of each group: its active count and the + -- creation time of its latest job (hash aggregation, no sort of the table) + SELECT + j.group_key, + j.action_name, + max(j.created_at) as latest_created_at, + COUNT(*) FILTER (WHERE j.status = ${JOB_STATUS_ACTIVE}) as active_count FROM ${this.tables.jobsActiveTable} j - WHERE j.group_key IS NOT NULL + WHERE j.expires_at IS NULL OR j.expires_at > now() + GROUP BY j.group_key, j.action_name + ), + group_concurrency AS ( + -- The concurrency limit of the latest unexpired job of each group (ties: highest id) + SELECT DISTINCT ON (gs.group_key, gs.action_name) + gs.group_key, + gs.action_name, + j.concurrency_limit, + gs.active_count + FROM group_stats gs + INNER JOIN ${this.tables.jobsActiveTable} j + ON j.group_key = gs.group_key + AND j.action_name = gs.action_name + AND j.created_at = gs.latest_created_at AND (j.expires_at IS NULL OR j.expires_at > now()) - ORDER BY j.group_key, j.action_name, j.created_at DESC, j.id DESC + ORDER BY gs.group_key, gs.action_name, j.id DESC ), eligible_groups AS ( - -- Find all groups with their active counts that are below their concurrency limit - SELECT - gc.group_key, - gc.action_name, - gc.concurrency_limit, - COUNT(*) FILTER (WHERE j.status = ${JOB_STATUS_ACTIVE}) as active_count + -- The groups below their concurrency limit + SELECT gc.group_key, gc.action_name, gc.concurrency_limit, gc.active_count FROM group_concurrency gc - LEFT JOIN ${this.tables.jobsActiveTable} j - ON j.group_key = gc.group_key - AND j.action_name = gc.action_name - AND (j.expires_at IS NULL OR j.expires_at > now()) - GROUP BY gc.group_key, gc.action_name, gc.concurrency_limit - HAVING COUNT(*) FILTER (WHERE j.status = ${JOB_STATUS_ACTIVE}) < gc.concurrency_limit + WHERE gc.active_count < gc.concurrency_limit ), candidate_jobs AS ( - -- Lock candidate jobs first (before applying window functions) - SELECT - j.id, - j.action_name, - j.group_key as job_group_key, - j.created_at - FROM ${this.tables.jobsActiveTable} j - INNER JOIN eligible_groups eg - ON j.group_key = eg.group_key - AND j.action_name = eg.action_name - WHERE j.status = ${JOB_STATUS_CREATED} - FOR UPDATE OF j SKIP LOCKED - ), - ranked_jobs AS ( - -- Rank jobs within each group after locking - SELECT - cj.id, - cj.action_name, - cj.job_group_key, - cj.created_at, - ROW_NUMBER() OVER ( - PARTITION BY cj.job_group_key, cj.action_name - ORDER BY cj.created_at ASC, cj.id ASC - ) as job_rank - FROM candidate_jobs cj + -- The oldest created jobs of each eligible group that fit in its free slots + SELECT c.id, c.created_at + FROM eligible_groups eg + CROSS JOIN LATERAL ( + SELECT j.id, j.created_at + FROM ${this.tables.jobsActiveTable} j + WHERE j.group_key = eg.group_key + AND j.action_name = eg.action_name + AND j.status = ${JOB_STATUS_CREATED} + ORDER BY j.created_at ASC, j.id ASC + LIMIT eg.concurrency_limit - eg.active_count + ) c ), next_job AS ( - -- Select only jobs that fit within the concurrency limit per group - -- Ordered globally by created_at to respect job creation order - SELECT rj.id, rj.action_name, rj.job_group_key - FROM ranked_jobs rj - INNER JOIN eligible_groups eg - ON rj.job_group_key = eg.group_key - AND rj.action_name = eg.action_name - WHERE rj.job_rank <= (eg.concurrency_limit - eg.active_count) - ORDER BY rj.created_at ASC, rj.id ASC + -- Lock candidates in global creation order, skipping rows other transactions + -- hold, until the batch is full: only the claimed rows are locked + SELECT j.id + FROM ${this.tables.jobsActiveTable} j + INNER JOIN candidate_jobs cj ON cj.id = j.id + WHERE j.status = ${JOB_STATUS_CREATED} + ORDER BY cj.created_at ASC, cj.id ASC LIMIT ${batch} + FOR UPDATE OF j SKIP LOCKED ) UPDATE ${this.tables.jobsActiveTable} j SET status = ${JOB_STATUS_ACTIVE}, @@ -1535,11 +1578,7 @@ export abstract class PostgresBaseAdapter< client_id = ${this.id}, updated_at = now() FROM next_job nj - INNER JOIN eligible_groups eg - ON nj.job_group_key = eg.group_key - AND nj.action_name = eg.action_name WHERE j.id = nj.id - AND eg.active_count < eg.concurrency_limit RETURNING j.id, j.action_name as "actionName", diff --git a/packages/duron/src/adapters/postgres/schema.default.ts b/packages/duron/src/adapters/postgres/schema.default.ts index 5e2e5b0..76ba591 100644 --- a/packages/duron/src/adapters/postgres/schema.default.ts +++ b/packages/duron/src/adapters/postgres/schema.default.ts @@ -7,6 +7,7 @@ const { jobStepsActiveTable, jobStepsArchiveTable, clientsTable, + claimLockTable, } = createSchema('duron') export { @@ -16,4 +17,5 @@ export { jobStepsActiveTable, jobStepsArchiveTable, clientsTable, + claimLockTable, } diff --git a/packages/duron/src/adapters/postgres/schema.ts b/packages/duron/src/adapters/postgres/schema.ts index 092f4a2..691706e 100644 --- a/packages/duron/src/adapters/postgres/schema.ts +++ b/packages/duron/src/adapters/postgres/schema.ts @@ -236,6 +236,15 @@ export default function createSchema(schemaName: string) { last_seen_at: timestamp('last_seen_at', { withTimezone: true }).notNull().defaultNow(), }) + // ============================================================================ + // Claim Lock (claim serialization) + // ============================================================================ + + // Always empty. Each claim transaction locks it (LOCK TABLE ... IN EXCLUSIVE MODE) before + // its claim statement, so claims of this schema run one at a time. LOCK TABLE takes no + // snapshot, so the claim's SERIALIZABLE snapshot starts after the previous claim committed. + const claimLockTable = schema.table('claim_lock', {}) + return { schema, jobsActiveTable, @@ -243,5 +252,6 @@ export default function createSchema(schemaName: string) { jobStepsActiveTable, jobStepsArchiveTable, clientsTable, + claimLockTable, } } diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index ff91e80..7408a87 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -72,10 +72,10 @@ const notAccepting = () => new Error('Lifecycle is not accepting work') const EMPTY_CLAIM_RETRIES = 2 /** - * Delay of a follow-up after a short claim, random so peers do not align: 10–50 ms, and + * Delay of a follow-up after an empty claim, random so peers do not align: 10–50 ms, and * five times as long for each empty claim already followed up in a row (50–250 ms). */ -function shortClaimDelay(emptyRetries: number): number { +function emptyClaimDelay(emptyRetries: number): number { return (10 + Math.floor(Math.random() * 41)) * 5 ** emptyRetries } @@ -91,17 +91,17 @@ function shortClaimDelay(emptyRetries: number): number { * another automatic request for the rest of that demand, so a backlog keeps draining * without waiting for the periodic tick. A claim that covered all of its hints (for * example one job for one hint) is not followed up: later hints add their own demand. - * - A short claim (fewer jobs than its batch) while hinted demand remains usually means that - * peers' claims hold the other rows, not that the queue is empty: a claim locks every - * eligible row it sees (SKIP LOCKED) until it commits, so a concurrent claim can even - * return nothing. One follow-up for the rest of the demand is queued after a random - * 10–50 ms delay, once those claims have committed. After a claim that returned nothing, - * this happens only for more than one uncovered hint (a lone hint that a peer won is not - * retried) and at most twice in a row, the second time after 50–250 ms (a peer's next - * small claim can lock the rest again); a third empty claim in a row ends it, so an empty - * queue is never polled. A claim that returns jobs, or a new hint, resets the count. + * - The claims of all workers run one at a time (the adapters' claim lock), so a claim sees + * the jobs that earlier claims took. A short claim (fewer jobs than its batch) that + * returned jobs is not followed up: while hinted demand remains, its jobs' settlement + * wakes look again (see below), and the peers that took the rest received the same hints. + * An empty claim (for example after a claim lock timeout, which returns no jobs) is + * followed up after a random 10–50 ms delay only for more than one uncovered hint (a lone + * hint that a peer won is not retried) and at most twice in a row, the second time after + * 50–250 ms; a third empty claim in a row ends it, so an empty queue is never polled. A + * claim that returns jobs, or a new hint, resets the count. * - Demand becomes unbounded once a settlement or a periodic check merges into it; from then - * on only settlement wakes, not short-claim follow-ups, look for the rest. + * on only settlement wakes, not empty-claim follow-ups, look for the rest. * - A local job requests discovery again when it settles (unbounded demand, coalesced; * trigger `settled`) if its own claim did not cover its demand, or while the last * automatic claim left demand uncovered (`#uncovered`): its settlement can free a slot of @@ -149,8 +149,8 @@ export class WorkerDiscovery { * nothing. While set, every local settlement wakes discovery (see `#track`). */ #uncovered = false - /** The pending follow-up of short claims (see `#followShortClaim`). */ - #shortFollowUp: { + /** The pending follow-up of empty claims (see `#followEmptyClaim`). */ + #emptyFollowUp: { timer: ReturnType demand: number triggers: Set @@ -202,10 +202,10 @@ export class WorkerDiscovery { this.#stopped = true if (this.#tick) clearTimeout(this.#tick) if (this.#wake) clearTimeout(this.#wake) - if (this.#shortFollowUp) clearTimeout(this.#shortFollowUp.timer) + if (this.#emptyFollowUp) clearTimeout(this.#emptyFollowUp.timer) this.#tick = null this.#wake = null - this.#shortFollowUp = null + this.#emptyFollowUp = null const queued = this.#queue this.#queue = [] this.#automatic = null @@ -350,16 +350,17 @@ export class WorkerDiscovery { // covered all of its hints (one job for one hint) is not followed up. The // follow-up keeps the uncovered demand (unbounded stays unbounded). this.#mergeAutomatic(request.demand - batch, request.triggers) - } else if (Number.isFinite(request.demand) && request.demand > got) { - if (got > 0) { - this.#emptyRetries = 0 - this.#followShortClaim(request.demand - got, request.triggers) - } else if (this.#emptyRetries < EMPTY_CLAIM_RETRIES && request.demand > 1) { - this.#followShortClaim(request.demand, request.triggers) - this.#emptyRetries++ - } } else if (got > 0) { + // A short claim that returned jobs is not followed up: while it left demand + // uncovered, each settlement of its jobs looks again (`#uncovered`). this.#emptyRetries = 0 + } else if ( + Number.isFinite(request.demand) && + request.demand > 1 && + this.#emptyRetries < EMPTY_CLAIM_RETRIES + ) { + this.#followEmptyClaim(request.demand, request.triggers) + this.#emptyRetries++ } } catch (error) { this.#cooldownUntil = monotonicMs() + this.#interval @@ -384,29 +385,29 @@ export class WorkerDiscovery { } /** - * A short (or empty) claim left hinted demand uncovered: peers' claims probably hold those - * rows. Ask again after a short random delay, once their transactions have committed. Only finite - * (hinted) demand is followed: unbounded demand has no evidence of more jobs, and its - * jobs' settlement wakes cover a group-limited backlog. Concurrent follow-ups merge. + * An empty claim left more than one hinted job uncovered: the claim lock was not + * available in time, or the hinted jobs were not claimable yet when it ran. Ask again + * after a short random delay. Only finite (hinted) demand is followed: unbounded demand + * has no evidence of more jobs. Concurrent follow-ups merge. */ - #followShortClaim(demand: number, triggers: Iterable): void { + #followEmptyClaim(demand: number, triggers: Iterable): void { if (!this.#open) return - if (this.#shortFollowUp) { - this.#shortFollowUp.demand += demand - for (const trigger of triggers) this.#shortFollowUp.triggers.add(trigger) + if (this.#emptyFollowUp) { + this.#emptyFollowUp.demand += demand + for (const trigger of triggers) this.#emptyFollowUp.triggers.add(trigger) return } const followUp = { demand, triggers: new Set(triggers), timer: setTimeout(() => { - this.#shortFollowUp = null + this.#emptyFollowUp = null if (!this.#open) return this.#mergeAutomatic(followUp.demand, followUp.triggers) this.#pump() - }, shortClaimDelay(this.#emptyRetries)), + }, emptyClaimDelay(this.#emptyRetries)), } - this.#shortFollowUp = followUp + this.#emptyFollowUp = followUp } #track(settlement: Promise, wake: boolean): void { diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 7e825d3..0b6f9ea 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -137,7 +137,10 @@ async function claimDatabase() { IF current_setting('application_name') = '${applicationName}' THEN PERFORM setval('duron.claim_test_seen_active', (SELECT count(*) FROM duron.jobs_active WHERE status = 'active')); - PERFORM pg_advisory_xact_lock(${BARRIER_KEY}); + -- Polls instead of waiting: a lock wait would end at the claim lock_timeout. + WHILE NOT pg_try_advisory_xact_lock(${BARRIER_KEY}) LOOP + PERFORM pg_sleep(0.005); + END LOOP; END IF; RETURN NULL; END $$; @@ -157,7 +160,9 @@ async function claimDatabase() { BEGIN barrier_key := CASE current_setting('application_name') ${cases} END; IF barrier_key IS NOT NULL THEN - PERFORM pg_advisory_xact_lock(barrier_key); + WHILE NOT pg_try_advisory_xact_lock(barrier_key) LOOP + PERFORM pg_sleep(0.005); + END LOOP; END IF; RETURN NULL; END $$; @@ -195,11 +200,10 @@ async function claimDatabase() { }, async waitingAtBarrier(applicationName: string): Promise { await eventually(async () => { + // The barrier polls with pg_sleep while the barrier session holds its key. const rows = await admin` - SELECT count(*)::int AS count FROM pg_locks l - JOIN pg_stat_activity a ON a.pid = l.pid - WHERE l.locktype = 'advisory' AND NOT l.granted - AND a.application_name = ${applicationName}` + SELECT count(*)::int AS count FROM pg_stat_activity + WHERE wait_event = 'PgSleep' AND application_name = ${applicationName}` return rows[0]!['count'] === 1 }) }, @@ -284,6 +288,42 @@ async function createJobs( return ids } +type ClaimSql = { query: string; parameters: unknown[] } + +// The exact claim statement the adapter generates for `batch`, captured from an empty claim +// (the adapter is started and left to the database cleanup). +async function captureClaim(adapter: PostgresAdapter, batch: number): Promise { + const statements = traceStatements(adapter) + await adapter.start() + expect(await adapter.fetch({ batch })).toEqual([]) + const claims = statements.filter(isClaim) + expect(claims).toHaveLength(1) + return claims[0]! +} + +// Runs and commits the claim statement in its own SERIALIZABLE transaction without the +// claim lock (an older Duron version's claim). Returns the claimed ids. +async function claimWithoutLock(session: postgres.Sql, claim: ClaimSql): Promise { + const rows = await session.begin('isolation level serializable', (tx) => + tx.unsafe(claim.query, claim.parameters as never[]), + ) + return (rows as unknown as Array<{ id: string }>).map((row) => row.id) +} + +// Inserts a created job of the same group and limit as `job`, committed now but +// sorting before it (an earlier created_at), as a job created in a longer transaction +// does. Returns its id. +async function insertEarlierJob(admin: postgres.Sql, job: string): Promise { + const [row] = await admin` + INSERT INTO duron.jobs_active (action_name, group_key, checksum, timeout_ms, input, + concurrency_limit, concurrency_step_limit, created_at) + SELECT action_name, group_key, checksum, timeout_ms, input, concurrency_limit, + concurrency_step_limit, created_at - interval '1 second' + FROM duron.jobs_active WHERE id = ${job} + RETURNING id` + return row!['id'] as string +} + // Seeded schedules from the accepted capacity evidence. Base READ COMMITTED // produced 3/4/2 active claims for these limits; fresh controls stay at capacity. const schedules = [ @@ -295,14 +335,18 @@ const schedules = [ const suite = process.env['POSTGRES_TEST'] === 'true' ? describe : describe.skip suite('Native PostgreSQL claim admission', () => { for (const schedule of schedules) { + // Built-in claims wait for each other (claim lock), so the competing claim is the claim + // SQL without the claim lock, as an older Duron version or a custom claimant runs it. it(`retries a stale overlapping Adapter.fetch instead of exceeding group capacity (${schedule.name})`, async () => { const db = await claimDatabase() + const competitor = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) try { const a = db.adapter('claim-a') const b = db.adapter('claim-b') const logs = captureLogs(b) await a.start() await b.start() + const claimSql = await captureClaim(db.adapter('claim-capture'), schedule.batch) await createJobs(a, schedule.jobs, schedule.limit) if (schedule.preclaimed) { expect(await a.fetch({ batch: schedule.preclaimed })).toHaveLength(schedule.preclaimed) @@ -311,7 +355,7 @@ suite('Native PostgreSQL claim admission', () => { await db.hold() const stale = observe(b.fetch({ batch: schedule.batch })) await db.waitingAtBarrier('claim-b') - expect(await a.fetch({ batch: schedule.batch })).toHaveLength( + expect(await claimWithoutLock(competitor, claimSql)).toHaveLength( schedule.limit - schedule.preclaimed, ) // Native snapshot proxy: the paused claim still sees the pre-claimed count. @@ -330,6 +374,7 @@ suite('Native PostgreSQL claim admission', () => { db.recordFailure(error) throw error } finally { + await competitor.end({ timeout: 5 }) await db.cleanup() } }, 30_000) @@ -355,7 +400,7 @@ suite('Native PostgreSQL claim admission', () => { }, 30_000) } - it('withholds the claim until COMMIT while keeping the existing candidate lock footprint', async () => { + it('withholds the claim until COMMIT, locks only the jobs it claims, and makes the next claim wait', async () => { const db = await claimDatabase() try { const a = db.adapter('claim-a') @@ -374,18 +419,34 @@ suite('Native PostgreSQL claim admission', () => { expect(settled).toBe(false) const before = await db.admin`SELECT status FROM duron.jobs_active ORDER BY created_at, id` expect(before.map((row) => row['status'])).toEqual(Array(5).fill('created')) - // Selected and unselected candidates stay locked by the open claim transaction. - for (const id of [ids[0]!, ids[4]!]) { - const probe = await observe( - db.admin`SELECT id FROM duron.jobs_active WHERE id = ${id} FOR UPDATE NOWAIT`, - ) - expect(sqlState(rejection(probe))).toBe('55P03') - } - expect(await b.fetch({ batch: 1 })).toEqual([]) + // The open claim transaction locks the job it claims, and no other candidate. + const probe = await observe( + db.admin`SELECT id FROM duron.jobs_active WHERE id = ${ids[0]!} FOR UPDATE NOWAIT`, + ) + expect(sqlState(rejection(probe))).toBe('55P03') + const unlocked = await db.admin` + SELECT count(*)::int AS count FROM ( + SELECT id FROM duron.jobs_active FOR UPDATE SKIP LOCKED + ) AS s` + expect(unlocked[0]!['count']).toBe(4) + // A concurrent claim waits for the claim lock until the open claim commits, then sees + // its claim and takes the next job. + let waited = false + const next = b.fetch({ batch: 1 }).finally(() => { + waited = true + }) + await Bun.sleep(200) + expect(waited).toBe(false) await db.release(BARRIER_KEY + 1) expect((await claim).map((job) => job.id)).toEqual([ids[0]!]) - expect(await db.activeCount()).toBe(1) - expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[1]!]) + expect((await next).map((job) => job.id)).toEqual([ids[1]!]) + expect(await db.activeCount()).toBe(2) + // A job another transaction holds is skipped: the claim takes the next candidate. + await db.admin.begin(async (tx) => { + await tx`SELECT id FROM duron.jobs_active WHERE id = ${ids[2]!} FOR UPDATE` + expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[3]!]) + }) + expect((await b.fetch({ batch: 1 })).map((job) => job.id)).toEqual([ids[2]!]) } catch (error) { db.recordFailure(error) throw error @@ -648,46 +709,47 @@ suite('Native PostgreSQL claim admission', () => { it('retries a distinct-row write skew rejected at COMMIT without publishing its provisional claim', async () => { const db = await claimDatabase() - const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) + // A is the claim SQL without the claim lock (as an older Duron version runs it), held + // open after its claim statement: built-in claims would wait for each other instead. + const competitor = postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }) // Test-owned gates live outside try so finally can always release them. - const locked = Promise.withResolvers() - const unlock = Promise.withResolvers() - let holding: Promise | undefined + const claimedA = Promise.withResolvers() + const commitA = Promise.withResolvers() + let claimA: Promise | undefined try { - const a = db.adapter('claim-a') const b = db.adapter('claim-b', 1) const logs = captureLogs(b) - await a.start() await b.start() - const [first, second] = await createJobs(a, 2, 1) - await db.installAfterUpdateBarrier(['claim-a', 'claim-b']) + const claimSql = await captureClaim(db.adapter('claim-a'), 1) + const [first] = await createJobs(b, 1, 1) + await db.installAfterUpdateBarrier(['claim-b']) await db.hold(BARRIER_KEY + 1) - await db.hold(BARRIER_KEY + 2) - // Labelled SQL instrumentation: an owned row lock makes A skip the second job. - holding = holder.begin(async (tx) => { - await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` - locked.resolve() - await unlock.promise + claimA = competitor.begin('isolation level serializable', async (tx) => { + claimedA.resolve(await tx.unsafe(claimSql.query, claimSql.parameters as never[])) + await commitA.promise }) - failGateWith(locked, holding) - await locked.promise - const claimA = observe(a.fetch({ batch: 1 })) - await db.waitingAtBarrier('claim-a') - unlock.resolve() - await holding - // B's snapshot cannot see A's uncommitted claim; it skips A's locked row. + failGateWith(claimedA, claimA) + expect(((await claimedA.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ + first!, + ]) + // A job that commits after A's snapshot but sorts first in the group (as a job + // created in a longer transaction does) is the only candidate within B's slot. + const early = await insertEarlierJob(db.admin, first!) + // B's snapshot cannot see A's uncommitted claim; it claims the other job. const claimB = observe(b.fetch({ batch: 1 })) await db.waitingAtBarrier('claim-b') const provisional = await db.admin`SELECT id, status FROM duron.jobs_active ORDER BY created_at, id` - expect(provisional.map((row) => row['status'])).toEqual(['created', 'created']) + expect(provisional.map((row) => [row['id'], row['status']])).toEqual([ + [early, 'created'], + [first!, 'created'], + ]) + commitA.resolve() + await claimA await db.release(BARRIER_KEY + 1) - const resultA = await claimA - expect(fulfilment(resultA).map((job) => job.id)).toEqual([first!]) - await db.release(BARRIER_KEY + 2) const resultB = await claimB const final = await db.admin`SELECT id, status FROM duron.jobs_active ORDER BY created_at, id` - expect(final.map((row) => row['status'])).toEqual(['active', 'created']) + expect(final.map((row) => row['status'])).toEqual(['created', 'active']) // B's COMMIT failed with 40001 and published nothing; its retry, a new transaction, // sees A's claim and the group at its limit. expect(fulfilment(resultB)).toEqual([]) @@ -706,10 +768,10 @@ suite('Native PostgreSQL claim admission', () => { throw error } finally { // Release every owned gate before awaiting work or ending sessions. - unlock.resolve() + commitA.resolve() await db.release().catch(() => undefined) - await holding?.catch(() => undefined) - await holder.end({ timeout: 5 }) + await claimA?.catch(() => undefined) + await competitor.end({ timeout: 5 }) await db.cleanup() } }, 30_000) @@ -719,18 +781,16 @@ suite('Native PostgreSQL claim admission', () => { for (const [isolation, expected] of [ ['read committed', ['active', 'active']], ['repeatable read', ['active', 'active']], - ['serializable', ['active', 'created']], + ['serializable', ['created', 'active']], ] as const) { it(`replays the exact claim SQL under ${isolation} for the distinct-row schedule`, async () => { const db = await claimDatabase() - const sessions = [0, 1, 2].map(() => + const sessions = [0, 1].map(() => postgres(db.url, { max: 1, connection: { statement_timeout: 5_000 } }), ) - const [holder, sessionA, sessionB] = sessions as [postgres.Sql, postgres.Sql, postgres.Sql] + const [sessionA, sessionB] = sessions as [postgres.Sql, postgres.Sql] const pending: Promise[] = [] // Test-owned gates live outside try so finally can always release them. - const lockedSecond = Promise.withResolvers() - const unlock = Promise.withResolvers() const claimedA = Promise.withResolvers() const claimedB = Promise.withResolvers() const commitA = Promise.withResolvers() @@ -743,16 +803,8 @@ suite('Native PostgreSQL claim admission', () => { expect(await capture.fetch({ batch: 1 })).toEqual([]) const claims = statements.filter(isClaim) expect(claims).toHaveLength(1) - const [first, second] = await createJobs(capture, 2, 1) + const [first] = await createJobs(capture, 1, 1) const { query, parameters } = claims[0]! - const hold = holder.begin(async (tx) => { - await tx`SELECT id FROM duron.jobs_active WHERE id = ${second!} FOR UPDATE` - lockedSecond.resolve() - await unlock.promise - }) - pending.push(hold) - failGateWith(lockedSecond, hold) - await lockedSecond.promise const replay = ( session: postgres.Sql, claimed: PromiseWithResolvers, @@ -770,11 +822,11 @@ suite('Native PostgreSQL claim admission', () => { expect(((await claimedA.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ first!, ]) - unlock.resolve() - await hold + // Committed after A's snapshot, sorting first: the only candidate in B's slot. + const early = await insertEarlierJob(db.admin, first!) const replayB = replay(sessionB, claimedB, commitB) expect(((await claimedB.promise) as Array<{ id: string }>).map((row) => row.id)).toEqual([ - second!, + early, ]) commitA.resolve() expect((await replayA).status).toBe('fulfilled') @@ -792,7 +844,6 @@ suite('Native PostgreSQL claim admission', () => { throw error } finally { // Release every owned gate before awaiting replay work or ending sessions. - unlock.resolve() commitA.resolve() commitB.resolve() await Promise.allSettled(pending) @@ -817,7 +868,7 @@ suite('Native PostgreSQL claim admission', () => { await a.start() expect(await a.fetch({ batch: 1 })).toEqual([]) const { query, parameters } = statements.find(isClaim)! - await createJobs(a, 3, 2) + const [, second] = await createJobs(a, 3, 2) expect(await a.fetch({ batch: 1 })).toHaveLength(1) await db.installBeforeUpdateBarrier('claim-b') await db.hold() @@ -827,7 +878,9 @@ suite('Native PostgreSQL claim admission', () => { ), ) await db.waitingAtBarrier('claim-b') - expect(await a.fetch({ batch: 1 })).toHaveLength(1) + // A job that the paused claim's snapshot cannot see takes the last slot. + const early = await insertEarlierJob(db.admin, second!) + expect((await a.fetch({ batch: 1 })).map((job) => job.id)).toEqual([early]) await db.release() expect((await stale).status).toBe('fulfilled') expect(await db.activeCount()).toBe(3) @@ -877,17 +930,23 @@ suite('Native PostgreSQL claim admission', () => { expect(await a.fetch({ batchSize: 1 })).toHaveLength(1) await db.installBeforeUpdateBarrier('claim-b') await db.hold() - const stale = observe(b.fetch({ batchSize: 1 })) + const first = observe(b.fetch({ batchSize: 1 })) await db.waitingAtBarrier('claim-b') - expect(await a.fetch({ batchSize: 1 })).toHaveLength(1) + // A's claim waits for B's claim lock instead of claiming from the same snapshot. + let settled = false + const second = observe(a.fetch({ batchSize: 1 })).finally(() => { + settled = true + }) + await Bun.sleep(200) + expect(settled).toBe(false) await db.release() - const result = await stale + expect(fulfilment(await first)).toHaveLength(1) + // A's claim then sees B's claim and the group at its limit: no conflict. + expect(fulfilment(await second)).toEqual([]) await eventually(() => started.length >= 2) await Bun.sleep(50) expect(started).toHaveLength(2) expect(await db.activeCount()).toBe(2) - // The stale claim conflicted (40001) and its retry found the group at its limit. - expect(fulfilment(result)).toEqual([]) handlers.resolve() await eventually(async () => (await db.activeCount()) === 0) } catch (error) { @@ -901,7 +960,110 @@ suite('Native PostgreSQL claim admission', () => { } }, 30_000) - it('retries natural conflicts between concurrent claimers and claims every job exactly once', async () => { + it('returns an empty claim, without an error or a retry, when the claim lock is not available', async () => { + const db = await claimDatabase() + const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 10_000 } }) + // Test-owned gates live outside try so finally can always release them. + const locked = Promise.withResolvers() + const unlock = Promise.withResolvers() + let holding: Promise | undefined + try { + const a = db.adapter('claim-a') + const entries: Array> = [] + a.setLogger( + pino({ level: 'debug' }, { write: (line: string) => entries.push(JSON.parse(line)) }), + ) + await a.start() + const [id] = await createJobs(a, 1, 1) + // A transaction that holds the claim lock and does not finish (a stuck claim). + holding = holder.begin(async (tx) => { + await tx`LOCK TABLE duron.claim_lock IN EXCLUSIVE MODE` + locked.resolve() + await unlock.promise + }) + failGateWith(locked, holding) + await locked.promise + const begun = performance.now() + expect(await a.fetch({ batch: 1 })).toEqual([]) + const waited = performance.now() - begun + // lock_timeout is 1 s. + expect(waited).toBeGreaterThanOrEqual(900) + expect(waited).toBeLessThan(3_000) + expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) + expect(entries.filter((entry) => /claim conflict/.test(entry['msg']))).toEqual([]) + const timeouts = entries.filter((entry) => /Claim lock not available/.test(entry['msg'])) + expect(timeouts.map((entry) => [entry['level'], entry['err']['code']])).toEqual([ + [20, '55P03'], + ]) + expect(await db.activeCount()).toBe(0) + unlock.resolve() + await holding + expect((await a.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id!]) + } catch (error) { + db.recordFailure(error) + throw error + } finally { + unlock.resolve() + await holding?.catch(() => undefined) + await holder.end({ timeout: 5 }) + await db.cleanup() + } + }, 30_000) + + it('does not pause Client discovery after a claim lock timeout', async () => { + const db = await claimDatabase() + const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 10_000 } }) + const locked = Promise.withResolvers() + const unlock = Promise.withResolvers() + let holding: Promise | undefined + const entries: Array> = [] + const action = defineAction()({ + name: 'claim-timeout', + input: z.object({ index: z.number() }), + output: z.object({ index: z.number() }), + handler: async (ctx) => ({ index: ctx.input.index }), + }) + const client = new Client({ + id: 'claim-a', + database: db.adapter('claim-a'), + actions: { claimTimeout: action }, + syncPattern: false, + // A failed claim would delay the next one by a full pullInterval. + pullInterval: 60_000, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: pino({ level: 'debug' }, { write: (line: string) => entries.push(JSON.parse(line)) }), + }) + try { + await client.start() + const id = await client.runAction('claimTimeout', { index: 0 }) + holding = holder.begin(async (tx) => { + await tx`LOCK TABLE duron.claim_lock IN EXCLUSIVE MODE` + locked.resolve() + await unlock.promise + }) + failGateWith(locked, holding) + await locked.promise + expect(await client.fetch({ batchSize: 1 })).toEqual([]) + unlock.resolve() + await holding + const begun = performance.now() + expect((await client.fetch({ batchSize: 1 })).map((job) => job.id)).toEqual([id]) + expect(performance.now() - begun).toBeLessThan(1_000) + expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) + } catch (error) { + db.recordFailure(error) + throw error + } finally { + unlock.resolve() + await holding?.catch(() => undefined) + await holder.end({ timeout: 5 }) + await client.stop().catch(() => undefined) + await db.cleanup() + } + }, 30_000) + + it('claims every job exactly once across concurrent claimers without claim conflicts', async () => { const db = await claimDatabase() try { const claimers = ['claim-a', 'claim-b', 'claim-c', 'claim-d'].map((name) => { @@ -911,12 +1073,10 @@ suite('Native PostgreSQL claim admission', () => { for (const { adapter } of claimers) await adapter.start() const conflicts = () => claimers.flatMap(({ logs }) => logs.conflicts()) const failures: unknown[] = [] - // A round has a natural conflict only sometimes, so rounds repeat (bounded) until - // at least one conflict was retried. let active = 0 - // 100 rounds (measured: at most 14 needed) leave margin for quiet or slow CI runners; - // a round takes tens of milliseconds. - for (let round = 0; round < 100 && conflicts().length === 0; round++) { + // Without the claim lock, 1 to 14 rounds of this tight-loop contention produced a + // retried 40001, and exhausted retries were seen in multi-worker bursts. + for (let round = 0; round < 20; round++) { const ids = await createJobs(claimers[0]!.adapter, 30, 10_000) const claimed: string[] = [] // Every claimer claims in a tight loop until a claim comes back empty. @@ -938,12 +1098,10 @@ suite('Native PostgreSQL claim admission', () => { active += ids.length expect(await db.activeCount()).toBe(active) } - expect(conflicts().length).toBeGreaterThan(0) - expect(conflicts().every((entry) => entry['err']['code'] === '40001')).toBe(true) - // Exhaustion (6 conflicts in a row for one claim) was not observed in 40 runs per - // PostgreSQL version of this tight-loop contention, but it is not impossible; only - // that exhausted retry surfaces, as the original 40001. - expect(failures.every((error) => sqlState(error) === '40001')).toBe(true) + // Claims wait for each other's claim lock: none conflicts, none fails. + expect(conflicts()).toEqual([]) + expect(failures).toEqual([]) + expect(claimers.flatMap(({ logs }) => logs.errors())).toEqual([]) } catch (error) { db.recordFailure(error) throw error diff --git a/packages/duron/test/claim-lock-migration.test.ts b/packages/duron/test/claim-lock-migration.test.ts new file mode 100644 index 0000000..3a4d929 --- /dev/null +++ b/packages/duron/test/claim-lock-migration.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from 'bun:test' +import { cp, mkdtemp, readdir, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { sql } from 'drizzle-orm' +import { drizzle as drizzlePglite } from 'drizzle-orm/pglite' +import { migrate as migratePglite } from 'drizzle-orm/pglite/migrator' +import { drizzle as drizzlePostgres } from 'drizzle-orm/postgres-js' +import { migrate as migratePostgres } from 'drizzle-orm/postgres-js/migrator' +import postgres from 'postgres' + +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// The claim lock migration applies to a database that already ran the earlier migrations +// and holds jobs: it adds the empty claim_lock table, keeps the jobs, and claims work. + +const MIGRATIONS = join(import.meta.dirname, '..', 'migrations', 'postgres') +const CLAIM_LOCK_MIGRATION = '20261202120334_silent_thunderbolt' +const MIGRATION_CONFIG = { migrationsTable: 'migrations', migrationsSchema: 'duron' } + +// A copy of the migrations folder without the claim lock migration and the later ones. +async function earlierMigrations(): Promise<{ folder: string; remove: () => Promise }> { + const root = await mkdtemp(join(tmpdir(), 'duron-migrations-')) + const folder = join(root, 'postgres') + const names = (await readdir(MIGRATIONS)).filter((name) => name < CLAIM_LOCK_MIGRATION) + expect(names.length).toBeGreaterThan(0) + for (const name of names) + await cp(join(MIGRATIONS, name), join(folder, name), { recursive: true }) + return { folder, remove: () => rm(root, { recursive: true, force: true }) } +} + +const insertJob = sql` + INSERT INTO duron.jobs_active (action_name, group_key, checksum, timeout_ms, + concurrency_limit, concurrency_step_limit) + VALUES ('upgrade-action', 'upgrade-group', 'upgrade', 60000, 1, 1) + RETURNING id` +const claimLockExists = sql`SELECT to_regclass('duron.claim_lock') IS NOT NULL AS present` +const appliedMigrations = sql`SELECT count(*)::int AS count FROM duron.migrations` + +function rowsOf(result: unknown): Array> { + return Array.isArray(result) + ? [...result] + : (result as { rows: Array> }).rows +} + +describe('Claim lock migration with pglite', () => { + it('applies on an existing database with jobs', async () => { + const earlier = await earlierMigrations() + const dataDir = await mkdtemp(join(tmpdir(), 'duron-pglite-')) + try { + const old = drizzlePglite({ connection: dataDir }) + await migratePglite(old, { migrationsFolder: earlier.folder, ...MIGRATION_CONFIG }) + expect(rowsOf(await old.execute(claimLockExists))[0]!['present']).toBe(false) + const id = rowsOf(await old.execute(insertJob))[0]!['id'] as string + const before = rowsOf(await old.execute(appliedMigrations))[0]!['count'] as number + await old.$client.close() + + const adapter = new PGLiteAdapter({ connection: dataDir, migrateOnStart: true }) + adapter.setId('upgrade-adapter') + await adapter.start() + try { + const db = (adapter as unknown as { db: { execute: (query: unknown) => Promise } }) + .db + expect(rowsOf(await db.execute(claimLockExists))[0]!['present']).toBe(true) + expect(rowsOf(await db.execute(appliedMigrations))[0]!['count']).toBe(before + 1) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id]) + } finally { + await adapter.stop() + } + } finally { + await rm(dataDir, { recursive: true, force: true }) + await earlier.remove() + } + }, 30_000) +}) + +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Claim lock migration with postgres', () => { + it('applies on an existing database with jobs', async () => { + const earlier = await earlierMigrations() + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + const client = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) + try { + const old = drizzlePostgres({ client }) + await migratePostgres(old, { migrationsFolder: earlier.folder, ...MIGRATION_CONFIG }) + expect(rowsOf(await old.execute(claimLockExists))[0]!['present']).toBe(false) + const id = rowsOf(await old.execute(insertJob))[0]!['id'] as string + const before = rowsOf(await old.execute(appliedMigrations))[0]!['count'] as number + + const adapter = new PostgresAdapter({ connection: CONNECTION_URL, migrateOnStart: true }) + adapter.setId('upgrade-adapter') + await adapter.start() + try { + expect(rowsOf(await old.execute(claimLockExists))[0]!['present']).toBe(true) + expect(rowsOf(await old.execute(appliedMigrations))[0]!['count']).toBe(before + 1) + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([id]) + } finally { + await adapter.stop() + } + } finally { + await client.end({ timeout: 5 }) + await deleteDb() + await earlier.remove() + } + }, 30_000) + }) +} diff --git a/packages/duron/test/claim-selection.test.ts b/packages/duron/test/claim-selection.test.ts index ddf16d4..599c6a2 100644 --- a/packages/duron/test/claim-selection.test.ts +++ b/packages/duron/test/claim-selection.test.ts @@ -80,6 +80,26 @@ const fixtures: Array<{ name: string; batch: number; rows: Row[]; claimed: numbe ], claimed: [1, 2, 3], }, + { + name: 'older jobs of a full group do not block a younger job of a free group', + batch: 1, + rows: [ + { id: 1, group: 'full', created: 1, limit: 1, status: 'active', expires: 'future' }, + ...[2, 3, 4, 5, 6].map((n) => ({ id: n, group: 'full', created: n, limit: 1 })), + { id: 7, group: 'free', created: 7, limit: 1 }, + ], + claimed: [7], + }, + { + name: 'older jobs beyond their group slots do not take batch room from younger groups', + batch: 3, + rows: [ + ...[1, 2, 3, 4, 5].map((n) => ({ id: n, group: 'g1', created: n, limit: 2 })), + { id: 6, group: 'g2', created: 6, limit: 2 }, + { id: 7, group: 'g2', created: 7, limit: 2 }, + ], + claimed: [1, 2, 6], + }, { name: 'null-expiry active jobs count toward capacity and expired active jobs do not', batch: 10, diff --git a/packages/duron/test/discovery-throughput.test.ts b/packages/duron/test/discovery-throughput.test.ts index 05eca98..9345bc7 100644 --- a/packages/duron/test/discovery-throughput.test.ts +++ b/packages/duron/test/discovery-throughput.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'bun:test' +import pino from 'pino' + import { defineAction } from '../src/action.js' import type { Adapter } from '../src/adapters/adapter.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' @@ -168,13 +170,14 @@ for (const factory of factories) { }) } -// Several workers on one database: a claim that returns fewer jobs than requested because -// peers hold the rows (SKIP LOCKED) must not drop the rest of a burst until the periodic tick. +// Several workers on one database: their claims wait for each other (claim lock), and a +// claim that returns fewer jobs than its hints because peers took them must not drop the +// rest of a burst until the periodic tick. if (process.env['POSTGRES_TEST'] === 'true') { describe('Discovery throughput with several postgres workers', () => { // Short handlers: settlement wakes also find the rest of a burst. Long handlers (longer // than half of pullInterval, with room for the whole burst): no job settles before the - // check, so only the follow-up of a short claim can find the rest in time. + // check, so the hints' own claims (and empty-claim retries) must find the rest in time. for (const [handlerMs, batchSize] of [ [20, 10], [3_000, 100], @@ -186,6 +189,14 @@ if (process.env['POSTGRES_TEST'] === 'true') { adapters.push(new PostgresAdapter({ connection: instance.connectionUrl })) } const clients: Client[] = [] + // Retried claim conflicts (debug) and errors, such as an exhausted claim retry. + const entries: Array> = [] + const logger = pino( + { level: 'debug' }, + { + write: (line: string) => entries.push(JSON.parse(line)), + }, + ) let begun = 0 let starts: number[] = [] const action = defineAction()({ @@ -210,7 +221,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { actionConcurrencyLimit: 300, recoverJobsOnStart: false, recoverJobsInterval: 0, - logger: 'silent', + logger, }), ) } @@ -233,6 +244,9 @@ if (process.env['POSTGRES_TEST'] === 'true') { } // A part of a burst left for the periodic tick would start at about PULL_INTERVAL. expect(latest.filter((ms) => ms >= PULL_INTERVAL / 2)).toEqual([]) + // Claims wait for each other's claim lock: none conflicts, so no retry is exhausted. + expect(entries.filter((entry) => /claim conflict/.test(entry['msg']))).toEqual([]) + expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) } finally { for (const client of clients) await client.stop().catch(() => undefined) await instance.deleteDb() From 0273545a59f0bc84335165d1fabb1d45835b764c Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 10:41:35 -0300 Subject: [PATCH 02/20] fix(claim): end a stalled claim_lock holder and document the claim lock (F1 review) - R1: the claim transaction sets SET LOCAL idle_in_transaction_session_timeout = '5s' (PostgreSQL adapter). A worker that stalls between LOCK and COMMIT is ended by the server (25P03), its claim rolls back, and the claim lock is free: a fleet-wide claim stall lasts ~5 s instead of until TCP keepalive. A normal claim is idle only for round trips; the timer does not run during statements or lock waits. PGlite skips it (one in-process session; the timeout stops the engine). Native test: a relay withholds the LOCK reply of one claim; other claims return empty, then claim at ~5 s; 25P03 seen; both settings stay LOCAL. Fails without the setting. - A1: 55P03 debug log no longer claims it is always the claim lock. - R2: adapters.mdx documents GRANT UPDATE on claim_lock for separate worker roles (42501 otherwise; verified on PG19). - A2: multi-worker.mdx documents the per-schema claim rate ceiling (~17-60 claims/s at a 50k backlog, hundreds/s on small backlogs). - A3: rolling upgrade with old and new workers is safe; can be slower. - A4: fix stale worker-discovery comment; held test pins that a short claim that returned jobs is not followed up and its settlement looks again (fails on 2764089). --- packages/docs/content/docs/adapters.mdx | 18 +++++- packages/docs/content/docs/multi-worker.mdx | 8 ++- packages/duron/src/adapters/postgres/base.ts | 50 +++++++++++++-- .../duron/src/adapters/postgres/pglite.ts | 8 +++ packages/duron/test/claim-isolation.test.ts | 64 ++++++++++++++++++- packages/duron/test/worker-discovery.test.ts | 62 +++++++++++++++++- 6 files changed, 196 insertions(+), 14 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 2b0ecb3..3ccb8eb 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -236,7 +236,23 @@ touches no existing table and takes no lock on the job tables, so it applies at table size and needs no preparation or maintenance window (no concurrent pre-build). Upgraded instances lock this table in every claim; instances of the previous version do not, so during a rolling upgrade their claims are protected only by `SERIALIZABLE` (claims of both versions can -abort each other with `40001` and are retried) until every instance is upgraded. +abort each other with `40001` and are retried) until every instance is upgraded. Running both +versions is safe: group limits hold and every job is claimed once. Claims can be slower until the +rollout ends: a claim of the previous version row-locks every eligible job until it commits, +upgraded claims skip those jobs, and upgraded workers do not follow up a short claim at once, so +they can wait for a job settlement or the next `pullInterval` to claim the rest. + +`LOCK TABLE ... IN EXCLUSIVE MODE` requires the `UPDATE`, `DELETE` or `TRUNCATE` privilege on +`claim_lock` (or `MAINTAIN` on PostgreSQL 17 and later), or ownership of the table. If your workers +connect with a different role than the one that runs the migrations, and you grant privileges per +table (for example a one-time `GRANT ... ON ALL TABLES IN SCHEMA duron`, without default +privileges), grant the new table to the worker role after the migration, before you start upgraded +workers. Otherwise every claim fails with SQLSTATE `42501` (insufficient privilege), and no job is +claimed: + +```sql +GRANT UPDATE ON "duron"."claim_lock" TO ; +``` If you manage Duron's tables with your own Drizzle migrations, export `claimLockTable` from `createSchema()` too (see below) and generate a migration: the adapter locks the diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index c98c36b..8edd981 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -226,7 +226,11 @@ process.on('SIGINT', async () => { The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` transaction per fetch. The latest unexpired job for each action name and group key supplies the concurrency limit. The claim first selects, without row locks, the oldest created jobs of each group that fit in its free slots (its limit minus its active jobs), so the older jobs of a full group never keep younger jobs of other groups from being claimed. It then row-locks those candidates, oldest first, with `SKIP LOCKED` until the batch is full. A claim therefore locks only the jobs it claims, not the whole backlog. A candidate that another transaction holds (for example a concurrent cancel) is skipped and still uses its group's slot in that claim. Claimed jobs are returned, and their handlers can start, only after the transaction commits. -Before its claim statement, each claim transaction locks the schema's `claim_lock` table, an empty table that only serves this purpose (`LOCK TABLE ... IN EXCLUSIVE MODE`). The claims of all workers on a schema therefore run one at a time, in the order they asked for the lock. A claim holds the lock for a few milliseconds (about 60 ms with a backlog of 50,000 jobs). Taking the lock does not start the transaction's snapshot, so each claim sees the jobs that the previous claims took: concurrent workers do not claim the same jobs, do not claim more than a group's limit, and do not abort each other's claims. A claim waits at most 1 second for the lock (`SET LOCAL lock_timeout`; the timeout also bounds any other lock wait of the claim transaction). This leaves room for more than 15 claims queued ahead of it even with a large backlog, while a claim whose connection stops responding with the lock held delays other claims by at most 1 second each and stays well within the shutdown budgets. When the wait times out (SQLSTATE `55P03`), the transaction rolls back and the fetch returns no jobs. This is logged at debug level, is not retried, and is not a failure: automatic discovery treats it as an empty claim, without a cooldown. +Before its claim statement, each claim transaction locks the schema's `claim_lock` table, an empty table that only serves this purpose (`LOCK TABLE ... IN EXCLUSIVE MODE`). The claims of all workers on a schema therefore run one at a time, in the order they asked for the lock. A claim holds the lock for a few milliseconds (about 60 ms with a backlog of 50,000 jobs). Taking the lock does not start the transaction's snapshot, so each claim sees the jobs that the previous claims took: concurrent workers do not claim the same jobs, do not claim more than a group's limit, and do not abort each other's claims. A claim waits at most 1 second for the lock (`SET LOCAL lock_timeout`; the timeout also bounds any other lock wait of the claim transaction, for example while DDL locks a job table). This leaves room for more than 15 claims queued ahead of it even with a large backlog. When the wait times out (SQLSTATE `55P03`), the transaction rolls back and the fetch returns no jobs. This is logged at debug level, is not retried, and is not a failure: automatic discovery treats it as an empty claim, without a cooldown. + +A worker can stop between taking the lock and committing, for example when its process is paused, its VM is suspended or its network is lost. While it holds the lock, every claim on the schema waits 1 second and returns no jobs. To bound this, the PostgreSQL adapter's claim transaction also sets `SET LOCAL idle_in_transaction_session_timeout = '5s'`: when the claim session waits more than 5 seconds for its client's next statement, PostgreSQL ends that session (SQLSTATE `25P03`), the claim rolls back with nothing claimed, and the lock is free again. So a stalled worker stops all claims on the schema for about 5 seconds, not until TCP keepalive ends its session (about 2 hours by default). A normal claim waits for its client only for a few round trips, far below 5 seconds; the timer does not run while a statement runs or waits for a lock. A worker whose own event loop is blocked for more than 5 seconds during a claim loses that claim: its fetch fails with a connection error, the jobs stay claimable, and automatic discovery logs the error and waits one `pullInterval`. Both settings are `LOCAL` to the claim transaction and do not change the session. The PGLite adapter has one in-process session, so it does not set the idle timeout. + +Because the claims on a schema run one at a time, the claim lock limits the claim rate of all workers on that schema together to about one claim per claim duration. A claim takes a few milliseconds on a small backlog, so hundreds of claims per second, and about 17 to 57 ms with a backlog of 50,000 created jobs, so about 17 to 60 claims per second (measured on PostgreSQL 16 and 19 for one claim of 10 jobs). Each claim takes up to its batch size of jobs, so the job start rate of the fleet is at most about that rate times the batch size. Larger batches raise this ceiling. When more claims queue than finish within 1 second, the claims at the end of the queue return empty after the lock timeout and are made again later. The `SERIALIZABLE` isolation remains a safety net for claims that do not take the claim lock, such as a worker running an older Duron version. When such a claim and a built-in claim would together exceed a group's limit, PostgreSQL rejects one of them with a serialization failure (SQLSTATE `40001`), either during the claim statement or at `COMMIT`. The rejected transaction claims nothing. A concurrent cancel, delete or time travel of a candidate job can also cause this error, and PostgreSQL tracks predicates coarsely, so conflicts between unrelated groups are possible. @@ -234,7 +238,7 @@ The fetch retries a claim rejected with `40001` up to 5 times. Each retry is a n Limits of this protection: -- Only built-in claims participate. A worker running an older Duron version (which does not take the claim lock), a custom `_fetch` override or direct SQL that claims under `READ COMMITTED` can still exceed a limit when it runs concurrently. During a rolling upgrade, claims of older workers can also conflict (`40001`) with claims of upgraded workers, as before. +- Only built-in claims participate. A worker running an older Duron version (which does not take the claim lock), a custom `_fetch` override or direct SQL that claims under `READ COMMITTED` can still exceed a limit when it runs concurrently. During a rolling upgrade, claims of older workers can also conflict (`40001`) with claims of upgraded workers, as before. Mixing versions is safe: the `SERIALIZABLE` isolation still keeps every claim within its group limits and claims every job once. It can be slower until all workers are upgraded: an older worker's claim row-locks every eligible job until it commits, and upgraded claims skip those jobs (see [Upgrading to the claim lock](/docs/adapters#upgrading-to-the-claim-lock)). - SQL `now()` in a claim is the claim transaction's start time, before any wait for the claim lock, not the claim statement's. It determines which latest jobs supply limits, which active jobs count, and the claimed jobs' `startedAt` and `expiresAt`. - The limit governs admission under the existing latest-job and expiry rules. It is not a lease or fence on running work; expiry, recovery and limit changes keep their existing behavior. - If a claim's commit reply is lost, the outcome is uncertain. Duron does not run or replay that claim; existing liveness and recovery handle a job that was committed. diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index a6273cf..d347167 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -89,10 +89,26 @@ function jsonParam(value: unknown, column: PgColumn): SQL { * How long a claim waits for the claim lock (SQLSTATE 55P03 after it). A claim holds the lock * for one claim statement and its COMMIT: a few ms, about 60 ms at a 50,000-job backlog. So * 1 s covers a queue of more than 15 such claims ahead of it, while a holder that does not - * finish (a stuck connection) costs a claim at most 1 s, well within the 5 s stop budgets. + * finish costs each waiting claim at most 1 s, well within the 5 s stop budgets. The holder + * itself is ended by {@link CLAIM_IDLE_TIMEOUT}. */ const CLAIM_LOCK_TIMEOUT = '1s' +/** + * How long the claim transaction may stay idle between its statements before the server ends + * its session (`idle_in_transaction_session_timeout`, SQLSTATE 25P03). The claim rolls back, + * so nothing is claimed, and the claim lock is free again. Without it, a worker that stops + * between LOCK and COMMIT (process paused, VM suspended, network lost) keeps the lock until + * TCP keepalive ends its session (about 2 h by default), and every claim on the schema returns + * no jobs until then. The timer runs only while the server waits for the client's next + * statement, not while a statement runs or waits for a lock. A normal claim is idle for three + * round trips (after SET, after LOCK, and before COMMIT) of well under 100 ms, so 5 s is + * never reached unless the client stalls for seconds (for example an event loop blocked by + * synchronous work in the same process). Such a claim fails with a connection error instead + * of claiming late. 5 s bounds a fleet-wide stall to the order of the stop budgets. + */ +const CLAIM_IDLE_TIMEOUT = '5s' + /** Retries of a claim after a serialization failure (SQLSTATE 40001). */ const CLAIM_CONFLICT_RETRIES = 5 /** Backoff before retry n (1-based): a random 1..min(cap, base * 2^n) ms ("full jitter"). */ @@ -1403,9 +1419,12 @@ export abstract class PostgresBaseAdapter< * claim committed and sees its jobs, so built-in claims do not conflict with each other * (concurrent claims used to abort each other with 40001). A claim waits at most * {@link CLAIM_LOCK_TIMEOUT} for any lock in its transaction (`SET LOCAL lock_timeout`); - * after it (SQLSTATE 55P03, for example while another claim's connection is stuck) the - * transaction rolls back and the fetch returns no jobs, logged at debug level, without a - * retry: an ordinary empty claim for the caller, not a failure. + * after it (SQLSTATE 55P03, for example while another claim's connection is stuck, or while + * DDL locks a job table) the transaction rolls back and the fetch returns no jobs, logged at + * debug level, without a retry: an ordinary empty claim for the caller, not a failure. The + * claim transaction also sets `idle_in_transaction_session_timeout` + * ({@link CLAIM_IDLE_TIMEOUT}), so the server ends a claim session that stalls with the + * claim lock held, and the other claims continue. * * A serialization failure (SQLSTATE 40001, from the claim statement or COMMIT) always * rolls the whole transaction back, so the claim is retried up to @@ -1429,7 +1448,7 @@ export abstract class PostgresBaseAdapter< if (lockTimeout) { this.logger?.debug( { err: lockTimeout, timeout: CLAIM_LOCK_TIMEOUT }, - 'Claim lock not available (SQLSTATE 55P03): no jobs claimed', + 'A lock of the claim transaction was not available in time (SQLSTATE 55P03): no jobs claimed', ) return [] } @@ -1465,16 +1484,33 @@ export abstract class PostgresBaseAdapter< }) } + /** + * The claim transaction's `idle_in_transaction_session_timeout` ({@link CLAIM_IDLE_TIMEOUT}), + * or `undefined` to not set it (PGlite: one in-process session, so no other claim can wait + * for a stalled one, and the timeout would end its only session). + */ + protected _claimIdleTimeout(): string | undefined { + return CLAIM_IDLE_TIMEOUT + } + /** One claim attempt in its own SERIALIZABLE transaction, after the claim lock. */ private async _claim(batch: number): Promise { let claim: Promise | undefined try { return await this.db.transaction( (tx) => { - // Neither statement takes a snapshot: the claim statement's snapshot begins after - // the lock is granted. + // No statement before the claim statement takes a snapshot: its snapshot begins + // after the lock is granted. Both settings are LOCAL to this transaction. + const idleTimeout = this._claimIdleTimeout() claim = tx .execute(sql.raw(`SET LOCAL lock_timeout = '${CLAIM_LOCK_TIMEOUT}'`)) + .then(() => + idleTimeout + ? tx.execute( + sql.raw(`SET LOCAL idle_in_transaction_session_timeout = '${idleTimeout}'`), + ) + : undefined, + ) .then(() => tx.execute(sql`LOCK TABLE ${this.tables.claimLockTable} IN EXCLUSIVE MODE`)) .then(() => tx.execute(this._claimQuery(batch))) .then((rows) => this._map(rows)) diff --git a/packages/duron/src/adapters/postgres/pglite.ts b/packages/duron/src/adapters/postgres/pglite.ts index d3137cf..bce0099 100644 --- a/packages/duron/src/adapters/postgres/pglite.ts +++ b/packages/duron/src/adapters/postgres/pglite.ts @@ -52,6 +52,14 @@ export class PGLiteAdapter extends PostgresBaseAdapter { } } + /** + * No idle timeout for claims: PGlite has one in-process session, so no other claim can wait + * for a stalled claim, and when the timeout fires, the engine stops answering. + */ + protected override _claimIdleTimeout(): string | undefined { + return undefined + } + protected override _canCleanup(): boolean { return !this.db.$client.closed && super._canCleanup() } diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 0b6f9ea..580f728 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -64,7 +64,7 @@ function driverOf(adapter: PostgresAdapter): postgres.Sql { async function withholdReplyFrom( relay: PruneRelay, adapter: PostgresAdapter, - command: 'BEGIN' | 'COMMIT' | 'ROLLBACK', + command: 'BEGIN' | 'COMMIT' | 'ROLLBACK' | 'LOCK TABLE', ): Promise { const pid = Number((await driverOf(adapter)`SELECT pg_backend_pid() AS pid`)[0]!['pid']) let withholding = false @@ -991,7 +991,9 @@ suite('Native PostgreSQL claim admission', () => { expect(waited).toBeLessThan(3_000) expect(entries.filter((entry) => entry['level'] >= 50)).toEqual([]) expect(entries.filter((entry) => /claim conflict/.test(entry['msg']))).toEqual([]) - const timeouts = entries.filter((entry) => /Claim lock not available/.test(entry['msg'])) + const timeouts = entries.filter((entry) => + /lock of the claim transaction was not available/.test(entry['msg']), + ) expect(timeouts.map((entry) => [entry['level'], entry['err']['code']])).toEqual([ [20, '55P03'], ]) @@ -1010,6 +1012,64 @@ suite('Native PostgreSQL claim admission', () => { } }, 30_000) + it('ends a claim session that stalls with the claim lock held, so other claims continue', async () => { + const db = await claimDatabase() + const relay = new PruneRelay() + const stalledAdapter = db.adapter('claim-a', 1, relay.port) + // One session, so SHOW below reads the session that ran the claims. + const b = db.adapter('claim-b', 1) + let stalled: Promise> | undefined + try { + await stalledAdapter.start() + await b.start() + const [id] = await createJobs(b, 1, 1) + // A stalled claimant (paused process, lost network): the server grants claim-a the + // claim lock, but claim-a never gets the reply, so it never sends its claim statement + // or COMMIT. + const pid = await withholdReplyFrom(relay, stalledAdapter, 'LOCK TABLE') + stalled = observe(stalledAdapter.fetch({ batch: 1 })) + await eventually(async () => { + const [row] = await db.admin`SELECT state FROM pg_stat_activity WHERE pid = ${pid}` + return row?.['state'] === 'idle in transaction' + }) + const locked = performance.now() + // Each claim waits 1 s for the lock (lock_timeout) and returns empty, until the server + // ends the stalled session (idle_in_transaction_session_timeout 5 s) and frees the lock. + let empty = 0 + let claimed: Array<{ id: string }> = [] + while (claimed.length === 0) { + if (performance.now() - locked > 10_000) throw new Error('The claim lock stayed held') + claimed = await b.fetch({ batch: 1 }) + if (claimed.length === 0) empty++ + } + const waited = performance.now() - locked + expect(claimed.map((job) => job.id)).toEqual([id!]) + expect(empty).toBeGreaterThanOrEqual(3) + expect(waited).toBeGreaterThanOrEqual(4_500) + expect(waited).toBeLessThan(7_000) + // The server ended the stalled session with SQLSTATE 25P03 (the frame never reached + // claim-a); its fetch fails with the closed connection and claimed nothing. + await eventually(() => + relay.held.some(({ frame }) => frame[0] === 0x45 && frame.includes('25P03')), + ) + expect(rejection(await stalled)).toBeDefined() + expect(await db.activeCount()).toBe(1) + // Both settings are LOCAL to the claim transactions: the session keeps its defaults. + const [settings] = await driverOf(b)` + SELECT current_setting('lock_timeout') AS lock, + current_setting('idle_in_transaction_session_timeout') AS idle` + expect(settings).toEqual({ lock: '0', idle: '0' }) + } catch (error) { + db.recordFailure(error) + throw error + } finally { + relay.flush() + await relay.close() + await stalled + await db.cleanup() + } + }, 30_000) + it('does not pause Client discovery after a claim lock timeout', async () => { const db = await claimDatabase() const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 10_000 } }) diff --git a/packages/duron/test/worker-discovery.test.ts b/packages/duron/test/worker-discovery.test.ts index 72ddf8c..cb9c2d0 100644 --- a/packages/duron/test/worker-discovery.test.ts +++ b/packages/duron/test/worker-discovery.test.ts @@ -568,8 +568,8 @@ for (const factory of factories) { fetch.releaseAll() await Bun.sleep(600) // Both claims return empty (not full). The empty hinted claim is retried after - // 10–50 ms and once more after 50–250 ms (peers' claims could have held the rows); - // a third empty claim in a row ends it. + // 10–50 ms and once more after 50–250 ms (for example the claim lock was not + // available in time); a third empty claim in a row ends it. expect(fetch.batches).toEqual([4, followUp, followUp, followUp]) expect(fetch.maxActive).toBe(1) } finally { @@ -581,6 +581,64 @@ for (const factory of factories) { ) } + it( + 'does not follow up a short claim that returned jobs; their settlement looks again (held)', + async () => { + const instance = await factory.create() + let client: Client | null = null + const fetch = holdFetch(instance.adapter) + const finish = Promise.withResolvers() + try { + const action = defineAction()({ + name: 'hinted', + handler: async () => { + await finish.promise + return {} + }, + }) + client = new Client({ + database: instance.adapter, + actions: { hinted: action }, + syncPattern: 'push', + pullInterval: 60_000, + batchSize: 4, + recoverJobsOnStart: false, + logger: 'silent', + }) + expect(await client.start()).toBe(true) + await eventually(() => fetch.held === 1, 'startup pass is held') + for (let i = 0; i < 3; i++) { + instance.adapter.emit('job-available', { jobId: `hint-${i}` }) + } + fetch.releaseNext() + await eventually(() => fetch.held === 1, 'the claim for three hints is held') + // One claimable job for three hints, created without a hint of its own. + const dropped = dropAvailabilityHints(instance.adapter) + const jobId = await client.runAction('hinted', {}) + expect(dropped()).toBe(1) + fetch.releaseNext() + await eventually( + async () => (await status(instance.adapter, jobId)) === 'active', + 'the short claim takes the job', + ) + await eventually(() => fetch.active === 0, 'the short claim settles') + await Bun.sleep(300) + // Claims run one at a time (claim lock), so the short claim saw every claimable job: + // no follow-up (it came after 10–50 ms before the claim lock). + expect(fetch.batches).toEqual([4, 3]) + // The claim left demand uncovered: its job's settlement looks again. + finish.resolve() + await eventually(() => fetch.batches.length === 3, 'the settlement wakes discovery') + expect(fetch.batches).toEqual([4, 3, 4]) + } finally { + finish.resolve() + fetch.releaseAll() + await closeInstance(client, instance) + } + }, + TEST_MS, + ) + it( 'does not retry an empty claim for a lone hint, and stop cancels a pending retry (held)', async () => { From 718b13ef9649470a8b0d5aaa43f06c6d8471b3b0 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 11:22:09 -0300 Subject: [PATCH 03/20] feat(stop): shutdownTimeout option; graceful stop releases unfinished jobs - Client option shutdownTimeout (ms, integer 1..2147483647, default 5000) sets the budget of every stop phase (lifecycle) of the Client's adapter; stop errors now read "exceeded the shutdown timeout (N ms)". - BREAKING: stop() releases instead of cancelling. Running handlers are aborted; after the handler settles, a resolved handler completes its job, otherwise the job is released (Adapter.releaseJob: created, owner, start and expiry cleared, job-available notification). Steps keep their stored status like recovery (completed reused; active re-run, retries_count back to 0). Claimed-but-unstarted jobs (queued, or claim reply after stop) are released too. Explicit cancelJob still cancels; a job whose handler awaits stop() is cancelled so it does not stop the next worker. A handler that never settles within the budget stays active for recovery. - Default Adapter._releaseJob returns false (custom adapters unchanged). - Tests: shutdown-release (PGlite + native, multi-worker handoff), and budget-bound tests use a short shutdownTimeout (11 files 355 s -> 155 s). - Docs: shutdownTimeout, stop() release semantics + breaking note, lifecycle phases, custom adapters. --- packages/docs/content/docs/adapters.mdx | 4 +- packages/docs/content/docs/client-api.mdx | 32 +- packages/docs/content/docs/multi-worker.mdx | 22 +- packages/duron/src/action-job.ts | 86 ++++ packages/duron/src/action-manager.ts | 38 +- packages/duron/src/adapters/adapter.ts | 44 ++ packages/duron/src/adapters/postgres/base.ts | 36 +- .../duron/src/adapters/postgres/prune-lock.ts | 2 +- packages/duron/src/adapters/schemas.ts | 6 + packages/duron/src/client.ts | 29 +- packages/duron/src/lifecycle.ts | 56 ++- packages/duron/src/local-cancellation.ts | 5 + packages/duron/src/step-manager.ts | 14 +- packages/duron/src/worker-discovery.ts | 14 +- packages/duron/test/claim-isolation.test.ts | 17 +- packages/duron/test/lifecycle-budgets.test.ts | 12 +- .../duron/test/lifecycle-close-retry.test.ts | 2 + packages/duron/test/lifecycle-sql.test.ts | 10 + packages/duron/test/lifecycle.test.ts | 12 + .../duron/test/local-cancellation.test.ts | 38 +- packages/duron/test/notifications.test.ts | 8 +- packages/duron/test/prune-bootstrap.test.ts | 18 +- packages/duron/test/prune-ownership.test.ts | 19 +- packages/duron/test/prune-replies.test.ts | 4 +- packages/duron/test/recover-snapshot.test.ts | 3 + packages/duron/test/shutdown-release.test.ts | 384 ++++++++++++++++++ packages/duron/test/wait-lifecycle.test.ts | 13 +- 27 files changed, 856 insertions(+), 72 deletions(-) create mode 100644 packages/duron/test/shutdown-release.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 3ccb8eb..0d0ca1f 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -106,7 +106,7 @@ A bootstrap failure of the first client, an uncertain or malformed coordination **Exclusion requires a healthy coordination session.** After its loss, another scheduler can acquire the lock while an already-issued DELETE continues on the old owner's query pool. Observed loss gates subsequent library-controlled scheduled SQL, but it does not cancel issued SQL or arbitrary override code. There is no fencing, rollback, instantaneous loss detection, or failure-proof mutual exclusion promise, and no ordinary prune SQL/pass deadline. -Stop clears the timer immediately and uses the shared lifecycle's startup-settlement, admitted-work, database-cleanup and owned-close budgets. Healthy final cleanup returns the reservation once after settled work and confirmed unlock, then closes the isolated client. Uncertain ownership is not returned as reusable. A pending/rejected return cannot consume the independent close opportunity; a stop that joins an existing fault close does not restart its five-second observer. Observer expiry and fulfilled driver `end()` alone are not proof of physical release. Incomplete cleanup remains reported and tracked for later safe completion rather than being canceled or silently declared successful. +Stop clears the timer immediately and uses the shared lifecycle's startup-settlement, admitted-work, database-cleanup and owned-close budgets. Healthy final cleanup returns the reservation once after settled work and confirmed unlock, then closes the isolated client. Uncertain ownership is not returned as reusable. A pending/rejected return cannot consume the independent close opportunity; a stop that joins an existing fault close does not restart its observer budget (`shutdownTimeout`). Observer expiry and fulfilled driver `end()` alone are not proof of physical release. Incomplete cleanup remains reported and tracked for later safe completion rather than being canceled or silently declared successful. ## Database Schema @@ -397,6 +397,8 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). For its own recoveries, the Client tells the built-in `_recoverJobs` which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom `_recoverJobs` keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A direct `recoverJobs()` call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs. +A graceful `Client.stop()` returns the jobs it did not finish to the queue through `releaseJob()`, which calls `_releaseJob({ jobId })`. The built-in adapters set the job back to `created` (start, expiry and owner cleared) when it is still `active`, owned by this adapter's id and not expired, and keep its steps. The default `_releaseJob` of the `Adapter` class releases nothing and returns `false`: with a custom adapter that does not override it, the unfinished jobs stay `active` until recovery requeues them, as before releases existed. + ## Best Practices ### Use PGLite for Development diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index 7f527a3..a14b4fe 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -219,6 +219,16 @@ Recovery checks for: } ``` +### `shutdownTimeout` + +**Optional.** Budget in milliseconds of each phase of [`stop()`](#stop): settling a startup that is still running, draining admitted work (running handlers and steps, their final writes, and the release of the jobs that did not finish), database cleanup, and closing the adapter's connections. A phase that exceeds it makes `stop()` reject. It applies to this Client's adapter. An integer from `1` to `2147483647`; other values make the constructor throw. Defaults to `5000` (5 seconds). + +```ts +{ + shutdownTimeout: 10_000, // give running jobs up to 10 seconds to finish or release +} +``` + ### `logger` **Optional.** Logger instance or log level. Defaults to `'error'`. @@ -269,13 +279,27 @@ await client.start() ### `stop()` -Stop the Duron instance. Stops worker discovery, aborts all running jobs, waits for queues to drain, and stops the database. +Stop the Duron instance. Stops worker discovery, aborts all running jobs, returns the jobs that did not finish to the queue, waits for that work to drain, and stops the database. ```ts await client.stop() ``` -`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. Like every running job, the calling job is aborted and ends `cancelled`. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. The exclusion covers only the calling handler or step and the steps that enclose it. It never covers a sibling step, and it never crosses a job boundary: when job A enqueues job B and B calls `stop()`, the drain still waits for A's handler. +A graceful stop releases unfinished jobs instead of cancelling them: + +- Each running handler is aborted: its steps' `signal` aborts with an `ActionCancelError`. Once the handler settles, a handler that still resolves completes its job normally (its output is validated). A handler that rejects, for example because a step honored the abort, returns its job to the queue. +- Claimed jobs that have not started (queued behind `actionConcurrencyLimit`, or claimed while the stop began) are returned to the queue too. +- A returned job is `created` again, without an owner, start or expiry, and a `job-available` notification is sent, so any worker can claim it. Its steps are kept, as [recovery](/docs/multi-worker#job-recovery) keeps them: the next run reuses completed steps and runs again the steps that were running or waiting for a retry, whose retry count starts again at 0. Jobs have no attempt counter, so a release does not count as a failed attempt. +- An explicit `cancelJob()` still cancels: a job cancelled before or during the stop ends `cancelled`, not released. +- The drain waits for the handlers within [`shutdownTimeout`](#shutdowntimeout). A handler that does not settle in time is not released: the stop rejects, the job stays `active`, and recovery requeues it once this Client's liveness is gone (another worker's periodic recovery, or this `id`'s next startup). + + + Breaking change: before, `stop()` cancelled every running job, and its queued jobs stayed claimed + until recovery. Now they return to the queue and run again on a worker. Make handlers idempotent + across a restart, or call `cancelJob()` before `stop()` for jobs that must not run again. + + +`stop()` can also be called, and awaited, from inside a handler or a step (for example a job that shuts its worker down). The drain then does not wait for that handler or step, which is waiting for `stop()` itself; it still waits for everything else, including the calling job's own abort and cancellation write. The calling job is aborted and ends `cancelled`, not released, so it does not stop the next worker that would claim it. Code that runs in it after `stop()` resolves cannot issue database calls. The exclusion follows the handler's async context, not the `await`: a `stop()` started from a timer, callback or fire-and-forget task that a running handler or step created also excludes that handler or step from the drain, even if nothing awaits `stop()`. To stop and still wait for a handler, call `stop()` from outside it. The exclusion covers only the calling handler or step and the steps that enclose it. It never covers a sibling step, and it never crosses a job boundary: when job A enqueues job B and B calls `stop()`, the drain still waits for A's handler. ## Job Methods @@ -302,7 +326,7 @@ const jobId = await client.runAction('sendEmail', { Manually fetch and process jobs from the database. -Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`. If the Client did not start (`start()` resolved `false`, for example because a custom adapter's `start()` declined), the call rejects instead of waiting. Direct `client.database.fetch()` calls are outside this coordination. +Each call keeps its own batch and returns the jobs it actually claimed, after its claim (not after the handlers finish). Calls are served one at a time together with automatic discovery, in arrival order, so a call can wait behind a running discovery, a due recovery (see `recoverJobsInterval`) or a failure cooldown. A failed call rejects with the original error and is not retried. Calls still waiting when `stop()` begins reject; a call whose claim was already issued returns its jobs, but no handler starts after `stop()`: those jobs are returned to the queue. If the Client did not start (`start()` resolved `false`, for example because a custom adapter's `start()` declined), the call rejects instead of waiting. Direct `client.database.fetch()` calls are outside this coordination. ```ts const jobs = await client.fetch({ @@ -679,7 +703,7 @@ controller.abort() - Each periodic pass considers at most ten IDs in round-robin order. Initial/hint checks share a four-actual-chain limit and one chain per ID. No waits means no periodic wait timer. These are work bounds, not completion or query-rate guarantees. - Expired results are discarded. Caller cancellation and read-observer expiry do **not** cancel SQL or release actual capacity. Four unresolved chains can block all further checks, including queued initial reads. - Retained results must remain readable long enough to be observed. Pruned output cannot be reconstructed; there is no stronger SQL snapshot or execution-generation guarantee. -- Stop settles pending waits locally and drains actual reads/transaction cleanup under the existing shared five-second drain budget. `waitReadTimeout` does not extend or reset any lifecycle phase. +- Stop settles pending waits locally and drains actual reads/transaction cleanup under the shared drain budget (`shutdownTimeout`, 5 seconds by default). `waitReadTimeout` does not extend or reset any lifecycle phase. ### `getActions()` diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index 8edd981..e0d3003 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -339,20 +339,20 @@ There is no ordinary notification deadline or background delivery queue. A stuck ## Lifecycle and Shutdown -`client.stop()` closes admission immediately: it cancels scheduled heartbeat/discovery/prune timers, discards pending automatic discovery, rejects queued `client.fetch()` calls that have not started, disables new event-driven work, settles pending waits with `null`, and requests action cancellation. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. +`client.stop()` closes admission immediately: it cancels scheduled heartbeat/discovery/prune timers, discards pending automatic discovery, rejects queued `client.fetch()` calls that have not started, disables new event-driven work, settles pending waits with `null`, and aborts running handlers. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. Jobs that do not finish are returned to the queue (`created`, without an owner) and announced with a `job-available` notification, so another worker claims them: a handler that still resolves after the abort completes its job, the others, and the claimed jobs that did not start, are released. See [`stop()`](/docs/client-api#stop). It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. -Client and Adapter share four internal shutdown budgets. Each budget applies to the whole phase, not separately to nested calls or individual resources: +Client and Adapter share four shutdown phases, each with the budget set by the Client's [`shutdownTimeout`](/docs/client-api#shutdowntimeout) option (5 seconds by default). Each budget applies to the whole phase, not separately to nested calls or individual resources: -| Phase | Budget | Work | -| ------------------- | --------- | ----------------------------------------------------------------------- | -| Startup settlement | 5 seconds | Observe already-issued initialization; skip remaining stages where safe | -| Admitted-work drain | 5 seconds | Observe actual ordinary operations, callbacks and action/step work | -| Database cleanup | 5 seconds | Attempt independent listener and liveness cleanup while SQL is usable | -| Owned close | 5 seconds | Close owned query/listener clients or the PGLite engine | +| Phase | Work | +| ------------------- | ---------------------------------------------------------------------------------------- | +| Startup settlement | Observe already-issued initialization; skip remaining stages where safe | +| Admitted-work drain | Observe actual ordinary operations, callbacks and action/step work, and the job releases | +| Database cleanup | Attempt independent listener and liveness cleanup while SQL is usable | +| Owned close | Close owned query/listener clients or the PGLite engine | -Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately twenty seconds when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee. +Empty phases are skipped. Later cleanup phases still receive their opportunity after an earlier failure or timeout. The planned asynchronous wait is approximately four budgets (twenty seconds by default) when all phases are needed, not a hard elapsed-time or natural-process-exit guarantee. A job whose handler does not settle within the drain budget is not released: it stays `active`, and recovery requeues it once this worker's liveness row is gone. -After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls `stop()` itself is not waited for by the drain (it waits for `stop()`); the rest of its job, including the abort and cancellation write, still is. This follows the async context: a `stop()` from a timer or fire-and-forget task started by a running handler or step also excludes that handler or step, whether or not it awaits `stop()`. +After the drain boundary, no new ordinary SQL may begin. Already-issued SQL is not assumed cancelled. A successful mutation that reaches notification submission too late keeps its successful result; the forbidden hint is omitted and logged as delivery unconfirmed. User JavaScript and external side effects are not forcibly terminated or fenced by these in-process gates. A handler or step that calls `stop()` itself is not waited for by the drain (it waits for `stop()`); the rest of its job, including the abort and cancellation write, still is. Such a job is cancelled, not released, so that it does not stop the next worker. This follows the async context: a `stop()` from a timer or fire-and-forget task started by a running handler or step also excludes that handler or step, whether or not it awaits `stop()`. A timeout or cleanup failure rejects `stop()`. A sole error is preserved; multiple failures use `AggregateError`. Log and inspect the rejection rather than treating it as proof that resources closed or work stopped. Concurrent stop callers share cleanup. A later stop joins pending resource operations or retries only safe unfinished cleanup; it does not replay completed application work or allocate a replacement connection. Failed or withheld liveness deletion cannot be repaired after SQL has closed. A failed explicit unsubscribe remains an error for that attempt even if owned close subsequently releases its resources. @@ -398,7 +398,7 @@ Keep `heartbeatTimeout` at least 3x `heartbeatInterval` to tolerate occasional m - **Separate dashboard and workers**: Run dashboard/server in a separate process to avoid resource competition - **Monitor worker health**: Use process managers (PM2, systemd, etc.) to restart failed workers -- **Graceful shutdown**: Handle `SIGINT`/`SIGTERM`, await `client.stop()`, and report cleanup failures. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence. +- **Graceful shutdown**: Handle `SIGINT`/`SIGTERM`, await `client.stop()`, and report cleanup failures. Unfinished jobs return to the queue for the other workers; make steps honor their `signal` so that handlers end within `shutdownTimeout`, and keep the orchestrator's grace period (for example Kubernetes' `terminationGracePeriodSeconds`) above the stop's phases. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence. ### Scaling diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index 1519424..e10053c 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -50,6 +50,12 @@ export class ActionJob> { #done: Promise #resolve: (() => void) | null = null #handler: Promise = Promise.resolve() + /** The action handler was called (a release can only complete a job whose handler ran). */ + #handlerInvoked = false + /** An explicit cancellation (cancelJob) aborted the job: it ends cancelled. */ + #cancelled = false + /** A graceful stop aborted the job: it is returned to the queue (see `release`). */ + #releasing = false #jobSpan!: Span // ============================================================================ @@ -161,6 +167,7 @@ export class ActionJob> { throw new ActionCancelError(this.#action.name, this.#job.id) } this.#abortController.signal.throwIfAborted() + this.#handlerInvoked = true return this.#action.handler(ctx) }), // User code: a stop() it awaits is excluded from the drain (see Lifecycle.stop). @@ -212,6 +219,10 @@ export class ActionJob> { // Wait for step manager to drain (all steps to settle) await this.#stepManager.drain() + if (this.#releasing && !this.#cancelled && !isTimeoutError(error)) { + return await this.#finishReleased() + } + if ( isCancelError(error) || (error instanceof Error && error.name === 'AbortError' && isCancelError(error.cause)) @@ -273,15 +284,90 @@ export class ActionJob> { * Clears the timeout and aborts the action handler. */ cancel() { + this.#cancelled = true this.#clear() const cancelError = new ActionCancelError(this.#action.name, this.#job.id) this.#abortController.abort(cancelError) } + /** + * Graceful stop: abort the handler like `cancel()` (its signal's reason is an + * ActionCancelError), but return the job to the queue instead of cancelling it, unless its + * handler still completes (see `#finishReleased`). A later `cancel()` still cancels it. + */ + release() { + this.#releasing = true + this.#stepManager.release() + this.#clear() + if (!this.#abortController.signal.aborted) { + this.#abortController.abort(new ActionCancelError(this.#action.name, this.#job.id)) + } + } + // ============================================================================ // Private Methods // ============================================================================ + /** + * End a job that a graceful stop aborted. Waits for its raw handler: a handler that still + * resolves completes the job normally (output validated); one that rejects, or a failed + * completion, returns the job to the queue (`releaseJob`). The steps already kept their + * stored status (see StepManager.release). An explicit `cancel()` meanwhile cancels it. A + * handler that awaits `stop()` itself cannot settle before stop does: that job is + * cancelled, as before, so that it does not stop the next worker that would claim it. + */ + async #finishReleased(): Promise { + const lifecycle = lifecycleFor(this.#database) + const handled = await lifecycle.settledOrExcluded(this.#handler) + let outcome: 'complete' | 'release' | 'cancel' = 'release' + let result: unknown + if (handled === 'excluded' || this.#cancelled) { + outcome = 'cancel' + } else { + const settled = await Promise.allSettled([this.#handler]) + if (this.#handlerInvoked && settled[0].status === 'fulfilled') { + outcome = 'complete' + result = settled[0].value ?? null + } + } + if (outcome === 'complete') { + try { + if (this.#action.output) result = await validateSchema(this.#action.output, result) + if (await this.#database.completeJob({ jobId: this.#job.id, output: result })) { + this.#logger.debug( + { jobId: this.#job.id, actionName: this.#action.name }, + '[ActionJob] Action finished executing during stop', + ) + this.#jobSpan.setStatus({ code: SpanStatusCode.OK }) + this.#jobSpan.end() + return + } + } catch (error) { + this.#logger.warn( + { error, jobId: this.#job.id, actionName: this.#action.name }, + '[ActionJob] Job not completed during stop; releasing it', + ) + } + } + if (outcome === 'cancel') { + this.#logger.warn( + { jobId: this.#job.id, actionName: this.#action.name }, + '[ActionJob] Job cancelled', + ) + await this.#database.cancelJob({ jobId: this.#job.id }) + this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job cancelled' }) + this.#jobSpan.end() + return + } + this.#logger.info( + { jobId: this.#job.id, actionName: this.#action.name }, + '[ActionJob] Job released to the queue on stop', + ) + await this.#database.releaseJob({ jobId: this.#job.id }) + this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job released' }) + this.#jobSpan.end() + } + /** * Clear the timeout timer. */ diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index 646363a..c6405ed 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -73,7 +73,11 @@ export class ActionManager> { this.#unstarted.delete(entry) let settlement: (() => Promise) | undefined try { - if (this.#stopped || !lifecycleFor(this.#database).accepting) return + if (this.#stopped || !lifecycleFor(this.#database).accepting) { + // Stop began before this claimed job started: return it to the queue. + settlement = () => this.#releaseUnstarted(entry.job.id) + return + } // A root context: the queue can start this job from another job's settlement. await lifecycleFor(this.#database).run( () => @@ -128,11 +132,12 @@ export class ActionManager> { } /** - * Cancel all active jobs. + * Graceful stop of all active jobs: abort their handlers and return the jobs that do not + * complete to the queue (see ActionJob.release). */ - abortAll(): void { + releaseAll(): void { for (const actionJob of this.#activeJobs.values()) { - actionJob.cancel() + actionJob.release() } } @@ -157,12 +162,13 @@ export class ActionManager> { } this.#stopped = true - this.abortAll() + this.releaseAll() const drained = this.#queue.killAndDrain() - // Killed queue entries never start a handler; their local accounting settles now, or once - // the cancellation writes of a suppressed entry settle. Killed push promises never settle. + // Killed queue entries never start a handler: they are returned to the queue. Their local + // accounting settles once that write and the cancellation writes of a suppressed entry + // settle. Killed push promises never settle. for (const entry of this.#unstarted) { - entry.settle(this.#cancellation.consumeQueued(entry.job.id)) + entry.settle(this.#releaseUnstarted(entry.job.id)) } this.#unstarted.clear() await drained @@ -175,6 +181,22 @@ export class ActionManager> { // Private Methods // ============================================================================ + /** + * A claimed job that will not start because stop began: return it to the queue, and settle + * its queued state and any cancellation flag. A job with a pending explicit cancellation is + * left to that cancellation. Never rejects. + */ + #releaseUnstarted(jobId: string): Promise { + if (this.#cancellation.cancelling(jobId)) return this.#cancellation.consumeQueued(jobId) + const released = this.#database.releaseJob({ jobId }).then( + () => undefined, + (error: unknown) => { + this.#logger.warn({ error, jobId }, `[ActionManager] Could not release job ${jobId}`) + }, + ) + return Promise.all([released, this.#cancellation.consumeQueued(jobId)]).then(() => undefined) + } + /** * Execute a job by creating an ActionJob and running it. * diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index 71994aa..bc209d8 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -42,6 +42,7 @@ import { NumberResultSchema, PruneArchiveOptionsSchema, RecoverJobsOptionsSchema, + ReleaseJobOptionsSchema, RetryJobOptionsSchema, TimeTravelJobOptionsSchema, } from './schemas.js' @@ -71,6 +72,7 @@ import type { JobStepStatusResult, PruneArchiveOptions, RecoverJobsOptions, + ReleaseJobOptions, RetryJobOptions, TimeTravelJobOptions, } from './schemas.js' @@ -106,6 +108,7 @@ export type { JobStepStatusResult, PruneArchiveOptions, RecoverJobsOptions, + ReleaseJobOptions, RetryJobOptions, SortOrder, TimeTravelJobOptions, @@ -342,6 +345,35 @@ export abstract class Adapter extends EventEmitter { }) } + /** + * Return an active job of this adapter's client id to the queue (status `created`, its + * start, expiry and owner cleared), so any worker can claim it again. Its steps are kept, + * as recovery keeps them: completed steps are reused and active steps run again. A graceful + * `Client.stop()` releases the jobs it did not finish. An expired job is not released + * (recovery archives it as failed). + * + * @returns Promise resolving to `true` if released, `false` otherwise + */ + async releaseJob(options: ReleaseJobOptions): Promise { + return this.#lifecycle.run(async () => { + try { + if (!(await this.start()) && !this.#lifecycle.isStarted(this)) { + throw new Error('Adapter is not accepting work') + } + const parsedOptions = ReleaseJobOptionsSchema.parse(options) + const result = await this._releaseJob(parsedOptions) + const success = BooleanResultSchema.parse(result) + if (success) { + await this._notify('job-available', { jobId: parsedOptions.jobId }) + } + return success + } catch (error) { + this.#logger?.error(error, 'Error in Adapter.releaseJob()') + throw error + } + }) + } + /** * Retry a failed job by creating a copy of it with status 'created' and cleared output/error. * @@ -662,6 +694,18 @@ export abstract class Adapter extends EventEmitter { */ protected abstract _cancelJob(options: CancelJobOptions): Promise + /** + * Internal method to return an active job of this adapter's client id to the queue (see + * `releaseJob`). The default releases nothing and returns `false`: the job stays active and + * recovery requeues it once this client's liveness is gone. Override it in a custom adapter. + * + * @param options - Validated job release options + * @returns Promise resolving to `true` if released, `false` otherwise + */ + protected async _releaseJob(_options: ReleaseJobOptions): Promise { + return false + } + /** * Internal method to retry a failed job by creating a copy of it with status 'created' and cleared output/error. * diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index d347167..2bc4221 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -59,6 +59,7 @@ import { type JobStepStatusResult, type PruneArchiveOptions, type RecoverJobsOptions, + type ReleaseJobOptions, type RetryJobOptions, type TimeTravelJobOptions, } from '../adapter.js' @@ -89,7 +90,7 @@ function jsonParam(value: unknown, column: PgColumn): SQL { * How long a claim waits for the claim lock (SQLSTATE 55P03 after it). A claim holds the lock * for one claim statement and its COMMIT: a few ms, about 60 ms at a 50,000-job backlog. So * 1 s covers a queue of more than 15 such claims ahead of it, while a holder that does not - * finish costs each waiting claim at most 1 s, well within the 5 s stop budgets. The holder + * finish costs each waiting claim at most 1 s, well within the default 5 s stop budgets. The holder * itself is ended by {@link CLAIM_IDLE_TIMEOUT}. */ const CLAIM_LOCK_TIMEOUT = '1s' @@ -105,7 +106,7 @@ const CLAIM_LOCK_TIMEOUT = '1s' * round trips (after SET, after LOCK, and before COMMIT) of well under 100 ms, so 5 s is * never reached unless the client stalls for seconds (for example an event loop blocked by * synchronous work in the same process). Such a claim fails with a connection error instead - * of claiming late. 5 s bounds a fleet-wide stall to the order of the stop budgets. + * of claiming late. 5 s bounds a fleet-wide stall to the order of the default stop budgets. */ const CLAIM_IDLE_TIMEOUT = '5s' @@ -1003,6 +1004,37 @@ export abstract class PostgresBaseAdapter< }) } + /** + * Internal method to return an active job of this client id to the queue: the requeue of + * recovery (status `created`; start, expiry, finish, output and error cleared), with the + * owner cleared too. Its steps are kept, so a new run reuses completed steps and runs + * active ones again, as after recovery. An expired job is left for recovery, which archives + * it as failed. One statement: the row lock orders it with cancel, complete and fail. + * + * @returns Promise resolving to `true` if released, `false` otherwise + */ + protected override async _releaseJob({ jobId }: ReleaseJobOptions): Promise { + const rows = this._map( + await this.db.execute<{ id: string }>(sql` + UPDATE ${this.tables.jobsActiveTable} j + SET status = ${JOB_STATUS_CREATED}, + started_at = NULL, + expires_at = NULL, + finished_at = NULL, + output = NULL, + error = NULL, + client_id = NULL, + updated_at = now() + WHERE j.id = ${jobId} + AND j.status = ${JOB_STATUS_ACTIVE} + AND j.client_id = ${this.id} + AND (j.expires_at IS NULL OR j.expires_at > now()) + RETURNING j.id + `), + ) + return rows.length > 0 + } + /** * Internal method to retry a completed, cancelled, or failed job by creating a copy of it with status 'created' and cleared output/error. * Uses SELECT FOR UPDATE to prevent concurrent retries from creating duplicate jobs. diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 41204f3..5d70225 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -204,7 +204,7 @@ export class PostgresPruneLock { * ran a statement and never requested key 42, and this lock never uses its client again * (`#uncertain` is set and the setup is not repeated). Give the connection back so that the * fault close's `end()` closes it at once: a reserved connection would stay open until the - * end timeout destroys it, and the close would fail its five-second budget. The client is + * end timeout destroys it, and the close would fail its budget (`shutdownTimeout`, 5 s by default). The client is * ending, so postgres.js does not lease the connection again. * `#physicallyClosed` stays true from the bootstrap session's close, although a new * connection can be open here. The close is still confirmed only after that connection diff --git a/packages/duron/src/adapters/schemas.ts b/packages/duron/src/adapters/schemas.ts index a99cb65..326c4f5 100644 --- a/packages/duron/src/adapters/schemas.ts +++ b/packages/duron/src/adapters/schemas.ts @@ -199,6 +199,11 @@ export const CancelJobOptionsSchema = z.object({ jobId: z.string(), }) +export const ReleaseJobOptionsSchema = z.object({ + /** The ID of the active job (owned by this adapter's client id) to return to the queue */ + jobId: z.string(), +}) + export const RetryJobOptionsSchema = z.object({ /** The ID of the job to retry */ jobId: z.string(), @@ -368,6 +373,7 @@ export type FetchOptions = z.infer export type CompleteJobOptions = z.infer export type FailJobOptions = z.infer export type CancelJobOptions = z.infer +export type ReleaseJobOptions = z.infer export type RetryJobOptions = z.infer export type DeleteJobOptions = z.infer export type DeleteJobsOptions = z.infer diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 9565644..7b39f81 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -25,7 +25,7 @@ import type { import type { JobStatusResult, JobStepStatusResult } from './adapters/schemas.js' import { JOB_STATUS_CANCELLED, JOB_STATUS_FAILED, type JobStatus } from './constants.js' import { WaitReadFailedError, WaitReadTimeoutError } from './errors.js' -import { type Lifecycle, lifecycleFor } from './lifecycle.js' +import { DEFAULT_SHUTDOWN_TIMEOUT, type Lifecycle, lifecycleFor } from './lifecycle.js' import { type FetchToken, LocalCancellation } from './local-cancellation.js' import { markClientAdapter, recoverJobsForClient, usedByClient } from './recovery-scope.js' import { validateSchema } from './standard-schema.js' @@ -306,6 +306,17 @@ export interface BaseOptionsInput { * @default 60000 */ recoverJobsInterval?: number + + /** + * Budget in milliseconds of each phase of `stop()`: startup settlement, the drain of + * admitted work (running handlers and steps, their final writes and the release of jobs + * that did not finish), database cleanup and the close of owned connections. A phase that + * exceeds it makes `stop()` reject. It applies to this Client's adapter. An integer from 1 + * to 2147483647. + * + * @default 5000 + */ + shutdownTimeout?: number } const BaseOptionsSchema = z.object({ @@ -327,6 +338,10 @@ const BaseOptionsSchema = z.object({ heartbeatInterval: z._default(z.number(), 5000), heartbeatTimeout: z._default(z.number(), 15000), recoverJobsInterval: z._default(z.number(), 60_000), + shutdownTimeout: z._default( + z.number().check(z.int(), z.minimum(1), z.maximum(2_147_483_647)), + DEFAULT_SHUTDOWN_TIMEOUT, + ), }) // Compile-time check: ensure BaseOptionsInput is assignable to the Zod schema's input type @@ -468,6 +483,7 @@ export class Client< // Side effects from here on. this.#database = options.database this.#lifecycle = lifecycleFor(this.#database) + this.#lifecycle.shutdownTimeout = this.#options.shutdownTimeout this.#lifecycle.onQuiesce(() => this.#quiesce()) this.#database.setId(this.#id) markClientAdapter(this.#database) @@ -1270,9 +1286,18 @@ export class Client< return suppressed } - if (!this.#actions || !this.#lifecycle.accepting) { + if (!this.#actions) { return Promise.resolve() } + if (!this.#lifecycle.accepting) { + // Claimed, but stop began before dispatch: no handler starts, return it to the queue. + return this.#database.releaseJob({ jobId: job.id }).then( + () => undefined, + (error: unknown) => { + this.#logger.warn({ error, jobId: job.id }, `[Duron] Could not release job ${job.id}`) + }, + ) + } const action = Object.values(this.#actions).find((a) => a.name === job.actionName) if (!action) { diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index f477db1..5e38dc8 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -59,11 +59,19 @@ function signal(): { promise: Promise; resolve: () => void } { return { promise, resolve } } +/** Default budget of each shutdown phase (Client option `shutdownTimeout`). */ +export const DEFAULT_SHUTDOWN_TIMEOUT = 5_000 + // A deadline bounds observation, not execution. The losing promise remains observed. class ShutdownBudget { - readonly #deadline = performance.now() + 5_000 + readonly #deadline: number - constructor(readonly phase: Phase) {} + constructor( + readonly phase: Phase, + readonly timeout: number, + ) { + this.#deadline = performance.now() + timeout + } async observe(work: Promise): Promise { let timer: ReturnType | undefined @@ -72,7 +80,12 @@ class ShutdownBudget { work, new Promise((_, reject) => { timer = setTimeout( - () => reject(new Error(`Incomplete shutdown: ${this.phase} exceeded five seconds`)), + () => + reject( + new Error( + `Incomplete shutdown: ${this.phase} exceeded the shutdown timeout (${this.timeout} ms)`, + ), + ), Math.max(0, this.#deadline - performance.now()), ) }), @@ -102,7 +115,7 @@ class CleanupObligation { // An isolated resource can close before global shutdown. The raw attempt stays // in this same ledger; a later stop observes its original deadline, not a new one. observeEarlyClose(): Promise { - this.#earlyCloseBudget ??= new ShutdownBudget(this.phase) + this.#earlyCloseBudget ??= new ShutdownBudget(this.phase, this.timeout()) return this.observe() } @@ -116,6 +129,7 @@ class CleanupObligation { readonly phase: 'database cleanup' | 'owned close', readonly execute: () => Promise, readonly usable: () => boolean, + readonly timeout: () => number, ) {} attempt(): Promise { @@ -203,6 +217,16 @@ export class Lifecycle { #stopping: StopAttempt | null = null #lastStop: StopAttempt | null = null #phase: Phase | null = null + #timeout = DEFAULT_SHUTDOWN_TIMEOUT + + /** The budget of each shutdown phase, in ms (the Client's `shutdownTimeout`). */ + get shutdownTimeout(): number { + return this.#timeout + } + /** Read when a phase begins: a phase already running keeps its deadline. */ + set shutdownTimeout(timeout: number) { + this.#timeout = timeout + } get accepting(): boolean { return !this.#terminal @@ -248,7 +272,7 @@ export class Lifecycle { execute: () => Promise, usable: () => boolean = () => true, ): CleanupObligation { - const obligation = new CleanupObligation(name, phase, execute, usable) + const obligation = new CleanupObligation(name, phase, execute, usable, () => this.#timeout) this.#obligations.add(obligation) return obligation } @@ -338,6 +362,24 @@ export class Lifecycle { } } + /** + * Resolves when `work` settles (`'settled'`) or once it is excluded from the drain + * (`'excluded'`: its user code awaits `stop()`, so it cannot settle before stop does). + * Never rejects. + */ + async settledOrExcluded(work: Promise): Promise<'settled' | 'excluded'> { + const settled = work.then( + () => 'settled' as const, + () => 'settled' as const, + ) + for (;;) { + if (this.#drainExcluded.has(work)) return 'excluded' + const changed = this.#drainExclusionChanged.promise.then(() => null) + const outcome = await Promise.race([settled, changed]) + if (outcome) return outcome + } + } + /** Diagnostic: the number of this lifecycle's contexts linked around the caller. */ contextDepth(): number { let depth = 0 @@ -451,7 +493,7 @@ export class Lifecycle { ) if (!obligations.length) continue this.#phase = phase - const budget = new ShutdownBudget(phase) + const budget = new ShutdownBudget(phase, this.#timeout) const work = obligations.map((task) => this.#inContext('cleanup', () => task.observe()).catch((error: unknown) => { failures.push({ error, phase, obligation: task.name }) @@ -488,7 +530,7 @@ export class Lifecycle { } } try { - await new ShutdownBudget(phase).observe(settle()) + await new ShutdownBudget(phase, this.#timeout).observe(settle()) return true } catch (error) { failures.push({ error, phase }) diff --git a/packages/duron/src/local-cancellation.ts b/packages/duron/src/local-cancellation.ts index 8018819..477c53b 100644 --- a/packages/duron/src/local-cancellation.ts +++ b/packages/duron/src/local-cancellation.ts @@ -150,6 +150,11 @@ export class LocalCancellation { return this.#consume(jobId, intent) } + /** True while an explicit cancellation of `jobId` has an Adapter call that has not settled. */ + cancelling(jobId: string): boolean { + return (this.#intents.get(jobId)?.pendingWrites ?? 0) > 0 + } + /** A queued entry left without starting (early return, rejected admission or kill). */ consumeQueued(jobId: string): Promise { if (!this.#queued.delete(jobId)) return Promise.resolve() diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index e121b73..813da9c 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -343,6 +343,7 @@ export class StepManager { #stepSpans = new Map() // Store the job span for creating step spans #jobSpan!: Span + #releasing = false // Factory function to create run functions with the correct parent step ID and abort signal #runFnFactory: | ((parentStepId: string | null, abortSignal: AbortSignal) => StepHandlerContext['run']) @@ -398,6 +399,15 @@ export class StepManager { * Set the job span for this step manager. * Called from ActionJob after the job span is created. */ + /** + * The job is being released to the queue (graceful stop): steps that end from now on keep + * their stored status (as recovery keeps them), so a new run of the job runs them again + * instead of failing on a step stored as cancelled or failed. + */ + release(): void { + this.#releasing = true + } + setJobSpan(span: Span): void { this.#jobSpan = span } @@ -925,7 +935,9 @@ export class StepManager { this.#stepSpans.delete(step.id) } - if (isCancelError(error)) { + if (this.#releasing) { + // Released job: the step keeps its stored status for the next run. + } else if (isCancelError(error)) { await this.#stepStore.updateStatus(step.id, 'cancelled') } else { await this.#stepStore.updateStatus( diff --git a/packages/duron/src/worker-discovery.ts b/packages/duron/src/worker-discovery.ts index 7408a87..9909be7 100644 --- a/packages/duron/src/worker-discovery.ts +++ b/packages/duron/src/worker-discovery.ts @@ -28,9 +28,12 @@ type DiscoveryRequest = AutomaticRequest | ManualRequest /** One actual Adapter.fetch result, bound to that call by the claim function. */ export interface ClaimedBatch { jobs: Job[] - /** Queue a claimed job locally; resolves (never rejects) at its actual local settlement. */ + /** + * Queue a claimed job locally; resolves (never rejects) at its actual local settlement. + * After the stop gate it starts no handler and returns the job to the queue instead. + */ dispatch: (job: Job) => Promise - /** Called once every returned job was dispatched or dropped after the gate. */ + /** Called once every returned job was dispatched. */ release: () => void } @@ -335,8 +338,11 @@ export class WorkerDiscovery { this.#uncovered = got < request.demand && (got > 0 || Number.isFinite(request.demand)) } try { - if (!this.#stopped && this.#options.lifecycle.accepting) { - for (const job of claimed.jobs) this.#track(claimed.dispatch(job), wake) + const open = !this.#stopped && this.#options.lifecycle.accepting + for (const job of claimed.jobs) { + // After the stop gate, dispatch starts no handler: it returns the job to the queue. + const settlement = claimed.dispatch(job) + if (open) this.#track(settlement, wake) } } finally { claimed.release() diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index 580f728..b7ee7d6 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -527,11 +527,14 @@ suite('Native PostgreSQL claim admission', () => { expect(settled).toBe(false) expect(stopped).toBe(false) relay.flush() - // The admitted manual fetch returns its actual claim, but no handler starts after stop. + // The admitted manual fetch returns its actual claim, but no handler starts after stop: + // the stop returns the job to the queue. expect((await fetched).map((job) => job.id)).toEqual([id]) expect(await stopping).toBe(true) expect(started).toEqual([]) - expect(await db.activeCount()).toBe(1) + expect(await db.activeCount()).toBe(0) + const [row] = await db.admin`SELECT status, client_id FROM duron.jobs_active WHERE id = ${id}` + expect([row!['status'], row!['client_id']]).toEqual(['created', null]) expect(relay.errors).toEqual([]) } catch (error) { db.recordFailure(error) @@ -600,6 +603,8 @@ suite('Native PostgreSQL claim admission', () => { const db = await claimDatabase() try { const a = db.adapter('claim-a') + // The drain waits its whole budget: a short one keeps the test fast. + lifecycleFor(a).shutdownTimeout = 300 const statements = traceStatements(a) await a.start() await createJobs(a, 2, 2) @@ -608,8 +613,8 @@ suite('Native PostgreSQL claim admission', () => { const claim = observe(a.fetch({ batch: 1 })) await db.waitingAtBarrier('claim-a') const stopping = observe(a.stop()) - // Hold the admitted claim past the unchanged five-second drain budget. - await eventually(() => !lifecycleFor(a).ordinaryOpen, 7_000) + // Hold the admitted claim past the drain budget. + await eventually(() => !lifecycleFor(a).ordinaryOpen, 3_000) await db.release() expect((rejection(await claim) as Error).message).toBe('Lifecycle ordinary work has drained') expect(statements.filter(isClaim)).toHaveLength(1) @@ -627,6 +632,8 @@ suite('Native PostgreSQL claim admission', () => { const db = await claimDatabase() const relay = new PruneRelay() const a = db.adapter('claim-a', 1, relay.port) + // The drain waits its whole budget: a short one keeps the test fast. + lifecycleFor(a).shutdownTimeout = 300 try { const statements = traceStatements(a) await a.start() @@ -640,7 +647,7 @@ suite('Native PostgreSQL claim admission', () => { await eventually(() => relay.held.length > 0) const stopping = observe(a.stop()) // Hold the acquired-but-unacknowledged transaction past the drain budget. - await eventually(() => !lifecycleFor(a).ordinaryOpen, 7_000) + await eventually(() => !lifecycleFor(a).ordinaryOpen, 3_000) relay.flush() // The existing statement gate rejects SET TRANSACTION; the driver rolls back. expect((rejection(await claim) as Error).message).toBe('Lifecycle ordinary work has drained') diff --git a/packages/duron/test/lifecycle-budgets.test.ts b/packages/duron/test/lifecycle-budgets.test.ts index 8f2b301..03fe6b9 100644 --- a/packages/duron/test/lifecycle-budgets.test.ts +++ b/packages/duron/test/lifecycle-budgets.test.ts @@ -27,6 +27,8 @@ type BudgetProbe = Adapter & { } } +const BUDGET = 300 + for (const factory of [ pgliteFactory, ...(process.env['POSTGRES_TEST'] === 'true' ? [postgresFactory] : []), @@ -39,6 +41,8 @@ for (const factory of [ id: 'four-budgets', database: adapter, syncPattern: false, + // Each of the four phases waits its whole budget: a short one keeps the test fast. + shutdownTimeout: BUDGET, logger: 'silent', }) const observer = @@ -106,7 +110,7 @@ for (const factory of [ const result = await Promise.race([ first, new Promise((resolve) => { - timer = setTimeout(() => resolve('observer deadline'), 23_000) + timer = setTimeout(() => resolve('observer deadline'), 4 * BUDGET + 3_000) }), ]) // An observation threshold in this controlled test, not a wall-clock SLA. @@ -121,7 +125,9 @@ for (const factory of [ 'owned close', ]) { expect( - failures.some((error) => String(error).includes(`${phase} exceeded five seconds`)), + failures.some((error) => + String(error).includes(`${phase} exceeded the shutdown timeout (${BUDGET} ms)`), + ), ).toBe(true) } const withheld = failures.find((error) => @@ -167,6 +173,6 @@ for (const factory of [ await observer?.end({ timeout: 5 }) await instance.deleteDb() } - }, 40_000) + }, 15_000) }) } diff --git a/packages/duron/test/lifecycle-close-retry.test.ts b/packages/duron/test/lifecycle-close-retry.test.ts index 7532c81..fd706a7 100644 --- a/packages/duron/test/lifecycle-close-retry.test.ts +++ b/packages/duron/test/lifecycle-close-retry.test.ts @@ -31,6 +31,8 @@ for (const factory of [ id: 'pending-close', database: adapter, syncPattern: false, + // Owned close waits its whole budget: a short one keeps the test fast. + shutdownTimeout: 300, logger: 'silent', }) const cleanup = adapter._stop.bind(adapter) diff --git a/packages/duron/test/lifecycle-sql.test.ts b/packages/duron/test/lifecycle-sql.test.ts index 5e8897f..65bc7d4 100644 --- a/packages/duron/test/lifecycle-sql.test.ts +++ b/packages/duron/test/lifecycle-sql.test.ts @@ -3,9 +3,13 @@ import { describe, expect, it } from 'bun:test' import type { SQL } from 'drizzle-orm' import type { Job } from '../src/adapters/adapter.js' +import { lifecycleFor } from '../src/lifecycle.js' import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' +/** Shutdown budget of the tests that wait for a phase to time out. */ +const BUDGET = 300 + type Row = Record type SqlProbe = Adapter & { _close: () => Promise @@ -36,6 +40,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as SqlProbe adapter.setId('migration-cutoff') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const entered = Promise.withResolvers() const release = Promise.withResolvers() const close = adapter._close.bind(adapter) @@ -98,6 +104,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as SqlProbe adapter.setId('sql-read-cutoff') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const entered = Promise.withResolvers() const release = Promise.withResolvers() const close = adapter._close.bind(adapter) @@ -148,6 +156,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as SqlProbe adapter.setId('sql-transaction-cutoff') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const entered = Promise.withResolvers() const release = Promise.withResolvers() const close = adapter._close.bind(adapter) diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts index 92e6699..f48fec5 100644 --- a/packages/duron/test/lifecycle.test.ts +++ b/packages/duron/test/lifecycle.test.ts @@ -5,9 +5,13 @@ import postgres from 'postgres' import { defineAction } from '../src/action.js' import { Client } from '../src/client.js' +import { lifecycleFor } from '../src/lifecycle.js' import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' +/** Shutdown budget of the tests that wait for a phase to time out. */ +const BUDGET = 300 + // Fault-injected public lifecycle tests. Native observations prove resource release; // a rejected start/fulfilled stop alone is not evidence of physical closure. type LifecycleProbe = Adapter & { @@ -410,6 +414,8 @@ for (const factory of [ id: 'incomplete-drain', database: adapter, syncPattern: false, + // The drain waits its whole budget: a short one keeps the test fast. + shutdownTimeout: BUDGET, logger: 'silent', }) const reports: unknown[] = [] @@ -691,6 +697,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as LifecycleProbe adapter.setId('held-cleanup') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const cleanup = adapter._stop.bind(adapter) const release = Promise.withResolvers() let attempts = 0 @@ -728,6 +736,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as LifecycleProbe adapter.setId('held-close') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const driver = adapter.db.$client const close = driver.close?.bind(driver) const end = driver.end?.bind(driver) @@ -881,6 +891,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as LifecycleProbe adapter.setId('held-start') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const observer = factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null let deadlineTimer: ReturnType | undefined diff --git a/packages/duron/test/local-cancellation.test.ts b/packages/duron/test/local-cancellation.test.ts index 4ceb976..0bb75e8 100644 --- a/packages/duron/test/local-cancellation.test.ts +++ b/packages/duron/test/local-cancellation.test.ts @@ -234,6 +234,19 @@ function countCalls(adapter: Adapter, name: 'failJob' | 'completeJob') { return calls } +// Records each call of `name` with its job id and result. +function recordResults(adapter: Adapter, name: 'releaseJob' | 'completeJob') { + const target = adapter as any + const real = target[name].bind(adapter) + const calls: Array<{ jobId: string; result: unknown }> = [] + target[name] = async (options: { jobId: string }) => { + const result = await real(options) + calls.push({ jobId: options.jobId, result }) + return result + } + return calls +} + function captureLogs() { const entries: Array> = [] const logger = pino( @@ -251,6 +264,7 @@ interface HarnessOptions { recoverJobsOnStart?: boolean recoverJobsInterval?: number logger?: pino.Logger + shutdownTimeout?: number } interface Harness { @@ -336,6 +350,8 @@ async function harness(factory: AdapterFactory, options: HarnessOptions = {}): P recoverJobsOnStart: options.recoverJobsOnStart ?? false, recoverJobsInterval: options.recoverJobsInterval ?? 0, logger: options.logger ?? 'silent', + // Tests that wait for the drain budget to expire do not need five seconds of it. + shutdownTimeout: options.shutdownTimeout ?? 5_000, }) expect(await client.start()).toBe(true) const c = client @@ -775,12 +791,14 @@ for (const factory of factories) { ) it( - 'E2c: stop kills queued work without compensating writes and observes the pending write (held, inspected)', + 'E2c: stop releases queued work, completes a finished handler and observes the pending write (held, inspected)', async () => { const h = await harness(factory, { actionConcurrencyLimit: 1 }) try { const cancels = controlCancel(h.adapter) const fails = countCalls(h.adapter, 'failJob') + const releases = recordResults(h.adapter, 'releaseJob') + const completions = recordResults(h.adapter, 'completeJob') const blocker = await occupySlot(h) const target = await h.run() const other = await h.run() @@ -797,7 +815,7 @@ for (const factory of factories) { stopped = true return result }) - // The aborted blocker's raw handler settles; the pending write still holds the drain. + // The aborted blocker's raw handler resolves; the pending write still holds the drain. h.gate(blocker).resolve() await stateReached( h.client, @@ -816,12 +834,13 @@ for (const factory of factories) { expect(await cancelling).toBe(false) expect(await stopping).toBe(true) expect(h.starts).toEqual([blocker]) - // The pending write cancelled the killed job; the killed item without an intent was - // left claimed for recovery (no cancel/fail call for it): nothing compensates. + // The pending write cancelled the killed job; stop left it to that write and returned + // the other killed item to the queue. The blocker's handler resolved after the abort, + // so it completed instead of being released. expect(cancels.for(target)[0]!.result).toBe(true) - expect(cancels.calls.map((call) => call.jobId).toSorted()).toEqual( - [blocker, target].toSorted(), - ) + expect(cancels.calls.map((call) => call.jobId)).toEqual([target]) + expect(releases).toEqual([{ jobId: other, result: true }]) + expect(completions).toEqual([{ jobId: blocker, result: true }]) expect(fails).toEqual([]) expectState(h.client, QUIESCENT) } finally { @@ -1118,7 +1137,10 @@ for (const factory of factories) { it( `Q: a nested cancelJob during drain is admitted, starts no handler and its pending write is ${variant} (held, inspected)`, async () => { - const h = await harness(factory, { actionConcurrencyLimit: 1 }) + const h = await harness(factory, { + actionConcurrencyLimit: 1, + shutdownTimeout: variant === 'incomplete' ? 300 : 5_000, + }) try { const cancels = controlCancel(h.adapter) const runner = await h.run({ mode: 'nested-cancel' }) diff --git a/packages/duron/test/notifications.test.ts b/packages/duron/test/notifications.test.ts index cacdb48..9fbbdf3 100644 --- a/packages/duron/test/notifications.test.ts +++ b/packages/duron/test/notifications.test.ts @@ -5,6 +5,8 @@ import { identifier, query as templateQuery } from '@electric-sql/pglite/templat import pino from 'pino' import postgres from 'postgres' +import { lifecycleFor } from '../src/lifecycle.js' + import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' const noop = () => {} @@ -567,6 +569,8 @@ for (const factory of [ const instance = await factory.create() const adapter = instance.adapter as NotificationProbe adapter.setId('pending-notification') + // The drain waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = 300 const reports = captureErrors(adapter) const entered = Promise.withResolvers() const release = Promise.withResolvers() @@ -622,10 +626,10 @@ for (const factory of [ expect(stopped).toBeInstanceOf(AggregateError) expect( (stopped as AggregateError).errors.some((error) => - String(error).includes('admitted-work drain exceeded five seconds'), + String(error).includes('admitted-work drain exceeded the shutdown timeout (300 ms)'), ), ).toBe(true) - expect(performance.now() - started).toBeGreaterThanOrEqual(4_900) + expect(performance.now() - started).toBeGreaterThanOrEqual(250) expect(closes).toBe(1) expect(livenessAtClose).toEqual([{ id: 'pending-notification' }]) expect(settled).toBe(false) diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index 17333b4..254e07a 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -4,10 +4,14 @@ import pino from 'pino' import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { lifecycleFor } from '../src/lifecycle.js' import { getPostgresConnection } from './docker.js' import { PruneRelay } from './prune-relay.js' +/** Shutdown budget of the tests that wait for a phase to time out. */ +const BUDGET = 300 + // postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain // Promise, which is enough because PostgresPruneLock only awaits the reservation. type ReserveStub = { reserve: () => Promise } @@ -83,6 +87,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { pruneArchive: { olderThan: '1d', intervalMs: 20 }, }) adapter.setId(`pending-bootstrap-${mode}`) + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const observer = postgres(CONNECTION_URL, { max: 1 }) let stopped: Promise> | undefined try { @@ -115,7 +121,9 @@ if (process.env['POSTGRES_TEST'] === 'true') { outcome.reason instanceof AggregateError ? outcome.reason.errors : [outcome.reason] expect( errors.some((error) => - error.message.includes('admitted-work drain exceeded five seconds'), + error.message.includes( + `admitted-work drain exceeded the shutdown timeout (${BUDGET} ms)`, + ), ), ).toBe(true) } @@ -183,6 +191,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { pruneArchive: { olderThan: '1d', intervalMs: 20 }, }) adapter.setId('stalled-bootstrap-end-timeout') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET const observer = postgres(CONNECTION_URL, { max: 1 }) let stopped: Promise> | undefined try { @@ -211,10 +221,10 @@ if (process.env['POSTGRES_TEST'] === 'true') { const reason = (outcome as PromiseRejectedResult).reason const errors: Error[] = reason instanceof AggregateError ? reason.errors : [reason] expect(errors.map((error) => error.message)).toEqual([ - 'Incomplete shutdown: admitted-work drain exceeded five seconds', + `Incomplete shutdown: admitted-work drain exceeded the shutdown timeout (${BUDGET} ms)`, 'Liveness release withheld because admitted work did not drain', - 'Incomplete shutdown: database cleanup exceeded five seconds', - 'Incomplete shutdown: owned close exceeded five seconds', + `Incomplete shutdown: database cleanup exceeded the shutdown timeout (${BUDGET} ms)`, + `Incomplete shutdown: owned close exceeded the shutdown timeout (${BUDGET} ms)`, ]) await eventually(async () => { expect( diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts index 11f17ce..4a68ffe 100644 --- a/packages/duron/test/prune-ownership.test.ts +++ b/packages/duron/test/prune-ownership.test.ts @@ -4,9 +4,13 @@ import pino from 'pino' import postgres, { type ReservedSql, type Sql } from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { lifecycleFor } from '../src/lifecycle.js' import { getPostgresConnection } from './docker.js' +/** Shutdown budget of the tests that wait for a phase to time out. */ +const BUDGET = 300 + // postgres 4.2 types reserve() as a cancellable Leasing. These stubs return a plain // Promise, which is enough because PostgresPruneLock only awaits the reservation. type ReserveStub = { reserve: () => Promise } @@ -448,6 +452,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { pruneArchive: { olderThan: '1d', intervalMs: 20 }, }) adapter.setId('shared-fault-close-deadline') + // The early close budget runs out while stop waits: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = 1_000 adapter.instrument = (client) => { const reserve = client.reserve.bind(client) ;(client as ReserveStub).reserve = async () => { @@ -477,14 +483,15 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(await adapter.start()).toBe(true) await eventually(async () => expect(endStarted).toBeGreaterThan(0)) await adapter.heartbeat() - await Bun.sleep(2_000) + // Stop begins well inside the early close's budget, which it must not restart. + await Bun.sleep(400) const stopping = adapter.stop() const duplicate = adapter.stop() const outcomes = await Promise.allSettled([stopping, duplicate]) expect(outcomes[0]?.status).toBe('rejected') expect(outcomes[1]?.status).toBe('rejected') - expect(performance.now() - endStarted).toBeGreaterThanOrEqual(4_900) - expect(performance.now() - endStarted).toBeLessThan(6_500) + expect(performance.now() - endStarted).toBeGreaterThanOrEqual(950) + expect(performance.now() - endStarted).toBeLessThan(1_350) expect(endCalls).toBe(1) expect(returnCalls).toBe(0) const sessions = await observer` @@ -532,6 +539,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { pruneArchive: { olderThan: '1d', intervalMs: 60_000 }, }) adapter.setId('pending-return-ack') + // The phase waits its whole budget: a short one keeps the test fast. + lifecycleFor(adapter).shutdownTimeout = BUDGET adapter.instrument = (client) => { const end = client.end.bind(client) const reserve = client.reserve.bind(client) @@ -558,7 +567,9 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { expect((await adapter.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date) }) - await expect(adapter.stop()).rejects.toThrow('database cleanup exceeded five seconds') + await expect(adapter.stop()).rejects.toThrow( + `database cleanup exceeded the shutdown timeout (${BUDGET} ms)`, + ) expect(returnCalls).toBe(1) expect(closeCalls).toBe(1) await eventually(async () => { diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts index 943c328..007f9b2 100644 --- a/packages/duron/test/prune-replies.test.ts +++ b/packages/duron/test/prune-replies.test.ts @@ -109,7 +109,9 @@ if (process.env['POSTGRES_TEST'] === 'true') { : 'False or malformed scheduled prune unlock or changed backend', ) for (const error of errors.slice(1)) - expect(error.message).toBe('Incomplete shutdown: owned close exceeded five seconds') + expect(error.message).toBe( + 'Incomplete shutdown: owned close exceeded the shutdown timeout (5000 ms)', + ) expect(nativeLocks).toBe(phase === 'acquired' ? 1 : 0) await eventually(async () => expect(endSettled).toBe(true)) expect(hooks).toBe(phase === 'acquired' ? 0 : 1) diff --git a/packages/duron/test/recover-snapshot.test.ts b/packages/duron/test/recover-snapshot.test.ts index 5329c8b..0de448a 100644 --- a/packages/duron/test/recover-snapshot.test.ts +++ b/packages/duron/test/recover-snapshot.test.ts @@ -4,6 +4,7 @@ import type { SQL } from 'drizzle-orm' import postgres from 'postgres' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { lifecycleFor } from '../src/lifecycle.js' import { type Adapter, type AdapterFactory, pgliteFactory } from './adapters.js' import { getPostgresConnection } from './docker.js' @@ -934,6 +935,8 @@ native('Native PostgreSQL recovery step membership', () => { await withDatabase(async (db) => { const w = await db.adapter('w') const r = await db.adapter('r') + // The drain waits its whole budget: a short one keeps the test fast. + lifecycleFor(r).shutdownTimeout = 300 const { jobId, s1 } = await claimedJobWithStep(w, 300) await db.untilExpired(jobId) const probe = r as unknown as { _close: () => Promise } diff --git a/packages/duron/test/shutdown-release.test.ts b/packages/duron/test/shutdown-release.test.ts new file mode 100644 index 0000000..e227769 --- /dev/null +++ b/packages/duron/test/shutdown-release.test.ts @@ -0,0 +1,384 @@ +import { describe, expect, it } from 'bun:test' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { sql } from 'drizzle-orm' +import { z } from 'zod' + +import { defineAction } from '../src/action.js' +import type { Adapter } from '../src/adapters/adapter.js' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' +import { Client } from '../src/client.js' + +import { getPostgresConnection } from './docker.js' + +// A graceful stop returns the jobs it did not finish to the queue (released), instead of +// cancelling them. A database that outlives the stopped adapter (a PGlite data directory or a +// PostgreSQL database) lets a new adapter inspect the rows and run the released job again. + +type Store = { + name: 'pglite' | 'postgres' + adapter: () => Adapter + close: () => Promise +} + +async function pgliteStore(): Promise { + const dir = await mkdtemp(join(tmpdir(), 'duron-release-')) + return { + name: 'pglite', + adapter: () => new PGLiteAdapter({ connection: dir }), + close: () => rm(dir, { recursive: true, force: true }), + } +} + +async function postgresStore(): Promise { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + return { + name: 'postgres', + adapter: () => new PostgresAdapter({ connection: CONNECTION_URL }), + close: deleteDb, + } +} + +const stores = [ + { name: 'pglite', create: pgliteStore }, + ...(process.env['POSTGRES_TEST'] === 'true' ? [{ name: 'postgres', create: postgresStore }] : []), +] + +function rowsOf(result: unknown): Array> { + return Array.isArray(result) ? [...result] : (result as { rows: Array> }).rows +} + +async function query(adapter: Adapter, statement: ReturnType) { + const db = (adapter as unknown as { db: { execute: (q: unknown) => Promise } }).db + return rowsOf(await db.execute(statement)) +} + +async function jobRow(adapter: Adapter, jobId: string) { + const [active] = await query( + adapter, + sql`SELECT status, client_id, started_at, expires_at FROM duron.jobs_active WHERE id = ${jobId}`, + ) + if (active) return active + const [archived] = await query( + adapter, + sql`SELECT status, client_id, output FROM duron.jobs_archive WHERE id = ${jobId}`, + ) + return archived +} + +async function stepRows(adapter: Adapter, jobId: string) { + const rows = await query( + adapter, + sql`SELECT name, status FROM duron.job_steps_active WHERE job_id = ${jobId} + UNION ALL + SELECT name, status FROM duron.job_steps_archive WHERE job_id = ${jobId}`, + ) + return Object.fromEntries(rows.map((row) => [row['name'], row['status']])) +} + +async function until(check: () => boolean, ms = 5_000) { + const end = performance.now() + ms + while (!check()) { + if (performance.now() > end) throw new Error('condition not reached') + await Bun.sleep(5) + } +} + +function client(adapter: Adapter, actions: Record, options: object = {}) { + return new Client({ + database: adapter, + actions, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + ...options, + }) +} + +for (const { name, create: createStore } of stores) { + describe(`Graceful stop releases unfinished jobs`, () => { + it(`releases an aborted job, keeps its steps for the next run and runs it again (${name})`, async () => { + const store = await createStore() + const calls: Record = { first: 0, second: 0 } + const inSecond = Promise.withResolvers() + let honorAbort = true + const action = defineAction()({ + name: 'two-steps', + output: z.object({ done: z.boolean() }), + handler: async (ctx) => { + await ctx.step('first', async () => { + calls['first']!++ + return {} + }) + await ctx.step('second', async ({ signal }) => { + calls['second']!++ + if (!honorAbort) return {} + inSecond.resolve() + await new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + }) + }) + return { done: true } + }, + }) + try { + const worker = client(store.adapter(), { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await inSecond.promise + expect(await worker.stop()).toBe(true) + + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + const row = await jobRow(reader, jobId) + expect(row?.['status']).toBe('created') + expect(row?.['client_id']).toBeNull() + expect(row?.['started_at']).toBeNull() + expect(row?.['expires_at']).toBeNull() + // Like recovery: the completed step is kept, the aborted one stays active. + expect(await stepRows(reader, jobId)).toEqual({ first: 'completed', second: 'active' }) + } finally { + await reader.stop() + } + + // The next worker runs it again: the completed step is reused. + honorAbort = false + const next = client(store.adapter(), { action }) + await next.start() + try { + expect((await next.fetch()).map((job) => job.id)).toEqual([jobId]) + const result = await next.waitForJob(jobId, { timeout: 5_000 }) + expect(result?.status).toBe('completed') + expect(calls).toEqual({ first: 1, second: 2 }) + } finally { + await next.stop() + } + } finally { + await store.close() + } + }, 30_000) + + it(`completes a job whose handler still resolves after the abort (${name})`, async () => { + const store = await createStore() + const started = Promise.withResolvers() + const finish = Promise.withResolvers() + const action = defineAction()({ + name: 'ignores-abort', + output: z.object({ value: z.number() }), + handler: async () => { + started.resolve() + await finish.promise + return { value: 42 } + }, + }) + try { + const worker = client(store.adapter(), { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await started.promise + const stopping = worker.stop() + await Bun.sleep(50) + finish.resolve() + expect(await stopping).toBe(true) + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + const row = await jobRow(reader, jobId) + expect(row?.['status']).toBe('completed') + expect(row?.['output']).toEqual({ value: 42 }) + } finally { + await reader.stop() + } + } finally { + await store.close() + } + }, 30_000) + + it(`releases claimed jobs that did not start (${name})`, async () => { + const store = await createStore() + const started = Promise.withResolvers() + const action = defineAction()({ + name: 'slow', + input: z.object({ index: z.number() }), + handler: async (ctx) => { + await ctx.step('wait', async ({ signal }) => { + started.resolve() + await new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + }) + }) + return {} + }, + }) + try { + const worker = client(store.adapter(), { action }, { actionConcurrencyLimit: 1 }) + await worker.start() + const first = await worker.runAction('action', { index: 0 }) + const second = await worker.runAction('action', { index: 1 }) + expect(await worker.fetch({ batchSize: 2 })).toHaveLength(2) + await started.promise + expect(await worker.stop()).toBe(true) + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + expect((await jobRow(reader, first))?.['status']).toBe('created') + expect((await jobRow(reader, second))?.['status']).toBe('created') + } finally { + await reader.stop() + } + } finally { + await store.close() + } + }, 30_000) + + it(`still cancels a job that is explicitly cancelled while stopping (${name})`, async () => { + const store = await createStore() + const started = Promise.withResolvers() + const finish = Promise.withResolvers() + const action = defineAction()({ + name: 'cancel-me', + handler: async () => { + started.resolve() + await finish.promise + throw new Error('ended by the test') + }, + }) + try { + const worker = client(store.adapter(), { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await started.promise + // Admitted before stop begins: the cancellation reaches the job during the stop. + const cancelling = worker.cancelJob(jobId) + const stopping = worker.stop() + expect(await cancelling).toBe(true) + finish.resolve() + expect(await stopping).toBe(true) + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + expect((await jobRow(reader, jobId))?.['status']).toBe('cancelled') + } finally { + await reader.stop() + } + } finally { + await store.close() + } + }, 30_000) + + it(`bounds the drain by shutdownTimeout and leaves a job whose handler never settles active (${name})`, async () => { + const store = await createStore() + const started = Promise.withResolvers() + const action = defineAction()({ + name: 'stuck', + handler: async () => { + started.resolve() + await new Promise(() => undefined) + return {} + }, + }) + try { + const worker = client(store.adapter(), { action }, { shutdownTimeout: 200 }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await started.promise + const begun = performance.now() + const failure = await worker.stop().then( + () => null, + (error: unknown) => error, + ) + const errors = failure instanceof AggregateError ? failure.errors : [failure] + expect(errors.map(String)).toContain( + 'Error: Incomplete shutdown: admitted-work drain exceeded the shutdown timeout (200 ms)', + ) + expect(performance.now() - begun).toBeLessThan(2_000) + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + // Not released: recovery requeues it once the worker's liveness is gone. + expect((await jobRow(reader, jobId))?.['status']).toBe('active') + } finally { + await reader.stop() + } + } finally { + await store.close() + } + }, 30_000) + }) +} + +describe('shutdownTimeout option', () => { + for (const value of [0, -1, 1.5, 2_147_483_648, Number.NaN, '100']) { + it(`rejects ${String(value)}`, () => { + expect( + () => + new Client({ + database: new PGLiteAdapter({ connection: ':memory:' }), + shutdownTimeout: value as number, + logger: 'silent', + }), + ).toThrow() + }) + } +}) + +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Graceful stop with several postgres workers', () => { + it('lets another worker run a job that a stopped worker released', async () => { + const store = await postgresStore() + const firstRun = Promise.withResolvers() + const runs: string[] = [] + const action = defineAction()({ + name: 'handoff', + handler: async (ctx) => { + runs.push(ctx.jobId) + if (runs.length === 1) { + await ctx.step('wait', async ({ signal }) => { + firstRun.resolve() + await new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + }) + }) + } + return {} + }, + }) + const options = { syncPattern: 'hybrid', pullInterval: 60_000 } + const a = client(store.adapter(), { action }, options) + const b = client(store.adapter(), { action }, { ...options, batchSize: 1 }) + try { + await a.start() + const jobId = await a.runAction('action', {}) + await firstRun.promise + // B starts after A claimed the job: only the release's notification wakes it. + await b.start() + await Bun.sleep(100) + const begun = performance.now() + expect(await a.stop()).toBe(true) + await until(() => runs.length === 2) + expect(performance.now() - begun).toBeLessThan(2_000) + expect(runs).toEqual([jobId, jobId]) + const result = await b.waitForJob(jobId, { timeout: 5_000 }) + expect(result?.status).toBe('completed') + } finally { + await a.stop().catch(() => undefined) + await b.stop().catch(() => undefined) + await store.close() + } + }, 30_000) + }) +} diff --git a/packages/duron/test/wait-lifecycle.test.ts b/packages/duron/test/wait-lifecycle.test.ts index 6578c96..f31d382 100644 --- a/packages/duron/test/wait-lifecycle.test.ts +++ b/packages/duron/test/wait-lifecycle.test.ts @@ -38,14 +38,17 @@ for (const factory of [ } }, 20_000) + // A drain budget between the two read budgets: neither read budget bounds the drain. + const DRAIN = 500 for (const waitReadTimeout of [40, 15_000]) { - it(`retains the shared five-second drain with a ${waitReadTimeout}ms read budget`, async () => { + it(`retains the shared drain budget (shutdownTimeout ${DRAIN} ms) with a ${waitReadTimeout}ms read budget`, async () => { const instance = await factory.create() const adapter = instance.adapter const client = new Client({ database: adapter, syncPattern: false, waitReadTimeout, + shutdownTimeout: DRAIN, logger: 'silent', }) const status = adapter.getJobStatus.bind(adapter) @@ -77,9 +80,11 @@ for (const factory of [ expect(error).toBeInstanceOf(Error) const messages = error instanceof AggregateError ? error.errors.map(String).join(' ') : String(error) - expect(messages).toContain('admitted-work drain exceeded five seconds') - expect(performance.now() - started).toBeGreaterThanOrEqual(4_900) - expect(performance.now() - started).toBeLessThan(7_000) + expect(messages).toContain( + `admitted-work drain exceeded the shutdown timeout (${DRAIN} ms)`, + ) + expect(performance.now() - started).toBeGreaterThanOrEqual(DRAIN - 100) + expect(performance.now() - started).toBeLessThan(DRAIN + 2_000) release.resolve() await done.promise await Bun.sleep(10) From b24d34427f5aa62006088f4cd6121046efd07e18 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 11:49:17 -0300 Subject: [PATCH 04/20] fix(stop): keep a job's outcome, liveness and step statuses on release (F2 review) - R1: release() does nothing for a job an earlier abort already ends (failed handler, timeout, cancel): it is failed/cancelled, not released, and its steps are written. An invalid output during stop fails the job. - R2: steps that a release left unwritten are written (cancelled/failed) before a job that still completes or fails, so no finished job keeps an active step. - R3: the Client keeps heartbeating during the admitted-work drain until its jobs ended (no beat after the drain phase), and a job is released only once its handler and step callbacks settled. Another worker's recovery no longer runs a job that still runs on a stopping worker, also with shutdownTimeout > heartbeatTimeout (native multi-worker test). - A1: a job dequeued just before stop is released, not cancelled. - A2: cancel() during stop cancels a released job at once, also while its handler never settles. - A3: releaseJob false/throw is logged as left to recovery (no "released" log), and the job span always ends. - A4: postgres.js end() timeout is min(5 s, shutdownTimeout). - A5: orphaned setJobSpan JSDoc. - Docs: shutdownTimeout and heartbeat during the drain, release never deletes steps vs recovery with an unknown checksum (rolling deploys), custom adapter behaviour change (cancel -> left active for recovery). --- packages/docs/content/docs/adapters.mdx | 2 +- packages/docs/content/docs/client-api.mdx | 14 +- packages/docs/content/docs/multi-worker.mdx | 6 +- packages/duron/src/action-job.ts | 154 +++++---- packages/duron/src/action-manager.ts | 18 +- .../duron/src/adapters/postgres/postgres.ts | 4 +- .../duron/src/adapters/postgres/prune-lock.ts | 7 +- packages/duron/src/client.ts | 57 +++- packages/duron/src/lifecycle.ts | 9 + packages/duron/src/step-manager.ts | 65 +++- packages/duron/test/shutdown-release.test.ts | 296 ++++++++++++++++++ 11 files changed, 542 insertions(+), 90 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 0d0ca1f..9ce96fb 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -397,7 +397,7 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). For its own recoveries, the Client tells the built-in `_recoverJobs` which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom `_recoverJobs` keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A direct `recoverJobs()` call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs. -A graceful `Client.stop()` returns the jobs it did not finish to the queue through `releaseJob()`, which calls `_releaseJob({ jobId })`. The built-in adapters set the job back to `created` (start, expiry and owner cleared) when it is still `active`, owned by this adapter's id and not expired, and keep its steps. The default `_releaseJob` of the `Adapter` class releases nothing and returns `false`: with a custom adapter that does not override it, the unfinished jobs stay `active` until recovery requeues them, as before releases existed. +A graceful `Client.stop()` returns the jobs it did not finish to the queue through `releaseJob()`, which calls `_releaseJob({ jobId })`. The built-in adapters set the job back to `created` (start, expiry and owner cleared) when it is still `active`, owned by this adapter's id and not expired, and keep its steps. The default `_releaseJob` of the `Adapter` class releases nothing and returns `false`, and the Client logs a warning for each job it could not release. This changes the behavior of a custom adapter that does not override it: before releases existed, `stop()` cancelled the running jobs (`_cancelJob`), and only claimed jobs that had not started stayed `active`. Now neither kind is cancelled: both stay `active` with this adapter's id until recovery requeues them (another worker's recovery once this adapter's liveness row is deleted or stale, or a startup recovery with the same id). Override `_releaseJob` to return them to the queue at once. ## Best Practices diff --git a/packages/docs/content/docs/client-api.mdx b/packages/docs/content/docs/client-api.mdx index a14b4fe..7ea3b4f 100644 --- a/packages/docs/content/docs/client-api.mdx +++ b/packages/docs/content/docs/client-api.mdx @@ -223,9 +223,11 @@ Recovery checks for: **Optional.** Budget in milliseconds of each phase of [`stop()`](#stop): settling a startup that is still running, draining admitted work (running handlers and steps, their final writes, and the release of the jobs that did not finish), database cleanup, and closing the adapter's connections. A phase that exceeds it makes `stop()` reject. It applies to this Client's adapter. An integer from `1` to `2147483647`; other values make the constructor throw. Defaults to `5000` (5 seconds). +The stopping Client keeps its heartbeat (every `heartbeatInterval`) until each of its jobs is completed, failed, cancelled or released, so the drain can last longer than `heartbeatTimeout`: other workers do not recover a job that still runs here. A job whose handler or step does not settle within `shutdownTimeout` stays `active`: the heartbeat stops when the drain phase ends, and recovery requeues the job once this Client's liveness is gone. + ```ts { - shutdownTimeout: 10_000, // give running jobs up to 10 seconds to finish or release + shutdownTimeout: 30_000, // give running jobs up to 30 seconds to finish or be released } ``` @@ -287,11 +289,13 @@ await client.stop() A graceful stop releases unfinished jobs instead of cancelling them: -- Each running handler is aborted: its steps' `signal` aborts with an `ActionCancelError`. Once the handler settles, a handler that still resolves completes its job normally (its output is validated). A handler that rejects, for example because a step honored the abort, returns its job to the queue. +- Each running handler is aborted: its steps' `signal` aborts with an `ActionCancelError`. Once the handler settles, a handler that still resolves completes its job normally: its output is validated (an invalid output fails the job), and the steps that the abort ended are stored `cancelled` (or `failed`). A handler that rejects, for example because a step honored the abort, returns its job to the queue once its step callbacks have ended too, so the job does not run on another worker while its handler or a step callback still runs here. +- A job that already ended before the stop reached it keeps its outcome: a handler that failed or timed out fails its job, a cancelled job is cancelled. - Claimed jobs that have not started (queued behind `actionConcurrencyLimit`, or claimed while the stop began) are returned to the queue too. -- A returned job is `created` again, without an owner, start or expiry, and a `job-available` notification is sent, so any worker can claim it. Its steps are kept, as [recovery](/docs/multi-worker#job-recovery) keeps them: the next run reuses completed steps and runs again the steps that were running or waiting for a retry, whose retry count starts again at 0. Jobs have no attempt counter, so a release does not count as a failed attempt. -- An explicit `cancelJob()` still cancels: a job cancelled before or during the stop ends `cancelled`, not released. -- The drain waits for the handlers within [`shutdownTimeout`](#shutdowntimeout). A handler that does not settle in time is not released: the stop rejects, the job stays `active`, and recovery requeues it once this Client's liveness is gone (another worker's periodic recovery, or this `id`'s next startup). +- A returned job is `created` again, without an owner, start or expiry, and a `job-available` notification is sent, so any worker can claim it. A release never deletes its steps: the next run reuses completed steps (with their stored output) and runs again the steps that were running or waiting for a retry, whose retry count starts again at 0. Jobs have no attempt counter, so a release does not count as a failed attempt. +- Unlike a release, [recovery](/docs/multi-worker#job-recovery) deletes the steps of a requeued job when the recovering worker does not know the job's action checksum (its handler code or `version` changed). A claim does not compare checksums. So in a rolling deploy, a worker with the new code that claims a job released by an old worker reuses the outputs of the steps that the old code completed, matched by step name and parent step, and runs only the others. Keep step outputs compatible across versions, or give a step whose output changed a new name. +- An explicit `cancelJob()` still cancels: a job cancelled before or during the stop ends `cancelled`, not released, also while the stop waits for its handler. +- The drain waits for the handlers within [`shutdownTimeout`](#shutdowntimeout), and the Client keeps its heartbeat meanwhile. A handler or step that does not settle in time is not released: the stop rejects, the job stays `active`, and recovery requeues it once this Client's liveness is gone (another worker's periodic recovery, or this `id`'s next startup). Breaking change: before, `stop()` cancelled every running job, and its queued jobs stayed claimed diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index e0d3003..c9856e4 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -321,7 +321,7 @@ After a successful drain, shutdown deletes the instance's liveness row before cl ### Heartbeat clock and failure limits -The initial heartbeat must succeed before Client startup can succeed. Startup failure triggers automatic cleanup. A periodic heartbeat failure is logged through the configured logger, is nonfatal, and is retried at the normal heartbeat cadence only while running. +The initial heartbeat must succeed before Client startup can succeed. Startup failure triggers automatic cleanup. A periodic heartbeat failure is logged through the configured logger, is nonfatal, and is retried at the normal heartbeat cadence only while running. During `stop()`, the heartbeat continues at the same cadence until every job of the Client is completed, failed, cancelled or released, then stops before the liveness row is deleted. A drain longer than `heartbeatTimeout` therefore does not let other workers recover a job that still runs. No beat is sent after the admitted-work drain ends, also when it exceeds `shutdownTimeout`. SQL `now()` is transaction-start time, not continuously advancing wall time or commit time. Using it removes the application-clock offset from new heartbeat writes, but does not provide an execution lease or prevent duplicate effects. Delayed or failed writes, event-loop stalls and SQL clock movement can still affect recovery. Native SQL precision and the strict freshness comparison are preserved. Existing rows are not migrated; an ordinary heartbeat can replace a legacy future timestamp with an earlier SQL timestamp. @@ -339,7 +339,7 @@ There is no ordinary notification deadline or background delivery queue. A stuck ## Lifecycle and Shutdown -`client.stop()` closes admission immediately: it cancels scheduled heartbeat/discovery/prune timers, discards pending automatic discovery, rejects queued `client.fetch()` calls that have not started, disables new event-driven work, settles pending waits with `null`, and aborts running handlers. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. Jobs that do not finish are returned to the queue (`created`, without an owner) and announced with a `job-available` notification, so another worker claims them: a handler that still resolves after the abort completes its job, the others, and the claimed jobs that did not start, are released. See [`stop()`](/docs/client-api#stop). It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. +`client.stop()` closes admission immediately: it cancels scheduled discovery/prune timers (the heartbeat continues until the Client's jobs have ended, see [Heartbeat clock and failure limits](#heartbeat-clock-and-failure-limits)), discards pending automatic discovery, rejects queued `client.fetch()` calls that have not started, disables new event-driven work, settles pending waits with `null`, and aborts running handlers. A discovery that has already started issues no new claim after the stop, and locally queued jobs do not start. Jobs that do not finish are returned to the queue (`created`, without an owner) and announced with a `job-available` notification, so another worker claims them: a handler that still resolves after the abort completes its job, the others, and the claimed jobs that did not start, are released (a job is released only once its handler and step callbacks have ended here). See [`stop()`](/docs/client-api#stop). It observes actual admitted callbacks, actions and steps, including work that outlives an abort observer. Already-admitted operations and finalization may finish during draining; a late fetch result cannot start a new job handler. Client and Adapter share four shutdown phases, each with the budget set by the Client's [`shutdownTimeout`](/docs/client-api#shutdowntimeout) option (5 seconds by default). Each budget applies to the whole phase, not separately to nested calls or individual resources: @@ -398,7 +398,7 @@ Keep `heartbeatTimeout` at least 3x `heartbeatInterval` to tolerate occasional m - **Separate dashboard and workers**: Run dashboard/server in a separate process to avoid resource competition - **Monitor worker health**: Use process managers (PM2, systemd, etc.) to restart failed workers -- **Graceful shutdown**: Handle `SIGINT`/`SIGTERM`, await `client.stop()`, and report cleanup failures. Unfinished jobs return to the queue for the other workers; make steps honor their `signal` so that handlers end within `shutdownTimeout`, and keep the orchestrator's grace period (for example Kubernetes' `terminationGracePeriodSeconds`) above the stop's phases. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence. +- **Graceful shutdown**: Handle `SIGINT`/`SIGTERM`, await `client.stop()`, and report cleanup failures. Unfinished jobs return to the queue for the other workers; make steps honor their `signal` so that handlers end within `shutdownTimeout`, and keep the orchestrator's grace period (for example Kubernetes' `terminationGracePeriodSeconds`) above the stop's phases (up to four `shutdownTimeout` budgets). The stopping worker keeps its heartbeat while it drains, so `shutdownTimeout` can exceed `heartbeatTimeout`. Cancellation is cooperative; decide process-exit policy separately from resource-release evidence. ### Scaling diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index e10053c..bf81f34 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -56,6 +56,8 @@ export class ActionJob> { #cancelled = false /** A graceful stop aborted the job: it is returned to the queue (see `release`). */ #releasing = false + /** Resolved by `cancel()`: a released job that waits for its handler is cancelled at once. */ + #cancelRequested = Promise.withResolvers<'cancelled'>() #jobSpan!: Span // ============================================================================ @@ -227,33 +229,13 @@ export class ActionJob> { isCancelError(error) || (error instanceof Error && error.name === 'AbortError' && isCancelError(error.cause)) ) { - this.#logger.warn( - { jobId: this.#job.id, actionName: this.#action.name }, - '[ActionJob] Job cancelled', - ) - await this.#database.cancelJob({ jobId: this.#job.id }) - - // End job span as cancelled - this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job cancelled' }) - this.#jobSpan.end() - return - } - - const message = isTimeoutError(error) ? '[ActionJob] Job timed out' : '[ActionJob] Job failed' - - this.#logger.error({ jobId: this.#job.id, actionName: this.#action.name }, message) - await this.#database.failJob({ jobId: this.#job.id, error: serializeError(error) }) - - // End job span with error - this.#jobSpan.setStatus({ - code: SpanStatusCode.ERROR, - message: error instanceof Error ? error.message : String(error), - }) - if (error instanceof Error) { - this.#jobSpan.recordException(error) + return await this.#finishCancelled() } - this.#jobSpan.end() + // A failing job keeps no active step: write the final step statuses that a release + // left unwritten (a step timeout that raced with the stop; a no-op otherwise). + await this.#stepManager.writeSkipped() + await this.#finishFailed(error) throw error } finally { this.#clear() @@ -285,6 +267,7 @@ export class ActionJob> { */ cancel() { this.#cancelled = true + this.#cancelRequested.resolve('cancelled') this.#clear() const cancelError = new ActionCancelError(this.#action.name, this.#job.id) this.#abortController.abort(cancelError) @@ -294,8 +277,12 @@ export class ActionJob> { * Graceful stop: abort the handler like `cancel()` (its signal's reason is an * ActionCancelError), but return the job to the queue instead of cancelling it, unless its * handler still completes (see `#finishReleased`). A later `cancel()` still cancels it. + * + * A job that an earlier abort already ends (its handler failed, it timed out or it was + * cancelled) keeps that outcome: it is not released, and its steps are written as usual. */ release() { + if (this.#abortController.signal.aborted) return this.#releasing = true this.#stepManager.release() this.#clear() @@ -309,31 +296,40 @@ export class ActionJob> { // ============================================================================ /** - * End a job that a graceful stop aborted. Waits for its raw handler: a handler that still - * resolves completes the job normally (output validated); one that rejects, or a failed - * completion, returns the job to the queue (`releaseJob`). The steps already kept their - * stored status (see StepManager.release). An explicit `cancel()` meanwhile cancels it. A - * handler that awaits `stop()` itself cannot settle before stop does: that job is - * cancelled, as before, so that it does not stop the next worker that would claim it. + * End a job that a graceful stop aborted. Waits for its raw handler: + * - A handler that resolves completes the job normally. The steps that ended after the + * release are first written with the status they would have had without it (see + * `StepManager.writeSkipped`), so no step of the finished job stays active. An output that + * fails validation fails the job: a new run would produce the same result. + * - A handler that rejects, or a completion that fails, returns the job to the queue + * (`releaseJob`) once its step callbacks settled too. Its steps keep their stored status + * (see `StepManager.release`). + * - An explicit `cancel()` cancels the job, also while this waits for a handler or a step + * callback that does not settle. A handler or step that awaits `stop()` itself cannot + * settle before stop does: that job is cancelled, as before, so that it does not stop the + * next worker that claims it. */ async #finishReleased(): Promise { - const lifecycle = lifecycleFor(this.#database) - const handled = await lifecycle.settledOrExcluded(this.#handler) - let outcome: 'complete' | 'release' | 'cancel' = 'release' - let result: unknown - if (handled === 'excluded' || this.#cancelled) { - outcome = 'cancel' - } else { - const settled = await Promise.allSettled([this.#handler]) - if (this.#handlerInvoked && settled[0].status === 'fulfilled') { - outcome = 'complete' - result = settled[0].value ?? null + const handled = this.#cancelled + ? 'cancelled' + : await Promise.race([ + lifecycleFor(this.#database).settledOrExcluded(this.#handler), + this.#cancelRequested.promise, + ]) + if (handled !== 'settled' || this.#cancelled) return await this.#finishCancelled() + const [settled] = await Promise.allSettled([this.#handler]) + if (this.#handlerInvoked && settled.status === 'fulfilled') { + let output: unknown = settled.value ?? null + try { + if (this.#action.output) output = await validateSchema(this.#action.output, output) + } catch (error) { + await this.#stepManager.writeSkipped() + await this.#finishFailed(error) + throw error } - } - if (outcome === 'complete') { try { - if (this.#action.output) result = await validateSchema(this.#action.output, result) - if (await this.#database.completeJob({ jobId: this.#job.id, output: result })) { + await this.#stepManager.writeSkipped() + if (await this.#database.completeJob({ jobId: this.#job.id, output })) { this.#logger.debug( { jobId: this.#job.id, actionName: this.#action.name }, '[ActionJob] Action finished executing during stop', @@ -349,22 +345,66 @@ export class ActionJob> { ) } } - if (outcome === 'cancel') { + // Release only once no step callback of the job runs here, so that the job does not run + // on another worker at the same time. A callback that awaits stop() cancels the job. + const callbacks = await Promise.race([ + this.#stepManager.callbacksSettled(), + this.#cancelRequested.promise, + ]) + if (callbacks !== 'settled' || this.#cancelled) return await this.#finishCancelled() + await this.#finishRelease() + } + + /** Return the job to the queue. Never rejects: a job not released stays for recovery. */ + async #finishRelease(): Promise { + const log = { jobId: this.#job.id, actionName: this.#action.name } + let released = false + try { + released = await this.#database.releaseJob({ jobId: this.#job.id }) + if (released) { + this.#logger.info(log, '[ActionJob] Job released to the queue on stop') + } else { + // The default of a custom adapter, or a job that is no longer this worker's active job + // (finished, cancelled or recovered elsewhere, or expired). + this.#logger.warn( + log, + '[ActionJob] Job not released on stop: an active job is left to recovery', + ) + } + } catch (error) { this.#logger.warn( - { jobId: this.#job.id, actionName: this.#action.name }, - '[ActionJob] Job cancelled', + { ...log, error }, + '[ActionJob] Could not release job on stop: it is left active for recovery', ) - await this.#database.cancelJob({ jobId: this.#job.id }) - this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job cancelled' }) - this.#jobSpan.end() - return } - this.#logger.info( + this.#jobSpan.setStatus({ + code: SpanStatusCode.ERROR, + message: released ? 'Job released' : 'Job not released', + }) + this.#jobSpan.end() + } + + async #finishCancelled(): Promise { + this.#logger.warn( { jobId: this.#job.id, actionName: this.#action.name }, - '[ActionJob] Job released to the queue on stop', + '[ActionJob] Job cancelled', ) - await this.#database.releaseJob({ jobId: this.#job.id }) - this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job released' }) + await this.#database.cancelJob({ jobId: this.#job.id }) + this.#jobSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'Job cancelled' }) + this.#jobSpan.end() + } + + async #finishFailed(error: unknown): Promise { + const message = isTimeoutError(error) ? '[ActionJob] Job timed out' : '[ActionJob] Job failed' + this.#logger.error({ jobId: this.#job.id, actionName: this.#action.name }, message) + await this.#database.failJob({ jobId: this.#job.id, error: serializeError(error) }) + this.#jobSpan.setStatus({ + code: SpanStatusCode.ERROR, + message: error instanceof Error ? error.message : String(error), + }) + if (error instanceof Error) { + this.#jobSpan.recordException(error) + } this.#jobSpan.end() } diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index c6405ed..ff5d9e9 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -189,9 +189,20 @@ export class ActionManager> { #releaseUnstarted(jobId: string): Promise { if (this.#cancellation.cancelling(jobId)) return this.#cancellation.consumeQueued(jobId) const released = this.#database.releaseJob({ jobId }).then( - () => undefined, + (done) => { + // The default of a custom adapter, or a job no longer this worker's active job. + if (!done) { + this.#logger.warn( + { jobId }, + `[ActionManager] Job ${jobId} not released on stop: an active job is left to recovery`, + ) + } + }, (error: unknown) => { - this.#logger.warn({ error, jobId }, `[ActionManager] Could not release job ${jobId}`) + this.#logger.warn( + { error, jobId }, + `[ActionManager] Could not release job ${jobId}: it is left active for recovery`, + ) }, ) return Promise.all([released, this.#cancellation.consumeQueued(jobId)]).then(() => undefined) @@ -232,6 +243,9 @@ export class ActionManager> { }) this.#activeJobs.set(job.id, actionJob) track(() => actionJob.settled()) + // Dequeued just before stop() began (its releaseAll did not see this job): release it like + // the others, instead of letting it fail the lifecycle check and be cancelled. + if (this.#stopped) actionJob.release() try { // Execute the job - all error handling is done inside ActionJob.execute() diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index ed3216b..3d41408 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -6,7 +6,7 @@ import { migrate } from 'drizzle-orm/postgres-js/migrator' import { defineRelations } from 'drizzle-orm/relations' import type { Options as PostgresOptions } from 'postgres' -import { lifecycleFor } from '../../lifecycle.js' +import { driverEndTimeout, lifecycleFor } from '../../lifecycle.js' import type { WaitReadBudget } from '../../wait-read.js' import { type AdapterOptions, PostgresBaseAdapter, type PruneLockReplacement } from './base.js' @@ -162,7 +162,7 @@ export class PostgresAdapter extends PostgresBaseAdapter | null = null #heartbeatTimer: NodeJS.Timeout | null = null + /** performance.now() of the next scheduled heartbeat (see #heartbeatWhileDraining). */ + #heartbeatDueAt = 0 #discovery: WorkerDiscovery | null = null #cancellation: LocalCancellation #actionManagers = new Map>>() @@ -1229,6 +1233,7 @@ export class Client< } #quiesce(): Promise { + const beating = this.#heartbeatTimer !== null if (this.#heartbeatTimer) { clearTimeout(this.#heartbeatTimer) this.#heartbeatTimer = null @@ -1245,9 +1250,54 @@ export class Client< this.#pushListenerSetup = false } this.#waits.stop() - return Promise.all([...this.#actionManagers.values()].map((manager) => manager.stop())).then( - () => undefined, - ) + const stopped = Promise.all( + [...this.#actionManagers.values()].map((manager) => manager.stop()), + ).then(() => undefined) + if (!beating) return stopped + const stopBeating = this.#heartbeatWhileDraining() + return stopped.finally(stopBeating) + } + + /** + * Keep this Client's liveness while stop() drains its jobs: until each job is completed, + * failed, cancelled or released. Other workers' recovery requeues the active jobs of a + * client whose last heartbeat is older than `heartbeatTimeout`, so without it a drain + * longer than that would let another worker run a job whose handler still runs here. + * The beats run in the quiesce hook's operation context, which the drain waits for. A beat + * is never issued once the drain phase ends (the lifecycle rejects it), so a job whose + * handler does not settle within `shutdownTimeout` is left to recovery once database + * cleanup removes the liveness record. Returns a function that stops the beats. + */ + #heartbeatWhileDraining(): () => void { + const inQuiesce = AsyncLocalStorage.snapshot() + let timer: NodeJS.Timeout | null = null + let stopped = false + // The first beat keeps the cadence of the periodic heartbeat that quiesce cleared. + let delay = Math.max(0, this.#heartbeatDueAt - performance.now()) + const schedule = () => { + if (stopped || !this.#lifecycle.ordinaryOpen) return + timer = setTimeout(() => { + timer = null + inQuiesce(() => { + if (stopped || !this.#lifecycle.ordinaryOpen) return + this.#database.heartbeat().then(schedule, (error: unknown) => { + if (this.#lifecycle.ordinaryOpen) { + this.#logger.error({ error }, '[Duron] Heartbeat during stop failed') + } + schedule() + }) + }) + }, delay) + delay = this.#options.heartbeatInterval + // The drain itself keeps the process alive while there is work to wait for. + timer.unref?.() + } + schedule() + return () => { + stopped = true + if (timer) clearTimeout(timer) + timer = null + } } // ============================================================================ @@ -1408,6 +1458,7 @@ export class Client< return } + this.#heartbeatDueAt = performance.now() + this.#options.heartbeatInterval this.#heartbeatTimer = setTimeout(() => { if (!this.#lifecycle.accepting) return // A root context: each beat schedules the next, so they must not link into a chain. diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index 5e38dc8..c5aa120 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -62,6 +62,15 @@ function signal(): { promise: Promise; resolve: () => void } { /** Default budget of each shutdown phase (Client option `shutdownTimeout`). */ export const DEFAULT_SHUTDOWN_TIMEOUT = 5_000 +/** + * The `timeout` (seconds) of a postgres.js `end()` in the owned close: at most 5 s, and not + * longer than the close's budget, so that a short `shutdownTimeout` still lets `end()` force + * the connections closed before the budget expires. + */ +export function driverEndTimeout(lifecycle: Lifecycle): number { + return Math.min(5, lifecycle.shutdownTimeout / 1000) +} + // A deadline bounds observation, not execution. The losing promise remains observed. class ShutdownBudget { readonly #deadline: number diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index 813da9c..f81c3cf 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -344,6 +344,10 @@ export class StepManager { // Store the job span for creating step spans #jobSpan!: Span #releasing = false + // Final step writes that a release skipped (see `release` and `writeSkipped`) + #skippedWrites: Array<() => Promise> = [] + // Raw step callbacks that have not settled (an abort can settle their step first) + #callbacks = new Set>() // Factory function to create run functions with the correct parent step ID and abort signal #runFnFactory: | ((parentStepId: string | null, abortSignal: AbortSignal) => StepHandlerContext['run']) @@ -395,19 +399,50 @@ export class StepManager { ) } - /** - * Set the job span for this step manager. - * Called from ActionJob after the job span is created. - */ /** * The job is being released to the queue (graceful stop): steps that end from now on keep - * their stored status (as recovery keeps them), so a new run of the job runs them again - * instead of failing on a step stored as cancelled or failed. + * their stored status (`active`, as recovery keeps them), so a new run of the job runs them + * again instead of failing on a step stored as cancelled or failed. Their final writes are + * kept for `writeSkipped`. */ release(): void { this.#releasing = true } + /** + * The released job ends anyway (its handler resolved, or it fails): write the final status + * (cancelled or failed) that `release` skipped, so the finished job keeps no active step. + */ + async writeSkipped(): Promise { + await Promise.all(this.#skippedWrites.splice(0).map((write) => write())) + } + + /** + * Resolves once no step callback of this job runs (`'settled'`), or once one is excluded + * from the drain because it awaits `stop()` (`'excluded'`). An aborted step settles before + * its callback when the callback ignores the abort: a released job must not run again + * elsewhere while that callback still runs here. Never rejects. + */ + async callbacksSettled(): Promise<'settled' | 'excluded'> { + while (this.#callbacks.size > 0) { + const outcomes = [...this.#callbacks].map((callback) => + this.#lifecycle.settledOrExcluded(callback), + ) + const excluded = new Promise<'excluded'>((resolve) => { + for (const outcome of outcomes) { + void outcome.then((value) => value === 'excluded' && resolve('excluded')) + } + }) + const settled = Promise.all(outcomes).then(() => 'settled' as const) + if ((await Promise.race([excluded, settled])) === 'excluded') return 'excluded' + } + return 'settled' + } + + /** + * Set the job span for this step manager. + * Called from ActionJob after the job span is created. + */ setJobSpan(span: Span): void { this.#jobSpan = span } @@ -744,6 +779,9 @@ export class StepManager { // User code: a stop() it awaits is excluded from the drain (see Lifecycle.stop). { userCode: true }, ) + this.#callbacks.add(callbackPromise) + const untrack = () => this.#callbacks.delete(callbackPromise) + callbackPromise.then(untrack, untrack) let result: any = null let aborted = false @@ -935,17 +973,16 @@ export class StepManager { this.#stepSpans.delete(step.id) } + const stepId = step.id + const write = isCancelError(error) + ? () => this.#stepStore.updateStatus(stepId, STEP_STATUS_CANCELLED) + : () => + this.#stepStore.updateStatus(stepId, STEP_STATUS_FAILED, null, serializeError(error)) if (this.#releasing) { // Released job: the step keeps its stored status for the next run. - } else if (isCancelError(error)) { - await this.#stepStore.updateStatus(step.id, 'cancelled') + this.#skippedWrites.push(write) } else { - await this.#stepStore.updateStatus( - step.id, - STEP_STATUS_FAILED, - null, - serializeError(error), - ) + await write() } } throw error diff --git a/packages/duron/test/shutdown-release.test.ts b/packages/duron/test/shutdown-release.test.ts index e227769..06bed6d 100644 --- a/packages/duron/test/shutdown-release.test.ts +++ b/packages/duron/test/shutdown-release.test.ts @@ -79,6 +79,17 @@ async function stepRows(adapter: Adapter, jobId: string) { return Object.fromEntries(rows.map((row) => [row['name'], row['status']])) } +async function inspect(store: Store, jobId: string) { + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + return { job: (await jobRow(reader, jobId))?.['status'], steps: await stepRows(reader, jobId) } + } finally { + await reader.stop() + } +} + async function until(check: () => boolean, ms = 5_000) { const end = performance.now() + ms while (!check()) { @@ -319,6 +330,245 @@ for (const { name, create: createStore } of stores) { } }, 30_000) }) + + describe(`Graceful stop keeps the outcome a job already has`, () => { + it(`fails a job whose handler failed before the stop (${name})`, async () => { + const store = await createStore() + const failing = Promise.withResolvers() + const action = defineAction()({ + name: 'fails', + handler: async (ctx) => { + await Promise.all([ + ctx.step( + 'slow', + async () => { + await Bun.sleep(400) + return {} + }, + { parallel: true }, + ), + ctx.step( + 'boom', + async () => { + await Bun.sleep(20) + throw new Error('boom') + }, + { parallel: true, retry: { limit: 0 } }, + ), + ]) + return {} + }, + }) + try { + const adapter = store.adapter() + // The job failed: its handler rejected. Hold the aborted sibling's write, so that the + // job's fail write waits for the step drain while stop() begins. + const failJobStep = adapter.failJobStep.bind(adapter) + let calls = 0 + adapter.failJobStep = async (options) => { + if (++calls === 2) { + failing.resolve() + await Bun.sleep(300) + } + return failJobStep(options) + } + const worker = client(adapter, { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await failing.promise + expect(await worker.stop()).toBe(true) + expect(await inspect(store, jobId)).toEqual({ + job: 'failed', + steps: { boom: 'failed', slow: 'failed' }, + }) + } finally { + await store.close() + } + }, 30_000) + + it(`fails a job whose handler resolves an invalid output during the stop (${name})`, async () => { + const store = await createStore() + const started = Promise.withResolvers() + const finish = Promise.withResolvers() + const action = defineAction()({ + name: 'invalid-output', + output: z.object({ value: z.number() }), + handler: async () => { + started.resolve() + await finish.promise + return { value: 'not a number' } as unknown as { value: number } + }, + }) + try { + const worker = client(store.adapter(), { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await started.promise + const stopping = worker.stop() + await Bun.sleep(50) + finish.resolve() + expect(await stopping).toBe(true) + expect((await inspect(store, jobId)).job).toBe('failed') + } finally { + await store.close() + } + }, 30_000) + + it(`completes a job during the stop without leaving an active step (${name})`, async () => { + const store = await createStore() + const inStep = Promise.withResolvers() + const action = defineAction()({ + name: 'fallback', + handler: async (ctx) => { + await ctx.step('done', async () => ({})) + try { + await ctx.step('wait', async ({ signal }) => { + inStep.resolve() + await new Promise((_, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }) + }) + }) + } catch { + return { fallback: true } + } + return {} + }, + }) + try { + const worker = client(store.adapter(), { action }) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await inStep.promise + expect(await worker.stop()).toBe(true) + expect(await inspect(store, jobId)).toEqual({ + job: 'completed', + steps: { done: 'completed', wait: 'cancelled' }, + }) + } finally { + await store.close() + } + }, 30_000) + + it(`cancels a job that is cancelled during the stop while its handler never settles (${name})`, async () => { + const store = await createStore() + const started = { stuck: false, canceller: false } + let stuckId = '' + let worker!: Client + const stuck = defineAction()({ + name: 'stuck', + handler: async () => { + started.stuck = true + await new Promise(() => undefined) + return {} + }, + }) + const canceller = defineAction()({ + name: 'canceller', + handler: async (ctx) => { + // On the stop's abort, this step (an admitted operation) cancels the stuck job. + await ctx.step('cancel-other', async ({ signal }) => { + started.canceller = true + await new Promise((_, reject) => { + signal.addEventListener( + 'abort', + () => { + // Later than the stuck job's release: it already waits for its handler. + void Bun.sleep(100) + .then(() => worker.cancelJob(stuckId)) + .catch(() => undefined) + .finally(() => reject(signal.reason)) + }, + { once: true }, + ) + }) + }) + return {} + }, + }) + try { + worker = client(store.adapter(), { stuck, canceller }, { shutdownTimeout: 500 }) + await worker.start() + stuckId = await worker.runAction('stuck', {}) + await worker.runAction('canceller', {}) + await worker.fetch({ batchSize: 2 }) + await until(() => started.stuck && started.canceller) + const failure = await worker.stop().then( + () => null, + (error: unknown) => error, + ) + // The handler never settles: the drain still exceeds its budget. + expect(failure).not.toBeNull() + expect((await inspect(store, stuckId)).job).toBe('cancelled') + } finally { + await store.close() + } + }, 30_000) + + it(`keeps the liveness of a stopping worker until its jobs are released (${name})`, async () => { + const store = await createStore() + const inStep = Promise.withResolvers() + let ended = false + const action = defineAction()({ + name: 'slow-stop', + handler: async (ctx) => { + await ctx.step('work', async () => { + inStep.resolve() + // Ignores the abort: the drain lasts longer than the heartbeat timeout. + await Bun.sleep(800) + ended = true + return {} + }) + return {} + }, + }) + try { + const adapter = store.adapter() + const worker = client( + adapter, + { action }, + { heartbeatInterval: 50, heartbeatTimeout: 200, shutdownTimeout: 3_000 }, + ) + await worker.start() + const jobId = await worker.runAction('action', {}) + await worker.fetch() + await inStep.promise + const stopping = worker.stop() + await Bun.sleep(500) + // Recovery of another worker treats an owner as dead once last_seen_at is older than + // the heartbeat timeout: the stopping worker keeps beating while it drains. + const [row] = await query( + adapter, + sql`SELECT (extract(epoch FROM now() - last_seen_at) * 1000)::int AS age + FROM duron.clients WHERE client_id = ${adapter.id}`, + ) + expect(row?.['age']).toBeLessThan(200) + expect(await stopping).toBe(true) + expect(ended).toBe(true) + const reader = store.adapter() + reader.setId('release-reader') + await reader.start() + try { + // Released once the step callback ended. + expect(await stepRows(reader, jobId)).toEqual({ work: 'active' }) + expect((await jobRow(reader, jobId))?.['status']).toBe('created') + // No beat after the drain: the stop removed the liveness row for good. + await Bun.sleep(150) + const rows = await query( + reader, + sql`SELECT client_id FROM duron.clients WHERE client_id = ${adapter.id}`, + ) + expect(rows).toEqual([]) + } finally { + await reader.stop() + } + } finally { + await store.close() + } + }, 30_000) + }) } describe('shutdownTimeout option', () => { @@ -380,5 +630,51 @@ if (process.env['POSTGRES_TEST'] === 'true') { await store.close() } }, 30_000) + + it('does not let another worker run a job while a stopping worker still runs it (shutdownTimeout > heartbeatTimeout)', async () => { + const store = await postgresStore() + const inStep = Promise.withResolvers() + const events: string[] = [] + const action = defineAction()({ + name: 'long-drain', + handler: async (ctx) => { + events.push('run') + await ctx.step('work', async () => { + if (events.length === 1) { + inStep.resolve() + // Ignores the abort: the drain lasts several heartbeat timeouts. + await Bun.sleep(1_200) + } + events.push('step end') + return {} + }) + return {} + }, + }) + const liveness = { heartbeatInterval: 100, heartbeatTimeout: 300 } + const a = client(store.adapter(), { action }, { ...liveness, shutdownTimeout: 5_000 }) + const b = client( + store.adapter(), + { action }, + { ...liveness, syncPattern: 'pull', pullInterval: 50, recoverJobsInterval: 50 }, + ) + try { + await a.start() + const jobId = await a.runAction('action', {}) + await a.fetch() + await inStep.promise + // B starts after A claimed the job, and runs recovery every 50 ms. + await b.start() + expect(await a.stop()).toBe(true) + const result = await b.waitForJob(jobId, { timeout: 5_000 }) + expect(result?.status).toBe('completed') + // B runs the job only after A released it, once A's step callback ended. + expect(events).toEqual(['run', 'step end', 'run', 'step end']) + } finally { + await a.stop().catch(() => undefined) + await b.stop().catch(() => undefined) + await store.close() + } + }, 30_000) }) } From 3417ab4c46e5915f5aa4a62777bc61fb570ada89 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 12:14:11 -0300 Subject: [PATCH 05/20] fix: database-clock finished_at, migrate lock, per-schema prune key, getTracer name - finished_at of jobs and steps (and archived steps' job_finished_at) from the database clock (now()) instead of the JavaScript clock. - migrate() runs in one transaction after pg_advisory_xact_lock( hashtextextended('duron:migrate:duron', 0)): concurrent cold starts no longer race on DDL (PGlite: same path). - Scheduled-prune advisory key derived from the schema: hashtextextended('duron:prune:', 0) instead of 42; docs with a rolling-upgrade note (old/new workers may prune concurrently, harmless). - TelemetryContext.getTracer(name) returns the application provider's tracer `name` (context-aware), not Duron's tracer. - Claim timeouts keep a lower operator lock_timeout / idle_in_transaction_session_timeout (read once at startup); comment nit. - Adapter._heldJobIds(options): protected accessor for custom _recoverJobs. - driverEndTimeout = min(5 s, 80% of shutdownTimeout) so the forced end fires inside the owned-close budget; N1 known-limit comment on release after a failed completion. --- packages/docs/content/docs/adapters.mdx | 10 +- packages/docs/content/docs/multi-worker.mdx | 2 +- packages/docs/content/docs/telemetry.mdx | 2 +- packages/duron/src/action-job.ts | 10 +- packages/duron/src/action-manager.ts | 6 +- packages/duron/src/adapters/adapter.ts | 18 ++- packages/duron/src/adapters/postgres/base.ts | 149 ++++++++++++++---- .../duron/src/adapters/postgres/pglite.ts | 13 +- .../duron/src/adapters/postgres/postgres.ts | 15 +- .../duron/src/adapters/postgres/prune-key.ts | 8 + .../duron/src/adapters/postgres/prune-lock.ts | 18 ++- packages/duron/src/client.ts | 3 + packages/duron/src/lifecycle.ts | 8 +- packages/duron/src/step-manager.ts | 24 ++- packages/duron/test/claim-isolation.test.ts | 54 +++++++ packages/duron/test/finished-at-clock.test.ts | 88 +++++++++++ packages/duron/test/lifecycle-sql.test.ts | 35 ++-- packages/duron/test/lifecycle-startup.test.ts | 36 ++++- packages/duron/test/lifecycle.test.ts | 18 ++- .../duron/test/migrate-concurrency.test.ts | 44 ++++++ packages/duron/test/otel-integration.test.ts | 5 + packages/duron/test/prune-bootstrap.test.ts | 8 +- packages/duron/test/prune-key.test.ts | 64 ++++++++ packages/duron/test/prune-loss.test.ts | 9 +- packages/duron/test/prune-ownership.test.ts | 30 ++-- .../duron/test/prune-pglite-faults.test.ts | 6 +- packages/duron/test/prune-reestablish.test.ts | 6 +- packages/duron/test/prune-replies.test.ts | 2 +- packages/duron/test/prune-scheduler.test.ts | 4 +- packages/duron/test/prune-scope.test.ts | 45 ++++-- packages/duron/test/prune-transport.test.ts | 2 +- .../duron/test/recovery-held-accessor.test.ts | 48 ++++++ 32 files changed, 663 insertions(+), 127 deletions(-) create mode 100644 packages/duron/src/adapters/postgres/prune-key.ts create mode 100644 packages/duron/test/finished-at-clock.test.ts create mode 100644 packages/duron/test/migrate-concurrency.test.ts create mode 100644 packages/duron/test/prune-key.test.ts create mode 100644 packages/duron/test/recovery-held-accessor.test.ts diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 9ce96fb..9b673de 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -86,11 +86,11 @@ The scheduler attempts a pass immediately during startup, then at the configured ### PostgreSQL ownership and scope -An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects that session; only a lost session is replaced by a new client (see below). Each pass acquires session-level advisory key `42` and must receive a true unlock; the reservation is not returned between passes. +An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects that session; only a lost session is replaced by a new client (see below). Each pass acquires the schema's session-level advisory key (see below) and must receive a true unlock; the reservation is not returned between passes. -Key `42` coordinates **across schemas in the same database**, not just one Duron schema. Separate databases do not contend. Avoid using this advisory key for unrelated application locks. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. +The key is derived from the adapter's schema: `hashtextextended('duron:prune:' || schema, 0)` (for the default schema, `hashtextextended('duron:prune:duron', 0)`). Adapters of the same schema coordinate; other Duron schemas in the same database, separate databases and application locks on other keys do not contend. Earlier versions used the constant key `42` for every schema. During a rolling upgrade, a worker of an earlier version (key `42`) and an upgraded worker (the derived key) can prune the same schema at the same time; this is harmless, because a prune pass only deletes archived jobs older than its cutoff, and concurrent passes delete each row once. It ends when every worker is upgraded. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. -Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so key `42` keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start, later ticks try again after a backoff that doubles from the interval up to five minutes. The backoff counts from the failure, and the tick nearest to the due time retries, so a tick that fires slightly early does not add an interval. The replacement never requested the lock, and a new attempt starts only after its close is confirmed, so key `42` keeps a single owner. The fault decides the log level: +Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so the key keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start, later ticks try again after a backoff that doubles from the interval up to five minutes. The backoff counts from the failure, and the tick nearest to the due time retries, so a tick that fires slightly early does not add an interval. The replacement never requested the lock, and a new attempt starts only after its close is confirmed, so the key keeps a single owner. The fault decides the log level: - A connection or server startup fault (connection refused, reset or closed, a connect timeout, SQLSTATE class `08`, `57P01`, `57P02`, `57P03` or `57P05`, also a session that closes between the bootstrap and the reservation) is logged as a warning, as during a failover. - Another fault, such as rejected credentials (`28P01`) or a configuration error, is logged as an error on every attempt. The attempts continue, because the credentials can be restored. @@ -165,6 +165,8 @@ An empty table without columns. Each claim transaction locks it (`LOCK TABLE ... Duron automatically runs migrations on startup if `migrateOnStart` is enabled. Migrations are located in the `migrations/postgres` directory. +Instances that start at the same time migrate one at a time: each runs its migrations in one transaction that first takes a transaction-level advisory lock for the migrations schema (key `hashtextextended('duron:migrate:duron', 0)`). A later instance waits for the first one to commit, then finds the migrations applied and applies nothing, instead of failing on the concurrent creation of the same schema or tables. The lock is released when that transaction ends. On PGLite the same transaction and lock run on its single session. + To generate new migrations: ```bash @@ -395,7 +397,7 @@ See the [Adapter API Reference](/docs/adapters) for all required methods. `Adapter.fetch()` dispatches to your `_fetch` override, and so does `Client.fetch()` when the Client has actions configured. A custom `_fetch` is responsible for its own cross-worker capacity safety; it only receives the built-in `SERIALIZABLE` claim protection when it delegates to the built-in PostgreSQL/PGLite `_fetch` (see [Multi-Worker Setup](/docs/multi-worker#claim-admission-and-group-capacity)). -Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). For its own recoveries, the Client tells the built-in `_recoverJobs` which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom `_recoverJobs` keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A direct `recoverJobs()` call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs. +Likewise, the built-in cancellation storage locking covers only `_cancelJob`, `_completeJob`, `_failJob` and `_createOrRecoverJobStep` as shipped. An override of any of them that does not delegate to the built-in method does not take part in that locking (see [Cancellation and Stored Steps](/docs/multi-worker#cancellation-and-stored-steps)). A custom `_recoverJobs` likewise does not take part in recovery's per-phase locking (see [Recovery and concurrent steps](/docs/multi-worker#recovery-and-concurrent-steps)). For its own recoveries, the Client tells the built-in `_recoverJobs` which jobs it holds locally, through an internal channel tied to the options object (not an option field): the built-in method leaves those jobs alone while it rescues the adapter's other own jobs. A custom `_recoverJobs` keeps its own behavior for the adapter's own jobs; one that calls the built-in method with the same options object keeps the Client's held jobs, and one that passes a new options object gets the default of a direct call. A custom `_recoverJobs` that does not delegate can apply the same exclusion with the protected `_heldJobIds(options)`, passing the options object it received: an array means "include the adapter's own id, except these held jobs" (`[]` for a direct call on an adapter without a Client), and `null` means "skip the adapter's own id". A direct `recoverJobs()` call on an adapter used by a Client skips the adapter's own id; on an adapter without a Client it includes the adapter's own id entirely, including jobs that adapter claimed and still runs. A graceful `Client.stop()` returns the jobs it did not finish to the queue through `releaseJob()`, which calls `_releaseJob({ jobId })`. The built-in adapters set the job back to `created` (start, expiry and owner cleared) when it is still `active`, owned by this adapter's id and not expired, and keep its steps. The default `_releaseJob` of the `Adapter` class releases nothing and returns `false`, and the Client logs a warning for each job it could not release. This changes the behavior of a custom adapter that does not override it: before releases existed, `stop()` cancelled the running jobs (`_cancelJob`), and only claimed jobs that had not started stayed `active`. Now neither kind is cancelled: both stay `active` with this adapter's id until recovery requeues them (another worker's recovery once this adapter's liveness row is deleted or stale, or a startup recovery with the same id). Override `_releaseJob` to return them to the queue at once. diff --git a/packages/docs/content/docs/multi-worker.mdx b/packages/docs/content/docs/multi-worker.mdx index c9856e4..3cbc9c5 100644 --- a/packages/docs/content/docs/multi-worker.mdx +++ b/packages/docs/content/docs/multi-worker.mdx @@ -228,7 +228,7 @@ The built-in PostgreSQL and PGLite adapters claim jobs with one `SERIALIZABLE` t Before its claim statement, each claim transaction locks the schema's `claim_lock` table, an empty table that only serves this purpose (`LOCK TABLE ... IN EXCLUSIVE MODE`). The claims of all workers on a schema therefore run one at a time, in the order they asked for the lock. A claim holds the lock for a few milliseconds (about 60 ms with a backlog of 50,000 jobs). Taking the lock does not start the transaction's snapshot, so each claim sees the jobs that the previous claims took: concurrent workers do not claim the same jobs, do not claim more than a group's limit, and do not abort each other's claims. A claim waits at most 1 second for the lock (`SET LOCAL lock_timeout`; the timeout also bounds any other lock wait of the claim transaction, for example while DDL locks a job table). This leaves room for more than 15 claims queued ahead of it even with a large backlog. When the wait times out (SQLSTATE `55P03`), the transaction rolls back and the fetch returns no jobs. This is logged at debug level, is not retried, and is not a failure: automatic discovery treats it as an empty claim, without a cooldown. -A worker can stop between taking the lock and committing, for example when its process is paused, its VM is suspended or its network is lost. While it holds the lock, every claim on the schema waits 1 second and returns no jobs. To bound this, the PostgreSQL adapter's claim transaction also sets `SET LOCAL idle_in_transaction_session_timeout = '5s'`: when the claim session waits more than 5 seconds for its client's next statement, PostgreSQL ends that session (SQLSTATE `25P03`), the claim rolls back with nothing claimed, and the lock is free again. So a stalled worker stops all claims on the schema for about 5 seconds, not until TCP keepalive ends its session (about 2 hours by default). A normal claim waits for its client only for a few round trips, far below 5 seconds; the timer does not run while a statement runs or waits for a lock. A worker whose own event loop is blocked for more than 5 seconds during a claim loses that claim: its fetch fails with a connection error, the jobs stay claimable, and automatic discovery logs the error and waits one `pullInterval`. Both settings are `LOCAL` to the claim transaction and do not change the session. The PGLite adapter has one in-process session, so it does not set the idle timeout. +A worker can stop between taking the lock and committing, for example when its process is paused, its VM is suspended or its network is lost. While it holds the lock, every claim on the schema waits 1 second and returns no jobs. To bound this, the PostgreSQL adapter's claim transaction also sets `SET LOCAL idle_in_transaction_session_timeout = '5s'`: when the claim session waits more than 5 seconds for its client's next statement, PostgreSQL ends that session (SQLSTATE `25P03`), the claim rolls back with nothing claimed, and the lock is free again. So a stalled worker stops all claims on the schema for about 5 seconds, not until TCP keepalive ends its session (about 2 hours by default). A normal claim waits for its client only for a few round trips, far below 5 seconds; the timer does not run while a statement runs or waits for a lock. A worker whose own event loop is blocked for more than 5 seconds during a claim loses that claim: its fetch fails with a connection error, the jobs stay claimable, and automatic discovery logs the error and waits one `pullInterval`. Both settings are `LOCAL` to the claim transaction and do not change the session. A lower `lock_timeout` or `idle_in_transaction_session_timeout` that you configured (for the server, database or role, or in the connection options) is kept: the adapter reads both settings once at startup and uses the lower of each and Duron's bound (1 and 5 seconds). The PGLite adapter has one in-process session, so it does not set the idle timeout. Because the claims on a schema run one at a time, the claim lock limits the claim rate of all workers on that schema together to about one claim per claim duration. A claim takes a few milliseconds on a small backlog, so hundreds of claims per second, and about 17 to 57 ms with a backlog of 50,000 created jobs, so about 17 to 60 claims per second (measured on PostgreSQL 16 and 19 for one claim of 10 jobs). Each claim takes up to its batch size of jobs, so the job start rate of the fleet is at most about that rate times the batch size. Larger batches raise this ceiling. When more claims queue than finish within 1 second, the claims at the end of the queue return empty after the lock timeout and are made again later. diff --git a/packages/docs/content/docs/telemetry.mdx b/packages/docs/content/docs/telemetry.mdx index a7a53dc..7352408 100644 --- a/packages/docs/content/docs/telemetry.mdx +++ b/packages/docs/content/docs/telemetry.mdx @@ -244,7 +244,7 @@ const aiAction = defineAction()({ }) ``` -The tracer returned by `getTracer()` is context-aware and automatically injects the parent span, so external libraries don't need to manually handle context propagation. +The tracer returned by `getTracer(name)` is context-aware and automatically injects the parent span, so external libraries don't need to manually handle context propagation. It is your provider's tracer `name` (`tracerProvider.getTracer(name)`), so its spans carry that instrumentation scope; `startSpan()` uses Duron's tracer (scope `duron`). ### Using startSpan diff --git a/packages/duron/src/action-job.ts b/packages/duron/src/action-job.ts index bf81f34..3d375c7 100644 --- a/packages/duron/src/action-job.ts +++ b/packages/duron/src/action-job.ts @@ -4,6 +4,7 @@ import { SpanKind, SpanStatusCode, type Tracer, + type TracerProvider, trace, } from '@opentelemetry/api' import type { Logger } from 'pino' @@ -27,6 +28,7 @@ export interface ActionJobOptions> { action: TAction database: Adapter tracer: Tracer + tracerProvider?: TracerProvider variables: Record logger: Logger } @@ -84,6 +86,7 @@ export class ActionJob> { actionName: options.job.actionName, adapter: options.database, tracer: options.tracer, + ...(options.tracerProvider ? { tracerProvider: options.tracerProvider } : {}), logger: options.logger, concurrencyLimit: options.action.steps.concurrency, }) @@ -339,8 +342,13 @@ export class ActionJob> { return } } catch (error) { + // Known limit: writeSkipped() may already have stored some steps' statuses (for + // example `cancelled`) when completeJob fails. The release below keeps them, so the + // job's next run fails on such a step ("Cannot recover a cancelled step") unless its + // handler catches that. It needs two faults (a failed completion, then a successful + // release); making both one transaction would need an adapter API change. this.#logger.warn( - { error, jobId: this.#job.id, actionName: this.#action.name }, + { error, jobId: this.#job.id, actionName: this.#action.name, stepsWritten: true }, '[ActionJob] Job not completed during stop; releasing it', ) } diff --git a/packages/duron/src/action-manager.ts b/packages/duron/src/action-manager.ts index ff5d9e9..2656402 100644 --- a/packages/duron/src/action-manager.ts +++ b/packages/duron/src/action-manager.ts @@ -1,4 +1,4 @@ -import type { Tracer } from '@opentelemetry/api' +import type { Tracer, TracerProvider } from '@opentelemetry/api' import fastq from 'fastq' import type { Logger } from 'pino' @@ -24,6 +24,7 @@ export interface ActionManagerOptions> { action: TAction database: Adapter tracer: Tracer + tracerProvider?: TracerProvider variables: Record logger: Logger concurrencyLimit: number @@ -41,6 +42,7 @@ export class ActionManager> { #action: TAction #database: Adapter #tracer: Tracer + #tracerProvider: TracerProvider | undefined #variables: Record #logger: Logger #queue: fastq.queueAsPromised @@ -63,6 +65,7 @@ export class ActionManager> { this.#action = options.action this.#database = options.database this.#tracer = options.tracer + this.#tracerProvider = options.tracerProvider this.#variables = options.variables this.#logger = options.logger this.#concurrencyLimit = options.concurrencyLimit @@ -238,6 +241,7 @@ export class ActionManager> { action: this.#action, database: this.#database, tracer: this.#tracer, + ...(this.#tracerProvider ? { tracerProvider: this.#tracerProvider } : {}), variables: this.#variables, logger: this.#logger, }) diff --git a/packages/duron/src/adapters/adapter.ts b/packages/duron/src/adapters/adapter.ts index bc209d8..c0979a0 100644 --- a/packages/duron/src/adapters/adapter.ts +++ b/packages/duron/src/adapters/adapter.ts @@ -10,7 +10,7 @@ import { type JobStatus, } from '../constants.js' import { isStopFailure, lifecycleFor } from '../lifecycle.js' -import { scopeRecovery } from '../recovery-scope.js' +import { heldJobIdsOf, scopeRecovery } from '../recovery-scope.js' import { ArchiveStatsSchema, @@ -759,6 +759,22 @@ export abstract class Adapter extends EventEmitter { */ protected abstract _recoverJobs(options: RecoverJobsOptions): Promise + /** + * The job ids that the recovery of `options` must leave alone, for a `_recoverJobs` + * implementation: pass it the options object `_recoverJobs` received. + * + * - An array: the adapter's own id counts as an unresponsive owner too (its jobs left by an + * earlier process are rescued), except these jobs, which its Client holds locally + * (claimed, queued, running or finalizing). A Client's own recovery passes them; a direct + * `recoverJobs()` call on an adapter without a Client gets `[]`. + * - `null`: skip the adapter's own id entirely (a direct call on an adapter used by a + * Client, which cannot know the held jobs, or a Client recovery while a claim reply is + * pending). + */ + protected _heldJobIds(options: RecoverJobsOptions): readonly string[] | null { + return heldJobIdsOf(this, options) + } + // ============================================================================ // Private Step Methods (to be implemented by adapters) // ============================================================================ diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index 2bc4221..e94d62d 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -29,7 +29,6 @@ import { STEP_STATUS_FAILED, } from '../../constants.js' import { lifecycleFor, throwLifecycleErrors } from '../../lifecycle.js' -import { heldJobIdsOf } from '../../recovery-scope.js' import { type WaitReadBudget, registerWaitReadExecutor } from '../../wait-read.js' import { Adapter, @@ -64,6 +63,7 @@ import { type TimeTravelJobOptions, } from '../adapter.js' +import { pruneLockKeyText } from './prune-key.js' import createSchema from './schema.js' export type Schema = ReturnType @@ -94,6 +94,7 @@ function jsonParam(value: unknown, column: PgColumn): SQL { * itself is ended by {@link CLAIM_IDLE_TIMEOUT}. */ const CLAIM_LOCK_TIMEOUT = '1s' +const CLAIM_LOCK_TIMEOUT_MS = 1_000 /** * How long the claim transaction may stay idle between its statements before the server ends @@ -102,13 +103,38 @@ const CLAIM_LOCK_TIMEOUT = '1s' * between LOCK and COMMIT (process paused, VM suspended, network lost) keeps the lock until * TCP keepalive ends its session (about 2 h by default), and every claim on the schema returns * no jobs until then. The timer runs only while the server waits for the client's next - * statement, not while a statement runs or waits for a lock. A normal claim is idle for three - * round trips (after SET, after LOCK, and before COMMIT) of well under 100 ms, so 5 s is + * statement, not while a statement runs or waits for a lock. A normal claim is idle only + * between its statements (after the idle SET, after LOCK and after the claim statement, plus + * any extra driver round trip), each well under 100 ms, so 5 s is * never reached unless the client stalls for seconds (for example an event loop blocked by * synchronous work in the same process). Such a claim fails with a connection error instead * of claiming late. 5 s bounds a fleet-wide stall to the order of the default stop budgets. */ const CLAIM_IDLE_TIMEOUT = '5s' +const CLAIM_IDLE_TIMEOUT_MS = 5_000 +// A lower session setting (an operator's) is kept for both timeouts: see _claimTimeouts. + +/** + * The scheduled-prune advisory key of `schema`, as SQL: `hashtextextended('duron:prune:' || + * schema, 0)`, a bigint. One key per schema, so Duron schemas in one database, and application + * locks on other keys (such as the former constant 42), do not contend. + */ +export function pruneLockKey(schema: string): SQL { + return sql`hashtextextended(${pruneLockKeyText(schema)}, 0)` +} + +/** The claim transaction's timeouts (`SET LOCAL` values). */ +interface ClaimTimeouts { + lock: string + /** `undefined`: the idle timeout is not set (PGlite). */ + idle: string | undefined +} + +/** The lower of a session setting in ms (`0` disables it) and Duron's bound. */ +function lowerTimeout(setting: unknown, boundMs: number, bound: string): string { + const ms = Number(setting) + return Number.isFinite(ms) && ms > 0 && ms < boundMs ? `${Math.floor(ms)}ms` : bound +} /** Retries of a claim after a serialization failure (SQLSTATE 40001). */ const CLAIM_CONFLICT_RETRIES = 5 @@ -194,6 +220,8 @@ export abstract class PostgresBaseAdapter< private initialized = false protected ownedClosed = false private readonly claimRetryWakers = new Set<() => void>() + /** The claim transaction's timeouts, read once from the session settings (see _claim). */ + private claimTimeouts: Promise | null = null private listenerObligations: Array<{ done: boolean }> = [] private readonly waitReadContext = new AsyncLocalStorage<{ db: DrizzleDatabase @@ -306,6 +334,27 @@ export abstract class PostgresBaseAdapter< // Lifecycle Methods // ============================================================================ + /** + * Run Duron's migrations (`migrate` gets a transaction to run them on) inside one + * transaction that first takes a transaction-level advisory lock keyed by the migrations + * schema (`hashtextextended('duron:migrate:', 0)`). Concurrent cold starts then + * migrate one at a time: each later one waits, then sees the migrations the first one + * applied (READ COMMITTED: every statement after the lock sees them) and applies nothing. + * Without it, their `CREATE SCHEMA/TABLE IF NOT EXISTS` and migration DDL race and fail with + * duplicate-object errors. The lock is released at COMMIT or ROLLBACK. + */ + protected async _migrateLocked( + migrationsSchema: string, + migrate: (tx: Parameters[0]>[0]) => Promise, + ): Promise { + await this.db.transaction(async (tx) => { + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtextextended(${`duron:migrate:${migrationsSchema}`}, 0))`, + ) + await migrate(tx) + }) + } + /** * Start the adapter. * Runs migrations if enabled and sets up database listeners. @@ -327,6 +376,10 @@ export abstract class PostgresBaseAdapter< if (!(await this._isUninitializedLivenessAbsence(error))) throw error } + if (!lifecycleFor(this).accepting) return + // Read the claim timeouts now, so the first claim does not wait for this read. + await this._claimTimeouts() + if (!lifecycleFor(this).accepting) return await this._listenForEvents(`job-status-changed`, (payload: string) => { if (lifecycleFor(this).accepting && this.listenerCount('job-status-changed') > 0) { @@ -488,9 +541,14 @@ export abstract class PostgresBaseAdapter< // Scheduler Methods // ============================================================================ - /** Scheduled pruning coordinates across schemas in the same database. */ + /** + * Scheduled pruning coordinates the adapters of one schema: its advisory key is derived + * from the schema name (see {@link pruneLockKey}). + */ protected async _acquirePruneLock(): Promise { - const result = await this.db.execute(sql`SELECT pg_try_advisory_lock(42) AS acquired`) + const result = await this.db.execute( + sql`SELECT pg_try_advisory_lock(${pruneLockKey(this.schema)}) AS acquired`, + ) const rows = this._map(result) if (rows.length !== 1 || typeof rows[0]?.acquired !== 'boolean') { throw new Error('Malformed scheduled prune acquisition result') @@ -499,7 +557,9 @@ export abstract class PostgresBaseAdapter< } protected async _releasePruneLock(): Promise { - const result = await this.db.execute(sql`SELECT pg_advisory_unlock(42) AS released`) + const result = await this.db.execute( + sql`SELECT pg_advisory_unlock(${pruneLockKey(this.schema)}) AS released`, + ) const rows = this._map(result) if (rows.length !== 1 || rows[0]?.released !== true) { throw new Error('False or malformed scheduled prune unlock result') @@ -792,7 +852,8 @@ export abstract class PostgresBaseAdapter< * Build the statement that copies an active job row into the archive with its * terminal status. The copy is SQL-native so stored values stay exact: a round * trip through JavaScript would cut timestamps to milliseconds and round jsonb - * numbers. `finished_at` and `updated_at` become `finishedAt`; `output` and + * numbers. `finished_at` and `updated_at` become the database time (`now()`, the + * transaction's start time, like the other timestamps); `output` and * `error` are replaced only when given (`null` or `undefined` stores SQL NULL). * Replacement values keep the driver's JSON encoding (see jsonParam). * Callers must already hold the job row lock (see _cancelJob). @@ -800,10 +861,8 @@ export abstract class PostgresBaseAdapter< #archiveJobRow( jobId: string, status: typeof JOB_STATUS_COMPLETED | typeof JOB_STATUS_FAILED | typeof JOB_STATUS_CANCELLED, - finishedAt: Date, replace: { output?: unknown; error?: unknown } = {}, ): SQL { - const finished = finishedAt.toISOString() const archive = this.tables.jobsArchiveTable return sql` INSERT INTO ${archive} ( @@ -815,8 +874,8 @@ export abstract class PostgresBaseAdapter< id, action_name, group_key, description, ${status}, checksum, input, ${'output' in replace ? jsonParam(replace.output, archive.output) : sql`output`}, ${'error' in replace ? jsonParam(replace.error, archive.error) : sql`error`}, - timeout_ms, expires_at, started_at, ${finished}::timestamptz, client_id, concurrency_limit, - concurrency_step_limit, created_at, ${finished}::timestamptz + timeout_ms, expires_at, started_at, now(), client_id, concurrency_limit, + concurrency_step_limit, created_at, now() FROM ${this.tables.jobsActiveTable} WHERE id = ${jobId} ` @@ -829,8 +888,6 @@ export abstract class PostgresBaseAdapter< */ protected async _completeJob({ jobId, output }: CompleteJobOptions) { return this.db.transaction(async (tx) => { - const finishedAt = new Date() - // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx .select({ id: this.tables.jobsActiveTable.id }) @@ -850,7 +907,7 @@ export abstract class PostgresBaseAdapter< } // 2. Insert job into archive FIRST (required for FK constraints) - await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_COMPLETED, finishedAt, { output })) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_COMPLETED, { output })) // 3. Archive steps using INSERT ... SELECT (SQL-native, no JS round-trip) await tx.execute(sql` @@ -864,7 +921,7 @@ export abstract class PostgresBaseAdapter< id, job_id, parent_step_id, parallel, name, status, output, error, started_at, finished_at, timeout_ms, expires_at, retries_limit, retries_count, delayed_ms, history_failed_attempts, created_at, - updated_at, ${finishedAt.toISOString()} + updated_at, now() FROM ${this.tables.jobStepsActiveTable} WHERE job_id = ${jobId} `) @@ -883,8 +940,6 @@ export abstract class PostgresBaseAdapter< */ protected async _failJob({ jobId, error }: FailJobOptions) { return this.db.transaction(async (tx) => { - const finishedAt = new Date() - // 1. Lock the job row first (see _cancelJob), with the unchanged guard const [job] = await tx .select({ id: this.tables.jobsActiveTable.id }) @@ -903,7 +958,7 @@ export abstract class PostgresBaseAdapter< } // 2. Insert job into archive FIRST (required for FK constraints) - await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_FAILED, finishedAt, { error })) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_FAILED, { error })) // 3. Archive steps using INSERT ... SELECT await tx.execute(sql` @@ -917,7 +972,7 @@ export abstract class PostgresBaseAdapter< id, job_id, parent_step_id, parallel, name, status, output, error, started_at, finished_at, timeout_ms, expires_at, retries_limit, retries_count, delayed_ms, history_failed_attempts, created_at, - updated_at, ${finishedAt.toISOString()} + updated_at, now() FROM ${this.tables.jobStepsActiveTable} WHERE job_id = ${jobId} `) @@ -946,8 +1001,6 @@ export abstract class PostgresBaseAdapter< */ protected async _cancelJob({ jobId }: CancelJobOptions) { return this.db.transaction(async (tx) => { - const finishedAt = new Date() - // 1. Lock the job row first, with the unchanged guard const [job] = await tx .select({ id: this.tables.jobsActiveTable.id }) @@ -972,13 +1025,13 @@ export abstract class PostgresBaseAdapter< .update(this.tables.jobStepsActiveTable) .set({ status: STEP_STATUS_CANCELLED, - finished_at: finishedAt, - updated_at: finishedAt, + finished_at: sql`now()`, + updated_at: sql`now()`, }) .where(eq(this.tables.jobStepsActiveTable.job_id, jobId)) // 3. Insert job into archive FIRST (required for FK constraints) - await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_CANCELLED, finishedAt)) + await tx.execute(this.#archiveJobRow(jobId, JOB_STATUS_CANCELLED)) // 4. Archive steps using INSERT ... SELECT await tx.execute(sql` @@ -992,7 +1045,7 @@ export abstract class PostgresBaseAdapter< id, job_id, parent_step_id, parallel, name, status, output, error, started_at, finished_at, timeout_ms, expires_at, retries_limit, retries_count, delayed_ms, history_failed_attempts, created_at, - updated_at, ${finishedAt.toISOString()} + updated_at, now() FROM ${this.tables.jobStepsActiveTable} WHERE job_id = ${jobId} `) @@ -1525,17 +1578,57 @@ export abstract class PostgresBaseAdapter< return CLAIM_IDLE_TIMEOUT } + /** + * The claim transaction's `lock_timeout` and `idle_in_transaction_session_timeout`: Duron's + * bounds ({@link CLAIM_LOCK_TIMEOUT}, {@link CLAIM_IDLE_TIMEOUT}), or the session's own + * setting when it is lower (and not 0, which disables it), so a claim never raises an + * operator's limit. `SET LOCAL` takes constants and the claim transaction cannot read the + * setting before LOCK TABLE without taking its snapshot, so the session settings (server, + * database, role and connection options, the same on every pooled connection) are read once, + * at startup (or before the first claim, if that read failed). A failed read is not cached. + */ + private _claimTimeouts(): Promise { + this.claimTimeouts ??= this.db + .execute<{ name: string; setting: string }>(sql` + SELECT name, setting FROM pg_settings + WHERE name IN ('lock_timeout', 'idle_in_transaction_session_timeout')`) + .then( + (result) => { + const rows: { name: string; setting: string }[] = this._map(result) + const setting = (name: string) => rows.find((row) => row.name === name)?.setting + const idle = this._claimIdleTimeout() + return { + lock: lowerTimeout(setting('lock_timeout'), CLAIM_LOCK_TIMEOUT_MS, CLAIM_LOCK_TIMEOUT), + idle: + idle === undefined + ? undefined + : lowerTimeout( + setting('idle_in_transaction_session_timeout'), + CLAIM_IDLE_TIMEOUT_MS, + idle, + ), + } + }, + (error: unknown) => { + this.claimTimeouts = null + throw error + }, + ) + return this.claimTimeouts + } + /** One claim attempt in its own SERIALIZABLE transaction, after the claim lock. */ private async _claim(batch: number): Promise { + const timeouts = await this._claimTimeouts() let claim: Promise | undefined try { return await this.db.transaction( (tx) => { // No statement before the claim statement takes a snapshot: its snapshot begins // after the lock is granted. Both settings are LOCAL to this transaction. - const idleTimeout = this._claimIdleTimeout() + const idleTimeout = timeouts.idle claim = tx - .execute(sql.raw(`SET LOCAL lock_timeout = '${CLAIM_LOCK_TIMEOUT}'`)) + .execute(sql.raw(`SET LOCAL lock_timeout = '${timeouts.lock}'`)) .then(() => idleTimeout ? tx.execute( @@ -1681,7 +1774,7 @@ export abstract class PostgresBaseAdapter< */ protected async _recoverJobs(options: RecoverJobsOptions): Promise { const { checksums, staleTimeoutMs = 15_000 } = options - const heldJobIds = heldJobIdsOf(this, options) + const heldJobIds = this._heldJobIds(options) // Find owners of active jobs that are dead: no liveness row or stale heartbeat. // This instance's own id is added below, apart from its held jobs (null: skipped). diff --git a/packages/duron/src/adapters/postgres/pglite.ts b/packages/duron/src/adapters/postgres/pglite.ts index bce0099..c5d5417 100644 --- a/packages/duron/src/adapters/postgres/pglite.ts +++ b/packages/duron/src/adapters/postgres/pglite.ts @@ -31,11 +31,14 @@ export class PGLiteAdapter extends PostgresBaseAdapter { */ protected override async _start() { if (this.migrateOnStart) { - await migrate(this.db, { - migrationsFolder: join(import.meta.dirname, '..', '..', '..', 'migrations', 'postgres'), - migrationsTable: 'migrations', - migrationsSchema: 'duron', - }) + // One migrator at a time (see _migrateLocked); the transaction runs the migrations. + await this._migrateLocked('duron', (tx) => + migrate(tx as unknown as typeof this.db, { + migrationsFolder: join(import.meta.dirname, '..', '..', '..', 'migrations', 'postgres'), + migrationsTable: 'migrations', + migrationsSchema: 'duron', + }), + ) } await super._start() diff --git a/packages/duron/src/adapters/postgres/postgres.ts b/packages/duron/src/adapters/postgres/postgres.ts index 3d41408..26f4def 100644 --- a/packages/duron/src/adapters/postgres/postgres.ts +++ b/packages/duron/src/adapters/postgres/postgres.ts @@ -10,6 +10,7 @@ import { driverEndTimeout, lifecycleFor } from '../../lifecycle.js' import type { WaitReadBudget } from '../../wait-read.js' import { type AdapterOptions, PostgresBaseAdapter, type PruneLockReplacement } from './base.js' +import { pruneLockKeyText } from './prune-key.js' import { PostgresPruneLock } from './prune-lock.js' import type createSchema from './schema.js' @@ -82,6 +83,7 @@ export class PostgresAdapter extends PostgresBaseAdapter this._retirePruning(error), this.pruneLockReplaced, + pruneLockKeyText(this.schema), ) return this.pruneLock.acquire() } @@ -145,11 +147,14 @@ export class PostgresAdapter extends PostgresBaseAdapter + migrate(tx as unknown as typeof this.db, { + migrationsFolder: join(import.meta.dirname, '..', '..', '..', 'migrations', 'postgres'), + migrationsTable: 'migrations', + migrationsSchema: 'duron', + }), + ) } await super._start() } diff --git a/packages/duron/src/adapters/postgres/prune-key.ts b/packages/duron/src/adapters/postgres/prune-key.ts new file mode 100644 index 0000000..271bd6e --- /dev/null +++ b/packages/duron/src/adapters/postgres/prune-key.ts @@ -0,0 +1,8 @@ +/** + * The text whose `hashtextextended(text, 0)` is the scheduled-prune advisory key of `schema`: + * one key per Duron schema, so Duron schemas in one database, and application advisory locks + * on other keys (such as the former constant 42), do not contend. + */ +export function pruneLockKeyText(schema: string): string { + return `duron:prune:${schema}` +} diff --git a/packages/duron/src/adapters/postgres/prune-lock.ts b/packages/duron/src/adapters/postgres/prune-lock.ts index 8070899..520a180 100644 --- a/packages/duron/src/adapters/postgres/prune-lock.ts +++ b/packages/duron/src/adapters/postgres/prune-lock.ts @@ -2,10 +2,12 @@ import postgres, { type Options, type ReservedSql, type Sql } from 'postgres' import { driverEndTimeout, type Lifecycle } from '../../lifecycle.js' +import { pruneLockKeyText } from './prune-key.js' + /** * Errors of a statement on an established session that this lock lost: its server session * ended, or its socket failed. When the server ends the session, it releases the session's - * advisory lock. After a socket failure, a half-open backend can keep the lock (key 42) until + * advisory lock. After a socket failure, a half-open backend can keep the lock (the prune key) until * the server reaps it; until then the replacement lock simply does not acquire it, so no * pass runs twice. * - `CONNECTION_CLOSED`: postgres.js, the socket closed under a pending statement; @@ -70,7 +72,7 @@ function isStartupFault(error: unknown): boolean { return code !== undefined && (STARTUP_FAULT.has(code) || /^08[0-9A-Z]{3}$/.test(code)) } -/** A bootstrap result that does not prove which backend would own key 42. */ +/** A bootstrap result that does not prove which backend would own the prune key. */ class SingleOwnerFault extends Error {} /** @@ -108,6 +110,8 @@ export class PostgresPruneLock { readonly retire: (error: unknown) => void, /** Replaces a lost session's lock: a failed bootstrap may be retried on a later tick. */ readonly replacement = false, + /** The key text of the advisory lock (see {@link pruneLockKeyText}). */ + readonly key = pruneLockKeyText('duron'), ) { const options: Options = { ...(typeof connection === 'string' ? {} : connection), @@ -201,11 +205,11 @@ export class PostgresPruneLock { /** * The bootstrap session closed while reserve() was pending. postgres.js then opened a new * connection for the pending reservation (or granted the closing one). That reservation never - * ran a statement and never requested key 42, and this lock never uses its client again + * ran a statement and never requested the prune key, and this lock never uses its client again * (`#uncertain` is set and the setup is not repeated). Give the connection back so that the * fault close's `end()` closes it at once: a reserved connection would stay open until the * end timeout destroys it, and the close would fail its budget (`shutdownTimeout`, 5 s by - * default; the end timeout is at most that budget, see `driverEndTimeout`). The client is + * default; the end timeout is 80% of that budget, see `driverEndTimeout`). The client is * ending, so postgres.js does not lease the connection again. * `#physicallyClosed` stays true from the bootstrap session's close, although a new * connection can be open here. The close is still confirmed only after that connection @@ -239,7 +243,7 @@ export class PostgresPruneLock { this.lifecycle.assertContinuation() this.#lock = 'unknown' const rows = await this.#noteLoss(this.#session!<{ pid: number; acquired: boolean }[]>` - SELECT pg_backend_pid() AS pid, pg_try_advisory_lock(42) AS acquired + SELECT pg_backend_pid() AS pid, pg_try_advisory_lock(hashtextextended(${this.key}, 0)) AS acquired `) if (rows.length !== 1 || rows[0]?.pid !== this.#pid || typeof rows[0]?.acquired !== 'boolean') { throw new Error('Malformed scheduled prune acquisition or changed backend') @@ -253,7 +257,7 @@ export class PostgresPruneLock { this.lifecycle.assertContinuation() this.#lock = 'unknown' const rows = await this.#noteLoss(this.#session!<{ pid: number; released: boolean }[]>` - SELECT pg_backend_pid() AS pid, pg_advisory_unlock(42) AS released + SELECT pg_backend_pid() AS pid, pg_advisory_unlock(hashtextextended(${this.key}, 0)) AS released `) if (rows.length !== 1 || rows[0]?.pid !== this.#pid || rows[0]?.released !== true) { throw new Error('False or malformed scheduled prune unlock or changed backend') @@ -280,7 +284,7 @@ export class PostgresPruneLock { * startup fault (for example during a failover); * - `failed`: this replacement lock failed its bootstrap with another fault (rejected * credentials, configuration). - * A failed replacement never requested key 42, so another attempt keeps a single owner. + * A failed replacement never requested the prune key, so another attempt keeps a single owner. * A bootstrap failure of the first lock, and a bootstrap result that does not prove the * backend identity, give `none`. */ diff --git a/packages/duron/src/client.ts b/packages/duron/src/client.ts index 5406a28..e345979 100644 --- a/packages/duron/src/client.ts +++ b/packages/duron/src/client.ts @@ -427,6 +427,7 @@ export class Client< #actions: TActions | null #database: Adapter #tracer: Tracer + #tracerProvider: TracerProvider #variables: Record #logger: Logger #lifecycle: Lifecycle @@ -482,6 +483,7 @@ export class Client< // application passed in. Without one, a ProxyTracerProvider with no delegate // gives a no-op tracer. It never reads the global tracer provider. const tracerProvider = telemetry?.tracerProvider ?? new ProxyTracerProvider() + this.#tracerProvider = tracerProvider this.#tracer = tracerProvider.getTracer(TRACER_NAME) // Side effects from here on. @@ -1379,6 +1381,7 @@ export class Client< action, database: this.#database, tracer: this.#tracer, + tracerProvider: this.#tracerProvider, variables: this.#variables, logger: this.#logger, concurrencyLimit: this.#options.actionConcurrencyLimit, diff --git a/packages/duron/src/lifecycle.ts b/packages/duron/src/lifecycle.ts index c5aa120..ed0645b 100644 --- a/packages/duron/src/lifecycle.ts +++ b/packages/duron/src/lifecycle.ts @@ -63,12 +63,12 @@ function signal(): { promise: Promise; resolve: () => void } { export const DEFAULT_SHUTDOWN_TIMEOUT = 5_000 /** - * The `timeout` (seconds) of a postgres.js `end()` in the owned close: at most 5 s, and not - * longer than the close's budget, so that a short `shutdownTimeout` still lets `end()` force - * the connections closed before the budget expires. + * The `timeout` (seconds) of a postgres.js `end()` in the owned close: at most 5 s, and 80% of + * the close's budget, so that `end()` forces busy connections closed before the budget expires + * (also at the default 5 s budget, where 5 s would fire at the deadline itself). */ export function driverEndTimeout(lifecycle: Lifecycle): number { - return Math.min(5, lifecycle.shutdownTimeout / 1000) + return Math.min(5, (lifecycle.shutdownTimeout / 1000) * 0.8) } // A deadline bounds observation, not execution. The losing promise remains observed. diff --git a/packages/duron/src/step-manager.ts b/packages/duron/src/step-manager.ts index f81c3cf..f2d62be 100644 --- a/packages/duron/src/step-manager.ts +++ b/packages/duron/src/step-manager.ts @@ -8,6 +8,7 @@ import { type SpanOptions, SpanStatusCode, type Tracer, + type TracerProvider, trace, } from '@opentelemetry/api' import type { StandardSchemaV1 } from '@standard-schema/spec' @@ -166,15 +167,16 @@ function createContextAwareTracer( function createTelemetryContext( span: Span | null, tracer: Tracer, + getTracer: (name: string) => Tracer, ids: TelemetryIds, ): TelemetryContext { return { getActiveSpan(): Span | undefined { return span ?? undefined }, - getTracer(_name: string): Tracer { - // Return a context-aware tracer that automatically links spans to the current trace - return createContextAwareTracer(tracer, span, ids) + getTracer(name: string): Tracer { + // The application's tracer `name`, context-aware: its spans join the current trace + return createContextAwareTracer(getTracer(name), span, ids) }, startSpan(name: string, options?: { attributes?: Record }): Span { // Create a child span linked to the current span (job or step) @@ -321,6 +323,8 @@ export interface StepManagerOptions { actionName: string adapter: Adapter tracer: Tracer + /** The application's provider: `TelemetryContext.getTracer(name)` gets its tracer `name`. */ + tracerProvider?: TracerProvider logger: Logger concurrencyLimit: number } @@ -335,6 +339,7 @@ export class StepManager { #stepStore: StepStore #lifecycle: Lifecycle #tracer: Tracer + #getTracer: (name: string) => Tracer #queue: fastq.queueAsPromised #logger: Logger // each step name should be executed only once per parent (name + parentStepId) @@ -367,6 +372,8 @@ export class StepManager { this.#actionName = options.actionName this.#logger = options.logger this.#tracer = options.tracer + const provider = options.tracerProvider + this.#getTracer = provider ? (name) => provider.getTracer(name) : () => options.tracer this.#stepStore = new StepStore(options.adapter) this.#lifecycle = lifecycleFor(options.adapter) // fastq starts a queued task from the settlement of the task that finished, in that task's @@ -485,7 +492,7 @@ export class StepManager { abortSignal: AbortSignal, logger: Logger, ): Promise> { - const telemetryContext = createTelemetryContext(this.#jobSpan, this.#tracer, { + const telemetryContext = createTelemetryContext(this.#jobSpan, this.#tracer, this.#getTracer, { jobId: job.id, }) return ActionContext.create(this, job, action, variables, abortSignal, logger, telemetryContext) @@ -497,10 +504,15 @@ export class StepManager { createStepTelemetryContext(stepId: string): TelemetryContext { const stepSpan = this.#stepSpans.get(stepId) if (stepSpan) { - return createTelemetryContext(stepSpan, this.#tracer, { jobId: this.#jobId, stepId }) + return createTelemetryContext(stepSpan, this.#tracer, this.#getTracer, { + jobId: this.#jobId, + stepId, + }) } // Fallback to job span if step span not found - return createTelemetryContext(this.#jobSpan, this.#tracer, { jobId: this.#jobId }) + return createTelemetryContext(this.#jobSpan, this.#tracer, this.#getTracer, { + jobId: this.#jobId, + }) } /** diff --git a/packages/duron/test/claim-isolation.test.ts b/packages/duron/test/claim-isolation.test.ts index b7ee7d6..95e86cd 100644 --- a/packages/duron/test/claim-isolation.test.ts +++ b/packages/duron/test/claim-isolation.test.ts @@ -1077,6 +1077,60 @@ suite('Native PostgreSQL claim admission', () => { } }, 30_000) + it('keeps lower operator lock and idle timeouts in the claim transaction', async () => { + const db = await claimDatabase() + const url = new URL(db.url) + const adapter = (name: string, connection: Record) => { + const instance = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + database: url.pathname.slice(1), + user: url.username, + password: url.password, + connection: { application_name: name, ...connection }, + }, + }) + instance.setId(name) + return instance + } + const lower = adapter('claim-lower', { + lock_timeout: '300', + idle_in_transaction_session_timeout: '2000', + }) + const higher = adapter('claim-higher', { + lock_timeout: '10000', + idle_in_transaction_session_timeout: '60000', + }) + try { + for (const [instance, lock, idle] of [ + [lower, '300ms', '2000ms'], + [higher, '1s', '5s'], + ] as const) { + const statements = traceStatements(instance) + await instance.start() + expect(await instance.fetch({ batch: 1 })).toEqual([]) + expect(await instance.fetch({ batch: 1 })).toEqual([]) + const settings = statements + .map((statement) => statement.query.trim()) + .filter((query) => query.startsWith('SET LOCAL')) + // Each claim sets the lower of the session's value and Duron's bound. + const claim = [ + `SET LOCAL lock_timeout = '${lock}'`, + `SET LOCAL idle_in_transaction_session_timeout = '${idle}'`, + ] + expect(settings).toEqual([...claim, ...claim]) + } + } catch (error) { + db.recordFailure(error) + throw error + } finally { + await lower.stop().catch(() => undefined) + await higher.stop().catch(() => undefined) + await db.cleanup() + } + }, 30_000) + it('does not pause Client discovery after a claim lock timeout', async () => { const db = await claimDatabase() const holder = postgres(db.url, { max: 1, connection: { statement_timeout: 10_000 } }) diff --git a/packages/duron/test/finished-at-clock.test.ts b/packages/duron/test/finished-at-clock.test.ts new file mode 100644 index 0000000..8846257 --- /dev/null +++ b/packages/duron/test/finished-at-clock.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it, setSystemTime } from 'bun:test' + +import { sql } from 'drizzle-orm' + +import { type Adapter, type AdapterFactory, postgresFactory } from './adapters.js' + +// finished_at (jobs, steps, and the archived steps' job_finished_at) comes from the database +// clock like started_at, created_at and updated_at: a JavaScript clock that is off (here set +// to the year 2000) must not change it. Native only: PGlite's now() reads the same process +// clock as JavaScript, so there the two clocks cannot differ (it runs the same SQL). + +function rowsOf(result: unknown): Array> { + return Array.isArray(result) ? [...result] : (result as { rows: Array> }).rows +} + +async function archived(adapter: Adapter, jobId: string) { + const db = (adapter as unknown as { db: { execute: (q: unknown) => Promise } }).db + const [job] = rowsOf( + await db.execute(sql` + SELECT started_at, finished_at, updated_at, now() AS db_now + FROM duron.jobs_archive WHERE id = ${jobId}`), + ) + const steps = rowsOf( + await db.execute(sql` + SELECT finished_at, job_finished_at FROM duron.job_steps_archive WHERE job_id = ${jobId}`), + ) + return { job: job!, steps } +} + +const year = (value: unknown) => new Date(value as string).getUTCFullYear() + +function run(factory: AdapterFactory) { + describe(`finished_at from the database clock with ${factory.name}`, () => { + for (const end of ['complete', 'fail', 'cancel'] as const) { + it(`${end} stores the database time`, async () => { + const instance = await factory.create() + const adapter = instance.adapter + adapter.setId('finished-clock') + try { + await adapter.start() + const jobId = (await adapter.createJob({ + queue: 'clock', + groupKey: 'clock', + input: {}, + timeoutMs: 60_000, + checksum: 'clock', + concurrencyLimit: 1, + concurrencyStepLimit: 1, + }))! + expect((await adapter.fetch({ batch: 1 })).map((job) => job.id)).toEqual([jobId]) + await adapter.createOrRecoverJobStep({ + jobId, + name: 'step', + timeoutMs: 60_000, + retriesLimit: 0, + parentStepId: null, + parallel: false, + }) + // The JavaScript clock is 26 years behind the database's. + setSystemTime(new Date('2000-01-01T00:00:00Z')) + try { + if (end === 'complete') + expect(await adapter.completeJob({ jobId, output: {} })).toBe(true) + if (end === 'fail') expect(await adapter.failJob({ jobId, error: {} })).toBe(true) + if (end === 'cancel') expect(await adapter.cancelJob({ jobId })).toBe(true) + } finally { + setSystemTime() + } + const { job, steps } = await archived(adapter, jobId) + expect(year(job['finished_at'])).toBe(year(job['db_now'])) + expect(new Date(job['finished_at']).getTime()).toBeGreaterThanOrEqual( + new Date(job['started_at']).getTime(), + ) + expect(year(job['updated_at'])).toBe(year(job['db_now'])) + expect(steps).toHaveLength(1) + expect(year(steps[0]!['job_finished_at'])).toBe(year(job['db_now'])) + if (end === 'cancel') expect(year(steps[0]!['finished_at'])).toBe(year(job['db_now'])) + } finally { + setSystemTime() + await adapter.stop() + await instance.deleteDb() + } + }) + } + }) +} + +if (process.env['POSTGRES_TEST'] === 'true') run(postgresFactory) diff --git a/packages/duron/test/lifecycle-sql.test.ts b/packages/duron/test/lifecycle-sql.test.ts index 65bc7d4..628f7a9 100644 --- a/packages/duron/test/lifecycle-sql.test.ts +++ b/packages/duron/test/lifecycle-sql.test.ts @@ -45,22 +45,29 @@ for (const factory of [ const entered = Promise.withResolvers() const release = Promise.withResolvers() const close = adapter._close.bind(adapter) - const execute = adapter.db.execute.bind(adapter.db) + const transaction = adapter.db.transaction.bind(adapter.db) const closeFailure = new Error('injected before owned close') const driver = adapter.db.$client let held = false - adapter.db.execute = async (query) => { - const result = await execute(query) - if ( - !held && - adapter.db.dialect.sqlToQuery(query).sql.includes('CREATE SCHEMA IF NOT EXISTS') - ) { - held = true - entered.resolve() - await release.promise - } - return result - } + // Migrations run on the migration transaction (see _migrateLocked): hold its statements. + adapter.db.transaction = (work, config) => + transaction((tx) => { + const probe = tx as { execute: (query: SQL) => Promise } + const execute = probe.execute.bind(tx) + probe.execute = async (query) => { + const result = await execute(query) + if ( + !held && + adapter.db.dialect.sqlToQuery(query).sql.includes('CREATE SCHEMA IF NOT EXISTS') + ) { + held = true + entered.resolve() + await release.promise + } + return result + } + return work(tx) + }, config) adapter._close = async () => { throw closeFailure } @@ -91,7 +98,7 @@ for (const factory of [ } finally { release.resolve() await started.catch(() => undefined) - adapter.db.execute = execute + adapter.db.transaction = transaction adapter._close = close await adapter.stop().catch(() => undefined) if (driver.close && !driver.closed) await driver.close() diff --git a/packages/duron/test/lifecycle-startup.test.ts b/packages/duron/test/lifecycle-startup.test.ts index 42147e4..4cc1604 100644 --- a/packages/duron/test/lifecycle-startup.test.ts +++ b/packages/duron/test/lifecycle-startup.test.ts @@ -17,6 +17,7 @@ type StartupProbe = Adapter & { ) => Promise<{ unlisten: () => void | Promise }> db: { execute: (query: SQL) => Promise + transaction: (work: (tx: unknown) => Promise, config?: unknown) => Promise dialect: { sqlToQuery: (query: SQL) => { sql: string } } $client: { query?: (text: string) => Promise<{ rows: Row[] }> @@ -54,6 +55,7 @@ for (const factory of [ const observer = factory.name === 'postgres' ? postgres(instance.connectionUrl, { max: 1 }) : null const execute = adapter.db.execute.bind(adapter.db) + const transaction = adapter.db.transaction.bind(adapter.db) const listen = adapter._listen.bind(adapter) const close = adapter._close.bind(adapter) const native = async (statement: string): Promise => @@ -63,11 +65,11 @@ for (const factory of [ let registrations = 0 let closes = 0 let remaining: unknown - const nativeFailure = async (): Promise => { + const nativeFailure = async (run = execute): Promise => { // Actual22012, or42P01 for an UNEXPECTED relation, at a labelled // substituted SQL boundary. Not an ACL/network/migration-content claim. try { - await execute( + await run( stage === 'startup-GC' ? sql`SELECT * FROM duron.unexpected_missing_relation` : sql`SELECT 1 / 0`, @@ -80,16 +82,36 @@ for (const factory of [ } adapter.db.execute = async (query) => { const text = adapter.db.dialect.sqlToQuery(query).sql - const selected = - stage === 'migration' - ? text.includes('CREATE SCHEMA IF NOT EXISTS') - : stage === 'startup-GC' && text.includes('DELETE FROM "duron"."clients"') - if (selected && !injected) { + if ( + stage === 'startup-GC' && + text.includes('DELETE FROM "duron"."clients"') && + !injected + ) { injected = true return nativeFailure() } return execute(query) } + // Migrations run on the migration transaction (see _migrateLocked): fail its first + // migration statement there. + adapter.db.transaction = (work, config) => + transaction((tx) => { + const probe = tx as { execute: (query: SQL) => Promise } + const run = probe.execute.bind(tx) + probe.execute = async (query) => { + const text = adapter.db.dialect.sqlToQuery(query).sql + if ( + stage === 'migration' && + text.includes('CREATE SCHEMA IF NOT EXISTS') && + !injected + ) { + injected = true + return nativeFailure(run) + } + return run(query) + } + return work(tx) + }, config) adapter._listen = async (event, callback) => { const handle = await listen(event, callback) registrations++ diff --git a/packages/duron/test/lifecycle.test.ts b/packages/duron/test/lifecycle.test.ts index f48fec5..5234e86 100644 --- a/packages/duron/test/lifecycle.test.ts +++ b/packages/duron/test/lifecycle.test.ts @@ -5,7 +5,7 @@ import postgres from 'postgres' import { defineAction } from '../src/action.js' import { Client } from '../src/client.js' -import { lifecycleFor } from '../src/lifecycle.js' +import { driverEndTimeout, lifecycleFor } from '../src/lifecycle.js' import { type Adapter, pgliteFactory, postgresFactory } from './adapters.js' @@ -985,3 +985,19 @@ for (const factory of [ }, 30_000) }) } + +describe('driverEndTimeout', () => { + it('forces the owned close inside its budget, at most 5 seconds', () => { + const lifecycle = lifecycleFor({}) + // seconds for postgres.js end(): 80% of shutdownTimeout, capped at 5 s + for (const [timeout, seconds] of [ + [5_000, 4], + [300, 0.24], + [10_000, 5], + [60_000, 5], + ] as const) { + lifecycle.shutdownTimeout = timeout + expect(driverEndTimeout(lifecycle)).toBeCloseTo(seconds, 10) + } + }) +}) diff --git a/packages/duron/test/migrate-concurrency.test.ts b/packages/duron/test/migrate-concurrency.test.ts new file mode 100644 index 0000000..18e55df --- /dev/null +++ b/packages/duron/test/migrate-concurrency.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'bun:test' + +import postgres from 'postgres' + +import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' + +import { getPostgresConnection } from './docker.js' + +// Concurrent cold starts on an empty database: every adapter migrates under one advisory lock, +// so their DDL does not race (duplicate schema, table or type errors) and each one starts. + +if (process.env['POSTGRES_TEST'] === 'true') { + describe('Concurrent migrations with postgres', () => { + it('starts several adapters at once on an empty database', async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + const observer = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) + const adapters = Array.from({ length: 6 }, (_, index) => { + const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) + adapter.setId(`migrator-${index}`) + return adapter + }) + try { + const results = await Promise.allSettled(adapters.map((adapter) => adapter.start())) + const failures = results.filter((result) => result.status === 'rejected') + expect( + failures.map((failure) => String((failure as PromiseRejectedResult).reason)), + ).toEqual([]) + expect(results.map((result) => (result as PromiseFulfilledResult).value)).toEqual( + Array(adapters.length).fill(true), + ) + // Each migration is recorded once. + const [row] = await observer` + SELECT count(*)::int AS count, count(DISTINCT hash)::int AS distinct + FROM duron.migrations` + expect(row!['count']).toBe(row!['distinct']) + expect(row!['count']).toBeGreaterThan(0) + } finally { + for (const adapter of adapters) await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 60_000) + }) +} diff --git a/packages/duron/test/otel-integration.test.ts b/packages/duron/test/otel-integration.test.ts index b2a2531..1b0cc95 100644 --- a/packages/duron/test/otel-integration.test.ts +++ b/packages/duron/test/otel-integration.test.ts @@ -312,6 +312,11 @@ describe('OpenTelemetry with an application tracer provider', () => { expect(parentSpanId(actionOperation)).toBe(jobSpan.spanContext().spanId) expect(custom.attributes['custom.input']).toBe(7) expect(custom.attributes['custom.output']).toBe(28) + // getTracer(name) uses the application's provider with that name (instrumentation + // scope); startSpan uses Duron's tracer. + expect(library.instrumentationScope.name).toBe('app-library') + expect(libraryActive.instrumentationScope.name).toBe('app-library') + expect(custom.instrumentationScope.name).toBe('duron') // Handler spans carry the job and step ids of their parent. const jobId = jobSpan.attributes['duron.job.id'] diff --git a/packages/duron/test/prune-bootstrap.test.ts b/packages/duron/test/prune-bootstrap.test.ts index 254e07a..efb254f 100644 --- a/packages/duron/test/prune-bootstrap.test.ts +++ b/packages/duron/test/prune-bootstrap.test.ts @@ -199,8 +199,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(await adapter.start()).toBe(true) await eventually(async () => expect(relay.held.length).toBeGreaterThan(0)) stopped = Promise.allSettled([adapter.stop()]).then((results) => results[0]!) - // Stop drains (5s) and cleans up (5s) before the owned close; the driver's five-second - // end timeout then destroys the stalled startup attempt. + // Stop drains and cleans up (one budget each) before the owned close; the driver's end + // timeout (80% of the budget) then destroys the stalled startup attempt. await eventually(async () => expect(endSettled).toBe(true), 25_000) expect(ends).toBe(1) // postgres.js 4 sends no close notice before ready; the owned close must still settle. @@ -215,7 +215,8 @@ if (process.env['POSTGRES_TEST'] === 'true') { const stats = (lock!.client as unknown as { stats: { connections: number; opening: number } }) .stats expect(stats).toMatchObject({ connections: 0, opening: 0 }) - // Every stop phase waits on the stalled bootstrap: these are reported, never a false close. + // The drain and cleanup phases wait on the stalled bootstrap and are reported. The owned + // close ends within its budget: the end timeout destroys the attempt before it expires. const outcome = await stopped expect(outcome.status).toBe('rejected') const reason = (outcome as PromiseRejectedResult).reason @@ -224,7 +225,6 @@ if (process.env['POSTGRES_TEST'] === 'true') { `Incomplete shutdown: admitted-work drain exceeded the shutdown timeout (${BUDGET} ms)`, 'Liveness release withheld because admitted work did not drain', `Incomplete shutdown: database cleanup exceeded the shutdown timeout (${BUDGET} ms)`, - `Incomplete shutdown: owned close exceeded the shutdown timeout (${BUDGET} ms)`, ]) await eventually(async () => { expect( diff --git a/packages/duron/test/prune-key.test.ts b/packages/duron/test/prune-key.test.ts new file mode 100644 index 0000000..2dc2e04 --- /dev/null +++ b/packages/duron/test/prune-key.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'bun:test' + +import { sql } from 'drizzle-orm' +import postgres from 'postgres' + +import { type Adapter, type AdapterFactory, pgliteFactory, postgresFactory } from './adapters.js' + +// The scheduled-prune advisory key is derived from the schema name +// (hashtextextended('duron:prune:', 0)), not the constant 42: an application lock on +// 42, or a Duron adapter on another schema, does not hold it. + +type PruneProbe = Adapter & { + _acquirePruneLock: () => Promise + _releasePruneLock: () => Promise + db: { execute: (query: unknown) => Promise } +} + +function rowsOf(result: unknown): Array> { + return Array.isArray(result) ? [...result] : (result as { rows: Array> }).rows +} + +// pg_locks splits a bigint advisory key into classid (high 32 bits) and objid (low 32 bits). +const heldPruneKey = (schema: string) => sql` + SELECT count(*)::int AS count FROM pg_locks + WHERE locktype = 'advisory' AND objsubid = 1 AND granted + AND ((classid::bigint << 32) | objid::bigint) = hashtextextended(${`duron:prune:${schema}`}, 0)` + +function run(factory: AdapterFactory) { + describe(`Scheduled prune key with ${factory.name}`, () => { + it('locks the key derived from the schema name', async () => { + const instance = await factory.create() + const adapter = instance.adapter as PruneProbe + adapter.setId('prune-key') + const app = + factory.name === 'postgres' + ? postgres(instance.connectionUrl, { max: 1, onnotice: () => undefined }) + : null + try { + await adapter.start() + // An application lock on the former constant key does not block scheduled pruning. + if (app) { + expect((await app`SELECT pg_try_advisory_lock(42) AS acquired`)[0]!['acquired']).toBe( + true, + ) + } + expect(await adapter._acquirePruneLock()).toBe(true) + const [held] = rowsOf(await adapter.db.execute(heldPruneKey('duron'))) + expect(held!['count']).toBe(1) + const [other] = rowsOf(await adapter.db.execute(heldPruneKey('other'))) + expect(other!['count']).toBe(0) + await adapter._releasePruneLock() + const [released] = rowsOf(await adapter.db.execute(heldPruneKey('duron'))) + expect(released!['count']).toBe(0) + } finally { + await app?.end({ timeout: 5 }) + await adapter.stop() + await instance.deleteDb() + } + }) + }) +} + +run(pgliteFactory) +if (process.env['POSTGRES_TEST'] === 'true') run(postgresFactory) diff --git a/packages/duron/test/prune-loss.test.ts b/packages/duron/test/prune-loss.test.ts index 67629ce..430e0dc 100644 --- a/packages/duron/test/prune-loss.test.ts +++ b/packages/duron/test/prune-loss.test.ts @@ -111,7 +111,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { const owners = await observer<{ pid: number }[]>` SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON a.pid = l.pid WHERE a.datname = current_database() AND a.application_name = ${application} - AND l.locktype = 'advisory' AND l.classid = 0 AND l.objid = 42 + AND l.locktype = 'advisory' AND ((l.classid::bigint << 32) | l.objid::bigint) = hashtextextended('duron:prune:duron', 0) AND l.objsubid = 1 AND l.granted ` expect(owners).toHaveLength(1) @@ -125,8 +125,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { ).toHaveLength(1) await eventually(async () => expect(observedLoss).toBe(true)) expect( - (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] - ?.acquired, + ( + await observer< + { acquired: boolean }[] + >`SELECT pg_try_advisory_lock(hashtextextended('duron:prune:duron', 0)) AS acquired` + )[0]?.acquired, ).toBe(true) expect( await observer` diff --git a/packages/duron/test/prune-ownership.test.ts b/packages/duron/test/prune-ownership.test.ts index 4a68ffe..d4afca3 100644 --- a/packages/duron/test/prune-ownership.test.ts +++ b/packages/duron/test/prune-ownership.test.ts @@ -86,7 +86,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { const owners = await observer<{ pid: number }[]>` SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON a.pid = l.pid WHERE a.datname = current_database() AND l.locktype = 'advisory' - AND l.classid = 0 AND l.objid = 42 AND l.objsubid = 1 AND l.granted + AND ((l.classid::bigint << 32) | l.objid::bigint) = hashtextextended('duron:prune:duron', 0) AND l.objsubid = 1 AND l.granted ` expect(owners).toHaveLength(1) expect( @@ -237,8 +237,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { const observer = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) try { expect( - (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] - ?.acquired, + ( + await observer< + { acquired: boolean }[] + >`SELECT pg_try_advisory_lock(hashtextextended('duron:prune:duron', 0)) AS acquired` + )[0]?.acquired, ).toBe(true) expect(await adapter.start()).toBe(true) await eventually(async () => expect(acquisitions.length).toBeGreaterThanOrEqual(3)) @@ -248,8 +251,11 @@ if (process.env['POSTGRES_TEST'] === 'true') { expect(reserves).toBe(1) expect(returns).toBe(0) expect( - (await observer<{ released: boolean }[]>`SELECT pg_advisory_unlock(42) AS released`)[0] - ?.released, + ( + await observer< + { released: boolean }[] + >`SELECT pg_advisory_unlock(hashtextextended('duron:prune:duron', 0)) AS released` + )[0]?.released, ).toBe(true) await eventually(async () => expect(pause).toBe(true)) expect(hooks).toBe(3) @@ -261,12 +267,18 @@ if (process.env['POSTGRES_TEST'] === 'true') { // Pause before another acquisition, not after it: independent acquisition // here excludes residual native reentrant stacks on the still-live backend. expect( - (await observer<{ acquired: boolean }[]>`SELECT pg_try_advisory_lock(42) AS acquired`)[0] - ?.acquired, + ( + await observer< + { acquired: boolean }[] + >`SELECT pg_try_advisory_lock(hashtextextended('duron:prune:duron', 0)) AS acquired` + )[0]?.acquired, ).toBe(true) expect( - (await observer<{ released: boolean }[]>`SELECT pg_advisory_unlock(42) AS released`)[0] - ?.released, + ( + await observer< + { released: boolean }[] + >`SELECT pg_advisory_unlock(hashtextextended('duron:prune:duron', 0)) AS released` + )[0]?.released, ).toBe(true) const stopping = adapter.stop() permitNext.resolve() diff --git a/packages/duron/test/prune-pglite-faults.test.ts b/packages/duron/test/prune-pglite-faults.test.ts index 1a5a449..567576d 100644 --- a/packages/duron/test/prune-pglite-faults.test.ts +++ b/packages/duron/test/prune-pglite-faults.test.ts @@ -40,7 +40,9 @@ for (const fault of ['malformed acquisition', 'malformed unlock', 'native false if (fault === 'native false unlock') { // Actual interference on this one owned engine makes the library's // following unlock return PostgreSQL false, not a mocked result. - await this.db.execute(sql`SELECT pg_advisory_unlock(42)`) + await this.db.execute( + sql`SELECT pg_advisory_unlock(hashtextextended('duron:prune:duron', 0))`, + ) } await super._releasePruneLock() } @@ -75,7 +77,7 @@ for (const fault of ['malformed acquisition', 'malformed unlock', 'native false if (fault === 'malformed acquisition') expect(stats.lastPrunedAt).toBeNull() else expect(stats.lastPrunedAt).toBeInstanceOf(Date) const locks = await engine.query<{ count: number }>( - `SELECT count(*)::integer AS count FROM pg_locks WHERE locktype = 'advisory' AND classid = 0 AND objid = 42 AND objsubid = 1`, + `SELECT count(*)::integer AS count FROM pg_locks WHERE locktype = 'advisory' AND ((classid::bigint << 32) | objid::bigint) = hashtextextended('duron:prune:duron', 0) AND objsubid = 1`, ) expect(locks.rows[0]?.count).toBe(fault === 'malformed acquisition' ? 1 : 0) expect(adapter.engine).toBe(engine) diff --git a/packages/duron/test/prune-reestablish.test.ts b/packages/duron/test/prune-reestablish.test.ts index ec8fb65..528ba93 100644 --- a/packages/duron/test/prune-reestablish.test.ts +++ b/packages/duron/test/prune-reestablish.test.ts @@ -12,7 +12,7 @@ import { getPostgresConnection } from './docker.js' // A lost coordination session (server restart, idle_session_timeout, pg_terminate_backend) // retires the scheduler only until the old session is confirmed closed: a later tick builds -// a new lock session and pruning continues. Key 42 keeps one owner: the server released the +// a new lock session and pruning continues. The prune key keeps one owner: the server released the // old session's lock when it ended, and no pass overlaps the re-establishment. // A replacement lock that cannot start is retried after a backoff: a connection fault logs a // warning, another fault (rejected credentials) an error. A single-owner fault (changed or @@ -113,11 +113,11 @@ async function harness( } adapter.setLogger(logger) const observer = postgres(CONNECTION_URL, { max: 1 }) - // The lock session is the backend whose last statement used advisory key 42. + // The lock session is the backend whose last statement used the scheduled-prune advisory key. const lockSessions = () => observer<{ pid: number }[]>` SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND application_name = ${application} - AND query LIKE '%advisory%lock(42)%' + AND query LIKE '%advisory%lock(hashtextextended(%' ` return { adapter, diff --git a/packages/duron/test/prune-replies.test.ts b/packages/duron/test/prune-replies.test.ts index 007f9b2..262bf7c 100644 --- a/packages/duron/test/prune-replies.test.ts +++ b/packages/duron/test/prune-replies.test.ts @@ -56,7 +56,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { if (!(phase in (rows[0] ?? {}))) return rows const locks = await observer` SELECT pid FROM pg_locks WHERE pid = ${rows[0]!.pid} AND locktype = 'advisory' - AND classid = 0 AND objid = 42 AND objsubid = 1 AND granted + AND ((classid::bigint << 32) | objid::bigint) = hashtextextended('duron:prune:duron', 0) AND objsubid = 1 AND granted ` nativeLocks = locks.length // Only the observed result is corrupted after native SQL and diff --git a/packages/duron/test/prune-scheduler.test.ts b/packages/duron/test/prune-scheduler.test.ts index b745c83..3b1cc60 100644 --- a/packages/duron/test/prune-scheduler.test.ts +++ b/packages/duron/test/prune-scheduler.test.ts @@ -56,7 +56,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { // Native ownership evidence supplements the public start/override path. const locks = await observer<{ pid: number }[]>` SELECT pid FROM pg_locks - WHERE locktype = 'advisory' AND classid = 0 AND objid = 42 AND objsubid = 1 + WHERE locktype = 'advisory' AND ((classid::bigint << 32) | objid::bigint) = hashtextextended('duron:prune:duron', 0) AND objsubid = 1 AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) AND granted ` @@ -222,7 +222,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { const owners = await observer<{ pid: number }[]>` SELECT a.pid FROM pg_stat_activity a JOIN pg_locks l ON l.pid = a.pid WHERE a.datname = current_database() AND a.application_name = ${application} - AND l.locktype = 'advisory' AND l.classid = 0 AND l.objid = 42 + AND l.locktype = 'advisory' AND ((l.classid::bigint << 32) | l.objid::bigint) = hashtextextended('duron:prune:duron', 0) AND l.objsubid = 1 AND l.granted ` expect(owners).toHaveLength(1) diff --git a/packages/duron/test/prune-scope.test.ts b/packages/duron/test/prune-scope.test.ts index 6e0e21b..70c3f69 100644 --- a/packages/duron/test/prune-scope.test.ts +++ b/packages/duron/test/prune-scope.test.ts @@ -37,7 +37,7 @@ class ScopePrune extends PostgresAdapter { } if (process.env['POSTGRES_TEST'] === 'true') { - it('configured schemas contend database-wide, another database proceeds, and direct prune stays outside coordination', async () => { + it('each schema has its own prune key, another database proceeds, and direct prune stays outside coordination', async () => { const first = await getPostgresConnection() const other = await getPostgresConnection() const release = Promise.withResolvers() @@ -45,18 +45,22 @@ if (process.env['POSTGRES_TEST'] === 'true') { const owner = new ScopePrune({ connection: first.CONNECTION_URL, pruneArchive }) owner.hold = release.promise owner.setId('schema-owner') - const contender = new ScopePrune({ + const otherSchema = new ScopePrune({ connection: first.CONNECTION_URL, schema: 'prune_other', migrateOnStart: false, pruneArchive, }) - contender.setId('schema-contender') + otherSchema.setId('schema-other') + // Same schema as the owner, no scheduled pruning: only direct calls. + const direct = new ScopePrune({ connection: first.CONNECTION_URL, migrateOnStart: false }) + direct.setId('schema-direct') const independent = new ScopePrune({ connection: other.CONNECTION_URL, pruneArchive }) independent.setId('database-independent') const observer = postgres(first.CONNECTION_URL, { max: 1 }) try { expect(await owner.start()).toBe(true) + // The owner holds its schema's prune key while its scheduled pass waits. await eventually(async () => expect(owner.calls).toBe(1)) const jobId = await owner.createJob({ queue: 'schema-prune', @@ -75,34 +79,38 @@ if (process.env['POSTGRES_TEST'] === 'true') { await observer`CREATE TABLE prune_other.jobs_archive (LIKE duron.jobs_archive INCLUDING ALL)` await observer`CREATE TABLE prune_other.job_steps_archive (LIKE duron.job_steps_archive INCLUDING ALL)` await observer`INSERT INTO prune_other.jobs_archive SELECT * FROM duron.jobs_archive` - expect(await contender.start()).toBe(true) - await eventually(async () => expect(contender.contentions).toBeGreaterThanOrEqual(3)) - expect(contender.calls).toBe(0) - expect((await contender.getArchiveStats()).jobsCount).toBe(1) + // Another schema's scheduled pruning does not wait for the owner's key. + expect(await otherSchema.start()).toBe(true) + await eventually(async () => + expect((await otherSchema.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), + ) + expect(otherSchema.contentions).toBe(0) + expect((await otherSchema.getArchiveStats()).jobsCount).toBe(0) expect(await independent.start()).toBe(true) await eventually(async () => expect((await independent.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), ) expect(owner.calls).toBe(1) - expect(contender.calls).toBe(0) - // Direct calls must reach the actual override/super and preserve counts, - // despite a different schema's currently held scheduled key42 lock. + // Direct calls reach the actual override/super and preserve counts, despite the + // owner's currently held scheduled key for the same schema. + expect(await direct.start()).toBe(true) expect( - await contender.pruneArchive({ + await direct.pruneArchive({ olderThan: new Date('2099-01-01'), batchSize: 1, maxBatches: 1, }), ).toBe(1) - expect(contender.calls).toBe(1) - expect((await contender.getArchiveStats()).lastPrunedAt).toBeNull() + expect(direct.calls).toBe(1) + expect((await direct.getArchiveStats()).lastPrunedAt).toBeNull() release.resolve() await eventually(async () => - expect((await contender.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), + expect((await owner.getArchiveStats()).lastPrunedAt).toBeInstanceOf(Date), ) expect((await owner.getArchiveStats()).jobsCount).toBe(0) expect(await owner.stop()).toBe(true) - expect(await contender.stop()).toBe(true) + expect(await otherSchema.stop()).toBe(true) + expect(await direct.stop()).toBe(true) expect(await independent.stop()).toBe(true) await eventually(async () => { expect( @@ -116,7 +124,12 @@ if (process.env['POSTGRES_TEST'] === 'true') { }) } finally { release.resolve() - await Promise.allSettled([owner.stop(), contender.stop(), independent.stop()]) + await Promise.allSettled([ + owner.stop(), + otherSchema.stop(), + direct.stop(), + independent.stop(), + ]) await observer.end({ timeout: 5 }) await first.deleteDb() await other.deleteDb() diff --git a/packages/duron/test/prune-transport.test.ts b/packages/duron/test/prune-transport.test.ts index 269a79c..2ab5ed0 100644 --- a/packages/duron/test/prune-transport.test.ts +++ b/packages/duron/test/prune-transport.test.ts @@ -126,7 +126,7 @@ if (process.env['POSTGRES_TEST'] === 'true') { await eventually(async () => { const locks = await observer` SELECT pid FROM pg_locks WHERE pid = ${pid} AND locktype = 'advisory' - AND classid = 0 AND objid = 42 AND objsubid = 1 AND granted + AND ((classid::bigint << 32) | objid::bigint) = hashtextextended('duron:prune:duron', 0) AND objsubid = 1 AND granted ` expect(locks).toHaveLength(phase === 'acquire reply' ? 1 : 0) expect( diff --git a/packages/duron/test/recovery-held-accessor.test.ts b/packages/duron/test/recovery-held-accessor.test.ts new file mode 100644 index 0000000..23ba9c2 --- /dev/null +++ b/packages/duron/test/recovery-held-accessor.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'bun:test' + +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' +import type { RecoverJobsOptions } from '../src/adapters/schemas.js' +import { Client } from '../src/client.js' +import { recoverJobsForClient } from '../src/recovery-scope.js' + +// A custom adapter's `_recoverJobs` reads the Client's held job ids through the protected +// `_heldJobIds(options)` accessor, so it can apply the same exclusion as the built-in one. + +class RecordingAdapter extends PGLiteAdapter { + seen: Array = [] + protected override async _recoverJobs(options: RecoverJobsOptions): Promise { + this.seen.push(this._heldJobIds(options)) + return super._recoverJobs(options) + } +} + +describe('Held job ids for a custom _recoverJobs', () => { + it('passes the Client held ids, and the defaults of direct calls', async () => { + const unbound = new RecordingAdapter({ connection: ':memory:' }) + unbound.setId('unbound') + const bound = new RecordingAdapter({ connection: ':memory:' }) + const client = new Client({ + id: 'bound', + database: bound, + syncPattern: false, + recoverJobsOnStart: false, + recoverJobsInterval: 0, + logger: 'silent', + }) + try { + await unbound.start() + await client.start() + // Direct call on an adapter without a Client: its own id is included entirely. + await unbound.recoverJobs({ checksums: [] }) + // Direct call on an adapter used by a Client: its own id is skipped (null). + await bound.recoverJobs({ checksums: [] }) + // The Client's recovery: the ids it holds. + await recoverJobsForClient(bound, { checksums: [] }, ['held-1', 'held-2']) + expect(unbound.seen).toEqual([[]]) + expect(bound.seen).toEqual([null, ['held-1', 'held-2']]) + } finally { + await client.stop() + await unbound.stop() + } + }) +}) From 490c9f59d5f6b44d7158395b3fba5f0c286685b8 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 12:21:42 -0300 Subject: [PATCH 06/20] fix(migrate): run the locked migration transaction READ COMMITTED (F3 review) With default_transaction_isolation = repeatable read or serializable, the migration transaction took its snapshot at the advisory-lock SELECT, before the wait, so a later migrator did not see the migrations of the first one and applied them again (5/6 cold starts failed on PG19). Set isolationLevel 'read committed' explicitly. Test: PGlite probe of the transaction isolation and the concurrent cold-start test under a repeatable-read default. Docs: the migration transaction is READ COMMITTED; during a rolling upgrade two unlocked prune passes can rarely deadlock (40P01), one pass logs the error and the next tick retries. --- packages/docs/content/docs/adapters.mdx | 4 +- packages/duron/src/adapters/postgres/base.ts | 22 ++-- .../duron/test/migrate-concurrency.test.ts | 110 +++++++++++++----- 3 files changed, 97 insertions(+), 39 deletions(-) diff --git a/packages/docs/content/docs/adapters.mdx b/packages/docs/content/docs/adapters.mdx index 9b673de..bc9201f 100644 --- a/packages/docs/content/docs/adapters.mdx +++ b/packages/docs/content/docs/adapters.mdx @@ -88,7 +88,7 @@ The scheduler attempts a pass immediately during startup, then at the configured An opted-in adapter owns one additional, max-one postgres.js client for coordination. It first performs an ordinary read-only backend-identity query, then reserves that same ready backend once for the scheduler lifetime. Initial driver setup attempts are permitted only while that first bootstrap is pending. After bootstrap succeeds, coordination never reconnects that session; only a lost session is replaced by a new client (see below). Each pass acquires the schema's session-level advisory key (see below) and must receive a true unlock; the reservation is not returned between passes. -The key is derived from the adapter's schema: `hashtextextended('duron:prune:' || schema, 0)` (for the default schema, `hashtextextended('duron:prune:duron', 0)`). Adapters of the same schema coordinate; other Duron schemas in the same database, separate databases and application locks on other keys do not contend. Earlier versions used the constant key `42` for every schema. During a rolling upgrade, a worker of an earlier version (key `42`) and an upgraded worker (the derived key) can prune the same schema at the same time; this is harmless, because a prune pass only deletes archived jobs older than its cutoff, and concurrent passes delete each row once. It ends when every worker is upgraded. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. +The key is derived from the adapter's schema: `hashtextextended('duron:prune:' || schema, 0)` (for the default schema, `hashtextextended('duron:prune:duron', 0)`). Adapters of the same schema coordinate; other Duron schemas in the same database, separate databases and application locks on other keys do not contend. Earlier versions used the constant key `42` for every schema. During a rolling upgrade, a worker of an earlier version (key `42`) and an upgraded worker (the derived key) can prune the same schema at the same time; this is harmless, because a prune pass only deletes archived jobs older than its cutoff, and concurrent passes delete each row once. At worst, two passes lock the same rows in different orders and one of them fails with a deadlock error (`40P01`); Duron logs it, and the next tick retries. It ends when every worker is upgraded. DELETEs still run on the adapter's original query pool, including when that pool has `max: 1`. Custom `_pruneArchive` overrides remain in the dispatch path and can delegate to `super._pruneArchive`. Observed session loss, uncertain/malformed coordination results, or false/rejected unlock retires scheduling for that adapter and attempts to close only its isolated lock client. It does not replay pruning or close the normal query/listener resources. While retired, each tick is skipped and logged as a warning. After the loss of an established session (a server restart or failover, `idle_session_timeout`, a pooler or load-balancer idle timeout, `pg_terminate_backend`), once the old client is confirmed closed and no pass is running, the next tick creates a new lock client and pruning continues; the server released the old session's lock when it ended, so the key keeps a single owner. Such a loss is logged as a warning, not an error. If that replacement client cannot start, later ticks try again after a backoff that doubles from the interval up to five minutes. The backoff counts from the failure, and the tick nearest to the due time retries, so a tick that fires slightly early does not add an interval. The replacement never requested the lock, and a new attempt starts only after its close is confirmed, so the key keeps a single owner. The fault decides the log level: @@ -165,7 +165,7 @@ An empty table without columns. Each claim transaction locks it (`LOCK TABLE ... Duron automatically runs migrations on startup if `migrateOnStart` is enabled. Migrations are located in the `migrations/postgres` directory. -Instances that start at the same time migrate one at a time: each runs its migrations in one transaction that first takes a transaction-level advisory lock for the migrations schema (key `hashtextextended('duron:migrate:duron', 0)`). A later instance waits for the first one to commit, then finds the migrations applied and applies nothing, instead of failing on the concurrent creation of the same schema or tables. The lock is released when that transaction ends. On PGLite the same transaction and lock run on its single session. +Instances that start at the same time migrate one at a time: each runs its migrations in one transaction that first takes a transaction-level advisory lock for the migrations schema (key `hashtextextended('duron:migrate:duron', 0)`). A later instance waits for the first one to commit, then finds the migrations applied and applies nothing, instead of failing on the concurrent creation of the same schema or tables. The lock is released when that transaction ends. The transaction is `READ COMMITTED` whatever `default_transaction_isolation` is, so the later instance sees the migrations that the first one committed while it waited. On PGLite the same transaction and lock run on its single session. To generate new migrations: diff --git a/packages/duron/src/adapters/postgres/base.ts b/packages/duron/src/adapters/postgres/base.ts index e94d62d..bac0353 100644 --- a/packages/duron/src/adapters/postgres/base.ts +++ b/packages/duron/src/adapters/postgres/base.ts @@ -340,19 +340,25 @@ export abstract class PostgresBaseAdapter< * schema (`hashtextextended('duron:migrate:', 0)`). Concurrent cold starts then * migrate one at a time: each later one waits, then sees the migrations the first one * applied (READ COMMITTED: every statement after the lock sees them) and applies nothing. - * Without it, their `CREATE SCHEMA/TABLE IF NOT EXISTS` and migration DDL race and fail with - * duplicate-object errors. The lock is released at COMMIT or ROLLBACK. + * The transaction sets READ COMMITTED explicitly: with a default isolation of REPEATABLE READ + * or SERIALIZABLE, its snapshot would be taken at the lock statement, before the wait, and a + * later migrator would apply every migration again. Without the lock, their + * `CREATE SCHEMA/TABLE IF NOT EXISTS` and migration DDL race and fail with duplicate-object + * errors. The lock is released at COMMIT or ROLLBACK. */ protected async _migrateLocked( migrationsSchema: string, migrate: (tx: Parameters[0]>[0]) => Promise, ): Promise { - await this.db.transaction(async (tx) => { - await tx.execute( - sql`SELECT pg_advisory_xact_lock(hashtextextended(${`duron:migrate:${migrationsSchema}`}, 0))`, - ) - await migrate(tx) - }) + await this.db.transaction( + async (tx) => { + await tx.execute( + sql`SELECT pg_advisory_xact_lock(hashtextextended(${`duron:migrate:${migrationsSchema}`}, 0))`, + ) + await migrate(tx) + }, + { isolationLevel: 'read committed' }, + ) } /** diff --git a/packages/duron/test/migrate-concurrency.test.ts b/packages/duron/test/migrate-concurrency.test.ts index 18e55df..8cf0a41 100644 --- a/packages/duron/test/migrate-concurrency.test.ts +++ b/packages/duron/test/migrate-concurrency.test.ts @@ -1,44 +1,96 @@ import { describe, expect, it } from 'bun:test' +import { sql } from 'drizzle-orm' import postgres from 'postgres' +import { PGLiteAdapter } from '../src/adapters/postgres/pglite.js' import { PostgresAdapter } from '../src/adapters/postgres/postgres.js' import { getPostgresConnection } from './docker.js' // Concurrent cold starts on an empty database: every adapter migrates under one advisory lock, // so their DDL does not race (duplicate schema, table or type errors) and each one starts. +// The migration transaction is READ COMMITTED whatever the default isolation is: under +// REPEATABLE READ or SERIALIZABLE its snapshot would be taken at the lock statement, before the +// wait, so a later migrator would not see the migrations of the first one and would apply them +// again. + +type MigrateProbe = { + db: { execute: (query: unknown) => Promise } + _migrateLocked: ( + schema: string, + migrate: (tx: { execute: (query: unknown) => Promise }) => Promise, + ) => Promise +} + +function rowsOf(result: unknown): Array> { + return Array.isArray(result) ? [...result] : (result as { rows: Array> }).rows +} + +describe('Migration transaction with pglite', () => { + it('runs READ COMMITTED when the default isolation is REPEATABLE READ', async () => { + const adapter = new PGLiteAdapter({ connection: ':memory:', migrateOnStart: true }) + adapter.setId('migrate-isolation') + const probe = adapter as unknown as MigrateProbe + try { + await adapter.start() + await probe.db.execute(sql`SET default_transaction_isolation = 'repeatable read'`) + let isolation: unknown + await probe._migrateLocked('duron', async (tx) => { + const [row] = rowsOf( + await tx.execute(sql`SELECT current_setting('transaction_isolation') AS level`), + ) + isolation = row!['level'] + }) + expect(isolation).toBe('read committed') + } finally { + await adapter.stop() + } + }) +}) if (process.env['POSTGRES_TEST'] === 'true') { describe('Concurrent migrations with postgres', () => { - it('starts several adapters at once on an empty database', async () => { - const { CONNECTION_URL, deleteDb } = await getPostgresConnection() - const observer = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) - const adapters = Array.from({ length: 6 }, (_, index) => { - const adapter = new PostgresAdapter({ connection: CONNECTION_URL }) - adapter.setId(`migrator-${index}`) - return adapter - }) - try { - const results = await Promise.allSettled(adapters.map((adapter) => adapter.start())) - const failures = results.filter((result) => result.status === 'rejected') - expect( - failures.map((failure) => String((failure as PromiseRejectedResult).reason)), - ).toEqual([]) - expect(results.map((result) => (result as PromiseFulfilledResult).value)).toEqual( - Array(adapters.length).fill(true), - ) - // Each migration is recorded once. - const [row] = await observer` - SELECT count(*)::int AS count, count(DISTINCT hash)::int AS distinct - FROM duron.migrations` - expect(row!['count']).toBe(row!['distinct']) - expect(row!['count']).toBeGreaterThan(0) - } finally { - for (const adapter of adapters) await adapter.stop().catch(() => undefined) - await observer.end({ timeout: 5 }) - await deleteDb() - } - }, 60_000) + for (const isolation of ['read committed', 'repeatable read'] as const) { + it(`starts several adapters at once on an empty database (default ${isolation})`, async () => { + const { CONNECTION_URL, deleteDb } = await getPostgresConnection() + const observer = postgres(CONNECTION_URL, { max: 1, onnotice: () => undefined }) + const url = new URL(CONNECTION_URL) + const adapters = Array.from({ length: 6 }, (_, index) => { + const adapter = new PostgresAdapter({ + connection: { + host: url.hostname, + port: Number(url.port), + user: decodeURIComponent(url.username), + password: decodeURIComponent(url.password), + database: url.pathname.slice(1), + connection: { default_transaction_isolation: isolation }, + }, + }) + adapter.setId(`migrator-${index}`) + return adapter + }) + try { + const results = await Promise.allSettled(adapters.map((adapter) => adapter.start())) + const failures = results.filter((result) => result.status === 'rejected') + expect( + failures.map((failure) => String((failure as PromiseRejectedResult).reason)), + ).toEqual([]) + expect( + results.map((result) => (result as PromiseFulfilledResult).value), + ).toEqual(Array(adapters.length).fill(true)) + // Each migration is recorded once. + const [row] = await observer` + SELECT count(*)::int AS count, count(DISTINCT hash)::int AS distinct + FROM duron.migrations` + expect(row!['count']).toBe(row!['distinct']) + expect(row!['count']).toBeGreaterThan(0) + } finally { + for (const adapter of adapters) await adapter.stop().catch(() => undefined) + await observer.end({ timeout: 5 }) + await deleteDb() + } + }, 60_000) + } }) } From b09c1a8410ea4eb8e6c92c196c5be6591fedce02 Mon Sep 17 00:00:00 2001 From: Martin Acosta Date: Wed, 2 Dec 2026 12:28:07 -0300 Subject: [PATCH 07/20] test: run the suite in parallel processes and create test databases from templates - scripts/test-parallel.ts: one `bun test --timeout 10000 ` process per file, a pool of half the CPU cores, longest files first; files with wall-clock budgets run afterwards, one at a time. Per-file lines, full output of failed files, a per-file count table, exit 1 on any failure. `bun run test` and both CI jobs use it; `test:serial` keeps plain bun test. - Native: each test database is CREATE DATABASE ... TEMPLATE over SQL (no docker exec); base (pgcrypto) and migrated templates are built once per server under an advisory lock, keyed by a hash of the migrations folder and the Drizzle version. deleteDb drops over SQL. - PGlite: factory engines start from a per-process dumpDataDir snapshot (skips initdb). - Factories return a migrated database unless `fresh: true` or `migrateOnStart: false`; tests that observe the migrations use `fresh: true`. --- .github/workflows/test.yml | 7 +- AGENTS.md | 23 +- packages/duron/package.json | 3 +- packages/duron/scripts/test-parallel.ts | 257 ++++++++++++++++++ packages/duron/test/adapter.test.ts | 13 +- packages/duron/test/adapters.ts | 107 +++++++- packages/duron/test/docker.ts | 183 ++++++++++--- packages/duron/test/lifecycle-sql.test.ts | 3 +- packages/duron/test/lifecycle-startup.test.ts | 3 +- packages/duron/tsconfig.json | 2 +- 10 files changed, 543 insertions(+), 58 deletions(-) create mode 100644 packages/duron/scripts/test-parallel.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 86f4c29..f6d9f46 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,13 +30,14 @@ jobs: # typecheck uses `bun check`; the published `dist` is emitted by tsc, so build it too. - name: Build run: bun run build + # scripts/test-parallel.ts: files in parallel processes, timing-sensitive files serially. - name: Run tests - run: bun test --timeout 10000 + run: bun run test # The native PostgreSQL suite (POSTGRES_TEST=true) on every supported server major. # test/docker.ts provisions the server itself: it runs DURON_TEST_POSTGRES_IMAGE as the # container duron-postgres-test- on port 5440 and creates one database per test - # with `docker exec` (createdb/psql/dropdb). The runner's Docker daemon is enough, so no + # over SQL from a template database. The runner's Docker daemon is enough, so no # `services:` container is used (docker.ts would refuse one that holds port 5440). native: timeout-minutes: 60 @@ -61,7 +62,7 @@ jobs: run: docker pull "$DURON_TEST_POSTGRES_IMAGE" # Every PostgreSQL test runs only with POSTGRES_TEST; the test job above is PGlite only. - name: Run native tests - run: bun test --timeout 10000 + run: bun run test - name: PostgreSQL container logs if: failure() run: docker logs "duron-postgres-test-${DURON_TEST_POSTGRES_IMAGE//[^a-zA-Z0-9_.-]/-}" 2>&1 | tail -200 diff --git a/AGENTS.md b/AGENTS.md index e0be5f4..d2e1f12 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ bun run lint # oxlint check bun run lint:fix # oxlint fix bun run fmt:check # oxfmt check bun run fmt # oxfmt fix -bun test --timeout 10000 # runs packages/duron tests (same as `bun run test`) +bun run test # packages/duron tests in parallel processes (scripts/test-parallel.ts) # Build bun run build # all packages @@ -61,9 +61,18 @@ bun run build:docs # docs only - Framework: `bun:test` - Tests live in `packages/duron/test/*.test.ts` - Run single file: `bun test --timeout 10000 specific.test.ts` -- Default per-test timeout: pass `--timeout 10000` (the `test` script and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. -- Core tests run with `bun test --timeout 10000` (no `--concurrent`: many suites share native resources and time-sensitive lifecycle budgets, and fail under cross-file concurrency) -- A plain `bun test --timeout 10000` runs PGlite only and needs no Docker. PostgreSQL tests run only with `POSTGRES_TEST=true`; every file that uses PostgreSQL gates it on that variable. +- Default per-test timeout: pass `--timeout 10000` (the runner and CI do). Bun ignores a `timeout` key in `bunfig.toml` (oven-sh/bun#7789), so a plain `bun test` uses 5000 ms. +- Full suite: `bun run test` (root or `packages/duron`) runs `packages/duron/scripts/test-parallel.ts`. CI uses it too. + - Each test file runs in its own `bun test --timeout 10000 ` process. Files without wall-clock budgets run in a pool of `--jobs N` processes (default: half the CPU cores; `DURON_TEST_JOBS` overrides). + - Files with wall-clock budgets (the `SERIAL` list in the script: `lifecycle*`, `prune-*`, `stop-*`, `shutdown-*`, `wait-native*`, `discovery-throughput`, `claim-isolation`, `claim-pglite`, `cross-mechanism`, `step-abort-settlement`, `wait-lifecycle`, `wait-cadence`) run after the pool, one at a time, with no other test process. Add a file there when it asserts elapsed time or observes timers/cadences under a bound. + - Output: one line per finished file (pass/skip/fail counts, time); then the complete output of each failed file, a per-file count table and the totals. Exit status 1 when a file fails (non-zero `bun test` exit, a failed test, or no summary). Every file's log is kept in `DURON_TEST_LOG_DIR` (default: a new temporary directory; the path is printed). + - Filters: `bun run test -- wait-` (in `packages/duron`) runs the files whose path contains a filter. +- `bun test --timeout 10000` (root, or `bun run test:serial` in `packages/duron`) still runs every file in one process, one file after another. It is slower; use it for one file or to compare. +- PGlite tests need no Docker. PostgreSQL tests run only with `POSTGRES_TEST=true`; every file that uses PostgreSQL gates it on that variable. +- Test databases (`test/adapters.ts`, `test/docker.ts`): + - `pgliteFactory` / `postgresFactory` give a database with all migrations already applied; `migrateOnStart` only checks them. With `fresh: true` or `migrateOnStart: false` the database is empty (as a new one). Use `fresh: true` in a test that observes the migrations themselves. + - PGlite: each process dumps one migrated and one empty engine once (`dumpDataDir`); every factory engine starts from a dump (`loadDataDir`), which skips `initdb` (about 450 ms of the 500 ms of a new engine). + - PostgreSQL: each test database is `CREATE DATABASE "" TEMPLATE "