From 2db845f79136d66544d3f98f803960a7c604f0cd Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Wed, 25 Nov 2026 19:44:59 +0800 Subject: [PATCH 1/3] fix(runtime): flush tracked stdout/stderr before exit after run --- packages/cli/src/main.ts | 28 ++--- packages/kscli/src/main.ts | 16 +-- packages/runtime/src/create-cli.ts | 45 +++++++- packages/runtime/src/error-handler.ts | 12 ++- packages/runtime/src/index.ts | 8 +- packages/runtime/src/output/flush.ts | 89 ++++++++++++++++ packages/runtime/tests/error-handler.test.ts | 80 +++++++------- packages/runtime/tests/flush-output.test.ts | 100 ++++++++++++++++++ .../runtime/tests/harness/run-to-exit-main.ts | 30 ++++++ packages/runtime/tests/interrupt.test.ts | 49 +++++++++ packages/runtime/tests/preparation.test.ts | 4 +- .../runtime/tests/run-to-exit.e2e.test.ts | 79 ++++++++++++++ packages/runtime/tests/run-to-exit.test.ts | 52 +++++++++ 13 files changed, 522 insertions(+), 70 deletions(-) create mode 100644 packages/runtime/src/output/flush.ts create mode 100644 packages/runtime/tests/flush-output.test.ts create mode 100644 packages/runtime/tests/harness/run-to-exit-main.ts create mode 100644 packages/runtime/tests/run-to-exit.e2e.test.ts create mode 100644 packages/runtime/tests/run-to-exit.test.ts diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index ea836fc29..a8f65cdd3 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -1,4 +1,4 @@ -import { createCli } from "bailian-cli-runtime"; +import { createCli, runToExit } from "bailian-cli-runtime"; import { commandAliases, commands } from "./commands.ts"; import { commandPackPolicy } from "./command-pack-policy.ts"; import pkg from "../package.json" with { type: "json" }; @@ -12,15 +12,17 @@ const quickStartTasks = [ "介绍一下 Bailian CLI 能帮我完成哪些任务,并根据我的需求推荐使用方式。\n Explain what Bailian CLI can help me accomplish, and recommend how to use it based on my needs.", ] as const; -void createCli( - { ...commands, ...commandAliases }, - { - binName: "bl", - ...resolveAliyunIntegration(process.env), - version: pkg.version, - clientName: "bailian-cli", - npmPackage: "bailian-cli", - quickStartTasks, - commandPacks: commandPackPolicy, - }, -).run(); +void runToExit( + createCli( + { ...commands, ...commandAliases }, + { + binName: "bl", + ...resolveAliyunIntegration(process.env), + version: pkg.version, + clientName: "bailian-cli", + npmPackage: "bailian-cli", + quickStartTasks, + commandPacks: commandPackPolicy, + }, + ), +); diff --git a/packages/kscli/src/main.ts b/packages/kscli/src/main.ts index fbd0f0453..6cf1ee1bc 100644 --- a/packages/kscli/src/main.ts +++ b/packages/kscli/src/main.ts @@ -1,10 +1,12 @@ -import { createCli } from "bailian-cli-runtime"; +import { createCli, runToExit } from "bailian-cli-runtime"; import { commands } from "./commands.ts"; import pkg from "../package.json" with { type: "json" }; -void createCli(commands, { - binName: "kscli", - version: pkg.version, - clientName: "knowledge-studio-cli", - npmPackage: "knowledge-studio-cli", -}).run(); +void runToExit( + createCli(commands, { + binName: "kscli", + version: pkg.version, + clientName: "knowledge-studio-cli", + npmPackage: "knowledge-studio-cli", + }), +); diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index 4969e9ac8..d07576464 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -44,6 +44,7 @@ import { } from "bailian-cli-core"; import { setupProxyFromEnv } from "./proxy.ts"; import { handleError } from "./error-handler.ts"; +import { flushOutput, INTERRUPT_FLUSH_TIMEOUT_MS, trackStreamWrites } from "./output/flush.ts"; import { type OutputReporter, createOutputReporter } from "./output/reporter.ts"; import { loadCommandPacks } from "./command-packs/load.ts"; import { createCommandPackManager } from "./command-packs/manager.ts"; @@ -124,6 +125,8 @@ interface ProcessOutputContext { const activeProcessOutputs = new Set(); const managedInterruptHandlers = new Set<() => void>(); +/** True while the default SIGINT path is flushing before exit(130). */ +let interruptExiting = false; /** Let a command cancel asynchronous work and finish cleanup before the runtime exits. */ export function registerInterruptHandler(handler: () => void): () => void { @@ -139,8 +142,14 @@ export function registerInterruptHandler(handler: () => void): () => void { /** One process event produces one error, using the first still-active invocation. */ function handleInterrupt(): void { if (managedInterruptHandlers.size > 0) return; + // Second Ctrl-C during flush: exit immediately instead of waiting out the short timeout. + if (interruptExiting) { + process.exit(130); + return; + } const active = activeProcessOutputs.values().next().value; if (!active) return; + interruptExiting = true; active .getReporter() .error( @@ -149,14 +158,22 @@ function handleInterrupt(): void { 130 as ExitCode, ), ); - void flushTelemetry(500).finally(() => process.exit(130)); + void flushTelemetry(500) + .catch(() => undefined) + .then(() => flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS)) + .finally(() => process.exit(130)); } /** Keep EPIPE protection after run() returns, without retaining completed invocations. */ function handleStdoutPipeError(error: NodeJS.ErrnoException): void { + // Broken pipe: further flush cannot deliver data and may wait out the timeout. if (error.code === "EPIPE") process.exit(0); const active = activeProcessOutputs.values().next().value; - if (active) process.exit(active.getReporter().error(error)); + if (active) { + const code = active.getReporter().error(error); + void flushOutput().finally(() => process.exit(code)); + return; + } // Outside an invocation, let other listeners handle errors or retain Node's failure behavior. if (process.stdout.listenerCount("error") === 1) throw error; } @@ -168,7 +185,10 @@ function installProcessHandlers( if (!process.stdout.listeners("error").includes(handleStdoutPipeError)) { process.stdout.on("error", handleStdoutPipeError); } - if (activeProcessOutputs.size === 0) process.on("SIGINT", handleInterrupt); + if (activeProcessOutputs.size === 0) { + interruptExiting = false; + process.on("SIGINT", handleInterrupt); + } const context = { getReporter, localize }; activeProcessOutputs.add(context); return () => { @@ -409,10 +429,27 @@ export function createCli(commands: Record, opts: CliOptions } catch (error) { for (const warning of warnings.splice(0)) reporter.output.warning(warning); await flushTelemetry(1000); - handleError(error, reporter); + await handleError(error, reporter); } finally { cleanup(); } }, }; } + +/** + * Product entry helper: await the invocation, flush tracked stdout/stderr, then + * exit. Forces the process to leave after a successful run so Bun keep-alive + * sockets cannot linger (~50 s on Windows release binaries). + * + * `run()` itself stays unchanged for in-process harnesses. Install write + * tracking before `run()` so every real write's callback is awaited; an empty + * `write("")` flush is not reliable on Bun when stdout is a pipe. + */ +export async function runToExit(cli: Cli, argv?: string[]): Promise { + trackStreamWrites(process.stdout); + trackStreamWrites(process.stderr); + await cli.run(argv); + await flushOutput(); + process.exit(process.exitCode ?? 0); +} diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index 292817044..78771c6ec 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -7,12 +7,18 @@ import { type LocalizedText, } from "bailian-cli-core"; import type { OutputReporter } from "./output/reporter.ts"; +import { flushOutput } from "./output/flush.ts"; import { sanitizeDiagnosticDetails } from "./output/diagnostics.ts"; import { API_KEY_PAGE } from "./urls.ts"; -/** The invocation owns rendering; this boundary owns process termination. */ -export function handleError(error: unknown, reporter: Pick): never { - process.exit(reporter.error(error)); +/** Render the error, flush tracked stderr/stdout, then terminate. */ +export async function handleError( + error: unknown, + reporter: Pick, +): Promise { + const code = reporter.error(error); + await flushOutput(); + process.exit(code); } export function normalizeError( diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 3c581b292..8cb9ce2f7 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -2,10 +2,16 @@ // each entrypoint (bl / rag / …) injects its own command set via createCli(). // Entrypoint factory + identity -export { createCli, registerInterruptHandler } from "./create-cli.ts"; +export { createCli, registerInterruptHandler, runToExit } from "./create-cli.ts"; export { buildCommandSchema, serializeCommandSchema } from "./introspect.ts"; export type { CommandSchema, CommandSchemaNode } from "./introspect.ts"; export type { Cli, CliOptions } from "./create-cli.ts"; +export { + DEFAULT_FLUSH_TIMEOUT_MS, + flushOutput, + INTERRUPT_FLUSH_TIMEOUT_MS, + trackStreamWrites, +} from "./output/flush.ts"; // Command Pack product policy export type { diff --git a/packages/runtime/src/output/flush.ts b/packages/runtime/src/output/flush.ts new file mode 100644 index 000000000..16be9cbbb --- /dev/null +++ b/packages/runtime/src/output/flush.ts @@ -0,0 +1,89 @@ +/** + * Track every stdout/stderr write so the process can exit only after the data + * reached the OS. Bun does not order an empty write's callback after earlier + * writes and does not report writableLength, so the callback of each real write + * is the only reliable completion signal on both Node and Bun. + */ + +import { writeSync } from "node:fs"; + +const pending = new Set>(); +const tracked = new WeakSet(); + +/** Default wait for success / error-render paths. */ +export const DEFAULT_FLUSH_TIMEOUT_MS = 5000; + +/** Short wait for Ctrl-C so a stuck write cannot feel like a hang. */ +export const INTERRUPT_FLUSH_TIMEOUT_MS = 500; + +type WriteCallback = (error?: Error | null) => void; + +export function trackStreamWrites(stream: NodeJS.WriteStream): void { + if (tracked.has(stream)) return; + tracked.add(stream); + const original = stream.write.bind(stream) as { + (chunk: unknown, callback?: WriteCallback): boolean; + (chunk: unknown, encoding: BufferEncoding, callback?: WriteCallback): boolean; + }; + stream.write = (( + chunk: unknown, + encodingOrCallback?: BufferEncoding | WriteCallback, + maybeCallback?: WriteCallback, + ) => { + const callback = typeof encodingOrCallback === "function" ? encodingOrCallback : maybeCallback; + const encoding = typeof encodingOrCallback === "function" ? undefined : encodingOrCallback; + let settle!: () => void; + const done = new Promise((resolve) => { + settle = resolve; + }); + pending.add(done); + void done.then(() => pending.delete(done)); + const onComplete: WriteCallback = (error) => { + // Settle on error too: an EPIPE must not keep the process alive. + settle(); + callback?.(error); + }; + try { + if (encoding !== undefined) return original(chunk, encoding, onComplete); + return original(chunk, onComplete); + } catch (error) { + settle(); + throw error; + } + }) as typeof stream.write; +} + +/** + * Wait until every tracked write has completed, or `timeoutMs` has passed. + * Returns true when the wait timed out (output may be truncated). Does not + * change process.exitCode; callers keep their existing exit codes. + */ +export async function flushOutput(timeoutMs = DEFAULT_FLUSH_TIMEOUT_MS): Promise { + if (pending.size === 0) return false; + const waiting = [...pending]; + let timer: ReturnType | undefined; + const timedOut = await Promise.race([ + Promise.all(waiting).then(() => false), + new Promise((resolve) => { + timer = setTimeout(() => resolve(true), timeoutMs); + timer.unref?.(); + }), + ]); + clearTimeout(timer); + // Drop waiters that never completed so a later flush is not blocked by them. + if (timedOut) { + for (const done of waiting) pending.delete(done); + // Observable signal only — do not change exit codes. writeSync bypasses the + // tracked wrapper so this diagnostic is not itself left pending. + try { + writeSync( + 2, + "Warning: timed out waiting for stdout/stderr to flush; output may be truncated.\n" + + "警告:等待标准输出刷新超时,输出可能被截断。\n", + ); + } catch { + // stderr may already be broken; ignore. + } + } + return timedOut; +} diff --git a/packages/runtime/tests/error-handler.test.ts b/packages/runtime/tests/error-handler.test.ts index b34625b34..fc9a0228c 100644 --- a/packages/runtime/tests/error-handler.test.ts +++ b/packages/runtime/tests/error-handler.test.ts @@ -7,7 +7,7 @@ import { ConfirmationRequiredError } from "../src/confirm.ts"; const blHasCommand = (path: string) => path === "usage free" || path === "usage freetier"; const kscliHasCommand = () => false; -function render( +async function render( error: unknown, output: "text" | "json" = "json", options: { @@ -34,7 +34,7 @@ function render( throw new Error(`process.exit:${code ?? 0}`); }); try { - expect(() => handleError(error, reporter)).toThrow(/process.exit:/); + await expect(handleError(error, reporter)).rejects.toThrow(/process.exit:/); } finally { exit.mockRestore(); } @@ -47,11 +47,11 @@ const FREE_TIER_MESSAGE = const FREE_QUOTA_MESSAGE = 'Free quota exhausted. To continue accessing the model on a paid basis, please add funds or disable the "use free tier only" mode in the management console.'; -test("handleError: fetch failed JSON includes cause.code from errno", () => { +test("handleError: fetch failed JSON includes cause.code from errno", async () => { const cause = Object.assign(new Error("getaddrinfo ENOTFOUND example.invalid"), { code: "ENOTFOUND", }); - const stderr = render(new TypeError("fetch failed", { cause })); + const stderr = await render(new TypeError("fetch failed", { cause })); expect(stderr.trim().split("\n")).toHaveLength(1); expect(JSON.parse(stderr).error).toMatchObject({ code: ExitCode.NETWORK, @@ -59,16 +59,16 @@ test("handleError: fetch failed JSON includes cause.code from errno", () => { }); }); -test("handleError: fetch without nested cause still maps to NETWORK", () => { - const payload = JSON.parse(render(new TypeError("fetch failed"))).error; +test("handleError: fetch without nested cause still maps to NETWORK", async () => { + const payload = JSON.parse(await render(new TypeError("fetch failed"))).error; expect(payload.code).toBe(ExitCode.NETWORK); expect(payload.message).toContain("unknown cause"); expect(payload.cause).toEqual({ message: "fetch failed" }); }); -test("handleError: 沙箱拒绝 errno(EPERM)hint 引导放行网络而非换镜像", () => { +test("handleError: 沙箱拒绝 errno(EPERM)hint 引导放行网络而非换镜像", async () => { const cause = Object.assign(new Error("connect EPERM 1.2.3.4:443"), { code: "EPERM" }); - const payload = JSON.parse(render(new TypeError("fetch failed", { cause }))).error; + const payload = JSON.parse(await render(new TypeError("fetch failed", { cause }))).error; expect(payload.code).toBe(ExitCode.NETWORK); expect(payload.message).toContain("EPERM"); expect(payload.hint).toContain("agent sandbox"); @@ -85,34 +85,34 @@ test("normalizeError: 沙箱拒绝 hint 中文本地化", () => { expect(normalized.hint).toContain("HTTPS_PROXY"); }); -test("handleError: confirmation preserves its structured subtype and guidance", () => { +test("handleError: confirmation preserves its structured subtype and guidance", async () => { const confirmation = new ConfirmationRequiredError({ message: "Permanent deletion.", hint: "Add --yes to continue.", }); - expect(JSON.parse(render(confirmation))).toEqual(confirmation.toJSON()); - const text = render(confirmation, "text"); + expect(JSON.parse(await render(confirmation))).toEqual(confirmation.toJSON()); + const text = await render(confirmation, "text"); expect(text).toContain("Add --yes to continue."); expect(text).not.toContain("Risk:"); }); -test("model-auth guidance uses the invocation binary and does not leak into console errors", () => { - const auth = JSON.parse(render(new BailianError("No key", ExitCode.AUTH))).error; +test("model-auth guidance uses the invocation binary and does not leak into console errors", async () => { + const auth = JSON.parse(await render(new BailianError("No key", ExitCode.AUTH))).error; expect(auth.hint).toContain("kscli auth status"); const consoleError = new BailianError( "No console token", ExitCode.AUTH, "Run kscli auth login --console", ); - expect(JSON.parse(render(consoleError))).toEqual(consoleError.toJSON()); + expect(JSON.parse(await render(consoleError))).toEqual(consoleError.toJSON()); }); -test("free-tier hint appends for AllocationQuota.FreeTierOnly when product supports usage", () => { +test("free-tier hint appends for AllocationQuota.FreeTierOnly when product supports usage", async () => { const error = new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, undefined, { api: { httpStatus: 403, apiCode: FREE_TIER_ONLY_API_CODE }, }); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.code).toBe(ExitCode.GENERAL); expect(payload.message).toBe(FREE_TIER_MESSAGE); @@ -120,7 +120,7 @@ test("free-tier hint appends for AllocationQuota.FreeTierOnly when product suppo expect(payload.hint).toContain("bl usage freetier --off --model "); expect(payload.hint).not.toContain("--yes"); expect(payload.hint).not.toContain("--all"); - const text = render(error, "text", { commandPrefix: "bl", hasCommand: blHasCommand }); + const text = await render(error, "text", { commandPrefix: "bl", hasCommand: blHasCommand }); expect(text).toContain("Hint:"); expect(text).toContain("usage freetier --off"); expect(text).not.toContain("--yes"); @@ -141,16 +141,16 @@ test("free-tier hint uses message fallback when type shadows AllocationQuota.Fre expect(hint).toContain("bl usage freetier --off"); }); -test("OpenAI-compat Free quota exhausted copy matches via use free tier only phrase", () => { +test("OpenAI-compat Free quota exhausted copy matches via use free tier only phrase", async () => { const error = new BailianError(FREE_QUOTA_MESSAGE, ExitCode.GENERAL); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.hint).toContain("bl usage freetier --off --model "); expect(payload.hint).not.toContain("--yes"); }); -test("insufficient_quota TPS/TPM message does not get free-tier recovery", () => { +test("insufficient_quota TPS/TPM message does not get free-tier recovery", async () => { const error = new BailianError( "You exceeded your current quota, please check your plan and billing details.", ExitCode.GENERAL, @@ -158,34 +158,34 @@ test("insufficient_quota TPS/TPM message does not get free-tier recovery", () => { api: { apiCode: "insufficient_quota" } }, ); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.hint).toBeUndefined(); }); -test("free-tier hint is skipped when the product does not expose usage commands", () => { +test("free-tier hint is skipped when the product does not expose usage commands", async () => { const error = new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, undefined, { api: { apiCode: FREE_TIER_ONLY_API_CODE }, }); const payload = JSON.parse( - render(error, "json", { commandPrefix: "kscli", hasCommand: kscliHasCommand }), + await render(error, "json", { commandPrefix: "kscli", hasCommand: kscliHasCommand }), ).error; expect(payload.hint).toBeUndefined(); expect(payload.message).toBe(FREE_TIER_MESSAGE); }); -test("free-tier hint appends after an existing hint without replacing it", () => { +test("free-tier hint appends after an existing hint without replacing it", async () => { const existing = "Task id: task-demo"; const error = new BailianError(FREE_QUOTA_MESSAGE, ExitCode.GENERAL, existing); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.hint?.startsWith(existing)).toBe(true); expect(payload.hint).toContain("usage freetier --off"); expect(payload.hint).not.toContain("--yes"); }); -test("free-tier hint does not duplicate when existing hint already contains full recovery text", () => { +test("free-tier hint does not duplicate when existing hint already contains full recovery text", async () => { const recovery = errorHint( new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, undefined, { api: { apiCode: FREE_TIER_ONLY_API_CODE }, @@ -199,30 +199,30 @@ test("free-tier hint does not duplicate when existing hint already contains full api: { apiCode: FREE_TIER_ONLY_API_CODE }, }); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.hint).toBe(recovery); expect(payload.hint?.split("usage freetier").length - 1).toBe(1); }); -test("free-tier hint still appends when existing hint only mentions usage freetier loosely", () => { +test("free-tier hint still appends when existing hint only mentions usage freetier loosely", async () => { const existing = "Already guided: bl usage freetier --off --model demo"; const error = new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, existing, { api: { apiCode: FREE_TIER_ONLY_API_CODE }, }); const payload = JSON.parse( - render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), + await render(error, "json", { commandPrefix: "bl", hasCommand: blHasCommand }), ).error; expect(payload.hint?.startsWith(existing)).toBe(true); expect(payload.hint?.split("usage freetier").length - 1).toBe(2); }); -test("recovery hints append --config when a named profile is active", () => { +test("recovery hints append --config when a named profile is active", async () => { const freeTier = new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, undefined, { api: { httpStatus: 403, apiCode: FREE_TIER_ONLY_API_CODE }, }); const freeTierHint = JSON.parse( - render(freeTier, "json", { + await render(freeTier, "json", { commandPrefix: "bl", hasCommand: blHasCommand, configName: "prod", @@ -232,7 +232,7 @@ test("recovery hints append --config when a named profile is active", () => { expect(freeTierHint).toContain("bl usage freetier --off --model --config prod"); const authHint = JSON.parse( - render(new BailianError("No key", ExitCode.AUTH), "json", { + await render(new BailianError("No key", ExitCode.AUTH), "json", { commandPrefix: "bl", configName: "prod", }), @@ -241,7 +241,7 @@ test("recovery hints append --config when a named profile is active", () => { expect(authHint).toContain("bl auth status --config prod"); const timeoutHint = JSON.parse( - render(Object.assign(new Error("timed out"), { name: "TimeoutError" }), "json", { + await render(Object.assign(new Error("timed out"), { name: "TimeoutError" }), "json", { commandPrefix: "bl", configName: "prod", }), @@ -250,15 +250,15 @@ test("recovery hints append --config when a named profile is active", () => { expect(timeoutHint).toContain("bl auth status --config prod"); }); -test("recovery hints omit --config for the implicit default profile", () => { +test("recovery hints omit --config for the implicit default profile", async () => { const payload = JSON.parse( - render(new BailianError("No key", ExitCode.AUTH), "json", { commandPrefix: "bl" }), + await render(new BailianError("No key", ExitCode.AUTH), "json", { commandPrefix: "bl" }), ).error; expect(payload.hint).toContain("bl auth status"); expect(payload.hint).not.toContain("--config"); }); -test("recovery hints keep explicit --config default when active profile is named", () => { +test("recovery hints keep explicit --config default when active profile is named", async () => { // Loader normalizes explicit default to undefined; resolveRecoveryConfigName must restore it. expect(resolveRecoveryConfigName({ flags: { config: "default" }, configName: undefined })).toBe( "default", @@ -268,7 +268,7 @@ test("recovery hints keep explicit --config default when active profile is named expect(resolveRecoveryConfigName({ flags: {}, configName: undefined })).toBeUndefined(); const hint = JSON.parse( - render(new BailianError("No key", ExitCode.AUTH), "json", { + await render(new BailianError("No key", ExitCode.AUTH), "json", { commandPrefix: "bl", configName: "default", }), @@ -277,12 +277,12 @@ test("recovery hints keep explicit --config default when active profile is named expect(hint).toContain("bl auth status --config default"); }); -test("setRecoveryConfigName retargets free-tier and missing-api-key hints to default", () => { +test("setRecoveryConfigName retargets free-tier and missing-api-key hints to default", async () => { const freeTier = new BailianError(FREE_TIER_MESSAGE, ExitCode.GENERAL, undefined, { api: { httpStatus: 403, apiCode: FREE_TIER_ONLY_API_CODE }, }); const freeTierHint = JSON.parse( - render( + await render( freeTier, "json", { commandPrefix: "bl", hasCommand: blHasCommand, configName: "prod" }, @@ -293,7 +293,7 @@ test("setRecoveryConfigName retargets free-tier and missing-api-key hints to def expect(freeTierHint).not.toContain("--config prod"); const authHint = JSON.parse( - render( + await render( new BailianError("No key", ExitCode.AUTH), "json", { commandPrefix: "bl", configName: "prod" }, diff --git a/packages/runtime/tests/flush-output.test.ts b/packages/runtime/tests/flush-output.test.ts new file mode 100644 index 000000000..3c9fa41ef --- /dev/null +++ b/packages/runtime/tests/flush-output.test.ts @@ -0,0 +1,100 @@ +import { afterEach, expect, test, vi } from "vite-plus/test"; +import { flushOutput, INTERRUPT_FLUSH_TIMEOUT_MS, trackStreamWrites } from "../src/output/flush.ts"; + +type WriteCallback = (error?: Error | null) => void; + +function createDeferredWriteStream(options?: { neverComplete?: boolean }) { + const callbacks: WriteCallback[] = []; + const stream = { + write( + _chunk: unknown, + encodingOrCallback?: BufferEncoding | WriteCallback, + maybeCallback?: WriteCallback, + ) { + const callback = + typeof encodingOrCallback === "function" ? encodingOrCallback : maybeCallback; + if (callback && !options?.neverComplete) callbacks.push(callback); + return true; + }, + } as unknown as NodeJS.WriteStream; + trackStreamWrites(stream); + return { + stream, + completeNext(error?: Error | null) { + const callback = callbacks.shift(); + if (!callback) throw new Error("No pending write callback"); + callback(error); + }, + pendingCount: () => callbacks.length, + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +test("flushOutput waits for tracked write callbacks", async () => { + const writable = createDeferredWriteStream(); + writable.stream.write("hello"); + expect(writable.pendingCount()).toBe(1); + + let flushed = false; + let timedOut: boolean | undefined; + const pending = flushOutput(5_000).then((result) => { + timedOut = result; + flushed = true; + }); + await Promise.resolve(); + expect(flushed).toBe(false); + + writable.completeNext(); + await pending; + expect(flushed).toBe(true); + expect(timedOut).toBe(false); +}); + +test("flushOutput returns true when a callback never fires", async () => { + vi.useFakeTimers(); + const writable = createDeferredWriteStream({ neverComplete: true }); + writable.stream.write("stuck"); + + const pending = flushOutput(50); + await vi.advanceTimersByTimeAsync(50); + expect(await pending).toBe(true); +}); + +test("flushOutput settles when a write callback reports an error", async () => { + const writable = createDeferredWriteStream(); + writable.stream.write("broken"); + const pending = flushOutput(5_000); + writable.completeNext(new Error("EPIPE")); + expect(await pending).toBe(false); +}); + +test("trackStreamWrites is idempotent on the same stream", async () => { + const writable = createDeferredWriteStream(); + trackStreamWrites(writable.stream); + writable.stream.write("once"); + expect(writable.pendingCount()).toBe(1); + const pending = flushOutput(5_000); + writable.completeNext(); + expect(await pending).toBe(false); +}); + +test("trackStreamWrites settles pending when write throws synchronously", async () => { + const stream = { + write() { + throw new Error("sync write failure"); + }, + } as unknown as NodeJS.WriteStream; + trackStreamWrites(stream); + expect(() => stream.write("x")).toThrow("sync write failure"); + const startedAt = Date.now(); + expect(await flushOutput(5_000)).toBe(false); + expect(Date.now() - startedAt).toBeLessThan(1_000); +}); + +test("interrupt flush timeout is much shorter than the default", () => { + expect(INTERRUPT_FLUSH_TIMEOUT_MS).toBeLessThan(5_000); + expect(INTERRUPT_FLUSH_TIMEOUT_MS).toBeGreaterThan(0); +}); diff --git a/packages/runtime/tests/harness/run-to-exit-main.ts b/packages/runtime/tests/harness/run-to-exit-main.ts new file mode 100644 index 000000000..e0fcb3360 --- /dev/null +++ b/packages/runtime/tests/harness/run-to-exit-main.ts @@ -0,0 +1,30 @@ +import { createServer } from "node:http"; +import { runToExit } from "../../src/create-cli.ts"; + +const payloadBytes = Number(process.argv[2] ?? "2000000"); +const exitCode = Number(process.argv[3] ?? "0"); +const keepAliveMs = Number(process.argv[4] ?? "0"); + +async function holdKeepAlive(): Promise { + if (keepAliveMs <= 0) return; + const server = createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/plain", connection: "keep-alive" }); + response.end("ok"); + }); + server.keepAliveTimeout = keepAliveMs; + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + const response = await fetch(`http://127.0.0.1:${address.port}/`); + await response.text(); + // Leave the server (and keep-alive socket) alive; runToExit must still exit. + setTimeout(() => server.close(), keepAliveMs).unref?.(); +} + +await runToExit({ + async run() { + await holdKeepAlive(); + process.stdout.write(`${JSON.stringify({ data: "x".repeat(payloadBytes) })}\n`); + if (exitCode !== 0) process.exitCode = exitCode; + }, +}); diff --git a/packages/runtime/tests/interrupt.test.ts b/packages/runtime/tests/interrupt.test.ts index 6bebbfc05..e446c9878 100644 --- a/packages/runtime/tests/interrupt.test.ts +++ b/packages/runtime/tests/interrupt.test.ts @@ -66,3 +66,52 @@ test("临时 Ctrl-C 处理释放后恢复默认退出 130,释放可重复调 isolated.dispose(); } }); + +test("第二次 Ctrl-C 在中断刷新期间立即退出", async () => { + const isolated = buildIsolatedCliEnv({ + overrides: { + HTTP_PROXY: "", + HTTPS_PROXY: "", + http_proxy: "", + https_proxy: "", + NODE_OPTIONS: "", + NO_UPDATE_NOTIFIER: "1", + }, + }); + try { + await runInProcess( + async () => { + const cli = createCli( + { + fixture: { + auth: "none", + description: "fixture", + async run() { + const exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never); + try { + process.emit("SIGINT"); + process.emit("SIGINT"); + await vi.waitFor(() => expect(exit.mock.calls.length).toBeGreaterThanOrEqual(2)); + expect(exit.mock.calls.every((call) => call[0] === 130)).toBe(true); + } finally { + exit.mockRestore(); + } + }, + }, + }, + { + binName: "test-cli", + version: "0.0.0-test", + npmPackage: "test-cli", + clientName: "test-client", + }, + ); + await cli.run(["fixture"]); + }, + [], + { env: isolated.env }, + ); + } finally { + isolated.dispose(); + } +}); diff --git a/packages/runtime/tests/preparation.test.ts b/packages/runtime/tests/preparation.test.ts index 05c6aaaba..af71834e2 100644 --- a/packages/runtime/tests/preparation.test.ts +++ b/packages/runtime/tests/preparation.test.ts @@ -156,7 +156,7 @@ test("human confirmation output includes the actual plan and notices", async () try { await runCommandStage(context, async () => {}); } catch (error) { - expect(() => + await expect( handleError( error, createOutputReporter({ @@ -164,7 +164,7 @@ test("human confirmation output includes the actual plan and notices", async () commandPrefix: "fixture", }), ), - ).toThrow("exit-confirmation"); + ).rejects.toThrow("exit-confirmation"); } expect(output.join("")).toContain("creates"); expect(output.join("")).toContain("index"); diff --git a/packages/runtime/tests/run-to-exit.e2e.test.ts b/packages/runtime/tests/run-to-exit.e2e.test.ts new file mode 100644 index 000000000..cbc06638a --- /dev/null +++ b/packages/runtime/tests/run-to-exit.e2e.test.ts @@ -0,0 +1,79 @@ +import { execFile, spawnSync } from "node:child_process"; +import { dirname, join } from "node:path"; +import { performance } from "node:perf_hooks"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { describe, expect, test } from "vite-plus/test"; + +const execFileAsync = promisify(execFile); +const runtimeRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); +const harness = join(runtimeRoot, "tests/harness/run-to-exit-main.ts"); +const bun = process.env.BAILIAN_TEST_BUN ?? "bun"; +const hasBun = spawnSync(bun, ["--version"], { stdio: "ignore" }).status === 0; +const payloadBytes = 2_000_000; + +describe.each(["node", ...(hasBun ? ["bun"] : [])])( + "runToExit large piped stdout (%s)", + (runtime) => { + test("delivers the full JSON payload and exits promptly", async () => { + const startedAt = performance.now(); + const { stdout, stderr } = await execFileAsync( + runtime === "node" ? process.execPath : bun, + [ + ...(runtime === "node" ? ["--import", import.meta.resolve("tsx")] : []), + harness, + String(payloadBytes), + "0", + "60000", + ], + { + cwd: runtimeRoot, + // execFile pipes stdout by default; this is the Bun truncation scenario. + timeout: 15_000, + maxBuffer: payloadBytes + 64_000, + env: { + ...process.env, + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", + }, + }, + ); + const elapsedMs = performance.now() - startedAt; + expect(stderr).toBe(""); + const parsed = JSON.parse(stdout) as { data: string }; + expect(parsed.data.length).toBe(payloadBytes); + expect(elapsedMs).toBeLessThan(10_000); + }); + + test("preserves a non-zero process.exitCode", async () => { + const error = await execFileAsync( + runtime === "node" ? process.execPath : bun, + [ + ...(runtime === "node" ? ["--import", import.meta.resolve("tsx")] : []), + harness, + "16", + "3", + "0", + ], + { + cwd: runtimeRoot, + timeout: 10_000, + env: { + ...process.env, + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", + }, + }, + ).then( + () => undefined, + (failure: NodeJS.ErrnoException & { code?: number; stdout?: string }) => failure, + ); + expect(error).toBeDefined(); + expect(error?.code).toBe(3); + const parsed = JSON.parse(String(error?.stdout ?? "")) as { data: string }; + expect(parsed.data.length).toBe(16); + }); + }, +); diff --git a/packages/runtime/tests/run-to-exit.test.ts b/packages/runtime/tests/run-to-exit.test.ts new file mode 100644 index 000000000..22b5c58c9 --- /dev/null +++ b/packages/runtime/tests/run-to-exit.test.ts @@ -0,0 +1,52 @@ +import { afterEach, expect, test, vi } from "vite-plus/test"; +import { runToExit, type Cli } from "../src/create-cli.ts"; + +afterEach(() => { + vi.restoreAllMocks(); + process.exitCode = undefined; +}); + +test("runToExit exits with code 0 after run resolves", async () => { + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + const run = vi.fn(async () => undefined); + const cli: Cli = { run }; + await runToExit(cli); + expect(run).toHaveBeenCalledOnce(); + expect(exit).toHaveBeenCalledWith(0); +}); + +test("runToExit keeps an exit code set during run", async () => { + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + const cli: Cli = { + async run() { + process.exitCode = 3; + }, + }; + await runToExit(cli); + expect(exit).toHaveBeenCalledWith(3); +}); + +test("runToExit does not exit while run is still pending", async () => { + const exit = vi + .spyOn(process, "exit") + .mockImplementation((() => undefined) as typeof process.exit); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const cli: Cli = { + async run() { + await gate; + }, + }; + const pending = runToExit(cli); + await Promise.resolve(); + expect(exit).not.toHaveBeenCalled(); + release(); + await pending; + expect(exit).toHaveBeenCalledWith(0); +}); From e0cbe4d573858b77d2d3bb4902c98797e71e8668 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 26 Nov 2026 10:02:45 +0800 Subject: [PATCH 2/3] fix(runtime): wait for flush without truncating slow pipe readers --- packages/runtime/src/create-cli.ts | 33 ++++- packages/runtime/src/error-handler.ts | 3 +- packages/runtime/src/index.ts | 1 + packages/runtime/src/output/flush.ts | 118 +++++++++++++---- packages/runtime/tests/flush-output.test.ts | 45 ++++++- packages/runtime/tests/interrupt.test.ts | 14 +- .../runtime/tests/run-to-exit.e2e.test.ts | 123 ++++++++++++------ 7 files changed, 259 insertions(+), 78 deletions(-) diff --git a/packages/runtime/src/create-cli.ts b/packages/runtime/src/create-cli.ts index d07576464..c307e0f54 100644 --- a/packages/runtime/src/create-cli.ts +++ b/packages/runtime/src/create-cli.ts @@ -121,6 +121,7 @@ function presentationFlags(argv: string[]): Partial { interface ProcessOutputContext { getReporter: () => OutputReporter; localize: (text: LocalizedText) => string; + getOutputFormat: () => "text" | "json"; } const activeProcessOutputs = new Set(); @@ -160,7 +161,12 @@ function handleInterrupt(): void { ); void flushTelemetry(500) .catch(() => undefined) - .then(() => flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS)) + .then(() => + flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS, { + mode: "deadline", + format: active.getOutputFormat(), + }), + ) .finally(() => process.exit(130)); } @@ -171,7 +177,10 @@ function handleStdoutPipeError(error: NodeJS.ErrnoException): void { const active = activeProcessOutputs.values().next().value; if (active) { const code = active.getReporter().error(error); - void flushOutput().finally(() => process.exit(code)); + void flushOutput(INTERRUPT_FLUSH_TIMEOUT_MS, { + mode: "deadline", + format: active.getOutputFormat(), + }).finally(() => process.exit(code)); return; } // Outside an invocation, let other listeners handle errors or retain Node's failure behavior. @@ -181,6 +190,7 @@ function handleStdoutPipeError(error: NodeJS.ErrnoException): void { function installProcessHandlers( getReporter: () => OutputReporter, localize: (text: LocalizedText) => string, + getOutputFormat: () => "text" | "json", ): () => void { if (!process.stdout.listeners("error").includes(handleStdoutPipeError)) { process.stdout.on("error", handleStdoutPipeError); @@ -189,7 +199,7 @@ function installProcessHandlers( interruptExiting = false; process.on("SIGINT", handleInterrupt); } - const context = { getReporter, localize }; + const context = { getReporter, localize, getOutputFormat }; activeProcessOutputs.add(context); return () => { activeProcessOutputs.delete(context); @@ -394,6 +404,7 @@ export function createCli(commands: Record, opts: CliOptions let translator = createTranslator(DEFAULT_LANGUAGE); const localize = (text: LocalizedText) => translator.localize(text); const initialSettings = buildOutputSettings({ flags, env: process.env }); + let outputFormat: "text" | "json" = initialSettings.output; let reporter = createOutputReporter({ settings: initialSettings, localize, @@ -401,13 +412,19 @@ export function createCli(commands: Record, opts: CliOptions hasCommand, }); const warnings: OutputDiagnostic[] = []; - const cleanup = installProcessHandlers(() => reporter, localize); + const cleanup = installProcessHandlers( + () => reporter, + localize, + () => outputFormat, + ); try { const sources = buildSources(flags, (warning) => warnings.push(warning)); const recoveryConfigName = resolveRecoveryConfigName(sources); translator = createTranslator(sources.file.language ?? DEFAULT_LANGUAGE); + const sourceSettings = buildOutputSettings(sources); + outputFormat = sourceSettings.output; reporter = createOutputReporter({ - settings: buildOutputSettings(sources), + settings: sourceSettings, localize, commandPrefix, hasCommand, @@ -416,6 +433,7 @@ export function createCli(commands: Record, opts: CliOptions setupProxyFromEnv(); const registry = await getRegistry(translator); await dispatch(registry, argv, localize, sources, (settings) => { + outputFormat = settings.output; reporter = createOutputReporter({ settings, localize, @@ -445,11 +463,14 @@ export function createCli(commands: Record, opts: CliOptions * `run()` itself stays unchanged for in-process harnesses. Install write * tracking before `run()` so every real write's callback is awaited; an empty * `write("")` flush is not reliable on Bun when stdout is a pipe. + * + * Success-path flush waits until writes complete (no hard timeout) so slow + * readers such as `| less` are not truncated. */ export async function runToExit(cli: Cli, argv?: string[]): Promise { trackStreamWrites(process.stdout); trackStreamWrites(process.stderr); await cli.run(argv); - await flushOutput(); + await flushOutput(null); process.exit(process.exitCode ?? 0); } diff --git a/packages/runtime/src/error-handler.ts b/packages/runtime/src/error-handler.ts index 78771c6ec..407ddc834 100644 --- a/packages/runtime/src/error-handler.ts +++ b/packages/runtime/src/error-handler.ts @@ -17,7 +17,8 @@ export async function handleError( reporter: Pick, ): Promise { const code = reporter.error(error); - await flushOutput(); + // Wait until writes complete; no timeout, so format-based warnings do not apply. + await flushOutput(null); process.exit(code); } diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 8cb9ce2f7..42745d1d0 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -11,6 +11,7 @@ export { flushOutput, INTERRUPT_FLUSH_TIMEOUT_MS, trackStreamWrites, + type FlushOutputOptions, } from "./output/flush.ts"; // Command Pack product policy diff --git a/packages/runtime/src/output/flush.ts b/packages/runtime/src/output/flush.ts index 16be9cbbb..9556da71b 100644 --- a/packages/runtime/src/output/flush.ts +++ b/packages/runtime/src/output/flush.ts @@ -10,14 +10,24 @@ import { writeSync } from "node:fs"; const pending = new Set>(); const tracked = new WeakSet(); -/** Default wait for success / error-render paths. */ +/** Default idle window when a numeric timeout is requested. */ export const DEFAULT_FLUSH_TIMEOUT_MS = 5000; -/** Short wait for Ctrl-C so a stuck write cannot feel like a hang. */ +/** Short hard deadline for Ctrl-C / broken-pipe paths. */ export const INTERRUPT_FLUSH_TIMEOUT_MS = 500; type WriteCallback = (error?: Error | null) => void; +export type FlushOutputOptions = { + /** + * `idle` (default): reset the timer whenever a write completes; time out only + * after `timeoutMs` with no progress. `deadline`: one shot from start. + */ + mode?: "idle" | "deadline"; + /** Skip the plain-text diagnostic when stderr must stay JSON-only. */ + format?: "text" | "json"; +}; + export function trackStreamWrites(stream: NodeJS.WriteStream): void { if (tracked.has(stream)) return; tracked.add(stream); @@ -53,37 +63,91 @@ export function trackStreamWrites(stream: NodeJS.WriteStream): void { }) as typeof stream.write; } +function emitFlushTimeoutWarning(format: "text" | "json" | undefined): void { + // JSON mode must keep stderr as parseable JSON lines; skip the plain warning. + if (format === "json") return; + try { + writeSync( + 2, + "Warning: timed out waiting for stdout/stderr to flush; output may be truncated.\n" + + "警告:等待标准输出刷新超时,输出可能被截断。\n", + ); + } catch { + // stderr may already be broken; ignore. + } +} + /** - * Wait until every tracked write has completed, or `timeoutMs` has passed. - * Returns true when the wait timed out (output may be truncated). Does not - * change process.exitCode; callers keep their existing exit codes. + * Wait until every tracked write has completed. + * + * - `timeoutMs === null`: wait until all pending writes finish (no truncation on + * slow readers such as `| less`). + * - numeric + `mode: "idle"`: reset the timer on each write completion; time out + * only after `timeoutMs` with no progress. + * - numeric + `mode: "deadline"`: hard cap from the start (interrupt paths). + * + * Returns true when the wait timed out. Does not change process.exitCode. */ -export async function flushOutput(timeoutMs = DEFAULT_FLUSH_TIMEOUT_MS): Promise { +export async function flushOutput( + timeoutMs: number | null = DEFAULT_FLUSH_TIMEOUT_MS, + options: FlushOutputOptions = {}, +): Promise { if (pending.size === 0) return false; + + if (timeoutMs === null) { + await Promise.all(pending); + return false; + } + + const mode = options.mode ?? "idle"; const waiting = [...pending]; - let timer: ReturnType | undefined; - const timedOut = await Promise.race([ - Promise.all(waiting).then(() => false), - new Promise((resolve) => { - timer = setTimeout(() => resolve(true), timeoutMs); - timer.unref?.(); - }), - ]); - clearTimeout(timer); - // Drop waiters that never completed so a later flush is not blocked by them. + let timedOut = false; + + if (mode === "deadline") { + let timer: ReturnType | undefined; + timedOut = await Promise.race([ + Promise.all(waiting).then(() => false), + new Promise((resolve) => { + timer = setTimeout(() => resolve(true), timeoutMs); + timer.unref?.(); + }), + ]); + clearTimeout(timer); + } else { + timedOut = await new Promise((resolve) => { + let finished = false; + let timer: ReturnType | undefined; + + const finish = (timedOutResult: boolean) => { + if (finished) return; + finished = true; + clearTimeout(timer); + resolve(timedOutResult); + }; + + const armIdle = () => { + clearTimeout(timer); + timer = setTimeout(() => finish(true), timeoutMs); + timer.unref?.(); + }; + + const onProgress = () => { + if (finished) return; + if (pending.size === 0) { + finish(false); + return; + } + armIdle(); + }; + + for (const item of waiting) void item.then(onProgress); + armIdle(); + }); + } + if (timedOut) { for (const done of waiting) pending.delete(done); - // Observable signal only — do not change exit codes. writeSync bypasses the - // tracked wrapper so this diagnostic is not itself left pending. - try { - writeSync( - 2, - "Warning: timed out waiting for stdout/stderr to flush; output may be truncated.\n" + - "警告:等待标准输出刷新超时,输出可能被截断。\n", - ); - } catch { - // stderr may already be broken; ignore. - } + emitFlushTimeoutWarning(options.format); } return timedOut; } diff --git a/packages/runtime/tests/flush-output.test.ts b/packages/runtime/tests/flush-output.test.ts index 3c9fa41ef..1e229d80b 100644 --- a/packages/runtime/tests/flush-output.test.ts +++ b/packages/runtime/tests/flush-output.test.ts @@ -53,12 +53,53 @@ test("flushOutput waits for tracked write callbacks", async () => { expect(timedOut).toBe(false); }); -test("flushOutput returns true when a callback never fires", async () => { +test("flushOutput with null timeout waits until writes complete", async () => { + vi.useFakeTimers(); + const writable = createDeferredWriteStream(); + writable.stream.write("slow"); + const pending = flushOutput(null); + let settled = false; + void pending.then(() => { + settled = true; + }); + await vi.advanceTimersByTimeAsync(60_000); + expect(settled).toBe(false); + writable.completeNext(); + expect(await pending).toBe(false); + expect(settled).toBe(true); +}); + +test("flushOutput idle mode resets the timer when a write completes", async () => { + vi.useFakeTimers(); + const writable = createDeferredWriteStream(); + writable.stream.write("one"); + writable.stream.write("two"); + + const pending = flushOutput(100, { mode: "idle" }); + await vi.advanceTimersByTimeAsync(90); + writable.completeNext(); + await vi.advanceTimersByTimeAsync(90); + expect(writable.pendingCount()).toBe(1); + writable.completeNext(); + expect(await pending).toBe(false); +}); + +test("flushOutput deadline mode times out from the start", async () => { + vi.useFakeTimers(); + const writable = createDeferredWriteStream({ neverComplete: true }); + writable.stream.write("stuck"); + + const pending = flushOutput(50, { mode: "deadline" }); + await vi.advanceTimersByTimeAsync(50); + expect(await pending).toBe(true); +}); + +test("flushOutput returns true when idle window elapses with no progress", async () => { vi.useFakeTimers(); const writable = createDeferredWriteStream({ neverComplete: true }); writable.stream.write("stuck"); - const pending = flushOutput(50); + const pending = flushOutput(50, { mode: "idle" }); await vi.advanceTimersByTimeAsync(50); expect(await pending).toBe(true); }); diff --git a/packages/runtime/tests/interrupt.test.ts b/packages/runtime/tests/interrupt.test.ts index e446c9878..4a991c431 100644 --- a/packages/runtime/tests/interrupt.test.ts +++ b/packages/runtime/tests/interrupt.test.ts @@ -81,6 +81,13 @@ test("第二次 Ctrl-C 在中断刷新期间立即退出", async () => { try { await runInProcess( async () => { + const flush = await import("../src/output/flush.ts"); + let releaseFlush!: (timedOut: boolean) => void; + const flushGate = new Promise((resolve) => { + releaseFlush = resolve; + }); + // Hold the first interrupt in flush so only the second SIGINT can exit synchronously. + const flushSpy = vi.spyOn(flush, "flushOutput").mockImplementation(() => flushGate); const cli = createCli( { fixture: { @@ -90,11 +97,16 @@ test("第二次 Ctrl-C 在中断刷新期间立即退出", async () => { const exit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never); try { process.emit("SIGINT"); + expect(exit).not.toHaveBeenCalled(); process.emit("SIGINT"); + expect(exit).toHaveBeenCalledTimes(1); + expect(exit).toHaveBeenCalledWith(130); + // Finish the first interrupt chain while exit is still mocked. + releaseFlush(false); await vi.waitFor(() => expect(exit.mock.calls.length).toBeGreaterThanOrEqual(2)); - expect(exit.mock.calls.every((call) => call[0] === 130)).toBe(true); } finally { exit.mockRestore(); + flushSpy.mockRestore(); } }, }, diff --git a/packages/runtime/tests/run-to-exit.e2e.test.ts b/packages/runtime/tests/run-to-exit.e2e.test.ts index cbc06638a..c482c9ea5 100644 --- a/packages/runtime/tests/run-to-exit.e2e.test.ts +++ b/packages/runtime/tests/run-to-exit.e2e.test.ts @@ -1,4 +1,5 @@ -import { execFile, spawnSync } from "node:child_process"; +import { execFile, spawn, spawnSync } from "node:child_process"; +import { once } from "node:events"; import { dirname, join } from "node:path"; import { performance } from "node:perf_hooks"; import { fileURLToPath } from "node:url"; @@ -12,33 +13,34 @@ const bun = process.env.BAILIAN_TEST_BUN ?? "bun"; const hasBun = spawnSync(bun, ["--version"], { stdio: "ignore" }).status === 0; const payloadBytes = 2_000_000; +function harnessArgs(runtime: string, ...args: string[]): { command: string; args: string[] } { + if (runtime === "node") { + return { + command: process.execPath, + args: ["--import", import.meta.resolve("tsx"), harness, ...args], + }; + } + return { command: bun, args: [harness, ...args] }; +} + describe.each(["node", ...(hasBun ? ["bun"] : [])])( "runToExit large piped stdout (%s)", (runtime) => { test("delivers the full JSON payload and exits promptly", async () => { const startedAt = performance.now(); - const { stdout, stderr } = await execFileAsync( - runtime === "node" ? process.execPath : bun, - [ - ...(runtime === "node" ? ["--import", import.meta.resolve("tsx")] : []), - harness, - String(payloadBytes), - "0", - "60000", - ], - { - cwd: runtimeRoot, - // execFile pipes stdout by default; this is the Bun truncation scenario. - timeout: 15_000, - maxBuffer: payloadBytes + 64_000, - env: { - ...process.env, - NODE_NO_WARNINGS: "1", - DO_NOT_TRACK: "1", - NO_UPDATE_NOTIFIER: "1", - }, + const invocation = harnessArgs(runtime, String(payloadBytes), "0", "60000"); + const { stdout, stderr } = await execFileAsync(invocation.command, invocation.args, { + cwd: runtimeRoot, + // execFile pipes stdout by default; this is the Bun truncation scenario. + timeout: 15_000, + maxBuffer: payloadBytes + 64_000, + env: { + ...process.env, + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", }, - ); + }); const elapsedMs = performance.now() - startedAt; expect(stderr).toBe(""); const parsed = JSON.parse(stdout) as { data: string }; @@ -47,26 +49,17 @@ describe.each(["node", ...(hasBun ? ["bun"] : [])])( }); test("preserves a non-zero process.exitCode", async () => { - const error = await execFileAsync( - runtime === "node" ? process.execPath : bun, - [ - ...(runtime === "node" ? ["--import", import.meta.resolve("tsx")] : []), - harness, - "16", - "3", - "0", - ], - { - cwd: runtimeRoot, - timeout: 10_000, - env: { - ...process.env, - NODE_NO_WARNINGS: "1", - DO_NOT_TRACK: "1", - NO_UPDATE_NOTIFIER: "1", - }, + const invocation = harnessArgs(runtime, "16", "3", "0"); + const error = await execFileAsync(invocation.command, invocation.args, { + cwd: runtimeRoot, + timeout: 10_000, + env: { + ...process.env, + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", }, - ).then( + }).then( () => undefined, (failure: NodeJS.ErrnoException & { code?: number; stdout?: string }) => failure, ); @@ -75,5 +68,53 @@ describe.each(["node", ...(hasBun ? ["bun"] : [])])( const parsed = JSON.parse(String(error?.stdout ?? "")) as { data: string }; expect(parsed.data.length).toBe(16); }); + + test("keeps the full payload when the reader is idle for more than 5s", async () => { + const invocation = harnessArgs(runtime, String(payloadBytes), "0", "0"); + // Delay the pipe consumer for >5s so a hard flush timeout would truncate. + const delayedReader = spawn( + process.execPath, + [ + "--input-type=module", + "-e", + ` +import { setTimeout as sleep } from "node:timers/promises"; +await sleep(7000); +let chunks = ""; +for await (const chunk of process.stdin) chunks += chunk; +process.stdout.write(chunks); +`, + ], + { + cwd: runtimeRoot, + stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, NODE_NO_WARNINGS: "1" }, + }, + ); + const producer = spawn(invocation.command, invocation.args, { + cwd: runtimeRoot, + env: { + ...process.env, + NODE_NO_WARNINGS: "1", + DO_NOT_TRACK: "1", + NO_UPDATE_NOTIFIER: "1", + }, + stdio: ["ignore", "pipe", "pipe"], + }); + producer.stdout?.pipe(delayedReader.stdin!); + const stderrChunks: Buffer[] = []; + producer.stderr?.on("data", (chunk: Buffer) => stderrChunks.push(chunk)); + const stdoutChunks: Buffer[] = []; + delayedReader.stdout?.on("data", (chunk: Buffer) => stdoutChunks.push(chunk)); + const [[producerCode], [readerCode]] = await Promise.all([ + once(producer as unknown as NodeJS.EventEmitter, "close") as Promise<[number | null]>, + once(delayedReader as unknown as NodeJS.EventEmitter, "close") as Promise<[number | null]>, + ]); + expect(producerCode).toBe(0); + expect(readerCode).toBe(0); + expect(Buffer.concat(stderrChunks).toString("utf8")).toBe(""); + const parsed = JSON.parse(Buffer.concat(stdoutChunks).toString("utf8")) as { data: string }; + expect(parsed.data.length).toBe(payloadBytes); + }, 25_000); }, ); From 756b0ecabf8893368b7960459a4ccf1d43f39b88 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Thu, 26 Nov 2026 17:23:06 +0800 Subject: [PATCH 3/3] fix(telemetry): await in-flight local JSONL writes in flushTelemetry --- docs/agents/telemetry-change.md | 3 +- packages/core/src/telemetry/sink.ts | 22 ++++++++-- packages/core/tests/telemetry-sink.test.ts | 41 ++++++++++++++++++- .../tests/harness/telemetry-exit-main.ts | 31 +++++++++++--- .../runtime/tests/telemetry-exit.e2e.test.ts | 38 +++++++++++++---- 5 files changed, 117 insertions(+), 18 deletions(-) diff --git a/docs/agents/telemetry-change.md b/docs/agents/telemetry-change.md index 5aca305f9..47ab3ad0f 100644 --- a/docs/agents/telemetry-change.md +++ b/docs/agents/telemetry-change.md @@ -179,7 +179,7 @@ AEM 映射: | `c5` | request ID | | `c6` | `bizFrom` 业务来源(全局 `--biz-from`,归一化标量;专用扁平列,直接筛选/分组) | -远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。 +远端发送是 best-effort,不得阻塞命令或改变退出码。正常退出最多等待 1 秒,SIGINT 最多等待 500 ms。`flushTelemetry` 同时等待在途本地 JSONL 落盘与远端发送,共享同一超时预算;超时只取消远端,本地写不可取消但仍不得无限阻塞退出。 ## 必查清单 @@ -213,6 +213,7 @@ AEM 映射: - [ ] `remoteSink` 从调用到 `remoteSendEvent` 入队之间不得出现 `await`(flush 只排空已入队事件) - [ ] 测试中调用 `remoteSink` 的用例必须使用 `enterIsolatedHome()`,避免写入真实配置目录 - [ ] 遥测发送的 DNS/HTTP/响应体必须受可取消预算控制;flush 超时必须取消在途操作,不能只停止等待,也不能修改全局 DNS/dispatcher 或强制退出宿主 +- [ ] `localSink` 在途写入须登记并由 `flushTelemetry` 等待(即使无远端 in-flight);命令路径仍可 fire-and-forget,不得因本地写失败改退出码;用 `telemetry-sink` 单测覆盖「无远端也落盘」和「本地卡住仍按时返回」,并用 `telemetry-exit` e2e 的 `fast-run-to-exit` 子进程用例守住「远端立即响应 + `runToExit` 强制退出仍落盘」 - [ ] 退出生命周期变更保留真实子进程回归:挂起响应头/响应体、DNS 预查询和关闭遥测;检查实际退出及进程仍存活时的连接释放,不以 flush Promise 返回代替验收 - [ ] 错误字段不得额外拼接 token、请求体、prompt 或本地路径 diff --git a/packages/core/src/telemetry/sink.ts b/packages/core/src/telemetry/sink.ts index 9735627b1..06e46338b 100644 --- a/packages/core/src/telemetry/sink.ts +++ b/packages/core/src/telemetry/sink.ts @@ -31,6 +31,8 @@ interface PendingSend { promise: Promise; } const inflightSends = new Set(); +/** In-flight local JSONL writes; flush must wait so process.exit cannot drop them. */ +const inflightLocalWrites = new Set>(); let remoteClient: any = undefined; let remoteInitialized = false; @@ -83,11 +85,12 @@ function initRemote(): void { } /** - * Best-effort wait for all in-flight telemetry sends. + * Best-effort wait for in-flight local JSONL writes and remote sends. * * 1. Call `_sendAll` to drain the tracker's debounce queue so events still in * the 500ms merge window are pushed to the network immediately. - * 2. Wait for sends within the budget; on timeout, cancel DNS/HTTP/body work. + * 2. Wait for local writes and remote sends within the budget; on timeout, + * cancel DNS/HTTP/body work (local writes are not cancellable). * * Telemetry must never block the CLI: callers should pass a short timeout * (e.g. 1000ms) and always race against it. Errors and timeouts are swallowed. @@ -106,9 +109,11 @@ export async function flushTelemetry(timeoutMs = 1000): Promise { // flush itself must never throw } } - if (inflightSends.size === 0) return; + const localWrites = [...inflightLocalWrites]; + const remotePromises = [...inflightSends].map((pending) => pending.promise); + if (localWrites.length === 0 && remotePromises.length === 0) return; await Promise.race([ - Promise.allSettled([...inflightSends].map((pending) => pending.promise)), + Promise.allSettled([...localWrites, ...remotePromises]), new Promise((resolve) => { deadline = setTimeout(() => { for (const pending of inflightSends) pending.controller.abort(); @@ -125,6 +130,15 @@ export async function flushTelemetry(timeoutMs = 1000): Promise { } export async function localSink(event: TrackingEvent | FirstInstallEvent): Promise { + let pending!: Promise; + pending = writeLocalEvent(event).finally(() => { + inflightLocalWrites.delete(pending); + }); + inflightLocalWrites.add(pending); + await pending; +} + +async function writeLocalEvent(event: TrackingEvent | FirstInstallEvent): Promise { try { await ensureConfigDir(); const path = TELEMETRY_FILE(); diff --git a/packages/core/tests/telemetry-sink.test.ts b/packages/core/tests/telemetry-sink.test.ts index 77dbc8ed8..a0ec2df8b 100644 --- a/packages/core/tests/telemetry-sink.test.ts +++ b/packages/core/tests/telemetry-sink.test.ts @@ -1,4 +1,5 @@ -import { existsSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; import type { TrackingEvent } from "../src/telemetry/event.ts"; import { enterIsolatedHome, type IsolatedHomeHandle } from "./helpers/isolation.ts"; @@ -39,6 +40,7 @@ afterEach(() => { iso.restore(); vi.clearAllTimers(); vi.useRealTimers(); + vi.doUnmock("../src/config/paths.ts"); vi.resetModules(); fixture.signals = []; fixture.complete = false; @@ -100,3 +102,40 @@ test("importing sink without reporting does not create the uid file", async () = const { getUidPath } = await import("../src/telemetry/uid.ts"); expect(existsSync(getUidPath())).toBe(false); }); + +test("flush waits for in-flight local writes even when no remote send is pending", async () => { + const { localSink, flushTelemetry } = await import("../src/telemetry/sink.ts"); + // Fire-and-forget as trackCommandExecution does; flush must still persist the line. + void localSink({ command: "local-only" } as TrackingEvent); + await flushTelemetry(1000); + const path = join(iso.configDir, "telemetry.jsonl"); + expect(existsSync(path)).toBe(true); + expect(readFileSync(path, "utf8")).toContain('"command":"local-only"'); +}); + +test("flush returns within its budget when a local write stalls", async () => { + vi.useFakeTimers(); + vi.doMock("../src/config/paths.ts", async () => { + const actual = + await vi.importActual("../src/config/paths.ts"); + return { + ...actual, + ensureConfigDir: () => new Promise(() => {}), + }; + }); + const { localSink, flushTelemetry } = await import("../src/telemetry/sink.ts"); + void localSink({ command: "stalled-local" } as TrackingEvent); + const pending = flushTelemetry(50); + await vi.advanceTimersByTimeAsync(49); + // Still within budget: flush must not have resolved by hanging on local I/O alone. + let settled = false; + void pending.then(() => { + settled = true; + }); + await Promise.resolve(); + expect(settled).toBe(false); + await vi.advanceTimersByTimeAsync(1); + await pending; + expect(settled).toBe(true); + expect(vi.getTimerCount()).toBe(0); +}); diff --git a/packages/runtime/tests/harness/telemetry-exit-main.ts b/packages/runtime/tests/harness/telemetry-exit-main.ts index ff3a8b724..2613aba59 100644 --- a/packages/runtime/tests/harness/telemetry-exit-main.ts +++ b/packages/runtime/tests/harness/telemetry-exit-main.ts @@ -4,8 +4,12 @@ import { performance } from "node:perf_hooks"; import { httpTransport } from "../../../core/src/client/transport.ts"; const [mode, origin, dnsServer, tlsOrigin] = process.argv.slice(2); +// "fast-run-to-exit" reuses the immediate-response endpoint but leaves through +// runToExit's forced process.exit instead of the natural event-loop exit. +const forceExit = mode === "fast-run-to-exit"; +const remoteMode = forceExit ? "fast" : mode; // Detect the old independent DNS preflight without touching system DNS. -if (mode === "dns") { +if (remoteMode === "dns") { const resolver = new dns.Resolver({ timeout: 30_000, tries: 1 }); resolver.setServers([dnsServer!]); dns.resolve = resolver.resolve.bind(resolver); @@ -22,8 +26,18 @@ const redirectTelemetry = (fetcher: typeof fetch): typeof fetch => if (!url.startsWith("https://gm.mmstat.com/")) { throw new Error("Unexpected telemetry target"); } + if (forceExit) { + // Synthetic microtask-resolved response: the remote send drains as fast + // as possible without any socket round-trip, maximizing the race between + // "flush sees nothing pending" and the still-queued local JSONL write. + // Without this, loopback latency lets the old fire-and-forget write win. + return Promise.resolve(new Response(null, { status: 204 })); + } return fetcher( - new URL(mode === "dns" ? "/fast" : `/${mode}`, mode?.startsWith("tls") ? tlsOrigin : origin), + new URL( + remoteMode === "dns" ? "/fast" : `/${remoteMode}`, + remoteMode?.startsWith("tls") ? tlsOrigin : origin, + ), options, ); }) as typeof fetch; @@ -36,9 +50,9 @@ if (process.versions.bun) { transport.fetch = redirectTelemetry(transport.fetch); } -const { createCli } = await import("../../src/create-cli.ts"); +const { createCli, runToExit } = await import("../../src/create-cli.ts"); let outputCompletedAt = 0; -await createCli( +const cli = createCli( { probe: { description: "Telemetry exit fixture", @@ -55,7 +69,14 @@ await createCli( clientName: "telemetry-fixture", npmPackage: "telemetry-fixture", }, -).run(["probe", "--output", "json"]); +); +if (forceExit) { + // runToExit force-exits once tracked stdout/stderr flush; the in-flight + // local telemetry write must survive that exit. + await runToExit(cli, ["probe", "--output", "json"]); + throw new Error("runToExit returned without exiting the process"); +} +await cli.run(["probe", "--output", "json"]); const outputToRunMs = performance.now() - outputCompletedAt; // Inspect closure while this process is still alive: exit must not hide a leak. diff --git a/packages/runtime/tests/telemetry-exit.e2e.test.ts b/packages/runtime/tests/telemetry-exit.e2e.test.ts index 90d2326e3..db918585c 100644 --- a/packages/runtime/tests/telemetry-exit.e2e.test.ts +++ b/packages/runtime/tests/telemetry-exit.e2e.test.ts @@ -3,7 +3,7 @@ import { createSocket } from "node:dgram"; import type { EventEmitter } from "node:events"; import { createServer, type Server } from "node:http"; import { createServer as createTcpServer, type Socket } from "node:net"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { performance } from "node:perf_hooks"; @@ -93,6 +93,7 @@ describe.each(["node", ...(hasBun ? ["bun"] : [])])( "dns", "tls", "fast", + "fast-run-to-exit", "disabled", "do-not-track", ...(runtime === "node" ? ["tls-no-proxy"] : []), @@ -105,6 +106,7 @@ describe.each(["node", ...(hasBun ? ["bun"] : [])])( join(directory, "config.json"), JSON.stringify({ language: "en-US", telemetry: mode !== "disabled" }), ); + const forceExit = mode === "fast-run-to-exit"; const disabled = mode === "disabled" || mode === "do-not-track"; const isolated = buildIsolatedCliEnv({ overrides: { @@ -152,18 +154,40 @@ describe.each(["node", ...(hasBun ? ["bun"] : [])])( const { stdout, stderr } = await execution; const exitedAt = performance.now(); expect(JSON.parse(stdout)).toEqual({ ok: true }); - const { outputToRunMs, ...connectionStatus } = JSON.parse(stderr); - expect(connectionStatus).toEqual({ requests: disabled ? 0 : 1, closed: !disabled }); - if (["fast", "headers", "body"].includes(mode)) { - expect(outputToRunMs).toBeGreaterThanOrEqual(0); - expect(outputToRunMs, "output completion to run() return").toBeLessThan(3_000); + if (forceExit) { + // runToExit already called process.exit; judge from the parent's + // evidence that nothing was dropped and nothing lingered. + // The synthetic immediate response never touches the fixture server, + // so the remote send settles within microtasks — the worst-case race + // for the forced exit to drop the pending local JSONL write. + expect(requests).toHaveLength(0); + const telemetryPath = join(directory, "telemetry.jsonl"); + expect(existsSync(telemetryPath), "runToExit dropped the in-flight local write").toBe( + true, + ); + const events = readFileSync(telemetryPath, "utf8") + .split("\n") + .filter((line) => line.trim() !== "") + .map((line) => JSON.parse(line) as { command?: string }); + expect(events.some((entry) => entry.command === "probe")).toBe(true); expect(outputCompletedAt).toBeDefined(); expect(exitedAt - outputCompletedAt!, "output completion to process exit").toBeLessThan( 3_000, ); + } else { + const { outputToRunMs, ...connectionStatus } = JSON.parse(stderr); + expect(connectionStatus).toEqual({ requests: disabled ? 0 : 1, closed: !disabled }); + if (["fast", "headers", "body"].includes(mode)) { + expect(outputToRunMs).toBeGreaterThanOrEqual(0); + expect(outputToRunMs, "output completion to run() return").toBeLessThan(3_000); + expect(outputCompletedAt).toBeDefined(); + expect(exitedAt - outputCompletedAt!, "output completion to process exit").toBeLessThan( + 3_000, + ); + } } expect(dnsQueries).toBe(0); - if (!disabled && !mode.startsWith("tls")) { + if (!disabled && !forceExit && !mode.startsWith("tls")) { expect(requests[0]?.method).toBe("POST"); const body = JSON.parse(requests[0]!.body) as { gokey: string; gmkey: string }; expect(body.gmkey).toBe("EXP");