mirror of
https://github.com/morluto/rea.git
synced 2026-11-23 23:15:58 +00:00
perf(process/ghidra/hopper): eliminate per-char array allocs, O(P*U) filesystem scans, unbounded wire sizing, and full-binary chunk copies (#13529)
* perf(process/ghidra/hopper): eliminate per-char array allocs, O(P*U) filesystem scans, unbounded wire sizing, and full-binary chunk copies (#13527) * fix(bridge): distinguish bounded request byte counts
This commit is contained in:
1 parent
9e9cfba67d
commit
3a0d9d6874
10 files changed
+187
-24
No files matched your search
@@ -131,7 +131,7 @@ const limitFacts = (
|
||||
export const bridgeRequestOversizeError = (
|
||||
operation: string,
|
||||
limit: BridgeMaxRequestBytes,
|
||||
payloadBytes: number,
|
||||
payload: number | { readonly bytesAtLeast: number },
|
||||
peer: BridgePeer,
|
||||
): AnalysisResourceConstraintError => {
|
||||
const recovery = bridgeMaxRequestBytesRecovery(limit, peer);
|
||||
@@ -143,7 +143,12 @@ export const bridgeRequestOversizeError = (
|
||||
operation,
|
||||
"transport",
|
||||
`${refusal} ${recovery}`,
|
||||
{ ...limitFacts(limit), payload_bytes: payloadBytes },
|
||||
{
|
||||
...limitFacts(limit),
|
||||
...(typeof payload === "number"
|
||||
? { payload_bytes: payload }
|
||||
: { payload_bytes_at_least: payload.bytesAtLeast }),
|
||||
},
|
||||
{
|
||||
remediationAction: recovery,
|
||||
retryable: false,
|
||||
|
||||
@@ -158,7 +158,7 @@ const serializeRequest = (
|
||||
throw bridgeRequestOversizeError(
|
||||
"cutter_command",
|
||||
limit,
|
||||
measured,
|
||||
{ bytesAtLeast: measured },
|
||||
"Cutter",
|
||||
);
|
||||
const requestBytes = JSON.stringify(requestValue);
|
||||
|
||||
@@ -71,6 +71,36 @@ const harness = (
|
||||
};
|
||||
};
|
||||
|
||||
it("reports a lower bound for a request whose size scan stopped early", async () => {
|
||||
const method = "search_strings";
|
||||
const params = { pattern: "x".repeat(32_768) };
|
||||
const maximum = 8_192;
|
||||
const { wire, writes, pending } = harness(limit(maximum));
|
||||
const result = await wire.request(method, params, {});
|
||||
if (result.ok) throw new Error("Expected a request ceiling refusal");
|
||||
const cause = result.error.cause;
|
||||
if (!(cause instanceof AnalysisResourceConstraintError))
|
||||
throw new Error("Expected a transport resource constraint");
|
||||
const facts = cause.reportedLimits;
|
||||
const measured = facts?.payload_bytes_at_least;
|
||||
if (typeof measured !== "number")
|
||||
throw new Error("Missing request size lower bound");
|
||||
expect(measured).toBeGreaterThan(maximum);
|
||||
expect(measured).toBeLessThan(
|
||||
Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
id: 1,
|
||||
token: "b".repeat(64),
|
||||
method,
|
||||
params,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(facts).not.toHaveProperty("payload_bytes");
|
||||
expect(writes).toEqual([]);
|
||||
expect(pending.size).toBe(0);
|
||||
});
|
||||
|
||||
it("admits the exact UTF-8 request boundary without changing reply ownership on refusal", async () => {
|
||||
const method = "search_strings";
|
||||
const params = { pattern: '前缀"\\\u0000😀\ud800'.repeat(1024) };
|
||||
@@ -118,7 +148,10 @@ it("admits the exact UTF-8 request boundary without changing reply ownership on
|
||||
AnalysisResourceConstraintError,
|
||||
);
|
||||
expect(result.error.cause).toMatchObject({
|
||||
reportedLimits: { max_request_bytes: size - 1, payload_bytes: size },
|
||||
reportedLimits: {
|
||||
max_request_bytes: size - 1,
|
||||
payload_bytes_at_least: size,
|
||||
},
|
||||
retryable: false,
|
||||
});
|
||||
expect(
|
||||
|
||||
@@ -140,14 +140,17 @@ export class GhidraWire {
|
||||
options.limits === undefined ? this.admitLimits() : ok(options.limits);
|
||||
if (!limits.ok) return limits;
|
||||
const { requestLimit, replyLimit } = limits.value;
|
||||
const payloadBytes = jsonValueByteLength(payloadValue);
|
||||
const payloadBytes = jsonValueByteLength(
|
||||
payloadValue,
|
||||
requestLimit.maximumBytes,
|
||||
);
|
||||
// Refuse before registering the operation and before any socket write, so
|
||||
// an oversized request never reaches the bridge or occupies a pending key.
|
||||
if (payloadBytes > requestLimit.maximumBytes) {
|
||||
const oversize = bridgeRequestOversizeError(
|
||||
method,
|
||||
requestLimit,
|
||||
payloadBytes,
|
||||
{ bytesAtLeast: payloadBytes },
|
||||
"Ghidra",
|
||||
);
|
||||
return err(
|
||||
|
||||
@@ -1302,7 +1302,7 @@ export class HopperClient<
|
||||
bridgeRequestOversizeError(
|
||||
method,
|
||||
requestLimit.value,
|
||||
measured,
|
||||
{ bytesAtLeast: measured },
|
||||
"Hopper",
|
||||
),
|
||||
);
|
||||
|
||||
@@ -412,7 +412,7 @@ async function readSourceSnapshot(file: FileHandle, signal?: AbortSignal) {
|
||||
signal,
|
||||
cancellationFailure: (reason) => new RegularFileOperationCancelled(reason),
|
||||
})) {
|
||||
const bytes = Buffer.from(chunk);
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
hash.update(bytes);
|
||||
if (size < prefix.length)
|
||||
bytes.copy(prefix, size, 0, Math.min(bytes.length, prefix.length - size));
|
||||
|
||||
@@ -290,7 +290,7 @@ const inspectHopperMachOImage = async (
|
||||
cancelledBy("open_binary", carriedReason(reason)),
|
||||
})) {
|
||||
if (signal?.aborted) return err(cancelledBy("open_binary", signal));
|
||||
const bytes = Buffer.from(chunk);
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
hash.update(bytes);
|
||||
size += bytes.length;
|
||||
if (!Number.isSafeInteger(size))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sep } from "node:path";
|
||||
|
||||
import { failedInspectionDescriptor } from "../../../tests/fixtures/processInspectionCleanup.js";
|
||||
import {
|
||||
@@ -17,6 +18,8 @@ import {
|
||||
import { SamplingReadBatchFailure } from "./ProcessSamplingObservation.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import { processScenarioSchema } from "../../domain/process/processScenario.js";
|
||||
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import type { ProcessFilesystemSnapshot } from "../../domain/process/processCapture.js";
|
||||
import type { ProcessCapture } from "../../domain/process/processCaptureParsing.js";
|
||||
import type {
|
||||
FilesystemCoverage,
|
||||
@@ -339,6 +342,63 @@ it.each(["symlink_not_followed", "observer_owned"] as const)(
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["before", "after"] as const)(
|
||||
"classifies absence against exact subtree coverage on the %s side",
|
||||
(phase) => {
|
||||
const paths = [
|
||||
`root_0:link${sep}child${sep}file`,
|
||||
"root_0:observer",
|
||||
`root_0:link-sibling${sep}file`,
|
||||
] as const;
|
||||
const partial: ProcessFilesystemSnapshot = {
|
||||
files: [],
|
||||
completeRoots: ["root_0"],
|
||||
truncated: true,
|
||||
coverage: {
|
||||
...emptyFilesystemCoverage(),
|
||||
unobserved_subtrees: [
|
||||
{ path: "root_0:link", reason: "symlink_not_followed" },
|
||||
{ path: "root_0:observer", reason: "observer_owned" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const observed: ProcessFilesystemSnapshot = {
|
||||
...partial,
|
||||
truncated: false,
|
||||
coverage: { ...emptyFilesystemCoverage(), unobserved_subtrees: [] },
|
||||
files: paths.map((path) => ({
|
||||
path,
|
||||
type: "file",
|
||||
mode: 0o100644,
|
||||
size: 1,
|
||||
sha256: "a".repeat(64),
|
||||
symlink_target: null,
|
||||
})),
|
||||
};
|
||||
const effects =
|
||||
phase === "before"
|
||||
? classifyFilesystemEffects(partial, observed)
|
||||
: classifyFilesystemEffects(observed, partial);
|
||||
expect(effects).toHaveLength(paths.length);
|
||||
const byPath = new Map(effects.map((effect) => [effect.path, effect]));
|
||||
expect(byPath.get(paths[0])).toMatchObject({
|
||||
status: "unknown",
|
||||
reason: expect.stringContaining(
|
||||
`The ${phase} snapshot did not observe the subtree at root_0:link (symlink_not_followed)`,
|
||||
),
|
||||
});
|
||||
expect(byPath.get(paths[1])).toMatchObject({
|
||||
status: "unknown",
|
||||
reason: expect.stringContaining(
|
||||
`The ${phase} snapshot did not observe the subtree at root_0:observer (observer_owned)`,
|
||||
),
|
||||
});
|
||||
expect(byPath.get(paths[2])?.status).toBe(
|
||||
phase === "before" ? "created" : "deleted",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("records the PTY session-leader SIGHUP limitation on POSIX captures only", () => {
|
||||
const capture = emptyCapture();
|
||||
const buildForPlatform = (platform: string) =>
|
||||
|
||||
@@ -4,27 +4,79 @@ import type {
|
||||
} from "../../domain/process/processCapture.js";
|
||||
import { sep } from "node:path";
|
||||
|
||||
type UnobservedSubtree = NonNullable<
|
||||
ProcessFilesystemSnapshot["coverage"]["unobserved_subtrees"]
|
||||
>[number];
|
||||
|
||||
interface IndexedAbsenceSnapshot {
|
||||
readonly completeRoots: ReadonlySet<string>;
|
||||
readonly subtreesByPath:
|
||||
| ReadonlyMap<
|
||||
string,
|
||||
{ readonly subtree: UnobservedSubtree; readonly index: number }
|
||||
>
|
||||
| undefined;
|
||||
}
|
||||
|
||||
const indexAbsenceSnapshot = (
|
||||
snapshot: ProcessFilesystemSnapshot,
|
||||
): IndexedAbsenceSnapshot => {
|
||||
const subtrees = snapshot.coverage.unobserved_subtrees;
|
||||
let subtreesByPath:
|
||||
| Map<
|
||||
string,
|
||||
{ readonly subtree: UnobservedSubtree; readonly index: number }
|
||||
>
|
||||
| undefined;
|
||||
if (subtrees !== undefined) {
|
||||
subtreesByPath = new Map();
|
||||
for (let index = 0; index < subtrees.length; index += 1) {
|
||||
const subtree = subtrees[index]!;
|
||||
if (!subtreesByPath.has(subtree.path))
|
||||
subtreesByPath.set(subtree.path, { subtree, index });
|
||||
}
|
||||
}
|
||||
return {
|
||||
completeRoots: new Set(snapshot.completeRoots),
|
||||
subtreesByPath,
|
||||
};
|
||||
};
|
||||
|
||||
const unobservedAbsenceReason = (
|
||||
path: string,
|
||||
phase: "before" | "after",
|
||||
snapshot: ProcessFilesystemSnapshot,
|
||||
indexed: IndexedAbsenceSnapshot,
|
||||
): string | undefined => {
|
||||
const alias = path.slice(0, path.indexOf(":"));
|
||||
if (!snapshot.completeRoots.includes(alias))
|
||||
if (!indexed.completeRoots.has(alias))
|
||||
return `The ${phase} snapshot did not exhaust path enumeration under ${alias}; absence remains unknown.`;
|
||||
const rootPath = `${alias}:.`;
|
||||
if (path === rootPath) return undefined;
|
||||
if (snapshot.coverage.unobserved_subtrees === undefined)
|
||||
const subtreesByPath = indexed.subtreesByPath;
|
||||
if (subtreesByPath === undefined)
|
||||
return `The ${phase} snapshot has no subtree coverage facts; descendant absence remains unknown.`;
|
||||
for (const subtree of snapshot.coverage.unobserved_subtrees) {
|
||||
const below =
|
||||
subtree.path === rootPath
|
||||
? path.startsWith(`${alias}:`)
|
||||
: path.startsWith(`${subtree.path}${sep}`);
|
||||
if (below || (subtree.reason === "observer_owned" && path === subtree.path))
|
||||
return `The ${phase} snapshot did not observe the subtree at ${subtree.path} (${subtree.reason}); descendant absence remains unknown.`;
|
||||
if (subtreesByPath.size === 0) return undefined;
|
||||
let best:
|
||||
| { readonly subtree: UnobservedSubtree; readonly index: number }
|
||||
| undefined;
|
||||
const consider = (
|
||||
entry:
|
||||
| { readonly subtree: UnobservedSubtree; readonly index: number }
|
||||
| undefined,
|
||||
): void => {
|
||||
if (entry !== undefined && (best === undefined || entry.index < best.index))
|
||||
best = entry;
|
||||
};
|
||||
if (path.startsWith(`${alias}:`)) consider(subtreesByPath.get(rootPath));
|
||||
const exact = subtreesByPath.get(path);
|
||||
if (exact?.subtree.reason === "observer_owned") consider(exact);
|
||||
for (let cut = path.lastIndexOf(sep); cut !== -1;) {
|
||||
consider(subtreesByPath.get(path.slice(0, cut)));
|
||||
cut = cut > 0 ? path.lastIndexOf(sep, cut - 1) : -1;
|
||||
}
|
||||
return undefined;
|
||||
return best === undefined
|
||||
? undefined
|
||||
: `The ${phase} snapshot did not observe the subtree at ${best.subtree.path} (${best.subtree.reason}); descendant absence remains unknown.`;
|
||||
};
|
||||
|
||||
/** Classify effects only from observed path absence, metadata, and content hashes. */
|
||||
@@ -34,6 +86,8 @@ export const classifyFilesystemEffects = (
|
||||
): FilesystemCheckpoint["effects"] => {
|
||||
const beforeByPath = new Map(before.files.map((file) => [file.path, file]));
|
||||
const afterByPath = new Map(after.files.map((file) => [file.path, file]));
|
||||
let beforeIndexed: IndexedAbsenceSnapshot | undefined;
|
||||
let afterIndexed: IndexedAbsenceSnapshot | undefined;
|
||||
return [...new Set([...beforeByPath.keys(), ...afterByPath.keys()])]
|
||||
.sort()
|
||||
.map((path) => {
|
||||
@@ -41,9 +95,17 @@ export const classifyFilesystemEffects = (
|
||||
const afterFile = afterByPath.get(path) ?? null;
|
||||
const reason =
|
||||
beforeFile === null
|
||||
? unobservedAbsenceReason(path, "before", before)
|
||||
? unobservedAbsenceReason(
|
||||
path,
|
||||
"before",
|
||||
(beforeIndexed ??= indexAbsenceSnapshot(before)),
|
||||
)
|
||||
: afterFile === null
|
||||
? unobservedAbsenceReason(path, "after", after)
|
||||
? unobservedAbsenceReason(
|
||||
path,
|
||||
"after",
|
||||
(afterIndexed ??= indexAbsenceSnapshot(after)),
|
||||
)
|
||||
: undefined;
|
||||
if (reason !== undefined)
|
||||
return {
|
||||
|
||||
@@ -80,7 +80,7 @@ const visibleUnits = function* (parts: readonly string[]) {
|
||||
? "csi"
|
||||
: code === 0x5d
|
||||
? "osc"
|
||||
: [0x50, 0x58, 0x5e, 0x5f].includes(code)
|
||||
: code === 0x50 || code === 0x58 || code === 0x5e || code === 0x5f
|
||||
? "string"
|
||||
: code >= 0x20 && code <= 0x2f
|
||||
? "intermediate"
|
||||
@@ -103,7 +103,7 @@ const visibleUnits = function* (parts: readonly string[]) {
|
||||
state = "osc";
|
||||
continue;
|
||||
}
|
||||
if ([0x90, 0x98, 0x9e, 0x9f].includes(code)) {
|
||||
if (code === 0x90 || code === 0x98 || code === 0x9e || code === 0x9f) {
|
||||
state = "string";
|
||||
continue;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user