Skip to content

PR #9 follow-ups: claim locking, release on stop, faster tests, refactors - #10

Merged
tinchoz49 merged 34 commits into
fix/postgres-reliabilityfrom
feat/review-followups
Dec 2, 2026
Merged

tinchoz49 merged 34 commits into
fix/postgres-reliabilityfrom
feat/review-followups

Conversation

@tinchoz49

@tinchoz49 tinchoz49 commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-ups and "Consider" items from the PR #9 reviews, stacked on #9 (base: fix/postgres-reliability). Retarget to main after #9 merges.

Every group was implemented on its own branch with tests that fail on the old code, reviewed independently (plus rechecks when fixes were needed) and gated with the full suites before merging here.

Final local checks: bun run test 615 pass / 80 skip / 0 fail (695 tests, PGlite), POSTGRES_TEST=true bun run test 1203 pass / 0 fail (PostgreSQL 19), typecheck, lint, format, duron/dashboard/docs builds.

⚠️ Breaking changes and upgrade notes

  • Graceful stop() returns unfinished jobs to the queue instead of cancelling them. Running handlers are still aborted; a handler that resolves still completes its job; an already-failed job stays failed; an explicit cancelJob still cancels. Completed steps are reused on the next run. A stopping worker keeps heartbeating while it drains, so peers do not start a job that is still running. Custom adapters without _releaseJob leave such jobs to recovery (with a warning).
  • New Client option shutdownTimeout (default 5000 ms) sets every stop budget (previously a fixed 5 s).
  • New migration 20261202120334: an empty claim_lock table. Apps that run Duron with a separate database role need GRANT UPDATE ON duron.claim_lock (see the adapters docs). Rolling upgrades with old and new workers are safe.
  • The prune lock key is derived from the schema name (hashtextextended('duron:prune:<schema>', 0)) instead of the constant 42.
  • migrate() runs in one READ COMMITTED transaction behind a schema-scoped advisory lock.
  • finished_at comes from the database clock.

What changed

Claim performance (F1)

  • Each claim locks only the jobs it takes (rank first, then LIMIT … FOR UPDATE SKIP LOCKED), instead of locking the whole eligible backlog. With a 50k backlog, one claim drops from 140–173 ms and 2.8 MB WAL to 17–57 ms and ~15 KB.
  • Claims across workers take turns on the claim_lock table, locked before the claim's snapshot. lock_timeout 1s turns a blocked claim into an empty one, and idle_in_transaction_session_timeout 5s stops a stalled holder from blocking the fleet. 4-worker bursts: 0 serialization conflicts, 0 errors. The redundant follow-up after a short claim is removed.

Shutdown (F2): shutdownTimeout, release on stop (above). Tests use short budgets.

Older behaviours (F3)

  • Database-clock finished_at, locked migrations (also with a stricter default isolation), a per-schema prune key.
  • getTracer(name) honours the name.
  • Lower operator timeout settings are respected.
  • A protected _heldJobIds(options) lets custom adapters see the held jobs.
  • The driver end timeout leaves a margin inside the shutdown budget.

Refactors (F4, behaviour-neutral)

  • Shared JOB_COLUMNS / STEP_COLUMNS, checked against the schema by a test.
  • #op helpers for the repeated start/lifecycle checks.
  • PruneScheduler moved to its own module.
  • A protected _transaction() helper replaces the monkey-patched db.transaction.
  • A prune-lock phase enum.
  • StopGateError (with a Symbol.for brand) replaces matching on message strings.

Faster tests

  • bun run test runs test files in 5 processes, with the timing-sensitive files run serially.
  • Native test databases come from a migrated template; PGlite starts from a migrated snapshot.
  • A per-file timeout names a hung file.
  • PostgreSQL suite: ~12–14.5 min → ~5.5–6 min. PGlite suite: ~5.5–6 min → ~2 min.

Tests and docs (F5)

  • 76 test files → 35, grouped by feature, with the same tests and assertions (name lists identical; a token-level diff shows only renames).
  • test/docker.ts waits with pg_isready.
  • A new How it works docs page holds the guarantees catalogue. The option docs are now short summaries with links.

CI: the test workflow also runs for pull requests into any branch, so stacked PRs get CI.

Notes

  • Under parallel load, one test exposed a heartbeat timeout that was too tight (300 ms). A heartbeat write on the loaded database took up to 2.3 s, so the peer legitimately recovered the job, which is the designed liveness contract. The test now uses 1 s and still fails if heartbeats stop during the drain.
  • During stop, the steps that the abort ended are written in the same transaction as completeJob/failJob, so a failed final write leaves them untouched and the released job's next run succeeds. Custom adapters keep the old (non-atomic) path unless they opt in via _finishesStepsWithJob (see the adapters docs).
  • Stop-gate refusals log as a plain Error again (pino type: 'Error'), as before the refactor.
  • recover.test.ts cleans up its temporary worker scripts and processes.

… 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.
…ck (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).
… (follow-up F1)

Rank-then-lock claim: candidates per group are chosen without locks, then only the
claimed rows are locked (no head-of-line blocking). Claims serialize on a new empty
claim_lock table (migration 20261202120334) taken before the claim snapshot, with
SET LOCAL lock_timeout 1s (55P03 -> empty claim) and idle_in_transaction_session_timeout
5s (a stalled holder cannot block the fleet). SERIALIZABLE + 40001 retry kept; the
short-claim follow-up is removed. 50k backlog claim: 140-173 ms / 2.8 MB WAL ->
17-57 ms / ~15 KB; 4-worker bursts: 0 conflicts, 0 errors. Docs: GRANT for app roles,
claim ceiling, rolling upgrade. Gates root/PostgreSQL 19 pass; review + recheck APPROVE.
… 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.
…e (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).
…eases unfinished jobs (follow-up F2)

