refactor(mcp): make analysis states unrepresentable (#468)
* refactor(config): parse capability settings into exact states * refactor(runtime): encode replay and process outcomes exactly * refactor: make analysis states unrepresentable * refactor(mcp): register canonical schemas with SDK * fix: preserve capability and catalog invariants * fix(build): remove stale compiled modules * fix(replay): update real verifier policy dependency * fix(package): verify the complete MCP catalog * fix(test): supply complete replay reload policy * refactor(contracts): centralize output schema lookup * refactor(mcp): delegate protocol boundaries to SDK * fix(browser): approve real source capture * fix(mcp): preserve catalog guidance
This commit is contained in:
@@ -7,52 +7,102 @@ import {
|
||||
} from "node:vm";
|
||||
import { types } from "node:util";
|
||||
|
||||
interface WorkerModule {
|
||||
readonly alias: string;
|
||||
readonly format: "esm" | "commonjs-factory";
|
||||
readonly dependencies: Readonly<Record<string, string>>;
|
||||
readonly source: string;
|
||||
}
|
||||
import type {
|
||||
WorkerModule,
|
||||
WorkerOutcome,
|
||||
WorkerRequest,
|
||||
WorkerSide,
|
||||
} from "./JavaScriptReplayWorkerTypes.js";
|
||||
|
||||
interface WorkerSide {
|
||||
readonly modules: readonly WorkerModule[];
|
||||
readonly entryAlias: string;
|
||||
readonly entryExport: string;
|
||||
}
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
interface WorkerRequest {
|
||||
readonly schemaVersion: 1;
|
||||
readonly left: WorkerSide;
|
||||
readonly right?: WorkerSide;
|
||||
readonly cases: readonly {
|
||||
readonly caseId: string;
|
||||
readonly arguments: readonly unknown[];
|
||||
readonly inputSha256: string;
|
||||
}[];
|
||||
readonly determinism: {
|
||||
readonly clockIso: string;
|
||||
readonly randomSeed: number;
|
||||
};
|
||||
readonly limits: {
|
||||
readonly resultDepth: number;
|
||||
readonly resultNodes: number;
|
||||
readonly exceptionBytes: number;
|
||||
};
|
||||
}
|
||||
const record = (value: unknown, label: string): Record<string, unknown> => {
|
||||
if (!isRecord(value)) throw new TypeError(`Invalid replay worker ${label}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
interface WorkerOutcome {
|
||||
readonly case_id: string;
|
||||
readonly outcome: "return" | "exception" | "serialization_error" | "denied";
|
||||
readonly value?: unknown;
|
||||
readonly exception?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
const string = (value: unknown, label: string): string => {
|
||||
if (typeof value !== "string")
|
||||
throw new TypeError(`Invalid replay worker ${label}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const integer = (value: unknown, label: string): number => {
|
||||
if (!Number.isSafeInteger(value) || Number(value) < 0)
|
||||
throw new TypeError(`Invalid replay worker ${label}`);
|
||||
return Number(value);
|
||||
};
|
||||
|
||||
const parseWorkerModule = (value: unknown): WorkerModule => {
|
||||
const module = record(value, "module");
|
||||
const format = module.format;
|
||||
if (format !== "esm" && format !== "commonjs-factory")
|
||||
throw new TypeError("Invalid replay worker module format");
|
||||
const dependencies = record(module.dependencies, "module dependencies");
|
||||
if (
|
||||
Object.values(dependencies).some(
|
||||
(dependency) => typeof dependency !== "string",
|
||||
)
|
||||
)
|
||||
throw new TypeError("Invalid replay worker module dependency");
|
||||
return {
|
||||
alias: string(module.alias, "module alias"),
|
||||
format,
|
||||
dependencies: Object.fromEntries(
|
||||
Object.entries(dependencies).map(([key, dependency]) => [
|
||||
key,
|
||||
string(dependency, "module dependency"),
|
||||
]),
|
||||
),
|
||||
source: string(module.source, "module source"),
|
||||
};
|
||||
readonly input_sha256: string;
|
||||
readonly output_sha256: null;
|
||||
readonly truncated: false;
|
||||
}
|
||||
};
|
||||
|
||||
const parseWorkerSide = (value: unknown): WorkerSide => {
|
||||
const side = record(value, "side");
|
||||
if (!Array.isArray(side.modules))
|
||||
throw new TypeError("Invalid replay worker modules");
|
||||
return {
|
||||
modules: side.modules.map(parseWorkerModule),
|
||||
entryAlias: string(side.entryAlias, "entry alias"),
|
||||
entryExport: string(side.entryExport, "entry export"),
|
||||
};
|
||||
};
|
||||
|
||||
const parseWorkerRequest = (value: unknown): WorkerRequest => {
|
||||
const request = record(value, "request");
|
||||
if (request.schemaVersion !== 1 || !Array.isArray(request.cases))
|
||||
throw new TypeError("Unsupported replay worker protocol");
|
||||
const determinism = record(request.determinism, "determinism");
|
||||
const limits = record(request.limits, "limits");
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
left: parseWorkerSide(request.left),
|
||||
...(request.right === undefined
|
||||
? {}
|
||||
: { right: parseWorkerSide(request.right) }),
|
||||
cases: request.cases.map((value) => {
|
||||
const replayCase = record(value, "case");
|
||||
if (!Array.isArray(replayCase.arguments))
|
||||
throw new TypeError("Invalid replay worker case arguments");
|
||||
return {
|
||||
caseId: string(replayCase.caseId, "case ID"),
|
||||
arguments: replayCase.arguments,
|
||||
inputSha256: string(replayCase.inputSha256, "case digest"),
|
||||
};
|
||||
}),
|
||||
determinism: {
|
||||
clockIso: string(determinism.clockIso, "clock"),
|
||||
randomSeed: integer(determinism.randomSeed, "random seed"),
|
||||
},
|
||||
limits: {
|
||||
resultDepth: integer(limits.resultDepth, "result depth"),
|
||||
resultNodes: integer(limits.resultNodes, "result nodes"),
|
||||
exceptionBytes: integer(limits.exceptionBytes, "exception bytes"),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
class ReplayDeniedError extends Error {
|
||||
override readonly name = "ReplayDeniedError";
|
||||
@@ -61,11 +111,10 @@ class ReplayDeniedError extends Error {
|
||||
const main = async (): Promise<void> => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
||||
const request = JSON.parse(
|
||||
const rawRequest: unknown = JSON.parse(
|
||||
Buffer.concat(chunks).toString("utf8"),
|
||||
) as WorkerRequest;
|
||||
if (request.schemaVersion !== 1)
|
||||
throw new TypeError("Unsupported replay worker protocol");
|
||||
);
|
||||
const request = parseWorkerRequest(rawRequest);
|
||||
const left: WorkerOutcome[] = [];
|
||||
const right: WorkerOutcome[] = [];
|
||||
for (let index = 0; index < request.cases.length; index += 1) {
|
||||
@@ -146,25 +195,22 @@ const loadEntry = async (
|
||||
throw new TypeError(
|
||||
`Synchronous require cannot load ESM module: ${alias}`,
|
||||
);
|
||||
const module = { exports: {} as Record<string, unknown> };
|
||||
const module: { exports: Record<string, unknown> } = { exports: {} };
|
||||
commonJsCache.set(alias, module.exports);
|
||||
const requireModule = ((specifier: string): Record<string, unknown> => {
|
||||
const requireModule = (specifier: string): Record<string, unknown> => {
|
||||
const dependency = descriptor.dependencies[specifier];
|
||||
if (dependency === undefined)
|
||||
throw new ReplayDeniedError(`Undeclared require: ${specifier}`);
|
||||
return loadCommonJs(dependency);
|
||||
}) as ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>;
|
||||
};
|
||||
installRspackHelpers(requireModule);
|
||||
const source = normalizeFactorySource(descriptor.source);
|
||||
const factory = new Script(`(${source})`, {
|
||||
const factory: unknown = new Script(`(${source})`, {
|
||||
filename: `/modules/${alias}.js`,
|
||||
}).runInContext(context) as (
|
||||
module: { exports: Record<string, unknown> },
|
||||
exports: Record<string, unknown>,
|
||||
require_: typeof requireModule,
|
||||
) => void;
|
||||
factory(module, module.exports, requireModule);
|
||||
}).runInContext(context);
|
||||
if (typeof factory !== "function")
|
||||
throw new TypeError(`CommonJS factory is not callable: ${alias}`);
|
||||
Reflect.apply(factory, undefined, [module, module.exports, requireModule]);
|
||||
commonJsCache.set(alias, module.exports);
|
||||
return module.exports;
|
||||
};
|
||||
@@ -219,7 +265,7 @@ const loadEntry = async (
|
||||
: exported[side.entryExport];
|
||||
}
|
||||
const namespace = (await loadEsm(side.entryAlias)).namespace;
|
||||
return (namespace as Record<string, unknown>)[side.entryExport];
|
||||
return Reflect.get(namespace, side.entryExport);
|
||||
};
|
||||
|
||||
const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
|
||||
@@ -239,7 +285,7 @@ const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
|
||||
return epoch;
|
||||
}
|
||||
}
|
||||
const replayMath = Object.create(Math) as Math;
|
||||
const replayMath: Math = Object.create(Math);
|
||||
Object.defineProperty(replayMath, "random", { value: random });
|
||||
return createContext(
|
||||
{ Date: ReplayDate, Math: replayMath },
|
||||
@@ -251,10 +297,9 @@ const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
|
||||
};
|
||||
|
||||
const installRspackHelpers = (
|
||||
require_: ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>,
|
||||
require_: (specifier: string) => Record<string, unknown>,
|
||||
): void => {
|
||||
require_.d = (
|
||||
const defineExports = (
|
||||
exports: Record<string, unknown>,
|
||||
definitions: Record<string, () => unknown>,
|
||||
) => {
|
||||
@@ -262,16 +307,22 @@ const installRspackHelpers = (
|
||||
if (!Object.prototype.hasOwnProperty.call(exports, name))
|
||||
Object.defineProperty(exports, name, { enumerable: true, get: getter });
|
||||
};
|
||||
require_.r = (exports: Record<string, unknown>) => {
|
||||
const markModule = (exports: Record<string, unknown>) => {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
};
|
||||
require_.n = (module: Record<string, unknown>) => {
|
||||
const normalizeModule = (module: Record<string, unknown>) => {
|
||||
const getter = () => (module.__esModule === true ? module.default : module);
|
||||
Object.defineProperty(getter, "a", { get: getter });
|
||||
return getter;
|
||||
};
|
||||
require_.nmd = (module: Record<string, unknown>) => module;
|
||||
const passModule = (module: Record<string, unknown>) => module;
|
||||
Object.defineProperties(require_, {
|
||||
d: { value: defineExports },
|
||||
r: { value: markModule },
|
||||
n: { value: normalizeModule },
|
||||
nmd: { value: passModule },
|
||||
});
|
||||
};
|
||||
|
||||
const requiredModule = (
|
||||
@@ -348,7 +399,7 @@ const projectLeaf = (candidate: unknown): unknown => {
|
||||
|
||||
const assertSupportedPrototype = (candidate: object): void => {
|
||||
if (Array.isArray(candidate)) return;
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
const prototype: object | null = Object.getPrototypeOf(candidate);
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
};
|
||||
@@ -421,7 +472,7 @@ const exceptionDetails = (
|
||||
if (types.isProxy(error))
|
||||
return { name: "Error", message: "Proxy replay exception", stack: null };
|
||||
const own = Object.getOwnPropertyDescriptors(error);
|
||||
const prototype = Object.getPrototypeOf(error) as object | null;
|
||||
const prototype: object | null = Object.getPrototypeOf(error);
|
||||
const inherited =
|
||||
prototype === null ? {} : Object.getOwnPropertyDescriptors(prototype);
|
||||
const stringValue = (
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/** One source module admitted to the disposable replay worker. */
|
||||
export interface WorkerModule {
|
||||
readonly alias: string;
|
||||
readonly format: "esm" | "commonjs-factory";
|
||||
readonly dependencies: Readonly<Record<string, string>>;
|
||||
readonly source: string;
|
||||
}
|
||||
|
||||
/** One independently loaded side of a replay comparison. */
|
||||
export interface WorkerSide {
|
||||
readonly modules: readonly WorkerModule[];
|
||||
readonly entryAlias: string;
|
||||
readonly entryExport: string;
|
||||
}
|
||||
|
||||
/** Parsed parent-to-worker runtime-hop request. */
|
||||
export interface WorkerRequest {
|
||||
readonly schemaVersion: 1;
|
||||
readonly left: WorkerSide;
|
||||
readonly right?: WorkerSide;
|
||||
readonly cases: readonly {
|
||||
readonly caseId: string;
|
||||
readonly arguments: readonly unknown[];
|
||||
readonly inputSha256: string;
|
||||
}[];
|
||||
readonly determinism: {
|
||||
readonly clockIso: string;
|
||||
readonly randomSeed: number;
|
||||
};
|
||||
readonly limits: {
|
||||
readonly resultDepth: number;
|
||||
readonly resultNodes: number;
|
||||
readonly exceptionBytes: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Worker-side observation before the parent authenticates its commitments. */
|
||||
export interface WorkerOutcome {
|
||||
readonly case_id: string;
|
||||
readonly outcome: "return" | "exception" | "serialization_error" | "denied";
|
||||
readonly value?: unknown;
|
||||
readonly exception?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
};
|
||||
readonly input_sha256: string;
|
||||
readonly output_sha256: null;
|
||||
readonly truncated: false;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
|
||||
|
||||
import {
|
||||
digestBytes,
|
||||
type JavaScriptReplayPolicy,
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
@@ -42,7 +42,7 @@ const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
async execute(
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReplayExecutionResult> {
|
||||
if (isAborted(signal))
|
||||
@@ -76,8 +76,7 @@ export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
collected,
|
||||
unitResult,
|
||||
cleanup,
|
||||
cancelled: replayProcess.cancelled,
|
||||
timedOut: replayProcess.timedOut,
|
||||
termination: replayProcess.termination,
|
||||
});
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", replayProcess.terminate);
|
||||
@@ -97,7 +96,7 @@ export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
|
||||
const validateReplayCommitments = async (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
): Promise<readonly RuntimeFile[]> => {
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
@@ -126,7 +125,7 @@ const buildWorkerPayload = (prepared: PreparedReplayPlan): Buffer => {
|
||||
|
||||
interface LaunchReplayProcessOptions {
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly policy: EnabledJavaScriptReplayPolicy;
|
||||
readonly encoded: Buffer;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
readonly filterPath: string;
|
||||
@@ -141,8 +140,7 @@ interface ReplayProcess {
|
||||
readonly terminate: () => void;
|
||||
readonly requestTermination: () => void;
|
||||
readonly terminationRequest: Promise<void> | undefined;
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
readonly termination: "cancelled" | "timeout" | undefined;
|
||||
}
|
||||
|
||||
const launchReplayProcess = (
|
||||
@@ -160,15 +158,14 @@ const launchReplayProcess = (
|
||||
});
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let termination: "cancelled" | "timeout" | undefined;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
termination ??= "cancelled";
|
||||
requestTermination();
|
||||
};
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
@@ -197,7 +194,7 @@ const launchReplayProcess = (
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
termination ??= "timeout";
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
@@ -212,11 +209,8 @@ const launchReplayProcess = (
|
||||
get terminationRequest() {
|
||||
return terminationRequest;
|
||||
},
|
||||
get cancelled() {
|
||||
return cancelled;
|
||||
},
|
||||
get timedOut() {
|
||||
return timedOut;
|
||||
get termination() {
|
||||
return termination;
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -239,20 +233,18 @@ interface ResolveReplayResultOptions {
|
||||
readonly collected: CollectedProcess;
|
||||
readonly unitResult: string;
|
||||
readonly cleanup: ReplayExecutionResult["cleanup"];
|
||||
readonly cancelled: boolean;
|
||||
readonly timedOut: boolean;
|
||||
readonly termination: "cancelled" | "timeout" | undefined;
|
||||
}
|
||||
|
||||
const resolveReplayResult = (
|
||||
options: ResolveReplayResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const { prepared, collected, unitResult, cleanup, cancelled, timedOut } =
|
||||
options;
|
||||
if (cancelled || timedOut)
|
||||
const { prepared, collected, unitResult, cleanup, termination } = options;
|
||||
if (termination !== undefined)
|
||||
return terminationResult({
|
||||
prepared,
|
||||
stderr: collected.stderr,
|
||||
termination: cancelled ? "cancelled" : "timeout",
|
||||
termination,
|
||||
cleanup,
|
||||
});
|
||||
if (collected.outputExceeded)
|
||||
@@ -277,7 +269,7 @@ const resolveReplayResult = (
|
||||
response = parseReplayWorkerResponse(
|
||||
rawResponse,
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
prepared.publicPlan.right === undefined ? "single" : "differential",
|
||||
);
|
||||
} catch {
|
||||
return terminationResult({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
digestJson,
|
||||
type JavaScriptReplayPolicy,
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { buildLinuxX64ReplaySeccomp } from "./LinuxSeccompPolicy.js";
|
||||
@@ -15,7 +15,7 @@ export type RuntimeFile = Awaited<
|
||||
|
||||
export interface SandboxArgumentsOptions {
|
||||
readonly unit: string;
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly policy: EnabledJavaScriptReplayPolicy;
|
||||
readonly prepared: PreparedReplayPlan;
|
||||
readonly workerPath: string;
|
||||
readonly closure: readonly RuntimeFile[];
|
||||
|
||||
+27
-16
@@ -50,19 +50,21 @@ export const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
if (outcome.outcome === "return")
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
value: jsonValueSchema.parse(outcome.value),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(outcome.value),
|
||||
truncated: false,
|
||||
};
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
exception: outcome.exception,
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
output_sha256: digestJson(outcome.exception),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
@@ -101,13 +103,22 @@ export const terminationResult = (
|
||||
options: TerminationResultOptions,
|
||||
): ReplayExecutionResult => {
|
||||
const { prepared, stderr, termination, cleanup, limitation } = options;
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const outcomes: ReplayExecutionResult["outcomes"] =
|
||||
termination === "protocol_error"
|
||||
? prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: true,
|
||||
}))
|
||||
: prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: false,
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
return {
|
||||
schema_version: 1,
|
||||
|
||||
@@ -1,42 +1,54 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const workerOutcomeSchema = z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
outcome: z.enum(["return", "exception", "serialization_error", "denied"]),
|
||||
value: z.json().optional(),
|
||||
exception: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
message: z.string(),
|
||||
stack: z.string().nullable(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
input_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
output_sha256: z.null(),
|
||||
truncated: z.literal(false),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (value.outcome === "return" && value.value === undefined)
|
||||
context.addIssue({ code: "custom", message: "Return value is missing" });
|
||||
if (value.outcome !== "return" && value.exception === undefined)
|
||||
context.addIssue({ code: "custom", message: "Exception is missing" });
|
||||
if (value.outcome === "return" && value.exception !== undefined)
|
||||
context.addIssue({ code: "custom", message: "Return has an exception" });
|
||||
});
|
||||
const workerOutcomeFacts = {
|
||||
case_id: z.string(),
|
||||
input_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
output_sha256: z.null(),
|
||||
truncated: z.literal(false),
|
||||
} as const;
|
||||
|
||||
const workerResponseSchema = z
|
||||
const exceptionSchema = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
message: z.string(),
|
||||
stack: z.string().nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const workerOutcomeSchema = z.discriminatedUnion("outcome", [
|
||||
z.strictObject({
|
||||
...workerOutcomeFacts,
|
||||
outcome: z.literal("return"),
|
||||
value: z.json(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...workerOutcomeFacts,
|
||||
outcome: z.enum(["exception", "serialization_error", "denied"]),
|
||||
exception: z.object(exceptionSchema.shape).strict(),
|
||||
}),
|
||||
]);
|
||||
|
||||
const singleWorkerResponseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
left: z.array(workerOutcomeSchema),
|
||||
right: z.array(workerOutcomeSchema).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const differentialWorkerResponseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
left: z.array(workerOutcomeSchema),
|
||||
right: z.array(workerOutcomeSchema),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type WorkerProtocolOutcome = z.infer<typeof workerOutcomeSchema>;
|
||||
export type WorkerProtocolResponse = z.infer<typeof workerResponseSchema>;
|
||||
export type WorkerProtocolResponse =
|
||||
| (z.infer<typeof singleWorkerResponseSchema> & { readonly right?: never })
|
||||
| z.infer<typeof differentialWorkerResponseSchema>;
|
||||
|
||||
export type ReplayWorkerResponseMode = "single" | "differential";
|
||||
|
||||
interface ExpectedCase {
|
||||
readonly case_id: string;
|
||||
@@ -47,14 +59,18 @@ interface ExpectedCase {
|
||||
export const parseReplayWorkerResponse = (
|
||||
rawResponse: unknown,
|
||||
cases: readonly ExpectedCase[],
|
||||
differential: boolean,
|
||||
mode: ReplayWorkerResponseMode,
|
||||
): WorkerProtocolResponse => {
|
||||
const response = workerResponseSchema.parse(rawResponse);
|
||||
if ((response.right !== undefined) !== differential)
|
||||
throw new TypeError("Replay worker differential response is incomplete");
|
||||
const response =
|
||||
mode === "single"
|
||||
? singleWorkerResponseSchema.parse(rawResponse)
|
||||
: differentialWorkerResponseSchema.parse(rawResponse);
|
||||
validateOutcomeSequence(response.left, cases);
|
||||
if (response.right !== undefined)
|
||||
validateOutcomeSequence(response.right, cases);
|
||||
if (mode === "differential")
|
||||
validateOutcomeSequence(
|
||||
differentialWorkerResponseSchema.parse(response).right,
|
||||
cases,
|
||||
);
|
||||
return response;
|
||||
};
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { spawn, type StdioOptions } from "node:child_process";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
EnabledJavaScriptReplayPolicy,
|
||||
ReplayExecutableIdentity,
|
||||
ReplaySourceBytes,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
@@ -86,7 +86,7 @@ export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
return linuxX64ReplaySeccompDigest();
|
||||
}
|
||||
|
||||
async probe(policy: JavaScriptReplayPolicy): Promise<void> {
|
||||
async probe(policy: EnabledJavaScriptReplayPolicy): Promise<void> {
|
||||
if (process.platform !== "linux" || process.arch !== "x64")
|
||||
throw new TypeError("Controlled replay requires Linux x86_64 in v1");
|
||||
const bwrapMetadata = await stat(policy.bubblewrapPath);
|
||||
|
||||
Reference in New Issue
Block a user