@genroc/eval-node 0.0.0-edge.4348678 → 0.0.0-edge.4394f2ae

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/realm.ts CHANGED
@@ -1,89 +1,44 @@
1
- // The evaluation realm. One Worker per execution: a fresh global object per script, and a
2
- // thread the host can kill mid-loop — the only thing that bounds a synchronous busy loop.
3
- // eval.ts owns the budget and does the killing; nothing here knows about time.
4
- //
5
- // Everything that touches the script's VALUE lives on this side of the boundary — compiling,
6
- // classifying, serialising — because this is the only realm the value exists in.
1
+ // The evaluation realm: one Worker per execution, killable mid-loop by eval.ts, which owns the
2
+ // budget. Everything touching the script's VALUE lives here, the only realm it exists in.
7
3
 
8
- import { createRequire } from "node:module";
4
+ import { registerHooks } from "node:module";
9
5
  import { parentPort } from "node:worker_threads";
10
6
 
11
7
  import type { EvalFailure, FailureKind, WorkerReply, WorkerRequest } from "./eval.ts";
12
8
 
13
- const AsyncFunction = async function () {}.constructor as new (
14
- ...args: string[]
15
- ) => (...args: unknown[]) => Promise<unknown>;
16
-
17
- const STRICT = '"use strict";\n';
18
-
19
- // Bundled `node:*` imports survive as `require` calls — the importer externalises builtins and
20
- // inlines everything else — and a function built by the AsyncFunction constructor has no
21
- // `require` in scope. Passing one in is what makes an import of a builtin work at runtime rather than at
22
- // typecheck only. Resolution is anchored here, which is right: only builtins reach it.
23
- const scriptRequire = createRequire(import.meta.url);
9
+ // IMPORTED under our own URL rather than compiled from a string, so frames carry the author's
10
+ // line numbers and builtin imports resolve normally.
11
+ const SCRIPT_URL = "script:main";
24
12
  const STACK_BYTES = 2_048;
25
13
 
