Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(process): retain diagnostics through bounded output finalization

morluto701695139490
diff --git a/docs/testing.md b/docs/testing.md
index 133a39234..6fe29071b 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -216,6 +216,12 @@ controlled production seam for interleavings that cannot be reproduced reliably.
| Cleanup fails after success or primary failure | Public output retains the completed observation or primary diagnostic, remaining resources, and owner recovery action. Restore the denied resource and verify the owning cleanup retry. |
| Target exits without an acknowledgement, or transport disappears while it stays alive | Positive owned exit proof resolves target lifetime; other resources still need cleanup. Lost transport alone does not prove exit. Verify unrelated/attached targets survive and same-connection recovery works when supported. |
+Shared process-supervision controls separate leader exit from output closure.
+Cover output during held or failed cleanup, bounded retention and drain timeout,
+retry, and borrowed stream authority. The POSIX inherited-stderr control uses a
+separate pipe as a release barrier after leader exit; it does not establish
+native Windows Job Object behavior.
+
Synchronize cancellation with the finalization boundary being tested; a fixed
delay after dispatch does not establish that phase. Use markers, barriers, or
owned cleanup seams while preserving real cleanup where feasible. Check server
diff --git a/docs/tool-design.md b/docs/tool-design.md
index ba3632dc2..7024c1d8d 100644
--- a/docs/tool-design.md
+++ b/docs/tool-design.md
@@ -79,6 +79,13 @@ providers need not expose identical state machines.
and resource release separate. A valid process handle, successful launcher,
or selected target establishes only its own fact. Publish available identity
and exit observations even when launch fails; retain unknown ownership.
+- Process exit does not establish output closure. The shared process supervisor
+ retains at most 64 KiB of additional diagnostics from owned stop entry,
+ including pending cleanup and retries, and drains for up to one second after
+ verified stop. It marks output incomplete when closure cannot be
+ observed and releases owned event-loop references without changing the proven
+ process-cleanup outcome. Failed process cleanup retains capture for retry;
+ borrowed processes and streams retain their own lifetime and reference state.
- Authenticate and capture identity through the same boundary on initial and
recovery handshakes. Bound abandoned unauthenticated listeners where the
protocol permits it; that deadline must not expire authenticated idle sessions
diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.ts
index c74b604b5..67ed3a97d 100644
--- a/src/process/ProviderProcess.ts
+++ b/src/process/ProviderProcess.ts
@@ -17,6 +17,8 @@ import {
const DEFAULT_TERMINATION_GRACE_MS = 250;
const DEFAULT_KILL_GRACE_MS = 1_000;
+const OUTPUT_CLOSE_GRACE_MS = 1_000;
+const MAX_LATE_OUTPUT_BYTES = 64 * 1024;
/** Spawn coordinates shared by owned, long-lived provider processes. */
export interface OwnedProviderProcessSpawnOptions {
@@ -303,6 +305,7 @@ export class ProviderProcessSupervisor {
readonly #exit = deferred<ProviderProcessExitObservation>();
readonly #outputClose = deferred<void>();
#outputClosed = false;
+ #outputIncomplete = false;
#stdoutObservedBytes = 0;
#stderrObservedBytes = 0;
#diagnosticTruncated = false;
@@ -373,7 +376,8 @@ export class ProviderProcessSupervisor {
/** Latest retained output and exit observation, with explicit configured truncation. */
snapshot(): ProviderProcessSnapshot {
- const outputIncomplete = this.launch.process.outputIncomplete === true;
+ const outputIncomplete =
+ this.#outputIncomplete || this.launch.process.outputIncomplete === true;
return {
...(this.#diagnosticTruncated || outputIncomplete
? { diagnosticTruncated: true }
@@ -436,6 +440,7 @@ export class ProviderProcessSupervisor {
const incomplete =
stdout.complete === false ||
stderr.complete === false ||
+ this.#outputIncomplete ||
this.launch.process.outputIncomplete === true;
return {
snapshot: {
@@ -530,6 +535,8 @@ export class ProviderProcessSupervisor {
/** Detach capture and process listeners after an adapter releases ownership. */
dispose(): void {
if (this.#disposed) return;
+ // Releasing capture before close cannot establish a complete output history.
+ if (!this.#outputClosed) this.#outputIncomplete = true;
this.#disposed = true;
this.launch.process.stdout?.off("data", this.#onStdout);
this.launch.process.stdout?.off("error", this.#onStdoutError);
@@ -561,11 +568,23 @@ export class ProviderProcessSupervisor {
async #stop(
options: ProviderProcessStopOptions,
): Promise<ProviderProcessStopResult> {
- this.ref();
+ if (this.launch.ownsProcessLifetime) {
+ this.ref();
+ // Bound retention throughout termination and failed cleanup, including retries.
+ this.limitAdditionalOutputBytes(MAX_LATE_OUTPUT_BYTES);
+ }
let completed = false;
try {
const result = await this.#stopWithin(options);
completed = result.status !== "incomplete";
+ if (completed && result.status !== "not-owned" && !this.#outputClosed) {
+ // Exit proves process lifetime only. Bound final retention while draining
+ // inherited pipes; a lost output tail does not revoke verified cleanup.
+ if (!(await this.waitForOutputClose(OUTPUT_CLOSE_GRACE_MS))) {
+ this.#outputIncomplete = true;
+ this.unref();
+ }
+ }
if (!completed) this.unref();
return result;
} finally {
@@ -661,6 +680,7 @@ export class ProviderProcessSupervisor {
}
#recordStreamError(stream: "stdout" | "stderr", cause: Error): void {
+ this.#outputIncomplete = true;
this.#options.onDiagnostic?.({
type: "error",
message: `${stream} stream failed: ${cause.message}`,
diff --git a/src/process/ProviderProcessOutput.test.ts b/src/process/ProviderProcessOutput.test.ts
index c11b93ce9..a7bb6eb19 100644
--- a/src/process/ProviderProcessOutput.test.ts
+++ b/src/process/ProviderProcessOutput.test.ts
@@ -4,6 +4,218 @@ import { expect, it, vi } from "vitest";
import { ProviderProcessSupervisor } from "./ProviderProcess.js";
import { redactCapturedTransportCredential } from "./ProviderDiagnosticRedaction.js";
+it("retains final stderr between verified exit and output close during stop", async () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ let cleanupStarted: () => void = () => {};
+ const started = new Promise<void>((resolve) => {
+ cleanupStarted = resolve;
+ });
+ const owner = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: true,
+ cleanup: async () => {
+ producer.emit("exit", 2, null);
+ cleanupStarted();
+ return { cleaned: true, signaled: false };
+ },
+ });
+ const stopped = owner.stop();
+ expect(owner.stop()).toBe(stopped);
+ await started;
+ // Let cleanup observe exit before delivering the separately acknowledged output.
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ producer.stderr.end("final launcher diagnostic");
+ producer.stdout.end();
+ producer.emit("close", 2, null);
+ await expect(stopped).resolves.toEqual({ status: "verified-cleanup" });
+ expect(owner.snapshot()).toMatchObject({
+ stderr: { text: "final launcher diagnostic" },
+ exitCode: 2,
+ });
+ expect(await owner.waitForOutputClose(0)).toBe(true);
+});
+
+it("bounds late output retention and drain without changing verified cleanup", async () => {
+ vi.useFakeTimers();
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: Object.assign(new PassThrough(), { unref: vi.fn() }),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ const owner = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: true,
+ cleanup: async () => {
+ producer.emit("exit", 0, null);
+ return { cleaned: true, signaled: false };
+ },
+ });
+ const checkpoint = owner.checkpointOutput();
+ try {
+ const stopped = owner.stop();
+ await vi.advanceTimersByTimeAsync(0);
+ producer.stderr.write("x".repeat(65537));
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(stopped).resolves.toEqual({ status: "verified-cleanup" });
+ expect(owner.snapshot()).toMatchObject({
+ stderr: { bytes: 65536, observedBytes: 65537 },
+ outputIncomplete: true,
+ diagnosticTruncated: true,
+ });
+ expect(owner.snapshotOutputSince(checkpoint).complete).toBe(false);
+ expect(producer.stderr.destroyed).toBe(false);
+ expect(producer.stderr.unref).toHaveBeenCalledOnce();
+ producer.emit("close", 0, null);
+ expect(owner.snapshot().outputIncomplete).toBe(true);
+ } finally {
+ owner.dispose();
+ producer.stdout.destroy();
+ producer.stderr.destroy();
+ vi.useRealTimers();
+ }
+});
+
+it("retries process cleanup with capture attached until output closes", async () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => false),
+ });
+ let fails = true;
+ const owner = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: true,
+ cleanup: async () => {
+ if (fails) return { cleaned: false, reason: "identity unavailable" };
+ producer.emit("exit", 0, null);
+ return { cleaned: true, signaled: false };
+ },
+ });
+ await expect(owner.stop()).resolves.toMatchObject({ status: "incomplete" });
+ producer.stderr.write("retained during retry");
+ fails = false;
+ const retried = owner.stop();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ producer.stderr.end(" and final tail");
+ producer.stdout.end();
+ producer.emit("close", 0, null);
+ await expect(retried).resolves.toEqual({ status: "verified-cleanup" });
+ expect(owner.snapshot().stderr.text).toBe(
+ "retained during retry and final tail",
+ );
+});
+
+it("bounds additional retention during held cleanup and across retries", async () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ let release: () => void = () => {};
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let fails = true;
+ const owner = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: true,
+ cleanup: async () => {
+ if (fails) {
+ await held;
+ return { cleaned: false, reason: "held ownership inspection failed" };
+ }
+ producer.stdout.end();
+ producer.stderr.end();
+ producer.emit("exit", 0, null);
+ producer.emit("close", 0, null);
+ return { cleaned: true, signaled: false };
+ },
+ });
+ const stopped = owner.stop();
+ producer.stderr.write("x".repeat(65537));
+ expect(owner.snapshot().stderr).toMatchObject({
+ bytes: 65536,
+ observedBytes: 65537,
+ });
+ release();
+ await expect(stopped).resolves.toMatchObject({ status: "incomplete" });
+ producer.stderr.write("tail");
+ fails = false;
+ await expect(owner.stop()).resolves.toEqual({ status: "verified-cleanup" });
+ expect(owner.snapshot()).toMatchObject({
+ stderr: { bytes: 65536, observedBytes: 65541 },
+ diagnosticTruncated: true,
+ });
+});
+
+it("releases borrowed capture as incomplete without killing or destroying streams", async () => {
+ const borrowedProcess = Object.assign(new EventEmitter(), {
+ stdout: Object.assign(new PassThrough(), { ref: vi.fn(), unref: vi.fn() }),
+ stderr: Object.assign(new PassThrough(), { ref: vi.fn(), unref: vi.fn() }),
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => false),
+ ref: vi.fn(),
+ unref: vi.fn(),
+ });
+ const borrowed = new ProviderProcessSupervisor({
+ process: borrowedProcess,
+ ownsProcessLifetime: false,
+ });
+ await expect(borrowed.stop()).resolves.toEqual({ status: "not-owned" });
+ expect(borrowedProcess.kill).not.toHaveBeenCalled();
+ for (const handle of [
+ borrowedProcess,
+ borrowedProcess.stdout,
+ borrowedProcess.stderr,
+ ]) {
+ expect(handle.ref).not.toHaveBeenCalled();
+ expect(handle.unref).not.toHaveBeenCalled();
+ }
+ expect(borrowedProcess.stderr.destroyed).toBe(false);
+ expect(borrowed.snapshot().outputIncomplete).toBe(true);
+ borrowedProcess.stdout.destroy();
+ borrowedProcess.stderr.destroy();
+});
+
+it("retains stream failure incompleteness even after output close", async () => {
+ const producer = Object.assign(new EventEmitter(), {
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ signalCode: null,
+ kill: () => false,
+ });
+ const owner = new ProviderProcessSupervisor({
+ process: producer,
+ ownsProcessLifetime: false,
+ });
+ const checkpoint = owner.checkpointOutput();
+ producer.stderr.emit("error", new Error("read failure"));
+ producer.emit("close", 1, null);
+ expect(await owner.waitForOutputClose(0)).toBe(true);
+ expect(owner.snapshot()).toMatchObject({
+ outputIncomplete: true,
+ diagnosticTruncated: true,
+ });
+ expect(owner.snapshotOutputSince(checkpoint).complete).toBe(false);
+ owner.dispose();
+ producer.stdout.destroy();
+ producer.stderr.destroy();
+});
+
it("exit does not establish complete output when a producer closes its streams later", async () => {
const producer = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
diff --git a/tests/boundary/process/providerProcessOutput.test.ts b/tests/boundary/process/providerProcessOutput.test.ts
index ae4c41882..42f3f6098 100644
--- a/tests/boundary/process/providerProcessOutput.test.ts
+++ b/tests/boundary/process/providerProcessOutput.test.ts
@@ -1,5 +1,6 @@
import { expect, it, vi } from "vitest";
import type { Socket } from "node:net";
+import type { Writable } from "node:stream";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import {
@@ -11,6 +12,36 @@ import {
stopProviderProcessFixture,
} from "../../fixtures/providerProcess.js";
+it.skipIf(process.platform === "win32")(
+ "drains inherited stderr after real leader exit before output close",
+ async () => {
+ const child = spawnProviderProcessFixture("late-stderr");
+ const owner = new ProviderProcessSupervisor({
+ process: child,
+ ownsProcessLifetime: true,
+ });
+ const release = child.stdio[3] as Writable;
+ try {
+ expect(await owner.waitForExit(2000)).toBe(true);
+ expect(await owner.waitForOutputClose(0)).toBe(false);
+ const stopped = owner.stop();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ release.end();
+ await expect(stopped).resolves.toEqual({ status: "already-exited" });
+ expect(owner.snapshot().stderr).toMatchObject({
+ text: "final-tail",
+ observedBytes: 10,
+ });
+ expect(owner.snapshot().outputIncomplete).toBeUndefined();
+ expect(await owner.waitForOutputClose(0)).toBe(true);
+ } finally {
+ release.end();
+ await owner.stop();
+ await stopProviderProcessFixture(child);
+ }
+ },
+);
+
it("unreferences inherited output streams without closing them", async () => {
const child = spawnProviderProcessFixture("stubborn");
const supervisor = new ProviderProcessSupervisor({
diff --git a/tests/fixtures/providerProcess.mjs b/tests/fixtures/providerProcess.mjs
index 91f183bb1..964bec7ea 100644
--- a/tests/fixtures/providerProcess.mjs
+++ b/tests/fixtures/providerProcess.mjs
@@ -23,6 +23,23 @@ const write = (stream, data) =>
});
switch (mode) {
+ case "late-stderr": {
+ // Keep stderr open after leader exit. FD3 is the test's explicit release barrier.
+ const writer = spawn(
+ process.execPath,
+ [
+ "-e",
+ "const deadline=setTimeout(()=>process.exit(64),5000); require('node:fs').readFile(3,error=>{clearTimeout(deadline);if(error)process.exitCode=65;else process.stderr.write('final-tail');});",
+ ],
+ { stdio: ["ignore", "ignore", process.stderr, 3] },
+ );
+ await new Promise((resolve, reject) => {
+ writer.once("spawn", resolve);
+ writer.once("error", reject);
+ });
+ writer.unref();
+ break;
+ }
case "burst": {
const bytes = Number(value);
await Promise.all([
diff --git a/tests/fixtures/providerProcess.ts b/tests/fixtures/providerProcess.ts
index ab7f5f74b..6ec569f41 100644
--- a/tests/fixtures/providerProcess.ts
+++ b/tests/fixtures/providerProcess.ts
@@ -15,13 +15,19 @@ export const spawnProviderProcessFixture = (
| "graceful"
| "invalid-utf8"
| "valid-multibyte"
+ | "late-stderr"
| "stubborn",
value?: number,
): ChildProcess =>
spawn(
process.execPath,
[fixturePath, mode, ...(value === undefined ? [] : [String(value)])],
- { stdio: ["ignore", "pipe", "pipe"] },
+ {
+ stdio:
+ mode === "late-stderr"
+ ? ["ignore", "pipe", "pipe", "pipe"]
+ : ["ignore", "pipe", "pipe"],
+ },
);
/** Wait until a long-lived fixture has installed its signal behavior. */