perf(browser): share JSON shape paths across repeated array rows
Accumulate observations once per structural path instead of allocating and serializing a path for every payload value. Remove the CDP body-shape wrapper and retain primitive, empty-array, and literal-property semantics. Validation: CDP capture/comparison regressions and CLI/MCP boundary checks pass; 1,507 differential cases match the previous implementation. A 2.5 MB repeated-row workload improves from 105.0 ms to 14.6 ms warm median across alternating runs. Real browser providers were not exercised.
This commit is contained in:
@@ -27,8 +27,7 @@ export const ingestResponseBodyShape = (
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = inferBodyShape(decoded);
|
||||
updateResponseBodyShape(state, requestId, inferred.shape);
|
||||
updateResponseBodyShape(state, requestId, inferJsonShape(decoded));
|
||||
};
|
||||
|
||||
export const requestBodyShape = (
|
||||
@@ -40,10 +39,10 @@ export const requestBodyShape = (
|
||||
const body = cdpStringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = inferBodyShape(body);
|
||||
const shape = inferJsonShape(body);
|
||||
return {
|
||||
status: inferred.shape === null ? "unavailable" : "included",
|
||||
request: inferred.shape,
|
||||
status: shape === null ? "unavailable" : "included",
|
||||
request: shape,
|
||||
response: null,
|
||||
};
|
||||
};
|
||||
@@ -68,10 +67,6 @@ export const updateResponseBodyShape = (
|
||||
});
|
||||
};
|
||||
|
||||
const inferBodyShape = (text: string): { readonly shape: JsonShape | null } => {
|
||||
return { shape: inferJsonShape(text) };
|
||||
};
|
||||
|
||||
const invalidResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
|
||||
+47
-38
@@ -33,6 +33,15 @@ export const jsonShapeSchema = z.object({
|
||||
});
|
||||
export type JsonShape = z.infer<typeof jsonShapeSchema>;
|
||||
|
||||
const arrayElementKey = Symbol("array-element");
|
||||
|
||||
interface ShapeNode {
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly types: Set<JsonValueType>;
|
||||
observations: number;
|
||||
children?: Map<string | typeof arrayElementKey, ShapeNode>;
|
||||
}
|
||||
|
||||
/** Parse approved JSON and immediately discard values after iterative shape inference. */
|
||||
export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
let root: unknown;
|
||||
@@ -43,48 +52,52 @@ export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
void cause;
|
||||
return null;
|
||||
}
|
||||
const properties = new Map<
|
||||
string,
|
||||
{
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly types: Set<JsonValueType>;
|
||||
observations: number;
|
||||
}
|
||||
>();
|
||||
const properties: ShapeNode[] = [];
|
||||
const rootShape: ShapeNode = {
|
||||
path: [],
|
||||
types: new Set(),
|
||||
observations: 0,
|
||||
};
|
||||
// Each structural path owns one accumulator, shared by all matching array rows.
|
||||
const childShape = (
|
||||
parent: ShapeNode,
|
||||
key: string | typeof arrayElementKey,
|
||||
): ShapeNode => {
|
||||
const children = (parent.children ??= new Map());
|
||||
const existing = children.get(key);
|
||||
if (existing !== undefined) return existing;
|
||||
const node: ShapeNode = {
|
||||
path: [
|
||||
...parent.path,
|
||||
typeof key === "string"
|
||||
? { kind: "property", name: key }
|
||||
: { kind: "array-element" },
|
||||
],
|
||||
types: new Set(),
|
||||
observations: 0,
|
||||
};
|
||||
children.set(key, node);
|
||||
properties.push(node);
|
||||
return node;
|
||||
};
|
||||
const pending: Array<{
|
||||
readonly value: unknown;
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly depth: number;
|
||||
}> = [{ value: root, path: [], depth: 0 }];
|
||||
readonly shape: ShapeNode;
|
||||
}> = [{ value: root, shape: rootShape }];
|
||||
let nodeCount = 0;
|
||||
let maxDepthObserved = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodeCount += 1;
|
||||
maxDepthObserved = Math.max(maxDepthObserved, current.depth);
|
||||
if (current.path.length > 0) {
|
||||
const key = JSON.stringify(current.path);
|
||||
const type = jsonValueType(current.value);
|
||||
const existing = properties.get(key);
|
||||
if (existing === undefined)
|
||||
properties.set(key, {
|
||||
path: current.path,
|
||||
types: new Set([type]),
|
||||
observations: 1,
|
||||
});
|
||||
else {
|
||||
existing.types.add(type);
|
||||
existing.observations += 1;
|
||||
}
|
||||
}
|
||||
maxDepthObserved = Math.max(maxDepthObserved, current.shape.path.length);
|
||||
current.shape.types.add(jsonValueType(current.value));
|
||||
current.shape.observations += 1;
|
||||
if (Array.isArray(current.value)) {
|
||||
if (current.value.length === 0) continue;
|
||||
const shape = childShape(current.shape, arrayElementKey);
|
||||
for (let index = current.value.length - 1; index >= 0; index -= 1)
|
||||
pending.push({
|
||||
value: current.value[index],
|
||||
path: [...current.path, { kind: "array-element" }],
|
||||
depth: current.depth + 1,
|
||||
});
|
||||
pending.push({ value: current.value[index], shape });
|
||||
continue;
|
||||
}
|
||||
if (!isRecord(current.value)) continue;
|
||||
@@ -93,18 +106,14 @@ export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
const entry = allEntries[index];
|
||||
if (entry === undefined) continue;
|
||||
const [name, value] = entry;
|
||||
const path: JsonShapePathSegment[] = [
|
||||
...current.path,
|
||||
{ kind: "property", name },
|
||||
];
|
||||
pending.push({ value, path, depth: current.depth + 1 });
|
||||
pending.push({ value, shape: childShape(current.shape, name) });
|
||||
}
|
||||
}
|
||||
return jsonShapeSchema.parse({
|
||||
root_type: jsonValueType(root),
|
||||
node_count: nodeCount,
|
||||
max_depth_observed: maxDepthObserved,
|
||||
properties: [...properties.values()]
|
||||
properties: properties
|
||||
.map((value) => ({
|
||||
path: value.path,
|
||||
types: [...value.types].sort(),
|
||||
|
||||
@@ -39,6 +39,68 @@ const equivalentBodies = [
|
||||
},
|
||||
];
|
||||
|
||||
it("captures all repeated array rows and empty arrays without retaining payload values", async () => {
|
||||
const count = 6_000;
|
||||
const body = JSON.stringify(
|
||||
Array.from({ length: count }, (_, index) => ({
|
||||
value: index % 2 === 0 ? index : "payload-value-excluded",
|
||||
nested: index % 2 === 0 ? [] : [true, null],
|
||||
empty: [],
|
||||
"*": { "": "payload-value-excluded" },
|
||||
})),
|
||||
);
|
||||
const before = captureBody("base64 response", body);
|
||||
const shape = before.network.requests[0]?.body_shapes.response;
|
||||
const element = { kind: "array-element" };
|
||||
const property = (name: string) => ({ kind: "property", name });
|
||||
expect(shape).toMatchObject({
|
||||
root_type: "array",
|
||||
node_count: count * 7 + 1,
|
||||
max_depth_observed: 3,
|
||||
properties: [
|
||||
{ path: [element], types: ["object"], observations: count },
|
||||
{
|
||||
path: [element, property("*")],
|
||||
types: ["object"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("*"), property("")],
|
||||
types: ["string"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("empty")],
|
||||
types: ["array"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("nested")],
|
||||
types: ["array"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("nested"), element],
|
||||
types: ["boolean", "null"],
|
||||
observations: count,
|
||||
},
|
||||
{
|
||||
path: [element, property("value")],
|
||||
types: ["number", "string"],
|
||||
observations: count,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(shape)).not.toContain("payload-value-excluded");
|
||||
const after = captureBody("base64 response", body);
|
||||
expect(
|
||||
(await compareCaptures(before, after)).dimensions.network,
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
total_changes: 0,
|
||||
});
|
||||
});
|
||||
|
||||
describe.each<BodySource>(["request", "response", "base64 response"])(
|
||||
"CDP %s JSON shape comparison",
|
||||
(source) => {
|
||||
|
||||
Reference in New Issue
Block a user