@happyvertical/smrt-jobs 0.61.3 → 0.61.4
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 +3 -3
- package/dist/chunks/{runner-DdonPDQV.js → runner-BRwm00s-.js} +160 -25
- package/dist/chunks/runner-BRwm00s-.js.map +1 -0
- package/dist/index.js +13 -15
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +797 -500
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1 -1
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-dedupe-slot.d.ts.map +1 -1
- package/dist/smrt-job-event.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +138 -132
- package/dist/smrt-knowledge.okf.md +6 -2
- package/dist/terminal-outcome.d.ts.map +1 -1
- package/dist/worker-liveness-thread.js +11 -3
- package/dist/worker-liveness-thread.js.map +1 -1
- package/dist/worker-liveness-ticker.d.ts +23 -8
- package/dist/worker-liveness-ticker.d.ts.map +1 -1
- package/dist/worker-liveness.d.ts +37 -7
- package/dist/worker-liveness.d.ts.map +1 -1
- package/package.json +11 -11
- package/dist/chunks/runner-DdonPDQV.js.map +0 -1
- package/dist/chunks/worker-liveness-C1Gjnhax.js +0 -58
- package/dist/chunks/worker-liveness-C1Gjnhax.js.map +0 -1
package/dist/runner.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../src/runner.ts"],"names":[],"mappings":"AAEA,OAAO,wBAAwB,CAAC;AAGhC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../src/runner.ts"],"names":[],"mappings":"AAEA,OAAO,wBAAwB,CAAC;AAGhC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAa3C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,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IACH,cAAc,IAAI,MAAM;IAIxB;;OAEG;IACH,OAAO,CAAC,YAAY;IAwBpB;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,kBAAkB;YAIZ,IAAI;IA2DlB;;;;;;;;;;OAUG;YACW,oBAAoB;YAmBpB,sBAAsB;IAmCpC;;;;;;;;;;;;;OAaG;YACW,UAAU;IAsGxB;;;;;;;OAOG;YACW,6BAA6B;IAW3C;;;;;;;;;;OAUG;IACH,OAAO,CAAC,yBAAyB;IA4BjC,6EAA6E;YAC/D,eAAe;IAQ7B;;;;;;;;;;;;;;;OAeG;YACW,cAAc;IA2C5B;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAiCvB;;;;;;;OAOG;YACW,aAAa;IAuB3B;;OAEG;YACW,UAAU;IA0LxB;;OAEG;YACW,cAAc;YAgGd,sBAAsB;IAmCpC,OAAO,CAAC,sBAAsB;YAkFhB,cAAc;IAuC5B,OAAO,CAAC,qBAAqB;IAe7B,OAAO,CAAC,kBAAkB;IAY1B;;;OAGG;YACW,iBAAiB;IAO/B;;;;;;;;;;;;;OAaG;YACW,gBAAgB;IA+G9B;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAczB;;;;;OAKG;YACW,mBAAmB;IA+GjC,OAAO,CAAC,wBAAwB;IAShC;;;;OAIG;YACW,kBAAkB;IAiBhC;;;;OAIG;IACH,OAAO,CAAC,cAAc;IAqBtB;;OAEG;YACW,iBAAiB;CAuBhC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,CAAC,EAAE,gBAAgB,GAAG,UAAU,CAEtE;AAED,eAAe,UAAU,CAAC"}
|
package/dist/runner.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as getActiveJobExecutionContext, i as createTaskRunner, n as JobTimeoutError, o as isRunnerExecutionContext, r as TaskRunner, t as JobCancelledError } from "./chunks/runner-
|
|
1
|
+
import { a as getActiveJobExecutionContext, i as createTaskRunner, n as JobTimeoutError, o as isRunnerExecutionContext, r as TaskRunner, t as JobCancelledError } from "./chunks/runner-BRwm00s-.js";
|
|
2
2
|
export { JobCancelledError, JobTimeoutError, TaskRunner, TaskRunner as default, createTaskRunner, getActiveJobExecutionContext, isRunnerExecutionContext };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schedule-runner.d.ts","sourceRoot":"","sources":["../src/schedule-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"schedule-runner.d.ts","sourceRoot":"","sources":["../src/schedule-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAM3C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAE5D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAgB9E;;GAEG;AACH;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C,MAAM,WAAW,oBAAoB;IACnC,iDAAiD;IACjD,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,mEAAmE;IACnE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,4CAA4C;IAC5C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gGAAgG;IAChG,gBAAgB,CAAC,EAAE,uBAAuB,GAAG,IAAI,CAAC;IAClD,0EAA0E;IAC1E,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,4EAA4E;IAC5E,SAAS,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACvC,mEAAmE;IACnE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B;;OAEG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED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,qBAMa,iBAAkB,SAAQ,UAAU;IAC/C,qDAAqD;
|
|
1
|
+
{"version":3,"file":"smrt-job-dedupe-slot.d.ts","sourceRoot":"","sources":["../src/smrt-job-dedupe-slot.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,cAAc,EACd,UAAU,EAEX,MAAM,0BAA0B,CAAC;AAElC;;;;;;GAMG;AACH,qBAMa,iBAAkB,SAAQ,UAAU;IAC/C,qDAAqD;IAOrD,OAAO,EAAE,MAAM,CAAM;IAErB,0EAA0E;IAE1E,KAAK,EAAE,MAAM,GAAG,IAAI,CAAQ;CAC7B;AAED,6EAA6E;AAC7E,qBAAa,2BAA4B,SAAQ,cAAc,CAAC,iBAAiB,CAAC;IAChF,MAAM,CAAC,QAAQ,CAAC,UAAU,2BAAqB;CAChD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smrt-job-event.d.ts","sourceRoot":"","sources":["../src/smrt-job-event.ts"],"names":[],"mappings":"AAEA,OAAO,wBAAwB,CAAC;AAEhC,OAAO,EAKL,cAAc,EACd,UAAU,EAEX,MAAM,0BAA0B,CAAC;AAQlC,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,UAAU,GAAG,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAEhF,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAEpE,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,gBAAgB,CAAC;IACxB,KAAK,CAAC,EAAE,iBAAiB,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM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AA0B,CAAC;IAqEtC,OAAO,CAAC,kBAAkB;IAwB1B;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,OAAO,CAAC,OAAO,EAAE;QAAE,MAAM,EAAE,IAAI,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAsB3E,OAAO,CAAC,6BAA6B;YAYvB,sBAAsB;CA6BrC;AAiFD,eAAe,YAAY,CAAC"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,14 +3,15 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-jobs",
|
|
6
|
-
"packageVersion": "0.61.
|
|
6
|
+
"packageVersion": "0.61.4",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "71305d60102629ce2f4738c124ac58677ab55aa1f13aceb59c728224a5d65fe5",
|
|
11
|
+
"packageJson": "02a45a3f3bf85ad9ce20e8c840d3c319b562e753009901829b2e4f52b381f2db",
|
|
12
|
+
"agents": "e416e14c3aa0f1f9d65bfac4c5a14a9d1c739f394b6a6465504da50bb25fc1cd",
|
|
13
13
|
"moduleDoc:agents/provider-loading.md": "fe0732df73c6de898e8cae189b04839f567b04a2b98a5211efba217e7d04e03e",
|
|
14
|
+
"moduleDoc:agents/worker-liveness.md": "75f592055d136982818a7ced82da78954493551954c4c953ee6373e891b9e035",
|
|
14
15
|
"moduleDoc:agents/scheduling.md": "ac216e8c20d83488305303c27f1d114ca90e1f43a32bb6e085c8acac33c1e4bf"
|
|
15
16
|
},
|
|
16
17
|
"exports": [
|
|
@@ -64,6 +65,131 @@
|
|
|
64
65
|
"sensitive-fields-excluded"
|
|
65
66
|
],
|
|
66
67
|
"objects": [
|
|
68
|
+
{
|
|
69
|
+
"name": "SmrtJobEvent",
|
|
70
|
+
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobEvent",
|
|
71
|
+
"collection": "smrtjobevents",
|
|
72
|
+
"tableName": "_smrt_job_events",
|
|
73
|
+
"packageName": "@happyvertical/smrt-jobs",
|
|
74
|
+
"extends": "SmrtObject",
|
|
75
|
+
"fields": [
|
|
76
|
+
{
|
|
77
|
+
"name": "tenantId",
|
|
78
|
+
"type": "text",
|
|
79
|
+
"required": false,
|
|
80
|
+
"columnType": "UUID"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"name": "jobId",
|
|
84
|
+
"type": "foreignKey",
|
|
85
|
+
"required": true,
|
|
86
|
+
"related": "SmrtJob",
|
|
87
|
+
"columnType": "UUID"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
"name": "type",
|
|
91
|
+
"type": "text",
|
|
92
|
+
"required": true,
|
|
93
|
+
"columnType": "TEXT",
|
|
94
|
+
"default": "log"
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"name": "level",
|
|
98
|
+
"type": "text",
|
|
99
|
+
"required": true,
|
|
100
|
+
"columnType": "TEXT",
|
|
101
|
+
"default": "info"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"name": "stage",
|
|
105
|
+
"type": "text",
|
|
106
|
+
"required": false,
|
|
107
|
+
"columnType": "TEXT"
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"name": "progress",
|
|
111
|
+
"type": "integer",
|
|
112
|
+
"required": false,
|
|
113
|
+
"columnType": "INTEGER"
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
"name": "message",
|
|
117
|
+
"type": "text",
|
|
118
|
+
"required": false,
|
|
119
|
+
"columnType": "TEXT",
|
|
120
|
+
"default": ""
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
"name": "data",
|
|
124
|
+
"type": "json",
|
|
125
|
+
"required": false,
|
|
126
|
+
"columnType": "JSON"
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
"name": "createdAt",
|
|
130
|
+
"type": "datetime",
|
|
131
|
+
"required": true,
|
|
132
|
+
"columnType": "TIMESTAMP"
|
|
133
|
+
}
|
|
134
|
+
],
|
|
135
|
+
"relationships": [
|
|
136
|
+
{
|
|
137
|
+
"name": "jobId",
|
|
138
|
+
"type": "foreignKey",
|
|
139
|
+
"required": true,
|
|
140
|
+
"related": "SmrtJob",
|
|
141
|
+
"columnType": "UUID"
|
|
142
|
+
}
|
|
143
|
+
],
|
|
144
|
+
"methods": [
|
|
145
|
+
"toCursor"
|
|
146
|
+
],
|
|
147
|
+
"methodSignatures": [
|
|
148
|
+
{
|
|
149
|
+
"name": "toCursor",
|
|
150
|
+
"returns": "string"
|
|
151
|
+
}
|
|
152
|
+
],
|
|
153
|
+
"tenant": {
|
|
154
|
+
"scoped": true,
|
|
155
|
+
"mode": "optional",
|
|
156
|
+
"field": "tenantId"
|
|
157
|
+
},
|
|
158
|
+
"conflictColumns": [
|
|
159
|
+
"tenant_id",
|
|
160
|
+
"slug",
|
|
161
|
+
"context"
|
|
162
|
+
],
|
|
163
|
+
"surfaces": [
|
|
164
|
+
{
|
|
165
|
+
"kind": "cli",
|
|
166
|
+
"name": "smrtjobevent_list",
|
|
167
|
+
"operation": "list",
|
|
168
|
+
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
"kind": "cli",
|
|
172
|
+
"name": "smrtjobevent_get",
|
|
173
|
+
"operation": "get",
|
|
174
|
+
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
175
|
+
}
|
|
176
|
+
],
|
|
177
|
+
"withheldSurfaces": [
|
|
178
|
+
{
|
|
179
|
+
"kind": "api",
|
|
180
|
+
"operation": "toCursor",
|
|
181
|
+
"code": "api-disabled",
|
|
182
|
+
"reason": "api is disabled",
|
|
183
|
+
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
184
|
+
}
|
|
185
|
+
],
|
|
186
|
+
"relationshipFeatures": [
|
|
187
|
+
"foreignKey",
|
|
188
|
+
"uuidColumns"
|
|
189
|
+
],
|
|
190
|
+
"tags": [],
|
|
191
|
+
"risks": []
|
|
192
|
+
},
|
|
67
193
|
{
|
|
68
194
|
"name": "ForgeDelivery",
|
|
69
195
|
"qualifiedName": "@happyvertical/smrt-jobs:ForgeDelivery",
|
|
@@ -105,7 +231,7 @@
|
|
|
105
231
|
{
|
|
106
232
|
"name": "eventName",
|
|
107
233
|
"type": "text",
|
|
108
|
-
"required":
|
|
234
|
+
"required": false,
|
|
109
235
|
"columnType": "TEXT"
|
|
110
236
|
},
|
|
111
237
|
{
|
|
@@ -239,7 +365,7 @@
|
|
|
239
365
|
{
|
|
240
366
|
"name": "deliveryId",
|
|
241
367
|
"type": "text",
|
|
242
|
-
"required":
|
|
368
|
+
"required": false,
|
|
243
369
|
"columnType": "TEXT"
|
|
244
370
|
},
|
|
245
371
|
{
|
|
@@ -391,131 +517,6 @@
|
|
|
391
517
|
"tags": [],
|
|
392
518
|
"risks": []
|
|
393
519
|
},
|
|
394
|
-
{
|
|
395
|
-
"name": "SmrtJobEvent",
|
|
396
|
-
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobEvent",
|
|
397
|
-
"collection": "smrtjobevents",
|
|
398
|
-
"tableName": "_smrt_job_events",
|
|
399
|
-
"packageName": "@happyvertical/smrt-jobs",
|
|
400
|
-
"extends": "SmrtObject",
|
|
401
|
-
"fields": [
|
|
402
|
-
{
|
|
403
|
-
"name": "tenantId",
|
|
404
|
-
"type": "text",
|
|
405
|
-
"required": false,
|
|
406
|
-
"columnType": "UUID"
|
|
407
|
-
},
|
|
408
|
-
{
|
|
409
|
-
"name": "jobId",
|
|
410
|
-
"type": "foreignKey",
|
|
411
|
-
"required": true,
|
|
412
|
-
"related": "SmrtJob",
|
|
413
|
-
"columnType": "UUID"
|
|
414
|
-
},
|
|
415
|
-
{
|
|
416
|
-
"name": "type",
|
|
417
|
-
"type": "text",
|
|
418
|
-
"required": true,
|
|
419
|
-
"columnType": "TEXT",
|
|
420
|
-
"default": "log"
|
|
421
|
-
},
|
|
422
|
-
{
|
|
423
|
-
"name": "level",
|
|
424
|
-
"type": "text",
|
|
425
|
-
"required": true,
|
|
426
|
-
"columnType": "TEXT",
|
|
427
|
-
"default": "info"
|
|
428
|
-
},
|
|
429
|
-
{
|
|
430
|
-
"name": "stage",
|
|
431
|
-
"type": "text",
|
|
432
|
-
"required": false,
|
|
433
|
-
"columnType": "TEXT"
|
|
434
|
-
},
|
|
435
|
-
{
|
|
436
|
-
"name": "progress",
|
|
437
|
-
"type": "integer",
|
|
438
|
-
"required": false,
|
|
439
|
-
"columnType": "INTEGER"
|
|
440
|
-
},
|
|
441
|
-
{
|
|
442
|
-
"name": "message",
|
|
443
|
-
"type": "text",
|
|
444
|
-
"required": true,
|
|
445
|
-
"columnType": "TEXT",
|
|
446
|
-
"default": ""
|
|
447
|
-
},
|
|
448
|
-
{
|
|
449
|
-
"name": "data",
|
|
450
|
-
"type": "json",
|
|
451
|
-
"required": false,
|
|
452
|
-
"columnType": "JSON"
|
|
453
|
-
},
|
|
454
|
-
{
|
|
455
|
-
"name": "createdAt",
|
|
456
|
-
"type": "datetime",
|
|
457
|
-
"required": true,
|
|
458
|
-
"columnType": "TIMESTAMP"
|
|
459
|
-
}
|
|
460
|
-
],
|
|
461
|
-
"relationships": [
|
|
462
|
-
{
|
|
463
|
-
"name": "jobId",
|
|
464
|
-
"type": "foreignKey",
|
|
465
|
-
"required": true,
|
|
466
|
-
"related": "SmrtJob",
|
|
467
|
-
"columnType": "UUID"
|
|
468
|
-
}
|
|
469
|
-
],
|
|
470
|
-
"methods": [
|
|
471
|
-
"toCursor"
|
|
472
|
-
],
|
|
473
|
-
"methodSignatures": [
|
|
474
|
-
{
|
|
475
|
-
"name": "toCursor",
|
|
476
|
-
"returns": "string"
|
|
477
|
-
}
|
|
478
|
-
],
|
|
479
|
-
"tenant": {
|
|
480
|
-
"scoped": true,
|
|
481
|
-
"mode": "optional",
|
|
482
|
-
"field": "tenantId"
|
|
483
|
-
},
|
|
484
|
-
"conflictColumns": [
|
|
485
|
-
"tenant_id",
|
|
486
|
-
"slug",
|
|
487
|
-
"context"
|
|
488
|
-
],
|
|
489
|
-
"surfaces": [
|
|
490
|
-
{
|
|
491
|
-
"kind": "cli",
|
|
492
|
-
"name": "smrtjobevent_list",
|
|
493
|
-
"operation": "list",
|
|
494
|
-
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
495
|
-
},
|
|
496
|
-
{
|
|
497
|
-
"kind": "cli",
|
|
498
|
-
"name": "smrtjobevent_get",
|
|
499
|
-
"operation": "get",
|
|
500
|
-
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
501
|
-
}
|
|
502
|
-
],
|
|
503
|
-
"withheldSurfaces": [
|
|
504
|
-
{
|
|
505
|
-
"kind": "api",
|
|
506
|
-
"operation": "toCursor",
|
|
507
|
-
"code": "api-disabled",
|
|
508
|
-
"reason": "api is disabled",
|
|
509
|
-
"objectName": "@happyvertical/smrt-jobs:SmrtJobEvent"
|
|
510
|
-
}
|
|
511
|
-
],
|
|
512
|
-
"relationshipFeatures": [
|
|
513
|
-
"foreignKey",
|
|
514
|
-
"uuidColumns"
|
|
515
|
-
],
|
|
516
|
-
"tags": [],
|
|
517
|
-
"risks": []
|
|
518
|
-
},
|
|
519
520
|
{
|
|
520
521
|
"name": "SmrtJobEventCollection",
|
|
521
522
|
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobEventCollection",
|
|
@@ -1341,13 +1342,18 @@
|
|
|
1341
1342
|
"polymorphicAssociations": 0,
|
|
1342
1343
|
"uuidColumns": 20
|
|
1343
1344
|
},
|
|
1344
|
-
"agentDoc": "# @happyvertical/smrt-jobs\n\nBackground job execution with persistent queue, scheduling, and fluent builder API.\nRetry SDK import boundary: [provider loading](agents/provider-loading.md).\n\n## Architecture\n\n```\nSmrtObject.bg('method') → SmrtJob (in _smrt_jobs) → TaskRunner picks up → executes via ObjectRegistry\nAgentSchedule (cron) → ScheduleRunner creates SmrtJob → TaskRunner executes → ScheduleRunner updates\nTaskRunner.start() → SmrtWorker lease (in _smrt_workers) → recovery keys on worker liveness, not heartbeat\n```\n\n## SmrtJob\n\nPersistent in `_smrt_jobs`. Fields: `queue` (default), `objectType`, `objectId`, `method`, `args`, `runAt`, `priority` (higher=sooner), `status`, `attempts`/`maxAttempts`, `timeout` (default 5min), `retryStrategy`, `workerId` (the owning runner's incarnation key), `workerHeartbeat` (telemetry only — no longer gates recovery).\n\nStatus: `pending → running → completed/failed/cancelled`.\n\n## TaskRunner\n\nPolling-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).\n\nOptional `tenantIds` scopes both atomic ready claims and orphan recovery before\nownership or terminal-state writes (`undefined` means all; `[]` means none;\n`null` includes global jobs). Recovery also respects configured queues. Scoped\nrunners default `retention` to `false`, since the system-wide maintenance sweep\nhas no tenant filter; opt into that sweep only in an authorized maintenance host.\n`ClaimReadyOptions` and `ListReadyOptions` accept the same tenant scope. Queue\nlease advertising remains queue-level; it does not prove per-tenant availability.\n\n1. `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\n2. 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\n3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`\n4. Resolves class via `ObjectRegistry.getClass(objectType)`. Object-bound jobs\n pass `objectId` to the constructor and let `initialize()` perform the single\n canonical hydration. Runner-owned `db`, `id`, and hydration options cannot be\n overridden by agent config; missing persisted targets fail before method\n dispatch. Jobs without `objectId` construct a static-like instance\n5. **Internal args**: `_agentConfig` and `_scheduleId` stripped from args before calling method. `_agentConfig` goes through `resolveLazyConfig()` with this job's identity as resolver context (`agentId` = `objectId`, qualified `agentClass`, `tenantId`, `scheduleId`, `jobId`; #2806). That identity comes from the job row only, never from scanning other agents. `scheduleId` is echoed from args unverified and is informational only\n6. Calls the requested method on the initialized instance\n7. Terminal/retry writes are **conditional** (`WHERE worker_id=? AND status='running'`) so a recovered row is never stomped\n8. Retry: uses strategy from `@happyvertical/jobs`, schedules future `runAt` on failure. A handler error's own hints win (#3308): `error.retryable === false` fails the job terminally; a positive `error.retryAfterMs` (capped at 24 h) is a floor on the strategy's delay\n9. Events: `job:started`, `job:completed`, `job:failed`, `job:retrying`, `runner:started/stopped`\n\n`start()` prepares the terminal-outcome storage before it registers or claims anything (#4735). Preparing it builds the registry's merged schemas, so a registry inconsistency (two unrelated classes claiming one table) rejects `start()` with that error, logged at error level, instead of stranding every claimed job as `running`. Readiness is cached per database: a model family that registers after start cannot block a later terminal write. A completion, failure or retry write that still cannot be persisted is logged at error level with the job id as well as emitted as `runner:error` (a listener that throws after the write committed is only a `runner:error`). The row is still `running` and owned by this live worker, so liveness-based recovery would skip it until the process stops; the runner records it in `unsettledJobs` and its own recovery sweep settles it as `failed` with its `stale-recovery` event and a `last_error` saying what happened, firing `job:failed` once. A handler that returned is never retried. State and event still commit together (see Terminal outcomes): if the settle cannot be persisted either, it is retried each sweep and logged once per job, and the sweep continues with the other orphans.\n\nA rejection from `processJob` can never escape the poll loop: the caller attaches `.catch(e => emit('runner:error', e))` and the error path (`handleJobError`) is itself try/caught, so a failure-path write that rejects is surfaced as a `runner:error` event instead of crashing the worker with an unhandled rejection.\n\n## Timeouts & at-least-once\n\n**Execution is at-least-once, never exactly-once. Make job handlers idempotent.**\n\nA job `timeout` only races the handler's promise — JavaScript cannot preempt an already-running function. When a handler exceeds its timeout:\n\n- The job is **failed terminally and NOT auto-retried** (a timed-out handler is still running; re-queueing it would let a second worker run a concurrent duplicate). This narrows, but does not eliminate, the overlap window — the orphaned handler keeps running until it returns on its own.\n- The orphaned handler's eventual terminal write is dropped by the ownership guard (`WHERE worker_id=? AND status='running'`), so it cannot resurrect the failed row — but any **side effects** it performs (external API calls, writes to other tables) still happen.\n- Key any non-idempotent work by `context.job.jobId` or a caller-supplied idempotency key.\n\n`timeoutBehavior` (persisted + shown in the UI) is now honored:\n\n- **`'fail'`** (default): on timeout the job fails (and, per above, is not retried).\n- **`'warn'`**: the handler is **not** raced against the timeout — it runs to completion, and at the deadline the runner logs a warning and emits a `timeout-warning` job event. A slow-but-successful handler still completes successfully.\n- **`'kill'`**: treated identically to `'fail'`. In-process JavaScript has no thread interruption, so a true \"kill\" of a running handler is impossible without worker isolation; this value is honest that it only fails the job row, it does not stop the handler. Prefer `'fail'` unless you specifically want the label.\n\n## Cooperative cancellation (`context.signal`)\n\nHandlers receive `context.signal`, a plain `AbortSignal` (pass it to `fetch` or an LLM SDK). It aborts when:\n\n- the job row is observed as `cancelled` while the handler runs (reason: exported `JobCancelledError`). The runner polls the owned row every `cancelPollInterval` (default 1s) with one read-only `SELECT status`; unref'd and cleared in `finally`. Poll errors are ignored.\n- the job times out under `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`), so the orphaned handler can stop. `'warn'` never aborts.\n\nCooperative 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`.\n\n**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.\n\n## Worker liveness & recovery (#1474)\n\nRecovery keys on **worker-process liveness**, never per-job heartbeat freshness (a CPU-bound synchronous handler used to starve the heartbeat and false-recover its own running jobs).\n\n- **`SmrtWorker` / `_smrt_workers`**: one lease row per runner *incarnation* (`workerId` is per-incarnation unique via `createWorkerKey`, so a restart never looks like it still owns the previous crash's jobs). `leaseExpiresAt` is a `datetime` (an integer epoch-ms column overflows `int4`/`INT32` on Postgres/DuckDB). Stage 1 writes/compares it against the host clock — the same approach the old heartbeat recovery used, so it's no more skew-sensitive than the code it replaced.\n- **`SmrtWorker.queues`** (nullable JSON `string[]`, #3902): the runner's configured `queues`, written at `registerWorker` and re-written on every lease renewal (main-loop and off-loop ticker). `SmrtWorkerCollection.liveWorkerKeysForQueue(queue)` returns fresh-lease workers that poll a queue; rows with `queues = null` (older runners, schedule runners) never match. Existing databases need `smrt db:migrate` (additive column) before an upgraded runner starts.\n- **Process-global live set** (`worker-liveness.ts`, `globalThis.__smrtLiveWorkers`): checked synchronously, so it can't be starved by a blocked loop. Covers all same-process topologies.\n- **Off-loop ticker** (`worker-liveness-ticker.ts` + `worker-liveness-thread.ts`): for engines a second connection can reach (Postgres, file-backed SQLite — `offLoopEligible()`), `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. In-memory SQLite / DuckDB, a thread-spawn failure, a start-handshake timeout, or the thread dying mid-run all fall back to main-loop renewal; the in-process live set keeps same-process correct regardless. The worker entry is a separate build entry resolved via `import.meta.resolve('@happyvertical/smrt-jobs/worker-liveness-thread')`. On PostgreSQL the ticker opens a bounded one-client pool (`livenessConnectionOptions()`: `max: 1`, core's runtime timeouts, no `dbid`), never a second default-sized pool (#3046). Stopping (or a failed start) lets the thread exit by draining its own event loop and calls `terminate()` only after a bound or for a hung handshake: Node 24/26 abort the whole process when a worker is terminated while a crypto completion is pending, and `@happyvertical/sql` starts an HMAC `generateKey` on import (#4865). Tests must not `terminate()` the thread either.\n- **Recovery rule** (both runners): a `running` job is orphaned iff its worker is *not alive* = not in the live set **and** no fresh `_smrt_workers` lease. The live set takes precedence over a stale lease. TaskRunner also never recovers a job in its own `activeJobs`. If `_smrt_workers` is absent, recovery skips lease checks (never mass-recovers). Recovery is swept at most once per lease tick, and terminal/recovery writes use `RETURNING id` (not `rowCount`, which DuckDB/JSON adapters always report as ≥1).\n- **Lease clock**: the lease is compared against the host clock (same as the old heartbeat; fine with NTP + a 30s TTL). A dead process stops renewing and the lease expires within its TTL — that is how recovery detects death. (Instant cross-process detection via Postgres session advisory locks was prototyped on `@happyvertical/sql`'s `acquireSession()` but deferred — treating a free lock as proof-of-death false-recovers any worker legitimately in main-loop fallback mode.)\n\n## ScheduleRunner\n\nTransactional schedule admission, tenant/type scopes, dedicated queues,\noccurrence metadata, retry/slot semantics, graceful drain, and tenant-partitioned\nnonterminal job keys are documented in [safe scheduling](agents/scheduling.md).\nRun `smrt db:migrate` before using the new job provenance and dedupe-slot schema.\n\nCustom 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).\n\n## JobBuilder — Fluent API\n\n```typescript\nconst handle = await doc.background('analyze', { detailed: true })\n .delay('5m').priority('high').retries(5).queue('analysis').timeout(600000).enqueue();\n\nawait handle.wait({ timeout: 60000, pollInterval: 100 }); // polling-based\n```\n\n## Durable forge projections\n\n`ForgeDeliveryCollection` owns the provider-neutral delivery inbox in\n`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter\ntransitions and monotonic checkpoints in\n`_smrt_forge_projection_checkpoints`.\n\n- Inbox identity is `(tenant_id, provider, delivery_id)`.\n- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or\n `claimReady`) so each claims and dead-letters only its own deliveries;\n unfiltered claims take every provider (smrt-commerce billing uses\n `<name>-billing:<sellerTenantId>`, #3060).\n- `claimReady` leases exactly one delivery; PostgreSQL uses the same\n `MATERIALIZED` CTE claim as jobs (#3105).\n- Tenant-facing accept/replay requires ambient tenant context. Worker claim is\n cross-tenant, then runtime restores the captured context before observation.\n Reads in the accept path go through the tenant-scoped collection (`list()`),\n so intake works under the interceptor's `rawQueryPolicy: 'throw'` production\n default without a bypass (#3100); keep new tenant-facing reads that way.\n- Projection callbacks must write through `ForgeProjectionContext.db`; the\n application projection, checkpoint, and inbox completion share one\n transaction.\n- Observation identity is tracker-independent\n `(projection, subjectKey, version)`. Equal or older versions are acknowledged\n without reapplying.\n- Lease-token conditions guard every terminal/failure write. Expired final\n attempts become replayable `dead_letter` rows, and persisted errors are\n redacted.\n- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit\n tenant-scoped operator action.\n\n`bg()` is shorthand: `await doc.bg('analyze', args)` → enqueues immediately, returns JobHandle.\n\n## withBackgroundJobs(Class)\n\nMixin that adds `bg()` and `background()` to any SmrtObject. Uses WeakMap for collection caching per DB instance.\n\n## Background policy (`background-policy.ts`, S5 audit #1402)\n\nThree opt-in guards, all owned **and enforced here**. Other packages apply the\neligibility marker (`reports`, `support`, `fields`, the MCP conformance\nfixture), but nothing outside this package acts on it — `TaskRunner` is the only\nreader. In particular `@happyvertical/smrt-agents` has no reference to any of\nthese guards and does not depend on this package, so marking a method does not\nchange what the agents runtime will dispatch.\n\n- `clampRetries()` / `MAX_JOB_RETRIES` (25): a requested retry count above the\n ceiling is clamped, not rejected.\n- `assertWithinTenantCreationCap(tenantId, current, cap)` /\n `DEFAULT_TENANT_JOB_CAP` (10 000): throws `TenantJobCapExceededError` when the\n tenant's count of non-terminal jobs is already at or above the cap. Applied in\n `SmrtJobCollection.enqueueJob()` (`smrt-job.ts`), which is the single choke\n point for the builder and `ScheduleRunner`; a `null` tenant and a `cap <= 0`\n both skip the check. Deliberately not serialized — concurrent enqueues can\n overshoot by the number of in-flight creators (see the method's own comment).\n- `@backgroundEligible()` / `markBackgroundEligible()` /\n `isBackgroundEligibleMethod()`: an allowlist of methods `TaskRunner` may\n dispatch, enforced at exactly one call site (`runner.ts`, after the method\n lookup). **Restrictive, not enabling** — a class with no marked methods allows\n any of its methods, and the first mark makes the set exhaustive, excluding\n every sibling method. Adding the decorator to one method of an existing class\n is therefore a behaviour change for the rest of it.\n\n## Terminal outcomes (#3696)\n\nTerminal state is authoritative together with its versioned event. Completion,\npermanent failure, timeout, stale-worker recovery, and cancellation update the\nowned `_smrt_jobs` row and append the safe `_smrt_job_events` projection in one\ndatabase transaction. If either write fails, neither commits. Conditional\nownership/status predicates prevent a lost race from appending an event.\nBuild the event from the conditional update's returned row, not a caller\nsnapshot, and bind that update to the row's tenant. Public cancellation must\nretain ambient-tenant isolation; only explicit bypass contexts may cross it.\nRetries are deliberately excluded until a later terminal transition. Ordinary\nprogress, logs, start, and retry telemetry remain best-effort.\n\n`SmrtJobEventCollection.listTerminalOutcomes()` requires an explicit tenant\n(`null` means global), reads newest-first, scans at most 1,000 candidates, and\nreturns only the safe versioned terminal shape. Never add job arguments,\nobject IDs, results, raw errors, or stacks to that shape. Applications must\nintersect job IDs with their own authorized ownership records; queue/object\ntype/method filters narrow the projection but do not authorize it.\n\n## Retention (#2375)\n\n`_smrt_jobs` and `_smrt_job_events` are append-only in practice — `cleanup()`\nexisted but nothing ever called it, and job events (one row per log line and\nprogress tick) had no prune path at all. `src/retention.ts` contributes both to\nthe framework retention sweep in `@happyvertical/smrt-core`.\n\n- `TaskRunner` starts a sweeper by default. `retention: false` opts out;\n `retention: { intervalMs, policy, jobs }` tunes it. The **first sweep is one\n interval after `start()`, never at start** — a crash-looping worker must not\n become a delete loop, and a short-lived runner must exit having deleted\n nothing. `stop()` only clears the timer — it does **not** unregister the job\n tasks. The package entry point (`index.ts`) registers them unconditionally\n on import, so \"this process loaded `@happyvertical/smrt-jobs`\" is the\n contract that contributes them, not \"a sweeper happens to be running\";\n `unregisterJobRetentionTasks()` is the explicit opt-out for callers that\n want a clean registry (tests, teardown).\n- Windows (`DEFAULT_JOB_RETENTION`): completed/cancelled 7 days, failed 30\n days, events 30 days, 10 000 job rows per sweep. Events deliberately outlive\n the jobs they describe, so a job row removed at 7 days still has a readable\n log for another three weeks. `SmrtJobEvent.jobId` is therefore the explicit\n same-package archival exception: `@foreignKey('SmrtJob', { constraint:\n false })` retains runtime relationship metadata and its index without a\n physical database constraint that would block parent pruning.\n- `cleanup()` counts before deleting (`rowCount` is unreliable across engines)\n and honours `dryRun`, which is what makes `smrt db:prune --dry-run` an exact\n preview. Its `(status, completed_at)` predicate is indexed by\n `ensureJobsSystemTableCompatibility()`, which this collection runs on every\n `initialize()` — bootstrap cannot do it, because `_smrt_jobs` does not exist\n yet when bootstrap runs.\n- `cleanup({})` with no cutoff returns 0. It must never be read as \"delete\n everything\".\n\n## Gotchas\n\n- The shared claim/recovery projection casts both job and tenant UUIDs to strings; DuckDB otherwise returns native UUID objects. Preserve NULL for global jobs.\n\n- **Cron zone comes from the row**: `_smrt_agent_schedules.timezone` (default `UTC`), not the host `TZ`; no missed-run catch-up (fire-once-forward)\n- **At-least-once execution**: a timeout cannot preempt a running handler; timed-out jobs fail without retry but the handler keeps running — make handlers idempotent (see \"Timeouts & at-least-once\")\n- **No dead letter queue**: failed jobs stay in DB with `status='failed'` — manual intervention\n- **Forge deliveries are not SmrtJobs**: they use their own replayable\n dead-letter inbox and projection checkpoint contract. Do not enqueue provider\n deliveries as generic background jobs.\n- **Result storage**: `resultPointer` is just a string — app must implement result backend\n- **Lazy builder**: `background()` returns builder — nothing happens until `enqueue()`\n- **wait() is polling**: JobHandle.wait() polls DB every 100ms (configurable)\n- **Migrate before start()**: `TaskRunner.start()` throws if `_smrt_workers` is missing — run `smrt db:migrate` after upgrading. Tables are never created at runtime.\n- **Recovery is liveness-based**: don't reintroduce heartbeat-threshold recovery; a blocked event loop must not look dead (see Worker liveness section, #1474)\n",
|
|
1345
|
+
"agentDoc": "# @happyvertical/smrt-jobs\n\nBackground job execution with persistent queue, scheduling, and fluent builder API.\nRetry SDK import boundary: [provider loading](agents/provider-loading.md).\n\n## Architecture\n\n```\nSmrtObject.bg('method') → SmrtJob (in _smrt_jobs) → TaskRunner picks up → executes via ObjectRegistry\nAgentSchedule (cron) → ScheduleRunner creates SmrtJob → TaskRunner executes → ScheduleRunner updates\nTaskRunner.start() → SmrtWorker lease (in _smrt_workers) → recovery keys on worker liveness, not heartbeat\n```\n\n## SmrtJob\n\nPersistent in `_smrt_jobs`. Fields: `queue` (default), `objectType`, `objectId`, `method`, `args`, `runAt`, `priority` (higher=sooner), `status`, `attempts`/`maxAttempts`, `timeout` (default 5min), `retryStrategy`, `workerId` (the owning runner's incarnation key), `workerHeartbeat` (telemetry only — no longer gates recovery).\n\nStatus: `pending → running → completed/failed/cancelled`.\n\n## TaskRunner\n\nPolling-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).\n\nOptional `tenantIds` scopes both atomic ready claims and orphan recovery before\nownership or terminal-state writes (`undefined` means all; `[]` means none;\n`null` includes global jobs). Recovery also respects configured queues. Scoped\nrunners default `retention` to `false`, since the system-wide maintenance sweep\nhas no tenant filter; opt into that sweep only in an authorized maintenance host.\n`ClaimReadyOptions` and `ListReadyOptions` accept the same tenant scope. Queue\nlease advertising remains queue-level; it does not prove per-tenant availability.\n\n1. `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\n2. 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\n3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`\n4. Resolves class via `ObjectRegistry.getClass(objectType)`. Object-bound jobs\n pass `objectId` to the constructor and let `initialize()` perform the single\n canonical hydration. Runner-owned `db`, `id`, and hydration options cannot be\n overridden by agent config; missing persisted targets fail before method\n dispatch. Jobs without `objectId` construct a static-like instance\n5. **Internal args**: `_agentConfig` and `_scheduleId` stripped from args before calling method. `_agentConfig` goes through `resolveLazyConfig()` with this job's identity as resolver context (`agentId` = `objectId`, qualified `agentClass`, `tenantId`, `scheduleId`, `jobId`; #2806). That identity comes from the job row only, never from scanning other agents. `scheduleId` is echoed from args unverified and is informational only\n6. Calls the requested method on the initialized instance\n7. Terminal/retry writes are **conditional** (`WHERE worker_id=? AND status='running'`) so a recovered row is never stomped\n8. Retry: uses strategy from `@happyvertical/jobs`, schedules future `runAt` on failure. A handler error's own hints win (#3308): `error.retryable === false` fails the job terminally; a positive `error.retryAfterMs` (capped at 24 h) is a floor on the strategy's delay\n9. Events: `job:started`, `job:completed`, `job:failed`, `job:retrying`, `runner:started/stopped`\n\n`start()` prepares the terminal-outcome storage before it registers or claims anything (#4735). Preparing it builds the registry's merged schemas, so a registry inconsistency (two unrelated classes claiming one table) rejects `start()` with that error, logged at error level, instead of stranding every claimed job as `running`. Readiness is cached per database: a model family that registers after start cannot block a later terminal write. A completion, failure or retry write that still cannot be persisted is logged at error level with the job id as well as emitted as `runner:error` (a listener that throws after the write committed is only a `runner:error`). The row is still `running` and owned by this live worker, so liveness-based recovery would skip it until the process stops; the runner records it in `unsettledJobs` and its own recovery sweep settles it as `failed` with its `stale-recovery` event and a `last_error` saying what happened, firing `job:failed` once. A handler that returned is never retried. State and event still commit together (see Terminal outcomes): if the settle cannot be persisted either, it is retried each sweep and logged once per job, and the sweep continues with the other orphans.\n\nA rejection from `processJob` can never escape the poll loop: the caller attaches `.catch(e => emit('runner:error', e))` and the error path (`handleJobError`) is itself try/caught, so a failure-path write that rejects is surfaced as a `runner:error` event instead of crashing the worker with an unhandled rejection.\n\n## Timeouts & at-least-once\n\n**Execution is at-least-once, never exactly-once. Make job handlers idempotent.**\n\nA job `timeout` only races the handler's promise — JavaScript cannot preempt an already-running function. When a handler exceeds its timeout:\n\n- The job is **failed terminally and NOT auto-retried** (a timed-out handler is still running; re-queueing it would let a second worker run a concurrent duplicate). This narrows, but does not eliminate, the overlap window — the orphaned handler keeps running until it returns on its own.\n- The orphaned handler's eventual terminal write is dropped by the ownership guard (`WHERE worker_id=? AND status='running'`), so it cannot resurrect the failed row — but any **side effects** it performs (external API calls, writes to other tables) still happen.\n- Key any non-idempotent work by `context.job.jobId` or a caller-supplied idempotency key.\n\n`timeoutBehavior` (persisted + shown in the UI) is now honored:\n\n- **`'fail'`** (default): on timeout the job fails (and, per above, is not retried).\n- **`'warn'`**: the handler is **not** raced against the timeout — it runs to completion, and at the deadline the runner logs a warning and emits a `timeout-warning` job event. A slow-but-successful handler still completes successfully.\n- **`'kill'`**: treated identically to `'fail'`. In-process JavaScript has no thread interruption, so a true \"kill\" of a running handler is impossible without worker isolation; this value is honest that it only fails the job row, it does not stop the handler. Prefer `'fail'` unless you specifically want the label.\n\n## Cooperative cancellation (`context.signal`)\n\nHandlers receive `context.signal`, a plain `AbortSignal` (pass it to `fetch` or an LLM SDK). It aborts when:\n\n- the job row is observed as `cancelled` while the handler runs (reason: exported `JobCancelledError`). The runner polls the owned row every `cancelPollInterval` (default 1s) with one read-only `SELECT status`; unref'd and cleared in `finally`. Poll errors are ignored.\n- the job times out under `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`), so the orphaned handler can stop. `'warn'` never aborts.\n\nCooperative 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`.\n\n**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.\n\n## Worker liveness & recovery (#1474)\n\nRecovery keys on **worker-process liveness**, never per-job heartbeat freshness (a CPU-bound synchronous handler used to starve the heartbeat and false-recover its own running jobs).\n\n- **`SmrtWorker` / `_smrt_workers`**: one lease row per runner *incarnation* (`workerId` is per-incarnation unique via `createWorkerKey`, so a restart never looks like it still owns the previous crash's jobs). `leaseExpiresAt` is a `datetime` (an integer epoch-ms column overflows `int4`/`INT32` on Postgres/DuckDB). Stage 1 writes/compares it against the host clock — the same approach the old heartbeat recovery used, so it's no more skew-sensitive than the code it replaced.\n- **`SmrtWorker.queues`** (nullable JSON `string[]`, #3902): the runner's configured `queues`, written at `registerWorker` and re-written on every lease renewal (main-loop and off-loop ticker). `SmrtWorkerCollection.liveWorkerKeysForQueue(queue)` returns fresh-lease workers that poll a queue; rows with `queues = null` (older runners, schedule runners) never match. Existing databases need `smrt db:migrate` (additive column) before an upgraded runner starts.\n- **Process-global live set** (`worker-liveness.ts`, `globalThis.__smrtLiveWorkers`): checked synchronously, so it can't be starved by a blocked loop. Covers all same-process topologies.\n- **Off-loop ticker** (`worker-liveness-ticker.ts` + `worker-liveness-thread.ts`): renews the lease off the main loop, only on a same-engine connection (SQLite through `db.reopenOptions()`, engine checked, #4978); otherwise main-loop renewal with one log. Details: [agents/worker-liveness.md](agents/worker-liveness.md).\n- **Recovery rule** (both runners): a `running` job is orphaned iff its worker is *not alive* = not in the live set **and** no fresh `_smrt_workers` lease. The live set takes precedence over a stale lease. TaskRunner also never recovers a job in its own `activeJobs`. If `_smrt_workers` is absent, recovery skips lease checks (never mass-recovers). Recovery is swept at most once per lease tick, and terminal/recovery writes use `RETURNING id` (not `rowCount`, which DuckDB/JSON adapters always report as ≥1).\n- **Lease clock**: the lease is compared against the host clock (same as the old heartbeat; fine with NTP + a 30s TTL). A dead process stops renewing and the lease expires within its TTL — that is how recovery detects death. (Instant cross-process detection via Postgres session advisory locks was prototyped on `@happyvertical/sql`'s `acquireSession()` but deferred — treating a free lock as proof-of-death false-recovers any worker legitimately in main-loop fallback mode.)\n\n## ScheduleRunner\n\nTransactional schedule admission, tenant/type scopes, dedicated queues,\noccurrence metadata, retry/slot semantics, graceful drain, and tenant-partitioned\nnonterminal job keys are documented in [safe scheduling](agents/scheduling.md).\nRun `smrt db:migrate` before using the new job provenance and dedupe-slot schema.\n\nCustom 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).\n\n## JobBuilder — Fluent API\n\n```typescript\nconst handle = await doc.background('analyze', { detailed: true })\n .delay('5m').priority('high').retries(5).queue('analysis').timeout(600000).enqueue();\n\nawait handle.wait({ timeout: 60000, pollInterval: 100 }); // polling-based\n```\n\n## Durable forge projections\n\n`ForgeDeliveryCollection` owns the provider-neutral delivery inbox in\n`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter\ntransitions and monotonic checkpoints in\n`_smrt_forge_projection_checkpoints`.\n\n- Inbox identity is `(tenant_id, provider, delivery_id)`.\n- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or\n `claimReady`) so each claims and dead-letters only its own deliveries;\n unfiltered claims take every provider (smrt-commerce billing uses\n `<name>-billing:<sellerTenantId>`, #3060).\n- `claimReady` leases exactly one delivery; PostgreSQL uses the same\n `MATERIALIZED` CTE claim as jobs (#3105).\n- Tenant-facing accept/replay requires ambient tenant context. Worker claim is\n cross-tenant, then runtime restores the captured context before observation.\n Reads in the accept path go through the tenant-scoped collection (`list()`),\n so intake works under the interceptor's `rawQueryPolicy: 'throw'` production\n default without a bypass (#3100); keep new tenant-facing reads that way.\n- Projection callbacks must write through `ForgeProjectionContext.db`; the\n application projection, checkpoint, and inbox completion share one\n transaction.\n- Observation identity is tracker-independent\n `(projection, subjectKey, version)`. Equal or older versions are acknowledged\n without reapplying.\n- Lease-token conditions guard every terminal/failure write. Expired final\n attempts become replayable `dead_letter` rows, and persisted errors are\n redacted.\n- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit\n tenant-scoped operator action.\n\n`bg()` is shorthand: `await doc.bg('analyze', args)` → enqueues immediately, returns JobHandle.\n\n## withBackgroundJobs(Class)\n\nMixin that adds `bg()` and `background()` to any SmrtObject. Uses WeakMap for collection caching per DB instance.\n\n## Background policy (`background-policy.ts`, S5 audit #1402)\n\nThree opt-in guards, all owned **and enforced here**. Other packages apply the\neligibility marker (`reports`, `support`, `fields`, the MCP conformance\nfixture), but nothing outside this package acts on it — `TaskRunner` is the only\nreader. In particular `@happyvertical/smrt-agents` has no reference to any of\nthese guards and does not depend on this package, so marking a method does not\nchange what the agents runtime will dispatch.\n\n- `clampRetries()` / `MAX_JOB_RETRIES` (25): a requested retry count above the\n ceiling is clamped, not rejected.\n- `assertWithinTenantCreationCap(tenantId, current, cap)` /\n `DEFAULT_TENANT_JOB_CAP` (10 000): throws `TenantJobCapExceededError` when the\n tenant's count of non-terminal jobs is already at or above the cap. Applied in\n `SmrtJobCollection.enqueueJob()` (`smrt-job.ts`), which is the single choke\n point for the builder and `ScheduleRunner`; a `null` tenant and a `cap <= 0`\n both skip the check. Deliberately not serialized — concurrent enqueues can\n overshoot by the number of in-flight creators (see the method's own comment).\n- `@backgroundEligible()` / `markBackgroundEligible()` /\n `isBackgroundEligibleMethod()`: an allowlist of methods `TaskRunner` may\n dispatch, enforced at exactly one call site (`runner.ts`, after the method\n lookup). **Restrictive, not enabling** — a class with no marked methods allows\n any of its methods, and the first mark makes the set exhaustive, excluding\n every sibling method. Adding the decorator to one method of an existing class\n is therefore a behaviour change for the rest of it.\n\n## Terminal outcomes (#3696)\n\nTerminal state is authoritative together with its versioned event. Completion,\npermanent failure, timeout, stale-worker recovery, and cancellation update the\nowned `_smrt_jobs` row and append the safe `_smrt_job_events` projection in one\ndatabase transaction. If either write fails, neither commits. Conditional\nownership/status predicates prevent a lost race from appending an event.\nBuild the event from the conditional update's returned row, not a caller\nsnapshot, and bind that update to the row's tenant. Public cancellation must\nretain ambient-tenant isolation; only explicit bypass contexts may cross it.\nRetries are deliberately excluded until a later terminal transition. Ordinary\nprogress, logs, start, and retry telemetry remain best-effort.\n\n`SmrtJobEventCollection.listTerminalOutcomes()` requires an explicit tenant\n(`null` means global), reads newest-first, scans at most 1,000 candidates, and\nreturns only the safe versioned terminal shape. Never add job arguments,\nobject IDs, results, raw errors, or stacks to that shape. Applications must\nintersect job IDs with their own authorized ownership records; queue/object\ntype/method filters narrow the projection but do not authorize it.\n\n## Retention (#2375)\n\n`_smrt_jobs` and `_smrt_job_events` are append-only in practice — `cleanup()`\nexisted but nothing ever called it, and job events (one row per log line and\nprogress tick) had no prune path at all. `src/retention.ts` contributes both to\nthe framework retention sweep in `@happyvertical/smrt-core`.\n\n- `TaskRunner` starts a sweeper by default. `retention: false` opts out;\n `retention: { intervalMs, policy, jobs }` tunes it. The **first sweep is one\n interval after `start()`, never at start** — a crash-looping worker must not\n become a delete loop, and a short-lived runner must exit having deleted\n nothing. `stop()` only clears the timer — it does **not** unregister the job\n tasks. The package entry point (`index.ts`) registers them unconditionally\n on import, so \"this process loaded `@happyvertical/smrt-jobs`\" is the\n contract that contributes them, not \"a sweeper happens to be running\";\n `unregisterJobRetentionTasks()` is the explicit opt-out for callers that\n want a clean registry (tests, teardown).\n- Windows (`DEFAULT_JOB_RETENTION`): completed/cancelled 7 days, failed 30\n days, events 30 days, 10 000 job rows per sweep. Events deliberately outlive\n the jobs they describe, so a job row removed at 7 days still has a readable\n log for another three weeks. `SmrtJobEvent.jobId` is therefore the explicit\n same-package archival exception: `@foreignKey('SmrtJob', { constraint:\n false })` retains runtime relationship metadata and its index without a\n physical database constraint that would block parent pruning.\n- `cleanup()` counts before deleting (`rowCount` is unreliable across engines)\n and honours `dryRun`, which is what makes `smrt db:prune --dry-run` an exact\n preview. Its `(status, completed_at)` predicate is indexed by\n `ensureJobsSystemTableCompatibility()`, which this collection runs on every\n `initialize()` — bootstrap cannot do it, because `_smrt_jobs` does not exist\n yet when bootstrap runs.\n- `cleanup({})` with no cutoff returns 0. It must never be read as \"delete\n everything\".\n\n## Gotchas\n\n- The shared claim/recovery projection casts both job and tenant UUIDs to strings; DuckDB otherwise returns native UUID objects. Preserve NULL for global jobs.\n\n- **Cron zone comes from the row**: `_smrt_agent_schedules.timezone` (default `UTC`), not the host `TZ`; no missed-run catch-up (fire-once-forward)\n- **At-least-once execution**: a timeout cannot preempt a running handler; timed-out jobs fail without retry but the handler keeps running — make handlers idempotent (see \"Timeouts & at-least-once\")\n- **No dead letter queue**: failed jobs stay in DB with `status='failed'` — manual intervention\n- **Forge deliveries are not SmrtJobs**: they use their own replayable\n dead-letter inbox and projection checkpoint contract. Do not enqueue provider\n deliveries as generic background jobs.\n- **Result storage**: `resultPointer` is just a string — app must implement result backend\n- **Lazy builder**: `background()` returns builder — nothing happens until `enqueue()`\n- **wait() is polling**: JobHandle.wait() polls DB every 100ms (configurable)\n- **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.\n- **Recovery is liveness-based**: don't reintroduce heartbeat-threshold recovery; a blocked event loop must not look dead (see Worker liveness section, #1474)\n",
|
|
1345
1346
|
"moduleDocs": [
|
|
1346
1347
|
{
|
|
1347
1348
|
"path": "agents/provider-loading.md",
|
|
1348
1349
|
"module": "provider-loading",
|
|
1349
1350
|
"content": "# Retry SDK loading\n\n`JobBuilder` does not import `@happyvertical/jobs` while a builder is created or\nconfigured. `enqueue()` resolves the default exponential strategy on demand;\na supplied strategy keeps its original `toConfig()` behavior without loading\nthe SDK. The runner resolves `fromConfig` only while handling a retryable job\nfailure, after the existing MCP-suspension early return.\n\nKeep the SDK's strategy implementation authoritative. Do not copy retry math\nor load private hashed SDK chunks to avoid its provider barrel. The installed\nSDK's root statically exports queue adapters; a public provider-neutral retry\nentrypoint or lazy adapter factory is the upstream boundary needed to avoid\nthose modules on first default-strategy use. Dynamic import rejections propagate\nunchanged; they are not converted into a fallback strategy.\n\n`src/__tests__/job-builder.test.ts` guards zero SDK loads before enqueue and for\ncustom strategies, then checks the first default enqueue against the SDK's own\nexponential configuration. Full runner tests cover persisted retry decisions,\nhints, timeouts, ownership and terminal outcomes.\n"
|
|
1350
1351
|
},
|
|
1352
|
+
{
|
|
1353
|
+
"path": "agents/worker-liveness.md",
|
|
1354
|
+
"module": "worker-liveness",
|
|
1355
|
+
"content": "# Off-loop worker liveness ticker (#1474, #4978)\n\n**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')`."
|
|
1356
|
+
},
|
|
1351
1357
|
{
|
|
1352
1358
|
"path": "agents/scheduling.md",
|
|
1353
1359
|
"module": "scheduling",
|
|
@@ -5,10 +5,10 @@ description: "Background job processing for SMRT objects with persistence and sc
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-16T03:35:11Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:2190ddc2936e5d16b1b438b5c1b41e024089f1d12974206f343605b7524b1ccc"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/package.json"
|
|
@@ -22,6 +22,9 @@ sources:
|
|
|
22
22
|
- id: "agents-3"
|
|
23
23
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/agents/scheduling.md"
|
|
24
24
|
title: "@happyvertical/smrt-jobs packages/jobs/agents/scheduling.md"
|
|
25
|
+
- id: "agents-4"
|
|
26
|
+
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/agents/worker-liveness.md"
|
|
27
|
+
title: "@happyvertical/smrt-jobs packages/jobs/agents/worker-liveness.md"
|
|
25
28
|
---
|
|
26
29
|
|
|
27
30
|
# @happyvertical/smrt-jobs
|
|
@@ -38,6 +41,7 @@ sources:
|
|
|
38
41
|
- `packages/jobs/AGENTS.md`
|
|
39
42
|
- `packages/jobs/agents/provider-loading.md`
|
|
40
43
|
- `packages/jobs/agents/scheduling.md`
|
|
44
|
+
- `packages/jobs/agents/worker-liveness.md`
|
|
41
45
|
|
|
42
46
|
## Framework dependencies
|
|
43
47
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"terminal-outcome.d.ts","sourceRoot":"","sources":["../src/terminal-outcome.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"terminal-outcome.d.ts","sourceRoot":"","sources":["../src/terminal-outcome.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,YAAY,EAAE,KAAK,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAI/E;;;;;;;;;GASG;AACH,wBAAsB,4BAA4B,CAChD,EAAE,EAAE,iBAAiB,GACpB,OAAO,CAAC,IAAI,CAAC,CAoBf;AAED,MAAM,WAAW,uBAAuB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,4BAA4B;IAC3C,GAAG,EAAE,uBAAuB,CAAC;IAC7B,MAAM,EAAE,qBAAqB,CAAC;IAC9B,WAAW,EAAE,IAAI,CAAC;IAClB,gBAAgB,EAAE,SAAS,EAAE,CAAC;IAC9B,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,WAAW,CAAC,EAAE,WAAW,GAAG,SAAS,GAAG,gBAAgB,CAAC;IACzD,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC7C;AAED;;;;;GAKG;AACH,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,iBAAiB,EACrB,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAoJ9B;AAED,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,IAAI,CACP,OAAO,EACP,IAAI,GAAG,UAAU,GAAG,OAAO,GAAG,YAAY,GAAG,QAAQ,GAAG,UAAU,CACnE,GACA,uBAAuB,GAAG,IAAI,CAUhC"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { applyPostgresRuntimeTimeouts, detectEngine } from "@happyvertical/smrt-core";
|
|
1
|
+
import { SQLITE_BUSY_TIMEOUT_MS, applyPostgresRuntimeTimeouts, detectEngine } from "@happyvertical/smrt-core";
|
|
3
2
|
import { parentPort, workerData } from "node:worker_threads";
|
|
4
3
|
import { getDatabase } from "@happyvertical/sql";
|
|
5
4
|
//#region src/worker-liveness-ticker.ts
|
|
6
5
|
function livenessConnectionOptions(options) {
|
|
6
|
+
if (options.reopen) return options.reopen;
|
|
7
|
+
if (detectEngine(options.url, options.type) === "sqlite") throw new Error("The liveness ticker needs reopen options for SQLite: building a connection from a URL can pick a different SQLite engine than the runtime and corrupt the file (#4978).");
|
|
7
8
|
const base = {
|
|
8
9
|
url: options.url,
|
|
9
10
|
type: options.type
|
|
@@ -16,7 +17,14 @@ function livenessConnectionOptions(options) {
|
|
|
16
17
|
}
|
|
17
18
|
async function runLivenessTicker(options) {
|
|
18
19
|
const db = await getDatabase(livenessConnectionOptions(options));
|
|
19
|
-
if (
|
|
20
|
+
if (options.reopen) try {
|
|
21
|
+
if (!options.expectedEngine) throw new Error("The liveness ticker needs the runtime connection's engine (expectedEngine) to use reopen options.");
|
|
22
|
+
if (db.engine !== options.expectedEngine) throw new Error(`Liveness connection uses engine ${db.engine ?? "unknown"}, expected ${options.expectedEngine}; refusing to share the SQLite file across engines.`);
|
|
23
|
+
await db.query(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
await db.close?.().catch(() => {});
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
20
28
|
const renew = async () => {
|
|
21
29
|
const now = /* @__PURE__ */ new Date();
|
|
22
30
|
const expiresAt = new Date(now.getTime() + options.leaseTtlMs).toISOString();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-liveness-thread.js","names":[],"sources":["../src/worker-liveness-ticker.ts","../src/worker-liveness-thread.ts"],"sourcesContent":["import {\n applyPostgresRuntimeTimeouts,\n detectEngine,\n} from '@happyvertical/smrt-core';\nimport {
|
|
1
|
+
{"version":3,"file":"worker-liveness-thread.js","names":[],"sources":["../src/worker-liveness-ticker.ts","../src/worker-liveness-thread.ts"],"sourcesContent":["import {\n applyPostgresRuntimeTimeouts,\n detectEngine,\n SQLITE_BUSY_TIMEOUT_MS,\n} from '@happyvertical/smrt-core';\nimport {\n getDatabase,\n type ReopenOptions,\n type DatabaseEngine as SqlEngine,\n} from '@happyvertical/sql';\n\n/** Options common to every engine. */\ninterface LivenessTickerBaseOptions {\n /** Database URL the owning runner is using (PostgreSQL only). */\n url: string;\n /** Optional explicit engine/type hint (PostgreSQL only). */\n type?: string;\n /** This runner incarnation's worker key (the `_smrt_workers.worker_id`). */\n workerKey: string;\n /** Lease time-to-live in milliseconds. */\n leaseTtlMs: number;\n /** Renewal cadence in milliseconds. */\n leaseTickMs: number;\n /** Queues the runner polls, re-written on every renewal. */\n queues?: string[];\n}\n\n/**\n * Configuration for an off-loop liveness ticker (passed via `workerData`).\n *\n * SQLite connects only through `reopen` (from the runtime connection's\n * `db.reopenOptions()`) together with the `expectedEngine` that connection\n * reported; the thread refuses to run on a different engine. Without `reopen`\n * only PostgreSQL may be reached, from `url`.\n */\nexport type LivenessTickerOptions = LivenessTickerBaseOptions &\n (\n | {\n reopen: ReopenOptions;\n /** The engine the runner's connection reported; required with `reopen`. */\n expectedEngine: SqlEngine;\n }\n | { reopen?: undefined; expectedEngine?: undefined }\n );\n\nexport interface LivenessTicker {\n /** Stop renewing and close the connection. */\n stop: () => Promise<void>;\n}\n\n/**\n * Connection options for the ticker's own database handle (#3046).\n *\n * The ticker issues one `UPDATE` per tick, so on PostgreSQL it needs exactly\n * one client: `max: 1` keeps it from opening a second default-sized (20-client)\n * pool next to the runner's, and the runtime timeout bounds (#2377) keep a hung\n * acquisition or statement from stalling the thread forever. No `dbid` is\n * passed, so the SDK keys this pool on its effective options and it can never\n * be confused with — or resize — the application's pool for the same URL.\n * Other engines pass through unchanged.\n */\nexport function livenessConnectionOptions(\n options: Pick<LivenessTickerOptions, 'url' | 'type' | 'reopen'>,\n): Parameters<typeof getDatabase>[0] {\n // Reopen options (SQLite) are used exactly as the SDK produced them.\n if (options.reopen) return options.reopen;\n if (detectEngine(options.url, options.type) === 'sqlite') {\n throw new Error(\n 'The liveness ticker needs reopen options for SQLite: building a connection from a URL can pick a different SQLite engine than the runtime and corrupt the file (#4978).',\n );\n }\n const base = {\n url: options.url,\n type: options.type as 'sqlite' | 'postgres' | 'duckdb' | undefined,\n };\n if (detectEngine(options.url, options.type) !== 'postgres') {\n return base as Parameters<typeof getDatabase>[0];\n }\n return {\n ...applyPostgresRuntimeTimeouts(base),\n max: 1,\n } as Parameters<typeof getDatabase>[0];\n}\n\n/**\n * Renew a worker's liveness lease from *outside* the handler event loop.\n *\n * Runs on a `node:worker_threads` thread (or, in tests, directly) with its own\n * database connection, so a CPU-bound synchronous handler on the main thread\n * cannot starve the renewal — the failure mode that made the old heartbeat\n * false-recover running jobs (#1474). A dead process stops renewing and the\n * lease expires within its TTL, which is how recovery detects death.\n */\nexport async function runLivenessTicker(\n options: LivenessTickerOptions,\n): Promise<LivenessTicker> {\n const db = await getDatabase(livenessConnectionOptions(options));\n\n if (options.reopen) {\n try {\n // Two SQLite engines do not coordinate file locks: refuse to run on a\n // different engine than the runner's connection, and never without\n // knowing which one that is.\n if (!options.expectedEngine) {\n throw new Error(\n \"The liveness ticker needs the runtime connection's engine (expectedEngine) to use reopen options.\",\n );\n }\n if (db.engine !== options.expectedEngine) {\n throw new Error(\n `Liveness connection uses engine ${db.engine ?? 'unknown'}, expected ${options.expectedEngine}; refusing to share the SQLite file across engines.`,\n );\n }\n // A reopened connection does not inherit PRAGMAs and neither engine\n // waits for a lock by default. Same value as the runtime's own.\n await db.query(`PRAGMA busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);\n } catch (error) {\n await db.close?.().catch(() => {});\n throw error;\n }\n }\n\n const renew = async (): Promise<void> => {\n const now = new Date();\n const expiresAt = new Date(\n now.getTime() + options.leaseTtlMs,\n ).toISOString();\n if (options.queues) {\n await db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?,\n queues = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n JSON.stringify(options.queues),\n options.workerKey,\n );\n return;\n }\n await db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n options.workerKey,\n );\n };\n\n try {\n // Renew immediately so the lease is fresh the moment the ticker starts.\n await renew();\n } catch (error) {\n // Don't leak the connection if the very first renewal fails.\n await db.close?.().catch(() => {});\n throw error;\n }\n\n const timer = setInterval(() => {\n renew().catch(() => {\n // Transient renewal failures are tolerated; the next tick retries and\n // the lease TTL absorbs a missed beat (TTL >= 3x tick).\n });\n }, options.leaseTickMs);\n\n let stopped = false;\n return {\n stop: async () => {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n try {\n await db.close?.();\n } catch {\n // Best-effort connection teardown.\n }\n },\n };\n}\n","/**\n * Worker-thread entry for the off-loop liveness ticker.\n *\n * Thin shell: read {@link LivenessTickerOptions} from `workerData`, start the\n * ticker, and stop it on a `'stop'` message from the parent. All real logic\n * lives in {@link runLivenessTicker} so it can be unit-tested without spawning\n * a thread. Keep this file decorator-free so Node type-stripping can run the\n * `.ts` directly under vitest.\n */\nimport { parentPort, workerData } from 'node:worker_threads';\nimport {\n type LivenessTickerOptions,\n runLivenessTicker,\n} from './worker-liveness-ticker.js';\n\nasync function main(): Promise<void> {\n const ticker = await runLivenessTicker(workerData as LivenessTickerOptions);\n\n parentPort?.on('message', async (message) => {\n if (message === 'stop') {\n await ticker.stop();\n parentPort?.postMessage('stopped');\n // Let the thread exit by draining its own event loop instead of being\n // terminated: terminate() while a crypto job's completion is still\n // pending (the SDK starts one at import) aborts the whole process\n // (smrt#4865).\n parentPort?.unref();\n }\n });\n\n // Signal the parent that the lease is seeded and renewal is running.\n parentPort?.postMessage('ready');\n}\n\nmain().catch((error) => {\n // Surface startup failure to the parent so the runner can fall back to\n // main-loop renewal rather than silently losing its lease.\n parentPort?.postMessage({\n type: 'error',\n message: error instanceof Error ? error.message : String(error),\n });\n});\n"],"mappings":";;;;AA6DO,SAAS,0BACd,SACmC;CAEnC,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,IAAI,aAAa,QAAQ,KAAK,QAAQ,IAAI,MAAM,UAC9C,MAAM,IAAI,MACR,yKACF;CAEF,MAAM,OAAO;EACX,KAAK,QAAQ;EACb,MAAM,QAAQ;CAChB;CACA,IAAI,aAAa,QAAQ,KAAK,QAAQ,IAAI,MAAM,YAC9C,OAAO;CAET,OAAO;EACL,GAAG,6BAA6B,IAAI;EACpC,KAAK;CACP;AACF;AAWA,eAAsB,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