@happyvertical/smrt-jobs 0.61.5 → 0.62.0
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.
- package/AGENTS.md +11 -29
- package/README.md +140 -2
- package/agents/forge-projections.md +30 -0
- package/agents/job-claims.md +82 -0
- package/agents/job-handlers.md +115 -0
- package/agents/provider-loading.md +19 -0
- package/agents/scheduling.md +206 -0
- package/agents/worker-liveness.md +3 -0
- package/dist/chunks/{runner-Bt6JV6uO.js → runner-ComDONr7.js} +862 -485
- package/dist/chunks/runner-ComDONr7.js.map +1 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +53 -2
- package/dist/index.js.map +1 -1
- package/dist/job-claim.d.ts +61 -0
- package/dist/job-claim.d.ts.map +1 -0
- package/dist/job-handlers.d.ts +127 -0
- package/dist/job-handlers.d.ts.map +1 -0
- package/dist/logger-extension.d.ts +5 -0
- package/dist/logger-extension.d.ts.map +1 -1
- package/dist/manifest.json +39 -1
- package/dist/runner.d.ts +67 -0
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +2 -2
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-event.d.ts +21 -1
- package/dist/smrt-job-event.d.ts.map +1 -1
- package/dist/smrt-job.d.ts +37 -4
- package/dist/smrt-job.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +58 -6
- package/dist/smrt-knowledge.okf.md +16 -4
- package/dist/terminal-outcome.d.ts +5 -2
- package/dist/terminal-outcome.d.ts.map +1 -1
- package/dist/worker-liveness.d.ts +9 -0
- package/dist/worker-liveness.d.ts.map +1 -1
- package/package.json +9 -8
- package/dist/chunks/runner-Bt6JV6uO.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Background job execution with persistent queue, scheduling, and fluent builder API.
|
|
4
4
|
Retry SDK import boundary: [provider loading](agents/provider-loading.md).
|
|
5
|
+
A job targets a model method or a registered named handler; runners claim only handlers they registered: [job handlers](agents/job-handlers.md).
|
|
5
6
|
|
|
6
7
|
## Architecture
|
|
7
8
|
|
|
@@ -32,7 +33,7 @@ lease advertising remains queue-level; it does not prove per-tenant availability
|
|
|
32
33
|
1. `start()` checks the build migrate fingerprint, then calls `assertReady()` (fail fast if `_smrt_workers` unmigrated), registers a seeded `SmrtWorker` lease, and adds its worker key to the process-global live set — all **before** polling
|
|
33
34
|
2. Polls `claimReady()` to atomically claim at most the free slots (`concurrency - active`) of pending jobs (`runAt <= NOW`, ordered by `priority DESC, runAt ASC, created_at ASC, id ASC`). On PostgreSQL the candidates come from a `MATERIALIZED` CTE joined to the UPDATE; never claim with `WHERE id IN (SELECT … LIMIT n FOR UPDATE SKIP LOCKED)` — a nested-loop semi join rescans it per outer row and takes the whole backlog (#3145). The runner also never starts more than the free slots and returns any surplus claim to `pending` with its attempt restored
|
|
34
35
|
3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`
|
|
35
|
-
4. Resolves class via `ObjectRegistry.getClass(objectType)
|
|
36
|
+
4. Resolves class via `ObjectRegistry.getClass(objectType)` (a `handler:` target uses the handler snapshot instead). Object-bound jobs
|
|
36
37
|
pass `objectId` to the constructor and let `initialize()` perform the single
|
|
37
38
|
canonical hydration. Runner-owned `db`, `id`, and hydration options cannot be
|
|
38
39
|
overridden by agent config; missing persisted targets fail before method
|
|
@@ -105,34 +106,7 @@ await handle.wait({ timeout: 60000, pollInterval: 100 }); // polling-based
|
|
|
105
106
|
|
|
106
107
|
## Durable forge projections
|
|
107
108
|
|
|
108
|
-
|
|
109
|
-
`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter
|
|
110
|
-
transitions and monotonic checkpoints in
|
|
111
|
-
`_smrt_forge_projection_checkpoints`.
|
|
112
|
-
|
|
113
|
-
- Inbox identity is `(tenant_id, provider, delivery_id)`.
|
|
114
|
-
- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or
|
|
115
|
-
`claimReady`) so each claims and dead-letters only its own deliveries;
|
|
116
|
-
unfiltered claims take every provider (smrt-commerce billing uses
|
|
117
|
-
`<name>-billing:<sellerTenantId>`, #3060).
|
|
118
|
-
- `claimReady` leases exactly one delivery; PostgreSQL uses the same
|
|
119
|
-
`MATERIALIZED` CTE claim as jobs (#3105).
|
|
120
|
-
- Tenant-facing accept/replay requires ambient tenant context. Worker claim is
|
|
121
|
-
cross-tenant, then runtime restores the captured context before observation.
|
|
122
|
-
Reads in the accept path go through the tenant-scoped collection (`list()`),
|
|
123
|
-
so intake works under the interceptor's `rawQueryPolicy: 'throw'` production
|
|
124
|
-
default without a bypass (#3100); keep new tenant-facing reads that way.
|
|
125
|
-
- Projection callbacks must write through `ForgeProjectionContext.db`; the
|
|
126
|
-
application projection, checkpoint, and inbox completion share one
|
|
127
|
-
transaction.
|
|
128
|
-
- Observation identity is tracker-independent
|
|
129
|
-
`(projection, subjectKey, version)`. Equal or older versions are acknowledged
|
|
130
|
-
without reapplying.
|
|
131
|
-
- Lease-token conditions guard every terminal/failure write. Expired final
|
|
132
|
-
attempts become replayable `dead_letter` rows, and persisted errors are
|
|
133
|
-
redacted.
|
|
134
|
-
- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit
|
|
135
|
-
tenant-scoped operator action.
|
|
109
|
+
Provider delivery inbox, leases and checkpoints: [forge projections](agents/forge-projections.md).
|
|
136
110
|
|
|
137
111
|
`bg()` is shorthand: `await doc.bg('analyze', args)` → enqueues immediately, returns JobHandle.
|
|
138
112
|
|
|
@@ -234,3 +208,11 @@ the framework retention sweep in `@happyvertical/smrt-core`.
|
|
|
234
208
|
- **wait() is polling**: JobHandle.wait() polls DB every 100ms (configurable)
|
|
235
209
|
- **Migrate before start()**: Both runners call core's `assertDatabaseMigratedForBuild` before polling (policy: [schema paths](../core/agents/schema-paths.md)). A missing or different record refuses production start; development warns, test databases are exempt, and the emergency override is logged. `TaskRunner.start()` throws if `_smrt_workers` is missing — run `smrt db:migrate` after upgrading. Tables are never created at runtime.
|
|
236
210
|
- **Recovery is liveness-based**: don't reintroduce heartbeat-threshold recovery; a blocked event loop must not look dead (see Worker liveness section, #1474)
|
|
211
|
+
|
|
212
|
+
## Transaction-bound claims
|
|
213
|
+
|
|
214
|
+
Use `getJobClaim`, `assertJobClaim`, `assertJobClaimForRelease`,
|
|
215
|
+
`assertFailedJobDispatch` and `assertAbandonedJobClaim` for dispatch fencing,
|
|
216
|
+
recovery and application lease release. Read [claim and recovery contracts](agents/job-claims.md)
|
|
217
|
+
for opt-in fencing, transaction affinity, liveness, exact outcome lookup and
|
|
218
|
+
PGlite validation. Never infer settlement from cancellation alone.
|
package/README.md
CHANGED
|
@@ -125,6 +125,63 @@ must be finite positive milliseconds within the Node timer range. The default
|
|
|
125
125
|
20× idle cap reduces combined claim and recovery traffic; latency-sensitive
|
|
126
126
|
workers can set a smaller cap.
|
|
127
127
|
|
|
128
|
+
### Target a named handler instead of a model method
|
|
129
|
+
|
|
130
|
+
A job targets either a model method (above) or a handler registered under a
|
|
131
|
+
namespaced `<package>:<name>`. Register every handler before
|
|
132
|
+
`runner.start()`: a running runner dispatches from the snapshot it took at
|
|
133
|
+
start, and registering while any runner in the process is running throws
|
|
134
|
+
`JobHandlerRegistrationClosedError`.
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
import {
|
|
138
|
+
getJobClaim,
|
|
139
|
+
registerJobHandler,
|
|
140
|
+
SmrtJobCollection,
|
|
141
|
+
TaskRunner,
|
|
142
|
+
} from '@happyvertical/smrt-jobs';
|
|
143
|
+
|
|
144
|
+
registerJobHandler(
|
|
145
|
+
'@happyvertical/smrt-workflows:workflow-run',
|
|
146
|
+
async (payload, context) => {
|
|
147
|
+
const claim = getJobClaim(context); // with claimFencing: true
|
|
148
|
+
context.logger.info('running', { runId: payload.runId });
|
|
149
|
+
return { runId: payload.runId };
|
|
150
|
+
},
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
const runner = new TaskRunner({ claimFencing: true, queues: ['workflows'] });
|
|
154
|
+
await runner.initialize(db);
|
|
155
|
+
await runner.start();
|
|
156
|
+
|
|
157
|
+
const jobs = await SmrtJobCollection.create({ db });
|
|
158
|
+
await jobs.enqueueHandlerJob({
|
|
159
|
+
handler: '@happyvertical/smrt-workflows:workflow-run',
|
|
160
|
+
payload: { runId },
|
|
161
|
+
queue: 'workflows',
|
|
162
|
+
dedupeKey: runId,
|
|
163
|
+
});
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The row is stored as `object_type = 'handler:<name>'`, `method = 'handle'`,
|
|
167
|
+
`object_id = NULL` (no schema change). Handler jobs share the model path for
|
|
168
|
+
MCP authority, tenancy, timeouts, cancellation, claim fencing, retries and
|
|
169
|
+
terminal outcomes. A runner claims model jobs and only the handler jobs it
|
|
170
|
+
registered (at most 256 handlers per process). A handler job left `pending`
|
|
171
|
+
longer than `handlerUnclaimedDeadlineMs` (runner option, default 24 h) past
|
|
172
|
+
its `run_at` is failed by a runner sweeping its queue that does not register
|
|
173
|
+
that handler (a runner never sweeps its own handlers; it claims them), failure
|
|
174
|
+
kind `handler-unclaimed`, event `job:unclaimed`. A claim made without the filter that reaches an
|
|
175
|
+
unregistered handler fails the job on that claim, never retried, failure
|
|
176
|
+
kind `handler-unregistered`. Schedules and MCP tasks target model methods
|
|
177
|
+
only.
|
|
178
|
+
|
|
179
|
+
**Upgrade first.** A runner older than this contract does not filter: it
|
|
180
|
+
retries a handler job as an unknown model up to `maxAttempts` and fails it,
|
|
181
|
+
and older outcome readers drop the `handler-unregistered` and
|
|
182
|
+
`handler-unclaimed` kinds. Enqueue handler jobs only after every runner is
|
|
183
|
+
upgraded. Details: [job handlers](agents/job-handlers.md).
|
|
184
|
+
|
|
128
185
|
### Back MCP task operations with durable jobs
|
|
129
186
|
|
|
130
187
|
`McpTaskStore` persists the MCP `io.modelcontextprotocol/tasks` lifecycle on
|
|
@@ -291,7 +348,7 @@ taskRunner.on('job:failed', (job, error) => {
|
|
|
291
348
|
| Export | Description |
|
|
292
349
|
|--------|------------|
|
|
293
350
|
| `SmrtJob` | Persistent job record stored in `_smrt_jobs` |
|
|
294
|
-
| `SmrtJobCollection` | Collection with `claimReady()`, `listReady()`, `listByStatus()`, `stats()`, `cleanup()` |
|
|
351
|
+
| `SmrtJobCollection` | Collection with `enqueueJob()`, `enqueueHandlerJob()`, `claimReady()`, `listReady()`, `listByStatus()`, `stats()`, `cleanup()` |
|
|
295
352
|
| `SmrtJobEventCollection` | Durable telemetry plus explicit-tenant `listTerminalOutcomes()` safe projection |
|
|
296
353
|
| `JobBuilder` | Fluent API: `.delay()`, `.priority()`, `.retries()`, `.queue()`, `.timeout()`, `.enqueue()` |
|
|
297
354
|
| `JobHandle` | Track, wait, cancel, or retry an enqueued job |
|
|
@@ -308,6 +365,8 @@ the same queue without duplicate-claiming a pending row.
|
|
|
308
365
|
|--------|------------|
|
|
309
366
|
| `createTaskRunner(config?)` | Factory for creating a configured TaskRunner |
|
|
310
367
|
| `createScheduleRunner(config?)` | Factory for creating a configured ScheduleRunner |
|
|
368
|
+
| `registerJobHandler(name, handler)` / `unregisterJobHandler(name)` / `listJobHandlers()` | Process registry of named job handlers; closed while a TaskRunner runs |
|
|
369
|
+
| `jobHandlerTarget(name)` / `isJobHandlerTarget(objectType)` / `jobHandlerName(objectType)` | Stored `handler:<name>` target form |
|
|
311
370
|
| `withBackgroundJobs(Class)` | Mixin that adds `.bg()` and `.background()` to any SmrtObject class |
|
|
312
371
|
| `parseDelay(delay)` | Parse human-readable delay strings (`'5m'`, `'1h'`, `'30s'`) to milliseconds |
|
|
313
372
|
| `priorityToNumber(priority)` | Convert priority label (`'critical'`/`'high'`/`'normal'`/`'low'`) to number |
|
|
@@ -315,7 +374,7 @@ the same queue without duplicate-claiming a pending row.
|
|
|
315
374
|
|
|
316
375
|
### Key Types
|
|
317
376
|
|
|
318
|
-
`Priority`, `JobStatus`, `JobResult`, `WaitOptions`, `BgOptions`, `BackgroundCapable`, `TaskRunnerConfig`, `TaskRunnerEvents`, `ScheduleRunnerConfig`, `ScheduleRunnerEvents`, `ScheduleInfo`, `JobContext`, `TimeoutBehavior`, `SmrtJobData`, `ListReadyOptions`, `DurableJobPayloadSigner`, `DurableJobPayloadIntegrity`
|
|
377
|
+
`JobHandler`, `JobHandlerPayload`, `HandlerJobData`, `Priority`, `JobStatus`, `JobResult`, `WaitOptions`, `BgOptions`, `BackgroundCapable`, `TaskRunnerConfig`, `TaskRunnerEvents`, `ScheduleRunnerConfig`, `ScheduleRunnerEvents`, `ScheduleInfo`, `JobContext`, `TimeoutBehavior`, `SmrtJobData`, `ListReadyOptions`, `DurableJobPayloadSigner`, `DurableJobPayloadIntegrity`
|
|
319
378
|
|
|
320
379
|
## Dependencies
|
|
321
380
|
|
|
@@ -449,3 +508,82 @@ untouched and emits `schedule:blocked`; require the
|
|
|
449
508
|
`requiredOccurrenceIntegrity` capability before creating such schedules. See
|
|
450
509
|
[durable required admission](agents/scheduling.md#durable-required-admission-3346)
|
|
451
510
|
for the typed policy, authorized rotation and verification-key retention contract.
|
|
511
|
+
|
|
512
|
+
## Atomic application checkpoints
|
|
513
|
+
|
|
514
|
+
With `TaskRunner({ claimFencing: true })`, capture a handler's dispatch identity
|
|
515
|
+
with `getJobClaim(context)`. Inside your
|
|
516
|
+
application checkpoint transaction, call `await assertJobClaim(tx, claim)`
|
|
517
|
+
before writing through that same `tx`. The assertion locks the job row and
|
|
518
|
+
throws `JobClaimLostError` if its worker incarnation, attempt, tenant, target
|
|
519
|
+
or running status changed. Propagate the error so the whole transaction rolls
|
|
520
|
+
back. A fresh read of the job's current worker cannot identify an old handler.
|
|
521
|
+
|
|
522
|
+
After the original operation promise truly settles, use
|
|
523
|
+
`assertJobClaimForRelease(tx, claim)` in the transaction clearing an application
|
|
524
|
+
lease. It accepts that same running/completed/cancelled/failed attempt, but
|
|
525
|
+
rejects pending jobs, cleared recovery ownership and newer claims. It does not
|
|
526
|
+
clear a job claim or expire a runner's process lease. Park approval/stopped work
|
|
527
|
+
by returning from the handler; TaskRunner completes the job. Resume by admitting
|
|
528
|
+
another job after the prior one settles. Claim assertions prove ownership, not
|
|
529
|
+
application permission: hosts must still authorize the owner and tenant.
|
|
530
|
+
|
|
531
|
+
Dispatch fencing is opt-in: start `TaskRunner` with `claimFencing: true` to
|
|
532
|
+
use `getJobClaim`. Defaults retain their previous terminal/retry behavior and
|
|
533
|
+
claim timing. Public `retry()` and surplus release clear `started_at` as before.
|
|
534
|
+
The opted-in runner uses `max(now, previousWorkerDispatch + 1ms)` for each claim
|
|
535
|
+
batch, reserved before SQL on its DB/worker incarnation. A frozen/backward clock
|
|
536
|
+
never delays ready work. This logical start may be ahead of wall time; catch-up
|
|
537
|
+
has no bounded wall duration after an arbitrary clock step and does not gate
|
|
538
|
+
scheduling. `runAt` eligibility still uses the normal host clock.
|
|
539
|
+
|
|
540
|
+
The generation clock belongs to the worker incarnation, not the job row, so
|
|
541
|
+
legacy retry/release clearing `started_at` cannot reuse an opted-in worker's
|
|
542
|
+
claim. A process restart uses a new worker key. Direct `claimReady` users that
|
|
543
|
+
opt into `claimFencing` must use one DB handle and a unique worker incarnation
|
|
544
|
+
per process, consistently enabling fencing for that incarnation. Never share
|
|
545
|
+
worker keys across independent runners or alternate fenced/unfenced claims.
|
|
546
|
+
No schema changes are required.
|
|
547
|
+
|
|
548
|
+
During rolling deployments, old runners retain their existing semantics and
|
|
549
|
+
cannot supply the new authentic claim proof. New fenced handlers reject an
|
|
550
|
+
unfenced context before doing application work. Route handlers requiring proofs
|
|
551
|
+
to a dedicated queue consumed only by opted-in upgraded runners, or upgrade all
|
|
552
|
+
consumers of that queue before admitting such jobs. Existing ordinary jobs need
|
|
553
|
+
no change. Timestamp clearing by old code is safe for new proofs: a replacement
|
|
554
|
+
worker key differs, and an opted-in original incarnation's clock still advances.
|
|
555
|
+
|
|
556
|
+
Use `assertFailedJobDispatch(tx, dispatch)` to lock an exact failed dispatch
|
|
557
|
+
before checkpoint recovery and re-admission. It checks tenant, target, attempt
|
|
558
|
+
and the original worker/start generation and rejects a concurrent retry/reclaim. Use
|
|
559
|
+
the same caller transaction for the domain CAS and job admission.
|
|
560
|
+
|
|
561
|
+
`SmrtJobEventCollection.getTerminalOutcome(jobId, { tenantId, attempts?,
|
|
562
|
+
completedAt? })` reads the safe outcome for that exact job and completion,
|
|
563
|
+
without depending on the tenant feed's 1,000 candidates. Event retention still
|
|
564
|
+
applies, and callers must authorize the resource as well as supply its tenant.
|
|
565
|
+
|
|
566
|
+
`assertAbandonedJobClaim(tx, claim)` permits an application lease release only
|
|
567
|
+
for its persisted exact terminal dispatch when the original worker is neither
|
|
568
|
+
in the process live set nor holding a fresh worker lease. It uses TaskRunner's
|
|
569
|
+
liveness contract, not an application's timeout. A cancelled row alone never
|
|
570
|
+
proves settlement. Keep the application lease CAS in that same transaction.
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
PGlite support is opt-in: call `enablePgliteJobs(db)` before creating jobs
|
|
574
|
+
collections or starting a runner. It enables PostgreSQL claim/event SQL and
|
|
575
|
+
main-loop liveness renewal for that shared SDK client (including transactions).
|
|
576
|
+
Merely exposing `dumpDataDir` does not change engine selection. Existing hosts
|
|
577
|
+
that do not call this API retain their previous behavior. The isolated fixture
|
|
578
|
+
regression is enabled with `SMRT_TEST_PGLITE_MODULE`; it is not a full PGlite
|
|
579
|
+
backend certification of the jobs suite.
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
With `claimFencing: true`, stale recovery retains the original terminal job's
|
|
583
|
+
worker key instead of clearing it. `JobDispatch` includes that key so the
|
|
584
|
+
failed-dispatch assertion cannot match another worker at the same timestamp.
|
|
585
|
+
This does not retain/renew its process lease or make a failed job executable.
|
|
586
|
+
Default recovery still clears worker ownership. An old/unfenced recovery that
|
|
587
|
+
cleared the key cannot provide the new exact proof and fails closed. Settled
|
|
588
|
+
original handlers may release only their own unchanged application lease;
|
|
589
|
+
running-claim assertions always reject a terminal job.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Durable forge projections
|
|
2
|
+
|
|
3
|
+
`ForgeDeliveryCollection` owns the provider-neutral delivery inbox in
|
|
4
|
+
`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter
|
|
5
|
+
transitions and monotonic checkpoints in
|
|
6
|
+
`_smrt_forge_projection_checkpoints`.
|
|
7
|
+
|
|
8
|
+
- Inbox identity is `(tenant_id, provider, delivery_id)`.
|
|
9
|
+
- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or
|
|
10
|
+
`claimReady`) so each claims and dead-letters only its own deliveries;
|
|
11
|
+
unfiltered claims take every provider (smrt-commerce billing uses
|
|
12
|
+
`<name>-billing:<sellerTenantId>`, #3060).
|
|
13
|
+
- `claimReady` leases exactly one delivery; PostgreSQL uses the same
|
|
14
|
+
`MATERIALIZED` CTE claim as jobs (#3105).
|
|
15
|
+
- Tenant-facing accept/replay requires ambient tenant context. Worker claim is
|
|
16
|
+
cross-tenant, then runtime restores the captured context before observation.
|
|
17
|
+
Reads in the accept path go through the tenant-scoped collection (`list()`),
|
|
18
|
+
so intake works under the interceptor's `rawQueryPolicy: 'throw'` production
|
|
19
|
+
default without a bypass (#3100); keep new tenant-facing reads that way.
|
|
20
|
+
- Projection callbacks must write through `ForgeProjectionContext.db`; the
|
|
21
|
+
application projection, checkpoint, and inbox completion share one
|
|
22
|
+
transaction.
|
|
23
|
+
- Observation identity is tracker-independent
|
|
24
|
+
`(projection, subjectKey, version)`. Equal or older versions are acknowledged
|
|
25
|
+
without reapplying.
|
|
26
|
+
- Lease-token conditions guard every terminal/failure write. Expired final
|
|
27
|
+
attempts become replayable `dead_letter` rows, and persisted errors are
|
|
28
|
+
redacted.
|
|
29
|
+
- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit
|
|
30
|
+
tenant-scoped operator action.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Jobs claim and recovery contracts
|
|
2
|
+
|
|
3
|
+
## Transaction-bound claim proof
|
|
4
|
+
|
|
5
|
+
`getJobClaim(context)` returns an immutable dispatch-time identity from an
|
|
6
|
+
actual TaskRunner context (never infer its worker from a later row read).
|
|
7
|
+
`assertJobClaim(tx, claim)` locks and proves the same running job, worker,
|
|
8
|
+
attempt, tenant and target before application writes in that transaction.
|
|
9
|
+
`assertJobClaimForRelease(tx, claim)` also accepts the same terminal attempt,
|
|
10
|
+
allowing a settled handler to clear its application's lease after Stop. It
|
|
11
|
+
rejects pending jobs, cleared ownership and replacement claims. Neither function changes
|
|
12
|
+
job status nor expires the process lease. Return from the handler to park;
|
|
13
|
+
TaskRunner owns job completion. Use only after current host authorization.
|
|
14
|
+
|
|
15
|
+
Dispatch fencing is opt-in: start `TaskRunner` with `claimFencing: true` to
|
|
16
|
+
use `getJobClaim`. Defaults retain their previous terminal/retry behavior and
|
|
17
|
+
claim timing. Public `retry()` and surplus release clear `started_at` as before.
|
|
18
|
+
The opted-in runner uses `max(now, previousWorkerDispatch + 1ms)` for each claim
|
|
19
|
+
batch, reserved before SQL on its DB/worker incarnation. A frozen/backward clock
|
|
20
|
+
never delays ready work. This logical start may be ahead of wall time; catch-up
|
|
21
|
+
has no bounded wall duration after an arbitrary clock step and does not gate
|
|
22
|
+
scheduling. `runAt` eligibility still uses the normal host clock.
|
|
23
|
+
|
|
24
|
+
The generation clock belongs to the worker incarnation, not the job row, so
|
|
25
|
+
legacy retry/release clearing `started_at` cannot reuse an opted-in worker's
|
|
26
|
+
claim. A process restart uses a new worker key. Direct `claimReady` users that
|
|
27
|
+
opt into `claimFencing` must use one DB handle and a unique worker incarnation
|
|
28
|
+
per process, consistently enabling fencing for that incarnation. Never share
|
|
29
|
+
worker keys across independent runners or alternate fenced/unfenced claims.
|
|
30
|
+
No schema changes are required.
|
|
31
|
+
|
|
32
|
+
During rolling deployments, old runners retain their existing semantics and
|
|
33
|
+
cannot supply the new authentic claim proof. New fenced handlers reject an
|
|
34
|
+
unfenced context before doing application work. Route handlers requiring proofs
|
|
35
|
+
to a dedicated queue consumed only by opted-in upgraded runners, or upgrade all
|
|
36
|
+
consumers of that queue before admitting such jobs. Existing ordinary jobs need
|
|
37
|
+
no change. Timestamp clearing by old code is safe for new proofs: a replacement
|
|
38
|
+
worker key differs, and an opted-in original incarnation's clock still advances.
|
|
39
|
+
|
|
40
|
+
Use `assertFailedJobDispatch(tx, dispatch)` to lock an exact failed dispatch
|
|
41
|
+
before checkpoint recovery and re-admission. It checks tenant, target, attempt
|
|
42
|
+
and the original worker/start generation and rejects a concurrent retry/reclaim. Use
|
|
43
|
+
the same caller transaction for the domain CAS and job admission.
|
|
44
|
+
|
|
45
|
+
`SmrtJobEventCollection.getTerminalOutcome(jobId, { tenantId, attempts?,
|
|
46
|
+
completedAt? })` reads the safe outcome for that exact job and completion,
|
|
47
|
+
without depending on the tenant feed's 1,000 candidates. Event retention still
|
|
48
|
+
applies, and callers must authorize the resource as well as supply its tenant.
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
`assertAbandonedJobClaim(tx, claim)` permits an application lease release only
|
|
52
|
+
for its persisted exact terminal dispatch when the original worker is neither
|
|
53
|
+
in the process live set nor holding a fresh worker lease. It uses TaskRunner's
|
|
54
|
+
liveness contract, not an application's timeout. A cancelled row alone never
|
|
55
|
+
proves settlement. Keep the application lease CAS in that same transaction.
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
PGlite support is opt-in: call `enablePgliteJobs(db)` before creating jobs
|
|
59
|
+
collections or starting a runner. It enables PostgreSQL claim/event SQL and
|
|
60
|
+
main-loop liveness renewal for that shared SDK client (including transactions).
|
|
61
|
+
Merely exposing `dumpDataDir` does not change engine selection. Existing hosts
|
|
62
|
+
that do not call this API retain their previous behavior. The isolated fixture
|
|
63
|
+
regression is enabled with `SMRT_TEST_PGLITE_MODULE`; it is not a full PGlite
|
|
64
|
+
backend certification of the jobs suite.
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
Abandonment locks only the exact job row. Its process live-set and fresh-worker
|
|
68
|
+
lease reads are observations without a worker-row lock, matching TaskRunner
|
|
69
|
+
stale recovery. They do not serialize against a later lease renewal or prove
|
|
70
|
+
that an expired/suspended process has physically stopped. Keep domain writes
|
|
71
|
+
claim-fenced after re-admission and external effects idempotent; do not treat
|
|
72
|
+
this API as stronger process exclusion or physical cancellation.
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
With `claimFencing: true`, stale recovery retains the original terminal job's
|
|
76
|
+
worker key instead of clearing it. `JobDispatch` includes that key so the
|
|
77
|
+
failed-dispatch assertion cannot match another worker at the same timestamp.
|
|
78
|
+
This does not retain/renew its process lease or make a failed job executable.
|
|
79
|
+
Default recovery still clears worker ownership. An old/unfenced recovery that
|
|
80
|
+
cleared the key cannot provide the new exact proof and fails closed. Settled
|
|
81
|
+
original handlers may release only their own unchanged application lease;
|
|
82
|
+
running-claim assertions always reject a terminal job.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Job targets: model methods and named handlers (#5005)
|
|
2
|
+
|
|
3
|
+
A job targets **either** a model method (`objectType` = a registered class,
|
|
4
|
+
`method` = one of its methods; unchanged) **or** a handler registered under a
|
|
5
|
+
namespaced name. Nothing else.
|
|
6
|
+
|
|
7
|
+
## Contract
|
|
8
|
+
|
|
9
|
+
- `registerJobHandler(name, handler)`, `unregisterJobHandler(name)`,
|
|
10
|
+
`listJobHandlers()`. Names are `<package>:<name>`: an npm package name, a
|
|
11
|
+
colon, a lowercase kebab-case local name, optionally dotted
|
|
12
|
+
(`@happyvertical/smrt-workflows:workflow-run`). A bad name throws
|
|
13
|
+
`JobHandlerNameError`; a duplicate throws `JobHandlerAlreadyRegisteredError`.
|
|
14
|
+
- Handler: `(payload, context) => result`. `payload` is the job's JSON
|
|
15
|
+
`args`; `context` is the same runner `JobExecutionContext` a model method
|
|
16
|
+
gets (authentic, so `getJobClaim(context)` works under `claimFencing: true`),
|
|
17
|
+
with `context.job.handler` naming the handler. There is no per-job lease
|
|
18
|
+
hook: the lease is per worker and the runner renews it while handlers run.
|
|
19
|
+
- Enqueue: `SmrtJobCollection.enqueueHandlerJob({ handler, payload, ...job
|
|
20
|
+
options })`. The handler need not be registered in the producer process.
|
|
21
|
+
Tenancy, dedupe, cap, retry ceiling and transaction options are
|
|
22
|
+
`enqueueJob`'s.
|
|
23
|
+
|
|
24
|
+
## Storage (no schema change)
|
|
25
|
+
|
|
26
|
+
A handler job is an ordinary `_smrt_jobs` row in a reserved canonical form:
|
|
27
|
+
`object_type = 'handler:<name>'`, `method = 'handle'`, `object_id = NULL`,
|
|
28
|
+
`args` = payload, no MCP task columns, no runner-owned `_mcpTask`,
|
|
29
|
+
`_agentConfig` or `_schedule*` keys. `enqueueJob` refuses any other
|
|
30
|
+
`handler:`-prefixed row. The prefix is checked before `ObjectRegistry`;
|
|
31
|
+
`handler:@…` is not a qualified class name, so it never resolves to a model.
|
|
32
|
+
Claims, indexes, terminal events, `JobClaim`, `assertJobClaim`,
|
|
33
|
+
`assertFailedJobDispatch` and `assertAbandonedJobClaim` work on it unchanged.
|
|
34
|
+
|
|
35
|
+
## Registration before claim
|
|
36
|
+
|
|
37
|
+
`TaskRunner.start()` snapshots the registry and closes it before the first
|
|
38
|
+
claim; it reopens once every runner in the process has stopped. Registering
|
|
39
|
+
or unregistering while any runner runs throws
|
|
40
|
+
`JobHandlerRegistrationClosedError` naming the handler. A `start()` that
|
|
41
|
+
fails before claiming leaves it open. Register every handler at process
|
|
42
|
+
startup, before `runner.start()`. The registry is process-wide: re-evaluating
|
|
43
|
+
a registering module while a runner runs (HMR, a duplicate package instance)
|
|
44
|
+
throws.
|
|
45
|
+
|
|
46
|
+
## Claim filter
|
|
47
|
+
|
|
48
|
+
A runner claims model jobs and only the handler jobs it registered. The
|
|
49
|
+
claim adds one predicate inside the candidate select (before its `LIMIT`, so
|
|
50
|
+
rows a runner cannot run never fill its window):
|
|
51
|
+
|
|
52
|
+
```sql
|
|
53
|
+
NOT (substr(object_type, 1, 8) = 'handler:')
|
|
54
|
+
OR object_type IN ('handler:<name>', …) -- the start() snapshot
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The prefix test is case-exact and wildcard-free on SQLite, PostgreSQL and
|
|
58
|
+
PGlite (SQLite `LIKE` is case-insensitive; `_` is a wildcard). With no
|
|
59
|
+
handler registered only the `NOT (…)` half is emitted, so the runner claims
|
|
60
|
+
no handler row. Model claims are unchanged and keep `_smrt_jobs_ready_idx`.
|
|
61
|
+
`claimReady({ handlerNames })` is the option; omitted, a direct caller's
|
|
62
|
+
claim does not filter by target. Each name is one bound parameter, so a
|
|
63
|
+
process may register at most `MAX_JOB_HANDLERS` (256) handlers
|
|
64
|
+
(`JobHandlerLimitError`); `claimReady` refuses more names (`RangeError`).
|
|
65
|
+
|
|
66
|
+
## Unclaimed deadline
|
|
67
|
+
|
|
68
|
+
A handler job still `pending` more than `handlerUnclaimedDeadlineMs` (runner
|
|
69
|
+
option, 1 ms to 10 years, default 24 h) after its `run_at` is failed with
|
|
70
|
+
failure kind `handler-unclaimed` and its terminal event; it never ran
|
|
71
|
+
(`attempts` as left). Every runner sweeps, from its poll, at most once per
|
|
72
|
+
1% of the deadline (between one lease tick and 15 min; about 14 min at the
|
|
73
|
+
default) and `HANDLER_UNCLAIMED_SWEEP_LIMIT` (100) rows per sweep (a full
|
|
74
|
+
batch sweeps again on the next poll), over its own queues and tenant scope,
|
|
75
|
+
leaving out the handlers it registered (`object_type NOT IN`, at most
|
|
76
|
+
`MAX_JOB_HANDLERS` bound parameters): it claims those, so an overdue backlog
|
|
77
|
+
it serves (a saturated queue, a fleet back after a day down) is run, not
|
|
78
|
+
failed. The runner emits `job:unclaimed` (not `job:failed`: it never
|
|
79
|
+
claimed the job) besides the persisted terminal event. Residual: while every
|
|
80
|
+
runner serving a handler is down past the deadline, a runner in the same
|
|
81
|
+
queue without that handler still fails its jobs; keep such runners out of
|
|
82
|
+
the queue, or raise the deadline, when that matters. `SmrtJob.retry()` on a handler job restarts its deadline (`run_at`
|
|
83
|
+
moves to now when it was in the past). Each row is one conditional
|
|
84
|
+
transition (`status = 'pending'` and `run_at` still past the cutoff), so
|
|
85
|
+
concurrent sweepers, a claim or a requeue win harmlessly: one event per job.
|
|
86
|
+
Model jobs are never swept. A queue no upgraded runner consumes is never
|
|
87
|
+
swept. With different deadlines in a fleet the shortest wins. A sweep
|
|
88
|
+
failure is a `runner:error`; the poll still claims.
|
|
89
|
+
|
|
90
|
+
## Outcomes
|
|
91
|
+
|
|
92
|
+
Handler jobs share the model path for MCP authority (checked first, so a
|
|
93
|
+
handler cannot bypass it), tenant context, timeout, cancellation, claim
|
|
94
|
+
fencing, retries and every terminal write. Differences:
|
|
95
|
+
|
|
96
|
+
- Unregistered on the claiming runner (a claim made without the filter; the
|
|
97
|
+
backstop): `JobHandlerUnregisteredError` (`retryable: false`) ends the job
|
|
98
|
+
`failed` on that claim whatever its `maxAttempts`, failure kind
|
|
99
|
+
`handler-unregistered`, with its terminal event.
|
|
100
|
+
- Unclaimed past the deadline: failure kind `handler-unclaimed` (above).
|
|
101
|
+
- A non-canonical `handler:` row (wrong method, an object id, an MCP task
|
|
102
|
+
id, owner or marker), written past `enqueueJob`, fails
|
|
103
|
+
terminally (`JobHandlerTargetError`, kind `execution`) after the authority
|
|
104
|
+
check, without running a handler. MCP tasks target model methods only.
|
|
105
|
+
- Schedules cannot target handlers: a schedule naming one is set to
|
|
106
|
+
`status = 'error'`.
|
|
107
|
+
|
|
108
|
+
## Upgrade order (older runners)
|
|
109
|
+
|
|
110
|
+
A runner older than #5005 does not filter: it claims `handler:<name>` as an
|
|
111
|
+
unknown model (`Unknown object type`, kind `execution`), retries it up to
|
|
112
|
+
`maxAttempts` (clamped to 25), then fails it. An older outcome reader drops
|
|
113
|
+
events with kind `handler-unregistered` or `handler-unclaimed`. Do not
|
|
114
|
+
enqueue handler jobs until every runner and outcome reader on the database
|
|
115
|
+
is upgraded.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Retry SDK loading
|
|
2
|
+
|
|
3
|
+
`JobBuilder` does not import `@happyvertical/jobs` while a builder is created or
|
|
4
|
+
configured. `enqueue()` resolves the default exponential strategy on demand;
|
|
5
|
+
a supplied strategy keeps its original `toConfig()` behavior without loading
|
|
6
|
+
the SDK. The runner resolves `fromConfig` only while handling a retryable job
|
|
7
|
+
failure, after the existing MCP-suspension early return.
|
|
8
|
+
|
|
9
|
+
Keep the SDK's strategy implementation authoritative. Do not copy retry math
|
|
10
|
+
or load private hashed SDK chunks to avoid its provider barrel. The installed
|
|
11
|
+
SDK's root statically exports queue adapters; a public provider-neutral retry
|
|
12
|
+
entrypoint or lazy adapter factory is the upstream boundary needed to avoid
|
|
13
|
+
those modules on first default-strategy use. Dynamic import rejections propagate
|
|
14
|
+
unchanged; they are not converted into a fallback strategy.
|
|
15
|
+
|
|
16
|
+
`src/__tests__/job-builder.test.ts` guards zero SDK loads before enqueue and for
|
|
17
|
+
custom strategies, then checks the first default enqueue against the SDK's own
|
|
18
|
+
exponential configuration. Full runner tests cover persisted retry decisions,
|
|
19
|
+
hints, timeouts, ownership and terminal outcomes.
|