26
- /**
27
- * Line offset the AsyncFunction preamble adds, measured rather than assumed: the generated
28
- * wrapper's shape is engine-specific, and a hardcoded number silently misreports every
29
- * script's error location the day it changes.
30
- */
31
- const lineOffset: Promise<number> = (async () => {
32
- // Same parameter list as a real compile: the preamble is what is being measured.
33
- const probe = new AsyncFunction("input", "require", STRICT + "throw new Error('probe');");
34
- try {
35
- await probe();
36
- return 0;
37
- } catch (err) {
38
- return reportedLine(err) - 1;
39
- }
40
- })();
41
-
42
- // V8 marks a frame compiled by the AsyncFunction constructor with the site that CALLED the
43
- // constructor, then the script's OWN position:
44
- // at inner (eval at run (file:///…/worker.ts:107:10), <anonymous>:6:9)
45
- // `eval at` is therefore what separates script frames from runner plumbing — matched without
46
- // the function name, which is whatever encloses the `new AsyncFunction` below. The LAST such
47
- // frame is the body's top level: frames interleave, since a script can throw inside a native
48
- // callback.
49
- const SCRIPT_FRAME = /\(eval at /;
50
- // The trailing `<anonymous>:LINE:COL` — the script's position, after the host file's own.
51
- const POSITION = /<anonymous>:(\d+):(\d+)\)?\s*$/;
52
- // ` at name (` — absent on the top-level frame, which V8 names `eval`.
53
- const FRAME_NAME = /^\s*at\s+(?:async\s+)?([^\s(]+)\s*\(/;
14
+ // The only channel a load hook has to the source. Written per request and read once — a realm
15
+ // evaluates one script and is then discarded, so no second execution can observe it.
16
+ let source = "";
54
17
 
55
- /** Line number of the throw as the engine reported it, or 1 if the stack is unreadable. */
56
- function reportedLine(err: unknown): number {
57
- const stack = err instanceof Error && typeof err.stack === "string" ? err.stack : "";
58
- const frame = stack.split("\n").find((l) => SCRIPT_FRAME.test(l)) ?? "";
59
- const m = frame.match(POSITION);
60
- return m ? Number(m[1]) : 1;
61
- }
18
+ registerHooks({
19
+ resolve: (specifier, context, next) =>
20
+ specifier === SCRIPT_URL ? { url: SCRIPT_URL, shortCircuit: true } : next(specifier, context),
21
+ load: (url, context, next) =>
22
+ url === SCRIPT_URL ? { format: "module", source, shortCircuit: true } : next(url, context),
23
+ });
62
24
 
63
- /** Renumbers each script frame to the line the AUTHOR wrote and drops the runner's own.
64
- * Rewriting the whole location is also what keeps the runner's path out of a script's
65
- * stack — V8 puts it inside every compiled frame. */
66
- function scriptStack(err: unknown, offset: number): string | undefined {
25
+ /** Keeps the frames that are the script's own. Everything below the last of them is runner
26
+ * plumbing the author cannot act on, and V8 puts this file's path in it. */
27
+ function scriptStack(err: unknown): string | undefined {
67
28
  if (!(err instanceof Error) || typeof err.stack !== "string") return undefined;
68
29
  const lines = err.stack.split("\n");
69
- let boundary = -1;
70
- for (let i = 0; i < lines.length; i++) if (SCRIPT_FRAME.test(lines[i]!)) boundary = i;
71
- const frames = (boundary >= 0 ? lines.slice(0, boundary + 1) : lines.slice(0, 1))
72
- .map((line) => {
73
- const pos = line.match(POSITION);
74
- if (!pos) return line; // the `Error: message` header and native frames, kept as-is
75
- const name = line.match(FRAME_NAME)?.[1];
76
- const at = name && name !== "eval" && name !== "anonymous" ? `at ${name} ` : "at ";
77
- const indent = line.match(/^\s*/)![0];
78
- return `${indent}${at}(script:${Math.max(1, Number(pos[1]) - offset)}:${pos[2]})`;
79
- })
80
- .join("\n");
81
- return frames.length > STACK_BYTES ? frames.slice(0, STACK_BYTES) : frames;
30
+ let last = 0;
31
+ for (let i = 0; i < lines.length; i++) if (lines[i]!.includes(SCRIPT_URL)) last = i;
32
+ const stack = lines.slice(0, last + 1).join("\n");
33
+ return stack.length > STACK_BYTES ? stack.slice(0, STACK_BYTES) : stack;
82
34
  }
83
35
 
84
- function describe(err: unknown, kind: FailureKind, offset: number): EvalFailure {
36
+ function describe(err: unknown, kind: FailureKind): EvalFailure {
85
37
  if (err instanceof Error) {
86
- return { kind, name: err.name, message: err.message, stack: scriptStack(err, offset) };
38
+ // A subclass inherits `name` from Error.prototype, so `class LimitExceeded extends Error {}`
39
+ // would report "Error"; a name the script set still wins.
40
+ const name = err.name === "Error" && err.constructor.name ? err.constructor.name : err.name;
41
+ return { kind, name, message: err.message, stack: scriptStack(err) };
87
42
  }
88
43
  // A script may throw a non-Error (`throw {code: "x"}`), so name/message must not assume one.
89
44
  return { kind, name: "Thrown", message: safeText(err) };
@@ -97,23 +52,39 @@ function safeText(v: unknown): string {
97
52
  }
98
53
  }
99
54
 
55
+ /** Unparseable code or an unresolvable import is broken code; anything else the import throws is
56
+ * the module's top level running, i.e. the script throwing. */
57
+ function unloadable(err: unknown): boolean {
58
+ const code = (err as { code?: unknown } | null)?.code;
59
+ return err instanceof SyntaxError || (typeof code === "string" && code.startsWith("ERR_MODULE"));
60
+ }
61
+
100
62
  async function run(req: WorkerRequest): Promise<WorkerReply> {
101
- const offset = await lineOffset;
63
+ source = req.code;
102
64
 
103
- let fn: (...args: unknown[]) => Promise<unknown>;
65
+ let main: unknown;
104
66
  try {
105
- // No compile cache: the realm is discarded after this execution, so a cache in it could
106
- // never be hit. Repeated compilation is the price of the fresh global object.
107
- fn = new AsyncFunction("input", "require", STRICT + req.code);
67
+ main = (await import(SCRIPT_URL)).default;
108
68
  } catch (err) {
109
- return { ok: false, failure: describe(err, "compile_error", offset) };
69
+ return { ok: false, failure: describe(err, unloadable(err) ? "compile_error" : "threw") };
70
+ }
71
+ if (typeof main !== "function") {
72
+ const got = main === undefined ? "no default export" : `a ${typeof main}`;
73
+ return {
74
+ ok: false,
75
+ failure: {
76
+ kind: "compile_error",
77
+ name: "NoDefaultExport",
78
+ message: `a script must export default a function; this one has ${got}`,
79
+ },
80
+ };
110
81
  }
111
82
 
112
83
  let value: unknown;
113
84
  try {
114
- value = await fn(req.input, scriptRequire);
85
+ value = await (main as (input: unknown) => unknown)(req.input);
115
86
  } catch (err) {
116
- return { ok: false, failure: describe(err, "threw", offset) };
87
+ return { ok: false, failure: describe(err, "threw") };
117
88
  }
118
89
 
119
90
  try {
@@ -121,12 +92,20 @@ async function run(req: WorkerRequest): Promise<WorkerReply> {
121
92
  // spells null, which is the right reading of a script that returned nothing.
122
93
  return { ok: true, body: value === undefined ? "" : JSON.stringify(value) ?? "" };
123
94
  } catch (err) {
124
- return { ok: false, failure: describe(err, "nonserializable", offset) };
95
+ return { ok: false, failure: describe(err, "nonserializable") };
125
96
  }
126
97
  }
127
98
 
99
+ // eval.ts terminates this thread the moment the reply lands, while stdio may still be in the
100
+ // pipe. An empty write's callback fires once the queue drains, making the reply a barrier.
101
+ function flush(stream: NodeJS.WriteStream): Promise<void> {
102
+ return new Promise((resolve) => stream.write("", () => resolve()));
103
+ }
104
+
128
105
  // Non-null because this module only ever runs as a worker entry point; a null port here
129
106
  // would mean eval.ts loaded it as a plain module, which nothing does.
130
107
  parentPort!.on("message", async (req: WorkerRequest) => {
131
- parentPort!.postMessage(await run(req));
108
+ const reply = await run(req);
109
+ await Promise.all([flush(process.stdout), flush(process.stderr)]);
110
+ parentPort!.postMessage(reply);
132
111
  });
package/worker.ts CHANGED
@@ -1,59 +1,59 @@
1
1
  #!/usr/bin/env node
2
- // The queue worker: claims parked `external` script tasks from genroc, evaluates each in its
3
- // own realm, and answers. This is the whole genroc-facing half — eval.ts and realm.ts know
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
- import { evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
5
+ import { readFileSync } from "node:fs";
6
+ import { Cancelled, evaluate, type EvalRequest, type FailureKind } from "./eval.ts";
9
7
 
10
8
  const SERVER = (process.env.GENROC_SERVER ?? "http://localhost:8448").replace(/\/$/, "");
11
9
  const WORKER_ID = process.env.WORKER_ID ?? `evaluator-${process.pid}`;
12
- // The credential, when the server runs with --auth token. A worker needs exactly the `worker`
13
- // permission — the four queue verbs plus GET /api/objects — so mint it scoped rather than
14
- // handing a worker an admin token: this is the credential most likely to sit on a machine you
15
- // trust least. specs/api-auth.md §5.
16
- //
17
- // Sent as a header rather than in the URL because Node's fetch REFUSES a URL carrying
18
- // credentials ("Request cannot be constructed from a URL that includes credentials"), so the
19
- // basic-auth-in-the-URL trick that works for genctl is not available here.
20
- const TOKEN = process.env.GENROC_TOKEN ?? "";
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.
13
+ const TOKEN =
14
+ process.env.GENROC_TOKEN ??
15
+ (process.env.GENROC_TOKEN_FILE ? readFileSync(process.env.GENROC_TOKEN_FILE, "utf8").trim() : "");
21
16
  const authHeaders: Record<string, string> = TOKEN ? { authorization: `Bearer ${TOKEN}` } : {};
22
- // Concurrency is the worker's to set, and that is the point of pulling: under the old fetch
23
- // shape genroc decided how many scripts ran at once (--max-concurrent, default 200) and the
24
- // evaluator accepted every one of them. Here it claims what it can run and no more, so a
25
- // 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.
26
19
  const CONCURRENCY = Number(process.env.CONCURRENCY ?? 4);
27
20
  const POLL_MS = Number(process.env.POLL_MS ?? 250);
28
21
  // The visibility timeout. Short, and renewed while work is in flight: a worker that dies
29
22
  // should return its task quickly rather than holding it for the whole budget.
30
23
  const LEASE_MS = Number(process.env.LEASE_MS ?? 30_000);
31
24
  const RENEW_MS = Math.max(1_000, Math.floor(LEASE_MS / 3));
32
- const PROCESS_FILTER = process.env.PROCESS ?? "";
33
- const TASK_FILTER = process.env.TASK ?? "";
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;
28
+ // script-node's names; a renamed copy sets PROCESS. The claim requires both: this worker answers
29
+ // one task's contract, so it must never be handed another's.
30
+ const PROCESS_FILTER = process.env.PROCESS ?? "script-node";
31
+ const TASK_FILTER = process.env.TASK ?? "eval_node";
32
+ if (!PROCESS_FILTER || !TASK_FILTER) {
33
+ console.error("PROCESS and TASK must both name the queue this worker serves; neither may be empty.");
34
+ process.exit(1);
35
+ }
34
36
 
35
37
  type ObjectEntry = { path: (string | number)[]; ref: string; size: number };
36
38
 
37
39
  type QueueTask = {
38
40
  token: string;
39
41
  process: string;
40
- task_id: string;
41
- input: unknown;
42
+ task: string;
43
+ external_input: unknown;
42
44
  objects?: ObjectEntry[];
43
- raises?: Record<string, unknown>;
45
+ deadline?: string;
44
46
  };
45
47
 
46
- // Values too large to ship inline are listed rather than carried, and a bundle is exactly that:
47
- // one object shared by every instance of a definition version, fetched once instead of copied
48
- // into each task. A ref is a content hash, so it is immutable — the cache never invalidates.
48
+ // Large values arrive as refs; a bundle is one object per definition version, fetched once.
49
+ // Refs are content hashes, so the cache never invalidates.
49
50
  const objectCache = new Map<string, unknown>();
50
51
 
51
52
  async function fetchObject(ref: string): Promise<unknown> {
52
53
  const cached = objectCache.get(ref);
53
54
  if (cached !== undefined) return cached;
54
- // Left to throw on purpose: this runs while a task is IN FLIGHT, and a task whose input
55
- // cannot be fetched must fail rather than silently run against a missing value. The caller
56
- // releases the claim, so the task returns to the queue.
55
+ // Left to throw: a task whose input cannot be fetched must not run against a missing value.
56
+ // The caller releases the claim.
57
57
  const res = await fetch(`${SERVER}/api/objects/${encodeURIComponent(ref)}`, { headers: authHeaders });
58
58
  if (!res.ok) throw new Error(`fetch object ${ref}: HTTP ${res.status}`);
59
59
  const { data } = (await res.json()) as { data: string };
@@ -70,15 +70,15 @@ async function fetchObject(ref: string): Promise<unknown> {
70
70
  /** Put each listed value back where its path says it belongs. Paths are arrays of keys, so this
71
71
  * needs no parser: the whole reason they are not JSON Pointer strings. */
72
72
  async function resolveObjects(job: QueueTask): Promise<unknown> {
73
- let input: any = job.input;
73
+ let input: any = job.external_input;
74
74
  for (const e of job.objects ?? []) {
75
75
  const value = await fetchObject(e.ref);
76
76
  if (e.path.length === 0) {
77
77
  input = value;
78
78
  continue;
79
79
  }
80
- // The path is rooted at the entry and starts with "input", which is the value being rebuilt.
81
- const rest = e.path[0] === "input" ? e.path.slice(1) : e.path;
80
+ // The path is rooted at the entry and starts with "external_input", the value being rebuilt.
81
+ const rest = e.path[0] === "external_input" ? e.path.slice(1) : e.path;
82
82
  if (rest.length === 0) {
83
83
  input = value;
84
84
  continue;
@@ -91,10 +91,8 @@ async function resolveObjects(job: QueueTask): Promise<unknown> {
91
91
  }
92
92
 
93
93
  async function call(path: string, body: unknown): Promise<{ ok: boolean; status: number; data: any }> {
94
- // A network error is a REPLY, not a throw. A worker outlives the server it polls — a
95
- // restart, a rolling deploy, a container coming up before genroc is listening — and an
96
- // unhandled rejection here kills it for a condition the next poll would clear. Status 0
97
- // says "never reached the server", which is distinct from anything genroc answers.
94
+ // A network error is a REPLY (status 0, "never reached the server"), not a throw: a worker
95
+ // outlives restarts and deploys, and an unhandled rejection would kill it.
98
96
  let res: Response;
99
97
  try {
100
98
  res = await fetch(SERVER + path, {
@@ -115,27 +113,24 @@ async function call(path: string, body: unknown): Promise<{ ok: boolean; status:
115
113
  return { ok: res.ok, status: res.status, data };
116
114
  }
117
115
 
118
- /** The task input IS an EvalRequest: `code` required, `input` and `timeout_ms` optional. A task
119
- * whose input is not that shape is the definition's fault, not the script's, and is reported
120
- * as a compile_error — the nearest permanent kind, since no retry can fix the definition. */
121
- function asEvalRequest(input: unknown): EvalRequest | string {
116
+ /** A task input that is not an EvalRequest is the definition's fault, reported as compile_error:
117
+ * the nearest permanent kind, since no retry fixes the definition. */
118
+ function asEvalRequest(input: unknown, timeoutMs: number | undefined): EvalRequest | string {
122
119
  if (typeof input !== "object" || input === null) return "the task input is not an object";
123
120
  const r = input as Record<string, unknown>;
124
121
  if (typeof r.code !== "string") return "the task input has no `code` string";
125
- return {
126
- code: r.code,
127
- input: r.input,
128
- timeout_ms: typeof r.timeout_ms === "number" ? r.timeout_ms : undefined,
129
- };
122
+ return { code: r.code, input: r.input, timeout_ms: timeoutMs };
130
123
  }
131
124
 
132
- const inFlight = new Map<string, QueueTask>();
125
+ /** genroc cannot call us, so a cancellation arrives on our own heartbeat and reaches the
126
+ * evaluation through the controller. */
127
+ type Running = { job: QueueTask; abort: AbortController };
128
+
129
+ const inFlight = new Map<string, Running>();
133
130
  let running = true;
134
131
 
135
- // Whether the last claim reached genroc. A worker polls several times a second, so an
136
- // unreachable server would otherwise emit a line per poll — thousands during a restart, which
137
- // buries the one line that mattered. Announce the TRANSITIONS instead: going away, and coming
138
- // back. Silence in between is the report that nothing changed.
132
+ // Announce reachability TRANSITIONS only: polling several times a second would otherwise emit
133
+ // thousands of lines during a restart.
139
134
  let serverReachable = true;
140
135
 
141
136
  async function claim(n: number): Promise<QueueTask[]> {
@@ -143,13 +138,12 @@ async function claim(n: number): Promise<QueueTask[]> {
143
138
  worker_id: WORKER_ID,
144
139
  limit: n,
145
140
  lease_ms: LEASE_MS,
146
- ...(PROCESS_FILTER ? { process: PROCESS_FILTER } : {}),
147
- ...(TASK_FILTER ? { task: TASK_FILTER } : {}),
141
+ process: PROCESS_FILTER,
142
+ task: TASK_FILTER,
148
143
  });
149
144
  if (!ok) {
150
- // A credential problem is not transient, and polling through it looks like a healthy
151
- // worker that never picks anything up — the worst shape for an operator to debug. Exit
152
- // instead, so a supervisor restarts it and the failure is visible where it happened.
145
+ // A credential problem is not transient, and polling through it looks like a healthy idle
146
+ // worker. Exit, so a supervisor restarts it visibly.
153
147
  if (status === 401 || status === 403) {
154
148
  console.error(
155
149
  `claim rejected (${status}): ${JSON.stringify(data)}\n` +
@@ -158,9 +152,7 @@ async function claim(n: number): Promise<QueueTask[]> {
158
152
  );
159
153
  process.exit(1);
160
154
  }
161
- // status 0 is "never reached the server" (see call): a restart, a rolling deploy, a
162
- // network blip. Not an error to act on — the next poll clears it — so it is reported once
163
- // and then waited out.
155
+ // status 0 (see call): a restart or blip the next poll clears, so it is reported once.
164
156
  if (status === 0) {
165
157
  if (serverReachable) {
166
158
  serverReachable = false;
@@ -186,10 +178,8 @@ async function release(token: string): Promise<void> {
186
178
  if (!ok) console.error(`release failed: ${JSON.stringify(data)}`);
187
179
  }
188
180
 
189
- /** answer submits the outcome. A refusal is NOT retried with a different one: the definition
190
- * declared a contract this worker does not satisfy (an undeclared code, a payload that does
191
- * not fit `raises`), and guessing again would only pick a second wrong answer. Release it, so
192
- * the task returns to the queue and an operator sees it waiting rather than silently gone. */
181
+ /** A refused outcome is not retried with another: the worker does not satisfy the declared
182
+ * contract. Released, so an operator sees the task waiting rather than gone. */
193
183
  async function answer(token: string, outcome: Record<string, unknown>): Promise<void> {
194
184
  const { ok, data } = await call("/api/external-tasks/resolve", { token, ...outcome });
195
185
  if (ok) return;
@@ -197,7 +187,10 @@ async function answer(token: string, outcome: Record<string, unknown>): Promise<
197
187
  await release(token);
198
188
  }
199
189
 
200
- async function run(job: QueueTask): Promise<void> {
190
+ async function run(job: QueueTask, signal: AbortSignal): Promise<void> {
191
+ // The task's own timeout is the script's budget, moved onto the monotonic clock so a wall-clock
192
+ // step mid-run cannot stretch it. Fetching the objects below spends the same deadline.
193
+ const due = job.deadline === undefined ? undefined : performance.now() + (Date.parse(job.deadline) - Date.now());
201
194
  let resolved: unknown;
202
195
  try {
203
196
  resolved = await resolveObjects(job);
@@ -208,7 +201,16 @@ async function run(job: QueueTask): Promise<void> {
208
201
  await release(job.token);
209
202
  return;
210
203
  }
211
- const req = asEvalRequest(resolved);
204
+ let timeoutMs: number | undefined;
205
+ if (due !== undefined) {
206
+ timeoutMs = Math.floor(due - performance.now() - ANSWER_MARGIN_MS);
207
+ if (timeoutMs <= 0) {
208
+ // Too late to run anything: the deadline fires as external.timeout, which is the truth.
209
+ await release(job.token);
210
+ return;
211
+ }
212
+ }
213
+ const req = asEvalRequest(resolved, timeoutMs);
212
214
  if (typeof req === "string") {
213
215
  await answer(job.token, {
214
216
  error: { code: "compile_error", message: req, data: { name: "BadTaskInput" } },
@@ -218,12 +220,17 @@ async function run(job: QueueTask): Promise<void> {
218
220
 
219
221
  let result;
220
222
  try {
221
- result = await evaluate(req);
223
+ result = await evaluate(req, signal);
222
224
  } catch (err) {
223
- // The RUNNER faulted, not the script — the one class where a retry can help. There is no
224
- // error code for it on purpose: releasing the claim is how a queue spells "retryable", and
225
- // it puts the task in front of a different worker instead of burning the definition's
226
- // on_error budget on this one's bad day.
225
+ // Cancelled is not a fault. Still released: the row is terminal so nothing re-claims it,
226
+ // but the release stops it waiting out a lease nobody serves.
227
+ if (err instanceof Cancelled) {
228
+ console.log(`cancelled: ${job.token}`);
229
+ await release(job.token);
230
+ return;
231
+ }
232
+ // The RUNNER faulted, the one retryable class. Releasing is how a queue spells "retryable",
233
+ // and it reaches another worker without spending the definition's on_error budget.
227
234
  console.error(`evaluator fault on ${job.token}: ${err instanceof Error ? err.message : String(err)}`);
228
235
  await release(job.token);
229
236
  return;
@@ -257,11 +264,18 @@ async function renewLoop(): Promise<void> {
257
264
  tokens,
258
265
  lease_ms: LEASE_MS,
259
266
  });
260
- // A short count means a claim lapsed and was taken over. Nothing to do about it — the work
261
- // continues and its answer will be refused — but say so, because it is the signal that
262
- // LEASE_MS is too short for what these scripts actually take.
263
- if (ok && data?.renewed < tokens.length) {
264
- console.error(`renewed ${data.renewed}/${tokens.length} claims; a lease lapsed under load`);
267
+ if (!ok) continue;
268
+
269
+ // Abort first rather than let a stopped script burn a core; the release rides run()'s
270
+ // catch, so nothing is released twice.
271
+ for (const token of (data?.cancelled ?? []) as string[]) {
272
+ inFlight.get(token)?.abort.abort();
273
+ }
274
+ // Lost: another worker holds it now and our answer will be refused; logged as the sign that
275
+ // LEASE_MS is too short. NOT released: that would bump the epoch out from under the holder.
276
+ const lost = (data?.lost ?? []) as string[];
277
+ if (lost.length) {
278
+ console.error(`lost ${lost.length}/${tokens.length} claims; a lease lapsed under load`);
265
279
  }
266
280
  }
267
281
  }
@@ -271,8 +285,9 @@ async function pollLoop(): Promise<void> {
271
285
  const free = CONCURRENCY - inFlight.size;
272
286
  const jobs = free > 0 ? await claim(free) : [];
273
287
  for (const job of jobs) {
274
- inFlight.set(job.token, job);
275
- void run(job).finally(() => inFlight.delete(job.token));
288
+ const abort = new AbortController();
289
+ inFlight.set(job.token, { job, abort });
290
+ void run(job, abort.signal).finally(() => inFlight.delete(job.token));
276
291
  }
277
292
  // Only idle when there was nothing to take: a full queue should be drained at the speed the
278
293
  // realms allow, not at the poll interval.