fix(kuna): stream string scans instead of capping them at 16 MiB (#4318)

* fix(kuna): stream string scans instead of capping them at 16 MiB

`list_strings` and `search_strings` buffered Kuna's whole string JSON and
refused anything above 16 MiB. Kuna writes about 290 bytes per row, so
every app above roughly 10 MB failed with a non-retryable memory error:
a 20 MB Ghostty binary produces 31 MB, Raycast 30 MB and an arm64
Firefox XUL 179 MB.

Parse the scan as Kuna writes it. `runOwnedCommand` accepts a stdout
sink, and `KunaStringInventoryReader` owns the interpretation: it
tokenizes synchronously with stream-json, keeps exact u64 address
tokens, validates each row before retaining it, skips members it does
not interpret, and admits retained rows against live heap headroom
rather than a fixed scan size. The first contradiction stops Kuna
instead of waiting for the rest; an incomplete document is judged only
after Kuna's own exit status. Diagnostics keep the 8 MiB Kuna budget,
now shared with the project export.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(kuna): admit string scan text as it streams and drop sinks with their command

Review found that packed string tokens were assembled whole before the
reader could discard them or check heap headroom, and that a stdout sink
could outlive a cancelled or timed-out command.

Move the token mechanics into `KunaJsonDocumentReader`: keys and numbers
(Kuna's own fields) stay packed, while strings, which carry target-derived
text, arrive in chunks. Ignored strings are dropped unassembled and kept
ones are admitted against live heap headroom as they grow. Kept text is
copied out of the decoded chunk it was sliced from, so retained rows no
longer pin whole chunks (XUL: 278 MB retained before, 156 MB after).
`KunaStringInventoryReader` keeps only the string-scan semantics.

`runOwnedCommand` now ties the stdout pipeline to the command's deadline
signal and aborts it when collection fails, destroying the sink.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(kuna): type the stream-json tokenizer where it is imported

The Reverse tools quality lane type-checks a partial project that reaches
KunaJsonStream without the separate streamJsonParser.d.ts augmentation,
so jsonParser had no declaration there. Declare the tokenizer's shape at
its only import site and remove the augmentation file, so every
compilation of the reader is self-contained. Split two helpers out of
the token dispatcher and simplify the stdout sink wait in
runOwnedCommand, which keeps the added complexity minimal.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(kuna): bound key and number assembly in streamed Kuna JSON

Review found that packed keys (and packed numbers) were assembled whole
by the tokenizer before the reader could discard or constrain them, so a
malformed scan with one enormous key could still exhaust the heap.

Stream every scalar. Keys are assembled only up to 64 code units, past
every field name the reader keeps, so a longer key is skipped unmatched;
kept numbers longer than that are rejected, and ignored numbers are
dropped unassembled. XUL's 611k-row scan parses in the same time.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(kuna): stream the call graph instead of capping it at 32 MiB (#4329)

* fix(kuna): stream the call graph instead of capping it at 32 MiB

Call relationships buffered `kuna decompile-graph` and refused output
above 32 MiB. A 53 MB Raycast binary produces a 157 MB graph (180k
functions, 773k edges), so every call query failed with a non-retryable
memory error after Kuna's minute-long whole-program walk.

`KunaCallGraphReader` validates the graph through the shared streaming
document reader. It retains only the facts queries use (126 MB for
Raycast) and checks edges against the complete node set once Kuna
exits. Unrequested bodies are refused before any of their text is
assembled, through new must-be-null row fields; address fields may be
null, as `forwardsTo` is. Malformed graphs are now `AnalysisOutputError`
like the string scan.

`KunaQueryWork.scan` owns the run-and-validate sequence both producers
shared: diagnostics budget, early rejection and retention of
deterministic overflow.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(kuna): index call-graph edges as they stream

Review found that the reader kept every parsed edge and built the edge
indexes only after streaming, outside any heap admission, so a large
graph could exhaust the heap instead of returning a memory constraint.

Index each edge when it arrives: duplicate pairs and callee orders are
checked per caller, call edges go straight into the caller/callee
indexes, and no edge array is kept, so the whole working set grows under
the per-row admission. Endpoints and order completeness are checked once
all nodes are known, and the validation-only indexes are released then.
Raycast's graph now peaks at 346 MB instead of 503 MB and retains 93 MB
instead of 126 MB, in the same time.

Also drop imports the shared scan made unused.

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(kuna): state the graph's retained size after incremental indexing

Refs #1957

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Kaoru0822andClaude Opus 5.5 authored and GitHub committed 2026-10-15 21:53:59 -07:00
1 parent d9d085a15e
commit 8ab5024397
20 files changed
+1413 -276

No files matched your search

+5 -1
View File
@@ -1,7 +1,7 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream, createWriteStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Transform } from "node:stream";
import { Transform, type Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { AnalysisError } from "../domain/analysisErrorBase.js";
@@ -54,7 +54,10 @@ export interface KunaCommandRequest {
readonly timeoutMs: number;
/** The deadline callers configured, reported when the run times out. */
readonly reportedTimeoutMs: number;
/** Buffered stderr bytes, plus stdout bytes unless `stdout` consumes them. */
readonly outputBytes: number;
/** Parses stdout as it arrives instead of buffering it; see `runOwnedCommand`. */
readonly stdout?: Writable | undefined;
readonly signal: AbortSignal;
readonly retainFailedFileClose: (
owner: OwnedFileHandle,
@@ -220,6 +223,7 @@ export const runKunaCommand = async (
{
timeoutMs: Math.max(1, request.timeoutMs),
diagnosticBytes: request.outputBytes,
...(request.stdout === undefined ? {} : { stdout: request.stdout }),
},
{
signal: request.signal,
+19 -11
View File
@@ -1,3 +1,20 @@
/** Read a numeric u64 address from its exact JSON token, before rounding. */
export const kunaAddressFromJsonNumber = (
source: string | undefined,
key: string,
): string => {
if (
source === undefined ||
source.length > 20 ||
!/^(?:0|[1-9][0-9]*)$/u.test(source)
)
throw new Error(`invalid numeric address in ${key}`);
const exact = BigInt(source);
if (exact > 0xffffffffffffffffn)
throw new Error(`address in ${key} exceeds u64`);
return `0x${exact.toString(16)}`;
};
/** Parse numeric u64 addresses from their exact JSON tokens, before rounding. */
export const parseKunaJson = (
text: string,
@@ -14,18 +31,9 @@ export const parseKunaJson = (
context?: { readonly source?: string },
): unknown => {
if (!addressKeys.has(key) || value === null) return value;
const source = context?.source;
if (
typeof value !== "number" ||
source === undefined ||
source.length > 20 ||
!/^(?:0|[1-9][0-9]*)$/u.test(source)
)
if (typeof value !== "number")
throw new Error(`invalid numeric address in ${key}`);
const exact = BigInt(source);
if (exact > 0xffffffffffffffffn)
throw new Error(`address in ${key} exceeds u64`);
return `0x${exact.toString(16)}`;
return kunaAddressFromJsonNumber(context?.source, key);
},
);
};
+554
View File
@@ -0,0 +1,554 @@
import { createHash } from "node:crypto";
import { Writable } from "node:stream";
import { getHeapStatistics } from "node:v8";
import { getManyValues, isMany, none, type Many } from "stream-chain/defs.js";
import * as streamJsonParser from "stream-json/core/parser.js";
import type { ParserOptions, Token } from "stream-json/core/parser.js";
import type { z } from "zod";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import { kunaAddressFromJsonNumber } from "./KunaJson.js";
/**
* stream-json 3's synchronous tokenizer behind `parser`, which its
* declarations omit. Each call returns the tokens `text` completes; `none`
* flushes the end of input.
*/
const { jsonParser } = streamJsonParser as unknown as {
readonly jsonParser: (
options: ParserOptions,
) => (text: string | typeof none) => Many<Token> | typeof none;
};
/** One array of flat row objects in a Kuna JSON document. */
export interface KunaJsonRows {
/** Scalar fields kept from each row; other fields are skipped unassembled. */
readonly fields: ReadonlySet<string>;
/** Kept numeric u64 fields, read from their exact tokens as hex, or null. */
readonly addresses: ReadonlySet<string>;
/** Array fields that must be empty, kept as `[]`. */
readonly empty: ReadonlySet<string>;
/** Fields that must be null, rejected before any other value is assembled. */
readonly nulls: ReadonlySet<string>;
}
/** The members of one Kuna JSON document that a reader interprets. */
export interface KunaJsonDocument {
/** Root scalar members kept in the header. */
readonly header: ReadonlySet<string>;
/** Root object members whose listed scalar fields are kept in the header. */
readonly sections: ReadonlyMap<string, ReadonlySet<string>>;
/** Root array members of rows, each passed to `acceptRow`. */
readonly rows: ReadonlyMap<string, KunaJsonRows>;
}
/** What the document established once Kuna stopped writing. */
export interface KunaJsonCompletion {
readonly header: Readonly<Record<string, unknown>>;
readonly sha256: string;
readonly bytes: number;
}
type Frame =
| { readonly kind: "root"; readonly values: Record<string, unknown> }
| {
readonly kind: "section";
readonly name: string;
readonly fields: ReadonlySet<string>;
readonly values: Record<string, unknown>;
}
| {
readonly kind: "rows";
readonly name: string;
readonly spec: KunaJsonRows;
}
| {
readonly kind: "row";
readonly member: string;
readonly spec: KunaJsonRows;
readonly values: Record<string, unknown>;
}
| { readonly kind: "empty"; readonly field: string };
/** Charge for one retained row beyond its UTF-16 text. */
const ROW_OVERHEAD_BYTES = 256;
/** Projected retention admitted between heap samples. */
const ADMISSION_INTERVAL_BYTES = 64 * 1024;
/** Per-row reserve for the owner's arrays, sorting and projections. */
const ROW_REFERENCE_BYTES = 16;
const describe = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
/**
* Longest key or kept number assembled. Kuna's field names and u64 decimals
* are far shorter, so a longer key names no kept field and a longer kept
* number is not one Kuna writes.
*/
const MAX_TOKEN_CODE_UNITS = 64;
/** Parse one row with its schema, naming the first field that is not Kuna's. */
export const parseKunaRow = <Schema extends z.ZodType>(
schema: Schema,
member: string,
fields: unknown,
): z.infer<Schema> => {
const parsed = schema.safeParse(fields);
if (parsed.success) return parsed.data;
throw new Error(
`${member} row field ${parsed.error.issues[0]?.path.join(".") ?? ""} is not Kuna's`,
);
};
/** V8 copies shorter substrings instead of slicing them. */
const SLICED_STRING_MIN_LENGTH = 13;
/**
* Copy kept text out of the decoded chunk the tokenizer sliced it from, so a
* retained row does not keep that whole chunk alive. UTF-16 code units copy
* losslessly, including lone surrogates.
*/
const detached = (text: string): string =>
text.length < SLICED_STRING_MIN_LENGTH
? text
: Buffer.from(text, "utf16le").toString("utf16le");
/**
* Validate a Kuna JSON document as Kuna writes it, without buffering it.
*
* Every scalar arrives in chunks and is assembled only as far as it can
* matter: keys up to the longest field name, kept numbers up to the longest
* u64, and kept strings, which can carry target-derived text of any length,
* admitted against live heap headroom as they grow, as are retained rows.
* Ignored values are dropped unassembled. The first contradiction aborts
* `rejected`, letting the owner stop Kuna early. The writable side never
* fails, so the command's own outcome stays authoritative; `complete` reports
* what the document established.
*/
export abstract class KunaJsonDocumentReader<Parsed> extends Writable {
readonly #hash = createHash("sha256");
readonly #decoder = new TextDecoder("utf-8", { fatal: true });
readonly #tokens = jsonParser({
packKeys: false,
packNumbers: false,
packStrings: false,
streamValues: true,
});
readonly #rejection = new AbortController();
readonly #frames: Frame[] = [];
readonly #rowsSeen = new Set<string>();
#header: Record<string, unknown> = {};
#bytes = 0;
#failure: AnalysisError | undefined;
#closed = false;
#key: string | undefined;
/** Containers still open inside an ignored value. */
#skipping = 0;
/** Key the scalar being read is kept under; undefined discards it. */
#target: string | undefined;
/** Whether `#target` holds a numeric u64 address. */
#targetIsAddress = false;
/** Whether the scalar being assembled is a key. */
#inKey = false;
/** The key or kept scalar assembled so far. */
#text = "";
#rows = 0;
#projectedBytes = 0;
#nextAdmission = 0;
constructor(
private readonly producer: string,
private readonly label: string,
private readonly document: KunaJsonDocument,
) {
super();
}
/** Validate and retain one row; throw to reject the document. */
protected abstract acceptRow(
member: string,
row: Readonly<Record<string, unknown>>,
): void;
/** Release retained rows once the document is rejected. */
protected abstract discardRows(): void;
/** The validated document, once Kuna has exited successfully on `input`. */
abstract finish(input: string): Result<Parsed, AnalysisError>;
/** Aborted at the first contradiction or refused retention. */
get rejected(): AbortSignal {
return this.#rejection.signal;
}
/** Why `rejected` aborted, if it has. */
get rejection(): AnalysisError | undefined {
return this.#rejection.signal.aborted ? this.#failure : undefined;
}
/** An output error naming this document. */
protected unusable(reason: string): AnalysisOutputError {
return new AnalysisOutputError(this.producer, reason, {
userMessage: `${this.label} cannot be used: ${reason}`,
});
}
override _write(
chunk: Buffer,
_encoding: BufferEncoding,
callback: (error?: Error | null) => void,
): void {
if (this.#failure === undefined)
try {
this.#bytes += chunk.byteLength;
this.#hash.update(chunk);
this.#feed(this.#decoder.decode(chunk, { stream: true }));
} catch (cause: unknown) {
this.#reject(cause);
this.#rejection.abort();
}
callback();
}
override _final(callback: (error?: Error | null) => void): void {
// Kuna has stopped writing, so an incomplete document is recorded for
// `complete` without signalling: its exit status may explain it.
if (this.#failure === undefined)
try {
this.#feed(this.#decoder.decode());
this.#feed(none);
} catch (cause: unknown) {
this.#reject(cause);
}
callback();
}
/** The kept header and source identity, once Kuna has exited successfully. */
protected complete(): Result<KunaJsonCompletion, AnalysisError> {
if (this.#failure !== undefined) return err(this.#failure);
if (
!this.writableFinished ||
!this.#closed ||
[...this.document.rows.keys()].some((name) => !this.#rowsSeen.has(name))
)
return err(this.unusable(`${this.label} ended before it was complete`));
return ok({
header: this.#header,
sha256: this.#hash.digest("hex"),
bytes: this.#bytes,
});
}
#reject(cause: unknown): void {
this.#failure ??=
cause instanceof AnalysisResourceConstraintError
? cause
: this.unusable(describe(cause));
this.#text = "";
this.#inKey = false;
this.#header = {};
this.discardRows();
}
#feed(text: string | typeof none): void {
const tokens = this.#tokens(text);
if (isMany(tokens))
for (const token of getManyValues(tokens)) this.#consume(token);
}
/** Consume a token inside an ignored value; false once none is open. */
#skip(token: Token): boolean {
if (this.#skipping === 0) return false;
if (token.name === "startObject" || token.name === "startArray")
this.#skipping += 1;
else if (token.name === "endObject" || token.name === "endArray")
this.#skipping -= 1;
return true;
}
#consume(token: Token): void {
if (this.#skip(token) || this.#assemble(token)) return;
switch (token.name) {
case "startKey":
this.#inKey = true;
return;
case "endKey":
this.#key = this.#text;
this.#text = "";
this.#inKey = false;
return;
case "startString":
this.#aim("string");
return;
case "endString":
if (this.#target !== undefined)
this.#store(detached(this.#text), "string");
this.#text = "";
return;
case "startNumber":
this.#aim("number");
return;
case "endNumber":
this.#store(this.#text, "number");
this.#text = "";
return;
case "nullValue":
this.#aim("null");
this.#store(null, "literal");
return;
case "trueValue":
case "falseValue":
this.#aim("boolean");
this.#store(token.value, "literal");
return;
case "startObject":
case "startArray":
this.#open(token.name === "startObject" ? "object" : "array");
return;
case "endObject":
case "endArray":
this.#close();
return;
default:
throw new Error(`unexpected JSON ${token.name}`);
}
}
/** Append a scalar fragment within its bound; false for other tokens. */
#assemble(token: Token): boolean {
if (token.name !== "stringChunk" && token.name !== "numberChunk")
return false;
const chunk = token.value;
if (this.#inKey) {
// A key longer than every kept field name is truncated unmatched.
if (this.#text.length <= MAX_TOKEN_CODE_UNITS)
this.#text += chunk.slice(
0,
MAX_TOKEN_CODE_UNITS + 1 - this.#text.length,
);
} else if (this.#target !== undefined) {
this.#text += chunk;
if (token.name === "stringChunk")
this.#charge(chunk.length * 2, this.#text.length);
else if (this.#text.length > MAX_TOKEN_CODE_UNITS)
throw new Error(`${this.#target} is not a number Kuna writes`);
}
return true;
}
/** Decide where a scalar value goes, before any of it is assembled. */
#aim(kind: "string" | "number" | "null" | "boolean"): void {
const frame = this.#frames.at(-1);
const key = this.#key!;
this.#key = undefined;
this.#targetIsAddress = false;
if (frame === undefined)
throw new Error(`${this.label} is not one JSON object`);
switch (frame.kind) {
case "root":
if (this.document.rows.has(key) || this.document.sections.has(key))
throw new Error(`${this.label} member ${key} is not a container`);
this.#target = this.#kept(frame.values, key, this.document.header);
return;
case "section":
this.#target = this.#kept(frame.values, key, frame.fields);
return;
case "rows":
throw new Error(`${frame.name} row is not an object`);
case "row":
if (frame.spec.empty.has(key))
throw new Error(`${frame.member} row ${key} is not an array`);
if (frame.spec.nulls.has(key)) {
if (kind !== "null")
throw new Error(`${frame.member} row ${key} must be null`);
this.#target = this.#kept(frame.values, key, frame.spec.nulls);
return;
}
if (frame.spec.addresses.has(key)) {
if (kind !== "number" && kind !== "null")
throw new Error(`invalid numeric address in ${key}`);
this.#target = this.#kept(frame.values, key, frame.spec.addresses);
this.#targetIsAddress = kind === "number";
return;
}
this.#target = this.#kept(frame.values, key, frame.spec.fields);
return;
case "empty":
throw new Error(`${frame.field} must be empty`);
}
}
/** The key a kept field is stored under, or undefined to discard it. */
#kept(
values: Record<string, unknown>,
key: string,
fields: ReadonlySet<string>,
): string | undefined {
if (!fields.has(key)) return undefined;
this.#claim(values, key);
return key;
}
#claim(values: Record<string, unknown>, key: string): void {
if (Object.hasOwn(values, key))
throw new Error(`${this.label} repeats ${key}`);
}
#store(
value: string | boolean | null,
kind: "string" | "number" | "literal",
): void {
const key = this.#target;
if (key === undefined) return;
this.#target = undefined;
this.#values()[key] = this.#targetIsAddress
? kunaAddressFromJsonNumber(value as string, key)
: kind === "number"
? Number(value)
: value;
}
#values(): Record<string, unknown> {
const frame = this.#frames.at(-1);
if (frame === undefined || frame.kind === "rows" || frame.kind === "empty")
throw new Error(`${this.label} value has no member`);
return frame.values;
}
/** Open a root member: rows, a section, or a value this reader skips. */
#openMember(
kind: "object" | "array",
key: string,
root: Record<string, unknown>,
): void {
const rows = this.document.rows.get(key);
const section = this.document.sections.get(key);
if (rows !== undefined) {
if (kind !== "array" || this.#rowsSeen.has(key))
throw new Error(`${this.label} rows ${key} are not one array`);
this.#frames.push({ kind: "rows", name: key, spec: rows });
} else if (section !== undefined) {
if (kind !== "object") throw new Error(`${key} is not an object`);
this.#claim(root, key);
const values: Record<string, unknown> = {};
root[key] = values;
this.#frames.push({
kind: "section",
name: key,
fields: section,
values,
});
} else if (this.document.header.has(key))
throw new Error(`${this.label} ${key} is not a scalar`);
else this.#skipping = 1;
}
#open(kind: "object" | "array"): void {
const frame = this.#frames.at(-1);
const key = this.#key;
this.#key = undefined;
if (frame === undefined) {
if (kind !== "object" || this.#closed)
throw new Error(`${this.label} is not one JSON object`);
this.#frames.push({ kind: "root", values: this.#header });
return;
}
switch (frame.kind) {
case "root":
this.#openMember(kind, key!, frame.values);
return;
case "rows":
if (kind !== "object")
throw new Error(`${frame.name} row is not an object`);
this.#frames.push({
kind: "row",
member: frame.name,
spec: frame.spec,
values: {},
});
return;
case "row":
if (frame.spec.empty.has(key!)) {
if (kind !== "array")
throw new Error(`${frame.member} row ${key!} is not an array`);
this.#claim(frame.values, key!);
this.#frames.push({ kind: "empty", field: key! });
} else if (
frame.spec.fields.has(key!) ||
frame.spec.addresses.has(key!) ||
frame.spec.nulls.has(key!)
)
throw new Error(`${frame.member} row ${key!} is not a scalar`);
else this.#skipping = 1;
return;
case "section":
if (frame.fields.has(key!))
throw new Error(`${frame.name} ${key!} is not a scalar`);
this.#skipping = 1;
return;
case "empty":
throw new Error(`${frame.field} must be empty`);
}
}
#close(): void {
const frame = this.#frames.pop();
switch (frame?.kind) {
case "root":
this.#closed = true;
return;
case "rows":
this.#rowsSeen.add(frame.name);
return;
case "row":
this.#rows += 1;
this.#charge(ROW_OVERHEAD_BYTES, 0);
this.acceptRow(frame.member, frame.values);
return;
case "empty": {
const row = this.#frames.at(-1);
if (row?.kind === "row") row.values[frame.field] = [];
return;
}
default:
return;
}
}
/** Admit growth against live headroom rather than a fixed document size. */
#charge(bytes: number, assemblingCodeUnits: number): void {
this.#projectedBytes += bytes;
if (this.#projectedBytes < this.#nextAdmission) return;
const heap = getHeapStatistics();
// Reserve the next interval, the owner's per-row references, and a flat
// copy of the string still being assembled.
const requiredBytes =
ADMISSION_INTERVAL_BYTES +
this.#rows * ROW_REFERENCE_BYTES +
assemblingCodeUnits * 2;
if (requiredBytes > heap.total_available_size)
throw new AnalysisResourceConstraintError(
this.producer,
"memory",
`Insufficient heap headroom to retain more of ${this.label} after ${String(this.#rows)} rows`,
{
retained_rows: this.#rows,
projected_retained_bytes: this.#projectedBytes,
required_headroom_bytes: requiredBytes,
available_heap_bytes: heap.total_available_size,
heap_size_limit_bytes: heap.heap_size_limit,
},
{
remediationAction:
"Close other targets in this REA process, or start REA with a larger Node.js heap (--max-old-space-size), then reopen the target.",
},
);
this.#nextAdmission = this.#projectedBytes + ADMISSION_INTERVAL_BYTES;
}
}
+3 -2
View File
@@ -1,6 +1,7 @@
/** Shared buffered-text capacity for a subprocess answer or one cached source facet. */
export const KUNA_FUNCTION_TEXT_BYTES = 16 * 1024 * 1024;
/** One buffered, retained string scan; independent of decompilation. */
export const KUNA_STRING_OUTPUT_BYTES = 16 * 1024 * 1024;
/** Kuna's notes and summary lines for one run; those of a large image stay far below this. */
export const KUNA_DIAGNOSTIC_BYTES = 8 * 1024 * 1024;
export const KUNA_STRING_MIN_LENGTH = 5;
+3 -4
View File
@@ -22,6 +22,7 @@ import {
type KunaProcessLauncher,
} from "./KunaCommand.js";
import type { KunaInstallation } from "./KunaInstallation.js";
import { KUNA_DIAGNOSTIC_BYTES } from "./KunaLimits.js";
import {
parseKunaExportSummary,
parseKunaInventory,
@@ -36,9 +37,6 @@ import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
/** Operation name every export and cache failure reports. */
export const KUNA_EXPORT_OPERATION = "kuna:decompile-project";
/** Kuna prints one summary line per export; notes on a large image stay far below this. */
const DIAGNOSTIC_BYTES = 8 * 1024 * 1024;
const INVENTORY_FILE = "functions.json";
/** Identity of one file an export consists of. */
@@ -258,7 +256,8 @@ export const exportKunaProject = async (
"--jobs",
String(configuration.jobs),
],
DIAGNOSTIC_BYTES,
// Kuna prints one summary line per export on stdout.
KUNA_DIAGNOSTIC_BYTES,
);
if (!exported.ok) return exported.outcome;
+43 -1
View File
@@ -1,8 +1,13 @@
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { err, type Result } from "../domain/result.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { matchRegexValues } from "../process/RegexMatcher.js";
import type { KunaJsonDocumentReader } from "./KunaJsonStream.js";
import { KUNA_DIAGNOSTIC_BYTES } from "./KunaLimits.js";
import { KunaRunSlots } from "./KunaRunSlots.js";
import type {
KunaTargetCommands,
@@ -62,6 +67,43 @@ export class KunaQueryWork {
}
}
/**
* Run a whole-program command whose stdout `reader` validates as it
* arrives. A rejected document stops Kuna and reports why; diagnostics
* beyond their buffer recur for this target and executable, so they are
* passed to `retain` for the session to keep.
*/
async scan<Parsed>(
request: Omit<
KunaTargetCommandRequest,
"releaseRun" | "outputBytes" | "stdout" | "signal"
>,
reader: KunaJsonDocumentReader<Parsed>,
signal: AbortSignal,
retain: (failure: AnalysisError) => void,
): Promise<Result<Parsed, AnalysisError>> {
const run = await this.run({
...request,
outputBytes: KUNA_DIAGNOSTIC_BYTES,
stdout: reader,
signal: AbortSignal.any([signal, reader.rejected]),
});
if (run.ok) return reader.finish(run.value.input);
const rejection = reader.rejection;
if (
rejection !== undefined &&
run.error instanceof AnalysisCancelledError &&
!signal.aborted
)
return err(rejection);
if (
run.error instanceof AnalysisResourceConstraintError &&
run.error.resource === "memory"
)
retain(run.error);
return run;
}
/** Bound inventory copies and regex workers; close cancels and drains both. */
match(input: RegexQuery): ReturnType<typeof matchRegexValues> {
const signal = AbortSignal.any([
+156 -79
View File
@@ -2,22 +2,16 @@ import { createHash } from "node:crypto";
import { z } from "zod";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareKunaAddresses } from "./KunaAddress.js";
import { parseKunaJson } from "./KunaJson.js";
import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js";
/** Raw JSON budgets also bound the materialized indexes; no decompiled bodies are admitted. */
export const KUNA_GRAPH_OUTPUT_BYTES = 32 * 1024 * 1024;
/** The raw xref budget also bounds its materialized rows. */
export const KUNA_XREF_OUTPUT_BYTES = 16 * 1024 * 1024;
const addressKeys = new Set([
"address",
"callerAddress",
"calleeAddress",
"forwardsTo",
"from_address",
"to_address",
]);
const addressKeys = new Set(["address", "from_address", "to_address"]);
const address = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u);
const count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const kind = z.enum(["call", "jump", "data", "read", "write"]);
@@ -29,8 +23,6 @@ const graphHeader = z.object({
functionCount: count,
edgeCount: count,
}),
functions: z.array(z.unknown()),
edges: z.array(z.unknown()),
});
const graphNode = z.object({
address,
@@ -60,75 +52,160 @@ export interface KunaCallGraph {
readonly callees: ReadonlyMap<string, readonly string[]>;
}
/** Validate once at the producer boundary and retain only facts used by queries. */
export const parseKunaCallGraph = (
text: string,
input: string,
): Result<KunaCallGraph, string> => {
try {
const header = graphHeader.parse(
parseKunaJson(text, KUNA_GRAPH_OUTPUT_BYTES, addressKeys),
);
if (header.binary.sourcePath !== input)
throw new Error("graph names a different input");
if (
header.binary.functionCount !== header.functions.length ||
header.binary.edgeCount !== header.edges.length
)
throw new Error("graph counts disagree with examined rows");
const nodes = new Map<string, KunaGraphNode>();
let hasIndirectCalls = false;
for (const raw of header.functions) {
const node = graphNode.parse(raw);
if (nodes.has(node.address))
throw new Error("graph repeats a function address");
nodes.set(node.address, node);
hasIndirectCalls ||= node.hasIndirectCalls;
}
const callers = new Map<string, string[]>();
const callees = new Map<string, string[]>();
const pairs = new Set<string>();
const orders = new Map<string, Set<number>>();
for (const raw of header.edges) {
const edge = graphEdge.parse(raw);
if (!nodes.has(edge.callerAddress) || !nodes.has(edge.calleeAddress))
throw new Error("graph edge has an unknown endpoint");
const pair = `${edge.callerAddress}:${edge.calleeAddress}`;
if (pairs.has(pair)) throw new Error("graph repeats an edge");
pairs.add(pair);
const order = orders.get(edge.callerAddress) ?? new Set<number>();
if (order.has(edge.calleeOrder))
throw new Error("graph repeats a callee order");
order.add(edge.calleeOrder);
orders.set(edge.callerAddress, order);
if (edge.kind !== "call") continue;
const incoming = callers.get(edge.calleeAddress) ?? [];
incoming.push(edge.callerAddress);
callers.set(edge.calleeAddress, incoming);
const outgoing = callees.get(edge.callerAddress) ?? [];
outgoing.push(edge.calleeAddress);
callees.set(edge.callerAddress, outgoing);
}
for (const order of orders.values())
for (let index = 0; index < order.size; index += 1)
if (!order.has(index))
throw new Error("graph callee orders are incomplete");
for (const list of [...callers.values(), ...callees.values()])
list.sort(compareKunaAddresses);
return ok({
nodes,
callers,
callees,
edgeCount: header.edges.length,
hasIndirectCalls,
bytes: Buffer.byteLength(text),
sha256: createHash("sha256").update(text).digest("hex"),
});
} catch (cause: unknown) {
return err(cause instanceof Error ? cause.message : String(cause));
}
const fieldsOf = (schema: z.ZodObject, excluded: readonly string[]) =>
new Set(Object.keys(schema.shape).filter((key) => !excluded.includes(key)));
const GRAPH_DOCUMENT = {
header: new Set(["schemaVersion"]),
sections: new Map([
["binary", new Set(Object.keys(graphHeader.shape.binary.shape))],
]),
rows: new Map([
[
"functions",
{
fields: fieldsOf(graphNode, [
"address",
"forwardsTo",
"codeC",
"assembly",
"error",
]),
addresses: new Set(["address", "forwardsTo"]),
empty: new Set<string>(),
// `--functions ''` requests no bodies; one is refused unassembled.
nulls: new Set(["codeC", "assembly", "error"]),
},
],
[
"edges",
{
fields: fieldsOf(graphEdge, ["callerAddress", "calleeAddress"]),
addresses: new Set(["callerAddress", "calleeAddress"]),
empty: new Set<string>(),
nulls: new Set<string>(),
},
],
]),
};
/**
* Validates `kuna decompile-graph --functions ''` as Kuna writes it and
* retains only the facts call queries use.
*/
export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
readonly #nodes = new Map<string, KunaGraphNode>();
/** Callees of every edge by caller, which also detects repeated edges. */
readonly #targets = new Map<string, Set<string>>();
/** Callee orders by caller; each caller's must be 0..n-1. */
readonly #orders = new Map<string, Set<number>>();
readonly #callers = new Map<string, string[]>();
readonly #callees = new Map<string, string[]>();
#edgeCount = 0;
#hasIndirectCalls = false;
constructor() {
super("kuna:call-graph", "Kuna's call graph", GRAPH_DOCUMENT);
}
override finish(input: string): Result<KunaCallGraph, AnalysisError> {
const completed = this.complete();
if (!completed.ok) return completed;
const header = graphHeader.safeParse(completed.value.header);
if (!header.success)
return err(this.unusable("the graph header is not Kuna's schema 4"));
if (header.data.binary.sourcePath !== input)
return err(this.unusable("graph names a different input"));
if (
header.data.binary.functionCount !== this.#nodes.size ||
header.data.binary.edgeCount !== this.#edgeCount
)
return err(this.unusable("graph counts disagree with examined rows"));
const invalid = this.#invalidEdges();
// These indexes only validate edges; queries never read them.
this.#targets.clear();
this.#orders.clear();
if (invalid !== undefined) return err(this.unusable(invalid));
for (const index of [this.#callers, this.#callees])
for (const list of index.values()) list.sort(compareKunaAddresses);
return ok({
nodes: this.#nodes,
callers: this.#callers,
callees: this.#callees,
edgeCount: this.#edgeCount,
hasIndirectCalls: this.#hasIndirectCalls,
bytes: completed.value.bytes,
sha256: completed.value.sha256,
});
}
protected override acceptRow(
member: string,
fields: Readonly<Record<string, unknown>>,
): void {
if (member === "edges") {
this.#index(parseKunaRow(graphEdge, "graph edge", fields));
return;
}
const node = parseKunaRow(graphNode, "graph function", fields);
if (this.#nodes.has(node.address))
throw new Error("graph repeats a function address");
this.#nodes.set(node.address, node);
this.#hasIndirectCalls ||= node.hasIndirectCalls;
}
protected override discardRows(): void {
for (const index of [
this.#nodes,
this.#targets,
this.#orders,
this.#callers,
this.#callees,
])
index.clear();
}
/**
* Index one edge as it arrives, so the working set grows under the row
* admission instead of after it; endpoints are checked once every node is
* known.
*/
#index(edge: z.infer<typeof graphEdge>): void {
const { callerAddress: caller, calleeAddress: callee } = edge;
this.#edgeCount += 1;
const targets = this.#targets.get(caller) ?? new Set<string>();
if (targets.has(callee)) throw new Error("graph repeats an edge");
targets.add(callee);
this.#targets.set(caller, targets);
const order = this.#orders.get(caller) ?? new Set<number>();
if (order.has(edge.calleeOrder))
throw new Error("graph repeats a callee order");
order.add(edge.calleeOrder);
this.#orders.set(caller, order);
if (edge.kind !== "call") return;
const incoming = this.#callers.get(callee) ?? [];
incoming.push(caller);
this.#callers.set(callee, incoming);
const outgoing = this.#callees.get(caller) ?? [];
outgoing.push(callee);
this.#callees.set(caller, outgoing);
}
/** Why the edges contradict the nodes, if they do. */
#invalidEdges(): string | undefined {
for (const [caller, targets] of this.#targets) {
if (!this.#nodes.has(caller)) return "graph edge has an unknown endpoint";
for (const callee of targets)
if (!this.#nodes.has(callee))
return "graph edge has an unknown endpoint";
}
for (const order of this.#orders.values())
for (let index = 0; index < order.size; index += 1)
if (!order.has(index)) return "graph callee orders are incomplete";
return undefined;
}
}
const xrefFunction = z.object({
name: z.string().min(1),
address,
+20 -29
View File
@@ -10,9 +10,8 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { err, ok, type Result } from "../domain/result.js";
import type { KunaInstallation } from "./KunaInstallation.js";
import {
KUNA_GRAPH_OUTPUT_BYTES,
KUNA_XREF_OUTPUT_BYTES,
parseKunaCallGraph,
KunaCallGraphReader,
parseKunaIncomingReferences,
type KunaCallGraph,
type KunaGraphNode,
@@ -108,33 +107,25 @@ export class KunaReferenceQueries {
}
if (this.#pendingGraph === undefined) {
const pending = this.work.start<KunaCallGraph>(
async (producerSignal) => {
const run = await this.work.run({
installation,
operation: "kuna:call-graph",
arguments: (input) => [
"decompile-graph",
input,
"--functions",
"",
],
timeoutMs: installation.configuration.projectTimeoutMs,
outputBytes: KUNA_GRAPH_OUTPUT_BYTES,
signal: producerSignal,
});
if (!run.ok) {
if (
run.error instanceof AnalysisResourceConstraintError &&
run.error.resource === "memory"
)
this.#graphFailure = run.error;
return run;
}
return this.#parsed(
parseKunaCallGraph(run.value.stdout.text, run.value.input),
"call graph",
);
},
(producerSignal) =>
this.work.scan(
{
installation,
operation: "kuna:call-graph",
arguments: (input) => [
"decompile-graph",
input,
"--functions",
"",
],
timeoutMs: installation.configuration.projectTimeoutMs,
},
new KunaCallGraphReader(),
producerSignal,
(failure) => {
this.#graphFailure = failure;
},
),
(value) => {
this.#graph = value;
},
+85 -54
View File
@@ -1,20 +1,14 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { analysisStringSchema } from "../domain/hopperValues.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareKunaAddresses } from "./KunaAddress.js";
import { parseKunaJson } from "./KunaJson.js";
import {
KUNA_STRING_OUTPUT_BYTES,
KUNA_STRING_MIN_LENGTH,
} from "./KunaLimits.js";
import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js";
import { KUNA_STRING_MIN_LENGTH } from "./KunaLimits.js";
const count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const address = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/u);
const addressKeys = new Set(["address"]);
const header = z.object({
binary: z.string(),
encoding: z.literal("all"),
@@ -25,7 +19,6 @@ const header = z.object({
scanned: z.enum(["sections", "segments"]),
xrefs: z.literal(false),
count,
strings: z.array(z.unknown()),
});
const row = z.object({
address,
@@ -40,6 +33,28 @@ const row = z.object({
functions: z.tuple([]),
});
const ROWS = "strings";
const DOCUMENT = {
header: new Set(Object.keys(header.shape)),
sections: new Map(),
rows: new Map([
[
ROWS,
{
fields: new Set(
Object.keys(row.shape).filter(
(key) => key !== "address" && key !== "functions",
),
),
addresses: new Set(["address"]),
// Rows are scanned with --no-xrefs, so `functions` must be empty.
empty: new Set(["functions"]),
nulls: new Set<string>(),
},
],
]),
} as const;
/** JSON text omits terminators; native lengths describe the encoded source. */
const validateStringFacts = (entry: z.infer<typeof row>): void => {
let characters = 0;
@@ -84,43 +99,30 @@ export interface KunaStringInventory {
readonly scanned: "sections" | "segments";
}
/** Validate the producer's complete scan before publishing any selected row. */
export const parseKunaStringInventory = (
text: string,
input: string,
): Result<KunaStringInventory, string> => {
try {
const document = header.parse(
parseKunaJson(text, KUNA_STRING_OUTPUT_BYTES, addressKeys),
);
if (document.binary !== input)
throw new Error("string inventory names a different input");
if (document.count !== document.strings.length)
throw new Error("string inventory count disagrees with examined rows");
const seen = new Set<string>();
const items = document.strings.map((value): KunaStringItem => {
const entry = row.parse(value);
validateStringFacts(entry);
if (entry.address !== entry.address_hex)
throw new Error("string address disagrees with its hex field");
const identity = `${entry.address}:${entry.encoding}`;
if (seen.has(identity))
throw new Error("string inventory repeats an identity");
seen.add(identity);
return {
address: entry.address,
value: entry.text,
string: {
encoding: entry.encoding,
encoding_status: "observed",
termination: entry.nul_terminated
? "present_or_not_required"
: "missing",
byte_length: entry.byte_length,
},
};
});
items.sort(
/** Validates `kuna strings --json` row by row as Kuna writes it. */
export class KunaStringInventoryReader extends KunaJsonDocumentReader<KunaStringInventory> {
readonly #items: KunaStringItem[] = [];
readonly #identities = new Set<string>();
constructor() {
super("kuna:strings", "Kuna's string inventory", DOCUMENT);
}
override finish(input: string): Result<KunaStringInventory, AnalysisError> {
const completed = this.complete();
if (!completed.ok) return completed;
const fields = header.safeParse(completed.value.header);
if (!fields.success)
return err(
this.unusable("the string inventory header is not Kuna's scan"),
);
if (fields.data.binary !== input)
return err(this.unusable("string inventory names a different input"));
if (fields.data.count !== this.#items.length)
return err(
this.unusable("string inventory count disagrees with examined rows"),
);
this.#items.sort(
(left, right) =>
compareKunaAddresses(left.address, right.address) ||
(left.string?.encoding ?? "").localeCompare(
@@ -129,12 +131,41 @@ export const parseKunaStringInventory = (
),
);
return ok({
items,
sha256: createHash("sha256").update(text).digest("hex"),
bytes: Buffer.byteLength(text),
scanned: document.scanned,
items: this.#items,
sha256: completed.value.sha256,
bytes: completed.value.bytes,
scanned: fields.data.scanned,
});
} catch (cause: unknown) {
return err(cause instanceof Error ? cause.message : String(cause));
}
};
protected override acceptRow(
_member: string,
fields: Readonly<Record<string, unknown>>,
): void {
const entry = parseKunaRow(row, "string", fields);
validateStringFacts(entry);
if (entry.address !== entry.address_hex)
throw new Error("string address disagrees with its hex field");
const identity = `${entry.address}:${entry.encoding}`;
if (this.#identities.has(identity))
throw new Error("string inventory repeats an identity");
this.#identities.add(identity);
this.#items.push({
address: entry.address,
value: entry.text,
string: {
encoding: entry.encoding,
encoding_status: "observed",
termination: entry.nul_terminated
? "present_or_not_required"
: "missing",
byte_length: entry.byte_length,
},
});
}
protected override discardRows(): void {
this.#items.length = 0;
this.#identities.clear();
}
}
+27 -47
View File
@@ -2,8 +2,6 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import {
analysisSearchPredicate,
@@ -16,12 +14,9 @@ import { normalizeKunaAddress } from "./KunaAddress.js";
import type { KunaInstallation } from "./KunaInstallation.js";
import type { KunaPendingQuery, KunaQueryWork } from "./KunaQueryWork.js";
import { kunaQueryFailureForCaller } from "./KunaQueryErrors.js";
import { KUNA_STRING_MIN_LENGTH } from "./KunaLimits.js";
import {
KUNA_STRING_MIN_LENGTH,
KUNA_STRING_OUTPUT_BYTES,
} from "./KunaLimits.js";
import {
parseKunaStringInventory,
KunaStringInventoryReader,
type KunaStringInventory,
type KunaStringItem,
} from "./KunaStringInventory.js";
@@ -129,46 +124,31 @@ export class KunaStringQueries {
}
if (this.#pending === undefined) {
const pending = this.work.start<KunaStringInventory>(
async (producerSignal) => {
const run = await this.work.run({
installation,
operation: "kuna:strings",
arguments: (input) => [
"strings",
input,
"--json",
"--encoding",
"all",
"--min-length",
String(KUNA_STRING_MIN_LENGTH),
"--termination",
"any",
"--no-xrefs",
],
timeoutMs: installation.configuration.projectTimeoutMs,
outputBytes: KUNA_STRING_OUTPUT_BYTES,
signal: producerSignal,
});
if (!run.ok) {
if (
run.error instanceof AnalysisResourceConstraintError &&
run.error.resource === "memory"
)
this.#failure = run.error;
return run;
}
const parsed = parseKunaStringInventory(
run.value.stdout.text,
run.value.input,
);
return parsed.ok
? parsed
: err(
new AnalysisOutputError("kuna:strings", parsed.error, {
userMessage: `Kuna's string inventory cannot be used: ${parsed.error}`,
}),
);
},
(producerSignal) =>
this.work.scan(
{
installation,
operation: "kuna:strings",
arguments: (input) => [
"strings",
input,
"--json",
"--encoding",
"all",
"--min-length",
String(KUNA_STRING_MIN_LENGTH),
"--termination",
"any",
"--no-xrefs",
],
timeoutMs: installation.configuration.projectTimeoutMs,
},
new KunaStringInventoryReader(),
producerSignal,
(failure) => {
this.#failure = failure;
},
),
(value) => {
this.#inventory = value;
},
+3
View File
@@ -1,5 +1,6 @@
import { basename, join } from "node:path";
import { realpath } from "node:fs/promises";
import type { Writable } from "node:stream";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
@@ -44,6 +45,8 @@ export interface KunaTargetCommandRequest {
readonly operation: string;
readonly arguments: (input: string) => readonly string[];
readonly outputBytes: number;
/** Parses stdout as it arrives instead of buffering it in the snapshot. */
readonly stdout?: Writable;
readonly timeoutMs: number;
readonly signal: AbortSignal;
/** Admission remains owned until the native process is proven stopped. */
+58 -11
View File
@@ -1,3 +1,6 @@
import type { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
import type {
OwnedProviderProcessSpawnOptions,
ProviderProcessSnapshot,
@@ -13,6 +16,7 @@ import {
type OwnedProcessGroup,
type ProcessCleanupFailure,
} from "./ProcessOwnership.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import {
ProviderStartupDeadline,
waitForAbortableDelay,
@@ -52,15 +56,25 @@ export const ownedCommandResources = (
`process-group:${ownership.processGroupId}`,
];
/** Output handling for one owned command. */
interface OwnedCommandLimits {
/** Retained stderr bytes, plus stdout bytes unless a sink consumes stdout. */
readonly diagnosticBytes: number;
/** Accept an ordinary nonzero exit after output closes without other process errors. */
readonly acceptNonZeroExit?: boolean;
/**
* Receives stdout instead of the retained snapshot, for output parsed as it
* arrives. The command completes only after the sink finishes. The sink
* records its own rejections and keeps accepting, so the command's outcome
* stays authoritative; a failing stream is a collection failure.
*/
readonly stdout?: Writable;
}
/** Execute a single owned process with independent cleanup and bounded diagnostic retention. */
export const runOwnedCommand = async (
spawn: OwnedProviderProcessSpawnOptions,
limits: {
readonly timeoutMs: number;
readonly diagnosticBytes: number;
/** Accept an ordinary nonzero exit after output closes without other process errors. */
readonly acceptNonZeroExit?: boolean;
},
limits: OwnedCommandLimits & { readonly timeoutMs: number },
options: {
readonly signal?: AbortSignal | undefined;
/** Synchronously accept unresolved cleanup ownership; execution still returns its original outcome. Must not throw. */
@@ -96,11 +110,7 @@ export const runOwnedCommand = async (
const collectOwnedCommand = async (
spawn: OwnedProviderProcessSpawnOptions,
limits: {
readonly diagnosticBytes: number;
/** Accept an ordinary nonzero exit after output closes without other process errors. */
readonly acceptNonZeroExit?: boolean;
},
limits: OwnedCommandLimits,
launcher: (
input: OwnedProviderProcessSpawnOptions,
) => Promise<SpawnedOwnedProviderProcess>,
@@ -143,6 +153,7 @@ const collectOwnedCommand = async (
(() => cleanupOwnedProcessGroup(launched.ownership)),
},
{
captureStdout: limits.stdout === undefined,
maxDiagnosticBytes: limits.diagnosticBytes,
onDiagnostic: (event) => {
if (event.type === "output" && event.truncated === true)
@@ -151,6 +162,16 @@ const collectOwnedCommand = async (
},
},
);
// A command that fails or is interrupted destroys its sink with its stdout.
const abandoned = new AbortController();
const consumed = consumeStdout(
launched.process.stdout,
limits.stdout,
AbortSignal.any([signal, abandoned.signal]),
);
void consumed.then((failed) => {
processFailure ??= failed;
});
let failure: OwnedCommandFailure | undefined;
try {
while (!(await supervisor.waitForOutputClose(10))) {
@@ -173,6 +194,9 @@ const collectOwnedCommand = async (
});
await waitForAbortableDelay(25, signal);
}
// Output has closed, but the sink may still be parsing what it buffered.
const sinkFailure = await waitForAbortable(consumed, signal);
if (sinkFailure !== ABORTED) processFailure ??= sinkFailure;
const snapshot = supervisor.snapshot();
const interruption = deadline.interruption;
if (interruption !== undefined)
@@ -220,6 +244,8 @@ const collectOwnedCommand = async (
{ cause },
);
}
// A finished sink ignores this; an unfinished one is destroyed.
abandoned.abort();
const stopped = await supervisor.stop();
const snapshot = supervisor.snapshot();
if (stopped.status === "incomplete" && retainCleanup !== undefined)
@@ -261,3 +287,24 @@ const collectOwnedCommand = async (
throw new OwnedCommandFailure("cancelled", "Command cancelled.", snapshot);
return snapshot;
};
/**
* Pipe stdout into its sink until `signal` aborts, which destroys both; settles
* with a failure message, never rejects.
*/
const consumeStdout = (
stdout: Readable | null,
sink: Writable | undefined,
signal: AbortSignal,
): Promise<string | undefined> => {
if (sink === undefined) return Promise.resolve(undefined);
if (stdout === null) {
sink.destroy();
return Promise.resolve("stdout stream is unavailable");
}
return pipeline(stdout, sink, { signal }).then(
() => undefined,
(cause: unknown) =>
`stdout stream failed: ${cause instanceof Error ? cause.message : String(cause)}`,
);
};