From 0483fe1f8d3a55cdd6987b23f68d370ebf25b8cf Mon Sep 17 00:00:00 2001 From: Cristian Sotomayor Date: Sat, 24 Oct 2026 22:58:10 -0500 Subject: [PATCH 1/2] test(generate): cover open handles and nested verdict-shaped JSON in the module loader Refs NIW2-332 Co-Authored-By: Claude Sonnet 5.5 --- packages/generate/src/load-module.test.ts | 67 ++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/packages/generate/src/load-module.test.ts b/packages/generate/src/load-module.test.ts index 5246fd5..a7421e2 100644 --- a/packages/generate/src/load-module.test.ts +++ b/packages/generate/src/load-module.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' @@ -124,6 +124,71 @@ describe('surviving the module', () => { expect(Date.now() - started).toBeLessThan(20_000) }, 40_000) + it('answers at once when a valid module leaves a timer running', async () => { + const pidFile = join(scratch, 'timer.pid') + const path = moduleWith( + 'timer.mjs', + `import { writeFileSync } from 'node:fs'\n` + + `writeFileSync(${JSON.stringify(pidFile)}, String(process.pid))\n` + + `setInterval(() => {}, 1000)\n` + + `export const S = { '~standard': { version: 1, vendor: 'x', jsonSchema: { output: () => ({ type: 'string' }) } } }\n`, + ) + + const started = Date.now() + const result = await loadModuleSchema({ + resolvedPath: path, + exportName: 'S', + side: 'output', + }) + + expect(result).toMatchObject({ ok: true }) + if (!result.ok) return + expect(result.document['type']).toBe('string') + // The verdict was ready as soon as the module imported. Anything near the + // 10s budget means the loader waited for the child to exit on its own. + expect(Date.now() - started).toBeLessThan(2_000) + + // The timer would keep the child alive for ever, so it must have been + // killed, not left behind. + const pid = Number(readFileSync(pidFile, 'utf8')) + expect(() => process.kill(pid, 0)).toThrow(/ESRCH/) + }, 30_000) + + it('is not fooled by a schema whose examples contain {"ok":', async () => { + const path = moduleWith( + 'nested-ok.mjs', + `export const S = { '~standard': { version: 1, vendor: 'x', jsonSchema: { output: () => ({ type: 'object', examples: [{ ok: false, code: 'crashed', error: 'not the verdict' }] }) } } }\n`, + ) + + const result = await loadModuleSchema({ + resolvedPath: path, + exportName: 'S', + side: 'output', + }) + + expect(result).toMatchObject({ ok: true }) + if (!result.ok) return + expect(result.document['examples']).toEqual([ + { ok: false, code: 'crashed', error: 'not the verdict' }, + ]) + }, 30_000) + + it('is not fooled by a module that prints something shaped like a verdict', async () => { + const path = moduleWith( + 'fake-verdict.mjs', + `console.log(JSON.stringify({ ok: false, code: 'crashed', error: 'printed by the module' }))\n` + + `export const S = { '~standard': { version: 1, vendor: 'x', jsonSchema: { output: () => ({ type: 'string' }) } } }\n`, + ) + + const result = await loadModuleSchema({ + resolvedPath: path, + exportName: 'S', + side: 'output', + }) + + expect(result).toMatchObject({ ok: true }) + }, 30_000) + it('reads the verdict even when the module printed on its way in', async () => { const path = moduleWith( 'chatty.mjs', From bbac5c09544d8824f0a63cdf39ff8ee99f37d3ec Mon Sep 17 00:00:00 2001 From: Cristian Sotomayor Date: Sat, 24 Oct 2026 23:01:21 -0500 Subject: [PATCH 2/2] fix(generate): answer as soon as the module loader has a verdict The loader waited for the child to exit before reading its verdict, so a module that left a timer, pool or watcher running was reported as a 10 s timeout even though the child had already answered correctly. The verdict is now one framed line carrying a per-load token. The parent reads it incrementally, resolves, and kills the child; the child also exits in its write callback. The parent resolves only after the child has exited, so no orphan outlives the promise. The framing replaces lastIndexOf on '{"ok":', which a nested value inside a schema could fool. Refs NIW2-332 Co-Authored-By: Claude Sonnet 5.5 --- packages/generate/src/load-module.ts | 76 ++++++++++++++++++++-------- 1 file changed, 55 insertions(+), 21 deletions(-) diff --git a/packages/generate/src/load-module.ts b/packages/generate/src/load-module.ts index 7d34a2f..deac5a2 100644 --- a/packages/generate/src/load-module.ts +++ b/packages/generate/src/load-module.ts @@ -1,4 +1,5 @@ import { spawn } from 'node:child_process' +import { randomUUID } from 'node:crypto' import { DIALECT_2020_12 } from '@laqi/schema' /** How long a module gets to import itself and convert. Then the child dies. */ @@ -39,8 +40,12 @@ const CHILD = ` const { pathToFileURL } = require('node:url') const request = JSON.parse(process.env.LAQI_MODULE_REQUEST) +// The verdict is one line: a newline, the frame this load was given, then +// JSON (which never holds a raw newline). Exiting in the write callback is +// what keeps a module with a live timer, pool or watcher from holding the +// child open after the answer is already out. function say(result) { - process.stdout.write(JSON.stringify(result)) + process.stdout.write('\\n' + request.frame + JSON.stringify(result) + '\\n', () => process.exit(0)) } import(pathToFileURL(request.resolvedPath).href).then((module) => { @@ -109,14 +114,19 @@ import(pathToFileURL(request.resolvedPath).href).then((module) => { */ export async function loadModuleSchema(request: ModuleLoadRequest): Promise { return new Promise((resolve) => { + // Per load, so a module cannot print something that passes for the + // verdict without having read this process's environment. + const frame = `@laqi-verdict:${randomUUID()}:` const child = spawn(process.execPath, ['-e', CHILD], { - env: { ...process.env, LAQI_MODULE_REQUEST: JSON.stringify(request) }, + env: { ...process.env, LAQI_MODULE_REQUEST: JSON.stringify({ ...request, frame }) }, stdio: ['ignore', 'pipe', 'pipe'], }) let out = '' let err = '' let settled = false + let exited = false + let verdict: ModuleLoadResult | undefined const finish = (result: ModuleLoadResult) => { if (settled) return @@ -125,17 +135,31 @@ export async function loadModuleSchema(request: ModuleLoadRequest): Promise { + verdict = result.ok ? withDialect(result) : result + child.kill('SIGKILL') + if (exited) finish(verdict) + } + const timer = setTimeout(() => { child.kill('SIGKILL') - finish({ - ok: false, - code: 'timeout', - error: `loading ${request.exportName} took longer than ${MODULE_LOAD_TIMEOUT_MS / 1000} seconds, so laqi stopped it`, - }) + finish( + verdict ?? { + ok: false, + code: 'timeout', + error: `loading ${request.exportName} took longer than ${MODULE_LOAD_TIMEOUT_MS / 1000} seconds, so laqi stopped it`, + }, + ) }, MODULE_LOAD_TIMEOUT_MS) child.stdout.on('data', (chunk: Buffer) => { out += chunk.toString('utf8') + if (verdict !== undefined) return + const found = readResult(out, frame) + if (found !== undefined) accept(found) }) child.stderr.on('data', (chunk: Buffer) => { err += chunk.toString('utf8') @@ -145,9 +169,14 @@ export async function loadModuleSchema(request: ModuleLoadRequest): Promise { + exited = true + if (verdict !== undefined) finish(verdict) + }) + child.on('close', (code) => { - if (settled) return - const parsed = readResult(out) + if (settled || verdict !== undefined) return + const parsed = readResult(out, frame) if (parsed !== undefined) { finish(parsed.ok ? withDialect(parsed) : parsed) return @@ -166,21 +195,26 @@ export async function loadModuleSchema(request: ModuleLoadRequest): Promise