@happyvertical/smrt-jobs 0.60.13 → 0.60.15

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 CHANGED
@@ -20,6 +20,14 @@ Status: `pending → running → completed/failed/cancelled`.
20
20
 
21
21
  Polling-based execution engine. Config: `concurrency` (5), `pollInterval` (1s), `idlePollInterval` (defaults to 20× `pollInterval`), `heartbeatInterval` (30s, telemetry only), `leaseTtlMs` (30s), `leaseTickMs` (10s), `shutdownTimeout` (30s). Empty claims back off exponentially to `idlePollInterval`; any claimed work, capacity pressure, or poll error resets to `pollInterval`. Every delay is capped at the effective worker lease TTL, including an oversized base interval; recovery sweep spacing stays TTL-bounded (plus query/event-loop time). Polling intervals must be finite positive milliseconds within the Node timer range. `stop()` waits (within `shutdownTimeout`) for an in-flight poll as well as active jobs; a poll that resumes after `stop()` began returns before claiming, and over-claimed rows are released both before and after the drain (#3148).
22
22
 
23
+ Optional `tenantIds` scopes both atomic ready claims and orphan recovery before
24
+ ownership or terminal-state writes (`undefined` means all; `[]` means none;
25
+ `null` includes global jobs). Recovery also respects configured queues. Scoped
26
+ runners default `retention` to `false`, since the system-wide maintenance sweep
27
+ has no tenant filter; opt into that sweep only in an authorized maintenance host.
28
+ `ClaimReadyOptions` and `ListReadyOptions` accept the same tenant scope. Queue
29
+ lease advertising remains queue-level; it does not prove per-tenant availability.
30
+
23
31
  1. `start()` 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
24
32
  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
25
33
  3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`
@@ -61,7 +69,7 @@ Handlers receive `context.signal`, a plain `AbortSignal` (pass it to `fetch` or
61
69
 
62
70
  Cooperative only: aborting changes no lifecycle state, retry policy, terminal-write guard or event. A handler that ignores the signal behaves exactly as before; one that rejects with the abort reason cannot overwrite `cancelled`/`failed` (the `WHERE worker_id=? AND status='running'` guard drops its terminal write). Not aborted on runner shutdown. `isRunnerExecutionContext` and MCP-task invocations are unchanged; they receive the same `signal`.
63
71
 
64
- **Why no dedup key / usage record here:** a caller dedup key and per-attempt usage live in `smrt-education` (generation jobs are unique on `(tenant_id, request_key)` with replay; generation usage records hold input/output tokens, cost and `usageJson`). Jobs only owns execution and cancellation.
72
+ **Domain request identity / usage:** `smrt-education` still owns generation request replay and per-attempt usage. The generic store dedupe key below only reserves one nonterminal job; it never replaces domain idempotency or usage records.
65
73
 
66
74
  ## Worker liveness & recovery (#1474)
67
75
 
@@ -76,11 +84,10 @@ Recovery keys on **worker-process liveness**, never per-job heartbeat freshness
76
84
 
77
85
  ## ScheduleRunner
78
86
 
79
- Polls `_smrt_agent_schedules` every 60s for due entries. Creates SmrtJob with `queue='agents'`, `priority=75`. Wires to TaskRunner events for completion/failure tracking. Slot reconciliation keys on worker liveness (it has no in-process active-job set, so the lease/live-set is its whole mechanism).
80
-
81
- The job is enqueued **before** `next_run` is advanced and `running_count` is incremented: a transient enqueue failure (tenant-cap hit, DB blip) therefore leaves `next_run` and `status='active'` untouched so the same due slot is retried on the next poll, rather than losing the slot and disabling the schedule.
82
-
83
- `next_run` is always recomputed from *now*, never from the previous `next_run` — this is **fire-once-forward**: runs that came due while the runner was down are not caught up, only the next future occurrence fires. There is no missed-run backfill.
87
+ Transactional schedule admission, tenant/type scopes, dedicated queues,
88
+ occurrence metadata, retry/slot semantics, graceful drain, and tenant-partitioned
89
+ nonterminal job keys are documented in [safe scheduling](agents/scheduling.md).
90
+ Run `smrt db:migrate` before using the new job provenance and dedupe-slot schema.
84
91
 
85
92
  Custom cron parser (`getNextCronDate(cron, timezone?)`): 5-field (minute hour dom month dow); `*`, ranges, lists, steps supported, each list term matched on its own. Fields match the wall clock of the schedule's IANA `timezone` (`Intl.DateTimeFormat`, DST-correct, no dependency); the re-arm passes the row's `timezone`, and a NULL/blank zone falls back to the column default `UTC`. Unknown zones throw `Invalid cron timezone`; the runner moves a row whose cron or zone is invalid to `status='error'` with `last_error`, since retrying it every poll cannot succeed. Only an omitted argument uses the host process zone (legacy; `smrt-reports` still relies on it). DST follows Vixie cron: fixed-time crons (no `*` in minute or hour) run once per day, a gap-skipped wall time runs shifted forward by the gap, a repeated one only at its first occurrence; wildcard crons follow elapsed time (gap minutes skipped, the repeated hour runs again) (#3859).
86
93
 
package/README.md CHANGED
@@ -196,6 +196,66 @@ The `ScheduleRunner` polls the `_smrt_agent_schedules` table for due cron entrie
196
196
 
197
197
  Upgrade note: rows that relied on the old behaviour shift. A row left at the default `timezone = 'UTC'` on a non-UTC host now fires in UTC, and day-of-month or month `*/n` now matches 1, 1+n, … (for example `0 0 */2 * *` runs on odd days) instead of counting from 0.
198
198
 
199
+ Admission rechecks the current row under a database lock, and enqueues the job
200
+ and advances `next_run` in one transaction. Multiple scheduler processes admit
201
+ one job per due occurrence. An enqueue failure rolls back the slot so the next
202
+ poll can retry. Pending jobs and delayed retries occupy `maxConcurrent` capacity.
203
+ TaskRunner owns job crash recovery; schedule reconciliation never independently
204
+ fails a worker-owned job.
205
+
206
+ The handler receives `_scheduledFor`, the original due slot as a UTC ISO instant.
207
+ This is **fire-once-forward**: after one overdue occurrence the runner arms the
208
+ next future cron time; it does not backfill every missed slot. Keep domain
209
+ request replay and current authorization in the handler. Reserved occurrence
210
+ arguments cannot be set in `method_args`.
211
+
212
+ Optional `agentTypes` and `tenantIds` limit selection, reconciliation and claim
213
+ (`[]` selects none); `queue` chooses the output queue (default `agents`). Use
214
+ exact scopes and a dedicated task-worker queue for an application-specific host.
215
+ Use the same optional `tenantIds` scope on `TaskRunner`: ready claims and orphan
216
+ recovery filter before changing ownership or terminal state, and recovery also
217
+ honors configured queues. Explicit empty scopes process nothing. A tenant-scoped
218
+ TaskRunner defaults to `retention: false`, because the normal retention sweep is
219
+ system-wide maintenance. Worker queue advertising remains queue-level and does
220
+ not assert per-tenant availability.
221
+
222
+ For handlers that require proof of admission, pass a trusted host
223
+ `occurrenceSigner` to ScheduleRunner and require its `occurrenceIntegrity`
224
+ capability. The runner signs the exact job ID, tenant, schedule, UTC period,
225
+ execution target and full args inside the enqueue transaction, saving reserved
226
+ `_scheduleAdmission` metadata before commit. `verifyScheduleAdmission(job, signer)`
227
+ fails closed on copied or changed job/period/tenant/args and missing signatures;
228
+ `getScheduleAdmissionPayload(job, keyId)` only builds the pure signature payload.
229
+ Unsigned legacy runners remain supported, so protected handlers must explicitly
230
+ verify the persisted row. Exact job retries preserve their signature. A trusted
231
+ keyring may retain old verification keys while minting with a current key; unknown
232
+ or retired keys deny. Signature verification complements current authority and
233
+ normal database claims/idempotency. See [the full admission integrity contract](agents/scheduling.md#exact-occurrence-integrity).
234
+
235
+ Stop the scheduler before draining the TaskRunner: `await scheduleRunner.stop()`
236
+ waits for its in-flight admission transaction.
237
+
238
+ `SmrtJobCollection.enqueueJob` also accepts a tenant-partitioned `dedupeKey`
239
+ (nonblank, at most 512 characters). Concurrent enqueues return the same
240
+ pending/running job unchanged. Once terminal, a new job may reserve the key;
241
+ retrying an older job refuses if a newer one reserves it. This prevents overlapping
242
+ nonterminal jobs for a caller-defined resource, rather than permanent request
243
+ replay. JavaScript timeout cannot preempt an orphan handler's side effects.
244
+ Use `{ transaction: tx }` as the second argument to join a caller-owned
245
+ transaction without nesting (required on DuckDB). Propagate failures and commit
246
+ or roll back that transaction. Run `smrt db:migrate` before upgrading workers:
247
+ the nullable job provenance field and package-owned `_smrt_job_dedupe_slots`
248
+ model are additive schema changes. Key slots retain one pointer per distinct key;
249
+ use stable resource keys rather than one-shot request tokens.
250
+
251
+ Keyed UUID tenant identities must use canonical lowercase hyphenated spelling,
252
+ including ambient context; alternate valid UUID spellings fail before writes.
253
+ Opaque non-UUID IDs retain exact case. `job.retry()` re-reads stored identity and
254
+ args, locks schedule→key→job, and enforces schedule capacity before resetting
255
+ lifecycle fields. It preserves args/signatures and refreshes the model revision.
256
+ Use `retry({ transaction: tx })` to join a caller transaction without nesting and
257
+ propagate failures/roll back. See the [retry capacity and lock-order contract](agents/scheduling.md#public-retry-capacity-and-lock-order).
258
+
199
259
  Wire them together via events:
200
260
 
201
261
  ```typescript
@@ -221,6 +281,7 @@ taskRunner.on('job:failed', (job, error) => {
221
281
  | Table | Purpose |
222
282
  |-------|---------|
223
283
  | `_smrt_jobs` | Persistent job queue (SmrtJob records) |
284
+ | `_smrt_job_dedupe_slots` | Tenant-partitioned nonterminal job-key serialization |
224
285
  | `_smrt_agent_schedules` | Cron schedule entries polled by ScheduleRunner |
225
286
 
226
287
  ## API
@@ -381,3 +442,10 @@ values before any awaited enqueue work. Extra caller fields are not persisted,
381
442
  and later mutation of the caller's binding cannot change the durable review
382
443
  reference. Live authorization still checks the saved reference at execution
383
444
  and resume; the snapshot never grants approval.
445
+
446
+ Protected schedules can require a durable exact queue/signing-key policy through
447
+ `methodArgs._scheduleAdmissionPolicy`. An unsigned/default runner leaves them
448
+ untouched and emits `schedule:blocked`; require the
449
+ `requiredOccurrenceIntegrity` capability before creating such schedules. See
450
+ [durable required admission](agents/scheduling.md#durable-required-admission-3346)
451
+ for the typed policy, authorized rotation and verification-key retention contract.