feat(process): compare declared concurrent traces

This commit is contained in:
morluto
2026-07-23 05:27:49 +08:00
parent d895e49145
commit d81745cb95
18 changed files with 1161 additions and 102 deletions
+11 -1
View File
@@ -24,6 +24,7 @@ const right = source("2");
const comparison = (
operation: "compare_process_captures" | "compare_artifacts",
result: JsonValue,
processPredicateVersion: "v3" | "v4" = "v3",
): Evidence => {
const process = operation === "compare_process_captures";
return createEvidence(
@@ -37,7 +38,7 @@ const comparison = (
},
{
predicateType: process
? "rea.process-comparison/v3"
? `rea.process-comparison/${processPredicateVersion}`
: "rea.artifact-comparison/v1",
operation,
parameters: {},
@@ -123,6 +124,15 @@ const artifactResult = (
});
describe("changed behavior", () => {
it("accepts declared-trace process comparison Evidence v4", () => {
const result = findChangedBehavior(
[comparison("compare_process_captures", processResult(), "v4")],
0,
100,
);
expect(result.behavior_status).toBe("observed_unchanged");
});
it("reports interaction and shim-only process changes", () => {
const evidence = comparison(
"compare_process_captures",
+361
View File
@@ -0,0 +1,361 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, describe, expect, it } from "vitest";
import { BinarySession } from "../src/application/BinarySession.js";
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
import { compareProcessEvidenceFiles } from "../src/application/ProcessCli.js";
import { PROCESS_PROVIDER } from "../src/application/ProcessEvidence.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../src/contracts/processCaptureExample.js";
import { createEvidence, parseEvidence } from "../src/domain/evidence.js";
import { jsonValueSchema } from "../src/domain/jsonValue.js";
import {
compareProcessCaptures,
processCaptureSchema,
} from "../src/domain/processCapture.js";
import type { ProcessTraceSpecification } from "../src/domain/processTraceComparison.js";
import { observed as ok } from "./fixtures/analysisExecution.js";
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
import { createServer } from "../src/server/createServer.js";
const resources: Array<{ close(): Promise<void> }> = [];
const temporaryRoots: string[] = [];
const beforeCheckpoint = {
name: "before",
at_ms: 0,
files: [],
effects: [],
truncated: false,
};
const afterCheckpoint = {
name: "after_settlement",
at_ms: 50,
files: [],
effects: [],
truncated: false,
};
afterEach(async () => {
await Promise.all(resources.splice(0).map((resource) => resource.close()));
await Promise.all(
temporaryRoots
.splice(0)
.map((root) => rm(root, { recursive: true, force: true })),
);
});
const capture = {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
event_journal: [
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
{ capture_order: 1, collection: "lifecycle", index: 0 },
{ capture_order: 2, collection: "lifecycle", index: 1 },
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
],
} as const;
const traceSpecification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "before",
source: "filesystem",
exact: beforeCheckpoint,
cardinality: { kind: "required" },
},
{
id: "exit",
source: "lifecycle",
exact: { event: "exit", ...capture.exit },
cardinality: { kind: "required" },
},
{
id: "settlement",
source: "lifecycle",
exact: { event: "settlement", ...capture.settlement },
cardinality: { kind: "required" },
},
{
id: "after",
source: "filesystem",
exact: afterCheckpoint,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [
{
id: "normal",
trace: ["before", "exit", "settlement", "after"],
},
],
},
};
const captureEvidence = (side: "left" | "right") =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4",
operation: "capture_process_scenario",
parameters: { side },
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
locations: [{ kind: "artifact-path", path: `/fixture/${side}` }],
});
describe("declared trace comparison adapters", () => {
it("treats only explicitly ignored schedule metadata as reorderable", () => {
const httpPayload = {
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocketPayload = {
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const scheduledCapture = (order: "http-first" | "websocket-first") => {
const protocolEvents =
order === "http-first"
? [
{ sequence: 0, at_ms: 1, ...httpPayload },
{ sequence: 1, at_ms: 2, ...websocketPayload },
]
: [
{ sequence: 0, at_ms: 1, ...websocketPayload },
{ sequence: 1, at_ms: 2, ...httpPayload },
];
return processCaptureSchema.parse({
...capture,
protocol_events: protocolEvents,
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
};
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "status",
source: "http",
exact: httpPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocketPayload,
ignore_fields: ["sequence", "at_ms"],
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [],
unordered_groups: [{ events: ["status", "done"] }],
prefix: [],
suffix: [],
},
};
expect(
compareProcessCaptures(
scheduledCapture("http-first"),
scheduledCapture("websocket-first"),
{ traceSpecification: specification },
),
).toMatchObject({
status: "unchanged",
protocol: "unchanged",
trace: {
verdict: "equivalent",
left: { raw_trace: [{ event_id: "status" }, { event_id: "done" }] },
right: { raw_trace: [{ event_id: "done" }, { event_id: "status" }] },
},
});
});
it("does not mask an unselected source in a covered legacy dimension", () => {
const http = {
sequence: 0,
at_ms: 1,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "unmatched" as const,
};
const websocket = (data: string) => ({
sequence: 1,
at_ms: 2,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data,
outcome: "matched" as const,
});
const withProtocol = (data: string) =>
processCaptureSchema.parse({
...capture,
protocol_events: [http, websocket(data)],
event_journal: [
{
capture_order: 0,
collection: "filesystem_checkpoints",
index: 0,
},
{ capture_order: 1, collection: "protocol_events", index: 0 },
{ capture_order: 2, collection: "protocol_events", index: 1 },
{ capture_order: 3, collection: "lifecycle", index: 0 },
{ capture_order: 4, collection: "lifecycle", index: 1 },
{
capture_order: 5,
collection: "filesystem_checkpoints",
index: 1,
},
],
});
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "status", trace: ["status"] }],
},
};
expect(
compareProcessCaptures(withProtocol("left"), withProtocol("right"), {
traceSpecification: specification,
}),
).toMatchObject({
status: "changed",
protocol: "changed",
trace: { verdict: "equivalent" },
});
});
it("does not call identical captures changed when both violate the language", () => {
const parsedCapture = processCaptureSchema.parse(capture);
const specification: ProcessTraceSpecification = {
...traceSpecification,
language: {
kind: "finite_traces",
variants: [
{
id: "reversed",
trace: ["after", "settlement", "exit", "before"],
},
],
},
};
expect(
compareProcessCaptures(parsedCapture, parsedCapture, {
traceSpecification: specification,
}),
).toMatchObject({
status: "unchanged",
trace: { verdict: "different" },
});
});
it("returns identical CLI and MCP results and derived Evidence identity", async () => {
const left = captureEvidence("left");
const right = captureEvidence("right");
const root = await createTestTempDirectory("rea-trace-adapters-");
temporaryRoots.push(root);
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
const specificationPath = join(root, "trace.json");
await Promise.all([
writeFile(leftPath, JSON.stringify(left)),
writeFile(rightPath, JSON.stringify(right)),
writeFile(specificationPath, JSON.stringify(traceSpecification)),
]);
const cliEvidence = parseEvidence(
await compareProcessEvidenceFiles(leftPath, rightPath, specificationPath),
);
const session = new BinarySession(
(_path) =>
({
execute: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(),
}) satisfies AnalysisClient,
);
expect(session.recordEvidence(left).ok).toBe(true);
expect(session.recordEvidence(right).ok).toBe(true);
const server = createServer(
{ execute: () => Promise.resolve(ok(null)) },
session,
);
const client = new Client({ name: "trace-parity", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
resources.push(client, server);
await server.connect(serverTransport);
await client.connect(clientTransport);
const response = await client.callTool({
name: "compare_process_captures",
arguments: {
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
trace_spec: traceSpecification,
},
});
expect(response.isError).not.toBe(true);
expect(response.structuredContent).toMatchObject({
result: { trace: { verdict: "equivalent" } },
evidence_id: cliEvidence.evidence_id,
});
const structuredResult =
typeof response.structuredContent === "object" &&
response.structuredContent !== null
? Reflect.get(response.structuredContent, "result")
: undefined;
expect(structuredResult).toEqual(cliEvidence.normalized_result);
expect(cliEvidence).toMatchObject({
predicate_type: "rea.process-comparison/v4",
locations: [
{ kind: "artifact-path", path: "/fixture/left" },
{ kind: "artifact-path", path: "/fixture/right" },
],
});
});
});
+451
View File
@@ -0,0 +1,451 @@
import { describe, expect, it } from "vitest";
import type { ProcessCapture } from "../src/domain/processCapture.js";
import {
compareProcessTraces,
processTraceSpecificationSchema,
type ProcessTraceSpecification,
} from "../src/domain/processTraceComparison.js";
const capture = (
values: Pick<
ProcessCapture,
| "frames"
| "process_samples"
| "filesystem_checkpoints"
| "protocol_events"
| "shim_events"
> & {
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
},
options: {
readonly truncated?: boolean;
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
} = {},
): ProcessCapture => ({
schema_version: 4,
manifest: {
rea_version: "test",
provider_version: "3",
platform: "linux",
architecture: "x64",
pty_backend: "node-pty",
started_at: "2026-01-01T00:00:00.000Z",
completed_at: "2026-01-01T00:00:01.000Z",
scenario: {},
comparison_contract: {},
shim_plan: [],
replay_plan: {},
full_scenario_sha256: "0".repeat(64),
comparison_contract_sha256: "1".repeat(64),
executable_sha256: "2".repeat(64),
normalization_sha256: "3".repeat(64),
shim_plan_sha256: "4".repeat(64),
replay_plan_sha256: "5".repeat(64),
},
normalization: {
paths: true,
pids: true,
ports: true,
time_bucket_ms: 10,
patterns: [],
},
frames: values.frames,
rendered_frames: [],
interaction_events: [],
exit: { code: 0, signal: null, reason: "exited" },
settlement: {
state: "quiesced",
elapsed_ms: 10,
cleanup_outcome: "not_required",
},
process_samples: values.process_samples,
filesystem_checkpoints: values.filesystem_checkpoints,
shim_events: values.shim_events,
protocol_events: values.protocol_events,
replay_transitions: [],
event_journal: values.event_journal,
files_before: [],
files_after: [],
filesystem_effects: [],
truncated: options.truncated ?? false,
limitations: [],
residual_unknowns: options.residualUnknowns ?? [],
cleanup: {
owned_process_group: "verified",
temporary_root: "removed",
},
});
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
const processStarted = {
at_ms: 1,
pid: 1,
parent_pid: 0,
command: "worker",
process_group_id: 1,
session_id: 1,
};
const http = {
sequence: 0,
at_ms: 2,
protocol: "http" as const,
direction: "request" as const,
method: "GET",
path: "/status",
data: "",
outcome: "matched" as const,
};
const websocket = {
sequence: 1,
at_ms: 3,
protocol: "websocket" as const,
direction: "received" as const,
method: null,
path: "/ws",
data: "done",
outcome: "matched" as const,
};
const values = (
order: readonly ("terminal" | "process" | "http" | "websocket")[],
): Parameters<typeof capture>[0] => ({
frames: [terminal],
process_samples: [processStarted],
filesystem_checkpoints: [],
protocol_events: [http, websocket],
shim_events: [],
event_journal: order.map((event, captureOrder) => ({
capture_order: captureOrder,
collection:
event === "terminal"
? "frames"
: event === "process"
? "process_samples"
: "protocol_events",
index: event === "websocket" ? 1 : 0,
})),
});
const partialSpecification = (): ProcessTraceSpecification => ({
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "worker",
source: "process",
exact: processStarted,
cardinality: { kind: "required" },
},
{
id: "status",
source: "http",
exact: http,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "ready", after: "status" },
{ before: "worker", after: "done" },
{ before: "status", after: "done" },
],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [{ events: ["worker", "status"] }],
prefix: ["ready"],
suffix: ["done"],
},
});
describe("process trace specification", () => {
it("rejects cycles, implicit concurrency, overlap, and unsatisfiable variants", () => {
const base = partialSpecification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
unordered_groups: [{ events: ["status", "done"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
id: "invalid-ignore",
source: "terminal_raw",
exact: "ready",
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
id: "invalid-ignore",
source: "terminal_raw",
exact: terminal,
ignore_fields: ["at_ms"],
},
],
language: {
kind: "finite_traces",
variants: [{ id: "one", trace: ["invalid-ignore"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: base.events.slice(0, 2),
language: { kind: "partial_order" },
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [base.events[0], { ...base.events[0], id: "duplicate" }],
language: {
kind: "partial_order",
unordered_groups: [{ events: ["ready", "duplicate"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [
{
...base.events[0],
cardinality: { kind: "exact", count: 2 },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "once", trace: ["ready"] }],
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
version: 1,
events: [base.events[0]],
language: {
kind: "finite_traces",
variants: [
{ id: "first", trace: ["ready"] },
{ id: "duplicate", trace: ["ready"] },
],
},
}).success,
).toBe(false);
});
});
describe("process trace comparison", () => {
it("accepts only explicitly declared concurrent schedules without timestamp causality", () => {
const left = capture(values(["terminal", "process", "http", "websocket"]));
const right = capture(values(["terminal", "http", "process", "websocket"]));
const comparison = compareProcessTraces(
left,
right,
partialSpecification(),
);
expect(comparison.verdict).toBe("equivalent");
expect(comparison.left.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"worker",
"status",
"done",
]);
expect(comparison.right.raw_trace.map(({ event_id }) => event_id)).toEqual([
"ready",
"status",
"worker",
"done",
]);
expect(comparison.left.satisfied_constraints).toContain(
"unordered:worker:status",
);
});
it("returns the minimal journal slice for a reversed required edge", () => {
const baseline = capture(
values(["terminal", "process", "http", "websocket"]),
);
const reversed = capture(
values(["process", "terminal", "http", "websocket"]),
);
const comparison = compareProcessTraces(
baseline,
reversed,
partialSpecification(),
);
expect(comparison).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["ready", "worker"],
locations: [{ capture_order: 1 }, { capture_order: 0 }],
},
});
});
it("enforces explicit negative not-before constraints", () => {
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "ready",
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
{
id: "done",
source: "websocket",
exact: websocket,
cardinality: { kind: "required" },
},
],
language: {
kind: "partial_order",
happens_before: [],
not_before: [{ event: "done", anchor: "ready" }],
unordered_groups: [],
prefix: [],
suffix: [],
},
};
const normal = capture(
values(["terminal", "process", "http", "websocket"]),
);
const invalid = capture(
values(["websocket", "terminal", "process", "http"]),
);
expect(compareProcessTraces(normal, invalid, specification)).toMatchObject({
verdict: "different",
diagnostic: {
kind: "edge",
side: "right",
event_ids: ["done", "ready"],
},
});
});
it("supports declared optional events and bounded duplicates", () => {
const first = { sequence: 0, at_ms: 1, data: "tick" };
const second = { sequence: 1, at_ms: 2, data: "tick" };
const one = capture({
frames: [first],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [{ capture_order: 0, collection: "frames", index: 0 }],
});
const two = capture({
frames: [first, second],
process_samples: [],
filesystem_checkpoints: [],
protocol_events: [],
shim_events: [],
event_journal: [
{ capture_order: 0, collection: "frames", index: 0 },
{ capture_order: 1, collection: "frames", index: 1 },
],
});
const specification: ProcessTraceSpecification = {
version: 1,
events: [
{
id: "tick1",
source: "terminal_raw",
exact: first,
cardinality: { kind: "required" },
},
{
id: "tick2",
source: "terminal_raw",
exact: second,
cardinality: { kind: "optional" },
},
],
language: {
kind: "finite_traces",
variants: [
{ id: "one", trace: ["tick1"] },
{ id: "two", trace: ["tick1", "tick2"] },
],
},
};
expect(compareProcessTraces(one, two, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "one" },
right: { matched_variant: "two" },
});
});
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
const complete = capture(
values(["terminal", "process", "http", "websocket"]),
);
const truncated = capture(
values(["terminal", "process", "http", "websocket"]),
{ truncated: true },
);
expect(
compareProcessTraces(complete, truncated, partialSpecification()).verdict,
).toBe("unknown");
const unknown = capture(
values(["terminal", "process", "http", "websocket"]),
{ residualUnknowns: [{ scope: "protocol", reason: "gap" }] },
);
expect(
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
).toBe("unknown");
const noJournal = capture({ ...values([]), event_journal: [] });
const comparison = compareProcessTraces(
complete,
noJournal,
partialSpecification(),
);
expect(comparison).toMatchObject({
verdict: "unknown",
diagnostic: { kind: "journal", side: "right" },
});
});
});