@happyvertical/smrt-jobs 0.61.6 → 0.62.1
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 +12 -30
- 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-CB6-XwRQ.js → runner-DDOMVWpW.js} +906 -484
- package/dist/chunks/runner-DDOMVWpW.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 +81 -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 +11 -10
- package/dist/chunks/runner-CB6-XwRQ.js.map +0 -1
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# Safe scheduling and job deduplication
|
|
2
|
+
|
|
3
|
+
Polls `_smrt_agent_schedules` every 60s. Due selection and the transactional
|
|
4
|
+
claim both apply optional `agentTypes` and `tenantIds` scopes (`[]` admits none;
|
|
5
|
+
`undefined` preserves system-wide operation). `queue` defaults to `agents`.
|
|
6
|
+
Configure a dedicated task-worker queue and exact scopes for a host that must
|
|
7
|
+
only run its own scheduled operation.
|
|
8
|
+
|
|
9
|
+
Admission locks and re-reads the authoritative schedule row, rechecks enabled /
|
|
10
|
+
active / due occurrence / capacity, then inserts the job and advances `next_run`
|
|
11
|
+
in the same transaction. Competing runners cannot consume the same occurrence.
|
|
12
|
+
A failed enqueue or process crash before commit rolls everything back; the next
|
|
13
|
+
poll can retry the unchanged due slot. After commit the durable job belongs to
|
|
14
|
+
TaskRunner's existing lease/retry/terminal recovery contract. ScheduleRunner
|
|
15
|
+
never independently fails a TaskRunner-owned job. Pending jobs (including delayed
|
|
16
|
+
retries) and running jobs both occupy `maxConcurrent` slots. Reconciliation takes
|
|
17
|
+
the same schedule-row lock, so a stale count cannot erase a new admission.
|
|
18
|
+
|
|
19
|
+
`args._scheduledFor` is the admitted original `next_run` as a UTC ISO instant,
|
|
20
|
+
retained across task attempts and passed to the handler. `_scheduleId` remains
|
|
21
|
+
internal metadata; neither field grants authority. `method_args` may not supply
|
|
22
|
+
`_scheduledFor`, `_scheduleId`, or `_agentConfig`. The handler must resolve current
|
|
23
|
+
authority and implement domain idempotency. `stop()` prevents new admissions and
|
|
24
|
+
waits for the in-flight poll/transaction before resolving; stop the scheduler
|
|
25
|
+
before draining its TaskRunner.
|
|
26
|
+
|
|
27
|
+
`next_run` is recomputed from *now*, never from the previous slot: this is
|
|
28
|
+
**fire-once-forward**. One overdue occurrence is admitted, then the next future
|
|
29
|
+
zoned cron time is armed. There is no missed-run backfill. One admission per
|
|
30
|
+
occurrence differs from no overlapping executions: `maxConcurrent = 1` prevents
|
|
31
|
+
multiple pending/running jobs for that schedule; a job dedupe key can serialize
|
|
32
|
+
a broader caller-defined resource. Neither promise preempts an orphaned timed-out
|
|
33
|
+
handler (see the at-least-once contract above).
|
|
34
|
+
|
|
35
|
+
### Store deduplication (#2994)
|
|
36
|
+
|
|
37
|
+
`SmrtJobCollection.enqueueJob({ ..., dedupeKey })` reserves at most one
|
|
38
|
+
pending/running job per effective tenant and nonblank key (at most 512 chars).
|
|
39
|
+
Concurrent calls return the existing job unchanged, even if the later arguments
|
|
40
|
+
differ. Terminal completion/failure/cancellation permits the next enqueue.
|
|
41
|
+
Ordinary retry delays retain the reservation; manual retry of an older terminal
|
|
42
|
+
job refuses while a newer job reserves its key. This is in-flight suppression,
|
|
43
|
+
not permanent occurrence/request replay or an authorization boundary.
|
|
44
|
+
|
|
45
|
+
The registered `_smrt_job_dedupe_slots` model owns the database uniqueness and
|
|
46
|
+
row lock; the opaque hash partitions keys by tenant, including global NULL.
|
|
47
|
+
The nullable indexed `SmrtJob.dedupeKey` retains provenance. Migrate before using
|
|
48
|
+
upgraded workers (`smrt db:migrate`); no partial-index dependency on DuckDB.
|
|
49
|
+
Slots retain one pointer per distinct key, including after terminal-job retention
|
|
50
|
+
prunes the referenced row. Use stable resource keys rather than one-shot tokens.
|
|
51
|
+
Generated slot API/CLI/MCP access is disabled. Callers must use `enqueueJob` and
|
|
52
|
+
public retry/cancel APIs; direct model/SQL lifecycle writes bypass store guards.
|
|
53
|
+
|
|
54
|
+
`enqueueJob(data, { transaction: tx })` uses an existing caller-owned transaction
|
|
55
|
+
for every read/write and opens no nested transaction (DuckDB has no savepoints).
|
|
56
|
+
The caller must propagate failures and commit/roll back `tx`. Without that option
|
|
57
|
+
a keyed enqueue opens its own transaction. Returned models use the caller's
|
|
58
|
+
connection, never an ended internal transaction. Enqueue persists once; a second
|
|
59
|
+
save must never race a consumer's first claim.
|
|
60
|
+
|
|
61
|
+
## Exact occurrence integrity
|
|
62
|
+
|
|
63
|
+
A trusted host can opt into `ScheduleRunnerConfig.occurrenceSigner` using a
|
|
64
|
+
`DurableJobPayloadSigner`; omitted or `null` preserves legacy unsigned runners.
|
|
65
|
+
The host configuration is the only source of that signer, never schedule or job
|
|
66
|
+
arguments. `ScheduleRunner.capabilities.occurrenceIntegrity` lets hosts reject an
|
|
67
|
+
older runtime before enabling schedules that require this contract.
|
|
68
|
+
|
|
69
|
+
During the same atomic occurrence transaction, after the real job ID exists,
|
|
70
|
+
the runner signs and saves `args._scheduleAdmission` before commit. A signer,
|
|
71
|
+
verification, or protected-save failure rolls back both job and consumed slot.
|
|
72
|
+
There is no post-commit signing/save or visible unsigned protected job. Row
|
|
73
|
+
`method_args` cannot supply the reserved `_scheduleAdmission` name.
|
|
74
|
+
|
|
75
|
+
The exact envelope is `{ purpose: 'smrt.schedule-admission', version: 1, keyId,
|
|
76
|
+
jobId, tenantId, scheduleId, scheduledFor, queue, objectType, objectId, method,
|
|
77
|
+
args }`. The args snapshot uses the existing signer's canonical persisted JSON
|
|
78
|
+
representation and excludes **only** top-level `_scheduleAdmission`; static
|
|
79
|
+
consent, constructor config and all other arguments remain bound. Metadata is
|
|
80
|
+
exactly `{ version: 1, keyId, signature }`. The tenant is explicit (`null` for
|
|
81
|
+
global); occurrence time must be a canonical UTC ISO instant.
|
|
82
|
+
|
|
83
|
+
`getScheduleAdmissionPayload(job, keyId)` is a pure payload builder, not a signer
|
|
84
|
+
or public minting endpoint. `verifyScheduleAdmission(job, signer)` returns false
|
|
85
|
+
on missing/unknown/malformed metadata, unknown/retired keys, tampered arguments,
|
|
86
|
+
or a copied signature on a different job, period, schedule, tenant or execution
|
|
87
|
+
target. Handlers requiring protected admission must verify the authoritative job
|
|
88
|
+
row even if a legacy unsigned runner could enqueue it. Actual worker execution
|
|
89
|
+
alone does not prove scheduler admission.
|
|
90
|
+
|
|
91
|
+
Legitimate retries preserve the same job ID, args and signature; lifecycle fields
|
|
92
|
+
are excluded. For key rotation a trusted keyring can mint with its current
|
|
93
|
+
`keyId` while retaining older verification keys for existing jobs. Retiring an old
|
|
94
|
+
key denies those retries until an explicit host reconciliation policy resolves
|
|
95
|
+
it. Never put keys in arguments or logs. This signature proves admitted identity,
|
|
96
|
+
not current actor grants, policy, database uniqueness, handler exactly-once
|
|
97
|
+
execution, or safety against trusted code that holds a signing key. Hosts must
|
|
98
|
+
still recheck current authority and use normal claims/domain idempotency.
|
|
99
|
+
|
|
100
|
+
## Public retry capacity and lock order
|
|
101
|
+
|
|
102
|
+
`job.retry()` reads canonical persisted tenant, schedule association, key and
|
|
103
|
+
arguments. Caller-edited model fields cannot choose another schedule/key or
|
|
104
|
+
rewrite business arguments/signatures. It validates current tenant ownership
|
|
105
|
+
before taking write locks, then locks **schedule → dedupe slot → job** in one
|
|
106
|
+
transaction. Admission and reconciliation use the same physical schedule row and
|
|
107
|
+
pending/running count. A pending retry's own slot is excluded; other pending,
|
|
108
|
+
delayed-retry and running occurrences count toward `maxConcurrent`, including
|
|
109
|
+
values greater than 1. Full capacity denies without resetting attempts, changing
|
|
110
|
+
status or reassigning the key. A later retry can proceed once a slot is free.
|
|
111
|
+
Running/completed jobs cannot be retried. Missing/foreign/malformed persisted
|
|
112
|
+
canonical occurrence associations fail closed.
|
|
113
|
+
|
|
114
|
+
`_scheduleId` alone is compatibility metadata shared by independent producers,
|
|
115
|
+
not an AgentSchedule discriminator. Persisted `_scheduledFor` or
|
|
116
|
+
`_scheduleAdmission` marks a canonical agent occurrence and requires its
|
|
117
|
+
same-tenant schedule even if that schedule's target was later reconfigured.
|
|
118
|
+
A legacy job without those markers occupies agent capacity only when its stored
|
|
119
|
+
execution type/object ID/method matches the actual same-tenant AgentSchedule.
|
|
120
|
+
Other producer metadata neither requires an agent table nor changes an unrelated
|
|
121
|
+
schedule, including a coincident ID. Table availability is checked portably on
|
|
122
|
+
the caller executor before SQL, without catching a missing-table error inside
|
|
123
|
+
an already-aborted PostgreSQL transaction. Admission/reconciliation count marked
|
|
124
|
+
prior occurrences across target reconfiguration and matching legacy agent jobs,
|
|
125
|
+
not unrelated producers' same-named metadata. Retry rechecks the canonical stored
|
|
126
|
+
arguments, tenant, target and association after its locks before lifecycle writes.
|
|
127
|
+
|
|
128
|
+
The transition changes lifecycle fields only, then hydrates the authoritative
|
|
129
|
+
row/revision back into the model, including keyed retries. It preserves the exact
|
|
130
|
+
stored args and signature. `retry({ transaction: tx })` joins an existing caller
|
|
131
|
+
transaction without nesting (DuckDB has no savepoints); the caller must propagate
|
|
132
|
+
errors and roll back on failure. That caller must not acquire lower-order locks
|
|
133
|
+
before this API. Completion's job transaction commits before its separate schedule
|
|
134
|
+
callback, so it never holds a job lock while waiting for a schedule lock. Automatic
|
|
135
|
+
handler retry keeps its existing nonterminal slot; no new admission is made.
|
|
136
|
+
This remains a nonterminal-row concurrency guarantee, not preemption of an orphan
|
|
137
|
+
JavaScript handler or a substitute for handler authority/idempotency.
|
|
138
|
+
|
|
139
|
+
Keyed enqueue requires canonical lowercase hyphenated UUID tenant identities,
|
|
140
|
+
including ambient context. Valid alternate UUID spellings (uppercase, braces or
|
|
141
|
+
compact form) fail before any slot/job write; load the canonical tenant identity
|
|
142
|
+
first. This prevents native PostgreSQL/DuckDB UUID hydration from changing the
|
|
143
|
+
identity used to hash a slot. Opaque non-UUID tenant strings remain exact and case
|
|
144
|
+
sensitive; no global case folding or relaxed tenant guard is applied. Nonkeyed
|
|
145
|
+
legacy enqueue behavior is unchanged. The keyed API is unreleased: private
|
|
146
|
+
uppercase development fixtures are not an existing-public-data migration case.
|
|
147
|
+
|
|
148
|
+
## Durable required admission (#3346)
|
|
149
|
+
|
|
150
|
+
A schedule that must never be consumed by an unsigned or differently routed host
|
|
151
|
+
persists this public requirement in `AgentSchedule.methodArgs`:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const policy: ScheduleAdmissionPolicy = {
|
|
155
|
+
version: 1,
|
|
156
|
+
requireIntegrity: true,
|
|
157
|
+
queue: 'protected-agents',
|
|
158
|
+
keyId: 'current-host-key',
|
|
159
|
+
};
|
|
160
|
+
schedule.methodArgs = { ...consentedArguments, _scheduleAdmissionPolicy: policy };
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`getScheduleAdmissionPolicy(args)` returns a validated copy, or `null` only when
|
|
164
|
+
absent. A present malformed/unknown policy blocks. `ScheduleRunner` requires a
|
|
165
|
+
trusted `occurrenceSigner` whose current `keyId` matches and the exact `queue`.
|
|
166
|
+
It checks before reconciliation/claim writes and again under the occurrence
|
|
167
|
+
lock. A blocked schedule keeps its due time, counts, errors and jobs unchanged;
|
|
168
|
+
`schedule:blocked` emits only `{ scheduleId, reason }` with a bounded reason code
|
|
169
|
+
(`INVALID_ADMISSION_POLICY`, `MISSING_OCCURRENCE_SIGNER`, `WRONG_OCCURRENCE_KEY`,
|
|
170
|
+
`WRONG_OCCURRENCE_QUEUE`). This diagnostic is not persisted on the schedule.
|
|
171
|
+
Hosts must require both `ScheduleRunner.capabilities.requiredOccurrenceIntegrity`
|
|
172
|
+
and `AgentSchedule.capabilities.requiredAdmissionPolicy`, plus the public
|
|
173
|
+
`AgentSchedule.prototype.reconfigureAdmissionPolicy` method, before enabling
|
|
174
|
+
protected schedules. New jobs with old agents is an unsupported mixed cohort.
|
|
175
|
+
Absent policy retains legacy unsigned scheduling behavior. Full immutable job
|
|
176
|
+
arguments, including this policy, participate in admission signing. Verification
|
|
177
|
+
also rejects a policy inconsistent with the signed job queue or signature key.
|
|
178
|
+
|
|
179
|
+
Ordinary public `AgentSchedule.save()`/generated updates cannot remove or replace
|
|
180
|
+
an existing policy through mutated arguments, including fresh-object natural-key
|
|
181
|
+
upserts. An agents-owned mandatory write predicate binds the canonical stored
|
|
182
|
+
JSON; late collisions fail closed and callers reload/retry. This uses core's
|
|
183
|
+
public `GlobalInterceptors.writeGuard` seam without replacing tenant predicates.
|
|
184
|
+
Ordinary sequential same-policy and unprotected upserts keep their existing API.
|
|
185
|
+
|
|
186
|
+
A trusted host explicitly rotates/removes policy through the loaded model's
|
|
187
|
+
`reconfigureAdmissionPolicy(nextPolicyOrNull, { authorize: async context => ... })`.
|
|
188
|
+
The callback must check the **current** authenticated operator/tenant permission;
|
|
189
|
+
its context contains persisted schedule ID/tenant and previous/next policy.
|
|
190
|
+
Throwing denies without a write. Generated CRUD never supplies this callback.
|
|
191
|
+
Current tenant ownership and normal loaded revision CAS still apply. The same
|
|
192
|
+
instance must not be concurrently saved/rebound during this operation. This is
|
|
193
|
+
an explicit authorization boundary, not a serialized bypass flag.
|
|
194
|
+
|
|
195
|
+
For rotation, first retain old verification keys in the trusted keyring while
|
|
196
|
+
selecting a new current minting key, then authorize the durable policy key change.
|
|
197
|
+
Existing jobs retain their original exact arguments/signature on retry; unknown
|
|
198
|
+
or retired verification keys deny. Integrity does not replace current authority,
|
|
199
|
+
job/schedule locking or downstream command idempotency. Code holding trusted keys
|
|
200
|
+
and authorization callbacks remains trusted; this does not defend against it.
|
|
201
|
+
|
|
202
|
+
Owning focused tests cover SQLite and native DuckDB policy blocking, locked
|
|
203
|
+
recheck, exact protected retry/rotation, public save/CAS and late collision.
|
|
204
|
+
`packages/jobs/src/__tests__/retry-admission-postgres.optional.test.ts` additionally
|
|
205
|
+
covers real separate-connection retry/admission commit and rollback with signature
|
|
206
|
+
preservation. Coordinator integration owns PostgreSQL and the complete gates.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
# Off-loop worker liveness ticker (#1474, #4978)
|
|
2
|
+
|
|
3
|
+
**Off-loop ticker** (`worker-liveness-ticker.ts` + `worker-liveness-thread.ts`): `start()` spawns a `node:worker_threads` ticker that renews the lease on its own thread, so a CPU-bound synchronous handler on the main loop can't starve it, but only when a second connection on the **same engine** as the runtime's is available (`planLivenessConnection()`, #4978). PostgreSQL: the thread builds its own `max: 1` pool from the URL, as before. File-backed SQLite: the thread opens `db.reopenOptions()` (never `{ url, type }`), checks that its connection's `engine` equals the engine the runner reported (`db.engine`), and applies `PRAGMA busy_timeout` itself (a reopened connection inherits no PRAGMAs; `SQLITE_BUSY_TIMEOUT_MS` from `@happyvertical/smrt-core`, the same 5000 the local runtime uses; `synchronous` already defaults to FULL on both engines). `start()` sets the runner connection's timeout only when none is set, so a shared collection connection keeps its shorter 250 ms main-thread wait. `node:sqlite` and `@libsql/client` are two copies of SQLite whose file locks do not coordinate, so a thread on the other engine corrupts the WAL file when a renewal lands inside a main-thread write transaction. **When no safe same-engine connection exists** (`db.engine` undefined, as on a wrapped/proxied connection or a test double; `reopenOptions` missing or throwing `ReopenNotSupportedError`; the engine differs after opening; in-memory SQLite; DuckDB and other single-owner engines; secure SQLite on Windows, whose custody verifier cannot cross a thread boundary) the thread is not started and the lease is renewed on the runner's own connection from the main loop, with one log naming the reason: `warn` where a thread used to run (file-backed SQLite with no same-engine connection, secure SQLite on Windows), `debug` for engines that never had a second connection (in-memory SQLite, DuckDB, JSON). A thread that fails to start logs its actual error. That fallback is safe but gives up the protection against a long synchronous handler: renewal can be delayed by it, so keep `leaseTtlMs` well above the longest synchronous section. A thread-spawn failure, a start-handshake timeout, or the thread dying mid-run fall back the same way. The worker entry is a separate build entry resolved via `import.meta.resolve('@happyvertical/smrt-jobs/worker-liveness-thread')`.
|