fix(native): bound retained observations and preserve failure evidence

This commit is contained in:
morluto
2026-10-09 01:55:12 +08:00
parent d6cc9ca3a6
commit 7c323870c2
15 changed files with 1045 additions and 36 deletions
+111 -15
View File
@@ -15,6 +15,7 @@ import type {
AnalysisCleanupObservation,
AnalysisError,
} from "../domain/analysisErrorBase.js";
import type { NativeCallPartialObservation } from "../domain/native/nativeCallPartialObservation.js";
import {
nativeCallEventSchema,
nativeCodeLocationSchema,
@@ -40,6 +41,12 @@ import {
} from "../process/ProviderDeadline.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import { resolveXcrunTool, type ResolvedTool } from "./CommandRunner.js";
import {
readLldbObservationJournal,
readBoundedPrefix,
readPartialCapture,
projectLldbPartialObservation,
} from "./LldbRetainedObservations.js";
const OPERATION = "observe_native_calls";
const PROVIDER = "native-macos";
@@ -82,6 +89,7 @@ const tracedSchema = z.strictObject({
stable: z.boolean(),
}),
resource_limit_reached: z.boolean(),
breakpoint_locations_truncated: z.boolean().optional(),
target_output: z.strictObject({
stdout_bytes: z.number().int().nonnegative(),
stderr_bytes: z.number().int().nonnegative(),
@@ -193,6 +201,7 @@ export class LldbCallTracer implements NativeCallTracer {
stderr: join(directory, "stderr"),
stdoutCapture: join(directory, "stdout.capture"),
stderrCapture: join(directory, "stderr.capture"),
observations: join(directory, "observations.jsonl"),
};
const { input } = request;
await writeFile(
@@ -221,6 +230,7 @@ export class LldbCallTracer implements NativeCallTracer {
result_path: paths.result,
pid_path: paths.pid,
identity_ack_path: paths.identityAck,
observation_path: paths.observations,
}),
{ mode: 0o600 },
);
@@ -271,26 +281,56 @@ export class LldbCallTracer implements NativeCallTracer {
: {
reason: cleanupDetails.join("; "),
resources: [
`native-target:${String((await readTargetPid(paths.pid)) ?? "unknown")}`,
...(exited.cleanupFailure === undefined
? []
: ["lldb-process-group"]),
...(terminated
? []
: [
`native-target:${String((await readTargetPid(paths.pid)) ?? "unknown")}`,
]),
],
};
const partialReason =
exited.kind === "cancelled"
? "cancelled"
: exited.kind === "timeout"
? "timeout"
: exited.cleanupFailure !== undefined
? "cleanup-failure"
: "tracer-failure";
const getPartialObservation = (
reason: NativeCallPartialObservation["coverage"]["reason"] = partialReason,
): Promise<NativeCallPartialObservation> =>
partialNativeObservation({
request,
pidPath: paths.pid,
stdoutPath: paths.stdoutCapture,
stderrPath: paths.stderrCapture,
observationPath: paths.observations,
version: output?.status === "traced" ? output.version : null,
reason,
});
if (exited.kind === "cancelled")
return err(
new AnalysisCancelledError(
OPERATION,
lifecycleCleanup === undefined
? undefined
: { cleanup: lifecycleCleanup },
),
new AnalysisCancelledError(OPERATION, {
...(lifecycleCleanup === undefined
? {}
: { cleanup: lifecycleCleanup }),
partialObservation: await getPartialObservation(),
}),
);
if (exited.kind === "timeout")
return err(
new AnalysisTimeoutError(
OPERATION,
input.duration_ms + DEADLINE_GRACE_MS,
lifecycleCleanup === undefined
? undefined
: { cleanup: lifecycleCleanup },
{
...(lifecycleCleanup === undefined
? {}
: { cleanup: lifecycleCleanup }),
partialObservation: await getPartialObservation(),
},
),
);
if (exited.cleanupFailure !== undefined)
@@ -307,6 +347,7 @@ export class LldbCallTracer implements NativeCallTracer {
? {}
: { target_cleanup: lifecycleCleanup }),
},
partialObservation: await getPartialObservation(),
}),
);
if (output === undefined)
@@ -320,13 +361,16 @@ export class LldbCallTracer implements NativeCallTracer {
? {}
: { target_cleanup: lifecycleCleanup }),
},
partialObservation: await getPartialObservation(),
...(lifecycleCleanup === undefined
? {}
: { cleanup: lifecycleCleanup }),
}),
);
if (output.status !== "traced") {
return err(tracerFailure(output, lifecycleCleanup));
return err(
tracerFailure(output, lifecycleCleanup, await getPartialObservation()),
);
}
const stdout = await capturedOutput(
paths.stdoutCapture,
@@ -340,9 +384,11 @@ export class LldbCallTracer implements NativeCallTracer {
output.target_output.stderr_truncated,
output.target_output.stderr_complete,
);
if (!stdout.ok || !stderr.ok)
if (!stdout.ok || !stderr.ok) {
const partial = await getPartialObservation("capture-failure");
return err(
new ProviderAdapterError(PROVIDER, OPERATION, {
partialObservation: partial,
diagnostics: {
reason: "LLDB target output capture could not be read",
...(stdout.ok ? {} : { stdout_capture_error: stdout.error }),
@@ -351,8 +397,12 @@ export class LldbCallTracer implements NativeCallTracer {
? {}
: { target_cleanup: lifecycleCleanup }),
},
...(lifecycleCleanup === undefined
? {}
: { cleanup: lifecycleCleanup }),
}),
);
}
return ok({
debugger: { ...lldb, version: output.version },
run: output,
@@ -378,8 +428,12 @@ const tracerFailure = (
readonly error: string | null;
},
cleanup?: AnalysisCleanupObservation,
partialObservation?: NativeCallPartialObservation,
): AnalysisError => {
const options = cleanup === undefined ? undefined : { cleanup };
const options = {
...(cleanup === undefined ? {} : { cleanup }),
...(partialObservation === undefined ? {} : { partialObservation }),
};
const message = output.error ?? "no LLDB error text";
if (output.status === "target-integrity-error")
return new EvidenceIntegrityError(
@@ -422,6 +476,44 @@ const tracerFailure = (
);
};
const partialNativeObservation = async (options: {
readonly request: Parameters<NativeCallTracer["trace"]>[0];
readonly pidPath: string;
readonly stdoutPath: string;
readonly stderrPath: string;
readonly observationPath: string;
readonly version: string | null;
readonly reason: NativeCallPartialObservation["coverage"]["reason"];
}): Promise<NativeCallPartialObservation> => {
const [journal, pid, stdout, stderr] = await Promise.all([
readLldbObservationJournal(options.observationPath),
readTargetPid(options.pidPath),
readPartialCapture(options.stdoutPath),
readPartialCapture(options.stderrPath),
]);
return projectLldbPartialObservation({
target: {
path: options.request.executable,
sha256: options.request.expectedSha256,
architecture: options.request.architecture,
arguments: options.request.input.arguments,
environment: options.request.input.environment,
working_directory: options.request.input.working_directory ?? null,
},
pid,
stdout: stdout?.capture ?? null,
stderr: stderr?.capture ?? null,
version: options.version,
journal: journal.parsed,
journalLimitations: journal.limitations,
limitations: [
...(stdout?.limitations ?? []),
...(stderr?.limitations ?? []),
],
reason: options.reason,
});
};
const readTracerOutput = async (
path: string,
): Promise<z.infer<typeof tracerOutputSchema> | undefined> => {
@@ -447,8 +539,12 @@ const capturedOutput = async (
try {
handle = await open(path, "r");
const { size } = await handle.stat();
const buffer = Buffer.alloc(Math.min(size, MAX_OUTPUT_BYTES));
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
const captureHandle = handle;
const { buffer, bytesRead } = await readBoundedPrefix(
Math.min(size, MAX_OUTPUT_BYTES),
async (target, offset, length, position) =>
(await captureHandle.read(target, offset, length, position)).bytesRead,
);
const captured = {
text: buffer.subarray(0, bytesRead).toString("utf8"),
bytes: observedBytes,
+237
View File
@@ -0,0 +1,237 @@
import { open } from "node:fs/promises";
import { nativeCallEventSchema } from "../domain/native/nativeCallObservation.js";
import type { NativeCallPartialObservation } from "../domain/native/nativeCallPartialObservation.js";
/** Maximum journal size enforced by the LLDB bridge. */
export const LLDB_OBSERVATION_JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
const MAX_CAPTURE_BYTES = 1024 * 1024;
export interface ParsedLldbJournal {
readonly events: ReturnType<typeof nativeCallEventSchema.parse>[];
readonly otherStops: string[];
readonly limitations: string[];
}
export interface PartialCaptureRead {
readonly capture: NonNullable<
NativeCallPartialObservation["process"]["stdout"]
>;
readonly limitations: readonly string[];
}
/** Join safely retained journal and process evidence into its failure contract. */
export const projectLldbPartialObservation = (input: {
readonly target: NativeCallPartialObservation["target"];
readonly pid: number | undefined;
readonly stdout: NativeCallPartialObservation["process"]["stdout"];
readonly stderr: NativeCallPartialObservation["process"]["stderr"];
readonly version: string | null;
readonly journal: ParsedLldbJournal;
readonly journalLimitations?: readonly string[];
readonly limitations?: readonly string[];
readonly reason: NativeCallPartialObservation["coverage"]["reason"];
}): NativeCallPartialObservation => ({
kind: "native-call-observation",
target: input.target,
process: {
pid: input.pid ?? null,
stdout: input.stdout,
stderr: input.stderr,
other_stops: input.journal.otherStops,
},
debugger: { version: input.version },
events: input.journal.events,
coverage: { status: "partial", reason: input.reason },
limitations: [
"The LLDB run did not produce a complete native call observation result.",
"The target SHA-256 identifies the selected artifact; LLDB did not verify the bytes loaded into the process.",
"Captured output byte counts are observed lower bounds because LLDB did not report final stream counters.",
...input.journal.limitations,
...(input.journalLimitations ?? []),
...(input.limitations ?? []),
...(input.pid === undefined ? ["The target PID was unavailable."] : []),
...(input.stdout === null
? ["The target stdout capture was unavailable."]
: []),
...(input.stderr === null
? ["The target stderr capture was unavailable."]
: []),
],
});
/** Parse completed JSONL records while retaining valid records around bad ones. */
export const parseLldbObservationJournal = (
bytes: Uint8Array,
): ParsedLldbJournal => {
const completeText = Buffer.from(bytes).toString("utf8");
const newline = completeText.lastIndexOf("\n");
const hasTornTail = newline !== completeText.length - 1;
const events: ParsedLldbJournal["events"] = [];
const otherStops: string[] = [];
const limitations: string[] = [];
let malformedCount = 0;
let firstMalformedRow: number | undefined;
let start = 0;
let rowNumber = 0;
while (start <= newline && newline >= 0) {
const end = completeText.indexOf("\n", start);
if (end < 0 || end > newline) break;
const line = completeText.slice(start, end);
start = end + 1;
if (line.length === 0) continue;
rowNumber += 1;
const markMalformed = () => {
malformedCount += 1;
firstMalformedRow ??= rowNumber;
};
let row: unknown;
try {
row = JSON.parse(line);
} catch {
markMalformed();
continue;
}
if (
typeof row !== "object" ||
row === null ||
!("kind" in row) ||
typeof row.kind !== "string"
) {
markMalformed();
continue;
}
if (row.kind === "event" && "event" in row) {
const event = nativeCallEventSchema.safeParse(row.event);
if (event.success) events.push(event.data);
else markMalformed();
} else if (
row.kind === "other-stop" &&
"reason" in row &&
typeof row.reason === "string"
) {
otherStops.push(row.reason);
} else {
markMalformed();
}
}
if (malformedCount > 0)
limitations.push(
`${malformedCount} observation journal row(s) were malformed or invalid and ignored (first at row ${String(firstMalformedRow)}).`,
);
if (hasTornTail)
limitations.push(
"The final observation journal record was incomplete and was ignored.",
);
return { events, otherStops, limitations };
};
/** Keep reading a bounded prefix across short reads until EOF or the bound. */
export const readBoundedPrefix = async (
requestedBytes: number,
readChunk: (
buffer: Buffer,
offset: number,
length: number,
position: number,
) => Promise<number>,
): Promise<{ readonly buffer: Buffer; readonly bytesRead: number }> => {
const buffer = Buffer.alloc(requestedBytes);
let bytesRead = 0;
while (bytesRead < requestedBytes) {
const count = await readChunk(
buffer,
bytesRead,
requestedBytes - bytesRead,
bytesRead,
);
if (count === 0) break;
if (count > requestedBytes - bytesRead)
throw new Error("The bounded read returned more bytes than requested");
bytesRead += count;
}
return { buffer, bytesRead };
};
const readPrefix = (
handle: Awaited<ReturnType<typeof open>>,
requestedBytes: number,
) =>
readBoundedPrefix(
requestedBytes,
async (buffer, offset, length, position) =>
(await handle.read(buffer, offset, length, position)).bytesRead,
);
/** Read at most the bridge's journal bound, checking size before allocation. */
export const readLldbObservationJournal = async (
path: string,
): Promise<{
readonly parsed: ParsedLldbJournal;
readonly limitations: string[];
}> => {
let handle: Awaited<ReturnType<typeof open>> | undefined;
try {
handle = await open(path, "r");
const { size } = await handle.stat();
const length = Math.min(size, LLDB_OBSERVATION_JOURNAL_MAX_BYTES);
const { buffer, bytesRead } = await readPrefix(handle, length);
const parsed = parseLldbObservationJournal(buffer.subarray(0, bytesRead));
const limitations = [
...(size > LLDB_OBSERVATION_JOURNAL_MAX_BYTES
? [
"The observation journal exceeded 8 MiB; only its bounded prefix was read.",
]
: []),
...(bytesRead < length
? [
"The observation journal became shorter while being read; the available prefix was parsed.",
]
: []),
];
return {
parsed,
limitations,
};
} catch (cause: unknown) {
return {
parsed: { events: [], otherStops: [], limitations: [] },
limitations: [
`The observation journal could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
],
};
} finally {
await handle?.close().catch(() => undefined);
}
};
/** Retain an available output prefix without claiming an unreported total. */
export const readPartialCapture = async (
path: string,
): Promise<PartialCaptureRead | null> => {
let handle: Awaited<ReturnType<typeof open>> | undefined;
try {
handle = await open(path, "r");
const { size } = await handle.stat();
const length = Math.min(size, MAX_CAPTURE_BYTES);
const { buffer, bytesRead } = await readPrefix(handle, length);
return {
capture: {
text: buffer.subarray(0, bytesRead).toString("utf8"),
bytes: Math.max(size, bytesRead),
truncated: true,
complete: false,
},
limitations:
bytesRead < length
? [
"A target output capture became shorter while being read; its retained prefix may be incomplete.",
]
: [],
};
} catch {
return null;
} finally {
await handle?.close().catch(() => undefined);
}
};
+10
View File
@@ -105,9 +105,11 @@ export const projectNativeCalls = (
.map(({ index }) => index);
const eventLimit = run.outcome === "event-limit";
const resourceLimit = run.outcome === "resource-limit";
const breakpointLocationLimit = run.breakpoint_locations_truncated === true;
const partial =
eventLimit ||
resourceLimit ||
breakpointLocationLimit ||
run.outcome === "duration-elapsed" ||
run.outcome === "stop-limit" ||
unresolved.length > 0;
@@ -155,6 +157,9 @@ export const projectNativeCalls = (
status: partial ? "partial" : "complete",
event_limit_reached: eventLimit,
resource_limit_reached: resourceLimit,
...(breakpointLocationLimit
? { breakpoint_locations_truncated: true }
: {}),
unresolved_breakpoints: unresolved,
},
limitations: [
@@ -197,6 +202,11 @@ export const projectNativeCalls = (
"Breakpoints with many matching locations list only the first 64; location_count gives the total.",
]
: []),
...(breakpointLocationLimit
? [
"Resolved breakpoint locations exceeded the aggregate 8 MiB metadata budget; omitted locations are counted in location_count. This metadata limit does not change the process outcome.",
]
: []),
...(trace.stdout.truncated || trace.stderr.truncated
? ["Target output beyond 1 MiB per stream is counted but not kept."]
: []),