fix(environment): preserve literal values and recorded comparison chronology

This commit is contained in:
morluto committed 2026-10-24 02:29:08 +08:00
1 parent e327baa7b8
commit 23ab2c4069
11 files changed
+266 -65

No files matched your search

@@ -472,6 +472,27 @@ const compareRows = (
};
describe("ids the comparison used to misread", () => {
it.each([
["", "", true],
['""', "", false],
["null", "", true],
] as const)(
"compares a recorded missing-item body representation %j against %j",
(recorded, live, equal) => {
const probe = compareRows(
[
["GET", "/api/books", [FIRST_BOOK]],
["GET", "/api/books/1", FIRST_BOOK],
["GET", "/api/books/9", recorded, 404],
],
[
["GET", "/api/books", [{ ...FIRST_BOOK, id: 101 }]],
["GET", "/api/books/999", live, 404],
],
);
expect(probe.results[1]?.equal).toBe(equal);
},
);
it("reads a twice-encoded path id once, so book%2531 is not book1", () => {
const probe = compareRows(
[
@@ -767,6 +788,41 @@ describe("what a probe did not observe", () => {
expect(report.value.summary).toMatchObject({ steps: 2, equal: 2 });
});
it.each([
["0002", "0001"],
["002", "001"],
])(
"orders probe requests by complete fractional timestamps: %s after %s",
(readFraction, writeFraction) => {
const report = run(
analysisViewCaptureEvidence(
environmentManifestCaptureFixture([
{
...exchange(0, "GET", "http://app.example/api/books/2", 404),
startedDateTime: `2026-10-20T09:00:00.${readFraction}Z`,
response: {
status: 404,
content: {
mimeType: "application/json",
text: JSON.stringify(BOOK_NOT_FOUND),
},
},
},
{
...exchange(0, "DELETE", "http://app.example/api/books/2", 204),
startedDateTime: `2026-10-20T09:00:00.${writeFraction}Z`,
},
]),
),
);
if (!report.ok) throw report.error;
expect(report.value.summary).toMatchObject({ steps: 2, equal: 2 });
expect(
report.value.probes[0]?.results.map(({ ordinal }) => ordinal),
).toEqual([1, 0]);
},
);
it("refuses a browser probe that makes writes without recorded request bodies", () => {
const report = run(
scenarioCaptureEvidence(
@@ -157,8 +157,11 @@ const entityOf = (
return { scope, at, identity };
};
const fromState = (answer: ReplayResult): boolean =>
(answer as Partial<StateAnswer>).state?.source === "state";
const fromState = (answer: ReplayResult): boolean => {
const state = (answer as Partial<StateAnswer>).state;
// Missing-item selection comes from state, but its response is a recording.
return state?.source === "state" && state.view !== "missing";
};
/** Identity facts come from decoded JSON or text scalars, never binary presentations or truncated bodies. */
const identityValue = (body: ReplayedBody): JsonValue | undefined => {
@@ -359,7 +362,21 @@ const compareStep = (
entityAt: entity.at,
identity: entity.identity,
});
const compared = compareAnswers(live, env, run.map, entity);
const plan = run.store?.state.writes.get(call.tool.name);
const generatedFields = new Set(
fromState(answered.value) && plan?.served === true
? plan.rules.flatMap((rule) =>
rule.rule === "unique" ||
(rule.rule === "identity" && rule.generator !== "sequence")
? [rule.field]
: [],
)
: [],
);
const compared = compareAnswers(live, env, run.map, {
...entity,
generatedFields,
});
for (const key of NORMALISED_KEYS)
run.normalised[key] += compared.normalised[key];
const differences = [...compared.differences];
@@ -17,7 +17,7 @@ const compare = (
);
describe("compareAnswers", () => {
it("agrees on mapped ids, clocks of one format and generated values, and counts each", () => {
it("normalizes mapped ids and clocks while comparing unproven generated-looking values literally", () => {
const map = new IdMap();
map.learn(101, 1);
const result = compare(
@@ -35,16 +35,40 @@ describe("compareAnswers", () => {
},
map,
);
expect(result.differences).toEqual([]);
expect(
result.differences.map(({ category, pointer }) => [category, pointer]),
).toEqual([
["value", "/token"],
["value", "/uuid"],
]);
expect(result.normalised).toEqual({
ids: 1,
clocks: 1,
generated: 2,
generated: 0,
large_bodies: 0,
unobserved_bodies: 0,
});
});
it("normalizes string generation only at fields identified by an executed write plan", () => {
const result = compareAnswers(
{
status: 201,
body: { kind: "json", value: { token: "live-token", sku: "product2" } },
},
{
status: 201,
body: { kind: "json", value: { token: "env-token", sku: "product1" } },
},
new IdMap(),
{ generatedFields: new Set(["token"]) },
);
expect(result.differences).toMatchObject([
{ category: "value", pointer: "/sku" },
]);
expect(result.normalised.generated).toBe(1);
});
it("categorises status, missing and extra fields, values and clock formats", () => {
const result = compare(
{ name: "A", gone: 1, at: "2026-10-20T10:00:00.123+00:00" },
@@ -152,7 +176,7 @@ describe("compareAnswers", () => {
).toEqual([]);
});
it("reports a reordered set of scalars as order alone and reads epoch array items as clocks", () => {
it("reports scalar reordering and keeps unnamed epoch-shaped array measurements literal", () => {
expect(
compare(
{ access: ["a", "b", "c"] },
@@ -162,7 +186,7 @@ describe("compareAnswers", () => {
expect(
compare({ stats: [[1792450800, 3]] }, { stats: [[1792285200, 3]] })
.differences,
).toEqual([]);
).toMatchObject([{ category: "value", pointer: "/stats/0/0" }]);
});
});
@@ -1,6 +1,5 @@
import type { JsonObject } from "../../domain/analysisView/environmentStateRules.js";
import {
isUuid,
readClock,
type ClockFormat,
} from "../../domain/analysisView/environmentStateWriteValues.js";
@@ -74,43 +73,21 @@ const formatKey = (format: ClockFormat): string =>
? `epoch-${format.unit}`
: `iso${format.separator}${String(format.fraction)}${format.zone === "" ? "" : format.zone === "Z" ? "Z" : "offset"}`;
/** The format of a clock value: an ISO-8601 string, or an epoch number under a time-named field or as an array item. */
/** ISO text has its own clock syntax; numeric epochs require a time-named field. */
const clockFormat = (
value: JsonValue,
key: string | undefined,
): string | undefined => {
if (
typeof value === "number" &&
key !== undefined &&
!TIME_FIELD.test(key) &&
!TIME_FIELD_CAMEL.test(key)
(key === undefined ||
(!TIME_FIELD.test(key) && !TIME_FIELD_CAMEL.test(key)))
)
return undefined;
const clock = readClock(value);
return clock === undefined ? undefined : formatKey(clock.format);
};
const characterClasses = (text: string): string =>
[
...new Set(
text
.replaceAll(/\d/gu, "0")
.replaceAll(/[a-z]/gu, "a")
.replaceAll(/[A-Z]/gu, "A"),
),
]
.sort()
.join("");
/** Two values each side generated on its own: both UUIDs, or one length of eight or more with the same character classes and a digit. */
const generatedPair = (live: string, env: string): boolean =>
(isUuid(live) && isUuid(env)) ||
(live.length === env.length &&
live.length >= 8 &&
/\d/u.test(live) &&
/\d/u.test(env) &&
characterClasses(live) === characterClasses(env));
class Differ {
readonly differences: Difference[] = [];
readonly normalised: Normalised = {
@@ -128,6 +105,7 @@ class Differ {
readonly scope: string | undefined;
readonly at: string;
readonly identity: boolean;
readonly generatedFields: ReadonlySet<string>;
},
) {}
@@ -211,9 +189,11 @@ class Differ {
if (
typeof live === "string" &&
typeof env === "string" &&
at.own === true &&
key !== undefined &&
this.entity.generatedFields.has(key) &&
!this.map.hasLive(live) &&
!this.map.hasEnv(env) &&
generatedPair(live, env)
!this.map.hasEnv(env)
) {
this.normalised.generated += 1;
return;
@@ -375,12 +355,15 @@ export const compareAnswers = (
readonly scope?: string;
readonly at?: string;
readonly identity?: boolean;
/** Direct entity fields whose executed write plan proves independent generation. */
readonly generatedFields?: ReadonlySet<string>;
} = {},
): { readonly differences: Difference[]; readonly normalised: Normalised } => {
const differ = new Differ(map, {
scope: entity.scope,
at: entity.at ?? "",
identity: entity.identity === true,
generatedFields: entity.generatedFields ?? new Set(),
});
if (live.status !== env.status)
differ.add({
@@ -27,6 +27,41 @@ const compareRows = (
};
describe("environment comparison identifier semantics", () => {
it("reports changed business tokens and numeric arrays through the application comparison boundary", () => {
const probe = compareRows(
[
[
"GET",
"/api/measurements",
{ sku: "product1", samples: [1700000000] },
],
],
[
[
"GET",
"/api/measurements",
{ sku: "product2", samples: [1800000000] },
],
],
);
expect(probe.results[0]?.equal).toBe(false);
expect(
probe.results[0]?.differences.map(({ category, pointer }) => [
category,
pointer,
]),
).toEqual([
["value", "/sku"],
["value", "/samples/0"],
]);
expect(probe.normalised.generated).toBe(0);
expect(probe.normalised.clocks).toBe(0);
const same = compareRows(
[["GET", "/api/measurements", { samples: [1700000000] }]],
[["GET", "/api/measurements", { samples: [1700000000] }]],
);
expect(same.results[0]?.equal).toBe(true);
});
it("compares numeric format identifiers literally while normalizing actual clock fields", () => {
const fourcc = (value: string) => Buffer.from(value).readUInt32LE(0);
const probe = compareRows(
@@ -1,4 +1,8 @@
import { z } from "zod";
import {
compareClockInstants,
readClock,
} from "../../domain/analysisView/environmentStateWriteValues.js";
import { isJsonLike } from "../../domain/analysisView/EnvironmentManifestAccumulator.js";
import {
primaryOrigin,
@@ -46,10 +50,11 @@ const postDataSchema = z.object({
const methodSchema = z.object({ request: z.object({ method: z.string() }) });
const startedMs = (record: WebNetworkCaptureRecord): number | undefined => {
const startedClock = (
record: WebNetworkCaptureRecord,
): ReturnType<typeof readClock> => {
const started = startedSchema.safeParse(record.reported);
const ms = started.success ? Date.parse(started.data.startedDateTime) : NaN;
return Number.isFinite(ms) ? ms : undefined;
return started.success ? readClock(started.data.startedDateTime) : undefined;
};
/** Whether a probe makes calls that carry a request body: a POST, PUT or PATCH. */
@@ -118,13 +123,17 @@ export const probeRequests = (
const unobserved: UnobservedRecord[] = [];
// Without a start time for every record the probe keeps its recorded order, as state extraction does.
const starts = new Map(
records.map((record) => [record.ordinal, startedMs(record)]),
records.map((record) => [record.ordinal, startedClock(record)]),
);
const timed = [...starts.values()].every((ms) => ms !== undefined);
const ordered = [...records].sort(
(left, right) =>
(timed ? starts.get(left.ordinal)! - starts.get(right.ordinal)! : 0) ||
left.ordinal - right.ordinal,
(timed
? compareClockInstants(
starts.get(left.ordinal)!,
starts.get(right.ordinal)!,
)
: 0) || left.ordinal - right.ordinal,
);
const lines = new Map(
records.map((record) => [