@genroc/eval-node 0.0.0-edge.dc4ff88 → 0.0.0-edge.dcfec388
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 +70 -71
- package/eval.ts +30 -21
- package/import.ts +175 -148
- package/package.json +1 -1
- package/realm.ts +12 -17
- package/worker.ts +78 -74
package/worker.ts
CHANGED
|
@@ -1,40 +1,30 @@
|
|
|
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
|
|
|
8
5
|
import { readFileSync } from "node:fs";
|
|
9
|
-
import { evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
|
|
6
|
+
import { Cancelled, evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
|
|
10
7
|
|
|
11
8
|
const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
|
|
12
9
|
const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
// trust least. specs/api-auth.md §5.
|
|
17
|
-
//
|
|
18
|
-
// Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
|
|
19
|
-
// credentials ("Request cannot be constructed from a URL that includes credentials"), so the
|
|
20
|
-
// basic-auth-in-the-URL trick that works for genctl is not available here.
|
|
21
|
-
// GENROC_TOKEN_FILE is the mounted-secret shape: a credential in a file rather than an
|
|
22
|
-
// environment variable, so it stays out of `docker inspect` and out of the process environment
|
|
23
|
-
// any child inherits. The inline variable wins when both are set.
|
|
10
|
+
// Needs only the `worker` permission (specs/api-auth.md §5): this credential sits on the machine
|
|
11
|
+
// you trust least. A header, because Node's fetch refuses credentials in a URL. The file form
|
|
12
|
+
// keeps it out of `docker inspect` and child environments; the inline variable wins.
|
|
24
13
|
const TOKEN =
|
|
25
14
|
process.env.GENROC_TOKEN ??
|
|
26
15
|
(process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
|
|
27
16
|
const authHeaders: Record<string, string> = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
// evaluator accepted every one of them. Here it claims what it can run and no more, so a
|
|
31
|
-
// backlog is a queue rather than 200 threads fighting over a core.
|
|
17
|
+
// The worker claims only what it can run, so a backlog is a queue rather than threads fighting
|
|
18
|
+
// over a core.
|
|
32
19
|
const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
|
|
33
20
|
const POLL_MS = Number(process.env.POLL_MS ?? 250);
|
|
34
21
|
// The visibility timeout. Short, and renewed while work is in flight: a worker that dies
|
|
35
22
|
// should return its task quickly rather than holding it for the whole budget.
|
|
36
23
|
const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
|
|
37
24
|
const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
|
|
25
|
+
// The answer has to land before the task's deadline fires, or a script that overran surfaces as
|
|
26
|
+
// external.timeout ("nobody answered") rather than as its own `timeout`.
|
|
27
|
+
const ANSWER_MARGIN_MS = 250;
|
|
38
28
|
const PROCESS_FILTER = process.env.PROCESS ?? "";
|
|
39
29
|
const TASK_FILTER = process.env.TASK ?? "";
|
|
40
30
|
|
|
@@ -43,23 +33,22 @@ type ObjectEntry = { path: (string | number)[]; ref: string; size: number };
|
|
|
43
33
|
type QueueTask = {
|
|
44
34
|
token: string;
|
|
45
35
|
process: string;
|
|
46
|
-
|
|
47
|
-
|
|
36
|
+
task: string;
|
|
37
|
+
external_input: unknown;
|
|
48
38
|
objects?: ObjectEntry[];
|
|
49
39
|
raises?: Record<string, unknown>;
|
|
40
|
+
deadline_in_ms?: number;
|
|
50
41
|
};
|
|
51
42
|
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
// into each task. A ref is a content hash, so it is immutable — the cache never invalidates.
|
|
43
|
+
// Large values arrive as refs; a bundle is one object per definition version, fetched once.
|
|
44
|
+
// Refs are content hashes, so the cache never invalidates.
|
|
55
45
|
const objectCache = new Map<string, unknown>();
|
|
56
46
|
|
|
57
47
|
async function fetchObject(ref: string): Promise<unknown> {
|
|
58
48
|
const cached = objectCache.get(ref);
|
|
59
49
|
if (cached !== undefined) return cached;
|
|
60
|
-
// Left to throw
|
|
61
|
-
//
|
|
62
|
-
// releases the claim, so the task returns to the queue.
|
|
50
|
+
// Left to throw: a task whose input cannot be fetched must not run against a missing value.
|
|
51
|
+
// The caller releases the claim.
|
|
63
52
|
const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
|
|
64
53
|
if (!res.ok) throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
|
|
65
54
|
const { data } = (await res.json()) as { data: string };
|
|
@@ -76,15 +65,15 @@ async function fetchObject(ref: string): Promise<unknown> {
|
|
|
76
65
|
/** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
|
|
77
66
|
* needs no parser: the whole reason they are not JSON Pointer strings. */
|
|
78
67
|
async function resolveObjects(job: QueueTask): Promise<unknown> {
|
|
79
|
-
let input: any = job.
|
|
68
|
+
let input: any = job.external_input;
|
|
80
69
|
for (const e of job.objects ?? []) {
|
|
81
70
|
const value = await fetchObject(e.ref);
|
|
82
71
|
if (e.path.length === 0) {
|
|
83
72
|
input = value;
|
|
84
73
|
continue;
|
|
85
74
|
}
|
|
86
|
-
// The path is rooted at the entry and starts with "
|
|
87
|
-
const rest = e.path[0] === "
|
|
75
|
+
// The path is rooted at the entry and starts with "external_input", the value being rebuilt.
|
|
76
|
+
const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
|
|
88
77
|
if (rest.length === 0) {
|
|
89
78
|
input = value;
|
|
90
79
|
continue;
|
|
@@ -97,10 +86,8 @@ async function resolveObjects(job: QueueTask): Promise<unknown> {
|
|
|
97
86
|
}
|
|
98
87
|
|
|
99
88
|
async function call(path: string, body: unknown): Promise<{ ok: boolean; status: number; data: any }> {
|
|
100
|
-
// A network error is a REPLY
|
|
101
|
-
//
|
|
102
|
-
// unhandled rejection here kills it for a condition the next poll would clear. Status 0
|
|
103
|
-
// says "never reached the server", which is distinct from anything genroc answers.
|
|
89
|
+
// A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
|
|
90
|
+
// outlives restarts and deploys, and an unhandled rejection would kill it.
|
|
104
91
|
let res: Response;
|
|
105
92
|
try {
|
|
106
93
|
res = await fetch(SERVER + path, {
|
|
@@ -121,27 +108,24 @@ async function call(path: string, body: unknown): Promise<{ ok: boolean; status:
|
|
|
121
108
|
return { ok: res.ok, status: res.status, data };
|
|
122
109
|
}
|
|
123
110
|
|
|
124
|
-
/**
|
|
125
|
-
*
|
|
126
|
-
|
|
127
|
-
function asEvalRequest(input: unknown): EvalRequest | string {
|
|
111
|
+
/** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
|
|
112
|
+
* the nearest permanent kind, since no retry fixes the definition. */
|
|
113
|
+
function asEvalRequest(input: unknown, timeoutMs: number | undefined): EvalRequest | string {
|
|
128
114
|
if (typeof input !== "object" || input === null) return "the task input is not an object";
|
|
129
115
|
const r = input as Record<string, unknown>;
|
|
130
116
|
if (typeof r.code !== "string") return "the task input has no `code` string";
|
|
131
|
-
return {
|
|
132
|
-
code: r.code,
|
|
133
|
-
input: r.input,
|
|
134
|
-
timeout_ms: typeof r.timeout_ms === "number" ? r.timeout_ms : undefined,
|
|
135
|
-
};
|
|
117
|
+
return { code: r.code, input: r.input, timeout_ms: timeoutMs };
|
|
136
118
|
}
|
|
137
119
|
|
|
138
|
-
|
|
120
|
+
/** genroc cannot call us, so a cancellation arrives on our own heartbeat and reaches the
|
|
121
|
+
* evaluation through the controller. */
|
|
122
|
+
type Running = { job: QueueTask; abort: AbortController };
|
|
123
|
+
|
|
124
|
+
const inFlight = new Map<string, Running>();
|
|
139
125
|
let running = true;
|
|
140
126
|
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
// buries the one line that mattered. Announce the TRANSITIONS instead: going away, and coming
|
|
144
|
-
// back. Silence in between is the report that nothing changed.
|
|
127
|
+
// Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
|
|
128
|
+
// thousands of lines during a restart.
|
|
145
129
|
let serverReachable = true;
|
|
146
130
|
|
|
147
131
|
async function claim(n: number): Promise<QueueTask[]> {
|
|
@@ -153,9 +137,8 @@ async function claim(n: number): Promise<QueueTask[]> {
|
|
|
153
137
|
...(TASK_FILTER ? { task: TASK_FILTER } : {}),
|
|
154
138
|
});
|
|
155
139
|
if (!ok) {
|
|
156
|
-
// A credential problem is not transient, and polling through it looks like a healthy
|
|
157
|
-
// worker
|
|
158
|
-
// instead, so a supervisor restarts it and the failure is visible where it happened.
|
|
140
|
+
// A credential problem is not transient, and polling through it looks like a healthy idle
|
|
141
|
+
// worker. Exit, so a supervisor restarts it visibly.
|
|
159
142
|
if (status === 401 || status === 403) {
|
|
160
143
|
console.error(
|
|
161
144
|
`claim rejected (${status}): ${JSON.stringify(data)}\n` +
|
|
@@ -164,9 +147,7 @@ async function claim(n: number): Promise<QueueTask[]> {
|
|
|
164
147
|
);
|
|
165
148
|
process.exit(1);
|
|
166
149
|
}
|
|
167
|
-
// status 0
|
|
168
|
-
// network blip. Not an error to act on — the next poll clears it — so it is reported once
|
|
169
|
-
// and then waited out.
|
|
150
|
+
// status 0 (see call): a restart or blip the next poll clears, so it is reported once.
|
|
170
151
|
if (status === 0) {
|
|
171
152
|
if (serverReachable) {
|
|
172
153
|
serverReachable = false;
|
|
@@ -192,10 +173,8 @@ async function release(token: string): Promise<void> {
|
|
|
192
173
|
if (!ok) console.error(`release failed: ${JSON.stringify(data)}`);
|
|
193
174
|
}
|
|
194
175
|
|
|
195
|
-
/**
|
|
196
|
-
*
|
|
197
|
-
* not fit `raises`), and guessing again would only pick a second wrong answer. Release it, so
|
|
198
|
-
* the task returns to the queue and an operator sees it waiting rather than silently gone. */
|
|
176
|
+
/** A refused outcome is not retried with another: the worker does not satisfy the declared
|
|
177
|
+
* contract. Released, so an operator sees the task waiting rather than gone. */
|
|
199
178
|
async function answer(token: string, outcome: Record<string, unknown>): Promise<void> {
|
|
200
179
|
const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
|
|
201
180
|
if (ok) return;
|
|
@@ -203,7 +182,10 @@ async function answer(token: string, outcome: Record<string, unknown>): Promise<
|
|
|
203
182
|
await release(token);
|
|
204
183
|
}
|
|
205
184
|
|
|
206
|
-
async function run(job: QueueTask): Promise<void> {
|
|
185
|
+
async function run(job: QueueTask, signal: AbortSignal): Promise<void> {
|
|
186
|
+
// The task's own timeout is the script's budget. Taken on arrival, because fetching the
|
|
187
|
+
// objects below spends the same deadline.
|
|
188
|
+
const due = job.deadline_in_ms === undefined ? undefined : performance.now() + job.deadline_in_ms;
|
|
207
189
|
let resolved: unknown;
|
|
208
190
|
try {
|
|
209
191
|
resolved = await resolveObjects(job);
|
|
@@ -214,7 +196,16 @@ async function run(job: QueueTask): Promise<void> {
|
|
|
214
196
|
await release(job.token);
|
|
215
197
|
return;
|
|
216
198
|
}
|
|
217
|
-
|
|
199
|
+
let timeoutMs: number | undefined;
|
|
200
|
+
if (due !== undefined) {
|
|
201
|
+
timeoutMs = Math.floor(due - performance.now() - ANSWER_MARGIN_MS);
|
|
202
|
+
if (timeoutMs <= 0) {
|
|
203
|
+
// Too late to run anything: the deadline fires as external.timeout, which is the truth.
|
|
204
|
+
await release(job.token);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const req = asEvalRequest(resolved, timeoutMs);
|
|
218
209
|
if (typeof req === "string") {
|
|
219
210
|
await answer(job.token, {
|
|
220
211
|
error: { code: "compile_error", message: req, data: { name: "BadTaskInput" } },
|
|
@@ -224,12 +215,17 @@ async function run(job: QueueTask): Promise<void> {
|
|
|
224
215
|
|
|
225
216
|
let result;
|
|
226
217
|
try {
|
|
227
|
-
result = await evaluate(req);
|
|
218
|
+
result = await evaluate(req, signal);
|
|
228
219
|
} catch (err) {
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
|
|
232
|
-
|
|
220
|
+
// Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
|
|
221
|
+
// but the release stops it waiting out a lease nobody serves.
|
|
222
|
+
if (err instanceof Cancelled) {
|
|
223
|
+
console.log(`cancelled: ${job.token}`);
|
|
224
|
+
await release(job.token);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
// The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
|
|
228
|
+
// and it reaches another worker without spending the definition's on_error budget.
|
|
233
229
|
console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
|
|
234
230
|
await release(job.token);
|
|
235
231
|
return;
|
|
@@ -263,11 +259,18 @@ async function renewLoop(): Promise<void> {
|
|
|
263
259
|
tokens,
|
|
264
260
|
lease_ms: LEASE_MS,
|
|
265
261
|
});
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
//
|
|
269
|
-
|
|
270
|
-
|
|
262
|
+
if (!ok) continue;
|
|
263
|
+
|
|
264
|
+
// Abort first rather than let a stopped script burn a core; the release rides run()'s
|
|
265
|
+
// catch, so nothing is released twice.
|
|
266
|
+
for (const token of (data?.cancelled ?? []) as string[]) {
|
|
267
|
+
inFlight.get(token)?.abort.abort();
|
|
268
|
+
}
|
|
269
|
+
// Lost: another worker holds it now and our answer will be refused; logged as the sign that
|
|
270
|
+
// LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
|
|
271
|
+
const lost = (data?.lost ?? []) as string[];
|
|
272
|
+
if (lost.length) {
|
|
273
|
+
console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
|
|
271
274
|
}
|
|
272
275
|
}
|
|
273
276
|
}
|
|
@@ -277,8 +280,9 @@ async function pollLoop(): Promise<void> {
|
|
|
277
280
|
const free = CONCURRENCY - inFlight.size;
|
|
278
281
|
const jobs = free > 0 ? await claim(free) : [];
|
|
279
282
|
for (const job of jobs) {
|
|
280
|
-
|
|
281
|
-
|
|
283
|
+
const abort = new AbortController();
|
|
284
|
+
inFlight.set(job.token, { job, abort });
|
|
285
|
+
void run(job, abort.signal).finally(() => inFlight.delete(job.token));
|
|
282
286
|
}
|
|
283
287
|
// Only idle when there was nothing to take: a full queue should be drained at the speed the
|
|
284
288
|
// realms allow, not at the poll interval.
|