Repository navigation
PostgreSQL reliability fixes, dependency updates and API-only telemetry - #9
Merged
Merged
Conversation
Constrain the initial ancestor lookup, recursive hops, and ancestor reset to the requested job while retaining accepted foreign-parent inputs. Cover direct and recursive foreign links on both SQL engines, including a parallel-root discriminator that fails with reset-only isolation. Preserve archived invalid-target restoration. Correct the nested-parallel fixture to establish completed siblings before testing retention; the previous failure setup could fail those siblings before time travel.
Merge SQL-01 after explicit acceptance of 29c0fa0. Merge-result typecheck, lint, root tests, formatting and PostgreSQL/PGLite time-travel tests passed. Preserve separate acceptance gates for subsequent fixes.
Group the existing name and English output search predicates before the strict millisecond boundary. Preserve parameterization, storage union, ordering and output omission. Add both-engine boundary, precision and search-preservation regressions plus Client/REST contract coverage. Correct step-list documentation to the existing nonpaginated response.
Merge SQL-05 and step-list documentation after explicit acceptance of e267efc. Merge-result typecheck, lint, root tests, formatting and both-engine adapter/server/time-travel tests passed.
Filter active/archive populations before a single global SQL page and obtain an independent exact count. Preserve ORM decoding, output, UTF-16 text order, public Date precision, Number duration ties, and final UUID ascending order. Add both-engine listing, restoration, Client/REST, filter/error, and real-driver payload-bound regressions. Correct listing documentation and the explicitly approved status-filter fixture assumption. Root typecheck/lint/test/format and core build pass. Listing-scoped both-engine verification passes; the unrelated preexisting PGLite recovery fixture failure from the broader run remains documented in the local implementation ticket.
Merge SQL-02/03/04/06 after exact-SHA acceptance of 39028eb. Root checks, core build and human-approved both-engine listing verification passed on the merge tree. Broader preexisting recovery-fixture and Node-runtime limits remain documented.
Apply the SQL-07 UTC-intermediate correction to time-travel shifts so all retained endpoints receive the same elapsed delta from transaction time. Preserve archive Date conversion limits, null finishes, graph guards and retained metadata. Add native-precision UTC, New York and Lord Howe regressions for both storage paths and engines, plus public override dispatch controls. Isolate the create-step fixture counter per test after the required both-engine gate exposed baseline cross-suite leakage; keep its expectations unchanged. Verified root typecheck, lint, tests and formatting, core build, scoped both-engine suites and Client Query Methods. Independent Standards and Spec reviews cover the pinned-base diff. No Node runtime verification or broader recovery-suite pass is claimed.
Exact-SHA acceptance of 2c9584f. Root and approved combined both-engine gates passed on the candidate-identical merge tree. Includes human-approved create-step fixture isolation; documented Node runtime and unrelated recovery-test limits remain.
Coordinate Client and Adapter shutdown through one internal lifecycle ledger. Track actual startup, operations, callbacks, handlers and steps through four shared phase budgets. Preserve cleanup errors and retry only safe unfinished resource obligations without reopening admission or releasing liveness early. Use SQL now() for both heartbeat upsert branches. Correct initial/periodic heartbeat error handling, PostgreSQL close timeout, and owned PGLite listener setup and cleanup. Omit forbidden late hints without changing mutation success. Add native lifecycle, clock, failure, retry and handler-entry regressions. Correct two approved recovery fixtures after exact-base attribution, and document implemented shutdown, clock limits and fetch-driven recovery. Verification: root typecheck, lint, formatting and core build passed. Root tests: 273 passed. Both-engine gate: 505 passed. Independent Standards and Spec reviews have no outstanding required findings. Node compatibility was reviewed at source/build level only; Node runtime remains untested.
Exact-SHA acceptance of 07009d6. Candidate-identical tree passed root273/0 and complete both-engine505/0 plus typecheck/lint/format/build. Native owned cleanup/inventory verified. Includes approved listener/cutoff ownership and fixture corrections; Node runtime remains untested.
Parameterize PGLite pg_notify and catch the entire built-in preparation/submission attempt on both SQL backends. Preserve successful validated mutation results and awaited delivery attempts, with original errors and delivery-unconfirmed context through the existing logger. Keep mutation wrappers, custom overrides, exact channels, native limits and lifecycle listener/cutoff ownership intact. Add both-engine public/native regressions for all six wrappers, reply uncertainty, encoding, callback cleanup and pending-attempt shutdown accounting; document advisory delivery and limits. Verified root typecheck/lint/test/fmt, core build and full POSTGRES_TEST=true suite. Independent Standards and Spec reviews bind the five-file candidate to immutable base d51b077. Node runtime remains untested under the approved source/build compatibility gate.
Exact-SHA acceptance of 5f247c0. Candidate-identical merge tree passed root296/0 and full both-engine550/0, typecheck/lint/format/corebuild. Log classification and native owned cleanup verified; Node runtime untested.
Bootstrap an isolated PostgreSQL lock client and retain one same-backend reservation for scheduled key42 ownership. Keep DELETEs and custom prune hooks on the original pool, with busy-tick skipping and scheduled-only continuation gates after loss. Integrate reservation return and prompt fault close with the shared lifecycle ledger, retaining original errors independently from positive resource release. Preserve manual pruning, partial commits and PGLite engine usability; document healthy-session-only exclusion. Add native transport, ownership, cleanup, error and both-engine regressions. Verification: root typecheck/lint/fmt/core build; root tests 307/0; full POSTGRES_TEST=true tests 596/0; focused prune 46/0. Independent Standards and Spec source reviews resolved Required findings. Node runtime remains untested; source/build compatibility only. Candidate awaits separate human acceptance.
Exact-SHA acceptance of 5ac7228. Identical merge tree passed root307/0, fullboth596/0, focusedprune46/0 and static/build gates. Logs and native owned cleanup verified; healthy-session-only and Node runtime limits preserved.
Run each built-in PostgreSQL/PGLite claim (`_fetch`) in its own SERIALIZABLE transaction on a transaction-bound context, using the byte-identical claim query. Concurrent claims can no longer both commit admissions from a stale group count: PostgreSQL rejects one with SQLSTATE 40001 at the statement or at COMMIT. Jobs are returned only after COMMIT; statement and COMMIT errors propagate without retry or empty conversion. SQL now() is the claim transaction's BEGIN time (approved). Existing transaction/statement lifecycle gates cover BEGIN, SET TRANSACTION, the claim and pre-COMMIT; the claim callback is tracked through outer driver rejection. Public/custom override dispatch is unchanged. Adds native PostgreSQL claim-admission regressions (stale overlap, Client held handlers, write skew, withheld COMMIT/ROLLBACK, drain/setup gates, BEGIN reference, lock footprint, mixed-legacy limit), seeded selection fixtures on both engines and PGLite shared-path tests; observes the in-flight fetch in two existing cancel fixtures; documents claim admission, limits and the postgres.js close limitation.
claim-isolation drops its owned database only after a fresh zero-session check passes; otherwise it keeps the database and fails with its name and the original error. claim-selection drops only after a successful adapter stop.
Hoist the write-skew and replay tests' promise gates out of try, reject a gate when its owning transaction fails first, track replay work, and release every owned gate and advisory barrier in finally before awaiting pending work or ending sessions, so an early failure cannot strand owned transactions. The mixed-legacy test releases its barrier first too.
Accept issue09 candidate 69de465 after exact-SHA human approval and candidate-identical merge verification. Root, full PostgreSQL, focused claim, typecheck, lint, format and core build gates passed; owned cleanup verified. Disclosed driver-close/reconnect and cancellation/prune limitations remain follow-ups.
Cancellation raced step creation: a creator could fail with FK 23503, a step could be archived active under a cancelled job, or a committed step could be lost. Competing cancel/complete/fail could hit 23505 or 40P01. Cancel, complete and fail now take the job row FOR UPDATE in their existing first statement, with unchanged guards. The step creator's job_check takes FOR KEY SHARE OF j in its single statement. Under READ COMMITTED a committed cancellation archives every earlier step as cancelled, and later creators get the existing null result. Competing terminators serialize; the loser returns false. Claims skip a job held by a cancellation. A waiting call rechecks its guard on the latest row version. A stale creator or a stale complete/fail racing a recovery requeue therefore loses, and the requeued job can run again (approved consequence). Status writers, claims, recovery and time travel are unchanged. Adds native PostgreSQL schedule tests (POSTGRES_TEST) and sequential both-engine tests, plus docs on guarantees and limits (READ COMMITTED, participating writers, frozen now(), lock waits, recovery residual).
Keep the single post-loss pg_stat_activity observation, its predicate and expected count of 2. Select backend_type, application_name, backend_start and state, and attach phase, cut pid and rows to the failure message so a natural extra or missing session is self-attributing. No waits or polling. Diagnostic improvement only; the intermittent third-session finding stays open.
Pending-safe independent finalization for the two real-PostgreSQL wait fixtures: either exact 57014 site for body readiness, first-nonzero identities, <=2s bounded zero, separate whole-target fresh zero before normal drop, primary preservation, 60s outer watchdog. Test-only; no driver or production change.
Test-only repair of the two real-PostgreSQL wait fixtures (candidate 9dc267f). Merge gates: root 446/60/0, full PostgreSQL 837/0/0, focused 97/0/0.
postgres.js 3.4.9 throws an uncaught socket.write TypeError on rollback after a lost connection (F1) and reconnects queued work after end() resolves, leaking an idle session (F2); 4.1.1 fixes both in direct reproductions. - prune lock: 4.1.1 calls onclose only for connections that reached ready, so a startup failure never confirmed the owned close. After end(), zero open and opening connections in sql.stats now count as native close evidence; drivers without stats keep waiting for onclose. - tests: wire-based setup-reply oracle, plain-array row comparison, and prune bootstrap expectations for 4.1.1 close behaviour.
postgres.js 4 end() resolves after its timeout while a destroyed startup attempt is still counted in stats.opening, and that attempt never calls onclose. Sampling stats once left the prune lock's owned close pending forever. Wait for zero open and opening connections (or onclose) instead; add a native test where startup stalls past the end timeout.
Fixes driver bugs F1 (uncaught socket.write after lost connection) and F2 (session leak after end()) by moving to postgres.js 4.1.1; prune lock accepts driver stats as close evidence for pre-ready connections. Gates: root 446/60/0, full PostgreSQL 838/0.
Each recovery phase (expired archival, then requeue) now runs in its own transaction: a standalone lock SELECT with the existing predicate and FOR UPDATE SKIP LOCKED, then the existing modifying CTE restricted to the locked IDs through one uuid[] parameter. Under READ COMMITTED the second statement sees every step committed before the job lock, so a discarded checksum no longer leaves a surviving step and expired archival no longer loses a step a creator received. Each phase uses its BEGIN-time now(). Adds native KR tests (old-arm red / candidate green) and adapts the heartbeat-clock fixture so recovery's phase transactions join its owned transaction.
…efore the Client starts Two push-worker tests could lose their direct fixture claim to the Client's own periodic discovery on slow CI (PR #9 native PG19). The fixtures are seeded and claimed before client.start(); the expiry test's waiting job no longer shares the blocker's 500 ms timeout. 25/25 under CPU load (was 3/25 failing). Lint 0 warnings.
…s; review follow-ups
N1: framework-started work (the worker discovery chain run, the ActionManager job run and
the heartbeat) now starts a root lifecycle context (`run(work, { root: true })`), so it no
longer inherits the context of the job or claim that triggered it. stop() awaited in job B
(enqueued and started from job A) waits for A's handler again, and the context chain stays
bounded while a backlog drains (it grew by one link per claim). The chain step callback ->
step queue run -> handler -> job run is unchanged, so stop() in a handler or step still
excludes its own work. Tests: stop-drain-scope.test.ts (PGlite + native; red before).
C3: heldJobIds is no longer a public RecoverJobsOptions field. The Client passes its held
job ids through the internal recoverJobsForClient (recovery-scope.ts), bound to the parsed
options object; the built-in _recoverJobs reads them with heldJobIdsOf. A direct
recoverJobs() keeps skipping the own id on a Client-bound adapter and includes it on a
Client-less adapter (documented). Custom _recoverJobs overrides keep working.
C2: docs and the multi-worker example use a unique id per process
(`worker-${crypto.randomUUID()}`) and explain that shared ids make recovery requeue
peers' running jobs.
Nits: prune-lock CONNECTION_LOSS comment (a half-open backend can keep key 42 until reaped);
error-handling.mdx lists WaitReadTimeoutError / WaitReadFailedError; claim-pglite pins one
attempt for a non-40001 (22012) claim error (the 'retry every error' mutant now fails).
Tests: adapter, server, archive, delete-jobs-safety and sql-injection run PGlite always and
PostgreSQL only with POSTGRES_TEST, so a plain `bun test` needs no Docker (AGENTS.md, CI
comment updated).
…heartbeat roots R1: fastq starts a queued task from the settlement of the task that finished, in that task's async context. A step queued behind a sibling's child step therefore inherited the sibling's callback context, and its stop() excluded the sibling from the drain. StepManager now captures AsyncLocalStorage.snapshot() in push() and runs the worker inside it. Test: stop-drain-scope 'waits for a sibling step of the stopping step' (nested fails without the fix on PGlite and native; flat is the control). R2: the bounded-chain test now also records the lifecycle context depth inside adapter.fetch (each claim) and adapter.heartbeat (each beat, heartbeatInterval 20) and asserts 1. Removing the discovery root fails it (62), removing the heartbeat root fails it (30/32), removing the ActionManager root fails it (3), on PGlite and native. A1: error-handling.mdx error-code table lists WAIT_READ_TIMEOUT and WAIT_READ_FAILED; client-api.mdx states that the stop() exclusion never covers a sibling step.
…gating) - stop() inside a handler/step excludes only its own work: framework-started work (discovery chain, job run, heartbeat) starts a root context, and queued steps run in the context of the code that called step(), not a sibling's. - Bounded lifecycle context depth (no growth per claim or heartbeat). - heldJobIds removed from the public recoverJobs options (private Client path). - Docs/example use unique worker ids; WaitRead* errors documented; 40001-only retry pinned by a test; prune-lock comment corrected. - Plain 'bun test' needs no Docker: native variants run only with POSTGRES_TEST. Gates: root 571/76/0 (PGlite only), PostgreSQL 19 1118/0, builds pass; review + recheck APPROVE.
…an uncovered claim settles C1: under several workers, a claim that returned fewer jobs than requested dropped its remaining demand, so part of a burst waited for the periodic tick. A claim locks every eligible row it sees (FOR UPDATE SKIP LOCKED in candidate_jobs) until it commits, so a concurrent claim returns few or even no jobs while work remains. Now a short claim with hinted (finite) demand left queues one follow-up after a random 10-50 ms delay. After an empty claim this happens only for more than one uncovered hint and only once in a row, so an empty queue is never polled and a lone hint that a peer won is not retried. The delay timer respects stop, cooldown and room (it only merges demand and pumps). Backlog: a completed job never woke discovery, so a group-limited backlog drained at L jobs per pullInterval. A job from a claim that did not cover its demand now requests discovery (unbounded demand, coalesced, trigger 'settled') when it settles locally. Jobs of a claim that covered its demand (one job for one hint) do not, so sparse traffic costs no extra claims. Tests: discovery-throughput.test.ts. A group-limited burst and backlog (limit 3, 20 ms jobs, 200 jobs, pullInterval 5 s) finish at handler speed with about one claim per freed slot and no claims once idle (PGlite + native). Native, 4 workers, 10 bursts of 300 jobs with 20 ms and 3000 ms jobs: every job starts before pullInterval / 2. worker-discovery: lone-hint empty claim is not retried, stop cancels a pending retry; two expectations updated for the new follow-ups. Docs: client-api batchSize, multi-worker Worker Discovery.
…e demand is uncovered R1: the empty-claim retry flag stayed set after a burst, so the next burst's empty claims were never retried. A new hint (a new created job) now resets it. Tracing the native 4-worker 3000 ms test showed a second cause: after the last hint, a worker's single retry can collide with a peer's next small claim, which locks every remaining eligible row (2 of 200 rounds still started jobs at ~3.17 s). Empty claims are now followed up at most twice in a row, the second time after 50-250 ms; a third empty claim ends it. With both: 20 of 20 runs (200 rounds) pass, max start 263 ms. R2: the settlement wake was per claim. When the claim that got the local jobs covered its own hints and the claims for the rest came back empty (group full), the backlog waited for the periodic tick. A Client-level #uncovered flag is set when an automatic claim gets less than its demand (except an unbounded claim that found nothing, which clears it, as does a covered claim); while it is set, every local settlement wakes discovery. Tests: discovery-throughput adds a limit 1 burst (200 ms jobs) and a limit 3 sequential creation (300 ms jobs), PGlite + native; each must finish within ideal + pullInterval / 2 (before: 7.4 s / 5.9 s; now ~3.2 s / ~1.8 s). worker-discovery adds 'a new hint allows the empty-claim retries again'; coalesce and retry expectations updated for the second retry. Mutants caught: no hint reset, no #uncovered, unbounded empty retries. Docs: client-api batchSize and multi-worker Worker Discovery describe the final rules (a slot freed by another worker is found by that worker or the periodic check). Comment at _claimQuery: candidate_jobs locks the whole eligible backlog (follow-up).
…cklogs (PR #9 follow-up C1) - A short claim with hinted demand left queues one jittered follow-up; empty claims under contention are retried at most twice (a hint or a productive claim resets this), because one in-flight claim locks the whole eligible backlog. - When a job from an uncovered claim settles (or this Client's last automatic claim was uncovered), discovery is requested again, so a group-limited backlog drains at handler speed instead of one batch per pullInterval. Bench: 2000-job burst across 4 workers 47 s -> ~16-20 s; group limit 3, 200 jobs: 2.6-2.8 s (was 39-99 of 200 in 60 s); steady arm latency unchanged, ~16% more (mostly empty) claims. Gates: root 577/76/0, PostgreSQL 19 1132/0, builds pass; review + recheck (fixes verified), final test fix 25/25.
…tors (#10) * 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. * 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). * 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. * 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). * 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:<schema>', 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. * 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. * test: run the suite in parallel processes and create test databases from templates - scripts/test-parallel.ts: one `bun test --timeout 10000 <file>` 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`. * test: serialize more wall-clock files, add a per-file timeout, drop stale templates (FAST review) - R1: local-cancellation.test (E5 100 ms margin), wait-context (350 ms budgets), worker-discovery (20 ms timer, 150 ms quiet window) and wait-cohorts (30 ms exact counts) run in the serial lane; AGENTS.md lists them. - A1: a per-file timeout (default 300000 ms, --file-timeout / DURON_TEST_FILE_TIMEOUT) kills a hung file and reports it by name with its output so far; the run continues. Pipes are read incrementally and released 2 s after exit, so a leaked grandchild that holds them cannot hang the runner. - A3: the runner drops templates of other migration keys before a native run (best effort, skipped while another run builds or copies them); a process whose template disappears (3D000) rebuilds it. - A4: the runner sets DURON_TEST_CONTAINER_READY=1 after preparing the container, so test processes skip the docker checks and the 1 s settle sleep. * test(claim-isolation): count only the claim's SERIALIZABLE setup migrate() now runs in a READ COMMITTED transaction (F3), so statements traced from start() include its SET TRANSACTION; the drain-boundary test counted it. * refactor: shared column lists, #op helpers, prune scheduler module, stop gate error Behaviour-neutral (F4): - columns.ts: JOB_COLUMNS / STEP_COLUMNS with columnNames/copiedColumns for the archive, recovery and time-travel copies; #archiveSteps helper; archive-columns test compares the lists with the schema. - Adapter #op(name, fn, { start, log }) and Client #op(fn) replace the repeated lifecycle/start/assert/log blocks (messages unchanged). - prune-scheduler.ts: PruneScheduler (state, tick, retire, re-establish) moved out of base.ts next to prune-lock.ts; base delegates via hooks. - base.ts: protected _transaction() helper replaces the monkey-patched this.db.transaction (same guards); lifecycle-sql hooks the helper. - prune-lock.ts: bootstrapPending/bootstrapSucceeded/established -> one #phase ('idle'|'bootstrapping'|'reserving'|'established'|'ended'). - StopGateError (one class, gate kind) for the stop-gate refusals; isStopFailure checks the type; messages and Error name unchanged. * fix: route prune faults through _retirePruning, brand StopGateError across copies - PruneScheduler acquisition and release faults call the host's retire, which goes through the protected _retirePruning hook again (as _pruneTick did), so an override receives them. Regression tests for both faults. - StopGateError carries a Symbol.for('duron.stopGate') brand on its prototype; isStopFailure checks the brand, so the error of another loaded copy of duron is recognized. instanceof still works. gate is non-enumerable, so a logged error has no extra field. - Document that subclasses must use this._transaction() to keep the stop gates (_transaction JSDoc, adapters.mdx). * test(shutdown-release): tolerate slow heartbeat writes in the long-drain test The test 'does not let another worker run a job while a stopping worker still runs it' failed once in a full native run with [run, run, step end, step end]. Cause: a test timing assumption, not a double run in Duron. The test used heartbeatInterval 100 ms and heartbeatTimeout 300 ms. Recovery treats a client whose last committed heartbeat is older than heartbeatTimeout as dead. On a loaded PostgreSQL the heartbeat upsert took 150 ms to 2.3 s, so B's recovery saw A's last_seen_at 321-929 ms old and requeued the job while A's step still ran. Instrumented reproductions (13 cases) all showed this. The beats during the drain keep the same cadence as the periodic beats before stop(): the stop adds no gap. A running (not stopping) worker with the same late heartbeat is recovered in the same way, which is the documented liveness contract. A second flake: the step slept 1.2 s from its start, so when b.start() took longer under load, the step ended before stop() and A completed the job ([run, step end]). Changes: - heartbeatTimeout 1000 ms (interval 100 ms): tolerates slow heartbeat writes. - The step waits for the abort, then runs 2 x heartbeatTimeout, so the drain starts with the stop and is longer than heartbeatTimeout plus B's recovery interval. - shutdownTimeout 10 s and waitForJob 10 s for headroom on a loaded machine. Red check: with the drain heartbeats disabled, the test still fails 3/3 with [run, run, step end]. * chore: group test files by feature, pg_isready readiness, How it works docs page - Tests: 76 -> 35 files, grouped by feature (lifecycle, prune-lock, prune-scheduler, wait, wait-timing, wait-native, claim, recover, local-cancellation, cancel-storage, stop, time-travel, archive, client). Each former file is a block with its own helpers under a banner; imports merged. Same test names and counts (PGlite 684 incl. 80 skip, native 1185: sorted name lists identical before/after). Two identifiers renamed to avoid new shadowing. - Fast runner SERIAL patterns updated (stop*, claim.test, wait-timing); every formerly serial test stays serial. AGENTS.md updated; oxlint override turns off consistent-function-scoping for test files. - test/docker.ts: waitForContainer polls pg_isready (TCP inside the container) instead of waiting for a log line. - Docs: short summaries for waitReadTimeout, pullInterval, batchSize, recoverJobsOnStart, recoverJobsInterval, shutdownTimeout and stop(); the guarantees catalogue (discovery/batchSize, recovery, wait reads, notification hints, shutdown, archive retention) moves to a new "How it works" page linked from them. * chore: F5 review nits (define B, dedupe shutdown text, stale comments, docker exec timeout) * ci: run the test workflow for pull requests into any branch (stacked PRs) * test(prune-lock): give the owned-close test room to close sessions on a loaded database The test holds database cleanup until its budget ends while owned close must still finish inside the same budget; with 300 ms (driver end 240 ms) closing the sessions on a loaded PostgreSQL 19 overran (local CI run). Uses 1 s; 5/5 native runs pass. * test(recover): delete the worker scripts when each test ends The worker scripts went to /tmp/duron-worker-*.ts and a 5 s timer deleted them. When the test process ended first (for example a filtered run) or the worker did not start, the files stayed. Each worker now gets a mkdtemp directory that afterEach deletes, also when the test fails. * fix(stop): write skipped step statuses in the job's final transaction During a graceful stop, a handler that still resolved had its aborted steps written as cancelled/failed (StepManager.writeSkipped) before completeJob. When completeJob then failed, the job was released with those steps already cancelled, and its next run failed on them ("Cannot recover a cancelled step"). completeJob and failJob now take an optional `steps` list (StepFinalization: stepId, status cancelled|failed, error). The built-in PostgreSQL/PGlite _completeJob/_failJob write them in the transaction that ends the job, after the job row lock and only for still-active steps, so a job that does not end keeps its steps unchanged. StepManager.takeSkipped() replaces writeSkipped(). Custom adapters keep the old behaviour: the protected getter _finishesStepsWithJob defaults to false, and then the Adapter writes each step with _cancelJobStep/_failJobStep first and calls _completeJob/_failJob without steps. Documented in adapters.mdx. The known-limit comment is removed. * fix(lifecycle): log stop-gate refusals as a plain Error again Since the stop-gate brand (F4), a logged refusal had pino `type` 'StopGateError' (from constructor.name) instead of 'Error'. `new StopGateError(gate)` now returns a plain Error (prototype Error.prototype, name 'Error', stack from the caller) with the same gate message, and non-enumerable own `gate` and Symbol.for('duron.stopGate') brand. isStopFailure still detects it by the brand, also as a cause. `instanceof StopGateError` still works: a static Symbol.hasInstance checks the brand, so it now also matches the error of another loaded copy. Before: {"err":{"type":"StopGateError","message":"Adapter is not accepting work",...}} After: {"err":{"type":"Error","message":"Adapter is not accepting work",...}} * docs: subclasses overriding _completeJob/_failJob must apply options.steps; JSDoc placement (leftovers review A1, A3)
Delete duplicates, tests that can never fail, tests of PGlite/PostgreSQL/zod instead of Duron, and implementation-coupled assertions; rewrite tests whose assertions did not check the behavior in their names. - adapter/archive/client/server: duplicated create, pagination, status and step-list tests; the always-passing recovery test; fetch batch checks now assert the exact count. - claim-isolation: raw-SQL isolation replays, the documented legacy READ COMMITTED non-guarantee, and the fresh-fetch copy of the stale-fetch test. - create-step/nested-steps/process-order: duplicate nesting and success cases, the fixture's own inventory branch; the option override and the nested cancel now assert their effect. - delete-jobs-safety, sql-injection, time-travel: rewritten against real active jobs, non-matching injections and a real re-execution. - lifecycle/notifications/prune-scheduler/recover/recover-snapshot: PGlite driver controls, duplicated startup-cleanup and prune-error tests, a crash test where no recovery happened, KR11 SQL-text binding checks, and tautological getConfig() assertions. - local-cancellation: remove the LOCAL_CANCELLATION_PUBLIC_ONLY switch. - claim: the migration count no longer assumes the claim lock migration is the last one.
- recover-snapshot (native): recover 70000 active jobs of a dead worker in
one phase. One parameter per locked ID would exceed the 65535-parameter
limit; this replaces the deleted KR11 SQL-text check.
- claim: count only migration directories (/^\d{14}_/).
- cancel-storage: delete "TT ... stale writes keep their unfenced results";
it asserted a non-guarantee.
Removes duplicates, tests that could never fail, tests of PGlite/PostgreSQL/zod rather than duron, and implementation-coupled assertions whose behaviour is covered elsewhere (18 files, net -1.2k lines; no production code changed). Rewritten tests are stricter. Adds a behavioural native test that recovers 70000 jobs in one phase (guards the single uuid[] binding). PGlite 615 -> 581 tests, PostgreSQL 1203 -> 1133. Independent coverage review APPROVE (every deleted test mapped to a remaining one); gates pass.
… and a time-window recipe Documents client.getArchiveStats/pruneArchive/truncateArchive and the /archive REST endpoints, the olderThan duration units, what a prune deletes (finished jobs and their steps), per-call limits, the clock note, and how to prune only in a time window.
Fix stale table names, options and defaults, examples that would not compile or run (getJobSteps paging, getHTML options, runAction key, postgres() instance as connection, z.record, z.date inputs), the GET /actions response shape, retry backoff formula, and timestamps that now come from the database clock. Document stop()/start() results, getJobs filters, adapter methods and hooks, DuronDashboard props.
Add the heartbeat change (database clock, start() rejects when the first heartbeat fails), say that only the adapter's migrateOnStart controls migrations, note the getTracer(name) instrumentation scope, the @default group limit and the 'Client is not accepting work' case; the multi-worker parent handles SIGTERM and a failed stop().
New 'Upgrading' page with every breaking and behaviour change since main and what to do; every docs page and README checked against the current code (defaults, options, methods, errors, routes, links); the multi-worker example stops workers gracefully on SIGTERM. Docs-only plus example code. Independent review: changes applied; docs build, 1126 internal links/anchors, 0 broken.
…igrations for any adapter schema - server: protected routes accept only access tokens (type 'access' with an email); /refresh accepts only refresh tokens; both verify HS256 only. - Client migrateOnStart is applied through Adapter.setMigrateOnStart(): migrations run at start only when neither the Client nor the adapter option is false. - The built-in migrations create the tables in the adapter's schema: for a schema other than duron, a temporary copy of the migrations names that schema; the migrations table and the migrate advisory lock key are per schema. Databases on the duron schema are unchanged. - Docs: client-api, adapters, server-api and Upgrading entries.
…, TelemetryContext type, React peer dependency - Adapter option migrationsFolder replaces the bundled migrations (applied unchanged, recorded in <schema>.migrations). - getHTML caches only the bundled assets and builds the page with the options of each call; the embedded config escapes '<'. - DuronDashboard enableLogin JSDoc says 'Defaults to false', as the code does. - duron/client re-exports the step-manager TelemetryContext (the type of ctx.telemetry). - duron-dashboard: react and react-dom are peer dependencies (^19.0.0), kept as dev dependencies for the build, and external in dist/index.js. - Docs: adapters, dashboard, dashboard README and Upgrading entries.
…of an action The action option 'concurrency' was validated (default 100) but never read. It is now the maximum number of running jobs of the action across all workers, with no default (no limit). - Migration 20261203025959: nullable action_concurrency_limit on jobs_active and jobs_archive (ADD COLUMN only). It is in JOB_COLUMNS, so archive, recovery and time-travel copies carry it; a retry takes the limit of the action's latest unexpired job (NULL included), else the source's. - Client.runAction stores action.concurrency with the job (CreateJobOptions actionConcurrencyLimit); jobs expose actionConcurrencyLimit. - Claim: under the existing claim lock, the action limit of the action's latest unexpired job and the action's active count (over its groups) bound the group candidates, ranked per action in creation order. A job needs room in both its group and its action; candidates of an action at its limit are dropped before the batch LIMIT, so other actions are claimed. - Tests: claim-selection fixtures (both engines), and an end-to-end test with 3 PostgreSQL workers (1 on PGlite) that the cap holds across workers and another action still runs. - Dashboard job details show the action limit. Docs: actions, multi-worker claim admission, how-it-works, jobs-and-steps, adapters, server-api and Upgrading.
- CI: the test job runs the duron-dashboard tests after Build; the getHTML test fails instead of skipping without dist when CI=true. Root 'bun run test' is unchanged. - Guard test: every quoted "duron" in the bundled migration SQL is a schema position. - Server tests: an HS512 token, a token without 'type' and one with a non-string email get 401. /refresh requires a string email. - duron-dashboard: react and react-dom are optional peers (getHTML needs neither). - Docs: Upgrading (set migrateOnStart: false for self-managed custom schemas, or startup fails with 'already exists'; clientMigrateOnStart for custom adapters; old workers' jobs lift the action limit during a rolling upgrade; optional peers), adapters (setMigrateOnStart and clientMigrateOnStart, temporary directory for custom-schema migrations), AGENTS.md CI section.
…emas, action concurrency, dashboard fixes - Security: protected routes accept only access tokens (HS256, type 'access'); /refresh accepts only refresh tokens. - The Client option migrateOnStart takes effect (migrations run only when neither the Client nor the adapter disables them). - Built-in migrations work for any adapter schema; migrationsFolder is honoured. - The action 'concurrency' option is a real cross-worker cap (new migration 20261203025959, nullable action_concurrency_limit; no default). - Dashboard: getHTML uses each call's options (assets cached), enableLogin docs match the default, React is an optional peer dependency; duron/client exports the real TelemetryContext type. CI runs the dashboard tests. Gates: root 602/74/0, PostgreSQL 19 1175/0, builds; follow-up checked (root 604/74/0, dashboard 2/0, server+migrations native). Review APPROVE.
…ustom schema Revert the custom-schema migration rewrite (bd8e156, 6fa6790): Duron's bundled migrations are only for the default "duron" schema. A custom schema is for applications that include Duron's tables in their own Drizzle schema with createSchema('<name>'), generate the migrations with drizzle-kit and set migrateOnStart: false. - Remove the temporary rewritten copy of the bundled SQL (migrations.ts) and its tests (the "duron" token guard, the custom-schema and two-schemas cases). - The applied migrations are recorded in duron.migrations again, under the 'duron' migrate lock, also for a custom migrationsFolder: a drizzle-kit migration creates its schema without IF NOT EXISTS, so it cannot share that schema with the migrations table. - start() fails before any SQL when the built-in migrations would run at start (migrateOnStart not false on the adapter and the Client, no migrationsFolder) and the adapter schema is not duron, with an error that points to the Integrating section of the docs. - A custom migrationsFolder with a custom schema is allowed. - Tests (PGlite and PostgreSQL): the start error leaves the database without schemas; tables generated from createSchema() with migrateOnStart: false run a job; a migrationsFolder generated from createSchema() applies and runs a job. - Docs: adapters schema/migrationsFolder/Migrations/Environment Isolation text; the Integrating section uses a named schema (createSchema('public') throws) and exports the schema object (or drizzle-kit does not create the schema). Upgrading: the custom-schema entry is replaced with the fail-fast note, and a checklist item. Kept: access-token fix, migrateOnStart precedence (Client and adapter), migrationsFolder, action concurrency, dashboard fixes, TelemetryContext.
- Test: Client-only migrateOnStart: false with a custom schema starts and runs a job without creating a duron schema (PGlite and PostgreSQL). - Docs and JSDoc: migrationsFolder with another schema creates a duron schema that holds only the migrations table. - _migrateLocked JSDoc: the adapters always pass duron (key 'duron:migrate:duron').
…n schema
Removes the custom-schema migration rewrite (temporary rewritten SQL copy): a custom
schema is for apps that include Duron's tables in their own Drizzle schema with
createSchema(name), generate the migrations with drizzle-kit and set
migrateOnStart: false. start() now fails before any SQL, with a message pointing to
the docs, when the built-in migrations would run for another schema. The Integrating
docs are corrected (createSchema('public') throws in Drizzle; export the schema).
Gates (3040182): root 0 fail (678 tests), PostgreSQL 19 0 fail (1179); follow-up
c94cd34 checked (migrations tests PGlite + native). Review APPROVE.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Reliability fixes for Duron's PostgreSQL adapter (and the PGlite adapter that shares it), a dependency refresh, and an OpenTelemetry API change. Every change was done on its own branch with tests that fail on the old code, independent review, and the full test suite before merging into this branch.
Final checks on this branch:
bun test577 pass / 76 skip / 0 fail (PGlite only, no Docker needed), full PostgreSQL suite (POSTGRES_TEST=true bun test) 1132 pass / 0 fail on PostgreSQL 19.0 (also run on 16), typecheck, lint, format, and duron/dashboard/docs builds. CI now also runs the full PostgreSQL suite on 16 and 19.telemetry: { traceExporter, serviceName, batchDelayMs }is replaced bytelemetry: { tracerProvider }. The app now creates its own OpenTelemetry provider (any SDK version, its own Resource/service name). Old options throw a clear error. Duron depends only on@opentelemetry/api(peer^1.9.0). Without the option, Duron no longer falls back to the global tracer provider, soNodeSDKusers must passtracerProviderexplicitly or spans disappear. See the migration section in the telemetry docs.Clienton an adapter that anotherClientuses (or used and stopped) throws aTypeError. Sharing never worked: the Clients shared one id, and stopping one stopped the other.stop()can reject (when cleanup fails within its time budgets), and every method rejects afterstop(). The lifecycle belongs to the adapter, so restarting needs a fresh adapter instance.syncPattern: 'push'now also runs periodic discovery as a safety net for lost notifications.runActionAndWaitthrowsWaitReadTimeoutError/WaitReadFailedError(new exports) when the database read times out or fails, and the lifecycle error when the client stops, instead ofJob not found.sort: []in job listing now means the default sort (startedAtdesc).worker-${crypto.randomUUID()}(worker-${process.pid}isworker-1in every container).client.database.fetch()are not held by the Client, so its recovery can requeue them.drizzle-orm(1.0.0-rc.6 || ^1.0.0),postgres(^4.1.1, optional) and@electric-sql/pglite(^0.5.17 || ^0.6.0, optional) are now declared peers.^20.19.0 || >=22.12.0(now inengines). Install docs pindrizzle-orm@1.0.0-rc.6, because the peer range does not accept later release candidates.socket.writeon a lost connection; a leaked session afterend()), both fixed in 4.x.20261130153037): indexes for job-list sorting on both job tables. Drizzle applies pending migrations in one transaction, so on large tables it briefly blocks writes; the adapter docs show how to pre-build the indexes withCREATE INDEX CONCURRENTLYfirst (the migration usesIF NOT EXISTS).COLLATE "C") and timestamps sort at full precision with anidtie-break that follows the sort direction.What was fixed (plain language)
Data correctness
falseno longer leaves the job stuck in active storage.updatedAfterfilter to name matches too.Lifecycle and workers
fetch()), with an automatic batch ceiling and failure cooldown; recovery uses a monotonic timer.await client.stop()inside a handler or step no longer deadlocks the shutdown; it skips waiting only for its own step and handler, never for other jobs or sibling steps.activeunder a failed job), and a parent step that times out waits for its running children (found by the new CI PostgreSQL jobs).Cancellation
Performance
Dependencies and tooling
p-retrymoved to devDependencies.typecheckusesbun check(tsc still buildsdist, which now starts clean and no longer shipsdrizzle.config.js).src/components/ui/(removed on purpose; AGENTS.md asks not to edit that folder, but these components were not used anywhere).sendEmailexample that would fail at runtime; examples are now type-checked.--frozen-lockfile, a build step, and a native PostgreSQL job on 16 and 19. Bun ignores thebunfig.tomltest timeout, so scripts and CI pass--timeout 10000.postgres:19-alpine(override withDURON_TEST_POSTGRES_IMAGE);bun run testno longer uses--concurrent, which was already broken onmain.Also included: follow-ups (#10) and test pruning
claim_locktable (new migration; separate app roles needGRANT UPDATE ON duron.claim_lock);shutdownTimeoutoption; gracefulstop()returns unfinished jobs to the queue instead of cancelling them (breaking); database-clockfinished_at; locked migrations; per-schema prune lock key; behaviour-neutral refactors; a parallel test runner (PostgreSQL suite ~6 min, PGlite ~2 min); tests grouped by feature; a "How it works" docs page. See PR #9 follow-ups: claim locking, release on stop, faster tests, refactors #10 for details.bun run test604 pass / 74 skip / 0 fail;POSTGRES_TEST=true bun run test1175 pass / 0 fail.Also included: docs audit and pre-existing bug fixes
mainwith what to change; every page and README was checked against the code; archive pruning (pruneArchive,getArchiveStats,truncateArchive, the/archiveendpoints) is documented.type: 'access');/refreshaccepts only refresh tokens. Before, a refresh token also worked as an access token.migrateOnStarttakes effect (before it was ignored); migrations run only when neither the Client nor the adapter disables them.duronschema; a custom schema is for apps that include Duron's tables in their own Drizzle schema (createSchema(name), their owndrizzle-kitmigrations,migrateOnStart: false). Before, that misconfiguration created a strayduronschema and failed withrelation does not exist.migrationsFolderis honoured. The Integrating docs are corrected.concurrencyoption is a real cross-worker cap (before it did nothing). New migration20261203025959adds a nullable column; no default, so nothing is capped unless you set it.getHTML()uses each call's options; React is an optional peer dependency; theenableLogindocs match its default (false).duron/clientexports the realTelemetryContexttype.Known limitations
Review
An independent review requested changes (claim conflicts, burst claiming, own stuck jobs, install docs). All required findings, most advisories and four pre-existing bugs it found are fixed in this PR. Refactors it suggested (shared column lists, splitting
base.ts, test consolidation, shorter user docs) are left for a follow-up PR.