@genroc/eval-node 0.0.0-edge.0477fb0 → 0.0.0-edge.04ed705c

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/dist/worker.js ADDED
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
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).
4
+ import { readFileSync } from "node:fs";
5
+ import { Cancelled, evaluate } from "./eval.js";
6
+ const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
7
+ const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
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.
11
+ const TOKEN = process.env.GENROC_TOKEN ??
12
+ (process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
13
+ const authHeaders = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
14
+ // The worker claims only what it can run, so a backlog is a queue rather than threads fighting
15
+ // over a core.
16
+ const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
17
+ const POLL_MS = Number(process.env.POLL_MS ?? 250);
18
+ // The visibility timeout. Short, and renewed while work is in flight: a worker that dies
19
+ // should return its task quickly rather than holding it for the whole budget.
20
+ const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
21
+ const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
22
+ const PROCESS_FILTER = process.env.PROCESS ?? "";
23
+ const TASK_FILTER = process.env.TASK ?? "";
24
+ // Large values arrive as refs; a bundle is one object per definition version, fetched once.
25
+ // Refs are content hashes, so the cache never invalidates.
26
+ const objectCache = new Map();
27
+ async function fetchObject(ref) {
28
+ const cached = objectCache.get(ref);
29
+ if (cached !== undefined)
30
+ return cached;
31
+ // Left to throw: a task whose input cannot be fetched must not run against a missing value.
32
+ // The caller releases the claim.
33
+ const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
34
+ if (!res.ok)
35
+ throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
36
+ const { data } = (await res.json());
37
+ let value;
38
+ try {
39
+ value = JSON.parse(data);
40
+ }
41
+ catch {
42
+ value = data;
43
+ }
44
+ objectCache.set(ref, value);
45
+ return value;
46
+ }
47
+ /** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
48
+ * needs no parser: the whole reason they are not JSON Pointer strings. */
49
+ async function resolveObjects(job) {
50
+ let input = job.external_input;
51
+ for (const e of job.objects ?? []) {
52
+ const value = await fetchObject(e.ref);
53
+ if (e.path.length === 0) {
54
+ input = value;
55
+ continue;
56
+ }
57
+ // The path is rooted at the entry and starts with "external_input", the value being rebuilt.
58
+ const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
59
+ if (rest.length === 0) {
60
+ input = value;
61
+ continue;
62
+ }
63
+ let cur = input;
64
+ for (let i = 0; i < rest.length - 1; i++)
65
+ cur = cur?.[rest[i]];
66
+ if (cur)
67
+ cur[rest[rest.length - 1]] = value;
68
+ }
69
+ return input;
70
+ }
71
+ async function call(path, body) {
72
+ // A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
73
+ // outlives restarts and deploys, and an unhandled rejection would kill it.
74
+ let res;
75
+ try {
76
+ res = await fetch(SERVER + path, {
77
+ method: "POST",
78
+ headers: { "content-type": "application/json", ...authHeaders },
79
+ body: JSON.stringify(body),
80
+ });
81
+ }
82
+ catch (err) {
83
+ return { ok: false, status: 0, data: { error: `${SERVER} unreachable: ${err.message}` } };
84
+ }
85
+ const text = await res.text();
86
+ let data = null;
87
+ try {
88
+ data = text ? JSON.parse(text) : null;
89
+ }
90
+ catch {
91
+ data = { error: text };
92
+ }
93
+ return { ok: res.ok, status: res.status, data };
94
+ }
95
+ /** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
96
+ * the nearest permanent kind, since no retry fixes the definition. */
97
+ function asEvalRequest(input) {
98
+ if (typeof input !== "object" || input === null)
99
+ return "the task input is not an object";
100
+ const r = input;
101
+ if (typeof r.code !== "string")
102
+ return "the task input has no `code` string";
103
+ return {
104
+ code: r.code,
105
+ input: r.input,
106
+ timeout_ms: typeof r.timeout_ms === "number" ? r.timeout_ms : undefined,
107
+ };
108
+ }
109
+ const inFlight = new Map();
110
+ let running = true;
111
+ // Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
112
+ // thousands of lines during a restart.
113
+ let serverReachable = true;
114
+ async function claim(n) {
115
+ const { ok, status, data } = await call("/api/external-tasks/claim", {
116
+ worker_id: WORKER_ID,
117
+ limit: n,
118
+ lease_ms: LEASE_MS,
119
+ ...(PROCESS_FILTER ? { process: PROCESS_FILTER } : {}),
120
+ ...(TASK_FILTER ? { task: TASK_FILTER } : {}),
121
+ });
122
+ if (!ok) {
123
+ // A credential problem is not transient, and polling through it looks like a healthy idle
124
+ // worker. Exit, so a supervisor restarts it visibly.
125
+ if (status === 401 || status === 403) {
126
+ console.error(`claim rejected (${status}): ${JSON.stringify(data)}\n` +
127
+ `The server requires authentication. Set GENROC_TOKEN to a token with the 'worker' ` +
128
+ `permission — mint one with: genctl token create --perms worker --label evaluator -q`);
129
+ process.exit(1);
130
+ }
131
+ // status 0 (see call): a restart or blip the next poll clears, so it is reported once.
132
+ if (status === 0) {
133
+ if (serverReachable) {
134
+ serverReachable = false;
135
+ console.error(`genroc at ${SERVER} is unreachable — ${data?.error ?? ""}. ` +
136
+ `Still polling every ${POLL_MS}ms; work resumes when it comes back.`);
137
+ }
138
+ return [];
139
+ }
140
+ console.error(`claim failed: ${JSON.stringify(data)}`);
141
+ return [];
142
+ }
143
+ if (!serverReachable) {
144
+ serverReachable = true;
145
+ console.error(`genroc at ${SERVER} is reachable again — resuming.`);
146
+ }
147
+ return (data?.items ?? []);
148
+ }
149
+ async function release(token) {
150
+ const { ok, data } = await call("/api/external-tasks/release", { token });
151
+ if (!ok)
152
+ console.error(`release failed: ${JSON.stringify(data)}`);
153
+ }
154
+ /** A refused outcome is not retried with another: the worker does not satisfy the declared
155
+ * contract. Released, so an operator sees the task waiting rather than gone. */
156
+ async function answer(token, outcome) {
157
+ const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
158
+ if (ok)
159
+ return;
160
+ console.error(`genroc refused the outcome for ${token}: ${JSON.stringify(data)}`);
161
+ await release(token);
162
+ }
163
+ async function run(job, signal) {
164
+ let resolved;
165
+ try {
166
+ resolved = await resolveObjects(job);
167
+ }
168
+ catch (err) {
169
+ // The values are there or they are not; this is the runner failing to read them, not the
170
+ // script failing, so hand the task back for someone else rather than reporting an outcome.
171
+ console.error(`resolving objects for ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
172
+ await release(job.token);
173
+ return;
174
+ }
175
+ const req = asEvalRequest(resolved);
176
+ if (typeof req === "string") {
177
+ await answer(job.token, {
178
+ error: { code: "compile_error", message: req, data: { name: "BadTaskInput" } },
179
+ });
180
+ return;
181
+ }
182
+ let result;
183
+ try {
184
+ result = await evaluate(req, signal);
185
+ }
186
+ catch (err) {
187
+ // Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
188
+ // but the release stops it waiting out a lease nobody serves.
189
+ if (err instanceof Cancelled) {
190
+ console.log(`cancelled: ${job.token}`);
191
+ await release(job.token);
192
+ return;
193
+ }
194
+ // The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
195
+ // and it reaches another worker without spending the definition's on_error budget.
196
+ console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
197
+ await release(job.token);
198
+ return;
199
+ }
200
+ if (result.ok) {
201
+ // `body` is JSON text produced inside the realm; an empty body is a script that returned
202
+ // nothing, which genroc reads as null.
203
+ await answer(job.token, { result: result.body === "" ? null : JSON.parse(result.body) });
204
+ return;
205
+ }
206
+ const f = result.failure;
207
+ await answer(job.token, {
208
+ error: {
209
+ // The failure KIND is the code, so an on_error rule branches on what went wrong without
210
+ // reading a payload. Every kind is permanent; see eval.ts.
211
+ code: f.kind,
212
+ message: f.message,
213
+ data: { name: f.name, ...(f.stack ? { stack: f.stack } : {}) },
214
+ },
215
+ });
216
+ }
217
+ async function renewLoop() {
218
+ while (running) {
219
+ await new Promise((r) => setTimeout(r, RENEW_MS));
220
+ const tokens = [...inFlight.keys()];
221
+ if (!tokens.length)
222
+ continue;
223
+ const { ok, data } = await call("/api/external-tasks/renew", {
224
+ worker_id: WORKER_ID,
225
+ tokens,
226
+ lease_ms: LEASE_MS,
227
+ });
228
+ if (!ok)
229
+ continue;
230
+ // Abort first rather than let a stopped script burn a core; the release rides run()'s
231
+ // catch, so nothing is released twice.
232
+ for (const token of (data?.cancelled ?? [])) {
233
+ inFlight.get(token)?.abort.abort();
234
+ }
235
+ // Lost: another worker holds it now and our answer will be refused; logged as the sign that
236
+ // LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
237
+ const lost = (data?.lost ?? []);
238
+ if (lost.length) {
239
+ console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
240
+ }
241
+ }
242
+ }
243
+ async function pollLoop() {
244
+ while (running) {
245
+ const free = CONCURRENCY - inFlight.size;
246
+ const jobs = free > 0 ? await claim(free) : [];
247
+ for (const job of jobs) {
248
+ const abort = new AbortController();
249
+ inFlight.set(job.token, { job, abort });
250
+ void run(job, abort.signal).finally(() => inFlight.delete(job.token));
251
+ }
252
+ // Only idle when there was nothing to take: a full queue should be drained at the speed the
253
+ // realms allow, not at the poll interval.
254
+ if (jobs.length === 0)
255
+ await new Promise((r) => setTimeout(r, POLL_MS));
256
+ }
257
+ }
258
+ async function shutdown(signal) {
259
+ if (!running)
260
+ return;
261
+ running = false;
262
+ const tokens = [...inFlight.keys()];
263
+ console.log(`${signal}: releasing ${tokens.length} claim(s)`);
264
+ // Hand work back rather than letting it sit out its lease. The evaluations still running are
265
+ // abandoned, which is exactly what the release says: nobody answered.
266
+ await Promise.all(tokens.map(release));
267
+ process.exit(0);
268
+ }
269
+ process.on("SIGINT", () => void shutdown("SIGINT"));
270
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
271
+ console.log(`evaluator worker ${WORKER_ID} polling ${SERVER} (concurrency=${CONCURRENCY}, lease=${LEASE_MS}ms)`);
272
+ void renewLoop();
273
+ void pollLoop();
package/eval.ts CHANGED
@@ -1,22 +1,18 @@
1
- // Evaluation core: run a code string in its OWN realm and classify every outcome into one of
2
- // the failure kinds in README.md. Nothing here knows about genroc — worker.ts is the only
3
- // thing that talks to the queue — so this stays testable and the containment stays swappable.
4
- //
5
- // The containment is a Worker per execution (realm.ts). It is what makes the budget real:
6
- // a synchronous busy loop never yields, so no in-process timer can interrupt it, and only a
7
- // 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.
8
4
 
9
5
  import { Worker } from "node:worker_threads";
10
6
 
11
7
  export type EvalRequest = {
8
+ /** An ES module whose default export is the function to run; `input` is its argument. */
12
9
  code: string;
13
10
  input?: unknown;
14
11
  timeout_ms?: number;
15
12
  };
16
13
 
17
- /** Every kind here is PERMANENT: a retry re-runs the same code on the same input and fails
18
- * identically. The retryable class has no kind because it is not an outcome — a runner that
19
- * 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. */
20
16
  export type FailureKind = "compile_error" | "threw" | "timeout" | "nonserializable" | "exited";
21
17
 
22
18
  export type EvalFailure = {
@@ -26,9 +22,8 @@ export type EvalFailure = {
26
22
  stack?: string;
27
23
  };
28
24
 
29
- /** `body` is JSON TEXT, not a value: serialising in the realm is what makes a nonserializable
30
- * return a script fault rather than a 500 thrown out of the response path. It is also what
31
- * 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. */
32
27
  export type EvalResult =
33
28
  | { ok: true; body: string }
34
29
  | { ok: false; failure: EvalFailure };
@@ -38,11 +33,15 @@ export type WorkerRequest = { code: string; input?: unknown };
38
33
  export type WorkerReply = EvalResult;
39
34
 
40
35
  const DEFAULT_TIMEOUT_MS = 5_000;
41
- const REALM_URL = new URL("./realm.ts", import.meta.url);
36
+ // Resolved from THIS file's own extension: run from a checkout it is `.ts`, and from the
37
+ // published package `.js`, because Node will not strip types under node_modules.
38
+ const REALM_URL = new URL(
39
+ import.meta.url.endsWith(".ts") ? "./realm.ts" : "./realm.js",
40
+ import.meta.url,
41
+ );
42
42
 
43
- /** Thrown, not returned: a realm that fails to start is the RUNNER faulting, which worker.ts
44
- * answers by releasing the claim rather than by reporting an outcome. A script fault is a
45
- * 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. */
46
45
  class RealmFault extends Error {
47
46
  constructor(message: string) {
48
47
  super(message);
@@ -50,24 +49,41 @@ class RealmFault extends Error {
50
49
  }
51
50
  }
52
51
 
53
- export async function evaluate(req: EvalRequest): Promise<EvalResult> {
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> {
54
62
  const budget = typeof req.timeout_ms === "number" ? req.timeout_ms : DEFAULT_TIMEOUT_MS;
55
63
 
56
64
  const worker = new Worker(REALM_URL);
57
65
  let timer: ReturnType<typeof setTimeout> | undefined;
66
+ let onAbort: (() => void) | undefined;
58
67
  try {
59
68
  return await new Promise<EvalResult>((resolve, reject) => {
60
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
+ }
61
77
  worker.once("message", (reply: WorkerReply) => resolve(reply));
62
- // A script may end its own realm (`process.exit()`), which is not a throw and would
63
- // otherwise present as a hang until the budget expired. Our own terminate() raises
64
- // 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.
65
80
  worker.once("exit", (code: number) => resolve(exited(code)));
66
81
  worker.once("error", (err: Error) => reject(new RealmFault(errorText(err))));
67
82
  worker.postMessage({ code: req.code, input: req.input } satisfies WorkerRequest);
68
83
  });
69
84
  } finally {
70
85
  clearTimeout(timer);
86
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
71
87
  // Awaited, and the whole point: on the timeout path a thread is still burning a core, and
72
88
  // resolving before it is gone would report an evaluation the machine is still running.
73
89
  await worker.terminate();