From 3a1814e63f069204d30394cd649adfd1aa8472cf Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:32:54 +0800 Subject: [PATCH] fix(pi): report truncated JSONL input on shutdown --- runtime/pi/src/worker.ts | 11 ++++++++++- runtime/pi/test/protocol.test.mjs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index f2992b3b..48bab304 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -356,7 +356,16 @@ const reader = new RecordReader(); process.stdin.on("data", (chunk: Buffer) => { try { for (const record of reader.push(chunk)) void command(record).catch(fatal); } catch (e) { void fatal(e); } }); -process.stdin.on("end", () => { if (started) void command({ type: "cancel" }); else process.exit(0); }); +process.stdin.on("end", () => { + try { + reader.finish(); + } catch (error) { + void fatal(error); + return; + } + if (started) void command({ type: "cancel" }); + else process.exit(0); +}); async function fatal(error: unknown): Promise { await send({ type: "fatal", error: error instanceof Error ? error.message : String(error) }); session?.dispose(); diff --git a/runtime/pi/test/protocol.test.mjs b/runtime/pi/test/protocol.test.mjs index ec9f0550..aaf0c107 100644 --- a/runtime/pi/test/protocol.test.mjs +++ b/runtime/pi/test/protocol.test.mjs @@ -3,6 +3,22 @@ import { test } from "node:test"; import { spawn } from "node:child_process"; import { once } from "node:events"; +test("the worker flushes a fatal record for a truncated input at EOF", { timeout: 10000 }, async t => { + const child = spawn(process.execPath, ["dist/worker.js"], { stdio: ["pipe", "pipe", "pipe"] }); + t.after(() => child.kill()); + const closed = once(child, "close"); + const chunks = []; + child.stdout.on("data", chunk => chunks.push(chunk)); + await once(child.stdout, "data"); + child.stdin.end('{"type":'); + const [code] = await closed; + const output = Buffer.concat(chunks).toString(); + assert.equal(code, 1); + assert.ok(output.endsWith("\n")); + const records = output.trimEnd().split("\n").map(line => JSON.parse(line)); + assert.deepEqual(records.at(-1), { type: "fatal", error: "Truncated protocol record" }); +}); + test("send waits for the write callback even below the stream high water mark", async () => { const child = spawn(process.execPath, ["--input-type=module", "-e", ` import { send } from './dist/protocol.js';