mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(process): wake OwnedCommand on output close, lazily materialize diagnostic snapshots, and bound tail copies (#13261)
* perf(process): wake OwnedCommand on output close, lazily materialize diagnostic snapshots, and bound tail copies * fix(process): capture event-time bytes in diagnostic snapshots and make wrap test independent
This commit is contained in:
1 parent
9e379c9589
commit
b795aee553
6 files changed
+638
-84
No files matched your search
@@ -94,3 +94,61 @@ describe("bounded output excerpts", () => {
|
||||
expect(excerpt.text).toBe("�A … [output omitted] … B�");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bounded output ring buffer", () => {
|
||||
it("matches head and tail bytes across repeated small writes wrapping the ring buffer", () => {
|
||||
const limit = 19;
|
||||
const headLimit = Math.ceil(limit / 2);
|
||||
const tailLimit = limit - headLimit;
|
||||
const excerpt = new BoundedOutputExcerpt(limit);
|
||||
const chunks = Array.from({ length: 120 }, (_, index) =>
|
||||
Buffer.from(index % 7 === 0 ? `🙂${index}` : `_${index}_`),
|
||||
);
|
||||
for (const chunk of chunks) excerpt.append(chunk);
|
||||
const full = Buffer.concat(chunks);
|
||||
const expectedHead = full.subarray(0, headLimit).toString("utf8");
|
||||
const expectedTail = full
|
||||
.subarray(full.length - tailLimit)
|
||||
.toString("utf8");
|
||||
expect(expectedHead).toBe("🙂0_1__2");
|
||||
expect(expectedTail).toBe("8_🙂119");
|
||||
expect(excerpt.truncated).toBe(true);
|
||||
expect(full.length).toBeGreaterThan(headLimit + tailLimit);
|
||||
expect(excerpt.text).toBe(
|
||||
`${expectedHead} … [output omitted] … ${expectedTail}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("drops split UTF-8 bytes at a wrapped ring tail boundary", () => {
|
||||
const limit = 13;
|
||||
const headLimit = Math.ceil(limit / 2);
|
||||
const tailLimit = limit - headLimit;
|
||||
const excerpt = new BoundedOutputExcerpt(limit);
|
||||
const chunks = Array.from({ length: 120 }, (_, index) =>
|
||||
Buffer.from(index % 7 === 0 ? `🙂${index}` : `_${index}_`),
|
||||
);
|
||||
for (const chunk of chunks) excerpt.append(chunk);
|
||||
const full = Buffer.concat(chunks);
|
||||
const rawHead = full.subarray(0, headLimit);
|
||||
const rawTail = full.subarray(full.length - tailLimit);
|
||||
expect(rawHead.toString("utf8")).toBe("🙂0_1");
|
||||
// The 6-byte tail starts inside the 4-byte "🙂" before "119".
|
||||
expect([...rawTail.subarray(0, 3)]).toEqual([0x9f, 0x99, 0x82]);
|
||||
expect(rawTail.subarray(3).toString("utf8")).toBe("119");
|
||||
expect(excerpt.truncated).toBe(true);
|
||||
expect(excerpt.text).toBe("🙂0_1 … [output omitted] … 119");
|
||||
});
|
||||
|
||||
it("handles zero budget and oversized tail replacement after partial writes", () => {
|
||||
const empty = new BoundedOutputExcerpt(0);
|
||||
empty.append(Buffer.from("abcdef"));
|
||||
expect(empty.truncated).toBe(true);
|
||||
expect(empty.text).toBe(" … [output omitted] … ");
|
||||
|
||||
const replaced = new BoundedOutputExcerpt(10);
|
||||
replaced.append(Buffer.from("1234567"));
|
||||
replaced.append(Buffer.from("ABCDEFGHIJK"));
|
||||
expect(replaced.truncated).toBe(true);
|
||||
expect(replaced.text).toBe("12345 … [output omitted] … GHIJK");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,12 @@
|
||||
const EMPTY_BUFFER = Buffer.alloc(0);
|
||||
|
||||
/** Byte-bounded head and tail diagnostics, decoded after stream chunks are joined. */
|
||||
export class BoundedOutputExcerpt {
|
||||
#head: Buffer = Buffer.alloc(0);
|
||||
#tail: Buffer = Buffer.alloc(0);
|
||||
readonly #headChunks: Buffer[] = [];
|
||||
#headBytes = 0;
|
||||
#tailRing: Buffer | undefined;
|
||||
#tailStart = 0;
|
||||
#tailLength = 0;
|
||||
// not-an-allowance: observed byte total, compared with the limit only to report truncation.
|
||||
#total = 0;
|
||||
readonly #headLimit: number;
|
||||
@@ -16,23 +21,67 @@ export class BoundedOutputExcerpt {
|
||||
this.#total += chunk.byteLength;
|
||||
const headCount = Math.min(
|
||||
chunk.byteLength,
|
||||
this.#headLimit - this.#head.byteLength,
|
||||
this.#headLimit - this.#headBytes,
|
||||
);
|
||||
if (headCount > 0)
|
||||
this.#head = Buffer.concat([this.#head, chunk.subarray(0, headCount)]);
|
||||
const rest = chunk.subarray(headCount);
|
||||
if (rest.byteLength > 0 && this.#tailLimit > 0) {
|
||||
const retained = rest.subarray(-this.#tailLimit);
|
||||
this.#tail = Buffer.concat([
|
||||
this.#tail.subarray(
|
||||
Math.max(
|
||||
0,
|
||||
this.#tail.byteLength + retained.byteLength - this.#tailLimit,
|
||||
),
|
||||
),
|
||||
retained,
|
||||
]);
|
||||
if (headCount > 0) {
|
||||
this.#headChunks.push(Buffer.from(chunk.subarray(0, headCount)));
|
||||
this.#headBytes += headCount;
|
||||
}
|
||||
const rest = chunk.subarray(headCount);
|
||||
if (rest.byteLength > 0 && this.#tailLimit > 0) this.#appendTail(rest);
|
||||
}
|
||||
|
||||
#appendTail(rest: Buffer): void {
|
||||
const retained =
|
||||
rest.byteLength > this.#tailLimit
|
||||
? rest.subarray(rest.byteLength - this.#tailLimit)
|
||||
: rest;
|
||||
const ring = (this.#tailRing ??= Buffer.allocUnsafe(this.#tailLimit));
|
||||
if (retained.byteLength === this.#tailLimit) {
|
||||
retained.copy(ring, 0);
|
||||
this.#tailStart = 0;
|
||||
this.#tailLength = this.#tailLimit;
|
||||
return;
|
||||
}
|
||||
const writeAt = (this.#tailStart + this.#tailLength) % this.#tailLimit;
|
||||
const firstWrite = Math.min(retained.byteLength, this.#tailLimit - writeAt);
|
||||
retained.copy(ring, writeAt, 0, firstWrite);
|
||||
if (firstWrite < retained.byteLength) retained.copy(ring, 0, firstWrite);
|
||||
const total = this.#tailLength + retained.byteLength;
|
||||
if (total <= this.#tailLimit) {
|
||||
this.#tailLength = total;
|
||||
return;
|
||||
}
|
||||
this.#tailStart =
|
||||
(this.#tailStart + (total - this.#tailLimit)) % this.#tailLimit;
|
||||
this.#tailLength = this.#tailLimit;
|
||||
}
|
||||
|
||||
#headBuffer(): Buffer {
|
||||
if (this.#headBytes === 0) return EMPTY_BUFFER;
|
||||
return this.#headChunks.length === 1
|
||||
? this.#headChunks[0]!
|
||||
: Buffer.concat(this.#headChunks, this.#headBytes);
|
||||
}
|
||||
|
||||
#tailBuffer(): Buffer {
|
||||
if (this.#tailRing === undefined || this.#tailLength === 0)
|
||||
return EMPTY_BUFFER;
|
||||
if (this.#tailStart === 0)
|
||||
return this.#tailRing.subarray(0, this.#tailLength);
|
||||
const firstLen = Math.min(
|
||||
this.#tailLength,
|
||||
this.#tailLimit - this.#tailStart,
|
||||
);
|
||||
if (firstLen === this.#tailLength)
|
||||
return this.#tailRing.subarray(
|
||||
this.#tailStart,
|
||||
this.#tailStart + firstLen,
|
||||
);
|
||||
const joined = Buffer.allocUnsafe(this.#tailLength);
|
||||
this.#tailRing.copy(joined, 0, this.#tailStart, this.#tailStart + firstLen);
|
||||
this.#tailRing.copy(joined, firstLen, 0, this.#tailLength - firstLen);
|
||||
return joined;
|
||||
}
|
||||
|
||||
get truncated(): boolean {
|
||||
@@ -40,20 +89,22 @@ export class BoundedOutputExcerpt {
|
||||
}
|
||||
|
||||
get text(): string {
|
||||
const headBytes = this.#headBuffer();
|
||||
const tailBytes = this.#tailBuffer();
|
||||
if (!this.truncated)
|
||||
return Buffer.concat([this.#head, this.#tail]).toString("utf8");
|
||||
return Buffer.concat([headBytes, tailBytes]).toString("utf8");
|
||||
|
||||
const head = decodeTruncatedHead(this.#head);
|
||||
const head = decodeTruncatedHead(headBytes);
|
||||
let tailStart = 0;
|
||||
while (
|
||||
tailStart < this.#tail.length &&
|
||||
(this.#tail[tailStart]! & 0xc0) === 0x80
|
||||
tailStart < tailBytes.length &&
|
||||
(tailBytes[tailStart]! & 0xc0) === 0x80
|
||||
)
|
||||
tailStart += 1;
|
||||
// A valid cut can leave at most three continuation bytes. Longer runs
|
||||
// are malformed output, so retain their decoding evidence.
|
||||
if (tailStart > 3) tailStart = 0;
|
||||
return `${head} … [output omitted] … ${this.#tail.subarray(tailStart).toString("utf8")}`;
|
||||
return `${head} … [output omitted] … ${tailBytes.subarray(tailStart).toString("utf8")}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,10 +35,7 @@ import {
|
||||
} from "./ProcessOwnership.js";
|
||||
import { AbortedWait, waitForAbortable } from "./AbortablePromise.js";
|
||||
import type { ManagedRuntime } from "./RuntimeExhaustion.js";
|
||||
import {
|
||||
ProviderStartupDeadline,
|
||||
waitForAbortableDelay,
|
||||
} from "./ProviderDeadline.js";
|
||||
import { ProviderStartupDeadline } from "./ProviderDeadline.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
import { launcherFailureOf, type LauncherFailure } from "./launchFailure.js";
|
||||
|
||||
@@ -317,6 +314,12 @@ const collectOwnedCommand = async (
|
||||
readonly collectionFailure: boolean;
|
||||
}
|
||||
| undefined;
|
||||
const waitWake = new AbortController();
|
||||
const wakeSignal = AbortSignal.any([signal, waitWake.signal]);
|
||||
const wakeMonitor = (): void => {
|
||||
if (!waitWake.signal.aborted)
|
||||
waitWake.abort(OwnerCancellation.noLongerNeeded);
|
||||
};
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{
|
||||
...launched,
|
||||
@@ -334,6 +337,7 @@ const collectOwnedCommand = async (
|
||||
exceeded = true;
|
||||
if (deadline.interruption === undefined)
|
||||
outputLimitObservedBeforeInterruption = true;
|
||||
wakeMonitor();
|
||||
}
|
||||
if (event.type === "error") {
|
||||
processFailure ??= event.message;
|
||||
@@ -344,6 +348,7 @@ const collectOwnedCommand = async (
|
||||
processError,
|
||||
collectionFailure: true,
|
||||
};
|
||||
wakeMonitor();
|
||||
}
|
||||
if (event.type === "exit" && deadline.interruption === undefined) {
|
||||
const acceptedNonzeroExit =
|
||||
@@ -380,6 +385,7 @@ const collectOwnedCommand = async (
|
||||
exceeded = true;
|
||||
if (deadline.interruption === undefined)
|
||||
outputLimitObservedBeforeInterruption = true;
|
||||
wakeMonitor();
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -391,6 +397,7 @@ const collectOwnedCommand = async (
|
||||
processError,
|
||||
collectionFailure: true,
|
||||
};
|
||||
if (failed !== undefined) wakeMonitor();
|
||||
});
|
||||
let inputFailure:
|
||||
| {
|
||||
@@ -420,6 +427,7 @@ const collectOwnedCommand = async (
|
||||
collectionFailure: true,
|
||||
};
|
||||
abandoned.abort(OwnerCancellation.noLongerNeeded);
|
||||
wakeMonitor();
|
||||
})
|
||||
: Promise.resolve();
|
||||
let failure: OwnedCommandFailure | undefined;
|
||||
@@ -461,7 +469,7 @@ const collectOwnedCommand = async (
|
||||
);
|
||||
};
|
||||
try {
|
||||
while (!(await supervisor.waitForOutputClose(10))) {
|
||||
while (!(await supervisor.waitForOutputClose(undefined, wakeSignal))) {
|
||||
const interrupted = interruptionOrObservedFailure(deadline.interruption);
|
||||
if (interrupted !== undefined) throw interrupted;
|
||||
if (exceeded)
|
||||
@@ -475,7 +483,7 @@ const collectOwnedCommand = async (
|
||||
processError,
|
||||
collectionFailure: true,
|
||||
});
|
||||
await waitForAbortableDelay(25, signal);
|
||||
if (waitWake.signal.aborted) break;
|
||||
}
|
||||
// Output has closed, but the sink may still be parsing what it buffered.
|
||||
const sinkFailure = await waitForAbortable(consumed, collectionSignal);
|
||||
@@ -530,6 +538,7 @@ const collectOwnedCommand = async (
|
||||
);
|
||||
}
|
||||
// A finished sink ignores this; an unfinished one is destroyed.
|
||||
wakeMonitor();
|
||||
abandoned.abort(OwnerCancellation.noLongerNeeded);
|
||||
const stopped = await supervisor.stop(
|
||||
limits.termination === undefined ? {} : { termination: limits.termination },
|
||||
|
||||
@@ -10,6 +10,34 @@ export interface ProviderProcessOutputToken {
|
||||
/** True when the line's right edge is cut or its end has not been observed. */
|
||||
readonly trailingContextIncomplete?: true;
|
||||
}
|
||||
|
||||
/** Immutable raw byte snapshot of a confirmed token before UTF-8 decoding. */
|
||||
export interface RawProcessOutputToken {
|
||||
readonly offset: number;
|
||||
readonly prefix: Buffer | undefined;
|
||||
readonly suffix: Buffer;
|
||||
readonly truncated: boolean;
|
||||
readonly trailingContextIncomplete: boolean;
|
||||
}
|
||||
|
||||
/** Decode an immutable raw token snapshot into its UTF-8 projection. */
|
||||
export const materializeProcessOutputToken = (
|
||||
raw: RawProcessOutputToken,
|
||||
): ProviderProcessOutputToken => {
|
||||
const bytes =
|
||||
raw.prefix === undefined
|
||||
? raw.suffix
|
||||
: Buffer.concat([raw.prefix, raw.suffix]);
|
||||
return {
|
||||
offset: raw.offset,
|
||||
line: bytes.toString("utf8"),
|
||||
...(!isUtf8(bytes) ? { invalidUtf8: true as const } : {}),
|
||||
truncated: raw.truncated,
|
||||
...(raw.trailingContextIncomplete
|
||||
? { trailingContextIncomplete: true as const }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
const PROCESS_OUTPUT_TOKEN_CONTEXT_BYTES = 1024;
|
||||
const NEWLINE = 0x0a;
|
||||
const isWordByte = (byte: number): boolean =>
|
||||
@@ -74,30 +102,33 @@ export class ProcessOutputTokenScanner {
|
||||
this.#pending = undefined;
|
||||
if (this.#latest !== undefined) this.#latest.open = false;
|
||||
}
|
||||
latestWithin(
|
||||
/** Capture event-time bytes and truncation flags without UTF-8 decoding. */
|
||||
snapshotLatestWithin(
|
||||
start: number,
|
||||
end: number,
|
||||
): ProviderProcessOutputToken | undefined {
|
||||
): RawProcessOutputToken | undefined {
|
||||
const latest = this.#latest;
|
||||
if (latest === undefined || latest.offset < start || latest.offset >= end)
|
||||
return undefined;
|
||||
// Omit a prefix crossing the checkpoint in full: neither its old cause
|
||||
// text nor a credential fragment cut on the left belongs to this scope.
|
||||
const prefixInRange = latest.offset - latest.prefix.length >= start;
|
||||
const bytes = Buffer.concat([
|
||||
...(prefixInRange ? [latest.prefix] : []),
|
||||
latest.suffix,
|
||||
]);
|
||||
return {
|
||||
offset: latest.offset,
|
||||
line: bytes.toString("utf8"),
|
||||
...(!isUtf8(bytes) ? { invalidUtf8: true as const } : {}),
|
||||
prefix: prefixInRange ? latest.prefix : undefined,
|
||||
suffix: latest.suffix,
|
||||
truncated: latest.prefixCut || latest.suffixCut || !prefixInRange,
|
||||
...(latest.suffixCut || latest.open
|
||||
? { trailingContextIncomplete: true as const }
|
||||
: {}),
|
||||
trailingContextIncomplete: latest.suffixCut || latest.open,
|
||||
};
|
||||
}
|
||||
|
||||
latestWithin(
|
||||
start: number,
|
||||
end: number,
|
||||
): ProviderProcessOutputToken | undefined {
|
||||
const raw = this.snapshotLatestWithin(start, end);
|
||||
return raw === undefined ? undefined : materializeProcessOutputToken(raw);
|
||||
}
|
||||
#record(searched: Buffer, index: number, searchedStart: number): Match {
|
||||
const lineStart =
|
||||
index === 0 ? 0 : searched.lastIndexOf(NEWLINE, index - 1) + 1;
|
||||
|
||||
+197
-44
@@ -17,8 +17,10 @@ import type { Readable, Writable } from "node:stream";
|
||||
import { WindowsOwnedProcess } from "../windows/WindowsOwnedProcess.js";
|
||||
|
||||
import {
|
||||
materializeProcessOutputToken,
|
||||
ProcessOutputTokenScanner,
|
||||
type ProviderProcessOutputToken,
|
||||
type RawProcessOutputToken,
|
||||
} from "./ProcessOutputTokenScanner.js";
|
||||
|
||||
import type {
|
||||
@@ -494,11 +496,13 @@ export class ProviderProcessSupervisor {
|
||||
): void => {
|
||||
this.#recordExit(code, signal);
|
||||
this.#outputClosed = true;
|
||||
if (!this.#disposed)
|
||||
this.#options.onDiagnostic?.({
|
||||
type: "output-close",
|
||||
snapshot: this.snapshot(),
|
||||
});
|
||||
const onDiagnostic = this.#options.onDiagnostic;
|
||||
if (!this.#disposed && onDiagnostic !== undefined) {
|
||||
const raw = this.#captureSnapshotRaw();
|
||||
onDiagnostic(
|
||||
diagnosticEventWithLazySnapshot({ type: "output-close" }, raw),
|
||||
);
|
||||
}
|
||||
this.#outputClose.resolve(undefined);
|
||||
};
|
||||
readonly #onError = (cause: Error): void => {
|
||||
@@ -587,6 +591,26 @@ export class ProviderProcessSupervisor {
|
||||
};
|
||||
}
|
||||
|
||||
/** Capture event-time bytes and flags without materializing UTF-8 strings yet. */
|
||||
#captureSnapshotRaw(): RawProviderProcessSnapshot {
|
||||
const outputIncomplete =
|
||||
this.#outputIncomplete || this.launch.process.outputIncomplete === true;
|
||||
return {
|
||||
diagnosticTruncated: this.#diagnosticTruncated || outputIncomplete,
|
||||
stdout: this.#stdout.snapshotRaw(this.#stdoutObservedBytes),
|
||||
stderr: this.#stderr.snapshotRaw(this.#stderrObservedBytes),
|
||||
exitCode: this.#exitObservation?.code,
|
||||
signal: this.#exitObservation?.signal,
|
||||
memoryLimitReached: this.launch.process.memoryLimitReached === true,
|
||||
stopRequested: this.#stopRequested,
|
||||
outputIncomplete,
|
||||
runtimeExhaustion: this.#captureRuntimeExhaustionWithin({
|
||||
stdout: 0,
|
||||
stderr: 0,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Mark the current raw-byte position without copying or retaining output. */
|
||||
checkpointOutput(): ProviderProcessOutputCheckpoint {
|
||||
const checkpoint = Object.freeze({}) as ProviderProcessOutputCheckpoint;
|
||||
@@ -678,27 +702,35 @@ export class ProviderProcessSupervisor {
|
||||
}
|
||||
|
||||
/** The runtime's exhaustion report after a position; stderr is preferred. */
|
||||
#runtimeExhaustionWithin(position: {
|
||||
#captureRuntimeExhaustionWithin(position: {
|
||||
readonly stdout: number;
|
||||
readonly stderr: number;
|
||||
}): Pick<ProviderProcessSnapshot, "runtimeExhaustion"> {
|
||||
}): RawRuntimeExhaustion | undefined {
|
||||
const runtime = this.#options.runtime;
|
||||
if (runtime === undefined) return {};
|
||||
const stderr = this.#stderrMarker?.latestWithin(
|
||||
if (runtime === undefined) return undefined;
|
||||
const stderr = this.#stderrMarker?.snapshotLatestWithin(
|
||||
position.stderr,
|
||||
this.#stderrObservedBytes,
|
||||
);
|
||||
if (stderr !== undefined)
|
||||
return {
|
||||
runtimeExhaustion: runtimeExhaustion(runtime, "stderr", stderr),
|
||||
};
|
||||
const stdout = this.#stdoutMarker?.latestWithin(
|
||||
return { runtime, stream: "stderr", token: stderr };
|
||||
const stdout = this.#stdoutMarker?.snapshotLatestWithin(
|
||||
position.stdout,
|
||||
this.#stdoutObservedBytes,
|
||||
);
|
||||
return stdout === undefined
|
||||
? undefined
|
||||
: { runtime, stream: "stdout", token: stdout };
|
||||
}
|
||||
|
||||
#runtimeExhaustionWithin(position: {
|
||||
readonly stdout: number;
|
||||
readonly stderr: number;
|
||||
}): Pick<ProviderProcessSnapshot, "runtimeExhaustion"> {
|
||||
const raw = this.#captureRuntimeExhaustionWithin(position);
|
||||
return raw === undefined
|
||||
? {}
|
||||
: { runtimeExhaustion: runtimeExhaustion(runtime, "stdout", stdout) };
|
||||
: { runtimeExhaustion: materializeRuntimeExhaustion(raw) };
|
||||
}
|
||||
|
||||
#resetMarkers(): void {
|
||||
@@ -1100,17 +1132,130 @@ export class ProviderProcessSupervisor {
|
||||
if (this.#exitObservation !== undefined) return;
|
||||
this.#exitObservation = { code, signal };
|
||||
this.#exit.resolve(this.#exitObservation);
|
||||
this.#options.onDiagnostic?.({
|
||||
type: "exit",
|
||||
code,
|
||||
signal,
|
||||
snapshot: this.snapshot(),
|
||||
});
|
||||
const onDiagnostic = this.#options.onDiagnostic;
|
||||
if (onDiagnostic === undefined) return;
|
||||
const raw = this.#captureSnapshotRaw();
|
||||
onDiagnostic(
|
||||
diagnosticEventWithLazySnapshot({ type: "exit", code, signal }, raw),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
interface RawRuntimeExhaustion {
|
||||
readonly runtime: ManagedRuntime;
|
||||
readonly stream: "stdout" | "stderr";
|
||||
readonly token: RawProcessOutputToken;
|
||||
}
|
||||
|
||||
interface RawOutputCapture {
|
||||
readonly chunks: readonly Buffer[];
|
||||
readonly bytes: number;
|
||||
readonly observedBytes: number;
|
||||
}
|
||||
|
||||
interface RawProviderProcessSnapshot {
|
||||
readonly diagnosticTruncated: boolean;
|
||||
readonly stdout: RawOutputCapture;
|
||||
readonly stderr: RawOutputCapture;
|
||||
readonly exitCode: number | null | undefined;
|
||||
readonly signal: NodeJS.Signals | null | undefined;
|
||||
readonly memoryLimitReached: boolean;
|
||||
readonly stopRequested: boolean;
|
||||
readonly outputIncomplete: boolean;
|
||||
readonly runtimeExhaustion: RawRuntimeExhaustion | undefined;
|
||||
}
|
||||
|
||||
const materializeRuntimeExhaustion = (
|
||||
raw: RawRuntimeExhaustion,
|
||||
): RuntimeExhaustion =>
|
||||
runtimeExhaustion(
|
||||
raw.runtime,
|
||||
raw.stream,
|
||||
materializeProcessOutputToken(raw.token),
|
||||
);
|
||||
|
||||
const materializeProviderProcessSnapshot = (
|
||||
raw: RawProviderProcessSnapshot,
|
||||
): ProviderProcessSnapshot => ({
|
||||
...(raw.diagnosticTruncated ? { diagnosticTruncated: true } : {}),
|
||||
stdout: materializeCapturedOutput(
|
||||
raw.stdout.chunks,
|
||||
raw.stdout.bytes,
|
||||
raw.stdout.observedBytes,
|
||||
),
|
||||
stderr: materializeCapturedOutput(
|
||||
raw.stderr.chunks,
|
||||
raw.stderr.bytes,
|
||||
raw.stderr.observedBytes,
|
||||
),
|
||||
exitCode: raw.exitCode,
|
||||
signal: raw.signal,
|
||||
...(raw.memoryLimitReached ? { memoryLimitReached: true } : {}),
|
||||
...(raw.stopRequested ? { stopRequested: true } : {}),
|
||||
...(raw.outputIncomplete ? { outputIncomplete: true } : {}),
|
||||
...(raw.runtimeExhaustion === undefined
|
||||
? {}
|
||||
: {
|
||||
runtimeExhaustion: materializeRuntimeExhaustion(raw.runtimeExhaustion),
|
||||
}),
|
||||
});
|
||||
|
||||
const diagnosticEventWithLazySnapshot = <
|
||||
Event extends { readonly type: "exit" | "output-close" },
|
||||
>(
|
||||
fields: Event,
|
||||
raw: RawProviderProcessSnapshot,
|
||||
): Event & { readonly snapshot: ProviderProcessSnapshot } => {
|
||||
let pending: RawProviderProcessSnapshot | undefined = raw;
|
||||
let snapshot: ProviderProcessSnapshot | undefined;
|
||||
return Object.defineProperty({ ...fields }, "snapshot", {
|
||||
enumerable: true,
|
||||
get() {
|
||||
if (snapshot === undefined) {
|
||||
snapshot = materializeProviderProcessSnapshot(pending!);
|
||||
pending = undefined;
|
||||
}
|
||||
return snapshot;
|
||||
},
|
||||
}) as Event & { readonly snapshot: ProviderProcessSnapshot };
|
||||
};
|
||||
|
||||
const EMPTY_CHUNKS: readonly Buffer[] = [];
|
||||
const EMPTY_OUTPUT_BUFFER = Buffer.alloc(0);
|
||||
|
||||
const materializeCapturedOutput = (
|
||||
chunks: readonly Buffer[],
|
||||
bytes: number,
|
||||
observedBytes: number,
|
||||
): ProviderProcessSnapshot["stdout"] => {
|
||||
const buffer =
|
||||
chunks.length === 0
|
||||
? EMPTY_OUTPUT_BUFFER
|
||||
: chunks.length === 1
|
||||
? chunks[0]!
|
||||
: Buffer.concat(chunks, bytes);
|
||||
return snapshotOutputBuffer(buffer, observedBytes);
|
||||
};
|
||||
|
||||
const snapshotOutputBuffer = (
|
||||
buffer: Buffer,
|
||||
observedBytes: number,
|
||||
): ProviderProcessSnapshot["stdout"] => {
|
||||
if (buffer.byteLength === 0) return { text: "", bytes: 0, observedBytes };
|
||||
const text = buffer.toString("utf8");
|
||||
const invalidUtf8 = !isStrictUtf8(buffer);
|
||||
return {
|
||||
text,
|
||||
bytes: buffer.byteLength,
|
||||
observedBytes,
|
||||
...(invalidUtf8 ? { invalidUtf8: true } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
class ProcessOutputCapture {
|
||||
readonly #chunks: Buffer[] = [];
|
||||
#chunks: Buffer[] = [];
|
||||
// Copy-on-write: shared with pending lazy snapshots until the next mutation or reset.
|
||||
#sharedChunks = false;
|
||||
// not-an-allowance: retained length of a tail buffer that drops its front past the limit instead of refusing input.
|
||||
#bytes = 0;
|
||||
/** Observed bytes before the first retained one, which tail retention dropped. */
|
||||
@@ -1120,15 +1265,28 @@ class ProcessOutputCapture {
|
||||
return this.#bytes;
|
||||
}
|
||||
|
||||
#mutableChunks(): Buffer[] {
|
||||
if (this.#sharedChunks) {
|
||||
this.#chunks = this.#chunks.slice();
|
||||
this.#sharedChunks = false;
|
||||
}
|
||||
return this.#chunks;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.#chunks.length = 0;
|
||||
if (this.#sharedChunks) {
|
||||
this.#chunks = [];
|
||||
this.#sharedChunks = false;
|
||||
} else {
|
||||
this.#chunks.length = 0;
|
||||
}
|
||||
this.#bytes = 0;
|
||||
this.#start = 0;
|
||||
}
|
||||
|
||||
append(chunk: Buffer): void {
|
||||
this.#bytes += chunk.byteLength;
|
||||
this.#chunks.push(Buffer.from(chunk));
|
||||
this.#mutableChunks().push(Buffer.from(chunk));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1161,8 +1319,9 @@ class ProcessOutputCapture {
|
||||
((first[drop] ?? 0) & 0xc0) === 0x80
|
||||
)
|
||||
drop += 1;
|
||||
if (drop === first.byteLength) this.#chunks.shift();
|
||||
else if (drop > 0) this.#chunks[0] = Buffer.from(first.subarray(drop));
|
||||
if (drop === first.byteLength) this.#mutableChunks().shift();
|
||||
else if (drop > 0)
|
||||
this.#mutableChunks()[0] = Buffer.from(first.subarray(drop));
|
||||
this.#bytes -= drop;
|
||||
this.#start += drop;
|
||||
remaining -= Math.min(remaining, drop);
|
||||
@@ -1170,11 +1329,19 @@ class ProcessOutputCapture {
|
||||
}
|
||||
}
|
||||
|
||||
snapshot(observedBytes: number): ProviderProcessSnapshot["stdout"] {
|
||||
return this.#snapshotBuffer(
|
||||
Buffer.concat(this.#chunks, this.#bytes),
|
||||
snapshotRaw(observedBytes: number): RawOutputCapture {
|
||||
if (this.#chunks.length === 0)
|
||||
return { chunks: EMPTY_CHUNKS, bytes: 0, observedBytes };
|
||||
this.#sharedChunks = true;
|
||||
return {
|
||||
chunks: this.#chunks,
|
||||
bytes: this.#bytes,
|
||||
observedBytes,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
snapshot(observedBytes: number): ProviderProcessSnapshot["stdout"] {
|
||||
return materializeCapturedOutput(this.#chunks, this.#bytes, observedBytes);
|
||||
}
|
||||
|
||||
snapshotRange(
|
||||
@@ -1197,26 +1364,12 @@ class ProcessOutputCapture {
|
||||
}
|
||||
const buffer = Buffer.concat(chunks, availableEnd - availableStart);
|
||||
return {
|
||||
stream: this.#snapshotBuffer(buffer, Math.max(0, end - start)),
|
||||
stream: snapshotOutputBuffer(buffer, Math.max(0, end - start)),
|
||||
complete:
|
||||
start === end ||
|
||||
(start >= this.#start && start <= retainedEnd && end <= retainedEnd),
|
||||
};
|
||||
}
|
||||
|
||||
#snapshotBuffer(
|
||||
buffer: Buffer,
|
||||
observedBytes: number,
|
||||
): ProviderProcessSnapshot["stdout"] {
|
||||
const text = buffer.toString("utf8");
|
||||
const invalidUtf8 = !isStrictUtf8(buffer);
|
||||
return {
|
||||
text,
|
||||
bytes: buffer.byteLength,
|
||||
observedBytes,
|
||||
...(invalidUtf8 ? { invalidUtf8: true } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface Deferred<Value> {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { withVerifierCleanup } from "../../scripts/lib/verifier-cleanup.mjs";
|
||||
import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
type ProcessDiagnosticBudget,
|
||||
type ProviderProcessDiagnostic,
|
||||
} from "./ProviderProcess.js";
|
||||
import { redactExplicitOutput } from "../domain/explicitSensitiveValues.js";
|
||||
|
||||
@@ -850,3 +851,254 @@ it("retains a stream's latest bytes in tail retention, with checkpoints over wha
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
describe("lazy diagnostic snapshot materialization", () => {
|
||||
it("exposes enumerable memoized snapshots on exit and output-close events", () => {
|
||||
const producer = createProducer();
|
||||
const events: {
|
||||
readonly type: string;
|
||||
readonly snapshot?: unknown;
|
||||
}[] = [];
|
||||
let repeatedExitSnapshotSame = false;
|
||||
let repeatedCloseSnapshotSame = false;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: producer, ownsProcessLifetime: false },
|
||||
{
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "exit") {
|
||||
events.push(event);
|
||||
repeatedExitSnapshotSame = event.snapshot === event.snapshot;
|
||||
} else if (event.type === "output-close") {
|
||||
events.push(event);
|
||||
repeatedCloseSnapshotSame = event.snapshot === event.snapshot;
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
producer.stdout.write("hello");
|
||||
producer.emit("exit", 0, null);
|
||||
producer.stdout.end();
|
||||
producer.stderr.end();
|
||||
producer.emit("close", 0, null);
|
||||
|
||||
expect(events).toHaveLength(2);
|
||||
expect(Object.keys(events[0]!)).toContain("snapshot");
|
||||
expect(Object.keys(events[1]!)).toContain("snapshot");
|
||||
expect(repeatedExitSnapshotSame).toBe(true);
|
||||
expect(repeatedCloseSnapshotSame).toBe(true);
|
||||
expect(events[0]?.snapshot).toMatchObject({
|
||||
exitCode: 0,
|
||||
stdout: { text: "hello", bytes: 5 },
|
||||
});
|
||||
expect(events[1]?.snapshot).toEqual(supervisor.snapshot());
|
||||
} finally {
|
||||
supervisor.dispose();
|
||||
producer.stdout.destroy();
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-time snapshot capture before lazy materialization", () => {
|
||||
it("preserves exit and output-close snapshots across later stderr, overflow, and resetOutput", () => {
|
||||
const producer = createProducer();
|
||||
let exitEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "exit" }>
|
||||
| undefined;
|
||||
let closeEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "output-close" }>
|
||||
| undefined;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: producer, ownsProcessLifetime: false },
|
||||
{
|
||||
maxDiagnosticBytes: { stdout: 8, stderr: 8 },
|
||||
onDiagnostic: (event) => {
|
||||
// Store only the event object; do not access `.snapshot` yet.
|
||||
if (event.type === "exit") exitEvent = event;
|
||||
else if (event.type === "output-close") closeEvent = event;
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
producer.stdout.write("out-1");
|
||||
producer.stderr.write("err-1");
|
||||
producer.emit("exit", 0, null);
|
||||
// Late stderr overflows stderr budget after `exit` was emitted.
|
||||
producer.stderr.write("-tail-overflow");
|
||||
producer.stdout.end();
|
||||
producer.stderr.end();
|
||||
producer.emit("close", 0, null);
|
||||
// Clear retained buffers before reading either stored `.snapshot`.
|
||||
supervisor.resetOutput();
|
||||
|
||||
expect(exitEvent?.snapshot).toEqual({
|
||||
stdout: { text: "out-1", bytes: 5, observedBytes: 5 },
|
||||
stderr: { text: "err-1", bytes: 5, observedBytes: 5 },
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
});
|
||||
expect(closeEvent?.snapshot).toEqual({
|
||||
diagnosticTruncated: true,
|
||||
stdout: { text: "out-1", bytes: 5, observedBytes: 5 },
|
||||
stderr: { text: "err-1-ta", bytes: 8, observedBytes: 19 },
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
});
|
||||
expect(supervisor.snapshot()).toEqual({
|
||||
stdout: { text: "", bytes: 0, observedBytes: 0 },
|
||||
stderr: { text: "", bytes: 0, observedBytes: 0 },
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
});
|
||||
} finally {
|
||||
supervisor.dispose();
|
||||
producer.stdout.destroy();
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("isolates stored event snapshots from writes following resetOutput", () => {
|
||||
const producer = createProducer();
|
||||
let exitEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "exit" }>
|
||||
| undefined;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: producer, ownsProcessLifetime: false },
|
||||
{
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "exit") exitEvent = event;
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
producer.stdout.write("before-exit");
|
||||
producer.stderr.write("err-before");
|
||||
producer.emit("exit", 0, null);
|
||||
supervisor.resetOutput();
|
||||
producer.stdout.write("after-reset");
|
||||
producer.stderr.write("err-after");
|
||||
|
||||
expect(exitEvent?.snapshot).toEqual({
|
||||
stdout: { text: "before-exit", bytes: 11, observedBytes: 11 },
|
||||
stderr: { text: "err-before", bytes: 10, observedBytes: 10 },
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
});
|
||||
expect(supervisor.snapshot()).toEqual({
|
||||
stdout: { text: "after-reset", bytes: 11, observedBytes: 11 },
|
||||
stderr: { text: "err-after", bytes: 9, observedBytes: 9 },
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
});
|
||||
} finally {
|
||||
supervisor.dispose();
|
||||
producer.stdout.destroy();
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("event-time snapshot capture with tail retention and runtime exhaustion", () => {
|
||||
it("preserves tail-retained event snapshots when post-exit output drops front bytes", () => {
|
||||
const producer = createProducer();
|
||||
let exitEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "exit" }>
|
||||
| undefined;
|
||||
let closeEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "output-close" }>
|
||||
| undefined;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: producer, ownsProcessLifetime: false },
|
||||
{
|
||||
maxDiagnosticBytes: { stdout: 5, stderr: 5 },
|
||||
diagnosticRetention: "tail",
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "exit") exitEvent = event;
|
||||
else if (event.type === "output-close") closeEvent = event;
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
producer.stderr.write("12345");
|
||||
producer.emit("exit", 1, null);
|
||||
producer.stderr.write("67890");
|
||||
producer.stdout.end();
|
||||
producer.stderr.end();
|
||||
producer.emit("close", 1, null);
|
||||
supervisor.resetOutput();
|
||||
|
||||
expect(exitEvent?.snapshot).toEqual({
|
||||
stdout: { text: "", bytes: 0, observedBytes: 0 },
|
||||
stderr: { text: "12345", bytes: 5, observedBytes: 5 },
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
});
|
||||
expect(closeEvent?.snapshot).toEqual({
|
||||
diagnosticTruncated: true,
|
||||
stdout: { text: "", bytes: 0, observedBytes: 0 },
|
||||
stderr: { text: "67890", bytes: 5, observedBytes: 10 },
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
});
|
||||
} finally {
|
||||
supervisor.dispose();
|
||||
producer.stdout.destroy();
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves exit-time runtime exhaustion state before later stream updates", () => {
|
||||
const producer = createProducer();
|
||||
let exitEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "exit" }>
|
||||
| undefined;
|
||||
let closeEvent:
|
||||
| Extract<ProviderProcessDiagnostic, { type: "output-close" }>
|
||||
| undefined;
|
||||
const supervisor = new ProviderProcessSupervisor(
|
||||
{ process: producer, ownsProcessLifetime: false },
|
||||
{
|
||||
runtime: "jvm",
|
||||
onDiagnostic: (event) => {
|
||||
if (event.type === "exit") exitEvent = event;
|
||||
else if (event.type === "output-close") closeEvent = event;
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
producer.stderr.write("java.lang.OutOfMemoryError: ");
|
||||
producer.emit("exit", 1, null);
|
||||
producer.stderr.write("Java heap space\n");
|
||||
producer.stdout.end();
|
||||
producer.stderr.end();
|
||||
producer.emit("close", 1, null);
|
||||
supervisor.resetOutput();
|
||||
supervisor.dispose();
|
||||
|
||||
expect(exitEvent?.snapshot.runtimeExhaustion).toEqual({
|
||||
runtime: "jvm",
|
||||
area: undefined,
|
||||
stream: "stderr",
|
||||
line: "java.lang.OutOfMemoryError: ",
|
||||
lineComplete: false,
|
||||
truncated: false,
|
||||
invalidUtf8: false,
|
||||
});
|
||||
expect(closeEvent?.snapshot.runtimeExhaustion).toEqual({
|
||||
runtime: "jvm",
|
||||
area: "heap",
|
||||
stream: "stderr",
|
||||
line: "java.lang.OutOfMemoryError: Java heap space",
|
||||
lineComplete: true,
|
||||
truncated: false,
|
||||
invalidUtf8: false,
|
||||
});
|
||||
expect(supervisor.snapshot().runtimeExhaustion).toBeUndefined();
|
||||
} finally {
|
||||
supervisor.dispose();
|
||||
producer.stdout.destroy();
|
||||
producer.stderr.destroy();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user