@memberjunction/code-execution 5.29.0 → 5.30.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/.turbo/turbo-build.log +6 -2
- package/CHANGELOG.md +23 -0
- package/dist/WorkerPool.d.ts +39 -1
- package/dist/WorkerPool.d.ts.map +1 -1
- package/dist/WorkerPool.js +305 -22
- package/dist/WorkerPool.js.map +1 -1
- package/dist/libraries/bundled-libs/date-fns.js +3 -0
- package/dist/libraries/bundled-libs/jstat.js +1 -0
- package/dist/libraries/bundled-libs/lodash.js +140 -0
- package/dist/libraries/bundled-libs/mathjs.js +3 -0
- package/dist/libraries/bundled-libs/papaparse.js +7 -0
- package/dist/libraries/bundled-libs/uuid.js +43 -0
- package/dist/libraries/bundled-libs/validator.js +23 -0
- package/dist/libraries/index.js +128 -7
- package/dist/libraries/index.js.map +1 -1
- package/dist/types/index.d.ts +106 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/worker.d.ts +22 -0
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +194 -4
- package/dist/worker.js.map +1 -1
- package/package.json +5 -4
- package/src/WorkerPool.ts +398 -26
- package/src/__tests__/WorkerPool.test.ts +7 -3
- package/src/__tests__/bridge.test.ts +188 -0
- package/src/__tests__/libraries.test.ts +13 -17
- package/src/libraries/index.ts +129 -7
- package/src/types/index.ts +129 -5
- package/src/worker.ts +255 -8
package/src/WorkerPool.ts
CHANGED
|
@@ -10,6 +10,10 @@
|
|
|
10
10
|
* - Automatic worker restart on crashes
|
|
11
11
|
* - Request queuing when all workers are busy
|
|
12
12
|
* - Health monitoring and circuit breaker pattern
|
|
13
|
+
* - Bidirectional bridge: sandbox code can call host-registered handlers
|
|
14
|
+
* via `__bridgeCall(name, args)`; the host routes the call, executes the
|
|
15
|
+
* handler, and sends the response back. See worker.ts for the sandbox-side
|
|
16
|
+
* wiring.
|
|
13
17
|
*/
|
|
14
18
|
|
|
15
19
|
import { fork, ChildProcess } from 'child_process';
|
|
@@ -18,15 +22,28 @@ import { fileURLToPath } from 'node:url';
|
|
|
18
22
|
|
|
19
23
|
const __filename = fileURLToPath(import.meta.url);
|
|
20
24
|
const __dirname = path.dirname(__filename);
|
|
21
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
BridgeHandlerMap,
|
|
27
|
+
CodeExecutionParams,
|
|
28
|
+
CodeExecutionResult
|
|
29
|
+
} from './types';
|
|
22
30
|
import { LogError, LogStatus } from '@memberjunction/core';
|
|
23
31
|
|
|
24
32
|
interface PendingRequest {
|
|
25
33
|
requestId: string;
|
|
26
34
|
params: CodeExecutionParams;
|
|
35
|
+
/** Bridge handlers scoped to this execution only (never sent over IPC). */
|
|
36
|
+
bridgeHandlers?: BridgeHandlerMap;
|
|
27
37
|
resolve: (result: CodeExecutionResult) => void;
|
|
28
38
|
reject: (error: Error) => void;
|
|
29
39
|
timeout: NodeJS.Timeout;
|
|
40
|
+
/**
|
|
41
|
+
* Listener we register on `params.abortSignal` so we can remove it again
|
|
42
|
+
* when the request settles. Kept here to make cleanup easy.
|
|
43
|
+
*/
|
|
44
|
+
abortListener?: () => void;
|
|
45
|
+
/** Tracks whether we already sent an `abort` IPC message for this request. */
|
|
46
|
+
aborted?: boolean;
|
|
30
47
|
}
|
|
31
48
|
|
|
32
49
|
interface Worker {
|
|
@@ -36,8 +53,22 @@ interface Worker {
|
|
|
36
53
|
currentRequest: PendingRequest | null;
|
|
37
54
|
crashCount: number;
|
|
38
55
|
lastCrashTime: number;
|
|
56
|
+
/**
|
|
57
|
+
* Rolling tail of the worker's stderr. We keep at most
|
|
58
|
+
* `STDERR_TAIL_BYTES` so a crashing worker that spews a huge stack
|
|
59
|
+
* doesn't balloon memory in the host. Used by `handleWorkerCrash`
|
|
60
|
+
* to enrich the error surfaced to the calling action — agents need
|
|
61
|
+
* to see the actual V8/Node diagnostic (e.g. "JavaScript heap out
|
|
62
|
+
* of memory") rather than an opaque "Worker process crashed".
|
|
63
|
+
*/
|
|
64
|
+
stderrTail: string;
|
|
39
65
|
}
|
|
40
66
|
|
|
67
|
+
/** Max bytes of stderr we keep per worker for crash diagnostics. 64KB is
|
|
68
|
+
* big enough for a full V8 fatal-error banner + stack trace, small
|
|
69
|
+
* enough that the host can't be starved by pathological output. */
|
|
70
|
+
const STDERR_TAIL_BYTES = 64 * 1024;
|
|
71
|
+
|
|
41
72
|
/**
|
|
42
73
|
* Configuration options for worker pool
|
|
43
74
|
*/
|
|
@@ -88,8 +119,11 @@ export class WorkerPool {
|
|
|
88
119
|
*/
|
|
89
120
|
private async createWorker(id: number): Promise<void> {
|
|
90
121
|
const workerPath = path.join(__dirname, 'worker.js'); // Use .js because worker.ts is compiled
|
|
122
|
+
// stdout 'inherit' so debug logs still reach MJAPI's console.
|
|
123
|
+
// stderr 'pipe' so we can capture a rolling tail for crash diagnostics
|
|
124
|
+
// AND still forward it to MJAPI's stderr — we listen below and echo.
|
|
91
125
|
const childProcess = fork(workerPath, [], {
|
|
92
|
-
stdio: ['ignore', 'inherit', '
|
|
126
|
+
stdio: ['ignore', 'inherit', 'pipe', 'ipc']
|
|
93
127
|
});
|
|
94
128
|
|
|
95
129
|
const worker: Worker = {
|
|
@@ -98,9 +132,27 @@ export class WorkerPool {
|
|
|
98
132
|
busy: false,
|
|
99
133
|
currentRequest: null,
|
|
100
134
|
crashCount: 0,
|
|
101
|
-
lastCrashTime: 0
|
|
135
|
+
lastCrashTime: 0,
|
|
136
|
+
stderrTail: ''
|
|
102
137
|
};
|
|
103
138
|
|
|
139
|
+
// Capture stderr for crash diagnostics + forward to MJAPI stderr so
|
|
140
|
+
// operators still see it live in logs during non-crash scenarios.
|
|
141
|
+
if (childProcess.stderr) {
|
|
142
|
+
childProcess.stderr.on('data', (chunk: Buffer) => {
|
|
143
|
+
// Forward to parent stderr — preserves existing debug behavior.
|
|
144
|
+
// Convert to string first since Node's ArrayBuffer types differ
|
|
145
|
+
// between versions and writing the Buffer directly trips TS.
|
|
146
|
+
const str = chunk.toString('utf8');
|
|
147
|
+
process.stderr.write(str);
|
|
148
|
+
// Append to rolling tail, truncating from the front.
|
|
149
|
+
worker.stderrTail += str;
|
|
150
|
+
if (worker.stderrTail.length > STDERR_TAIL_BYTES) {
|
|
151
|
+
worker.stderrTail = worker.stderrTail.slice(-STDERR_TAIL_BYTES);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
104
156
|
this.workers[id] = worker;
|
|
105
157
|
|
|
106
158
|
// Wait for ready message
|
|
@@ -136,7 +188,15 @@ export class WorkerPool {
|
|
|
136
188
|
}
|
|
137
189
|
|
|
138
190
|
/**
|
|
139
|
-
* Handle messages from worker process
|
|
191
|
+
* Handle messages from worker process.
|
|
192
|
+
*
|
|
193
|
+
* Types:
|
|
194
|
+
* - `ready` — initial startup / post-restart signal, ignored here.
|
|
195
|
+
* - `result` / `error` — the terminal outcome of the current execute() call.
|
|
196
|
+
* - `bridge-call` — a host-service request from inside the sandbox; we
|
|
197
|
+
* look up the registered handler and send back `bridge-response`.
|
|
198
|
+
* Critically, `bridge-call` does NOT end the request; the worker is
|
|
199
|
+
* still executing until it sends `result`/`error`.
|
|
140
200
|
*/
|
|
141
201
|
private handleWorkerMessage(worker: Worker, message: any): void {
|
|
142
202
|
if (message.type === 'ready') {
|
|
@@ -144,26 +204,125 @@ export class WorkerPool {
|
|
|
144
204
|
return;
|
|
145
205
|
}
|
|
146
206
|
|
|
207
|
+
if (message.type === 'bridge-call') {
|
|
208
|
+
// Dispatch to the registered handler for this execution.
|
|
209
|
+
void this.handleBridgeCall(worker, message);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
147
213
|
if (!worker.currentRequest) {
|
|
148
214
|
LogError(new Error(`Worker ${worker.id} sent message but has no current request`));
|
|
149
215
|
return;
|
|
150
216
|
}
|
|
151
217
|
|
|
218
|
+
// If the worker included a requestId, make sure it matches — this
|
|
219
|
+
// catches stale messages from aborted executions. Legacy test
|
|
220
|
+
// harnesses (and very old workers) don't include a requestId; in
|
|
221
|
+
// that case fall through and treat the message as belonging to the
|
|
222
|
+
// current request.
|
|
223
|
+
if (message.requestId && message.requestId !== worker.currentRequest.requestId) {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
152
227
|
const request = worker.currentRequest;
|
|
228
|
+
|
|
229
|
+
if (message.type === 'result' || message.type === 'error') {
|
|
230
|
+
this.settleRequest(worker, request, message);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Finalize a request once the worker reports `result` or `error`.
|
|
236
|
+
* Clears timeouts, detaches abort listeners, frees the worker, and
|
|
237
|
+
* drains the queue.
|
|
238
|
+
*/
|
|
239
|
+
private settleRequest(
|
|
240
|
+
worker: Worker,
|
|
241
|
+
request: PendingRequest,
|
|
242
|
+
message: { type: 'result' | 'error'; result?: CodeExecutionResult; error?: string }
|
|
243
|
+
): void {
|
|
153
244
|
clearTimeout(request.timeout);
|
|
245
|
+
this.detachAbortListener(request);
|
|
154
246
|
|
|
155
247
|
if (message.type === 'result') {
|
|
156
|
-
request.resolve(message.result);
|
|
157
|
-
} else
|
|
158
|
-
request.reject(new Error(message.error));
|
|
248
|
+
request.resolve(message.result!);
|
|
249
|
+
} else {
|
|
250
|
+
request.reject(new Error(message.error ?? 'Worker returned error'));
|
|
159
251
|
}
|
|
160
252
|
|
|
161
|
-
// Mark worker as available and process queue
|
|
162
253
|
worker.busy = false;
|
|
163
254
|
worker.currentRequest = null;
|
|
164
255
|
this.processQueue();
|
|
165
256
|
}
|
|
166
257
|
|
|
258
|
+
/**
|
|
259
|
+
* Route a `bridge-call` from the worker to the registered host handler,
|
|
260
|
+
* execute it, and send `bridge-response` back. All error paths here
|
|
261
|
+
* produce a response with `error` populated so the sandbox's
|
|
262
|
+
* `await __bridgeCall(...)` rejects cleanly rather than hanging.
|
|
263
|
+
*/
|
|
264
|
+
private async handleBridgeCall(
|
|
265
|
+
worker: Worker,
|
|
266
|
+
message: {
|
|
267
|
+
type: 'bridge-call';
|
|
268
|
+
requestId: string;
|
|
269
|
+
callId: string;
|
|
270
|
+
functionName: string;
|
|
271
|
+
args: unknown;
|
|
272
|
+
}
|
|
273
|
+
): Promise<void> {
|
|
274
|
+
const sendResponse = (payload: { result?: unknown; error?: string }) => {
|
|
275
|
+
try {
|
|
276
|
+
worker.process.send({
|
|
277
|
+
type: 'bridge-response',
|
|
278
|
+
requestId: message.requestId,
|
|
279
|
+
callId: message.callId,
|
|
280
|
+
...payload
|
|
281
|
+
});
|
|
282
|
+
} catch (err) {
|
|
283
|
+
LogError(
|
|
284
|
+
new Error(
|
|
285
|
+
`Failed to send bridge-response to worker ${worker.id}: ${
|
|
286
|
+
err instanceof Error ? err.message : String(err)
|
|
287
|
+
}`
|
|
288
|
+
)
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
if (!worker.currentRequest || worker.currentRequest.requestId !== message.requestId) {
|
|
294
|
+
sendResponse({ error: 'No active execution for this bridge call.' });
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const handlers = worker.currentRequest.bridgeHandlers;
|
|
299
|
+
if (!handlers) {
|
|
300
|
+
sendResponse({
|
|
301
|
+
error:
|
|
302
|
+
`Runtime action tried to call '${message.functionName}' but no bridge ` +
|
|
303
|
+
'handlers were registered for this execution.'
|
|
304
|
+
});
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const handler = handlers[message.functionName];
|
|
309
|
+
if (!handler) {
|
|
310
|
+
sendResponse({
|
|
311
|
+
error:
|
|
312
|
+
`Bridge handler '${message.functionName}' is not registered. ` +
|
|
313
|
+
`Available: ${Object.keys(handlers).join(', ') || '(none)'}.`
|
|
314
|
+
});
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
try {
|
|
319
|
+
const result = await handler(message.args);
|
|
320
|
+
sendResponse({ result });
|
|
321
|
+
} catch (err) {
|
|
322
|
+
sendResponse({ error: err instanceof Error ? err.message : String(err) });
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
167
326
|
/**
|
|
168
327
|
* Handle worker process crash
|
|
169
328
|
*/
|
|
@@ -179,17 +338,19 @@ export class WorkerPool {
|
|
|
179
338
|
}
|
|
180
339
|
worker.lastCrashTime = now;
|
|
181
340
|
|
|
341
|
+
const diagnostic = classifyWorkerCrash(code, signal, worker.stderrTail);
|
|
342
|
+
|
|
182
343
|
LogError(new Error(
|
|
183
344
|
`Worker ${worker.id} crashed (code: ${code}, signal: ${signal}). ` +
|
|
345
|
+
`Reason: ${diagnostic.reason}. ` +
|
|
184
346
|
`Crash count: ${worker.crashCount}/${this.maxCrashesPerWorker}`
|
|
185
347
|
));
|
|
186
348
|
|
|
187
349
|
// Reject current request if any
|
|
188
350
|
if (worker.currentRequest) {
|
|
189
351
|
clearTimeout(worker.currentRequest.timeout);
|
|
190
|
-
worker.currentRequest
|
|
191
|
-
|
|
192
|
-
));
|
|
352
|
+
this.detachAbortListener(worker.currentRequest);
|
|
353
|
+
worker.currentRequest.reject(new Error(diagnostic.userMessage));
|
|
193
354
|
worker.currentRequest = null;
|
|
194
355
|
}
|
|
195
356
|
|
|
@@ -239,27 +400,43 @@ export class WorkerPool {
|
|
|
239
400
|
return new Promise<CodeExecutionResult>((resolve, reject) => {
|
|
240
401
|
// Create timeout for entire request (includes queue time + execution)
|
|
241
402
|
const totalTimeout = ((params.timeoutSeconds || 30) + 5) * 1000; // Add 5s buffer for overhead
|
|
242
|
-
const timeout = setTimeout(() => {
|
|
243
|
-
// Remove from queue if still there
|
|
244
|
-
const queueIndex = this.requestQueue.findIndex(r => r.requestId === requestId);
|
|
245
|
-
if (queueIndex >= 0) {
|
|
246
|
-
this.requestQueue.splice(queueIndex, 1);
|
|
247
|
-
}
|
|
248
|
-
resolve({
|
|
249
|
-
success: false,
|
|
250
|
-
error: 'Request timed out waiting for worker availability',
|
|
251
|
-
errorType: 'TIMEOUT'
|
|
252
|
-
});
|
|
253
|
-
}, totalTimeout);
|
|
254
403
|
|
|
255
404
|
const request: PendingRequest = {
|
|
256
405
|
requestId,
|
|
257
406
|
params,
|
|
407
|
+
bridgeHandlers: params.bridgeHandlers,
|
|
258
408
|
resolve,
|
|
259
409
|
reject,
|
|
260
|
-
|
|
410
|
+
// placeholder — reassigned below once we have the request ref
|
|
411
|
+
timeout: null as unknown as NodeJS.Timeout
|
|
261
412
|
};
|
|
262
413
|
|
|
414
|
+
request.timeout = setTimeout(() => {
|
|
415
|
+
// If the worker is still processing, tell it to abort its
|
|
416
|
+
// in-flight bridge calls first — the sandbox's await will
|
|
417
|
+
// reject cleanly. Then reject on our side.
|
|
418
|
+
this.abortRequest(request, 'Request timed out waiting for worker availability');
|
|
419
|
+
}, totalTimeout);
|
|
420
|
+
|
|
421
|
+
// Mirror any caller-supplied AbortSignal into the same abort path.
|
|
422
|
+
if (params.abortSignal) {
|
|
423
|
+
const listener = () => {
|
|
424
|
+
this.abortRequest(
|
|
425
|
+
request,
|
|
426
|
+
typeof params.abortSignal!.reason === 'string'
|
|
427
|
+
? params.abortSignal!.reason
|
|
428
|
+
: 'Caller aborted'
|
|
429
|
+
);
|
|
430
|
+
};
|
|
431
|
+
request.abortListener = listener;
|
|
432
|
+
if (params.abortSignal.aborted) {
|
|
433
|
+
// Fire immediately if caller aborted before we even queued.
|
|
434
|
+
setImmediate(listener);
|
|
435
|
+
} else {
|
|
436
|
+
params.abortSignal.addEventListener('abort', listener, { once: true });
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
263
440
|
// Add to queue
|
|
264
441
|
this.requestQueue.push(request);
|
|
265
442
|
|
|
@@ -268,6 +445,81 @@ export class WorkerPool {
|
|
|
268
445
|
});
|
|
269
446
|
}
|
|
270
447
|
|
|
448
|
+
/**
|
|
449
|
+
* Abort an in-flight or queued request.
|
|
450
|
+
*
|
|
451
|
+
* If the request is still queued, removes it and resolves with a TIMEOUT
|
|
452
|
+
* result (no worker ever picked it up). If a worker is actively running
|
|
453
|
+
* it, sends an `abort` IPC message so the worker rejects its pending
|
|
454
|
+
* bridge calls cleanly, then resolves with a TIMEOUT result. The worker
|
|
455
|
+
* will still send its eventual `result` / `error` message when the
|
|
456
|
+
* sandbox unwinds; `handleWorkerMessage` drops it because
|
|
457
|
+
* `worker.currentRequest` is already cleared.
|
|
458
|
+
*/
|
|
459
|
+
private abortRequest(request: PendingRequest, reason: string): void {
|
|
460
|
+
if (request.aborted) return;
|
|
461
|
+
request.aborted = true;
|
|
462
|
+
|
|
463
|
+
// Remove from queue if still waiting.
|
|
464
|
+
const queueIndex = this.requestQueue.findIndex(r => r.requestId === request.requestId);
|
|
465
|
+
if (queueIndex >= 0) {
|
|
466
|
+
this.requestQueue.splice(queueIndex, 1);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// If a worker is actively running this request, tell it to abort
|
|
470
|
+
// pending bridge calls. We do NOT kill the worker — the sandbox
|
|
471
|
+
// script will unwind naturally once its awaits reject.
|
|
472
|
+
const activeWorker = this.workers.find(
|
|
473
|
+
w => w && w.currentRequest && w.currentRequest.requestId === request.requestId
|
|
474
|
+
);
|
|
475
|
+
if (activeWorker && activeWorker.process.connected) {
|
|
476
|
+
try {
|
|
477
|
+
activeWorker.process.send({
|
|
478
|
+
type: 'abort',
|
|
479
|
+
requestId: request.requestId,
|
|
480
|
+
reason
|
|
481
|
+
});
|
|
482
|
+
} catch (err) {
|
|
483
|
+
LogError(
|
|
484
|
+
new Error(
|
|
485
|
+
`Failed to send abort to worker ${activeWorker.id}: ${
|
|
486
|
+
err instanceof Error ? err.message : String(err)
|
|
487
|
+
}`
|
|
488
|
+
)
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
// Decouple the request from the worker so the eventual
|
|
492
|
+
// result/error message is ignored by handleWorkerMessage. Leave
|
|
493
|
+
// worker.busy=true so we don't queue fresh work onto a worker
|
|
494
|
+
// that's still winding down; it'll flip back when the stale
|
|
495
|
+
// result arrives (and the `requestId !== worker.currentRequest`
|
|
496
|
+
// guard in handleWorkerMessage catches it).
|
|
497
|
+
activeWorker.currentRequest = null;
|
|
498
|
+
// Allow the worker to accept fresh work as soon as it's ready;
|
|
499
|
+
// the pool will swing back around on the next settle from the
|
|
500
|
+
// stale message because we won't match the requestId.
|
|
501
|
+
activeWorker.busy = false;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
clearTimeout(request.timeout);
|
|
505
|
+
this.detachAbortListener(request);
|
|
506
|
+
|
|
507
|
+
request.resolve({
|
|
508
|
+
success: false,
|
|
509
|
+
error: reason,
|
|
510
|
+
errorType: 'TIMEOUT'
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
this.processQueue();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
private detachAbortListener(request: PendingRequest): void {
|
|
517
|
+
if (request.params.abortSignal && request.abortListener) {
|
|
518
|
+
request.params.abortSignal.removeEventListener('abort', request.abortListener);
|
|
519
|
+
request.abortListener = undefined;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
271
523
|
/**
|
|
272
524
|
* Process queued requests by assigning them to available workers
|
|
273
525
|
*/
|
|
@@ -292,11 +544,16 @@ export class WorkerPool {
|
|
|
292
544
|
worker.busy = true;
|
|
293
545
|
worker.currentRequest = request;
|
|
294
546
|
|
|
295
|
-
// Send execution request to worker
|
|
547
|
+
// Send execution request to worker — strip non-serializable fields
|
|
548
|
+
// (`bridgeHandlers` are functions, `abortSignal` is a live object).
|
|
549
|
+
const ipcParams = { ...request.params } as CodeExecutionParams;
|
|
550
|
+
delete (ipcParams as { bridgeHandlers?: unknown }).bridgeHandlers;
|
|
551
|
+
delete (ipcParams as { abortSignal?: unknown }).abortSignal;
|
|
552
|
+
|
|
296
553
|
worker.process.send({
|
|
297
554
|
type: 'execute',
|
|
298
555
|
requestId: request.requestId,
|
|
299
|
-
params:
|
|
556
|
+
params: ipcParams
|
|
300
557
|
});
|
|
301
558
|
|
|
302
559
|
// Try to process more if queue has items
|
|
@@ -335,6 +592,7 @@ export class WorkerPool {
|
|
|
335
592
|
// Reject all queued requests
|
|
336
593
|
for (const request of this.requestQueue) {
|
|
337
594
|
clearTimeout(request.timeout);
|
|
595
|
+
this.detachAbortListener(request);
|
|
338
596
|
request.resolve({
|
|
339
597
|
success: false,
|
|
340
598
|
error: 'Worker pool is shutting down',
|
|
@@ -370,3 +628,117 @@ export class WorkerPool {
|
|
|
370
628
|
LogStatus('Worker pool shutdown complete');
|
|
371
629
|
}
|
|
372
630
|
}
|
|
631
|
+
|
|
632
|
+
/**
|
|
633
|
+
* Classify an unexpected worker-process exit into an actionable error.
|
|
634
|
+
*
|
|
635
|
+
* "Worker process crashed" by itself is useless to a downstream AI agent
|
|
636
|
+
* trying to fix its Runtime action code — it doesn't know whether the
|
|
637
|
+
* problem is a memory leak, a bad native call, or a runaway loop. This
|
|
638
|
+
* helper inspects the Node exit `code`, kill `signal`, and the tail of
|
|
639
|
+
* stderr the worker emitted before dying, then returns:
|
|
640
|
+
*
|
|
641
|
+
* - `reason`: short label for logs
|
|
642
|
+
* - `userMessage`: the human-readable message surfaced all the way to
|
|
643
|
+
* the action's `message` field. Includes a "what to
|
|
644
|
+
* do about it" hint so agents can self-correct.
|
|
645
|
+
*/
|
|
646
|
+
function classifyWorkerCrash(
|
|
647
|
+
code: number | null,
|
|
648
|
+
signal: string | null,
|
|
649
|
+
stderrTail: string
|
|
650
|
+
): { reason: string; userMessage: string } {
|
|
651
|
+
const stderr = (stderrTail || '').trim();
|
|
652
|
+
const stderrForUser = stderr
|
|
653
|
+
? `\n\nWorker stderr (last ${STDERR_TAIL_BYTES / 1024}KB):\n${stderr.length > 4000 ? stderr.slice(-4000) : stderr}`
|
|
654
|
+
: '';
|
|
655
|
+
|
|
656
|
+
// 1) V8 Node-heap OOM — usually `code=134` + stderr with "JavaScript
|
|
657
|
+
// heap out of memory" banner.
|
|
658
|
+
if (/heap out of memory|Allocation failed/i.test(stderr) || code === 134) {
|
|
659
|
+
return {
|
|
660
|
+
reason: 'NODE_HEAP_OOM',
|
|
661
|
+
userMessage:
|
|
662
|
+
"Sandbox worker ran out of Node.js heap memory. The most common cause is a RunView / RunViews call that returned too many rows (e.g. `MaxRows: 0` against a high-volume table like `MJ: AI Prompt Runs`). Fix the Runtime action code to (a) cap `MaxRows` to a reasonable number, (b) add a time-window filter, or (c) page through results instead of loading everything at once." +
|
|
663
|
+
stderrForUser
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// 2) isolated-vm memory-limit OOM propagated from the v8 isolate via
|
|
668
|
+
// the standard "Array buffer allocation failed" / "out of memory"
|
|
669
|
+
// patterns. Separate from node-heap OOM because the fix is the
|
|
670
|
+
// same but the surface is different.
|
|
671
|
+
if (/out of memory|RangeError.*memory/i.test(stderr)) {
|
|
672
|
+
return {
|
|
673
|
+
reason: 'ISOLATE_OOM',
|
|
674
|
+
userMessage:
|
|
675
|
+
'Sandbox isolated-vm ran out of memory (128MB default). Reduce the data volume the Runtime action loads — cap `MaxRows`, narrow the ExtraFilter, or process in batches. Avoid pulling whole rows when you only need a few columns; project with `Fields` where supported.' +
|
|
676
|
+
stderrForUser
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// 3) Linux OOM killer — kernel killed the process because system
|
|
681
|
+
// memory was exhausted. code=null + signal='SIGKILL' is the
|
|
682
|
+
// canonical signature; stderr is often empty (the kernel doesn't
|
|
683
|
+
// let the process write anything before the kill).
|
|
684
|
+
if (signal === 'SIGKILL') {
|
|
685
|
+
return {
|
|
686
|
+
reason: 'KERNEL_SIGKILL',
|
|
687
|
+
userMessage:
|
|
688
|
+
'Sandbox worker was killed by the OS (SIGKILL). The most likely cause is the Linux OOM killer reclaiming memory under pressure — your Runtime action or the bridge result was large enough to put the host under memory stress. Reduce the data volume: cap `MaxRows`, narrow filters, or page through results.' +
|
|
689
|
+
stderrForUser
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// 4) Native crash — segfault, bus error, abort. ivm / v8 bugs, or
|
|
694
|
+
// passing something ExternalCopy cannot serialize.
|
|
695
|
+
if (signal === 'SIGSEGV' || signal === 'SIGBUS') {
|
|
696
|
+
return {
|
|
697
|
+
reason: 'NATIVE_CRASH',
|
|
698
|
+
userMessage:
|
|
699
|
+
`Sandbox worker crashed with native signal ${signal} — usually an isolated-vm / V8 fault, not something your code can fix directly. Common triggers include passing very deeply-nested objects or circular references through the utilities bridge. Simplify the values you return from RunView / actions before using them.` +
|
|
700
|
+
stderrForUser
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
if (signal === 'SIGABRT') {
|
|
704
|
+
return {
|
|
705
|
+
reason: 'PROCESS_ABORT',
|
|
706
|
+
userMessage:
|
|
707
|
+
'Sandbox worker aborted (SIGABRT). Usually triggered by an unrecoverable v8 assertion or a failed native check — often the same class of issue as a segfault. If this is reproducible, reduce the size and complexity of data your code allocates.' +
|
|
708
|
+
stderrForUser
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// 5) Maximum call stack — v8 throws a catchable RangeError normally,
|
|
713
|
+
// but in deep-native contexts (ivm bridge marshaling, sync
|
|
714
|
+
// callbacks) it can escape and kill the process. Signature is
|
|
715
|
+
// usually stderr mentioning "Maximum call stack size exceeded"
|
|
716
|
+
// with code=1.
|
|
717
|
+
if (/Maximum call stack|stack size exceeded/i.test(stderr)) {
|
|
718
|
+
return {
|
|
719
|
+
reason: 'STACK_OVERFLOW',
|
|
720
|
+
userMessage:
|
|
721
|
+
'Sandbox worker hit a stack overflow. Likely a recursive function with no base case, or a call pattern that recurses indirectly through the utilities bridge. Review loops and recursion in your Runtime action code.' +
|
|
722
|
+
stderrForUser
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// 6) Uncaught JS exception — code=1 with stderr containing a stack.
|
|
727
|
+
if (code === 1 && stderr.length > 0) {
|
|
728
|
+
return {
|
|
729
|
+
reason: 'UNCAUGHT_EXCEPTION',
|
|
730
|
+
userMessage:
|
|
731
|
+
'Sandbox worker crashed on an uncaught exception before the isolate could wrap it. Check the stderr tail below for the offending JS trace.' +
|
|
732
|
+
stderrForUser
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// 7) Unknown / fallback — still include exit metadata and stderr so
|
|
737
|
+
// the agent has SOMETHING to act on.
|
|
738
|
+
return {
|
|
739
|
+
reason: 'UNKNOWN',
|
|
740
|
+
userMessage:
|
|
741
|
+
`Sandbox worker process exited unexpectedly (code=${code}, signal=${signal}). The Runtime action code may be triggering a low-level issue in the sandbox. Simplify the code and retry.` +
|
|
742
|
+
stderrForUser
|
|
743
|
+
};
|
|
744
|
+
}
|
|
@@ -125,7 +125,9 @@ describe('WorkerPool', () => {
|
|
|
125
125
|
expect.stringContaining('worker.js'),
|
|
126
126
|
[],
|
|
127
127
|
expect.objectContaining({
|
|
128
|
-
|
|
128
|
+
// stderr is 'pipe' so the pool can capture a rolling tail for
|
|
129
|
+
// crash diagnostics while still forwarding it to MJAPI stderr.
|
|
130
|
+
stdio: ['ignore', 'inherit', 'pipe', 'ipc']
|
|
129
131
|
})
|
|
130
132
|
);
|
|
131
133
|
});
|
|
@@ -342,8 +344,10 @@ describe('WorkerPool', () => {
|
|
|
342
344
|
// Simulate the worker crashing
|
|
343
345
|
mockProcesses[0].simulateCrash(1, 'SIGSEGV');
|
|
344
346
|
|
|
345
|
-
// The promise should reject
|
|
346
|
-
|
|
347
|
+
// The promise should reject with the enriched diagnostic — the
|
|
348
|
+
// classifier recognizes SIGSEGV as a native crash and surfaces
|
|
349
|
+
// actionable guidance instead of the old opaque message.
|
|
350
|
+
await expect(executePromise).rejects.toThrow(/SIGSEGV/);
|
|
347
351
|
});
|
|
348
352
|
|
|
349
353
|
it('should attempt to restart crashed workers', async () => {
|