feat(process): run finite-state replay during capture
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user