@genroc/eval-node 0.0.0-edge.ea911c5 → 0.0.0-edge.eaf0756c
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/LICENSE +202 -0
- package/README.md +114 -289
- package/dist/eval.js +27 -15
- package/dist/import.js +119 -119
- package/dist/realm.js +12 -17
- package/dist/worker.js +80 -75
- package/eval.ts +30 -21
- package/import.ts +175 -148
- package/package.json +1 -1
- package/realm.ts +12 -17
- package/worker.ts +88 -79
package/dist/worker.js
CHANGED
|
@@ -1,50 +1,44 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The queue worker: claims parked `external` script tasks
|
|
3
|
-
//
|
|
4
|
-
// nothing about the queue, which is what keeps the containment strategy swappable.
|
|
5
|
-
//
|
|
6
|
-
// See README.md for the contract, and specs/external-task-queue.md for the queue itself.
|
|
2
|
+
// The queue worker: claims parked `external` script tasks, evaluates each in its own realm, and
|
|
3
|
+
// answers. The only genroc-facing half (README.md; specs/external-task-queue.md).
|
|
7
4
|
import { readFileSync } from "node:fs";
|
|
8
|
-
import { evaluate } from "./eval.js";
|
|
5
|
+
import { Cancelled, evaluate } from "./eval.js";
|
|
9
6
|
const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
|
|
10
7
|
const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// trust least. specs/api-auth.md §5.
|
|
15
|
-
//
|
|
16
|
-
// Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
|
|
17
|
-
// credentials ("Request cannot be constructed from a URL that includes credentials"), so the
|
|
18
|
-
// basic-auth-in-the-URL trick that works for genctl is not available here.
|
|
19
|
-
// GENROC_TOKEN_FILE is the mounted-secret shape: a credential in a file rather than an
|
|
20
|
-
// environment variable, so it stays out of `docker inspect` and out of the process environment
|
|
21
|
-
// any child inherits. The inline variable wins when both are set.
|
|
8
|
+
// Needs only the `worker` permission (specs/api-auth.md §5): this credential sits on the machine
|
|
9
|
+
// you trust least. A header, because Node's fetch refuses credentials in a URL. The file form
|
|
10
|
+
// keeps it out of `docker inspect` and child environments; the inline variable wins.
|
|
22
11
|
const TOKEN = process.env.GENROC_TOKEN ??
|
|
23
12
|
(process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
|
|
24
13
|
const authHeaders = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
// evaluator accepted every one of them. Here it claims what it can run and no more, so a
|
|
28
|
-
// backlog is a queue rather than 200 threads fighting over a core.
|
|
14
|
+
// The worker claims only what it can run, so a backlog is a queue rather than threads fighting
|
|
15
|
+
// over a core.
|
|
29
16
|
const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
|
|
30
17
|
const POLL_MS = Number(process.env.POLL_MS ?? 250);
|
|
31
18
|
// The visibility timeout. Short, and renewed while work is in flight: a worker that dies
|
|
32
19
|
// should return its task quickly rather than holding it for the whole budget.
|
|
33
20
|
const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
|
|
34
21
|
const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
//
|
|
39
|
-
//
|
|
22
|
+
// The answer has to land before the task's deadline fires, or a script that overran surfaces as
|
|
23
|
+
// external.timeout ("nobody answered") rather than as its own `timeout`.
|
|
24
|
+
const ANSWER_MARGIN_MS = 250;
|
|
25
|
+
// script-node's names; a renamed copy sets PROCESS. The claim requires both: this worker answers
|
|
26
|
+
// one task's contract, so it must never be handed another's.
|
|
27
|
+
const PROCESS_FILTER = process.env.PROCESS ?? "script-node";
|
|
28
|
+
const TASK_FILTER = process.env.TASK ?? "eval_node";
|
|
29
|
+
if (!PROCESS_FILTER || !TASK_FILTER) {
|
|
30
|
+
console.error("PROCESS and TASK must both name the queue this worker serves; neither may be empty.");
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
// Large values arrive as refs; a bundle is one object per definition version, fetched once.
|
|
34
|
+
// Refs are content hashes, so the cache never invalidates.
|
|
40
35
|
const objectCache = new Map();
|
|
41
36
|
async function fetchObject(ref) {
|
|
42
37
|
const cached = objectCache.get(ref);
|
|
43
38
|
if (cached !== undefined)
|
|
44
39
|
return cached;
|
|
45
|
-
// Left to throw
|
|
46
|
-
//
|
|
47
|
-
// releases the claim, so the task returns to the queue.
|
|
40
|
+
// Left to throw: a task whose input cannot be fetched must not run against a missing value.
|
|
41
|
+
// The caller releases the claim.
|
|
48
42
|
const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
|
|
49
43
|
if (!res.ok)
|
|
50
44
|
throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
|
|
@@ -62,15 +56,15 @@ async function fetchObject(ref) {
|
|
|
62
56
|
/** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
|
|
63
57
|
* needs no parser: the whole reason they are not JSON Pointer strings. */
|
|
64
58
|
async function resolveObjects(job) {
|
|
65
|
-
let input = job.
|
|
59
|
+
let input = job.external_input;
|
|
66
60
|
for (const e of job.objects ?? []) {
|
|
67
61
|
const value = await fetchObject(e.ref);
|
|
68
62
|
if (e.path.length === 0) {
|
|
69
63
|
input = value;
|
|
70
64
|
continue;
|
|
71
65
|
}
|
|
72
|
-
// The path is rooted at the entry and starts with "
|
|
73
|
-
const rest = e.path[0] === "
|
|
66
|
+
// The path is rooted at the entry and starts with "external_input", the value being rebuilt.
|
|
67
|
+
const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
|
|
74
68
|
if (rest.length === 0) {
|
|
75
69
|
input = value;
|
|
76
70
|
continue;
|
|
@@ -84,10 +78,8 @@ async function resolveObjects(job) {
|
|
|
84
78
|
return input;
|
|
85
79
|
}
|
|
86
80
|
async function call(path, body) {
|
|
87
|
-
// A network error is a REPLY
|
|
88
|
-
//
|
|
89
|
-
// unhandled rejection here kills it for a condition the next poll would clear. Status 0
|
|
90
|
-
// says "never reached the server", which is distinct from anything genroc answers.
|
|
81
|
+
// A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
|
|
82
|
+
// outlives restarts and deploys, and an unhandled rejection would kill it.
|
|
91
83
|
let res;
|
|
92
84
|
try {
|
|
93
85
|
res = await fetch(SERVER + path, {
|
|
@@ -109,49 +101,39 @@ async function call(path, body) {
|
|
|
109
101
|
}
|
|
110
102
|
return { ok: res.ok, status: res.status, data };
|
|
111
103
|
}
|
|
112
|
-
/**
|
|
113
|
-
*
|
|
114
|
-
|
|
115
|
-
function asEvalRequest(input) {
|
|
104
|
+
/** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
|
|
105
|
+
* the nearest permanent kind, since no retry fixes the definition. */
|
|
106
|
+
function asEvalRequest(input, timeoutMs) {
|
|
116
107
|
if (typeof input !== "object" || input === null)
|
|
117
108
|
return "the task input is not an object";
|
|
118
109
|
const r = input;
|
|
119
110
|
if (typeof r.code !== "string")
|
|
120
111
|
return "the task input has no `code` string";
|
|
121
|
-
return {
|
|
122
|
-
code: r.code,
|
|
123
|
-
input: r.input,
|
|
124
|
-
timeout_ms: typeof r.timeout_ms === "number" ? r.timeout_ms : undefined,
|
|
125
|
-
};
|
|
112
|
+
return { code: r.code, input: r.input, timeout_ms: timeoutMs };
|
|
126
113
|
}
|
|
127
114
|
const inFlight = new Map();
|
|
128
115
|
let running = true;
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
// buries the one line that mattered. Announce the TRANSITIONS instead: going away, and coming
|
|
132
|
-
// back. Silence in between is the report that nothing changed.
|
|
116
|
+
// Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
|
|
117
|
+
// thousands of lines during a restart.
|
|
133
118
|
let serverReachable = true;
|
|
134
119
|
async function claim(n) {
|
|
135
120
|
const { ok, status, data } = await call("/api/external-tasks/claim", {
|
|
136
121
|
worker_id: WORKER_ID,
|
|
137
122
|
limit: n,
|
|
138
123
|
lease_ms: LEASE_MS,
|
|
139
|
-
|
|
140
|
-
|
|
124
|
+
process: PROCESS_FILTER,
|
|
125
|
+
task: TASK_FILTER,
|
|
141
126
|
});
|
|
142
127
|
if (!ok) {
|
|
143
|
-
// A credential problem is not transient, and polling through it looks like a healthy
|
|
144
|
-
// worker
|
|
145
|
-
// instead, so a supervisor restarts it and the failure is visible where it happened.
|
|
128
|
+
// A credential problem is not transient, and polling through it looks like a healthy idle
|
|
129
|
+
// worker. Exit, so a supervisor restarts it visibly.
|
|
146
130
|
if (status === 401 || status === 403) {
|
|
147
131
|
console.error(`claim rejected (${status}): ${JSON.stringify(data)}\n` +
|
|
148
132
|
`The server requires authentication. Set GENROC_TOKEN to a token with the 'worker' ` +
|
|
149
133
|
`permission — mint one with: genctl token create --perms worker --label evaluator -q`);
|
|
150
134
|
process.exit(1);
|
|
151
135
|
}
|
|
152
|
-
// status 0
|
|
153
|
-
// network blip. Not an error to act on — the next poll clears it — so it is reported once
|
|
154
|
-
// and then waited out.
|
|
136
|
+
// status 0 (see call): a restart or blip the next poll clears, so it is reported once.
|
|
155
137
|
if (status === 0) {
|
|
156
138
|
if (serverReachable) {
|
|
157
139
|
serverReachable = false;
|
|
@@ -174,10 +156,8 @@ async function release(token) {
|
|
|
174
156
|
if (!ok)
|
|
175
157
|
console.error(`release failed: ${JSON.stringify(data)}`);
|
|
176
158
|
}
|
|
177
|
-
/**
|
|
178
|
-
*
|
|
179
|
-
* not fit `raises`), and guessing again would only pick a second wrong answer. Release it, so
|
|
180
|
-
* the task returns to the queue and an operator sees it waiting rather than silently gone. */
|
|
159
|
+
/** A refused outcome is not retried with another: the worker does not satisfy the declared
|
|
160
|
+
* contract. Released, so an operator sees the task waiting rather than gone. */
|
|
181
161
|
async function answer(token, outcome) {
|
|
182
162
|
const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
|
|
183
163
|
if (ok)
|
|
@@ -185,7 +165,10 @@ async function answer(token, outcome) {
|
|
|
185
165
|
console.error(`genroc refused the outcome for ${token}: ${JSON.stringify(data)}`);
|
|
186
166
|
await release(token);
|
|
187
167
|
}
|
|
188
|
-
async function run(job) {
|
|
168
|
+
async function run(job, signal) {
|
|
169
|
+
// The task's own timeout is the script's budget. Taken on arrival, because fetching the
|
|
170
|
+
// objects below spends the same deadline.
|
|
171
|
+
const due = job.deadline_in_ms === undefined ? undefined : performance.now() + job.deadline_in_ms;
|
|
189
172
|
let resolved;
|
|
190
173
|
try {
|
|
191
174
|
resolved = await resolveObjects(job);
|
|
@@ -197,7 +180,16 @@ async function run(job) {
|
|
|
197
180
|
await release(job.token);
|
|
198
181
|
return;
|
|
199
182
|
}
|
|
200
|
-
|
|
183
|
+
let timeoutMs;
|
|
184
|
+
if (due !== undefined) {
|
|
185
|
+
timeoutMs = Math.floor(due - performance.now() - ANSWER_MARGIN_MS);
|
|
186
|
+
if (timeoutMs <= 0) {
|
|
187
|
+
// Too late to run anything: the deadline fires as external.timeout, which is the truth.
|
|
188
|
+
await release(job.token);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
const req = asEvalRequest(resolved, timeoutMs);
|
|
201
193
|
if (typeof req === "string") {
|
|
202
194
|
await answer(job.token, {
|
|
203
195
|
error: { code: "compile_error", message: req, data: { name: "BadTaskInput" } },
|
|
@@ -206,13 +198,18 @@ async function run(job) {
|
|
|
206
198
|
}
|
|
207
199
|
let result;
|
|
208
200
|
try {
|
|
209
|
-
result = await evaluate(req);
|
|
201
|
+
result = await evaluate(req, signal);
|
|
210
202
|
}
|
|
211
203
|
catch (err) {
|
|
212
|
-
//
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
|
|
204
|
+
// Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
|
|
205
|
+
// but the release stops it waiting out a lease nobody serves.
|
|
206
|
+
if (err instanceof Cancelled) {
|
|
207
|
+
console.log(`cancelled: ${job.token}`);
|
|
208
|
+
await release(job.token);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
// The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
|
|
212
|
+
// and it reaches another worker without spending the definition's on_error budget.
|
|
216
213
|
console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
|
|
217
214
|
await release(job.token);
|
|
218
215
|
return;
|
|
@@ -245,11 +242,18 @@ async function renewLoop() {
|
|
|
245
242
|
tokens,
|
|
246
243
|
lease_ms: LEASE_MS,
|
|
247
244
|
});
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
//
|
|
251
|
-
|
|
252
|
-
|
|
245
|
+
if (!ok)
|
|
246
|
+
continue;
|
|
247
|
+
// Abort first rather than let a stopped script burn a core; the release rides run()'s
|
|
248
|
+
// catch, so nothing is released twice.
|
|
249
|
+
for (const token of (data?.cancelled ?? [])) {
|
|
250
|
+
inFlight.get(token)?.abort.abort();
|
|
251
|
+
}
|
|
252
|
+
// Lost: another worker holds it now and our answer will be refused; logged as the sign that
|
|
253
|
+
// LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
|
|
254
|
+
const lost = (data?.lost ?? []);
|
|
255
|
+
if (lost.length) {
|
|
256
|
+
console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
|
|
253
257
|
}
|
|
254
258
|
}
|
|
255
259
|
}
|
|
@@ -258,8 +262,9 @@ async function pollLoop() {
|
|
|
258
262
|
const free = CONCURRENCY - inFlight.size;
|
|
259
263
|
const jobs = free > 0 ? await claim(free) : [];
|
|
260
264
|
for (const job of jobs) {
|
|
261
|
-
|
|
262
|
-
|
|
265
|
+
const abort = new AbortController();
|
|
266
|
+
inFlight.set(job.token, { job, abort });
|
|
267
|
+
void run(job, abort.signal).finally(() => inFlight.delete(job.token));
|
|
263
268
|
}
|
|
264
269
|
// Only idle when there was nothing to take: a full queue should be drained at the speed the
|
|
265
270
|
// realms allow, not at the poll interval.
|
package/eval.ts
CHANGED
|
@@ -1,11 +1,6 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the containment stays swappable.
|
|
5
|
-
//
|
|
6
|
-
// The containment is a Worker per execution (realm.ts). It is what makes the budget real:
|
|
7
|
-
// a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
|
|
8
|
-
// thread the host can kill bounds it.
|
|
1
|
+
// Imports a script module in its own realm (a Worker per execution, realm.ts), calls its default
|
|
2
|
+
// export, and classifies every outcome (README.md). Only a killable thread bounds a synchronous
|
|
3
|
+
// busy loop, which is what makes the budget real. Knows nothing of genroc; worker.ts does.
|
|
9
4
|
|
|
10
5
|
import { Worker } from "node:worker_threads";
|
|
11
6
|
|
|
@@ -16,9 +11,8 @@ export type EvalRequest = {
|
|
|
16
11
|
timeout_ms?: number;
|
|
17
12
|
};
|
|
18
13
|
|
|
19
|
-
/** Every kind
|
|
20
|
-
*
|
|
21
|
-
* faults releases its claim and lets another worker take the task. */
|
|
14
|
+
/** Every kind is PERMANENT: a retry fails identically. A faulting runner is not an outcome; it
|
|
15
|
+
* releases its claim. */
|
|
22
16
|
export type FailureKind = "compile_error" | "threw" | "timeout" | "nonserializable" | "exited";
|
|
23
17
|
|
|
24
18
|
export type EvalFailure = {
|
|
@@ -28,9 +22,8 @@ export type EvalFailure = {
|
|
|
28
22
|
stack?: string;
|
|
29
23
|
};
|
|
30
24
|
|
|
31
|
-
/**
|
|
32
|
-
*
|
|
33
|
-
* crosses the worker boundary — structured clone would refuse a different set of values. */
|
|
25
|
+
/** JSON TEXT serialised in the realm, so a nonserializable return is a script fault, not a 500,
|
|
26
|
+
* and structured clone (which refuses a different set of values) never sees the value. */
|
|
34
27
|
export type EvalResult =
|
|
35
28
|
| { ok: true; body: string }
|
|
36
29
|
| { ok: false; failure: EvalFailure };
|
|
@@ -47,9 +40,8 @@ const REALM_URL = new URL(
|
|
|
47
40
|
import.meta.url,
|
|
48
41
|
);
|
|
49
42
|
|
|
50
|
-
/** Thrown, not returned: a realm that fails to start is the
|
|
51
|
-
* answers by releasing the claim
|
|
52
|
-
* return value. */
|
|
43
|
+
/** Thrown, not returned: a realm that fails to start is the runner faulting, which worker.ts
|
|
44
|
+
* answers by releasing the claim. */
|
|
53
45
|
class RealmFault extends Error {
|
|
54
46
|
constructor(message: string) {
|
|
55
47
|
super(message);
|
|
@@ -57,24 +49,41 @@ class RealmFault extends Error {
|
|
|
57
49
|
}
|
|
58
50
|
}
|
|
59
51
|
|
|
60
|
-
|
|
52
|
+
/** Thrown when `signal` aborts: the answer is no longer wanted, so worker.ts releases rather
|
|
53
|
+
* than answers. Not a RealmFault: nothing is wrong. */
|
|
54
|
+
export class Cancelled extends Error {
|
|
55
|
+
constructor() {
|
|
56
|
+
super("cancelled");
|
|
57
|
+
this.name = "Cancelled";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function evaluate(req: EvalRequest, signal?: AbortSignal): Promise<EvalResult> {
|
|
61
62
|
const budget = typeof req.timeout_ms === "number" ? req.timeout_ms : DEFAULT_TIMEOUT_MS;
|
|
62
63
|
|
|
63
64
|
const worker = new Worker(REALM_URL);
|
|
64
65
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
66
|
+
let onAbort: (() => void) | undefined;
|
|
65
67
|
try {
|
|
66
68
|
return await new Promise<EvalResult>((resolve, reject) => {
|
|
67
69
|
timer = setTimeout(() => resolve(timedOut(budget)), budget);
|
|
70
|
+
// The abort is wired to the same promise as the budget, so both settle through the one
|
|
71
|
+
// finally below -- which is what guarantees the thread is gone before either returns.
|
|
72
|
+
if (signal) {
|
|
73
|
+
if (signal.aborted) reject(new Cancelled());
|
|
74
|
+
onAbort = () => reject(new Cancelled());
|
|
75
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
76
|
+
}
|
|
68
77
|
worker.once("message", (reply: WorkerReply) => resolve(reply));
|
|
69
|
-
// A script may
|
|
70
|
-
//
|
|
71
|
-
// this too, by which time the promise has settled and the first result stands.
|
|
78
|
+
// A script may `process.exit()`, which would otherwise look like a hang until the budget.
|
|
79
|
+
// Our own terminate() fires this too, after the promise has settled.
|
|
72
80
|
worker.once("exit", (code: number) => resolve(exited(code)));
|
|
73
81
|
worker.once("error", (err: Error) => reject(new RealmFault(errorText(err))));
|
|
74
82
|
worker.postMessage({ code: req.code, input: req.input } satisfies WorkerRequest);
|
|
75
83
|
});
|
|
76
84
|
} finally {
|
|
77
85
|
clearTimeout(timer);
|
|
86
|
+
if (signal && onAbort) signal.removeEventListener("abort", onAbort);
|
|
78
87
|
// Awaited, and the whole point: on the timeout path a thread is still burning a core, and
|
|
79
88
|
// resolving before it is gone would report an evaluation the machine is still running.
|
|
80
89
|
await worker.terminate();
|