BREAKING: graceful stop() returns unfinished running jobs to the queue instead of
cancelling them (handlers are aborted; a handler that resolves still completes; an
already-failed job stays failed; explicit cancelJob still cancels). Steps are kept
(completed outputs reused on the next run). Heartbeats continue during the drain so
peers do not recover still-running jobs; a release waits for step callbacks.
New Client option shutdownTimeout (default 5000 ms) sets every stop budget; tests use
short budgets (budget-bound files 355 s -> 155 s native). Custom adapters without
_releaseJob leave jobs to recovery. Gates root 597/79/0, PostgreSQL 19 1171/0;
review + recheck APPROVE.
…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.
… 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.
…rom 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`.
…d migrations, per-schema prune key (follow-up F3)

- finished_at / job_finished_at use the database clock (now()).
- migrate() runs in one READ COMMITTED transaction after a schema-scoped advisory
  lock, so concurrent cold starts no longer race on DDL (also with a stricter default
  isolation).
- The prune lock key is derived from the schema (hashtextextended), not constant 42;
  rolling-upgrade note in adapters.mdx.
- getTracer(name) honours the name; claim lock/idle timeouts keep a lower operator
  setting; protected Adapter._heldJobIds(options) for custom adapters; driver end
  timeout leaves a margin inside the shutdown budget.
Gates (3417ab4): root 600/80/0, PostgreSQL 19 1180/0, builds pass; fix 490c9f5:
static checks + affected tests (PGlite + native). Review APPROVE after the fix
(reviewer-verified approach).
…tale 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.
migrate() now runs in a READ COMMITTED transaction (F3), so statements traced
from start() include its SET TRANSACTION; the drain-boundary test counted it.
'bun run test' runs test files in 5 processes (timing-sensitive files serially),
native test databases are created from a migrated template (CREATE DATABASE ...
TEMPLATE) and PGlite starts from a migrated snapshot. Per-file timeout and stale
template cleanup. CI uses the runner; plain 'bun test' still works.
PostgreSQL suite 721-876 s -> ~350 s, PGlite 325-373 s -> ~110-125 s; same test
counts; 0 failures in 6 proof runs. Gates (runner): root 601/80/0, PostgreSQL 19
1182/0 in 8 min total; review APPROVE after the serial-lane fix.
…top 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.
…cross 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).
…ain 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].
…up F4)

Shared JOB_COLUMNS/STEP_COLUMNS for archive/recovery/time-travel copies (checked
against the schema by a test); #op helpers for the repeated start/lifecycle checks
(27 adapter, 18 client methods); PruneScheduler in its own module; a protected
_transaction() helper replaces the monkey-patched db.transaction; prune-lock phase
enum; StopGateError (Symbol.for brand) instead of matched message strings.
Gates: root 607/80/0, PostgreSQL 19 1188/0; review + recheck APPROVE.
… loaded database

Test-only: the multi-worker handoff test used heartbeatTimeout 300 ms; on a loaded
PostgreSQL a heartbeat write took up to 2.3 s, so the peer legitimately recovered the
job (designed liveness contract). heartbeatTimeout 1 s, drain starts at the abort;
still fails without heartbeats during the drain (3/3).
…s 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.
# Conflicts:
#	packages/duron/test/lifecycle.test.ts
#	packages/duron/test/prune-pglite-faults.test.ts
…it works' docs page (follow-up F5)

Test files 76 -> 35, grouped by feature with the same tests and assertions (name
lists identical; token-level diff shows only renames); serial lane and AGENTS.md
updated; test/docker.ts waits with pg_isready instead of a rotating log line.
Docs: a new 'How it works' page holds the guarantee catalogue (discovery, recovery,
wait reads, hints, shutdown, retention); option docs are short summaries with links.
Gates: root 607/80/0 (687 tests), PostgreSQL 19 1188/0; review APPROVE.
… 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.
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.
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.
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",...}}
…steps; JSDoc placement (leftovers review A1, A3)
…ogs for stop gates, test temp cleanup

- During stop, the skipped step results (cancelled/failed) are written in the same
  transaction as completeJob/failJob, so a failed final write leaves the steps
  untouched and the released job's next run succeeds (removes the documented
  double-fault limit). Custom adapters keep the old non-atomic path unless they opt in
  with _finishesStepsWithJob.
- Stop-gate refusals log as a plain Error again (pino type 'Error'); detection by brand,
  instanceof still works across copies.
- recover.test.ts removes its worker scripts and kills its workers on every path.
Gates: root 615/80/0 (695 tests), PostgreSQL 19 1203/0; review APPROVE (A1/A3 docs follow-up).
@tinchoz49
tinchoz49 merged commit 4021c43 into fix/postgres-reliability Dec 2, 2026
3 checks passed
tinchoz49 added a commit that referenced this pull request Dec 3, 2026
…ry (#9)

* Isolate time-travel ancestor traversal and reset by job

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.

* Apply step updatedAfter to both search branches

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.

* Fix global job listing order and pagination

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.

* Preserve elapsed retained-step timestamps across DST

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.

* Share lifecycle cleanup and use SQL heartbeat time

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.

* Make SQL notification emission safe and non-destructive

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 d51b0777a22fde298d54c37189331de3a6c9daec. Node runtime remains untested under the approved source/build compatibility gate.

* Coordinate scheduled archive pruning on an owned session

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.

* fix: reconcile pending waits with bounded read deadlines

* fix: claim jobs in SERIALIZABLE transactions published only after commit

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.

* test: retain owned claim test databases when cleanup preconditions fail

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.

* test: release claim test gates before awaiting owned work

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.

* fix: lock the job row in cancel/complete/fail and step creation

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).

* test: report session identities when prune transport count differs

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.

* test(postgres): bound and report native wait fixture cleanup

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.

* chore(postgres): test against postgres.js 4.1.1

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.

* fix(postgres): wait for driver stats to drain after a timed-out end

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.

* fix(postgres): lock recovery jobs before reading their steps

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.

* docs: describe recovery's per-phase step membership guarantee

Replace the unfixed recovery residual note with the implemented
lock-then-modify guarantee and its limits (effective READ COMMITTED,
built-in writers only, membership not version fidelity, no fencing,
BEGIN-time reference per phase, rollback on stop between statements).

* test(postgres): keep recovery snapshot test output quiet

Print the [KR] evidence rows only with KR_EVIDENCE=1, silence driver
notices on the test's own sessions, and release barrier advisory keys
only while held. No assertion or behaviour change.

* fix(duron): coordinate worker discovery and monotonic recovery

One Client-local discovery coordinator serves the startup pass, periodic
safety (pullInterval, all enabled modes), availability hints and manual
fetch calls: one chain at a time, one coalesced automatic request, FIFO
among eligible requests.

- Automatic claims stay within a Client-wide ceiling of B outstanding
  local claims (claimed, queued, running, finalizing incl. a lingering
  timed-out handler, unknown-action failure writes, reservations).
  Manual batches keep their own size/results and may exceed B.
- Due periodic recovery pauses all new claims until local work settles;
  its interval uses floor(performance.now()), anchored at startup
  recovery success and each attempt's settlement, strict >.
- Any chain failure logs once (background) or rejects (manual) and
  applies one pullInterval cooldown to every trigger; automatic demand
  is retried as a fresh claim, never replayed.
- Stop rejects queued calls, clears demand, issues no new claim after
  the gate and starts no handler for late results.
- Automatic discovery calls Adapter fetch/recoverJobs directly instead
  of the public Client.fetch.

Docs: multi-worker and client-api describe the batchSize ceiling vs
actionConcurrencyLimit vs SQL group admission vs direct Adapter calls.

Ticket: postgres-implementation 10-worker-reconciliation

* docs: warn against awaiting client.fetch() inside a job handler

While periodic recovery is due, fetch() waits for this Client's running
jobs, including the calling handler, so it can wait until stop rejects it.
Documentation only; no behavior change.

* fix(duron): suppress locally claimed jobs cancelled before their handler starts

Cover the claim-reply-pending and queued/deferred windows of this Client's own
claims. Each admitted non-running cancelJob call registers an intent
synchronously, reseeds it with every issued fetch and issues its own
Adapter.cancelJob; dispatch only suppresses. A suppressed claim keeps its one
ledger unit until the overlapping writes settle. Return values, per-call errors,
remote continuation and waitForJob semantics are unchanged; cancellation never
waits for worker discovery or recovery.

* test(duron): release every local-cancellation test hold on close

Register claim-reply, fetch, recovery and cancel-write holds per adapter and
release them before stopping the Client, and bound single held-event awaits.
Replace Promise.withResolvers in the internal registry with a local deferred
(Node.js < 22), log queued-window suppression at debug level, document the
one-entry-per-job assumption and restore the remote-cancellation consequence
in the docs.

* test(duron): wait for intents to drain after in-flight automatic fetches

In pull-mode local-cancellation tests a periodic fetch issued while a write was
pending legitimately joins the intent and can still be in flight; assert that the
intent drains within the bounded observation instead of an instantaneous check.

* test: add cross-mechanism acceptance and finish residual docs (ticket 11)

- cross-mechanism.test.ts: wait reconciliation while a due recovery barrier
  blocks discovery; job completion and waits with every notification
  dropped (one Client and producer/worker Clients); stop with a running
  handler, an in-flight wait read and a held prune pass inside the phase
  budgets. Acceptance tests of merged behavior, each shown able to fail
  under a temporary control mutation.
- client.test.ts: the two Concurrency Limits tests drop their own database
  after a successful stop (no more auxiliary leftovers per run).
- notifications/claim-isolation: cleanup failures no longer replace the
  test body's failure; checks and swallowing unchanged.
- docker.ts: one database name per provisioning call, so a retried
  partial provisioning cannot orphan an unnamed database.
- Docs: CONTEXT statuses/archive/group key/concurrency/advisory lock/
  recovery; group limits are per action name and group key; driver
  limitation now tested with postgres.js 4.1.1 (3.x keeps F1/F2).

* docs: correct F2 session lifetime and group-limit JSDoc (ticket 11 review)

- multi-worker.mdx: a leaked idle session on postgres.js 3.x lasts until the
  driver's max_lifetime (random 30-60 min by default) or process exit.
- client.ts groupConcurrencyLimit and action.ts groups.groupKey JSDoc: limits
  apply per action name and group key.

* fix: recover without pausing claims; own id only on first recovery

Postgres/PGLite recovery includes the adapter's own id only until one
recovery succeeds after start, so later recoveries never requeue this
worker's running jobs. Worker discovery no longer waits for local work to
settle before a due recovery: the recovery runs in the next chain and that
chain claims as usual (nothing when the automatic ceiling is full).

Docs drop the recovery barrier and the fetch-in-handler warning and
describe the startup-only own-id rescue and its trade-off.

* fix: claim nothing until a recovery has succeeded once

While periodic recovery is enabled, worker discovery treats recovery as
due in every chain until one recovery (startup or periodic) succeeds. A
failed recovery still skips that chain's claim and applies the cooldown,
so no job is claimed while the adapter still includes its own id and a
live job is never requeued. Normal cadence applies after the first
success; recoverJobsInterval 0 is unchanged.

* docs: qualify the own-jobs recovery guarantee for direct recoverJobs calls

The guarantee covers Duron's startup and periodic recovery. With
recoverJobsOnStart false and recoverJobsInterval 0 no recovery runs, own
leftovers are not rescued automatically, and the first successful direct
database.recoverJobs() call still includes the own id and can requeue
running jobs. A direct call overlapping the first recovery can requeue a
fresh claim. Docs and JSDoc only.

* chore: bump drizzle-orm and drizzle-kit to 1.0.0-rc.6; type JSON params as text

rc.6 no longer sets the transparent json (114) and jsonb (3802) serializers on
the postgres-js client (rc.4 postgres-js/driver.js:29-30). postgres.js then
applies its own JSON.stringify serializer (postgres src/types.js:24,251-252)
to a string parameter that the server types as jsonb. The value is stored as
a JSON string.

Cast the JSON.stringify parameters to text before jsonb. This does not depend
on the driver: rc.4 and rc.6, postgres.js 3 and 4, and PGlite.
- _delayJobStep: the error entry in history_failed_attempts
- #buildJsonbWhereConditions: the array containment filter (@>) for non-string values
- adapter.test.ts: 3 listing seed fixtures

Red -> green (native PostgreSQL, Bun 1.4.6-canary.1):
- red before the fix: adapter "should delay a job step" (ZodError: the error is
  a string), "global page payload", "listing filters" active/archive;
  create-step "should retry step definition before failing action"
- red after only the fixture fix: listing filters active/archive (the @> filter matched nothing)
- green: typecheck, lint, fmt, build; root 520 pass/75 skip/0 fail;
  native per-file 59/59 files; native full 1000 pass/0 fail

* chore: upgrade drizzle-kit snapshot to format 10

drizzle-kit 1.0.0-rc.6 refuses to generate from a format 8 snapshot ("run
drizzle-kit up"). Ran drizzle-kit up and formatted the file with oxfmt.
generate:postgres now reports "No schema changes". The runtime migrator reads
only migration.sql, so this file does not affect migrations at runtime.

* docs: install drizzle-orm@rc and state tested versions and Node floor

* chore: upgrade PGlite to 0.5.17 (PostgreSQL 18.7)

PGlite 0.5.16 fixed its identifier helper to escape double quotes, so the notifications
control that expected the old 42601 failure now records the fixed behaviour; Duron's
own channel quoting assertions are unchanged.

* docs: pin PGlite 0.5 in install instructions

* chore(deps): remove unused deps, add duron peer deps, apply in-range updates

- Remove unused: dashboard jsonata, radix-ui, elysia (dev); docs
  @tanstack/react-router-devtools, tailwind-merge; duron @opentelemetry/core
  (dev); examples zod; shared-actions @types/bun (dev).
- duron: move p-retry to devDependencies (src vendors src/utils/p-retry.ts).
- duron: declare peerDependencies drizzle-orm "1.0.0-rc.6 || ^1.0.0",
  postgres ^4.1.1 (optional), @electric-sql/pglite ^0.5.17 (optional).
  A ">=1.0.0-rc.6" bound would also match drizzle's hash-suffixed
  1.0.0-rc.<n>-<sha> snapshots under semver precedence.
- Apply in-range updates across workspaces (postgres 4.2.0, zod 4.6, OTel
  2.12/api 1.10, react 19.3, radix, oxlint 1.95, ...). TanStack Start/Router
  in docs stay on the current lock: Start 1.169+ requires Vite 8.
- Tests: postgres 4.2 types reserve() as Leasing<ReservedSql>; prune test
  stubs assign through a Promise-returning view.
- Docs: tested with postgres 4.2.0.

* fix(deps): keep @opentelemetry/api below 1.10, update multi-worker driver note

- duron and shared-actions declare @opentelemetry/api ">=1.9.0 <1.10.0"
  and lock 1.9.1. OTel SDK 2.x peers api <1.10.0; with ^1.10.0, npm
  installs a second api copy and duron's context.with() no longer makes
  job/step spans active once the app registers the SDK.
- multi-worker.mdx: tested with postgres.js 4.2.0, supports 4.1.1 or
  later; the 3.4.9 failure reproductions were checked on 4.1.1.

* chore(fmt): upgrade oxfmt to 0.80, rename experimentalSortImports to sortImports

oxfmt 0.80's configuration schema only documents sortImports. The old key is
still accepted as an alias (verified: same import order with either key).

* style: reformat with oxfmt 0.80

Formatting only, generated by `bun run fmt`. Sort-imports now breaks ties for one
source by subgroup (value import before type import). Markdown and TS layout
changes come from the newer formatter.

* chore(ts): TypeScript 7 in docs and shared-actions, @types/node 26

- docs devDependency typescript ^5.9.3 -> ^7.0.2; shared-actions peer ^5 -> ^7,
  matching root, duron, dashboard and examples.
- @types/node ^24 -> ^26.6.11 in docs and duron.
- TS 7 removed baseUrl: drop it from the docs and shared-actions tsconfigs.
  All paths entries are now relative (fumadocs-mdx:collections -> ./.source/*).
  No import resolved through baseUrl.

* chore(ts): type check with bun check instead of tsc --noEmit

- duron and duron-dashboard: "typecheck": "bun check --no-script" (the script
  name stays the same, so CI and AGENTS.md still run bun run typecheck). docs
  types:check: fumadocs-mdx && bun check --no-script.
- --no-script makes bun check always run the checker. Without it, a future
  "check" script would run instead, and could recurse into typecheck.
- tsc still emits duron's dist (build/dev).
- Parity: on scratch copies with injected errors (TS2322, TS4111, TS2532,
  TS2554, TS2307, a JSX prop error, and an error in a file imported from
  another package), tsc 7.0.2 and bun check report identical lines. They also
  match on examples' existing error, and clean runs pass under both. The stable
  Bun 1.4.5 used by CI includes bun check.

* build(duron): clean dist before building, stop publishing drizzle.config

- build: rm -rf dist && tsc. prepublishOnly runs build, so a publish no longer
  ships stale files from earlier builds (e.g. the old dist/src/**).
- Move drizzle.config.ts from src/adapters/postgres/ to the package root. It
  is the drizzle-kit dev config for generate:postgres. In src/ it was compiled
  to dist/adapters/postgres/drizzle.config.js (importing drizzle-kit) and
  published in both dist/ and src/, but no export reaches it. tsconfig.json
  includes it explicitly so it is still type checked.
- Pack dry-run: 109 files, no drizzle.config; dist has no drizzle-kit import.

* fix(lint): resolve the 12 oxlint 1.95 warnings

- errors.ts (unicorn/no-useless-error-capture-stack-trace): drop
  Error.captureStackTrace(this, this.constructor) from DuronError. Error
  subclass stacks already start at the caller: V8 skips frames up to
  new.target, and a Bun check shows the same first frames and name header
  with and without the call, for a subclass and a sub-subclass.
- dashboard step-list.tsx (import/no-named-as-default): import { clsx },
  as src/lib/utils.ts does.
- tests (unicorn/consistent-function-scoping, 10): hoist each function one
  scope up, to where the variables it uses live. endedEarly (3 copies) leaves
  the db.transaction replacement; run leaves the action handler; withAdapter
  (2), withStore and claimAs move out of their describe callbacks;
  createListingJobs and seedListingJob move above describe('Query Methods')
  with their comments. Code moves only, no logic changes.

* chore(dashboard): upgrade lucide-react 1, motion 14, nanoid 6, react-day-picker 10, maskito 5, TanStack Table 9

- TanStack Table 8 -> 9: useReactTable -> useTable with an explicit
  features object (lib/data-table-features.ts). It registers the features
  the data tables use: filtering, faceting, sorting, pagination, selection,
  visibility, ordering, pinning, sizing and resizing. It also registers the
  row models v8 always ran (bypassed by manual pagination, sorting and
  filtering) and the built-in filter functions that 'auto' resolves to;
  setColumnFilters uses their autoRemove hooks, as in v8.
  Other changes:
  - TFeatures is the first type argument everywhere, and TData extends RowData.
  - TableMeta/ColumnMeta augmentations take the v9 type parameters.
  - table.getState() -> table.store.state.
  - Column pinning left/right -> start/end, and columnPinning now sets both keys.
  - VisibilityState -> ColumnVisibilityState.
- react-day-picker 10 removed the deprecated `table` classNames key, so
  ui/calendar.tsx uses month_grid. This is the one forced edit to a shadcn
  file, and it matches the current shadcn registry calendar line for line.
- lucide-react 1, motion 14, nanoid 6, maskito 5: no code changes.
  lucide 1 redraws some icons (GitBranch, Calendar, CircleCheck).

* chore(docs): vite 8, TanStack Start 1.170, fumadocs 16.19/mdx 15, lucide-static 1

- vite 7 -> 8, @vitejs/plugin-react 5 -> 6, TanStack Start/Router/
  static-server-functions 1.168/1.170.18/1.167.19 -> 1.170.0/1.170.46/
  1.167.44 (Start >= 1.169 requires Vite 8), fumadocs-core/ui 16.2.0/16.1.0
  -> 16.19.8 (exact; ui pins core exactly), fumadocs-mdx 14.0.3 -> 15.6.4,
  lucide-static 0.552 -> 1.84 (all 13 frontmatter icons still resolve).
- vite-tsconfig-paths removed: Vite 8 resolves tsconfig paths natively
  (resolve.tsconfigPaths) and warns when the plugin is present.
- vite.config: import.meta.dirname and an explicit ./source.config.ts
  extension (Vite 8 native config loader warnings); tsconfig enables
  allowImportingTsExtensions for that import (noEmit).
- Start 1.169 removed createServerFn().inputValidator(): use .validator().
- fumadocs-mdx 15: createClientLoader<object> so <Content /> type-checks;
  page tree cast to PageTree.Root.
- fumadocs-core 16.14 moved built-in search from Orama to ZBSearch and
  16.17 deprecated useDocsSearch: the dialog uses useStaticSearch() and
  @orama/orama is no longer a dependency.
- fumadocs-ui HomeLayout's root now contains the navbar, so the home
  page centers its content in a flex-1 wrapper (as the upstream template
  does). Styling HomeLayout itself centered the navbar into the page.

* fix(examples): pass variables in server example; typecheck examples and shared-actions

- examples/server/start.ts registered sendEmail without the variables it
  was defined with. Its handler calls ctx.var.sendEmail, so the example
  failed at runtime. tsc caught it as TS2322 (server/start.ts:13), but
  nothing type-checked the examples. Pass `variables` like the other
  examples.
- examples and shared-actions get "typecheck": "bun check --no-script",
  so root `bun run typecheck` (and CI) now cover them.

* chore(shared-actions): AI SDK 7 (ai 7, @ai-sdk/openai 4, @ai-sdk/otel)

- ai 6 -> 7 and @ai-sdk/openai 3 -> 4. AI SDK 7 moved OpenTelemetry into
  @ai-sdk/otel and removed experimental_telemetry.tracer. The weather
  action now passes a per-call integration with the Duron step tracer
  (telemetry.integrations: [new OpenTelemetry({ tracer })]), so its AI spans
  stay under the step span. Checked with a mock model: invoke_agent, chat
  and step spans are children of step:<name>, in the job's single trace.
- @ai-sdk/otel depends on @opentelemetry/api 1.9.1, which is the locked
  version; there is still a single api copy.
- docs/telemetry.mdx: same pattern in the external library example.

* perf(listing): index-friendly getJobs sort keys and per-table sort indexes

Sorting the job list by status/actionName (~2.8 s) or description (~5.2 s) at
200k jobs was slow. Text keys were decoded row by row into UTF-16 code units, and
timestamps were wrapped in date_trunc('milliseconds'). Both prevented index use.

- Sort keys are now the stored columns:
  - timestamps (createdAt/startedAt/finishedAt/expiresAt) sort by stored precision;
  - status/actionName/description sort by `column COLLATE "C"`, which is byte order
    (Unicode code point order), independent of the database locale;
  - duration keeps its Number-precision key.
  NULLs stay last for asc and first for desc.
- The id tie-break follows the direction of the last sort key (ascending with no
  sort key). The order stays total and deterministic, and one (column, id) index
  serves both directions.
- Migration: (created_at, id), (started_at, id) and (status COLLATE "C", id) on
  jobs_active and jobs_archive. Verified with EXPLAIN on the SQL the adapter sends:
  Merge Append over Index Scan / Index Scan Backward for asc and desc, page 1 and
  page 200. idx_jobs_active_status stays: it is the default-collation index for
  status equality in claims, and the "C" index cannot serve it.
- Tests: the listing tests now assert the new contract (code point text order,
  stored timestamp precision, direction-following id ties). A new test checks page
  stability when equal sort values span pages. Native and PGLite.
- Docs: client-api and server-api describe the new order.

* docs(listing): migration locking and pre-build path; IF NOT EXISTS indexes

Review fixes for the job listing indexes (84befb0):
- migration.sql: CREATE INDEX IF NOT EXISTS for the six listing indexes (the
  drizzle snapshot is unchanged; drizzle-kit generate reports no changes). Operators
  can pre-build them with CREATE INDEX CONCURRENTLY and the migration builds nothing.
  Checked on an existing 205k-job install: the pre-built indexes keep their OID and
  relfilenode through the upgrade. On a fresh database the migration creates them
  with identical definitions.
- adapters.mdx (Migrations): Duron applies pending migrations in one transaction, so
  writes to jobs_active and jobs_archive are blocked until it commits, for a time
  that grows with table size. Documents the options (maintenance window or a single
  migrating instance) and the exact CONCURRENTLY statements, plus a validity check
  for failed concurrent builds.
- client-api/server-api: byte order is code point order in a UTF-8 database;
  only unfiltered createdAt/startedAt/status sorts are index-served.
- Page-stability test: seed in a non-monotonic order, so ascending also fails
  without the id tie-break (mutation-checked).

* chore(dashboard): remove unreachable code and its dependencies

An import graph from every dashboard entry point found 16 files that nothing
reaches. The entry points: the package exports' dev-source/types (index.tsx,
init.tsx, get-html.ts, types/*.d.ts), build.ts (index.tsx, init.tsx,
index.html), dev.tsx and css.d.ts. Removed files:
- data-table: action-bar, advanced-toolbar, filter-list, filter-menu,
  range-filter, skeleton, view-options
- ui (shadcn, unreachable): calendar, checkbox, faceted, skeleton, tabs
- hooks/use-copy-to-clipboard, lib/data-table, lib/id, views/job-io

Removed the dependencies only those files used: motion, nanoid,
react-day-picker, @radix-ui/react-checkbox. The date filter imported
react-day-picker only for the DateRange type; it now declares the same shape
locally.

The published dist JS is unchanged (the removed code was already tree-shaken).
The dist CSS shrinks (index.css 77.6 -> 66.7 KB, init.css 96.6 -> 86.4 KB),
and the package drops from 107 to 91 files.

* fix(docs): no React #418 when hydrating the home page shell

'/' is the SPA shell (spa.prerender.outputPath 'index.html'). Its route area
is an empty Suspense boundary. Since Start 1.168.36 / Router 1.170.19 the
client renders the index route on its first pass, without that boundary,
so hydration throws React #418 (upstream TanStack/router#8473, open).
Bisect: Start 1.168.31-1.168.35 are clean. Every version from 1.168.36 to
1.170.0 throws, on Vite 7 and on Vite 8, so no version pin fixes it.

The '/' route now sets wrapInSuspense and renders HomeLayout in
<ClientOnly>. The client's first pass then matches the shell. The content
renders after hydration, as in the 1.168.31 baseline. index.html is still
the shell and the SPA fallback, so the Cloudflare Pages deploy does not
change. Remove both when #8473 is fixed.

Pre-existing, also in the 1.168.31 baseline, not changed here:
- /no-such-page (SPA fallback to the shell) throws React #418.
- /docs/no-such-page logs "Unexpected token '<' ... is not valid JSON"
  because the docs server-fn fetch receives the HTML fallback.

* chore(dashboard): remove unused exports

knip, with the package entrypoints and public type files as entries, plus
a grep across packages/, found exports that no module imports.

- parsers: remove getFiltersStateParser and the filter item schema/type
  that only it used.
- types/data-table: remove FilterOperator, JoinOperator,
  DataTableRowAction and ExtendedColumnFilter. FilterVariant becomes
  module-local (ColumnMeta still uses it).
- compose-refs: composeRefs becomes module-local (used by
  useComposedRefs).
- badge-status: statusConfig and Status become module-local.

shadcn/diceui files in src/components/ui are unchanged: their unused
exports are upstream API, not our own additions.

* chore(dashboard): remove unread dataTableConfig keys

The only readers of dataTableConfig are data-table-sort-list
(dataTableConfig.sortOrders) and types/data-table
(DataTableConfig['filterVariants']). There is no indexed, dynamic or
spread access. Remove the per-type operator lists, operators and
joinOperators. Nothing read them after getFiltersStateParser was removed.

* chore(deps): oxlint 1.96, oxfmt 0.81, react-virtual 3.14.31, p-retry 9

- oxlint ^1.96.0, oxfmt ^0.81.0: lint and format are clean without
  changes.
- @tanstack/react-virtual ^3.14.31 (dashboard).
- p-retry ^9.0.0 (duron devDependency, used only by test/docker.ts).
  The breaking changes in 8.0 and 9.0 are the Node 22 requirement, the
  callback order, abort-signal semantics, shouldConsumeRetry defaults and
  option validation. docker.ts uses only retries/factor/min/maxTimeout,
  so no code change is needed.

* fix(time-travel): lossless archive restore keeps sub-millisecond step order

Time travel keeps a completed step only if it was created strictly
before the target (created_at < target.created_at). Restoring an
archived job went through a JS select/insert round trip, which cut
created_at, started_at and finished_at to milliseconds. On PostgreSQL,
two sequential sibling steps created in the same millisecond then tied,
and time travel deleted the completed earlier step: its output was lost
and its handler ran again.

Confirmed cause of the 'time travel to second child step' flake: equal
created_at at the strict comparison. Two sources: the lossy restore
(both engines) and PGLite's millisecond clock.

- Restore the archived job and its steps with INSERT ... SELECT in the
  time-travel transaction (ON CONFLICT DO NOTHING, per-job filters as
  before), so timestamps keep their microseconds.
- getJobSteps orders by created_at, then id, so tied steps come back in
  a stable order.
- New test (both engines): archived siblings created 800 microseconds
  apart; time travel to the second keeps the first. It fails on the old
  code: the first is deleted and the times are truncated.
- The elapsed-shift test pinned the lossy restore. It now expects
  lossless times from archive storage too (3600530865n, no date_trunc).
- PGLite's clock stays millisecond, so ties remain possible there by
  design. The time-travel test actions wait for the next millisecond
  after steps that tests expect to be kept, with a comment explaining
  why. The docs describe which steps are kept and the PGLite limitation.

* fix(postgres): archive the job row with SQL so stored values stay exact

complete/fail/cancel copied the job row to jobs_archive through JavaScript,
cutting timestamps (created_at, started_at, expires_at) to milliseconds and
rounding jsonb numbers. Copy it with INSERT ... SELECT in the same transaction,
after the unchanged job-row lock. Recover-expired archival was already SQL.

* fix(postgres): keep the driver JSON encoding for archived output and error

Bind the replacement output/error with the archive column so drizzle applies
the driver codec, as the former insert did. PGlite again stores a nested BigInt
as a string instead of failing the job, and custom postgres.js json serializers
apply. Tests pin the encoding on both engines and compare every copied column.

* fix(docs): show the not-found page for unknown paths

Unknown paths get the SPA shell from the host. A path no route matches threw
React #418 on hydration, and an unknown docs page failed parsing the HTML
fallback as the page's static loader data.

- Check the slug against a prerendered page list before loading a docs page.
- Render not-found pages client-only inside the shell's Suspense boundaries
  (TanStack/router#8473 workaround, as for the home page).
- Center the not-found content without moving the navbar.

* chore: test on PostgreSQL 19 and PGlite 0.6

- PGlite devDependency 0.6.1 (PostgreSQL 19); peer range ^0.5.17 || ^0.6.0,
  since PGlite 0.6 cannot open a data directory created by 0.5.
- Native tests default to postgres:19-alpine, overridable with
  DURON_TEST_POSTGRES_IMAGE. The container name includes the image, an existing
  container must run the selected image, and a taken port 5440 is reported
  instead of silently reaching another server. getPostgresConnection() takes
  no arguments.
- Dev docker-compose uses postgres:19-alpine.
- Docs: tested with PostgreSQL 16 and 19 and PGlite 0.6.1.

* feat(telemetry)!: depend only on @opentelemetry/api, take tracerProvider from the app

BREAKING CHANGE: telemetry.traceExporter, serviceName and batchDelayMs are
removed. Pass telemetry: { tracerProvider } created by the application.
Duron no longer creates a Resource or a tracer provider, and without the
telemetry option it does not use the global tracer provider.

- @opentelemetry/api is a peer dependency (^1.9.0); resources,
  sdk-trace-base, sdk-trace-node and semantic-conventions are removed
- tests use @opentelemetry/sdk-trace 3 + api 1.10 (dev only)
- docs: telemetry migration, client API, install, ADR 0002

* fix(telemetry): reject un-migrated telemetry config, propagate ids without SDK internals

- Client throws a TypeError naming telemetry.tracerProvider and the migration
  notes when telemetry is set without a valid tracerProvider or with a removed
  option (traceExporter, serviceName, batchDelayMs)
- duron.job.id / duron.step.id on handler spans come from StepManager state,
  not span.attributes, so any API-compliant provider works; startActiveSpan
  from getTracer() now carries them too
- tests: minimal API-only TracerProvider, validation cases, assert the global
  provider registration

* fix(test): run duron tests without --concurrent

'bun run test' used 'bun test --concurrent', which failed ~221 tests (shared native
resources and time-sensitive lifecycle budgets); CI already used plain 'bun test'.
'bun run test' now passes 546/75/0. AGENTS.md updated.

* fix: retry claim conflicts and keep draining job bursts

R1: a claim rejected with SQLSTATE 40001 (statement or COMMIT) is retried
up to 3 times, each in a new SERIALIZABLE transaction after a 1-20 ms random
delay. Retried conflicts are logged at debug level; only an exhausted retry
surfaces the original error (and only then does the WorkerDiscovery cooldown
apply). Claims still commit before they are returned, and a rolled-back
attempt publishes nothing.

R2: coalesced hints add one job each to the pending automatic request
(capped at B) instead of taking the maximum, and an automatic claim that
returns its full batch queues another automatic request of B, subject to
room, cooldown and due recovery. A Promise.all burst of 60 jobs (PGlite,
hybrid, pullInterval 5000, B 10) now completes in ~0.15 s instead of 29.7 s.

* fix: address G1 review (follow-up demand, stop gate, docs)

- Track automatic demand instead of a capped batch: one job per hint,
  unbounded for startup/periodic. A full claim is followed up only while
  demand remains (the rest of it), so one hint claiming one job no longer
  causes an empty follow-up claim, while B=1 bursts and room-limited claims
  still drain.
- Do not start a claim retry once the stop gate closed (checked before and
  after the delay): the original 40001 error propagates.
- batchSize JSDoc and client-api.mdx describe additive hint demand, the
  follow-up rule, cooldown/room waits and due recovery.
- Native natural-conflict test: repeat bounded rounds until a conflict was
  retried; allow an exhausted retry to surface only as 40001.

* fix: back off claim conflict retries exponentially

Retry a 40001 claim up to 5 times with exponential full-jitter backoff:
a random 1..min(160, 5 * 2^n) ms before retry n (at most 310 ms in total),
still checking the stop gate before and after each delay. Debug logs now
include the delay.

Measured with the native 4-claimer natural-conflict test (20 runs of 10
fixed rounds plus 20 runs of the test as committed, per version): the
previous policy (3 retries, 1-20 ms) surfaced exhausted retries in 6/20
(PG19) and 3/20 (PG16) heavy runs; this policy surfaced none in 40/40 runs
on each of PG19 and PG16. The slowest fetch that retried took 132 ms.

* fix: recover this worker's own abandoned jobs, never its held ones

R3: after the first successful recovery the adapter skipped its own client id
for good, so an own job that a rejected cancel write, or rejected final
completeJob/failJob writes, left active stayed active (and held a group slot)
until the process stopped.

- Recovery includes the adapter's own id again in every pass, except the job
  ids its Client holds locally, passed in the internal `heldJobIds` recovery
  option. The Client holds a job from dispatch until its actual local
  settlement (claimed, queued, running, finalizing, a lingering timed-out
  handler, a suppressed claim until its cancel writes settle). `null` skips
  the own id (used while a Client claim reply is pending, and by default for
  direct recoverJobs calls on an adapter a Client uses, which cannot see the
  held jobs). An adapter without a Client includes its own id.
- Worker discovery no longer gates claiming on a first successful recovery:
  that rule only protected claims from the own-id pass, which now skips held
  jobs. A failed recovery still skips that turn's claim and cools down.
- Docs/JSDoc (client.ts recoverJobsOnStart, recoverJobsInterval, cancelJob;
  client-api.mdx, multi-worker.mdx, adapters.mdx) describe the rescue.

* fix: one Client per adapter; address G2 review advisories

A4: Clients sharing one adapter share its client id (setId is last-write-
wins), liveness row and lifecycle: on 64a866c two Clients on one adapter
store each other's claims under the last id, and stopping one stops the
other. With own-id recovery each one's recovery would also requeue the
other's running jobs. The Client constructor now throws a TypeError when
another Client already uses the adapter (checked before any side effect;
a constructor that throws later does not bind the adapter). Tests that
built a second Client on a shared adapter now use their own adapter.

Advisories: remove stale own-id comments (A1), fix the no-new lint warning
(A2), document that jobs claimed by a direct client.database.fetch() are
not held and get requeued (A3) and that a running job whose cancellation
write rejects is requeued and runs again (A5), document one Client per
adapter, and widen the E5 recovery interval to 1500 ms (A6).

* fix: no Client constructor side effects before its fallible steps

R1: the constructor registered a quiesce hook (and, after an invalid logger
level, left it on the adapter's lifecycle) and bound the adapter before
creating the logger and the tracer. An invalid logger string then made a
later Client's stop() reject, and a throwing getTracer left the adapter
bound with the rejected id. All fallible steps (telemetry and option
checks, id, logger, tracer) now run before the first side effect.

Also: docs say an adapter whose Client stopped cannot be reused (A7); the
client.test.ts extra databases stop their adapter before the drop and all
drops run even if one fails (A8); client.test.ts runs PGlite always and
native PostgreSQL only with POSTGRES_TEST (A9).

* chore: native CI matrix, install docs and review nits (PR #9 review R4 + nits)

CI (.github/workflows/test.yml):
- Pin Bun 1.4.5 (first stable with `bun check`), `bun install --frozen-lockfile`,
  add a build step (tsc dist, dashboard, docs).
- New `native` job: POSTGRES_TEST=true bun test on postgres:16-alpine and
  postgres:19-alpine (DURON_TEST_POSTGRES_IMAGE), provisioned by test/docker.ts on
  the runner's Docker; covers client.test.ts's PostgreSQL path.

R4: install docs pin drizzle-orm@1.0.0-rc.6 (the peer range does not accept later
RCs). package.json engines: node ^20.19.0 || >=22.12.0. PGlite 0.5.17 suite run
manually (documented).

Nits:
- getJobs: an empty sort array uses the default sort (startedAt desc).
- Liveness-table absence before migration: SQLSTATE 42P01 plus a to_regclass
  probe instead of the locale-dependent message text.
- Remove the redundant length check in _recoverJobs.
- Client.fetch rejects when start() resolved false instead of hanging.
- waitForJob docs: pending waits resolve null on stop, calls after stop reject.
- Report quiesce hook failures once, in the stop attempt that observed them.

G1 recheck advisories:
- A5: stop wakes pending claim-retry delays at once.
- A6: a claim failure surfaced by a normal stop is logged at debug level
  (Adapter.fetch and WorkerDiscovery), not as two errors.
- A7: the natural-conflict test allows up to 100 rounds; docs say the 310 ms
  bound counts only the waits.

* fix: CI build on a clean checkout; narrower shutdown log demotion (G3 review)

R1: duron-dashboard's build:get-html (tsconfig.node.json types: ["node"]) needs
@types/node, which resolved only from a node_modules directory outside the repo.
Add it as a dashboard devDependency (bun.lock: one line). Verified from a git
archive in /tmp with Bun 1.4.5: frozen install, typecheck, lint, fmt:check,
build and bun test pass; the archive of b5390b4 fails with TS2688.

A1: after stop began, only failures that stopping causes (stop-gate refusals,
a claim 40001 no longer retried) are logged at debug; other claim errors stay
at error level (new internal isStopFailure).
A2: a failing to_regclass probe is logged and the original 42P01 is rethrown.
A3: Client.fetch racing stop rejects with the stop-gate refusal.

* fix: pre-existing bugs from the PR #9 review (time travel, prune lock, wait reads, stop in handler)

1. Time travel returning false no longer strands the job: the restore from the
   archive rolls back with the failed validation (private sentinel thrown inside
   the transaction), and the archived row is locked FOR UPDATE first so a
   concurrent prune cannot split the job and step copies. Pinned tests updated;
   the elapsed-shift "active" fixture seeds the legacy stranded state with SQL.
2. A lost prune-lock session no longer disables scheduled pruning until restart:
   the timer keeps ticking while retired (each skipped tick logs a warning), and
   once the old isolated client is confirmed closed and no pass runs, the next
   tick builds a new lock client. Only the loss of an established session
   qualifies; bootstrap failures, uncertain/malformed results, false unlock and
   PGLite stay retired. Key 42 keeps one owner (the server released the old lock).
3. runActionAndWait: an initial wait read that expires rejects with
   WaitReadTimeoutError, one that fails with WaitReadFailedError (cause = read
   error), instead of "Job not found". Both exported. waitForJob still resolves null.
4. await client.stop() inside a handler or step no longer deadlocks: the drain
   stops waiting for the caller's own user-code runs (handler/step callbacks, also
   when another stop is already in progress); the calling job is still aborted and
   writes its cancellation, and liveness is released.

G3 recheck N2: the probe-failure log carries originalCode/originalMessage.

* fix: G4 review (stop ordering test, replaced prune locks released, retries, docs)

R1: stop-in-handler tests a stop begun from outside any handler context first,
then a handler that awaits stop(); both the Client-branch exclusion and the
drain wake signal are needed (each mutation fails it).
R2: a re-established prune lock releases the replaced one: Lifecycle.dispose()
forgets its discharged obligations, the replaced postgres.js client is ended and
dropped, and coordination errors are trimmed after each pass and on
re-establishment. A native test does 4 re-establishments and asserts obligations,
open clients and retained errors do not grow.
A1: native test pins the archive FOR UPDATE (a time travel racing an uncommitted
prune waits and restores nothing; without the lock it resurrects the job).
A2: a replacement lock whose bootstrap fails retries on later ticks with a
doubling backoff (interval .. 5 min); it never held key 42.
A3: a lost established session (onclose, or a connection-loss error of its
statements) is logged as a warning; real faults stay errors.
A4: docs: stop() follows the handler's async context (timers, fire-and-forget).
A5: renamed the false-time-travel listing test; new seeded legacy listing test.
A6: runActionAndWait rejects with "Lifecycle is not accepting work" when the
Client stops during the wait.

* test: count only client backends in native session assertions

The gate failure of prune-transport 'post-boundary idle loss' (1 session left
after adapter.stop()) was not a leaked connection: a self-attributing rerun
caught it as backend_type 'autovacuum worker' (application_name '', started
24 ms after stop began). Autovacuum workers carry the database's datname in
pg_stat_activity, so every "sessions of this test database" count could see
one. Native session assertions now add backend_type = 'client backend'; the
prune-transport post-stop check reports pid/backend_type/application_name/
backend_start/state and the sessions seen before stop.

* fix: aborted steps settle before their job; CI-only test timing assumptions

Real bugs (red-first: test/step-abort-settlement.test.ts, deterministic with a
held step failure write, PGlite + PostgreSQL):
- StepManager.drain() called fastq's `drain` hook (a no-op) instead of
  `drained()`, so a failing job did not wait for its running steps: a slow
  step failure write lost the race with failJob and the step was archived
  'active' under the failed job. ActionManager.drain() had the same mistake.
- A step's abort race used waitForAbort's promise with only a fulfilment
  handler; it rejects on abort, so a parent step that timed out rethrew at
  once without waiting for its children (the abort branch was dead code).
These caused CI's nested-steps 'should abort child steps when parent times
out' failure (child archived 'active'; reproduced locally under CPU load).

Test assumptions:
- time-travel 'keep parallel sibling': branch-b failed while branch-a might
  not even be created yet (the failure aborts running siblings); branch-b now
  fails only after branch-a completed.
- wait-read-errors and other new PGlite tests had no explicit timeout: Bun
  ignores bunfig [test] timeout (oven-sh/bun#7789), so the default is 5 s,
  and the first PGlite start in a file takes 6-13 s on a slow CPU. They now
  pass 20 s; the misleading bunfig line is replaced by a comment.

* chore(test): pass --timeout 10000 explicitly to bun test (bunfig timeout is ignored)

Bun ignores [test] timeout in bunfig.toml (oven-sh/bun#7789). The duron test
script and both CI bun test steps now pass --timeout 10000; the bunfig comment
and AGENTS.md say so. A 6 s probe test fails without the flag (5000 ms) and
passes with it and via 'bun run test'.

* fix: an aborted parent step waits only for started children (G5 review)

R1/A2: with a low steps.concurrency a parent holds the slot its queued child
needs, so waiting for every child deadlocked: the job stayed active and stop()
failed after its drain budget. The parent now waits only for children whose
queue worker started (TaskStep.onStart, called by the fastq worker); a child
that starts after the abort throws before creating its row. Applied to the
timeout/abort, callback-error and unhandled-children paths, each with a
concurrency-1 regression test (job fails, no child row, stop() < 2 s).
A1: the settlement test's parent expire is 2 s, so the child's row exists first.
A3: remove ActionManager.drain(), which had no callers.

* fix: prune-lock replacement edge cases (G4 recheck N1-N4)

- N1: a replacement lock's bootstrap failure is classified. Connection and
  server startup faults retry with backoff as warnings; other faults (28P01,
  configuration) retry with backoff but log an error on every attempt;
  malformed or changed backend identity retires as on the first lock.
  Replacement faults are no longer reported as "session lost".
- N2: when the bootstrap session closes while reserve() is pending, the
  replacement is retried as a connection fault. The new reservation is given
  back to the ending client so the fault close confirms it closed promptly.
- N3: the established-session loss set drops CONNECTION_DESTROYED,
  CONNECTION_ENDED (own end()) and 57P03; adds ETIMEDOUT and 57P05.
- N4: the backoff counts from the failure, and the tick nearest the due time
  retries, so an early tick does not add an interval.
- Hooks: _pruneLockReplacement() replaces _canReplacePruneLock() and
  _pruneLockBootstrapFailed(); the tick is _pruneTick() with an injectable
  clock for tests.

* fix: prune replacement review (R1, A1, A2, A4)

- R1: during a stop, a replacement fault (also our own CONNECTION_DESTROYED)
  is not logged as a replaceable retirement; the pass reports it as an error.
- A1: an acquisition that resolves false after its lock retired (N2) keeps the
  backoff counter, so repeated N2 faults back off.
- A2: drop the #physicallyClosed reset in the N2 abandon path: postgres.js 4
  end() resolves only with no connection left, and close() awaits it first.
- A4: the N4 test pins the lower bound of the early-tick tolerance.

* test: prune backoff probes only after the due time is recorded (R2); docs wording (A5)

* test(worker-discovery): seed direct-claim fixtures before the Client starts

Two push-worker tests started the Client, created a job with runAction and
then claimed it with a direct adapter.fetch. On a slow runner the Client's
own periodic discovery (pullInterval 200 ms) claimed the job first, so the
direct claim returned [] (CI native PG19 failure at line 345).

- recovery-produced work: create, claim and abandon the job with direct
  Adapter calls before client.start(). Only the discovery chain's periodic
  recovery can requeue it; ran === 1 and the creation hint is dropped.
- expiry frees group capacity: seed and claim the blocker (timeoutMs 500)
  before client.start(). The action has no short expire now, so a slow run
  of the waiting job cannot expire before completeJob (second flake mode:
  'periodic safety claims after expiry' timed out under CPU load). The
  sleep + 'created' check becomes a timing-free assertion: the waiting
  job's startedAt >= the blocker's expiresAt (both database clock).

* test: silence no-unmodified-loop-condition in prune-backoff (async counter)

* fix: scope stop() drain exclusion to the caller's job; hide heldJobIds; 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).

* fix: run queued steps in the pusher's context; pin the discovery and 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.

* fix(discovery): follow up short claims; wake discovery when a job of 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.

* fix(discovery): re-arm empty-claim retries per hint; keep waking while 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).

* test: settle past the empty-claim retry tail before the idle check (R2B recheck R3)

* ci: run the test workflow for pull requests into any branch (stacked PRs)

* PR #9 follow-ups: claim locking, release on stop, faster tests, refactors (#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…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant