velocious 1.0.628 → 1.0.630

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +14 -3
  2. package/build/background-jobs/adapter.js +16 -0
  3. package/build/background-jobs/main.js +219 -22
  4. package/build/background-jobs/store.js +128 -19
  5. package/build/background-jobs/types.js +7 -0
  6. package/build/database/record/instance-relationships/base.js +1 -1
  7. package/build/database/record/instance-relationships/belongs-to.js +1 -1
  8. package/build/database/record/instance-relationships/has-many.js +2 -2
  9. package/build/database/record/instance-relationships/has-one.js +1 -1
  10. package/build/environment-handlers/node/cli/commands/generate/base-models.js +7 -8
  11. package/build/src/background-jobs/adapter.d.ts +17 -0
  12. package/build/src/background-jobs/adapter.d.ts.map +1 -1
  13. package/build/src/background-jobs/adapter.js +15 -1
  14. package/build/src/background-jobs/main.d.ts +71 -1
  15. package/build/src/background-jobs/main.d.ts.map +1 -1
  16. package/build/src/background-jobs/main.js +211 -24
  17. package/build/src/background-jobs/store.d.ts +44 -0
  18. package/build/src/background-jobs/store.d.ts.map +1 -1
  19. package/build/src/background-jobs/store.js +117 -19
  20. package/build/src/background-jobs/types.d.ts +25 -0
  21. package/build/src/background-jobs/types.d.ts.map +1 -1
  22. package/build/src/background-jobs/types.js +8 -1
  23. package/build/src/database/record/instance-relationships/base.d.ts +2 -2
  24. package/build/src/database/record/instance-relationships/base.d.ts.map +1 -1
  25. package/build/src/database/record/instance-relationships/base.js +2 -2
  26. package/build/src/database/record/instance-relationships/belongs-to.d.ts +2 -2
  27. package/build/src/database/record/instance-relationships/belongs-to.d.ts.map +1 -1
  28. package/build/src/database/record/instance-relationships/belongs-to.js +2 -2
  29. package/build/src/database/record/instance-relationships/has-many.d.ts +4 -4
  30. package/build/src/database/record/instance-relationships/has-many.d.ts.map +1 -1
  31. package/build/src/database/record/instance-relationships/has-many.js +3 -3
  32. package/build/src/database/record/instance-relationships/has-one.d.ts +2 -2
  33. package/build/src/database/record/instance-relationships/has-one.d.ts.map +1 -1
  34. package/build/src/database/record/instance-relationships/has-one.js +2 -2
  35. package/build/src/environment-handlers/node/cli/commands/generate/base-models.d.ts.map +1 -1
  36. package/build/src/environment-handlers/node/cli/commands/generate/base-models.js +10 -9
  37. package/package.json +1 -1
  38. package/src/background-jobs/adapter.js +16 -0
  39. package/src/background-jobs/main.js +219 -22
  40. package/src/background-jobs/store.js +128 -19
  41. package/src/background-jobs/types.js +7 -0
  42. package/src/database/record/instance-relationships/base.js +1 -1
  43. package/src/database/record/instance-relationships/belongs-to.js +1 -1
  44. package/src/database/record/instance-relationships/has-many.js +2 -2
  45. package/src/database/record/instance-relationships/has-one.js +1 -1
  46. package/src/environment-handlers/node/cli/commands/generate/base-models.js +7 -8
package/README.md CHANGED
@@ -34,7 +34,7 @@
34
34
  * Cross-process broadcast bus for `broadcastToChannel` via `velocious beacon`, including background job runner processes (see [docs/beacon.md](docs/beacon.md))
35
35
  * Configurable HTTP server worker handlers plus backpressured, descriptor-only file responses with completion callbacks (see [docs/http-server.md](docs/http-server.md))
36
36
  * Default-on buffered HTTP response compression with Brotli/gzip content negotiation, global and per-response opt-outs, and HEAD-correct representation headers (see [docs/http-server.md](docs/http-server.md#response-compression))
37
- * Background jobs with Node SQL/TCP workers plus a Browser/Expo local SQLite store and in-process dispatcher, failure events, and authorized database-scoped dashboard count snapshots/deltas (see [docs/background-jobs.md](docs/background-jobs.md), [docs/local-background-jobs.md](docs/local-background-jobs.md), and [docs/background-jobs-dashboard.md](docs/background-jobs-dashboard.md))
37
+ * Background jobs with Node SQL/TCP workers plus a Browser/Expo local SQLite store and in-process dispatcher, including failure events and authorized database-scoped dashboard count snapshots/deltas. Release-directory integrations have a required release-scoped jobs-main/worker generation and asynchronous retirement compliance target that current startup adoption does not implement end to end (see [docs/background-jobs.md](docs/background-jobs.md), [docs/local-background-jobs.md](docs/local-background-jobs.md), and [docs/background-jobs-dashboard.md](docs/background-jobs-dashboard.md))
38
38
  * Durable one-off background-job scheduling with exact epoch timestamps (see [docs/scheduled-background-job-enqueue.md](docs/scheduled-background-job-enqueue.md))
39
39
  * Rails-style request and database query logging (see [docs/logging.md](docs/logging.md))
40
40
  * EJS-backed mailers with delivery, queueing, and payload rendering support (see [docs/mailers.md](docs/mailers.md))
@@ -1133,6 +1133,8 @@ FrontendModelBase.setAutoload(false)
1133
1133
 
1134
1134
  Scoped frontend queries (e.g. `Task.where(...).preload([name]).toArray()` from user code) bypass cohort batching by design, same as the backend. Siblings with locally set state from `.setRelationship()` / `.build()` are preserved across cohort batches.
1135
1135
 
1136
+ Backend relationship `build(...)` / `create(...)` helpers and generated singular builders with a concrete target use that model's generated write-attribute type. Model-valued relationship attributes are accepted, while unknown and invalid attributes fail type checking. Targetless polymorphic `belongsTo` builders remain generic because no single target write contract exists. See [docs/relationships.md](docs/relationships.md#building-related-records).
1137
+
1136
1138
  ## Through relationships
1137
1139
 
1138
1140
  Use the `through` option on `hasMany` to define a relationship that traverses an intermediate (join) table:
@@ -2310,6 +2312,15 @@ Create the file `src/routes/testing/another-action.ejs` and so something like th
2310
2312
 
2311
2313
  Velocious includes a simple background jobs system inspired by Sidekiq.
2312
2314
 
2315
+ In a release-directory production topology, one jobs generation is a
2316
+ same-release `background-jobs-main` and worker pool on its own endpoint. Start the
2317
+ complete candidate generation before activation. A retired main stops schedules,
2318
+ new dispatch, and new handoffs but remains with its old workers to supervise the
2319
+ handoffs it already owns until every worker drains. Old workers never transfer to
2320
+ the new main. Deploy and HTTP/WebSocket drain completion are independent of this
2321
+ potentially hours-long lifecycle. See [release-generation
2322
+ draining](docs/background-jobs.md#release-generation-draining).
2323
+
2313
2324
  Jobs can opt into cross-worker durable concurrency limits by pairing a non-empty `concurrencyKey` with a positive-integer `maxConcurrency` in their background-job options, or by deriving the key in a hydrated job instance's non-static `concurrencyKey()` method. Explicit enqueue options win. The first cap registered for a key is stable; conflicting caps are rejected. See [durable concurrency limits](docs/background-jobs.md#durable-concurrency-limits).
2314
2325
 
2315
2326
  Production apps can listen for `background-job-failed` (or its `all-error` mirror) to report accepted failed attempts, including retry and terminal-state metadata, and for `background-job-orphaned` to react to a specific job the main process reclaimed after its worker died mid-run — e.g. enqueue a targeted recovery for the work it left behind, instead of only polling for the aftermath. Orphan handlers run before the sweep waits for reclaimed jobs to be dispatched, so a stalled dispatcher does not delay application recovery. See [docs/background-jobs.md](docs/background-jobs.md#failure-events).
@@ -2419,7 +2430,7 @@ VELOCIOUS_BACKGROUND_JOBS_WORKER_SHUTDOWN_TIMEOUT_MS=indefinite
2419
2430
  VELOCIOUS_BACKGROUND_JOBS_JOB_TIMEOUT_MS=5400000
2420
2431
  ```
2421
2432
 
2422
- `VELOCIOUS_BACKGROUND_JOBS_WORKER_SHUTDOWN_TIMEOUT_MS` (default: `indefinite`) bounds how long a `background-jobs-worker` waits for in-flight jobs on `SIGTERM`/`SIGINT` before terminating any forked or spawned child runners still running, so they are not orphaned across a deploy. The default waits for jobs to finish and never interrupts a running job; set a positive number of milliseconds for a finite cap (keep it shorter than your process supervisor's graceful-stop window so the worker reaps its own runners first). See [docs/background-jobs.md](docs/background-jobs.md#worker-shutdown-and-process-job-draining).
2433
+ `VELOCIOUS_BACKGROUND_JOBS_WORKER_SHUTDOWN_TIMEOUT_MS` (default: `indefinite`) bounds how long a `background-jobs-worker` waits for in-flight jobs on `SIGTERM`/`SIGINT` before terminating any forked or spawned child runners still running. The default waits for jobs to finish and never interrupts a running job; a positive finite cap is a per-worker shutdown control for an explicitly requested process stop, not the normal deploy-completion mechanism. During release retirement, the old jobs-main and workers may drain for hours after deploy returns. See [docs/background-jobs.md](docs/background-jobs.md#worker-shutdown-and-process-job-draining).
2423
2434
 
2424
2435
  `maxConcurrentInlineJobs` (default: `4`) caps how many `executionMode: "inline"` jobs a single `background-jobs-worker` process runs in parallel. Concurrency is at the JS event-loop level: every job in flight shares the worker's process and DB connection pool, so the cap should fit the pool, not the CPU count. Forking remains the right tool when you need memory isolation across long-running jobs or want to use more cores; select it with `executionMode: "forked"`.
2425
2436
 
@@ -2626,7 +2637,7 @@ Each job must define exactly one of `every` or `cron`. Cron times are evaluated
2626
2637
 
2627
2638
  ## Persistence and retries
2628
2639
 
2629
- Jobs are persisted in the configured database (`backgroundJobs.databaseIdentifier`) in an internal `background_jobs` table. When a worker picks a job, the main generates a unique lease id before asking the adapter to mark the job handed off, and the worker reports completion or failure back to the main process. If that persistence call has an ambiguous result, only the exact caller-generated lease is conditionally returned; failed recovery is retained for the dispatch error-retry path, so worker admission and concurrency do not remain stranded and a newer lease is never reclaimed. Custom adapters must persist a supplied `markHandedOff({handoffId})` exactly; built-in adapters continue generating one for legacy direct callers that omit it. If a worker socket disconnects unexpectedly, only the leases handed to that exact socket are immediately returned to the queue; late reports are fenced by lease id so they cannot mutate a newer attempt. This recovery is at-least-once and may repeat application side effects if the disconnected attempt had already started them. Gracefully draining workers keep their leases while they finish. When the **main** itself restarts (every deploy), a reconnecting worker's still-active handoffs are adopted into its new socket on `hello` so a later disconnect releases them instead of leaving them stuck until the orphan sweep; the main never time-reclaims a disconnected worker's jobs, so a gracefully-draining old-release worker is not double-run. For rolling upgrades, upgrade workers before the main process: a lease-aware main keeps legacy workers connected for old reports but dispatches new jobs only to workers advertising lease-reporting support. See [docs/background-jobs.md](docs/background-jobs.md#worker-disconnect-recovery).
2640
+ Jobs are persisted in the configured database (`backgroundJobs.databaseIdentifier`) in an internal `background_jobs` table. When a worker picks a job, the main generates a unique lease id before asking the adapter to mark the job handed off, and the worker reports completion or failure back to the main process. If that persistence call has an ambiguous result, only the exact caller-generated lease is conditionally returned; failed recovery is retained for the dispatch error-retry path, so worker admission and concurrency do not remain stranded and a newer lease is never reclaimed. Custom adapters must persist a supplied `markHandedOff({handoffId})` exactly; built-in adapters continue generating one for legacy direct callers that omit it. If a worker socket disconnects unexpectedly, only the leases handed to that exact socket are immediately returned to the queue; late reports are fenced by lease id so they cannot mutate a newer attempt. This recovery is at-least-once and may repeat application side effects if the disconnected attempt had already started them. Gracefully draining workers keep their leases while they finish. Startup reconnection/adoption is an abnormal crash/legacy-recovery facility, not the normal deploy topology: during ordinary release retirement the old main remains alive and owns its old workers, and they must not reconnect to the new main. A production integration that restarts jobs-main every deploy and depends on worker adoption is not compliant with the release-generation contract. See [release-generation draining](docs/background-jobs.md#release-generation-draining) and [worker disconnect recovery](docs/background-jobs.md#worker-disconnect-recovery).
2630
2641
 
2631
2642
  Failed jobs are re-queued with backoff and retried up to 10 times by default (10s, 1m, 10m, 1h, then +1h per retry). You can override the retry limit per job:
2632
2643
 
@@ -118,6 +118,22 @@ export default class BackgroundJobsAdapter {
118
118
  */
119
119
  async handedOffJobsForWorker(_args) { throw new Error("BackgroundJobsAdapter#handedOffJobsForWorker is not implemented") }
120
120
 
121
+ /**
122
+ * Snapshots exact active handoffs before a new main generation accepts worker
123
+ * reconnects. Adapters that do not persist worker leases may return none.
124
+ * @returns {Promise<import("./types.js").BackgroundJobHandoffSnapshot[]>} - Exact active handoffs.
125
+ */
126
+ async snapshotHandedOffJobs() { return [] }
127
+
128
+ /**
129
+ * Applies orphan failure semantics to unchanged exact handoff snapshots.
130
+ * Adapters that return startup snapshots must implement the matching fenced
131
+ * transition.
132
+ * @param {{handoffs: import("./types.js").BackgroundJobHandoffSnapshot[], error: ReturnType<typeof JSON.parse>}} _args - Exact leases and orphan reason.
133
+ * @returns {Promise<import("./types.js").BackgroundJobRow[]>} - Accepted transitions.
134
+ */
135
+ async markOrphanedHandoffs(_args) { return [] }
136
+
121
137
  /**
122
138
  * Marks a handed-off job failed or retryable.
123
139
  * @param {{jobId: string, error: ReturnType<typeof JSON.parse>, handoffId?: string, workerId?: string, handedOffAtMs?: number}} _args - Failure report.
@@ -34,6 +34,24 @@ const MAX_TIMER_MS = 2_147_483_647 // ~24.8 days
34
34
  const WORKER_STALE_TIMEOUT_MS = 60000
35
35
  /** How often the main scans workers for staleness. */
36
36
  const WORKER_LIVENESS_SWEEP_MS = 15000
37
+ /** Grace for workers from the previous main generation to reconnect and adopt leases. */
38
+ const WORKER_RECONNECT_GRACE_MS = 30000
39
+ const WORKER_RECONNECT_GRACE_VALIDATION_MESSAGE = `workerReconnectGraceMs must be an integer between 0 and ${MAX_TIMER_MS}`
40
+
41
+ /**
42
+ * Resolves a startup reconnect grace without allowing Node's timer overflow to
43
+ * turn an intentionally long grace into an immediate reclaim.
44
+ * @param {number | undefined} workerReconnectGraceMs - Requested reconnect grace.
45
+ * @returns {number} - Valid timer delay.
46
+ */
47
+ function normalizeWorkerReconnectGraceMs(workerReconnectGraceMs) {
48
+ if (workerReconnectGraceMs === undefined) return WORKER_RECONNECT_GRACE_MS
49
+ if (!Number.isInteger(workerReconnectGraceMs) || workerReconnectGraceMs < 0 || workerReconnectGraceMs > MAX_TIMER_MS) {
50
+ throw new TypeError(WORKER_RECONNECT_GRACE_VALIDATION_MESSAGE)
51
+ }
52
+
53
+ return workerReconnectGraceMs
54
+ }
37
55
  /**
38
56
  * Worker execution mode capabilities.
39
57
  * @type {WorkerExecutionModeCapability[]} */
@@ -61,10 +79,11 @@ export default class BackgroundJobsMain {
61
79
  * @param {number} [args.port] - Port.
62
80
  * @param {number} [args.workerStaleTimeoutMs] - Override how long a silent worker may go before being dropped (default 60000ms).
63
81
  * @param {number} [args.workerLivenessSweepMs] - Override how often stale workers are swept for (default 15000ms).
82
+ * @param {number} [args.workerReconnectGraceMs] - Integer from 0 through 2,147,483,647 overriding how long previous-generation workers may reconnect before exact startup leases are reclaimed (default 30000ms).
64
83
  * @param {boolean} [args.closeDatabaseConnectionsOnStop] - Whether stop owns closing the configuration's database pools (default true).
65
84
  * @param {() => void | Promise<void>} [args.onStopped] - Lifecycle hook invoked after the main process finishes stopping.
66
85
  */
67
- constructor({configuration, host, port, workerStaleTimeoutMs, workerLivenessSweepMs, closeDatabaseConnectionsOnStop = true, onStopped}) {
86
+ constructor({configuration, host, port, workerStaleTimeoutMs, workerLivenessSweepMs, workerReconnectGraceMs, closeDatabaseConnectionsOnStop = true, onStopped}) {
68
87
  this.configuration = configuration
69
88
  this.closeDatabaseConnectionsOnStop = closeDatabaseConnectionsOnStop
70
89
  this.onStopped = onStopped
@@ -78,6 +97,7 @@ export default class BackgroundJobsMain {
78
97
  // long is treated as wedged/dead: its leases are released and it is dropped.
79
98
  this.workerStaleTimeoutMs = typeof workerStaleTimeoutMs === "number" && workerStaleTimeoutMs >= 1 ? workerStaleTimeoutMs : WORKER_STALE_TIMEOUT_MS
80
99
  this.workerLivenessSweepMs = typeof workerLivenessSweepMs === "number" && workerLivenessSweepMs >= 1 ? workerLivenessSweepMs : WORKER_LIVENESS_SWEEP_MS
100
+ this.workerReconnectGraceMs = normalizeWorkerReconnectGraceMs(workerReconnectGraceMs)
81
101
  /** @type {import("./adapter.js").default | undefined} */
82
102
  this.adapter = undefined
83
103
  this.logger = new Logger(this)
@@ -104,6 +124,17 @@ export default class BackgroundJobsMain {
104
124
  * wait for these before closing the configuration's database pools.
105
125
  * @type {Set<Promise<void>>} */
106
126
  this.inflightWorkerHandoffAdoptions = new Set()
127
+ /**
128
+ * Worker ids whose handoffs were successfully adopted by a still-live
129
+ * connection in this main generation.
130
+ * @type {Set<string>}
131
+ */
132
+ this.reconnectedWorkerIds = new Set()
133
+ /** @type {import("./types.js").BackgroundJobHandoffSnapshot[]} */
134
+ this.startupHandoffSnapshot = []
135
+ /** @type {Promise<void>[]} */
136
+ this._startupHandoffAdoptionsAtDeadline = []
137
+ this._startupHandoffGraceElapsed = false
107
138
  /**
108
139
  * Narrows the runtime value to the documented type.
109
140
  * @type {net.Server | undefined} */
@@ -128,6 +159,10 @@ export default class BackgroundJobsMain {
128
159
  * Narrows the runtime value to the documented type.
129
160
  * @type {ReturnType<typeof setInterval> | undefined} */
130
161
  this._workerStaleTimer = undefined
162
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
163
+ this._startupHandoffReclaimTimer = undefined
164
+ /** @type {Promise<void> | undefined} */
165
+ this._startupHandoffReclaimPromise = undefined
131
166
  /**
132
167
  * Narrows the runtime value to the documented type.
133
168
  * @type {BackgroundJobsScheduler | undefined} */
@@ -178,6 +213,11 @@ export default class BackgroundJobsMain {
178
213
  async start() {
179
214
  this._stopped = false
180
215
  this.stopPromise = undefined
216
+ this.reconnectedWorkerIds.clear()
217
+ this.startupHandoffSnapshot = []
218
+ this._startupHandoffAdoptionsAtDeadline = []
219
+ this._startupHandoffGraceElapsed = false
220
+ this._startupHandoffReclaimPromise = undefined
181
221
  this.configuration.setCurrent()
182
222
 
183
223
  try {
@@ -194,6 +234,7 @@ export default class BackgroundJobsMain {
194
234
  // across processes with a database advisory lock, so concurrently started
195
235
  // mains cannot interleave them.
196
236
  await this.store.reconcileQueueConcurrency()
237
+ this.startupHandoffSnapshot = await this.store.snapshotHandedOffJobs()
197
238
  const server = net.createServer((socket) => this._handleConnection(socket))
198
239
  this.server = server
199
240
 
@@ -208,6 +249,7 @@ export default class BackgroundJobsMain {
208
249
  }
209
250
 
210
251
  this._setupDispatchTriggers()
252
+ this._setupStartupHandoffReclaim()
211
253
 
212
254
  this._orphanTimer = setInterval(() => {
213
255
  void this._sweepOrphans()
@@ -297,7 +339,11 @@ export default class BackgroundJobsMain {
297
339
  try {
298
340
  await this._drainWorkerHandoffAdoptions()
299
341
  } finally {
300
- await this._stopBeaconAndServer()
342
+ try {
343
+ await this._drainStartupHandoffReclaim()
344
+ } finally {
345
+ await this._stopBeaconAndServer()
346
+ }
301
347
  }
302
348
  }
303
349
  }
@@ -325,11 +371,13 @@ export default class BackgroundJobsMain {
325
371
  if (this._errorRetryTimer) clearTimeout(this._errorRetryTimer)
326
372
  if (this._orphanTimer) clearInterval(this._orphanTimer)
327
373
  if (this._workerStaleTimer) clearInterval(this._workerStaleTimer)
374
+ if (this._startupHandoffReclaimTimer) clearTimeout(this._startupHandoffReclaimTimer)
328
375
  this._pollTimer = undefined
329
376
  this._scheduledTimer = undefined
330
377
  this._errorRetryTimer = undefined
331
378
  this._orphanTimer = undefined
332
379
  this._workerStaleTimer = undefined
380
+ this._startupHandoffReclaimTimer = undefined
333
381
  }
334
382
 
335
383
  /**
@@ -431,6 +479,123 @@ export default class BackgroundJobsMain {
431
479
  beaconClient.on("connect", this._beaconConnectHandler)
432
480
  }
433
481
 
482
+ /**
483
+ * Arms the bounded adoption grace only when startup found exact persisted
484
+ * handoffs. The timer is unrefed so an otherwise-finished process is never
485
+ * retained solely to perform this cleanup.
486
+ * @returns {void}
487
+ */
488
+ _setupStartupHandoffReclaim() {
489
+ if (this.startupHandoffSnapshot.length === 0) return
490
+
491
+ this._startupHandoffReclaimTimer = setTimeout(() => {
492
+ this._startupHandoffReclaimTimer = undefined
493
+ this._startupHandoffAdoptionsAtDeadline = [...this.inflightWorkerHandoffAdoptions]
494
+ this._startupHandoffGraceElapsed = true
495
+ void this._startStartupHandoffReclaim()
496
+ }, this.workerReconnectGraceMs)
497
+ this._startupHandoffReclaimTimer.unref()
498
+ }
499
+
500
+ /**
501
+ * Starts one tracked startup-reclaim pass, coalescing lifecycle and retry
502
+ * callers so shutdown can wait for durable mutation before closing pools.
503
+ * @returns {Promise<void>} - Resolves after this pass settles.
504
+ */
505
+ _startStartupHandoffReclaim() {
506
+ if (this._startupHandoffReclaimPromise) return this._startupHandoffReclaimPromise
507
+
508
+ const reclaim = this._reclaimDisconnectedStartupHandoffs()
509
+
510
+ this._startupHandoffReclaimPromise = reclaim
511
+ const clearReclaim = () => {
512
+ if (this._startupHandoffReclaimPromise === reclaim) {
513
+ this._startupHandoffReclaimPromise = undefined
514
+ }
515
+ }
516
+ void reclaim.then(clearReclaim, clearReclaim)
517
+
518
+ return reclaim
519
+ }
520
+
521
+ /**
522
+ * Waits for an already-started startup reclaim before adapter shutdown.
523
+ * @returns {Promise<void>} - Resolves when no pass remains.
524
+ */
525
+ async _drainStartupHandoffReclaim() {
526
+ while (this._startupHandoffReclaimPromise) {
527
+ await this._startupHandoffReclaimPromise
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Orphans only startup-snapshotted leases whose stable worker id has not been
533
+ * observed by this main generation. Store fencing rejects completed,
534
+ * returned, replaced, and re-handed-off rows.
535
+ * @returns {Promise<void>} - Resolves after reclaim or retained retry state.
536
+ */
537
+ async _reclaimDisconnectedStartupHandoffs() {
538
+ if (this._stopped || !this._startupHandoffGraceElapsed) return
539
+ if (this.startupHandoffSnapshot.length === 0) return
540
+
541
+ await this._waitForStartupHandoffAdoptionsAtDeadline()
542
+ if (this._stopped) return
543
+
544
+ const handoffs = this.startupHandoffSnapshot.filter(({workerId}) => !this.reconnectedWorkerIds.has(workerId))
545
+
546
+ if (handoffs.length === 0) {
547
+ this.startupHandoffSnapshot = []
548
+ return
549
+ }
550
+
551
+ let orphanedJobs
552
+
553
+ try {
554
+ orphanedJobs = await this.store.markOrphanedHandoffs({
555
+ error: "Job orphaned after its pre-restart worker did not reconnect",
556
+ handoffs
557
+ })
558
+ } catch (error) {
559
+ this._reportStartupHandoffReclaimError(error)
560
+ this._scheduleErrorRetry()
561
+ return
562
+ }
563
+
564
+ this.startupHandoffSnapshot = []
565
+ await this._handleOrphanedJobs({
566
+ jobs: orphanedJobs,
567
+ warning: "Reclaimed background jobs from workers absent after main restart grace"
568
+ })
569
+ }
570
+
571
+ /**
572
+ * Lets adoption queries already running at the reconnect deadline settle
573
+ * before worker ids are filtered. A second bounded grace prevents a stuck
574
+ * adapter query from deferring startup reclaim forever.
575
+ * @returns {Promise<void>} - Resolves when the deadline set settles or times out.
576
+ */
577
+ async _waitForStartupHandoffAdoptionsAtDeadline() {
578
+ const adoptions = this._startupHandoffAdoptionsAtDeadline
579
+
580
+ this._startupHandoffAdoptionsAtDeadline = []
581
+ if (adoptions.length === 0) return
582
+
583
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
584
+ let timer
585
+ const waitLimit = new Promise((resolve) => {
586
+ // This lifecycle deadline must not keep the main process alive; the
587
+ // generic timeout helper intentionally uses a referenced timer.
588
+ timer = setTimeout(resolve, this.workerReconnectGraceMs)
589
+ timer.unref()
590
+ })
591
+
592
+ try {
593
+ await Promise.race([Promise.all(adoptions), waitLimit])
594
+ } finally {
595
+ if (timer) clearTimeout(timer)
596
+ }
597
+ }
598
+
434
599
  /**
435
600
  * Publishes a dispatch wake-up on the Beacon channel. No-op in polling
436
601
  * mode or when Beacon is not connected; in those cases the direct
@@ -583,6 +748,7 @@ export default class BackgroundJobsMain {
583
748
  for (const {jobId, handoffId} of handoffs) {
584
749
  map.set(jobId, handoffId)
585
750
  }
751
+ this.reconnectedWorkerIds.add(workerId)
586
752
  } catch (error) {
587
753
  this._reportHandoffAdoptError(error)
588
754
  }
@@ -820,6 +986,22 @@ export default class BackgroundJobsMain {
820
986
  errorEvents.emit("all-error", {...payload, errorType: "framework-error"})
821
987
  }
822
988
 
989
+ /**
990
+ * Reports an unexpected startup-snapshot reclaim failure while retaining the
991
+ * snapshot for the dispatcher's existing transient-error retry lifecycle.
992
+ * @param {ReturnType<typeof JSON.parse>} error - Reclaim failure.
993
+ * @returns {void}
994
+ */
995
+ _reportStartupHandoffReclaimError(error) {
996
+ const normalizedError = error instanceof Error ? error : new Error(String(error))
997
+ const payload = {context: {stage: "background-job-startup-handoff-reclaim"}, error: normalizedError}
998
+ const errorEvents = this.configuration.getErrorEvents()
999
+
1000
+ this.logger.error(() => ["Failed to reclaim disconnected startup handoffs:", normalizedError])
1001
+ errorEvents.emit("framework-error", payload)
1002
+ errorEvents.emit("all-error", {...payload, errorType: "framework-error"})
1003
+ }
1004
+
823
1005
  /**
824
1006
  * Runs handle enqueue.
825
1007
  * @param {object} args - Options.
@@ -1237,6 +1419,7 @@ export default class BackgroundJobsMain {
1237
1419
  * @returns {void} */
1238
1420
  _clearErrorRetryTimer() {
1239
1421
  if (this.pendingHandoffRecoveries.size > 0) return
1422
+ if (this._startupHandoffGraceElapsed && this.startupHandoffSnapshot.length > 0) return
1240
1423
 
1241
1424
  for (const worker of this.workerHandoffs.keys()) {
1242
1425
  if (!this.workers.has(worker)) return
@@ -1311,6 +1494,11 @@ export default class BackgroundJobsMain {
1311
1494
  async _retryAfterError() {
1312
1495
  if (this._stopped) return
1313
1496
 
1497
+ if (this._startupHandoffGraceElapsed && this.startupHandoffSnapshot.length > 0) {
1498
+ await this._startStartupHandoffReclaim()
1499
+ if (this.startupHandoffSnapshot.length > 0) return
1500
+ }
1501
+
1314
1502
  try {
1315
1503
  await this._retryPendingHandoffRecoveries()
1316
1504
  } catch {
@@ -1650,31 +1838,40 @@ export default class BackgroundJobsMain {
1650
1838
  try {
1651
1839
  const orphanedJobs = await this.store.markOrphanedJobs()
1652
1840
 
1653
- if (orphanedJobs.length > 0) {
1654
- this.logger.warn(() => ["Marked orphaned background jobs", orphanedJobs.length])
1655
- // Reclaimed orphans become `queued` again — wake the dispatcher first so
1656
- // an application event handler that throws below cannot strand them
1657
- // queued until the next external enqueue/reconnect.
1658
- this._notifyEnqueued()
1659
- // Emit an event per orphaned job so applications can react to a dead
1660
- // worker's specific job (e.g. targeted recovery) instead of only polling
1661
- // for its aftermath. Emit before awaiting the drain so a blocked
1662
- // dispatcher cannot delay application recovery. Isolate each so one
1663
- // throwing handler can't suppress the events for the rest.
1664
- for (const job of orphanedJobs) {
1665
- try {
1666
- this._emitBackgroundJobOrphaned({job})
1667
- } catch (error) {
1668
- this.logger.error(() => ["A background-job-orphaned event handler threw:", error])
1669
- }
1670
- }
1671
- await this._drain()
1672
- }
1841
+ await this._handleOrphanedJobs({jobs: orphanedJobs, warning: "Marked orphaned background jobs"})
1673
1842
  } catch (error) {
1674
1843
  this.logger.error(() => ["Failed to mark orphaned jobs:", error])
1675
1844
  }
1676
1845
  }
1677
1846
 
1847
+ /**
1848
+ * Publishes the common post-orphan lifecycle: wake queued retries, emit one
1849
+ * isolated event per accepted transition, and drain so released concurrency
1850
+ * can immediately admit other work.
1851
+ * @param {object} args - Options.
1852
+ * @param {import("./types.js").BackgroundJobRow[]} args.jobs - Accepted orphan transitions.
1853
+ * @param {string} args.warning - Lifecycle log message.
1854
+ * @returns {Promise<void>} - Resolves after the resulting drain.
1855
+ */
1856
+ async _handleOrphanedJobs({jobs, warning}) {
1857
+ if (jobs.length === 0) return
1858
+
1859
+ this.logger.warn(() => [warning, jobs.length])
1860
+ // Reclaimed orphans can become `queued` again — wake the dispatcher first
1861
+ // so an application event handler that throws below cannot strand them.
1862
+ this._notifyEnqueued()
1863
+ // Emit before awaiting the drain so a blocked dispatcher cannot delay
1864
+ // application recovery. Isolate handlers so one cannot suppress the rest.
1865
+ for (const job of jobs) {
1866
+ try {
1867
+ this._emitBackgroundJobOrphaned({job})
1868
+ } catch (error) {
1869
+ this.logger.error(() => ["A background-job-orphaned event handler threw:", error])
1870
+ }
1871
+ }
1872
+ await this._drain()
1873
+ }
1874
+
1678
1875
  /**
1679
1876
  * Drops workers that have gone silent past `workerStaleTimeoutMs` (no
1680
1877
  * heartbeat, ready, or report). A wedged worker keeps its socket open, so the
@@ -43,6 +43,13 @@ import {
43
43
  * @property {number | null} timeoutMs - Per-job timeout override, or null when omitted.
44
44
  */
45
45
 
46
+ /**
47
+ * BackgroundJobOrphanSelection type.
48
+ * @typedef {object} BackgroundJobOrphanSelection
49
+ * @property {Record<string, ReturnType<typeof JSON.parse>>} conditions - Exact update fence.
50
+ * @property {import("./types.js").BackgroundJobRow} job - Selected active handoff.
51
+ */
52
+
46
53
  /**
47
54
  * BackgroundJobTransactionSerializationOptions type.
48
55
  * @typedef {object} BackgroundJobTransactionSerializationOptions
@@ -1096,6 +1103,81 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1096
1103
  return handoffs
1097
1104
  }
1098
1105
 
1106
+ /**
1107
+ * Snapshots exact, lease-aware active handoffs before a new main generation
1108
+ * starts accepting worker reconnects. Legacy rows without a complete worker,
1109
+ * lease, and timestamp identity stay owned by the age-based orphan sweep.
1110
+ * @returns {Promise<import("./types.js").BackgroundJobHandoffSnapshot[]>} - Exact startup handoffs.
1111
+ */
1112
+ async snapshotHandedOffJobs() {
1113
+ await this.ensureReady()
1114
+
1115
+ const rows = await this._withDb(async (db) => await db
1116
+ .newQuery()
1117
+ .from(JOBS_TABLE)
1118
+ .where({status: "handed_off"})
1119
+ .order("created_at_ms ASC")
1120
+ .order("id ASC")
1121
+ .results())
1122
+ /** @type {import("./types.js").BackgroundJobHandoffSnapshot[]} */
1123
+ const handoffs = []
1124
+
1125
+ for (const row of rows) {
1126
+ const job = this._normalizeJobRow(row)
1127
+
1128
+ if (!job.handoffId || !job.workerId || typeof job.handedOffAtMs !== "number") continue
1129
+
1130
+ handoffs.push({
1131
+ handedOffAtMs: job.handedOffAtMs,
1132
+ handoffId: job.handoffId,
1133
+ jobId: job.id,
1134
+ workerId: job.workerId
1135
+ })
1136
+ }
1137
+
1138
+ return handoffs
1139
+ }
1140
+
1141
+ /**
1142
+ * Reclaims only unchanged exact handoffs selected by a main-generation startup
1143
+ * snapshot. The ordinary orphan failure path owns retries, terminal status,
1144
+ * count transitions, schedule ownership, and concurrency release.
1145
+ * @param {object} args - Options.
1146
+ * @param {import("./types.js").BackgroundJobHandoffSnapshot[]} args.handoffs - Exact startup snapshots.
1147
+ * @param {ReturnType<typeof JSON.parse>} args.error - Orphan reason.
1148
+ * @returns {Promise<import("./types.js").BackgroundJobRow[]>} - Accepted transitions.
1149
+ */
1150
+ async markOrphanedHandoffs({handoffs, error}) {
1151
+ await this.ensureReady()
1152
+
1153
+ return await this._serializedCountMutation(async (db) => {
1154
+ /** @type {BackgroundJobOrphanSelection[]} */
1155
+ const selections = []
1156
+
1157
+ for (const handoff of handoffs) {
1158
+ const job = await this._getJobRowById(db, handoff.jobId)
1159
+
1160
+ if (!job || job.status !== "handed_off") continue
1161
+ if (job.handoffId !== handoff.handoffId) continue
1162
+ if (job.workerId !== handoff.workerId) continue
1163
+ if (job.handedOffAtMs !== handoff.handedOffAtMs) continue
1164
+
1165
+ selections.push({
1166
+ conditions: {
1167
+ handed_off_at_ms: handoff.handedOffAtMs,
1168
+ handoff_id: handoff.handoffId,
1169
+ id: handoff.jobId,
1170
+ status: "handed_off",
1171
+ worker_id: handoff.workerId
1172
+ },
1173
+ job
1174
+ })
1175
+ }
1176
+
1177
+ return await this._markOrphanSelections({db, error, selections})
1178
+ })
1179
+ }
1180
+
1099
1181
  /**
1100
1182
  * Runs mark failed.
1101
1183
  * @param {object} args - Options.
@@ -1141,8 +1223,8 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1141
1223
 
1142
1224
  const rows = await query.results()
1143
1225
 
1144
- /** @type {import("./types.js").BackgroundJobRow[]} */
1145
- const orphanedJobs = []
1226
+ /** @type {BackgroundJobOrphanSelection[]} */
1227
+ const selections = []
1146
1228
 
1147
1229
  for (const row of rows) {
1148
1230
  const job = this._normalizeJobRow(row)
@@ -1160,28 +1242,55 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1160
1242
  // wrongly release the concurrency reservation of — that new lease.
1161
1243
  // `handed_off_at_ms` is always set on a handed-off row (and the SELECT
1162
1244
  // required it `<= cutoff`), so it is a reliable null-safe lease pin.
1163
- const orphanedJob = await this._applyFailure({
1164
- db,
1165
- job,
1166
- error: "Job orphaned after timeout",
1167
- markOrphaned: true,
1168
- conditions: {id: job.id, status: "handed_off", handed_off_at_ms: job.handedOffAtMs}
1245
+ selections.push({
1246
+ conditions: {id: job.id, status: "handed_off", handed_off_at_ms: job.handedOffAtMs},
1247
+ job
1169
1248
  })
1170
-
1171
- if (orphanedJob) orphanedJobs.push(orphanedJob)
1172
1249
  }
1173
1250
 
1174
- const statusCounts = this._statusCounts(orphanedJobs)
1175
- const deltas = this._emptyCountBuckets()
1251
+ return await this._markOrphanSelections({
1252
+ db,
1253
+ error: "Job orphaned after timeout",
1254
+ selections
1255
+ })
1256
+ })
1257
+ }
1258
+
1259
+ /**
1260
+ * Applies the common fenced orphan transition and records one aggregate count
1261
+ * delta for the accepted rows.
1262
+ * @param {object} args - Options.
1263
+ * @param {import("../database/drivers/base.js").default} args.db - Transaction connection.
1264
+ * @param {ReturnType<typeof JSON.parse>} args.error - Orphan reason.
1265
+ * @param {BackgroundJobOrphanSelection[]} args.selections - Selected handoffs and exact fences.
1266
+ * @returns {Promise<import("./types.js").BackgroundJobRow[]>} - Accepted transitions.
1267
+ */
1268
+ async _markOrphanSelections({db, error, selections}) {
1269
+ /** @type {import("./types.js").BackgroundJobRow[]} */
1270
+ const orphanedJobs = []
1271
+
1272
+ for (const {conditions, job} of selections) {
1273
+ const orphanedJob = await this._applyFailure({
1274
+ conditions,
1275
+ db,
1276
+ error,
1277
+ job,
1278
+ markOrphaned: true
1279
+ })
1176
1280
 
1177
- for (const [status, count] of Object.entries(statusCounts)) {
1178
- deltas.handed_off -= count
1179
- deltas[status] += count
1180
- }
1181
- await this._recordCountDelta(db, deltas)
1281
+ if (orphanedJob) orphanedJobs.push(orphanedJob)
1282
+ }
1182
1283
 
1183
- return orphanedJobs
1184
- })
1284
+ const statusCounts = this._statusCounts(orphanedJobs)
1285
+ const deltas = this._emptyCountBuckets()
1286
+
1287
+ for (const [status, count] of Object.entries(statusCounts)) {
1288
+ deltas.handed_off -= count
1289
+ deltas[status] += count
1290
+ }
1291
+ await this._recordCountDelta(db, deltas)
1292
+
1293
+ return orphanedJobs
1185
1294
  }
1186
1295
 
1187
1296
  /**
@@ -43,6 +43,13 @@
43
43
  * @property {string} handoffId - Unique handoff lease id.
44
44
  * @property {number} handedOffAtMs - Time handed to a worker in ms.
45
45
  */
46
+ /**
47
+ * @typedef {object} BackgroundJobHandoffSnapshot
48
+ * @property {string} jobId - Job holding the lease.
49
+ * @property {string} handoffId - Exact durable lease id.
50
+ * @property {string} workerId - Stable worker id that received the lease.
51
+ * @property {number} handedOffAtMs - Time handed to the worker in ms.
52
+ */
46
53
  /**
47
54
  * @typedef {object} BackgroundJobHandoffRequest
48
55
  * @property {string} jobId - Job to claim.
@@ -55,7 +55,7 @@ export default class VelociousDatabaseRecordBaseInstanceRelationship {
55
55
  /**
56
56
  * Runs build.
57
57
  * @abstract
58
- * @param {Record<string, ReturnType<typeof JSON.parse>>} attributes - Attributes.
58
+ * @param {ConstructorParameters<TMC>[0]} attributes - Target model write attributes.
59
59
  * @returns {InstanceType<TMC>} - The build.
60
60
  */
61
61
  build(attributes) { // eslint-disable-line no-unused-vars
@@ -19,7 +19,7 @@ export default class VelociousDatabaseRecordBelongsToInstanceRelationship extend
19
19
 
20
20
  /**
21
21
  * Runs build.
22
- * @param {Record<string, ReturnType<typeof JSON.parse>>} data - Data payload.
22
+ * @param {ConstructorParameters<TMC>[0]} data - Target model write attributes.
23
23
  * @returns {InstanceType<TMC>} - The build.
24
24
  */
25
25
  build(data) {