feat(process): run finite-state replay during capture

This commit is contained in:
morluto
2026-07-22 14:06:50 +00:00
parent e4ee4c9635
commit 34c583a170
186 changed files with 1702 additions and 666 deletions
+365 -154
View File
@@ -9,140 +9,216 @@ import type {
ProcessScenario,
ProtocolEvent,
} from "../domain/processCapture.js";
import {
type ReplayMachineDecision,
type ReplayTransitionRecord,
} from "../domain/replayMachineRuntime.js";
import {
closeReplayServer,
listenOnLoopback,
recordMachineEvent,
readReplayRequestBody,
ReplayRecorder,
requestHeaders,
waitForReplayDelay,
} from "./LoopbackReplayRecorder.js";
/** Owned loopback replay endpoints and their bounded protocol observations. */
export interface LoopbackReplay {
readonly httpUrl: string;
readonly websocketUrl: string;
readonly events: ProtocolEvent[];
readonly transitions: readonly ReplayTransitionRecord[];
readonly truncated: boolean;
close(): Promise<void>;
}
class ReplayRecorder {
readonly events: ProtocolEvent[] = [];
readonly started = Date.now();
truncated = false;
constructor(readonly scenario: ProcessScenario) {}
atMs(): number {
return (
Math.floor(
(Date.now() - this.started) /
this.scenario.normalization.time_bucket_ms,
) * this.scenario.normalization.time_bucket_ms
);
}
record(event: Omit<ProtocolEvent, "sequence">): void {
if (this.events.length < this.scenario.limits.protocol_events)
this.events.push({ sequence: this.events.length, ...event });
else this.truncated = true;
}
interface HttpReplayRequest {
readonly request: IncomingMessage;
readonly response: ServerResponse;
readonly method: string;
readonly path: string;
readonly body: string;
readonly rawAtMs: number;
readonly recordedAtMs: number;
}
const readRequestBody = async (
request: IncomingMessage,
limit: number,
): Promise<string | undefined> => {
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of request) {
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
bytes += value.byteLength;
if (bytes > limit) return undefined;
chunks.push(value);
const recordHttpResponse = (
recorder: ReplayRecorder,
request: Pick<HttpReplayRequest, "method" | "path">,
data: string,
outcome: ProtocolEvent["outcome"],
): void =>
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "response",
method: request.method,
path: request.path,
data,
outcome,
});
const handleMachineHttp = async (
recorder: ReplayRecorder,
request: HttpReplayRequest,
): Promise<void> => {
const machine = recorder.machine;
if (machine === undefined) return;
const decision = machine.dispatch({
protocol: "http",
connection: "not_applicable",
at_ms: request.rawAtMs,
recorded_at_ms: request.recordedAtMs,
method: request.method,
path: request.path,
headers: requestHeaders(request.request),
body: request.body,
});
recordMachineEvent(
recorder,
{
at_ms: request.recordedAtMs,
protocol: "http",
direction: "request",
method: request.method,
path: request.path,
data: request.body,
},
decision,
);
if (decision.outcome !== "matched") {
request.response.statusCode = decision.outcome === "unmatched" ? 404 : 409;
request.response.end();
return;
}
for (const action of decision.actions) {
if (action.type === "delay") await waitForReplayDelay(action.duration_ms);
else if (action.type === "disconnect") {
request.response.destroy();
recordHttpResponse(recorder, request, "", "disconnected");
return;
} else if (action.type === "http_response") {
request.response.statusCode = action.status;
for (const [name, value] of Object.entries(action.headers))
request.response.setHeader(name, value);
request.response.end(action.body);
recordHttpResponse(
recorder,
request,
machine.redact(action.body),
"matched",
);
}
}
return Buffer.concat(chunks).toString("utf8");
};
const createHttpHandler = (
const handleStaticHttp = async (
recorder: ReplayRecorder,
): ((request: IncomingMessage, response: ServerResponse) => Promise<void>) => {
const calls = new Map<number, number>();
return async (request, response) => {
const method = request.method ?? "GET";
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
const body = await readRequestBody(
request,
recorder.scenario.limits.protocol_body_bytes,
);
if (body === undefined) {
recorder.truncated = true;
response.statusCode = 413;
response.end();
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "request",
method,
path,
data: "<body-over-limit>",
outcome: "unmatched",
});
return;
}
const index = recorder.scenario.replay.http.findIndex((route) => {
if (route.method !== method || route.path !== path) return false;
if (route.request_body !== undefined && route.request_body !== body)
return false;
return Object.entries(route.request_headers).every(
([name, value]) => request.headers[name.toLowerCase()] === value,
);
});
const route = recorder.scenario.replay.http[index];
const used = index < 0 ? 0 : (calls.get(index) ?? 0);
const outcome =
route === undefined
? "unmatched"
: used >= route.max_calls
? "script_exhausted"
: "matched";
request: HttpReplayRequest,
calls: Map<number, number>,
): Promise<void> => {
const index = recorder.scenario.replay.http.findIndex((route) =>
route.method !== request.method || route.path !== request.path
? false
: (route.request_body === undefined ||
route.request_body === request.body) &&
Object.entries(route.request_headers).every(
([name, value]) =>
request.request.headers[name.toLowerCase()] === value,
),
);
const route = recorder.scenario.replay.http[index];
const used = index < 0 ? 0 : (calls.get(index) ?? 0);
const outcome =
route === undefined
? "unmatched"
: used >= route.max_calls
? "script_exhausted"
: "matched";
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "request",
method: request.method,
path: request.path,
data: request.body.length === 0 ? "" : "<redacted-request-body>",
outcome,
});
if (route === undefined || outcome === "script_exhausted") {
request.response.statusCode = route === undefined ? 404 : 409;
request.response.end();
return;
}
calls.set(index, used + 1);
if (route.delay_ms > 0) await waitForReplayDelay(route.delay_ms);
if (route.disconnect) {
request.response.destroy();
recordHttpResponse(recorder, request, "", "disconnected");
return;
}
request.response.statusCode = route.status;
for (const [name, value] of Object.entries(route.response_headers))
request.response.setHeader(name, value);
request.response.end(route.body);
recordHttpResponse(recorder, request, route.body, "matched");
};
const handleHttpRequest = async (
recorder: ReplayRecorder,
request: IncomingMessage,
response: ServerResponse,
calls: Map<number, number>,
): Promise<void> => {
const body = await readReplayRequestBody(
request,
recorder.scenario.limits.protocol_body_bytes,
);
const method = request.method ?? "GET";
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
if (body === undefined) {
recorder.truncated = true;
response.statusCode = 413;
response.end();
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "request",
method,
path,
data: body.length === 0 ? "" : "<redacted-request-body>",
outcome,
data: "<body-over-limit>",
outcome: "unmatched",
});
if (route === undefined || outcome === "script_exhausted") {
response.statusCode = route === undefined ? 404 : 409;
response.end();
return;
}
calls.set(index, used + 1);
if (route.delay_ms > 0)
await new Promise((resolveDelay) =>
setTimeout(resolveDelay, route.delay_ms),
);
if (route.disconnect) {
response.destroy();
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "response",
method,
path,
data: "",
outcome: "disconnected",
});
return;
}
response.statusCode = route.status;
for (const [name, value] of Object.entries(route.response_headers))
response.setHeader(name, value);
response.end(route.body);
recorder.record({
at_ms: recorder.atMs(),
protocol: "http",
direction: "response",
method,
path,
data: route.body,
outcome: "matched",
return;
}
const replayRequest = {
request,
response,
method,
path,
body,
rawAtMs: recorder.rawAtMs(),
recordedAtMs: recorder.atMs(),
};
await (recorder.machine === undefined
? handleStaticHttp(recorder, replayRequest, calls)
: recorder.enqueueMachine(() =>
handleMachineHttp(recorder, replayRequest),
));
};
const createHttpHandler = (
recorder: ReplayRecorder,
): ((request: IncomingMessage, response: ServerResponse) => void) => {
const calls = new Map<number, number>();
return (request, response) => {
void handleHttpRequest(recorder, request, response, calls).catch(() => {
recorder.truncated = true;
if (response.headersSent) response.destroy();
else {
response.statusCode = 500;
response.end();
}
});
};
};
@@ -204,6 +280,146 @@ const sendWebSocketScript = async (
}
};
const runWebSocketActions = async (
client: WebSocket,
recorder: ReplayRecorder,
decision: Extract<ReplayMachineDecision, { readonly outcome: "matched" }>,
path: string,
): Promise<void> => {
for (const action of decision.actions) {
if (action.type === "delay") {
await waitForReplayDelay(action.duration_ms);
continue;
}
if (action.type === "disconnect") {
client.close();
recorder.record({
at_ms: recorder.atMs(),
protocol: "websocket",
direction: "sent",
method: null,
path,
data: "",
outcome: "disconnected",
});
return;
}
if (action.type === "websocket_send" && client.readyState === 1) {
client.send(action.data);
recorder.record({
at_ms: recorder.atMs(),
protocol: "websocket",
direction: "sent",
method: null,
path,
data: recorder.machine?.redact(action.data) ?? action.data,
outcome: "matched",
});
}
}
};
const handleStaticWebSocket = (
client: WebSocket,
recorder: ReplayRecorder,
connection: number,
path: string,
): void => {
client.on("message", (value) =>
recorder.record({
at_ms: recorder.atMs(),
protocol: "websocket",
direction: "received",
method: null,
path,
data: value.toString(),
outcome: "matched",
}),
);
void sendWebSocketScript(client, connection, recorder);
};
const handleMachineWebSocket = (options: {
readonly client: WebSocket;
readonly request: IncomingMessage;
readonly recorder: ReplayRecorder;
readonly connection: number;
readonly path: string;
}): void => {
const { client, request, recorder, connection, path } = options;
const machine = recorder.machine;
if (machine === undefined) return;
void recorder
.enqueueMachine(async () => {
const connectedAt = recorder.atMs();
const connectionDecision = machine.dispatch({
protocol: "websocket_connect",
connection: connection === 1 ? "initial" : "reconnect",
at_ms: recorder.rawAtMs(),
recorded_at_ms: connectedAt,
method: null,
path,
headers: requestHeaders(request),
body: "",
});
recordMachineEvent(
recorder,
{
at_ms: connectedAt,
protocol: "websocket",
direction: "received",
method: null,
path,
data: "",
},
connectionDecision,
);
if (connectionDecision.outcome === "matched")
await runWebSocketActions(client, recorder, connectionDecision, path);
else client.close();
})
.catch(() => {
recorder.truncated = true;
client.terminate();
});
client.on("message", (value) => {
const body = value.toString();
const rawAtMs = recorder.rawAtMs();
const recordedAtMs = recorder.atMs();
void recorder
.enqueueMachine(async () => {
const decision = machine.dispatch({
protocol: "websocket_message",
connection: connection === 1 ? "initial" : "reconnect",
at_ms: rawAtMs,
recorded_at_ms: recordedAtMs,
method: null,
path,
headers: {},
body,
});
recordMachineEvent(
recorder,
{
at_ms: recordedAtMs,
protocol: "websocket",
direction: "received",
method: null,
path,
data: body,
},
decision,
);
if (decision.outcome === "matched")
await runWebSocketActions(client, recorder, decision, path);
})
.catch(() => {
recorder.truncated = true;
client.terminate();
});
});
};
const createWebSocketReplay = (
server: Server,
recorder: ReplayRecorder,
@@ -215,7 +431,10 @@ const createWebSocketReplay = (
clientTracking: true,
});
server.on("upgrade", (request, socket, head) => {
if (new URL(request.url ?? "/", "http://127.0.0.1").pathname !== "/ws") {
if (
recorder.machine === undefined &&
new URL(request.url ?? "/", "http://127.0.0.1").pathname !== "/ws"
) {
socket.destroy();
return;
}
@@ -223,7 +442,7 @@ const createWebSocketReplay = (
websocket.emit("connection", client, request),
);
});
websocket.on("connection", (client: WebSocket) => {
websocket.on("connection", (client: WebSocket, request: IncomingMessage) => {
connections += 1;
if (connections > recorder.scenario.limits.connections) {
recorder.truncated = true;
@@ -231,43 +450,21 @@ const createWebSocketReplay = (
return;
}
client.on("error", () => undefined);
client.on("message", (value) =>
recorder.record({
at_ms: recorder.atMs(),
protocol: "websocket",
direction: "received",
method: null,
path: "/ws",
data: value.toString(),
outcome: "matched",
}),
);
void sendWebSocketScript(client, connections, recorder);
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
if (recorder.machine === undefined)
handleStaticWebSocket(client, recorder, connections, path);
else
handleMachineWebSocket({
client,
request,
recorder,
connection: connections,
path,
});
});
return websocket;
};
const listen = async (server: Server): Promise<number> => {
await new Promise<void>((resolveListen, rejectListen) => {
server.once("error", rejectListen);
server.listen(0, "127.0.0.1", () => {
server.off("error", rejectListen);
resolveListen();
});
});
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("loopback replay did not acquire a TCP port");
return address.port;
};
const closeServer = (server: Server): Promise<void> =>
new Promise((resolveClose, rejectClose) => {
server.close((error) =>
error === undefined ? resolveClose() : rejectClose(error),
);
});
/** Start bounded HTTP and WebSocket replay endpoints on IPv4 loopback only. */
export const startLoopbackReplay = async (
scenario: ProcessScenario,
@@ -275,26 +472,40 @@ export const startLoopbackReplay = async (
const recorder = new ReplayRecorder(scenario);
const server = createServer(createHttpHandler(recorder));
const websocket = createWebSocketReplay(server, recorder);
let closePromise: Promise<void> | undefined;
let port: number;
try {
port = await listen(server);
port = await listenOnLoopback(server);
} catch (cause: unknown) {
await closeServer(server).catch(() => undefined);
await closeReplayServer(server).catch(() => undefined);
throw cause;
}
return {
httpUrl: `http://127.0.0.1:${String(port)}`,
websocketUrl: `ws://127.0.0.1:${String(port)}/ws`,
events: recorder.events,
get events() {
return recorder.events.map((event) => ({ ...event }));
},
get transitions() {
return recorder.transitions.map((transition) => ({
...transition,
sensitive_aliases: [...transition.sensitive_aliases],
}));
},
get truncated() {
return recorder.truncated;
},
async close() {
for (const client of websocket.clients) client.terminate();
await new Promise<void>((resolveClose) =>
websocket.close(() => resolveClose()),
);
await closeServer(server);
closePromise ??= (async () => {
recorder.stopMachineAdmission();
for (const client of websocket.clients) client.terminate();
await new Promise<void>((resolveClose) =>
websocket.close(() => resolveClose()),
);
await closeReplayServer(server);
await recorder.drainMachine();
})();
await closePromise;
},
};
};
+130
View File
@@ -0,0 +1,130 @@
import type { IncomingMessage, Server } from "node:http";
import type {
ProcessScenario,
ProtocolEvent,
} from "../domain/processCapture.js";
import {
ReplayMachineRuntime,
type ReplayMachineDecision,
type ReplayTransitionRecord,
} from "../domain/replayMachineRuntime.js";
/** Bounded protocol and replay-machine observations for one process run. */
export class ReplayRecorder {
readonly events: ProtocolEvent[] = [];
readonly started = Date.now();
readonly machine: ReplayMachineRuntime | undefined;
#machineQueue: Promise<void> = Promise.resolve();
#machineAdmissionOpen = true;
truncated = false;
constructor(readonly scenario: ProcessScenario) {
this.machine =
scenario.replay.machine === null
? undefined
: new ReplayMachineRuntime(scenario.replay.machine);
}
get transitions(): readonly ReplayTransitionRecord[] {
return this.machine?.timeline ?? [];
}
atMs(): number {
return (
Math.floor(
(Date.now() - this.started) /
this.scenario.normalization.time_bucket_ms,
) * this.scenario.normalization.time_bucket_ms
);
}
rawAtMs(): number {
return Date.now() - this.started;
}
enqueueMachine<T>(operation: () => Promise<T>): Promise<T> {
if (!this.#machineAdmissionOpen)
return Promise.reject(new Error("replay machine is closing"));
const result = this.#machineQueue.then(operation);
this.#machineQueue = result.then(
() => undefined,
() => undefined,
);
return result;
}
stopMachineAdmission(): void {
this.#machineAdmissionOpen = false;
}
async drainMachine(): Promise<void> {
await this.#machineQueue;
}
record(event: Omit<ProtocolEvent, "sequence">): void {
if (this.events.length < this.scenario.limits.protocol_events)
this.events.push({ sequence: this.events.length, ...event });
else this.truncated = true;
}
}
export const requestHeaders = (
request: IncomingMessage,
): Readonly<Record<string, string>> =>
Object.fromEntries(
Object.entries(request.headers).flatMap(([name, value]) =>
value === undefined
? []
: [[name, Array.isArray(value) ? value.join(", ") : value]],
),
);
export const readReplayRequestBody = async (
request: IncomingMessage,
limit: number,
): Promise<string | undefined> => {
const chunks: Buffer[] = [];
let bytes = 0;
for await (const chunk of request) {
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
bytes += value.byteLength;
if (bytes > limit) return undefined;
chunks.push(value);
}
return Buffer.concat(chunks).toString("utf8");
};
export const recordMachineEvent = (
recorder: ReplayRecorder,
event: Omit<ProtocolEvent, "sequence" | "outcome">,
decision: ReplayMachineDecision,
): void =>
recorder.record({
...event,
data: recorder.machine?.redact(event.data) ?? event.data,
outcome: decision.outcome,
});
export const waitForReplayDelay = (durationMs: number): Promise<void> =>
new Promise((resolveDelay) => setTimeout(resolveDelay, durationMs));
export const listenOnLoopback = async (server: Server): Promise<number> => {
await new Promise<void>((resolveListen, rejectListen) => {
server.once("error", rejectListen);
server.listen(0, "127.0.0.1", () => {
server.off("error", rejectListen);
resolveListen();
});
});
const address = server.address();
if (address === null || typeof address === "string")
throw new Error("loopback replay did not acquire a TCP port");
return address.port;
};
export const closeReplayServer = (server: Server): Promise<void> =>
new Promise((resolveClose, rejectClose) => {
server.close((error) =>
error === undefined ? resolveClose() : rejectClose(error),
);
});
@@ -115,6 +115,7 @@ export const buildCaptureResult = (
options.replay.events,
options.scenario,
),
replay_transitions: options.replay.transitions,
files_before: options.before.files,
files_after: options.after.files,
filesystem_effects: classifyFilesystemEffects(
+1
View File
@@ -382,6 +382,7 @@ const completeCapture = async (options: {
const after = await snapshotRoots(scenario, options.signal);
const renderedFrames = await runtime.renderer.frames();
const checkpoints = await runtime.checkpoints.finish(after);
await runtime.replay.close();
const manifest = await createRunManifest(
scenario,
runtime.startedAt,
+1
View File
@@ -58,6 +58,7 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
],
shim_events: [],
protocol_events: [],
replay_transitions: [],
files_before: [],
files_after: [],
filesystem_effects: [],
+27 -1
View File
@@ -5,6 +5,7 @@ import {
LEGACY_PROCESS_CAPTURE_MESSAGE,
normalizationSchema,
} from "./processScenario.js";
import type { ReplayTransitionRecord } from "./replayMachineRuntime.js";
export * from "./processScenario.js";
@@ -100,7 +101,13 @@ export interface ProtocolEvent {
| "matched"
| "unmatched"
| "script_exhausted"
| "disconnected";
| "disconnected"
| "invalid_state"
| "guard_failed"
| "transition_exhausted"
| "invalid_capture"
| "unexpected_reconnect"
| "limit_exhausted";
}
/**
@@ -148,6 +155,7 @@ export interface ProcessCapture {
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
readonly shim_events: readonly ShimEvent[];
readonly protocol_events: readonly ProtocolEvent[];
readonly replay_transitions: readonly ReplayTransitionRecord[];
readonly files_before: readonly FileState[];
readonly files_after: readonly FileState[];
readonly filesystem_effects: readonly FileEffect[];
@@ -299,9 +307,27 @@ export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
"unmatched",
"script_exhausted",
"disconnected",
"invalid_state",
"guard_failed",
"transition_exhausted",
"invalid_capture",
"unexpected_reconnect",
"limit_exhausted",
]),
}),
),
replay_transitions: z
.array(
z.object({
sequence: z.number().int().nonnegative(),
at_ms: z.number().int().nonnegative(),
transition_id: z.string().min(1).max(64),
state_before: z.string().min(1).max(64),
state_after: z.string().min(1).max(64),
sensitive_aliases: z.array(z.string().min(1).max(64)).max(32),
}),
)
.default([]),
files_before: z.array(fileStateSchema),
files_after: z.array(fileStateSchema),
filesystem_effects: z.array(fileEffectSchema),
+94 -15
View File
@@ -1,4 +1,5 @@
import type { ProcessCapture } from "./processCapture.js";
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
import { digestProcessCommitment } from "./processScenario.js";
/** One pure semantic validation failure in an otherwise shaped v4 capture. */
@@ -54,6 +55,7 @@ const validateOrdering = (
["interaction_events", capture.interaction_events],
["shim_events", capture.shim_events],
["protocol_events", capture.protocol_events],
["replay_transitions", capture.replay_transitions],
] as const)
require(values.every(
({ sequence }, index) => sequence === index,
@@ -65,6 +67,7 @@ const validateOrdering = (
["filesystem_checkpoints", capture.filesystem_checkpoints],
["shim_events", capture.shim_events],
["protocol_events", capture.protocol_events],
["replay_transitions", capture.replay_transitions],
] as const)
require(orderedTimestamps(values), name, "timestamps must be ordered");
};
@@ -144,15 +147,34 @@ const validateShimEvents = (
}
};
const validateReplayEvents = (
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null;
const machinePlan = (
replayPlan: Readonly<Record<string, unknown>>,
): ReplayMachine | undefined => {
const parsed = replayMachineSchema.safeParse(replayPlan["machine"]);
return parsed.success ? parsed.data : undefined;
};
const matchesHttpPlan = (
value: unknown,
event: ProcessCapture["protocol_events"][number],
): boolean => {
if (!isRecord(value)) return false;
const route = isRecord(value["trigger"]) ? value["trigger"] : value;
return (
(route["protocol"] === undefined || route["protocol"] === "http") &&
route["method"] === event.method &&
route["path"] === event.path
);
};
const validateMatchedHttpEvents = (
capture: ProcessCapture,
plans: readonly unknown[],
require: RequireInvariant,
): void => {
const { replay_plan: replayPlan } = capture.manifest;
const routes =
"http" in replayPlan && Array.isArray(replayPlan.http)
? replayPlan.http
: [];
for (const event of capture.protocol_events) {
if (
event.protocol !== "http" ||
@@ -160,16 +182,73 @@ const validateReplayEvents = (
event.outcome !== "matched"
)
continue;
const declared = routes.some(
(route) =>
typeof route === "object" &&
route !== null &&
"method" in route &&
route.method === event.method &&
"path" in route &&
route.path === event.path,
require(plans.some((plan) =>
matchesHttpPlan(plan, event),
), "protocol_events", "matched HTTP event has no declared replay route");
}
};
const validateReplayEvents = (
capture: ProcessCapture,
require: RequireInvariant,
): void => {
const replayPlan = capture.manifest.replay_plan;
const routes = Array.isArray(replayPlan["http"]) ? replayPlan["http"] : [];
const machine = machinePlan(replayPlan);
require(replayPlan["machine"] === undefined ||
replayPlan["machine"] === null ||
machine !==
undefined, "manifest.replay_plan.machine", "replay machine does not satisfy its declared schema");
validateMatchedHttpEvents(
capture,
[...routes, ...(machine?.transitions ?? [])],
require,
);
const plans = new Map(
(machine?.transitions ?? []).map((transition) => [
transition.id,
transition,
]),
);
const transitionUses = new Map<string, number>();
const stateVisits = new Map<string, number>();
if (machine !== undefined) stateVisits.set(machine.initial_state, 1);
require(machine === undefined ||
capture.replay_transitions.length <=
machine.max_transitions, "replay_transitions", "replay transition journal exceeds the declared machine limit");
for (const [index, transition] of capture.replay_transitions.entries()) {
const plan = plans.get(transition.transition_id);
require(plan !==
undefined, "replay_transitions", "replay transition has no declared machine transition");
if (plan === undefined) continue;
require(transition.state_before === plan.from &&
transition.state_after ===
plan.to, "replay_transitions", "replay transition states do not match the declared transition");
require(JSON.stringify(transition.sensitive_aliases) ===
JSON.stringify(
plan.captures
.filter(({ sensitive }) => sensitive)
.map(({ variable }) => variable)
.sort(),
), "replay_transitions", "replay transition sensitive aliases do not match the declared captures");
const uses = (transitionUses.get(plan.id) ?? 0) + 1;
transitionUses.set(plan.id, uses);
require(uses <=
plan.max_uses, "replay_transitions", "replay transition journal exceeds the transition use limit");
const visits = (stateVisits.get(transition.state_after) ?? 0) + 1;
stateVisits.set(transition.state_after, visits);
const state = machine?.states.find(
({ name }) => name === transition.state_after,
);
require(declared, "protocol_events", "matched HTTP event has no declared replay route");
require(state === undefined ||
visits <=
state.max_visits, "replay_transitions", "replay transition journal exceeds the state visit limit");
if (index === 0)
require(transition.state_before ===
machine?.initial_state, "replay_transitions", "first replay transition does not start at the declared initial state");
if (index > 0)
require(capture.replay_transitions[index - 1]!.state_after ===
transition.state_before, "replay_transitions", "replay transition states are not contiguous");
}
};
+8 -4
View File
@@ -130,7 +130,7 @@ export const processDimensionObservations = (
case "filesystem":
return filesystemObservations(capture);
case "protocol":
return capture.protocol_events;
return [...capture.protocol_events, ...capture.replay_transitions];
case "process":
return capture.process_samples;
case "shim":
@@ -316,7 +316,11 @@ const compareDimensions = (
filesystemObservations(left),
filesystemObservations(right),
),
protocol: classify("protocol", left.protocol_events, right.protocol_events),
protocol: classify(
"protocol",
[...left.protocol_events, ...left.replay_transitions],
[...right.protocol_events, ...right.replay_transitions],
),
process: classify("process", left.process_samples, right.process_samples),
shim: classify("shim", left.shim_events, right.shim_events),
};
@@ -365,8 +369,8 @@ export const compareProcessCaptures = (
),
firstCollectionDivergence(
"protocol",
left.protocol_events,
right.protocol_events,
[...left.protocol_events, ...left.replay_transitions],
[...right.protocol_events, ...right.replay_transitions],
),
firstCollectionDivergence(
"process",
+15
View File
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { resolve } from "node:path";
import canonicalize from "canonicalize";
import { z } from "zod";
import { replayMachineSchema } from "./replayMachine.js";
const positiveBudget = z.number().int().positive();
const timedEventBase = { at_ms: z.number().int().nonnegative() };
@@ -241,6 +242,7 @@ export const processScenarioSchema = z
}),
replay: z
.object({
machine: replayMachineSchema.nullable().default(null),
http: z
.array(
z.object({
@@ -285,6 +287,7 @@ export const processScenarioSchema = z
.default([]),
})
.default({
machine: null,
http: [],
websocket_messages: [],
websocket_connections: [],
@@ -361,6 +364,18 @@ export const processScenarioSchema = z
message: "command shim names must be unique",
path: ["command_shims"],
});
if (
scenario.replay.machine !== null &&
(scenario.replay.http.length > 0 ||
scenario.replay.websocket_messages.length > 0 ||
scenario.replay.websocket_connections.length > 0)
)
context.addIssue({
code: "custom",
message:
"a replay machine cannot be combined with static HTTP or WebSocket scripts",
path: ["replay"],
});
});
/** Parsed instructions and resource bounds for one process experiment. */
+19 -2
View File
@@ -15,8 +15,17 @@ const sensitiveHeaderNames = new Set([
"proxy-authorization",
"set-cookie",
]);
const headerNameSchema = z
.string()
.min(1)
.max(256)
.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u);
const headerValueSchema = z
.string()
.max(8_192)
.regex(/^[\t\x20-\x7e\x80-\xff]*$/u);
const replayHeaderMatchersSchema = z
.record(z.string().min(1).max(256), z.string().max(8_192))
.record(headerNameSchema, headerValueSchema)
.superRefine((headers, context) => {
const names = Object.keys(headers).map((name) => name.toLowerCase());
if (new Set(names).size !== names.length)
@@ -86,7 +95,7 @@ const replayActionSchema = z.discriminatedUnion("type", [
z.strictObject({
type: z.literal("http_response"),
status: z.number().int().min(100).max(599),
headers: z.record(z.string(), z.string()).default({}),
headers: z.record(headerNameSchema, headerValueSchema).default({}),
body: z.string().max(1_000_000),
}),
z.strictObject({
@@ -220,6 +229,14 @@ const validateReplayVariables = (
const capturedVariables = new Map<string, boolean>();
for (const [transitionIndex, transition] of machine.transitions.entries()) {
for (const capture of transition.captures) {
if (capture.sensitive && capture.value.source === "action_json")
context.addIssue({
code: "custom",
message:
"sensitive replay captures cannot read literal action JSON persisted in the replay plan",
path: ["transitions", transitionIndex, "captures"],
input: machine,
});
const sensitivity = capturedVariables.get(capture.variable);
if (sensitivity !== undefined && sensitivity !== capture.sensitive)
context.addIssue({
+36 -9
View File
@@ -4,12 +4,23 @@ import type { ReplayMachine } from "./replayMachine.js";
type ReplayTransition = ReplayMachine["transitions"][number];
type ReplayValueSource = ReplayTransition["captures"][number]["value"];
interface TransitionRecordOptions {
readonly sequence: number;
readonly atMs: number;
readonly stateBefore: string;
readonly transition: ReplayTransition;
readonly captures: readonly {
readonly variable: string;
readonly sensitive: boolean;
}[];
}
/** One bounded inbound protocol event offered to a replay machine. */
export interface ReplayMachineEvent {
readonly protocol: "http" | "websocket_connect" | "websocket_message";
readonly connection: "not_applicable" | "initial" | "reconnect";
readonly at_ms: number;
readonly recorded_at_ms?: number;
readonly method: string | null;
readonly path: string;
readonly headers: Readonly<Record<string, string>>;
@@ -19,6 +30,7 @@ export interface ReplayMachineEvent {
/** Persistable transition journal entry containing aliases, never secrets. */
export interface ReplayTransitionRecord {
readonly sequence: number;
readonly at_ms: number;
readonly transition_id: string;
readonly state_before: string;
readonly state_after: string;
@@ -141,6 +153,24 @@ const replayValuesEqual = (left: unknown, right: unknown): boolean =>
isJsonCompatible(right) &&
(Object.is(left, right) || canonicalize(left) === canonicalize(right));
const createTransitionRecord = ({
sequence,
atMs,
stateBefore,
transition,
captures,
}: TransitionRecordOptions): ReplayTransitionRecord => ({
sequence,
at_ms: atMs,
transition_id: transition.id,
state_before: stateBefore,
state_after: transition.to,
sensitive_aliases: captures
.filter(({ sensitive }) => sensitive)
.map(({ variable }) => variable)
.sort(),
});
/** Stateful evaluator for one validated replay-machine instance. */
export class ReplayMachineRuntime {
readonly #variables = new Map<string, unknown>();
@@ -267,16 +297,13 @@ export class ReplayMachineRuntime {
this.#sensitiveValues.set(capture.variable, values);
}
}
const record = {
const record = createTransitionRecord({
sequence: this.#timeline.length,
transition_id: transition.id,
state_before: this.#state,
state_after: transition.to,
sensitive_aliases: captures
.filter(({ sensitive }) => sensitive)
.map(({ variable }) => variable)
.sort(),
} satisfies ReplayTransitionRecord;
atMs: normalizedEvent.recorded_at_ms ?? normalizedEvent.at_ms,
stateBefore: this.#state,
transition,
captures,
});
this.#uses.set(transition.id, used + 1);
this.#stateVisits.set(transition.to, nextVisits);
this.#state = transition.to;
+5 -1
View File
@@ -451,7 +451,11 @@ const evidenceSection = (
if (section === "process")
return pick(result, ["process_samples", "exit", "settlement", "cleanup"]);
if (section === "protocol")
return pick(result, ["protocol_events", "shim_events"]);
return pick(result, [
"protocol_events",
"replay_transitions",
"shim_events",
]);
const value = result[section];
return value === undefined ? undefined : value;
};