Skip to content

3D engine that AI agents drive

Fix kernel offload cancel, key collisions and request errors (#2438)

Nguyen Xuan An148fae0aaa86
diff --git a/changes/2438.md b/changes/2438.md
new file mode 100644
index 00000000..edd8c86a
--- /dev/null
+++ b/changes/2438.md
@@ -0,0 +1 @@
+- Kernel offload: a build cancelled during a page kernel stops at once, kernel keys tell 0 from -0 and sparse arrays from dense ones, and a malformed worker request names the field it lacks (#2438, #2439, #2440).
diff --git a/src/kernel-offload.js b/src/kernel-offload.js
index 53cda1e8..8640b6bf 100644
--- a/src/kernel-offload.js
+++ b/src/kernel-offload.js
@@ -92,7 +92,8 @@ function mixNamedValue(hasher, key, value) {
/** Feeds a value into the hasher; returns false for anything that is not plain, cloneable data. */
function mixValue(hasher, value) {
if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
- const text = String(value);
+ // String(-0) is "0": spell the sign out so 0 and -0 do not share a key.
+ const text = Object.is(value, -0) ? '-0' : String(value);
mixText(hasher, `${typeof value}:${text.length}:${text};`);
return true;
}
@@ -108,7 +109,13 @@ function mixValue(hasher, value) {
}
if (Array.isArray(value)) {
mixText(hasher, `[${value.length}:`);
- return value.every(item => mixValue(hasher, item));
+ // By index, because `every` skips the holes of a sparse array and [, 1] would match [1, ,].
+ for (let index = 0; index < value.length; index++) {
+ if (!mixValue(hasher, value[index])) {
+ return false;
+ }
+ }
+ return true;
}
if (typeof value === 'object' && isPlainObject(value)) {
const keys = Object.keys(value);
@@ -198,6 +205,11 @@ function validateKernelTimeout(milliseconds) {
/** One job on one worker: resolves with the worker's answer, or rejects when the worker fails or stays silent too long. */
function requestKernel(worker, job, signal, timeoutMilliseconds) {
return new Promise((resolve, reject) => {
+ // A signal that fired while a page kernel ran never calls a listener added now.
+ if (signal?.aborted) {
+ reject(abortError(signal));
+ return;
+ }
const timer = setTimeout(() => {
cleanUp();
const error = new Error(`Kernel worker gave no answer for ${job.name} within ${timeoutMilliseconds} ms.`);
diff --git a/src/kernel-registry.js b/src/kernel-registry.js
index 642671a7..fce189ed 100644
--- a/src/kernel-registry.js
+++ b/src/kernel-registry.js
@@ -31,8 +31,11 @@ function collectBuffers(value, buffers) {
* Answers one worker request: `{ response, transfer }`. A kernel that throws answers with the error's class name and
* message, so the page raises the same error the inline path would.
*/
-export function answerKernelRequest({ name, args }) {
+export function answerKernelRequest(request) {
try {
+ if (request === null || typeof request !== 'object') throw new TypeError('a kernel request must be an object { name, args }');
+ const { name, args } = request;
+ if (!Array.isArray(args)) throw new TypeError(`kernel request field "args" must be an array of arguments, got ${typeof args}. Pass { name, args: [...] }.`);
if (!KERNELS[name]) throw new RangeError(`unknown kernel "${String(name)}": use one of ${Object.keys(KERNELS).join(', ')}`);
const value = KERNELS[name](...args);
const buffers = new Set();
diff --git a/tests/hunt-kernel-offload.test.js b/tests/hunt-kernel-offload.test.js
new file mode 100644
index 00000000..a7eee897
--- /dev/null
+++ b/tests/hunt-kernel-offload.test.js
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { buildWithKernels, kernelKey, runKernel } from '../src/kernel-offload.js';
+import { answerKernelRequest } from '../src/kernel-registry.js';
+
+test('a build cancelled while a page kernel runs stops at once instead of waiting for the worker timeout', async () => {
+ const controller = new AbortController();
+ const silentWorker = { postMessage() {}, terminate() {} };
+ const pageKernels = {
+ pattern: {
+ accepts: () => true,
+ compute: async () => {
+ controller.abort();
+ throw new Error('the GPU failed');
+ },
+ },
+ };
+ const started = Date.now();
+ await assert.rejects(
+ buildWithKernels(() => runKernel('pattern', [{ size: 1 }], () => 'inline'), {
+ createWorker: () => silentWorker,
+ available: true,
+ signal: controller.signal,
+ pageKernels,
+ kernelTimeoutMilliseconds: 2000,
+ }),
+ error => error.name === 'AbortError',
+ );
+ assert.ok(Date.now() - started < 1000, `the build took ${Date.now() - started} ms to notice the cancel`);
+});
+
+test('kernel keys tell 0 from -0 and arrays with holes from arrays without', () => {
+ assert.notEqual(kernelKey('k', [0]), kernelKey('k', [-0]));
+ assert.notEqual(kernelKey('k', [[, 1]]), kernelKey('k', [[1, ,]]));
+ assert.equal(kernelKey('k', [[0, 1]]), kernelKey('k', [[0, 1]]));
+});
+
+test('a malformed kernel request answers with an error that names the field', () => {
+ const missingArguments = answerKernelRequest({ name: 'cloth' }).response.error;
+ assert.equal(missingArguments.name, 'TypeError');
+ assert.match(missingArguments.message, /"args" must be an array/);
+ assert.match(answerKernelRequest({ name: 'cloth', args: 5 }).response.error.message, /"args" must be an array/);
+ assert.match(answerKernelRequest(null).response.error.message, /must be an object/);
+});