From 185491879816fccd925ec2f75cd1ed2146423845 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:10:41 -0500 Subject: [PATCH] perf(analysis-view): retain frozen snapshots across parent readers and index view lookups (#13315) * perf(analysis-view): retain frozen snapshots across parent readers and index view lookups * perf(analysis-view): use bounded k-way merge for multi-bucket fact pages --- src/domain/analysisView/analysisView.test.ts | 833 +++++++++++++++++- src/domain/analysisView/analysisView.ts | 35 +- .../analysisView/analysisViewParent.test.ts | 33 + src/domain/analysisView/analysisViewParent.ts | 6 +- .../analysisView/commandObservationView.ts | 13 +- src/domain/analysisView/dartAotView.ts | 6 +- src/domain/analysisView/evmInterfaceView.ts | 6 +- .../analysisView/fridaSessionStatusView.ts | 8 +- .../analysisView/javascriptApplicationView.ts | 206 ++++- .../analysisView/javascriptFactsView.ts | 365 +++++++- .../analysisView/javascriptRoutesView.test.ts | 52 ++ .../analysisView/javascriptRoutesView.ts | 45 +- src/domain/analysisView/machoView.ts | 6 +- .../analysisView/managedArtifactView.ts | 11 +- .../analysisView/pcapCaptureView.test.ts | 102 ++- src/domain/analysisView/pcapCaptureView.ts | 84 +- .../analysisView/protobufCaptureView.test.ts | 126 ++- src/domain/analysisView/wasmArtifactView.ts | 6 +- .../analysisView/webNetworkCaptureView.ts | 16 +- 19 files changed, 1817 insertions(+), 142 deletions(-) diff --git a/src/domain/analysisView/analysisView.test.ts b/src/domain/analysisView/analysisView.test.ts index f35d748465..57f0c2c268 100644 --- a/src/domain/analysisView/analysisView.test.ts +++ b/src/domain/analysisView/analysisView.test.ts @@ -3,8 +3,15 @@ import { completeWithinViewCoverage, pageViewCoverage, } from "./analysisViewCoverage.js"; -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; +import { freezeJsonSnapshot } from "../immutableJson.js"; +import { byteEntropySchema } from "../native/byteEntropy.js"; +import * as jsApplicationAnalysis from "../javascript/javascriptApplicationAnalysis.js"; +import { + javascriptFactsViewRequestSchema, + projectJavaScriptFacts, +} from "./javascriptFactsView.js"; import { functionDossierSchema } from "../native/functionDossier.js"; import { ghidraFunctionDossier } from "../ghidraValues.fixture.js"; import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js"; @@ -27,7 +34,10 @@ import { } from "../javascript/javascriptSemanticGraph.js"; import { sourceMapReference } from "../javascript/javascriptApplicationGraph.fixture.js"; import { createArtifactInspection } from "../artifactInspection.js"; -import { inspectAnalysisViewInputSchema } from "./analysisViewRequest.js"; +import { + inspectAnalysisViewInputSchema, + type AnalysisViewRequest, +} from "./analysisViewRequest.js"; import { projectAnalysisView } from "./analysisView.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { analysisViewResultSchema } from "./analysisViewResult.js"; @@ -1849,3 +1859,822 @@ it("ranks only the longest byte entropy runs with stable offset ties", () => { }, }); }); + +const multiModuleJavaScriptAnalysis = () => { + const base = analysisViewJavaScriptAnalysis(); + const baseObs = base.graph.nodes[0]!.observations[0]!; + const makeNode = ( + kind: "javascript-asset" | "javascript-module", + path: string, + shaSuffix: string, + extraPaths: readonly string[] = [], + ) => { + const sha256 = shaSuffix.repeat(64); + const makeObs = (obsPath: string | null, tag: string) => ({ + label: tag, + properties: { ...(obsPath === null ? {} : { path: obsPath }), tag }, + evidence: { + ...baseObs.evidence, + ...(obsPath === null + ? { + state: "inferred" as const, + confidence: "medium" as const, + limitations: ["Inferred without source location"], + } + : {}), + artifact: { + available: true as const, + artifact_id: `art_${sha256}`, + sha256, + }, + location: + obsPath === null + ? { + available: false as const, + reason: "not-applicable" as const, + detail: "Location omitted", + } + : { + available: true as const, + value: { kind: "artifact-path" as const, path: obsPath }, + }, + }, + }); + return createJavaScriptApplicationNode({ + kind, + identity: { + strategy: "content-digest", + stability: "global-exact", + sha256, + }, + observations: [ + makeObs(path, `${tagPrefix(kind)}:${path}`), + ...extraPaths.map((extra) => + makeObs(extra, `${tagPrefix(kind)}:${extra}`), + ), + makeObs(null, `${tagPrefix(kind)}:noloc`), + ], + }); + }; + const tagPrefix = (kind: "javascript-asset" | "javascript-module") => + kind === "javascript-asset" ? "asset" : "mod"; + const assetA = makeNode("javascript-asset", "a.js", "1", ["b.js"]); + const modB = makeNode("javascript-module", "b.js", "2"); + const assetA2 = makeNode("javascript-asset", "a.js", "3"); + const modC = makeNode("javascript-module", "c.js", "4"); + const { graph_id: _gid, ...restGraph } = base.graph; + const graph = createJavaScriptApplicationGraph({ + ...restGraph, + root_node_ids: [base.graph.nodes[0]!.node_id], + nodes: [base.graph.nodes[0]!, assetA, modB, assetA2, modC], + edges: [], + }); + return { + analysis: analysisViewBindJavaScriptGraphs(base, graph), + ids: { + assetA: assetA.node_id, + modB: modB.node_id, + assetA2: assetA2.node_id, + modC: modC.node_id, + }, + }; +}; + +it("preserves exact parity and WeakMap reuse for indexed JavaScript module and fact views", () => { + const { analysis, ids } = multiModuleJavaScriptAnalysis(); + const unsealed = javascriptParent(analysis); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: freezeJsonSnapshot(structuredClone(analysis)), + }; + const parseSpy = vi.spyOn( + jsApplicationAnalysis, + "parseOwnedJavaScriptApplicationAnalysisSteps", + ); + try { + const views: AnalysisViewRequest[] = [ + { kind: "summary" }, + { kind: "item", collection: "modules", selector: { node_id: ids.modB } }, + { kind: "item", collection: "modules", selector: { node_id: "missing" } }, + { kind: "item", collection: "modules", selector: { path: "c.js" } }, + { kind: "item", collection: "modules", selector: { path: "a.js" } }, + { kind: "item", collection: "modules", selector: { path: "none.js" } }, + { kind: "page", collection: "modules", offset: 1, limit: 2 }, + { + kind: "javascript", + collection: "modules", + projection: "references", + where: {}, + offset: 1, + limit: 2, + }, + { + kind: "javascript", + collection: "modules", + projection: "references", + where: { path: "b.js" }, + offset: 0, + limit: 10, + }, + { + kind: "javascript", + collection: "modules", + projection: "references", + where: { kind: "javascript-module" }, + offset: 0, + limit: 10, + }, + { + kind: "javascript", + collection: "modules", + projection: "references", + where: { kind: "javascript-asset", path: "b.js" }, + offset: 0, + limit: 10, + }, + { + kind: "javascript-facts", + where: {}, + property_keys: ["tag", "path"], + include_available_property_keys: true, + offset: 1, + limit: 5, + }, + { + kind: "javascript-facts", + where: { kinds: ["javascript-asset"], paths: ["a.js"] }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 0, + limit: 10, + }, + { + kind: "javascript-facts", + where: { + kinds: ["javascript-module", "javascript-asset"], + paths: ["b.js", "a.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 1, + limit: 4, + }, + { + kind: "javascript-facts", + where: { kinds: [] }, + property_keys: [], + include_available_property_keys: false, + offset: 0, + limit: 10, + }, + ]; + + const sealedResults = views.map((view) => + projectAnalysisView(sealed, view), + ); + expect(parseSpy).toHaveBeenCalledTimes(1); + for (const [index, view] of views.entries()) { + const sealedRes = sealedResults[index]!; + const unsealedRes = projectAnalysisView(unsealed, view); + expect(sealedRes.ok).toBe(unsealedRes.ok); + if (sealedRes.ok && unsealedRes.ok) + expect(sealedRes.value).toEqual(unsealedRes.value); + } + expect(parseSpy).toHaveBeenCalledTimes(1 + views.length); + + const factView = inspectAnalysisViewInputSchema.parse({ + source: { kind: "inline", evidence: {} }, + view: { + kind: "javascript-facts", + where: { + kinds: ["javascript-module", "javascript-asset"], + paths: ["b.js", "a.js"], + }, + property_keys: ["tag"], + offset: 0, + limit: 10, + }, + }).view; + if (factView.kind !== "javascript-facts") throw new Error("wrong view"); + expect( + projectJavaScriptFacts( + (sealed.normalizedResult as typeof analysis).graph.nodes, + factView, + sealed.normalizedResult as object, + ), + ).toEqual(projectJavaScriptFacts(analysis.graph.nodes, factView)); + } finally { + parseSpy.mockRestore(); + } +}); + +const interleavedFactsJavaScriptAnalysis = () => { + const base = analysisViewJavaScriptAnalysis(); + const baseObs = base.graph.nodes[0]!.observations[0]!; + type FactKind = + | "javascript-asset" + | "javascript-module" + | "javascript-expression" + | "browser-window" + | "native-addon"; + type ObsSpec = + | { + readonly kind: "artifact-path"; + readonly path: string; + readonly tag: string; + } + | { + readonly kind: "source-range"; + readonly source: string; + readonly tag: string; + } + | { readonly kind: "url"; readonly url: string; readonly tag: string } + | { readonly kind: "unavailable"; readonly tag: string }; + + let counter = 0; + const makeNode = (kind: FactKind, specs: readonly ObsSpec[]) => { + counter += 1; + const hex = counter.toString(16).padStart(2, "0"); + const sha256 = hex.repeat(32); + return createJavaScriptApplicationNode({ + kind, + identity: { + strategy: "content-digest", + stability: "global-exact", + sha256, + }, + observations: specs.map((spec) => ({ + label: spec.tag, + properties: { + tag: spec.tag, + ...(spec.kind === "artifact-path" + ? { path: spec.path } + : spec.kind === "source-range" + ? { path: spec.source } + : {}), + }, + evidence: { + ...baseObs.evidence, + ...(spec.kind === "unavailable" + ? { + state: "inferred" as const, + confidence: "medium" as const, + limitations: ["Inferred without source location"], + } + : {}), + artifact: { + available: true as const, + artifact_id: `art_${sha256}`, + sha256, + }, + location: + spec.kind === "artifact-path" + ? { + available: true as const, + value: { kind: "artifact-path" as const, path: spec.path }, + } + : spec.kind === "source-range" + ? { + available: true as const, + value: { + kind: "source-range" as const, + source: spec.source, + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 }, + }, + } + : spec.kind === "url" + ? { + available: true as const, + value: { kind: "url" as const, url: spec.url }, + } + : { + available: false as const, + reason: "not-applicable" as const, + detail: "Location omitted", + }, + }, + })), + }); + }; + + const nodes = [ + base.graph.nodes[0]!, + makeNode("javascript-asset", [ + { kind: "artifact-path", path: "a.js", tag: "asset-a-1" }, + { kind: "artifact-path", path: "b.js", tag: "asset-b-1" }, + { kind: "source-range", source: "d.js", tag: "asset-d-1" }, + ]), + makeNode("javascript-module", [ + { kind: "artifact-path", path: "b.js", tag: "mod-b-1" }, + { kind: "artifact-path", path: "a.js", tag: "mod-a-1" }, + { kind: "unavailable", tag: "mod-noloc-1" }, + ]), + makeNode("browser-window", [ + { kind: "artifact-path", path: "c.js", tag: "win-c-1" }, + { + kind: "url", + url: "https://example.invalid/app.html", + tag: "win-url-1", + }, + ]), + makeNode("javascript-expression", [ + { kind: "source-range", source: "d.js", tag: "expr-d-1" }, + { kind: "artifact-path", path: "a.js", tag: "expr-a-1" }, + ]), + makeNode("javascript-module", [ + { kind: "source-range", source: "d.js", tag: "mod-d-1" }, + { kind: "artifact-path", path: "b.js", tag: "mod-b-2" }, + ]), + // Skewed large bucket in (javascript-asset, a.js) plus small interleaved entries + makeNode( + "javascript-asset", + Array.from({ length: 14 }, (_, idx) => ({ + kind: "artifact-path" as const, + path: "a.js", + tag: `asset-a-bulk-${idx}`, + })), + ), + makeNode("native-addon", [ + { kind: "artifact-path", path: "c.js", tag: "addon-c-1" }, + ]), + makeNode("javascript-asset", [ + { kind: "artifact-path", path: "b.js", tag: "asset-b-2" }, + { kind: "artifact-path", path: "a.js", tag: "asset-a-2" }, + ]), + makeNode("browser-window", [ + { kind: "artifact-path", path: "a.js", tag: "win-a-1" }, + ]), + ]; + + const { graph_id: _gid, ...restGraph } = base.graph; + const graph = createJavaScriptApplicationGraph({ + ...restGraph, + root_node_ids: [base.graph.nodes[0]!.node_id], + nodes, + edges: [], + }); + return analysisViewBindJavaScriptGraphs(base, graph); +}; + +it("paginates multi-bucket JavaScript facts with exact parity across kinds, paths, and combined filters", () => { + const analysis = interleavedFactsJavaScriptAnalysis(); + const unsealed = javascriptParent(analysis); + const sealedResult = freezeJsonSnapshot(structuredClone(analysis)); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: sealedResult, + }; + const sealedNodes = (sealedResult as typeof analysis).graph.nodes; + + const whereModes: readonly { + readonly paths?: readonly string[]; + readonly kinds?: readonly (typeof analysis.graph.nodes)[number]["kind"][]; + }[] = [ + { kinds: ["javascript-asset", "javascript-module", "browser-window"] }, + { paths: ["a.js", "b.js", "d.js"] }, + { + kinds: ["javascript-asset", "javascript-module"], + paths: ["a.js", "b.js", "d.js"], + }, + ]; + + for (const where of whereModes) { + const baseline = projectJavaScriptFacts(analysis.graph.nodes, { + kind: "javascript-facts", + where: { + ...(where.paths ? { paths: [...where.paths] } : {}), + ...(where.kinds ? { kinds: [...where.kinds] } : {}), + }, + property_keys: ["tag", "path"], + include_available_property_keys: true, + offset: 0, + limit: 1000, + }); + const total = baseline.total; + expect(total).toBeGreaterThan(6); + + const windowCases: readonly { + readonly offset: number; + readonly limit: number; + }[] = [ + { offset: 0, limit: 3 }, + { offset: 2, limit: 5 }, + { offset: Math.max(0, total - 2), limit: 5 }, + { offset: total - 1, limit: 1 }, + { offset: total, limit: 4 }, + { offset: total + 50, limit: 5 }, + ]; + + for (const { offset, limit } of windowCases) { + const view: AnalysisViewRequest = { + kind: "javascript-facts", + where: { + ...(where.paths ? { paths: [...where.paths] } : {}), + ...(where.kinds ? { kinds: [...where.kinds] } : {}), + }, + property_keys: ["tag", "path"], + include_available_property_keys: true, + offset, + limit, + }; + const sealedView = projectAnalysisView(sealed, view); + const unsealedView = projectAnalysisView(unsealed, view); + expect(sealedView.ok).toBe(true); + expect(unsealedView.ok).toBe(true); + if (sealedView.ok && unsealedView.ok) { + expect(sealedView.value).toEqual(unsealedView.value); + } + + if (view.kind !== "javascript-facts") throw new Error("wrong view"); + const sealedDirect = projectJavaScriptFacts( + sealedNodes, + view, + sealedResult, + ); + const unsealedDirect = projectJavaScriptFacts(analysis.graph.nodes, view); + expect(sealedDirect).toEqual(unsealedDirect); + expect(sealedDirect.total).toBe(total); + expect(sealedDirect.rows).toEqual( + baseline.rows.slice(offset, offset + limit), + ); + } + + for (const pageLimit of [1, 5]) { + const collected: typeof baseline.rows = []; + let cursor = 0; + while (true) { + const view: AnalysisViewRequest = { + kind: "javascript-facts", + where: { + ...(where.paths ? { paths: [...where.paths] } : {}), + ...(where.kinds ? { kinds: [...where.kinds] } : {}), + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: cursor, + limit: pageLimit, + }; + const sealedRes = projectAnalysisView(sealed, view); + const unsealedRes = projectAnalysisView(unsealed, view); + expect(sealedRes).toEqual(unsealedRes); + if (!sealedRes.ok || sealedRes.value.kind !== "javascript-facts") { + throw new Error("unexpected result"); + } + collected.push(...sealedRes.value.rows); + if (sealedRes.value.coverage.exhausted) { + expect(sealedRes.value.coverage.next_offset).toBeNull(); + break; + } + cursor = sealedRes.value.coverage.next_offset!; + } + expect(collected).toHaveLength(total); + expect(collected.map((row) => row.properties.tag)).toEqual( + baseline.rows.map((row) => row.properties.tag), + ); + } + } +}); + +it("matches unindexed output across large-offset multi-bucket seek thresholds", () => { + const base = analysisViewJavaScriptAnalysis(); + const baseObs = base.graph.nodes[0]!.observations[0]!; + const kinds = [ + "javascript-asset", + "javascript-module", + "javascript-expression", + ] as const; + const paths = ["chunk-0.js", "chunk-1.js", "chunk-2.js"] as const; + const nodes = Array.from({ length: 160 }, (_, nodeIdx) => { + const sha256 = (nodeIdx + 1).toString(16).padStart(64, "0"); + const kind = kinds[nodeIdx % kinds.length]!; + return createJavaScriptApplicationNode({ + kind, + identity: { + strategy: "content-digest", + stability: "global-exact", + sha256, + }, + observations: Array.from({ length: 4 }, (_, obsIdx) => { + const path = paths[(nodeIdx + obsIdx) % paths.length]!; + return { + label: `obs-${nodeIdx}-${obsIdx}`, + properties: { seq: nodeIdx * 4 + obsIdx, path }, + evidence: { + ...baseObs.evidence, + artifact: { + available: true as const, + artifact_id: `art_${sha256}`, + sha256, + }, + location: { + available: true as const, + value: { kind: "artifact-path" as const, path }, + }, + }, + }; + }), + }); + }); + + const { graph_id: _gid, ...restGraph } = base.graph; + const graph = createJavaScriptApplicationGraph({ + ...restGraph, + root_node_ids: [base.graph.nodes[0]!.node_id], + nodes: [base.graph.nodes[0]!, ...nodes], + edges: [], + }); + const analysis = analysisViewBindJavaScriptGraphs(base, graph); + const unsealed = javascriptParent(analysis); + const sealedResult = freezeJsonSnapshot(structuredClone(analysis)); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: sealedResult, + }; + const sealedNodes = (sealedResult as typeof analysis).graph.nodes; + const total = 640; // 160 * 4 across 9 (kind, path) buckets; seekThreshold = max(64, 9 * 8) = 72 + + for (const [offset, limit] of [ + [0, 5], + [250, 7], + [total - 3, 10], + [total, 5], + ] as const) { + const view: AnalysisViewRequest = { + kind: "javascript-facts", + where: { + kinds: [...kinds], + paths: [...paths], + }, + property_keys: ["seq", "path"], + include_available_property_keys: false, + offset, + limit, + }; + expect(projectAnalysisView(sealed, view)).toEqual( + projectAnalysisView(unsealed, view), + ); + if (view.kind !== "javascript-facts") throw new Error("wrong view"); + expect(projectJavaScriptFacts(sealedNodes, view, sealedResult)).toEqual( + projectJavaScriptFacts(analysis.graph.nodes, view), + ); + } +}); + +it("handles missing buckets, deduplicated filters, and single-bucket fallback", () => { + const analysis = interleavedFactsJavaScriptAnalysis(); + const unsealed = javascriptParent(analysis); + const sealedResult = freezeJsonSnapshot(structuredClone(analysis)); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: sealedResult, + }; + const sealedNodes = (sealedResult as typeof analysis).graph.nodes; + + const edgeViews: readonly AnalysisViewRequest[] = [ + // Missing filter values mixed with populated multi-bucket filters + { + kind: "javascript-facts", + where: { + kinds: ["javascript-asset", "unknown", "javascript-module"], + paths: ["a.js", "missing.js", "b.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 1, + limit: 6, + }, + { + kind: "javascript-facts", + where: { paths: ["missing.js", "a.js", "b.js"] }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 2, + limit: 5, + }, + // All-missing buckets (buckets.length === 0) + { + kind: "javascript-facts", + where: { kinds: ["unknown"], paths: ["missing.js"] }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 0, + limit: 5, + }, + // Single matching bucket alongside missing entries (buckets.length === 1) + { + kind: "javascript-facts", + where: { + kinds: ["javascript-asset", "unknown"], + paths: ["a.js", "missing.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 3, + limit: 4, + }, + { + kind: "javascript-facts", + where: { + kinds: ["javascript-asset", "unknown"], + paths: ["a.js", "missing.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 999, + limit: 4, + }, + // Duplicate entries collapsing to single bucket vs multi-bucket + { + kind: "javascript-facts", + where: { + kinds: ["javascript-asset", "javascript-asset"], + paths: ["a.js", "a.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 0, + limit: 50, + }, + { + kind: "javascript-facts", + where: { + kinds: ["javascript-asset", "javascript-asset", "javascript-module"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 1, + limit: 8, + }, + ]; + + for (const view of edgeViews) { + expect(projectAnalysisView(sealed, view)).toEqual( + projectAnalysisView(unsealed, view), + ); + if (view.kind !== "javascript-facts") throw new Error("wrong view"); + expect(projectJavaScriptFacts(sealedNodes, view, sealedResult)).toEqual( + projectJavaScriptFacts(analysis.graph.nodes, view), + ); + } +}); + +it("enforces limit boundaries and filter-order determinism across cold and warm caches", () => { + const analysis = interleavedFactsJavaScriptAnalysis(); + const unsealed = javascriptParent(analysis); + const sealedResult = freezeJsonSnapshot(structuredClone(analysis)); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: sealedResult, + }; + const sealedNodes = (sealedResult as typeof analysis).graph.nodes; + + // Schema rejects limit: 0 + expect( + javascriptFactsViewRequestSchema.safeParse({ + kind: "javascript-facts", + property_keys: [], + limit: 0, + }).success, + ).toBe(false); + expect( + inspectAnalysisViewInputSchema.safeParse({ + source: { kind: "inline", evidence: {} }, + view: { kind: "javascript-facts", property_keys: [], limit: 0 }, + }).success, + ).toBe(false); + + // Direct call parity for limit: 0 across unfiltered, single-bucket, and multi-bucket + for (const where of [ + {}, + { kinds: ["javascript-asset" as const], paths: ["a.js"] }, + { + kinds: ["javascript-asset" as const, "javascript-module" as const], + paths: ["a.js", "b.js"], + }, + ]) { + const directZeroLimit = { + kind: "javascript-facts" as const, + where, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 0, + limit: 0, + }; + const indexedZero = projectJavaScriptFacts( + sealedNodes, + directZeroLimit, + sealedResult, + ); + const unindexedZero = projectJavaScriptFacts( + analysis.graph.nodes, + directZeroLimit, + ); + expect(indexedZero).toEqual(unindexedZero); + expect(indexedZero.rows).toEqual([]); + expect(indexedZero.total).toBeGreaterThan(0); + } + + // Determinism across reversed filter order and cold vs warm WeakMap cache + const freshColdResult = freezeJsonSnapshot(structuredClone(analysis)); + const freshColdParent: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: freshColdResult, + }; + const forwardView = { + kind: "javascript-facts" as const, + where: { + kinds: ["javascript-asset" as const, "javascript-module" as const], + paths: ["a.js", "b.js", "d.js"], + }, + property_keys: ["tag"], + include_available_property_keys: false, + offset: 2, + limit: 6, + }; + const reversedView = { + ...forwardView, + where: { + kinds: ["javascript-module" as const, "javascript-asset" as const], + paths: ["d.js", "b.js", "a.js"], + }, + }; + const coldForward = projectAnalysisView(freshColdParent, forwardView); + const warmReversed = projectAnalysisView(freshColdParent, reversedView); + const cachedForward = projectAnalysisView(sealed, forwardView); + if ( + !coldForward.ok || + !warmReversed.ok || + !cachedForward.ok || + coldForward.value.kind !== "javascript-facts" || + warmReversed.value.kind !== "javascript-facts" + ) { + throw new Error("expected javascript-facts result"); + } + expect(coldForward.value.rows).toEqual(warmReversed.value.rows); + expect(coldForward.value.coverage).toEqual(warmReversed.value.coverage); + expect(coldForward).toEqual(cachedForward); + expect( + projectJavaScriptFacts(sealedNodes, forwardView, sealedResult), + ).toEqual(projectJavaScriptFacts(sealedNodes, reversedView, sealedResult)); +}); + +it("caches sealed inspect_byte_entropy and analyze_function parents across repeated calls", () => { + const entropyPayload = { + artifact: { path: "/tmp/fixture", bytes: 256, sha256: "2".repeat(64) }, + block_size: 256, + window: { offset: 0, length: 256 }, + file_entropy: 4, + thresholds: { high: 7.5, low: 0.5 }, + blocks: [{ offset: 0, length: 256, entropy: 4 }], + runs: [], + limitations: [], + }; + const entropyParent: AnalysisViewParent = { + predicateType: "rea.byte-entropy", + evidenceId: `ev_${"1".repeat(64)}`, + operation: "inspect_byte_entropy", + limitations: [], + sealedResult: true, + normalizedResult: freezeJsonSnapshot(entropyPayload), + }; + const native = nativeParent(); + const sealedNative: AnalysisViewParent = { + ...native, + sealedResult: true, + normalizedResult: freezeJsonSnapshot( + structuredClone(native.normalizedResult) as Record, + ), + }; + const entropySpy = vi.spyOn(byteEntropySchema, "safeParse"); + const dossierSpy = vi.spyOn(functionDossierSchema, "safeParse"); + try { + expect(projectAnalysisView(entropyParent, { kind: "summary" }).ok).toBe( + true, + ); + expect( + projectAnalysisView({ ...entropyParent }, { kind: "summary" }).ok, + ).toBe(true); + expect(entropySpy).toHaveBeenCalledTimes(1); + + expect(projectAnalysisView(sealedNative, { kind: "summary" }).ok).toBe( + true, + ); + expect( + projectAnalysisView( + { ...sealedNative }, + { kind: "native", facet: "procedure", offset: 0, limit: 64 }, + ).ok, + ).toBe(true); + expect(dossierSpy).toHaveBeenCalledTimes(1); + } finally { + entropySpy.mockRestore(); + dossierSpy.mockRestore(); + } +}); diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index 2ef862b3ee..b967473d22 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -20,8 +20,7 @@ import { projectNativeExportsView } from "./nativeExportsView.js"; import { projectElfDependenciesView } from "./elfDependenciesView.js"; import { projectByteEntropyView } from "./byteEntropyView.js"; import { - parseAnalysisViewResult, - analysisViewResultInputError, + createAnalysisViewResultReader, parentArtifactPath, } from "./analysisViewParent.js"; import { projectJavaScriptRoutesView } from "./javascriptRoutesView.js"; @@ -122,21 +121,34 @@ export const sealAnalysisView = ( const parentEvidenceIdSchema = prefixedDigestSchema("ev"); -const parseJavaScriptParent = ( +const safeParseJavaScriptParent = ( input: unknown, -): Result => { +): z.ZodSafeParseResult => { try { // The format owner authenticates imported results completely before reuse; // mutable or merely frozen inputs still receive canonical validation. const steps = parseOwnedJavaScriptApplicationAnalysisSteps(input); let step = steps.next(); while (!step.done) step = steps.next(); - return ok(step.value); + return { success: true, data: step.value }; } catch (cause: unknown) { if (!(cause instanceof z.ZodError)) throw cause; - return err(analysisViewResultInputError(input, cause)); + return { + success: false, + error: cause as z.ZodError, + }; } }; +const readJavaScriptParent = createAnalysisViewResultReader({ + safeParse: safeParseJavaScriptParent, +}); +const readByteEntropyParent = createAnalysisViewResultReader(byteEntropySchema); +const readBinaryLayoutParent = createAnalysisViewResultReader({ + safeParse: safeParseOwnedBinaryLayout, +}); +const readFunctionDossierParent = createAnalysisViewResultReader( + functionDossierSchema, +); const unsupportedParent = ( parent: AnalysisViewParent, @@ -368,22 +380,19 @@ export const projectAnalysisView = ( return sealProjected(projected); } if (parent.operation === "inspect_byte_entropy") { - const report = parseAnalysisViewResult(byteEntropySchema, parent); + const report = readByteEntropyParent(parent); if (!report.ok) return report; const projected = projectByteEntropyView(parent, report.value, view); return sealProjected(projected); } if (parent.operation === "inspect_binary_layout") { - const layout = parseAnalysisViewResult( - { safeParse: safeParseOwnedBinaryLayout }, - parent, - ); + const layout = readBinaryLayoutParent(parent); if (!layout.ok) return layout; const projected = projectBinaryLayoutView(parent, layout.value, view); return sealProjected(projected); } if (parent.operation === "analyze_javascript_application") { - const analysis = parseJavaScriptParent(parent.normalizedResult); + const analysis = readJavaScriptParent(parent); if (!analysis.ok) return analysis; const projected = projectJavaScriptApplicationView( parent, @@ -393,7 +402,7 @@ export const projectAnalysisView = ( return sealProjected(projected); } if (parent.operation === "analyze_function") { - const native = parseAnalysisViewResult(functionDossierSchema, parent); + const native = readFunctionDossierParent(parent); if (!native.ok) return native; const projected = projectNativeFunctionView(parent, native.value, view); return sealProjected(projected); diff --git a/src/domain/analysisView/analysisViewParent.test.ts b/src/domain/analysisView/analysisViewParent.test.ts index 83873dcf3a..78d7e80300 100644 --- a/src/domain/analysisView/analysisViewParent.test.ts +++ b/src/domain/analysisView/analysisViewParent.test.ts @@ -102,3 +102,36 @@ it("preserves explicit undefined normalization without freezing or caching non-J expect(source).toEqual({}); expect(Object.hasOwn(source, "optional")).toBe(false); }); + +it("caches and returns the frozen normalized snapshot when borrowing is rejected", () => { + const shared = { tag: "x" }; + const source = freezeOwnedJsonTreeSnapshot({ + first: shared, + second: shared, + }); + let parseCount = 0; + const schema = z.strictObject({ + first: z.strictObject({ tag: z.string() }), + second: z.strictObject({ tag: z.string() }), + added: z.string().default("normalized"), + }); + const read = createAnalysisViewResultReader({ + safeParse: (input) => { + parseCount += 1; + return schema.safeParse(input); + }, + }); + const first = read(parent(source)); + const second = read({ ...parent(source) }); + expect(parseCount).toBe(1); + if (!first.ok || !second.ok) throw new Error("Expected ok results"); + expect(first.value).not.toBe(source); + expect(second.value).toBe(first.value); + expect(Object.isFrozen(first.value)).toBe(true); + expect(isImmutableJsonSnapshot(first.value)).toBe(true); + expect(first.value).toEqual({ + first: { tag: "x" }, + second: { tag: "x" }, + added: "normalized", + }); +}); diff --git a/src/domain/analysisView/analysisViewParent.ts b/src/domain/analysisView/analysisViewParent.ts index 45a1ef6c98..7c5c0394fb 100644 --- a/src/domain/analysisView/analysisViewParent.ts +++ b/src/domain/analysisView/analysisViewParent.ts @@ -70,9 +70,9 @@ export const createAnalysisViewResultReader = (parser: { } const normalized = ownedJsonValueSchema.safeParse(parsed.value); if (!normalized.success) return parsed; - freezeOwnedJsonTreeSnapshot(normalized.data); - checked.set(source, parsed.value); - return parsed; + const frozen = freezeOwnedJsonTreeSnapshot(normalized.data) as Value; + checked.set(source, frozen); + return ok(frozen); }; }; diff --git a/src/domain/analysisView/commandObservationView.ts b/src/domain/analysisView/commandObservationView.ts index c7fc569354..3270834d73 100644 --- a/src/domain/analysisView/commandObservationView.ts +++ b/src/domain/analysisView/commandObservationView.ts @@ -19,7 +19,7 @@ import { completeWithinViewCoverage, } from "./analysisViewCoverage.js"; import { analysisViewInputError } from "./analysisViewErrors.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import { isRecord } from "../../kernel/isRecord.js"; export const commandSummaryContext = { @@ -40,6 +40,13 @@ export const gdbCommandSummarySchema = gdbCommandResultSchema }), }); +const readGdbCommandResult = createAnalysisViewResultReader( + gdbCommandResultSchema, +); +const readCommandObservation = createAnalysisViewResultReader( + commandObservationSchema, +); + /** Select existing owner facts without parsing a command or its output protocol. */ export const projectCommandObservationView = ( parent: AnalysisViewParent, @@ -116,7 +123,7 @@ export const projectCommandObservationView = ( ), }; if (parent.operation === "gdb_console") { - const parsed = parseAnalysisViewResult(gdbCommandResultSchema, parent); + const parsed = readGdbCommandResult(parent); if (!parsed.ok) return parsed; const selection = parameters.data; if ( @@ -149,7 +156,7 @@ export const projectCommandObservationView = ( }, }); } - const parsed = parseAnalysisViewResult(commandObservationSchema, parent); + const parsed = readCommandObservation(parent); if (!parsed.ok) return parsed; const report = parsed.value; if ( diff --git a/src/domain/analysisView/dartAotView.ts b/src/domain/analysisView/dartAotView.ts index ddca44324e..2fe1ebc796 100644 --- a/src/domain/analysisView/dartAotView.ts +++ b/src/domain/analysisView/dartAotView.ts @@ -3,7 +3,7 @@ import { analysisViewInputError } from "./analysisViewErrors.js"; import { z } from "zod"; import { flutterResultSchemas } from "../flutter/flutterBuildAnalysis.js"; import { err, ok } from "../result.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { ownedView, @@ -45,6 +45,8 @@ export const dartAotViewContextSchema = z.strictObject({ string_pool: dartAotSummarySchema.shape.string_pool, }); +const readAotReport = createAnalysisViewResultReader(aotSchema); + /** Reuse authenticated AOT Evidence without opening the APK or rescanning its ELF. */ export const projectDartAotView = ( parent: AnalysisViewParent, @@ -63,7 +65,7 @@ export const projectDartAotView = ( }, ]), ); - const parsed = parseAnalysisViewResult(aotSchema, parent); + const parsed = readAotReport(parent); if (!parsed.ok) return parsed; const report = parsed.value; const { package_uris, dart_uris, class_like_tokens, ...pool } = diff --git a/src/domain/analysisView/evmInterfaceView.ts b/src/domain/analysisView/evmInterfaceView.ts index f8f609e391..ff8934c7e3 100644 --- a/src/domain/analysisView/evmInterfaceView.ts +++ b/src/domain/analysisView/evmInterfaceView.ts @@ -3,7 +3,7 @@ import { z } from "zod"; import { uniqueSorted } from "../canonicalOrdering.js"; import { evmInterfaceSchema } from "../evm/evmInterface.js"; import { err, ok } from "../result.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { ownedView, @@ -49,6 +49,8 @@ export const evmSummarySchema = z.strictObject({ limitations: evmInterfaceSchema.shape.limitations, }); +const readEvmInterface = createAnalysisViewResultReader(evmInterfaceSchema); + /** Select already authenticated producer facts; no interpreter or provider is invoked. */ export const projectEvmInterfaceView = ( parent: AnalysisViewParent, @@ -67,7 +69,7 @@ export const projectEvmInterfaceView = ( }, ]), ); - const parsed = parseAnalysisViewResult(evmInterfaceSchema, parent); + const parsed = readEvmInterface(parent); if (!parsed.ok) return parsed; const report = parsed.value; const subject = evidenceFileTarget(parent); diff --git a/src/domain/analysisView/fridaSessionStatusView.ts b/src/domain/analysisView/fridaSessionStatusView.ts index 878f30281b..2cf05b3444 100644 --- a/src/domain/analysisView/fridaSessionStatusView.ts +++ b/src/domain/analysisView/fridaSessionStatusView.ts @@ -13,7 +13,7 @@ import { completeWithinViewCoverage, } from "./analysisViewCoverage.js"; import { analysisViewInputError } from "./analysisViewErrors.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; export const fridaSessionStatusSummarySchema = fridaSessionStatusSchema .omit({ messages: true }) @@ -24,6 +24,10 @@ export const fridaSessionStatusViewContext = { source_parameters: z.strictObject({ session_id: z.string().uuid() }), }; +const readFridaSessionStatus = createAnalysisViewResultReader( + fridaSessionStatusSchema, +); + /** Summarize captured facts without interpreting caller-authored message payloads. */ export const projectFridaSessionStatusView = ( parent: AnalysisViewParent, @@ -40,7 +44,7 @@ export const projectFridaSessionStatusView = ( }, ]), ); - const report = parseAnalysisViewResult(fridaSessionStatusSchema, parent); + const report = readFridaSessionStatus(parent); if (!report.ok) return report; const parameters = fridaSessionStatusViewContext.source_parameters.safeParse( parent.parameters, diff --git a/src/domain/analysisView/javascriptApplicationView.ts b/src/domain/analysisView/javascriptApplicationView.ts index 5061ac333a..a58cccefaf 100644 --- a/src/domain/analysisView/javascriptApplicationView.ts +++ b/src/domain/analysisView/javascriptApplicationView.ts @@ -1,3 +1,4 @@ +import { isImmutableJsonSnapshot } from "../immutableJson.js"; import { isJavaScriptModuleUnit } from "../javascript/javascriptModuleUnits.js"; import { AnalysisInputError, @@ -94,20 +95,80 @@ function* moduleEntries( } } -/** Scan retained order once; materialize only the requested matching page. */ -const modulePage = ( - nodes: readonly ApplicationNode[], - view: { - readonly offset: number; - readonly limit: number; - readonly where?: z.output< - typeof javascriptModuleReferencesRequestSchema - >["where"]; - }, -): { entries: ModuleEntry[]; total: number } => { +interface ModuleIndex { + readonly moduleEntries: readonly ModuleEntry[]; + readonly byNodeId: ReadonlyMap; + readonly nodesByPath: ReadonlyMap; + readonly nodesByKind: ReadonlyMap< + JavaScriptModuleReference["kind"], + readonly ModuleEntry[] + >; +} + +const moduleIndexes = new WeakMap< + JavaScriptApplicationAnalysisResult, + ModuleIndex +>(); + +const buildModuleIndex = (nodes: readonly ApplicationNode[]): ModuleIndex => { + const entries: ModuleEntry[] = []; + const byNodeId = new Map(); + const nodesByPath = new Map(); + const nodesByKind = new Map< + JavaScriptModuleReference["kind"], + ModuleEntry[] + >(); + for (const entry of moduleEntries(nodes)) { + entries.push(entry); + byNodeId.set( + entry.node.node_id, + byNodeId.has(entry.node.node_id) ? null : entry, + ); + if (entry.paths.length === 0) { + const existing = nodesByPath.get(null); + if (existing === undefined) nodesByPath.set(null, [entry]); + else existing.push(entry); + } else { + for (const path of entry.paths) { + const existing = nodesByPath.get(path); + if (existing === undefined) nodesByPath.set(path, [entry]); + else existing.push(entry); + } + } + const kindList = nodesByKind.get(entry.node.kind); + if (kindList === undefined) nodesByKind.set(entry.node.kind, [entry]); + else kindList.push(entry); + } + return { moduleEntries: entries, byNodeId, nodesByPath, nodesByKind }; +}; + +const getModuleIndex = ( + analysis: JavaScriptApplicationAnalysisResult, +): ModuleIndex | undefined => { + if (!isImmutableJsonSnapshot(analysis)) return undefined; + let index = moduleIndexes.get(analysis); + if (index === undefined) { + index = buildModuleIndex(analysis.graph.nodes); + moduleIndexes.set(analysis, index); + } + return index; +}; + +type ModulePageRequest = { + readonly offset: number; + readonly limit: number; + readonly where?: z.output< + typeof javascriptModuleReferencesRequestSchema + >["where"]; +}; + +const paginateModuleEntries = ( + iterable: Iterable, + view: ModulePageRequest, +): { entries: readonly ModuleEntry[]; total: number } => { const entries: ModuleEntry[] = []; let total = 0; - for (const entry of moduleEntries(nodes)) { + for (const entry of iterable) { if (view.where?.kind !== undefined && entry.node.kind !== view.where.kind) continue; const selectedPath = view.where?.path; @@ -118,17 +179,56 @@ const modulePage = ( : !entry.paths.includes(selectedPath)) ) continue; - const selectedEntry = - selectedPath !== undefined && selectedPath !== null - ? { ...entry, path: selectedPath } - : entry; if (total >= view.offset && entries.length < view.limit) - entries.push(selectedEntry); + entries.push( + selectedPath !== undefined && selectedPath !== null + ? { ...entry, path: selectedPath } + : entry, + ); total += 1; } return { entries, total }; }; +/** Scan retained order once (or slice pre-built immutable index in O(page)). */ +const modulePage = ( + analysis: JavaScriptApplicationAnalysisResult, + view: ModulePageRequest, +): { entries: readonly ModuleEntry[]; total: number } => { + const index = getModuleIndex(analysis); + if (index === undefined) + return paginateModuleEntries(moduleEntries(analysis.graph.nodes), view); + const selectedKind = view.where?.kind; + const selectedPath = view.where?.path; + if (selectedPath !== undefined && selectedKind === undefined) { + const candidates = index.nodesByPath.get(selectedPath) ?? []; + const slice = candidates.slice(view.offset, view.offset + view.limit); + return { + entries: + selectedPath === null + ? slice + : slice.map((entry) => ({ ...entry, path: selectedPath })), + total: candidates.length, + }; + } + if (selectedPath === undefined && selectedKind !== undefined) { + const candidates = index.nodesByKind.get(selectedKind) ?? []; + return { + entries: candidates.slice(view.offset, view.offset + view.limit), + total: candidates.length, + }; + } + if (selectedPath === undefined && selectedKind === undefined) + return { + entries: index.moduleEntries.slice(view.offset, view.offset + view.limit), + total: index.moduleEntries.length, + }; + return paginateModuleEntries( + index.nodesByPath.get(selectedPath!) ?? [], + view, + ); +}; + const exportNames = (node: ApplicationNode): readonly string[] => { const names = new Set(); for (const observation of node.observations) { @@ -268,18 +368,34 @@ const parentFields = ( }; }; +const findSingleNodeById = ( + nodes: readonly ApplicationNode[], + nodeId: string, +): ModuleEntry | undefined => { + let matched: + | (ApplicationNode & { readonly kind: JavaScriptModuleReference["kind"] }) + | undefined; + for (const node of nodes) { + if (!isJavaScriptModuleUnit(node) || node.node_id !== nodeId) continue; + if (matched !== undefined) return undefined; + matched = node; + } + if (matched === undefined) return undefined; + const paths = javascriptModulePaths(matched); + return { node: matched, path: paths[0] ?? null, paths }; +}; + const selectModule = ( - modules: readonly ModuleEntry[], + analysis: JavaScriptApplicationAnalysisResult, selector: ItemAnalysisView["selector"], ): Result => { + const index = getModuleIndex(analysis); if ("node_id" in selector) { - const matches = modules.filter( - ({ node }) => node.node_id === selector.node_id, - ); - if (matches.length === 1) { - const selected = matches[0]; - if (selected !== undefined) return ok(selected); - } + const selected = + index !== undefined + ? index.byNodeId.get(selector.node_id) + : findSingleNodeById(analysis.graph.nodes, selector.node_id); + if (selected !== undefined && selected !== null) return ok(selected); return err( inputError([ { @@ -291,11 +407,14 @@ const selectModule = ( ); } if ("path" in selector) { - const matches = modules.filter((entry) => - selector.path === null - ? entry.path === null - : entry.paths.includes(selector.path), - ); + const matches = + index !== undefined + ? (index.nodesByPath.get(selector.path) ?? []) + : [...moduleEntries(analysis.graph.nodes)].filter((entry) => + selector.path === null + ? entry.path === null + : entry.paths.includes(selector.path), + ); if (matches.length === 1) { const selected = matches[0]; if (selected !== undefined) @@ -359,7 +478,11 @@ export const projectJavaScriptApplicationView = ( sourceCoverage, ); if (view.kind === "javascript-facts") { - const { rows, total } = projectJavaScriptFacts(analysis.graph.nodes, view); + const { rows, total } = projectJavaScriptFacts( + analysis.graph.nodes, + view, + isImmutableJsonSnapshot(analysis) ? analysis : undefined, + ); return ok({ ...shared, kind: "javascript-facts" as const, @@ -370,7 +493,7 @@ export const projectJavaScriptApplicationView = ( }); } if (view.kind === "javascript") { - const { entries, total } = modulePage(analysis.graph.nodes, view); + const { entries, total } = modulePage(analysis, view); const rows = entries.map(moduleReference); return ok({ ...shared, @@ -384,10 +507,16 @@ export const projectJavaScriptApplicationView = ( if (view.kind === "summary") { // Summary coverage counts modules. Graph nodes that are not modules stay // in summary.coverage.application rather than inflating this total. - const moduleCount = analysis.graph.nodes.reduce( - (count, node) => count + Number(isJavaScriptModuleUnit(node)), - 0, - ); + const cachedIndex = isImmutableJsonSnapshot(analysis) + ? moduleIndexes.get(analysis) + : undefined; + const moduleCount = + cachedIndex !== undefined + ? cachedIndex.moduleEntries.length + : analysis.graph.nodes.reduce( + (count, node) => count + Number(isJavaScriptModuleUnit(node)), + 0, + ); return ok({ kind: "summary" as const, view, @@ -430,8 +559,7 @@ export const projectJavaScriptApplicationView = ( "Section and symbol collections apply to inspect_binary_layout Evidence.", ), ); - const modules = [...moduleEntries(analysis.graph.nodes)]; - const selected = selectModule(modules, view.selector); + const selected = selectModule(analysis, view.selector); if (!selected.ok) return selected; return ok({ kind: "item" as const, @@ -447,7 +575,7 @@ export const projectJavaScriptApplicationView = ( "Section and symbol collections apply to inspect_binary_layout Evidence.", ), ); - const { entries, total } = modulePage(analysis.graph.nodes, view); + const { entries, total } = modulePage(analysis, view); const items = entries.map(({ node, path }) => ({ node_id: node.node_id, kind: node.kind, diff --git a/src/domain/analysisView/javascriptFactsView.ts b/src/domain/analysisView/javascriptFactsView.ts index 0e2f1952d3..0bba9bd23d 100644 --- a/src/domain/analysisView/javascriptFactsView.ts +++ b/src/domain/analysisView/javascriptFactsView.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { isImmutableJsonSnapshot } from "../immutableJson.js"; import { applicationNodeSchema, applicationNodeObservationSchema, @@ -65,10 +66,341 @@ const observationPath = ( return null; }; +interface FactEntry { + readonly node: ApplicationNode; + readonly observation: ApplicationNode["observations"][number]; +} + +interface FactsIndex { + readonly all: readonly FactEntry[]; + readonly byKind: ReadonlyMap; + readonly byPath: ReadonlyMap; + readonly byKindAndPath: ReadonlyMap< + string, + ReadonlyMap + >; +} + +const factsIndexes = new WeakMap< + object, + { readonly nodes: readonly ApplicationNode[]; readonly index: FactsIndex } +>(); + +const pushIndex = ( + map: Map, + key: string, + ordinal: number, +): void => { + const existing = map.get(key); + if (existing === undefined) map.set(key, [ordinal]); + else existing.push(ordinal); +}; + +const buildFactsIndex = (nodes: readonly ApplicationNode[]): FactsIndex => { + const all: FactEntry[] = []; + const byKind = new Map(); + const byPath = new Map(); + const byKindAndPath = new Map>(); + for (const node of nodes) { + let kindPaths = byKindAndPath.get(node.kind); + for (const observation of node.observations) { + const ordinal = all.length; + all.push({ node, observation }); + pushIndex(byKind, node.kind, ordinal); + const path = observationPath(observation); + if (path !== null) { + pushIndex(byPath, path, ordinal); + if (kindPaths === undefined) { + kindPaths = new Map(); + byKindAndPath.set(node.kind, kindPaths); + } + pushIndex(kindPaths, path, ordinal); + } + } + } + return { all, byKind, byPath, byKindAndPath }; +}; + +const getFactsIndex = ( + nodes: readonly ApplicationNode[], + cacheOwner: object | undefined, +): FactsIndex | undefined => { + if ( + cacheOwner === undefined || + !isImmutableJsonSnapshot(cacheOwner) || + !Object.isFrozen(nodes) + ) + return undefined; + const cached = factsIndexes.get(cacheOwner); + if (cached !== undefined && cached.nodes === nodes) return cached.index; + const index = buildFactsIndex(nodes); + factsIndexes.set(cacheOwner, { nodes, index }); + return index; +}; + +const buildFactRow = ( + node: ApplicationNode, + observation: ApplicationNode["observations"][number], + keys: readonly string[], + includeAvailablePropertyKeys: boolean, +): FactRow => ({ + node_id: node.node_id, + kind: node.kind, + identity: node.identity, + observation_id: observation.observation_id, + source_map_reference: observation.source_map_reference, + ...(includeAvailablePropertyKeys + ? { + available_property_keys: Object.keys(observation.properties).sort(), + } + : {}), + properties: Object.fromEntries( + keys.flatMap((key) => { + const value = observation.properties[key]; + return value !== undefined && Object.hasOwn(observation.properties, key) + ? [[key, value] as const] + : []; + }), + ), + evidence: observation.evidence, +}); + +const collectMatchingBuckets = ( + index: FactsIndex, + kinds: ReadonlySet | null, + paths: ReadonlySet | null, +): readonly (readonly number[])[] | undefined => { + if (kinds === null && paths === null) return undefined; + const buckets: (readonly number[])[] = []; + if (kinds !== null && paths !== null) { + for (const kind of kinds) { + const byPath = index.byKindAndPath.get(kind); + if (byPath === undefined) continue; + for (const path of paths) { + const bucket = byPath.get(path); + if (bucket !== undefined) buckets.push(bucket); + } + } + return buckets; + } + if (kinds !== null) { + for (const kind of kinds) { + const bucket = index.byKind.get(kind); + if (bucket !== undefined) buckets.push(bucket); + } + return buckets; + } + for (const path of paths!) { + const bucket = index.byPath.get(path); + if (bucket !== undefined) buckets.push(bucket); + } + return buckets; +}; + +const lowerBound = (bucket: readonly number[], target: number): number => { + let lo = 0; + let hi = bucket.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (bucket[mid]! < target) lo = mid + 1; + else hi = mid; + } + return lo; +}; + +const seekBucketOffsets = ( + buckets: readonly (readonly number[])[], + offset: number, +): { readonly cursors: Uint32Array; readonly skipped: number } => { + let lo = Number.POSITIVE_INFINITY; + let hi = Number.NEGATIVE_INFINITY; + for (const bucket of buckets) { + if (bucket.length === 0) continue; + const first = bucket[0]!; + const last = bucket[bucket.length - 1]!; + if (first < lo) lo = first; + if (last > hi) hi = last; + } + const cursors = new Uint32Array(buckets.length); + if (lo > hi) return { cursors, skipped: 0 }; + while (lo < hi) { + const mid = lo + Math.floor((hi - lo + 1) / 2); + let countLess = 0; + for (const bucket of buckets) { + countLess += lowerBound(bucket, mid); + if (countLess > offset) break; + } + if (countLess <= offset) lo = mid; + else hi = mid - 1; + } + let skipped = 0; + for (let i = 0; i < buckets.length; i++) { + const cursor = lowerBound(buckets[i]!, lo); + cursors[i] = cursor; + skipped += cursor; + } + return { cursors, skipped }; +}; + +const selectMultiBucketPage = ( + buckets: readonly (readonly number[])[], + offset: number, + limit: number, + total: number, +): readonly number[] => { + if (offset >= total || limit <= 0) return []; + const pageSize = Math.min(limit, total - offset); + const bucketCount = buckets.length; + const seekThreshold = Math.max(64, bucketCount * 8); + const { cursors, skipped } = + offset > seekThreshold + ? seekBucketOffsets(buckets, offset) + : { cursors: new Uint32Array(bucketCount), skipped: 0 }; + + const heapBucket = new Uint32Array(bucketCount); + const heapOrdinal = new Uint32Array(bucketCount); + let heapSize = 0; + for (let i = 0; i < bucketCount; i++) { + const bucket = buckets[i]!; + const cursor = cursors[i]!; + if (cursor >= bucket.length) continue; + heapBucket[heapSize] = i; + heapOrdinal[heapSize] = bucket[cursor]!; + heapSize += 1; + } + + const siftDown = (start: number): void => { + let idx = start; + const bIdx = heapBucket[idx]!; + const ord = heapOrdinal[idx]!; + while (true) { + const left = idx * 2 + 1; + if (left >= heapSize) break; + const right = left + 1; + const smallestChild = + right < heapSize && heapOrdinal[right]! < heapOrdinal[left]! + ? right + : left; + if (ord <= heapOrdinal[smallestChild]!) break; + heapBucket[idx] = heapBucket[smallestChild]!; + heapOrdinal[idx] = heapOrdinal[smallestChild]!; + idx = smallestChild; + } + heapBucket[idx] = bIdx; + heapOrdinal[idx] = ord; + }; + + for (let i = (heapSize >>> 1) - 1; i >= 0; i--) siftDown(i); + + const popNextOrdinal = (): number | undefined => { + if (heapSize === 0) return undefined; + const ordinal = heapOrdinal[0]!; + const bIdx = heapBucket[0]!; + const bucket = buckets[bIdx]!; + const nextCursor = cursors[bIdx]! + 1; + cursors[bIdx] = nextCursor; + if (nextCursor < bucket.length) { + heapOrdinal[0] = bucket[nextCursor]!; + siftDown(0); + } else { + heapSize -= 1; + if (heapSize > 0) { + heapBucket[0] = heapBucket[heapSize]!; + heapOrdinal[0] = heapOrdinal[heapSize]!; + siftDown(0); + } + } + return ordinal; + }; + + for (let i = skipped; i < offset; i++) { + if (popNextOrdinal() === undefined) break; + } + + const page: number[] = []; + while (page.length < pageSize) { + const ordinal = popNextOrdinal(); + if (ordinal === undefined) break; + page.push(ordinal); + } + return page; +}; + +const projectIndexedFacts = ( + index: FactsIndex, + view: FactRequest, + kinds: ReadonlySet | null, + paths: ReadonlySet | null, + keys: readonly string[], +): { readonly rows: FactRow[]; readonly total: number } => { + const buckets = collectMatchingBuckets(index, kinds, paths); + if (buckets === undefined) { + const total = index.all.length; + if (view.offset >= total || view.limit <= 0) return { rows: [], total }; + const end = view.offset + Math.min(view.limit, total - view.offset); + const rows: FactRow[] = []; + for (let i = view.offset; i < end; i++) { + const entry = index.all[i]!; + rows.push( + buildFactRow( + entry.node, + entry.observation, + keys, + view.include_available_property_keys, + ), + ); + } + return { rows, total }; + } + if (buckets.length === 0) return { rows: [], total: 0 }; + if (buckets.length === 1) { + const bucket = buckets[0]!; + const total = bucket.length; + if (view.offset >= total || view.limit <= 0) return { rows: [], total }; + const end = view.offset + Math.min(view.limit, total - view.offset); + const rows: FactRow[] = []; + for (let i = view.offset; i < end; i++) { + const entry = index.all[bucket[i]!]!; + rows.push( + buildFactRow( + entry.node, + entry.observation, + keys, + view.include_available_property_keys, + ), + ); + } + return { rows, total }; + } + let total = 0; + for (const bucket of buckets) total += bucket.length; + if (view.offset >= total || view.limit <= 0) return { rows: [], total }; + const ordinals = selectMultiBucketPage( + buckets, + view.offset, + view.limit, + total, + ); + const rows: FactRow[] = []; + for (const ordinal of ordinals) { + const entry = index.all[ordinal]!; + rows.push( + buildFactRow( + entry.node, + entry.observation, + keys, + view.include_available_property_keys, + ), + ); + } + return { rows, total }; +}; + /** One scan, O(page) retained rows; never materialize a whole node or graph. */ export const projectJavaScriptFacts = ( nodes: readonly ApplicationNode[], view: FactRequest, + cacheOwner?: object, ): { readonly rows: FactRow[]; readonly total: number } => { const paths = view.where.paths === undefined ? null : new Set(view.where.paths); @@ -76,6 +408,9 @@ export const projectJavaScriptFacts = ( view.where.kinds === undefined ? null : new Set(view.where.kinds); if (paths?.size === 0 || kinds?.size === 0) return { rows: [], total: 0 }; const keys = [...new Set(view.property_keys)]; + const index = getFactsIndex(nodes, cacheOwner); + if (index !== undefined) + return projectIndexedFacts(index, view, kinds, paths, keys); const rows: FactRow[] = []; let total = 0; for (const node of nodes) { @@ -87,30 +422,14 @@ export const projectJavaScriptFacts = ( } total += 1; if (total <= view.offset || rows.length >= view.limit) continue; - rows.push({ - node_id: node.node_id, - kind: node.kind, - identity: node.identity, - observation_id: observation.observation_id, - source_map_reference: observation.source_map_reference, - ...(view.include_available_property_keys - ? { - available_property_keys: Object.keys( - observation.properties, - ).sort(), - } - : {}), - properties: Object.fromEntries( - keys.flatMap((key) => { - const value = observation.properties[key]; - return value !== undefined && - Object.hasOwn(observation.properties, key) - ? [[key, value] as const] - : []; - }), + rows.push( + buildFactRow( + node, + observation, + keys, + view.include_available_property_keys, ), - evidence: observation.evidence, - }); + ); } } return { rows, total }; diff --git a/src/domain/analysisView/javascriptRoutesView.test.ts b/src/domain/analysisView/javascriptRoutesView.test.ts index 51c0ab707e..0b0f7aaaa2 100644 --- a/src/domain/analysisView/javascriptRoutesView.test.ts +++ b/src/domain/analysisView/javascriptRoutesView.test.ts @@ -355,3 +355,55 @@ it("admits a summary that fits exactly after sealing", () => { 1024 * 1024, ); }); + +it("paginates filtered and ID-selected route pages accurately across skipped offsets", () => { + const source = { + ...parent(), + normalizedResult: { + input_path: "/gone/app", + root_artifact_sha256: "c".repeat(64), + route_inventory: inventory( + [ + "createBrowserRouter([", + " { path: '/alpha' },", + " { path: '/beta' },", + " { path: '/gamma' },", + " { path: '/delta' },", + " { path: '/epsilon' },", + "]);", + "router.push('/login');", + ].join("\n"), + ), + }, + }; + const all = query(source, { collection: "routes", fields: ["path"] }); + expect(all.items).toHaveLength(6); + const byPath = new Map( + all.items.map((row) => ["path" in row ? row.path : undefined, row.id]), + ); + const page = query(source, { + collection: "routes", + fields: ["path"], + where: { + ids: [ + byPath.get("/epsilon")!, + byPath.get("/gamma")!, + byPath.get("/login")!, + byPath.get("/alpha")!, + byPath.get("/delta")!, + ], + classifications: ["page"], + }, + offset: 1, + limit: 2, + }); + expect( + page.items.map((row) => ("path" in row ? row.path : undefined)), + ).toEqual(["/delta", "/epsilon"]); + expect(page.coverage).toMatchObject({ + total: 4, + examined: 2, + next_offset: 3, + exhausted: false, + }); +}); diff --git a/src/domain/analysisView/javascriptRoutesView.ts b/src/domain/analysisView/javascriptRoutesView.ts index ddc020d1b9..8f75d96840 100644 --- a/src/domain/analysisView/javascriptRoutesView.ts +++ b/src/domain/analysisView/javascriptRoutesView.ts @@ -268,16 +268,16 @@ const read = (parent: AnalysisViewParent): Result => { const candidates = ( rows: Table, selected: readonly string[] | undefined, -): readonly T[] => - selected === undefined - ? rows.rows - : [...new Set(selected)] - .flatMap((id) => { - const entry = rows.byId.get(id); - return entry === undefined ? [] : [entry]; - }) - .sort((a, b) => a.index - b.index) - .map((entry) => entry.row); +): readonly T[] => { + if (selected === undefined) return rows.rows; + const entries: { row: T; index: number }[] = []; + for (const id of new Set(selected)) { + const entry = rows.byId.get(id); + if (entry !== undefined) entries.push(entry); + } + entries.sort((a, b) => a.index - b.index); + return entries.map((entry) => entry.row); +}; const choose = ( row: Record, fields: readonly string[], @@ -444,7 +444,7 @@ export const projectJavaScriptRoutesView = ( sources: readonly string[]; }, ) => { - const rows = candidates(source, ids).filter(predicate), + const rows = candidates(source, ids), items: Record[] = [], refs = new Map(); // Count the fixed envelope once. Counter widths and status text reserve the @@ -470,12 +470,17 @@ export const projectJavaScriptRoutesView = ( ), byte_limited = false; if (bytes > PAGE_BYTES) return tooLarge(); - for ( - let index = page.offset; - index < rows.length && items.length < page.limit; - index++ - ) { - const projected = project(rows[index]!), + let total = 0; + for (const row of rows) { + if (!predicate(row)) continue; + const matchedIndex = total++; + if ( + matchedIndex < page.offset || + items.length >= page.limit || + byte_limited + ) + continue; + const projected = project(row), additions: JavaScriptRouteInventorySource[] = []; let addedBytes = jsonValueByteLength(projected.item, PAGE_BYTES - bytes) + @@ -495,11 +500,11 @@ export const projectJavaScriptRoutesView = ( if (bytes + addedBytes > PAGE_BYTES) { if (items.length === 0) return tooLarge(); byte_limited = true; - break; + continue; } bytes += addedBytes; items.push(projected.item); - for (const row of additions) refs.set(row.id, row); + for (const sourceRow of additions) refs.set(sourceRow.id, sourceRow); } const result = { ...shared, @@ -507,7 +512,7 @@ export const projectJavaScriptRoutesView = ( sources: [...refs.values()], summary: null, byte_limited, - coverage: pageViewCoverage(page.offset, items.length, rows.length), + coverage: pageViewCoverage(page.offset, items.length, total), }; return jsonValueByteLength({ ...result, items }, PROJECTION_BYTES) > PROJECTION_BYTES diff --git a/src/domain/analysisView/machoView.ts b/src/domain/analysisView/machoView.ts index 63895c85dd..180c986dc8 100644 --- a/src/domain/analysisView/machoView.ts +++ b/src/domain/analysisView/machoView.ts @@ -6,7 +6,7 @@ import { isMachOFormat } from "../binaryTargetTypes.js"; import { machoSliceEncryptionViewSchema } from "../apple/machoEncryption.js"; import { inspectMachoSchema } from "../native/nativeInspection.js"; import { err, ok, type Result } from "../result.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { ownedView, @@ -92,11 +92,13 @@ export const machoSummarySchema = z.strictObject({ type MachoReport = z.output; +const readMachoReport = createAnalysisViewResultReader(inspectMachoSchema); + /** Admit a well-formed report whose recorded subject, if any, is a Mach-O. */ const parseMachoReport = ( parent: AnalysisViewParent, ): Result => { - const parsed = parseAnalysisViewResult(inspectMachoSchema, parent); + const parsed = readMachoReport(parent); if (!parsed.ok) return parsed; const file = evidenceFileTarget(parent); if (file !== undefined && !isMachOFormat(file.format)) diff --git a/src/domain/analysisView/managedArtifactView.ts b/src/domain/analysisView/managedArtifactView.ts index 654557cbc7..44c9899332 100644 --- a/src/domain/analysisView/managedArtifactView.ts +++ b/src/domain/analysisView/managedArtifactView.ts @@ -9,7 +9,7 @@ import { import { managedModuleRow } from "../managed/managedModuleIdentity.js"; import { validateManagedTokenScope } from "../managed/managedInspectionEvidence.js"; import { err, ok } from "../result.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; import { ownedView, @@ -74,6 +74,10 @@ export const managedViewIdentityUnknowns = ( : []), ]; +const readManagedArtifact = createAnalysisViewResultReader( + managedArtifactInspectionSchema, +); + /** Project authenticated metadata without reading a path or invoking a provider. */ export const projectManagedArtifactView = ( parent: AnalysisViewParent, @@ -93,10 +97,7 @@ export const projectManagedArtifactView = ( }, ]), ); - const parsed = parseAnalysisViewResult( - managedArtifactInspectionSchema, - parent, - ); + const parsed = readManagedArtifact(parent); if (!parsed.ok) return parsed; const report = parsed.value; const scope = validateManagedTokenScope( diff --git a/src/domain/analysisView/pcapCaptureView.test.ts b/src/domain/analysisView/pcapCaptureView.test.ts index 8f108ed46a..a077efdc6d 100644 --- a/src/domain/analysisView/pcapCaptureView.test.ts +++ b/src/domain/analysisView/pcapCaptureView.test.ts @@ -1,7 +1,10 @@ -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; import { createEvidence } from "../evidence.js"; +import { freezeJsonSnapshot } from "../immutableJson.js"; +import { pcapResultSchemas } from "../pcap/pcapAnalysis.js"; import { projectAnalysisView } from "./analysisView.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; +import type { AnalysisViewRequest } from "./analysisViewRequest.js"; const capture = ( tsharkStderr: string, @@ -190,3 +193,100 @@ it.each([ }); }, ); + +it("caches sealed pcap parents and matches query_index and query_labels_hex parity", () => { + const queries = [ + { + query: "a.b", + query_labels_hex: ["612e62"], + response_addresses: ["192.0.2.1"], + response_address_count: 1, + }, + { + query: "a.b", + query_labels_hex: ["61", "62"], + response_addresses: ["192.0.2.2"], + response_address_count: 1, + }, + { + query: "unique.example", + query_labels_hex: null, + response_addresses: ["192.0.2.3"], + response_address_count: 1, + }, + ]; + const unsealed = capture("", queries); + const sealed: AnalysisViewParent = { + ...unsealed, + sealedResult: true, + normalizedResult: freezeJsonSnapshot( + structuredClone(unsealed.normalizedResult) as Record, + ), + }; + const parseSpy = vi.spyOn( + pcapResultSchemas.inspect_pcap_capture, + "safeParse", + ); + try { + const views: AnalysisViewRequest[] = [ + { kind: "summary" }, + { + kind: "pcap", + facet: "dns-addresses", + query: "a.b", + query_index: 1, + offset: 0, + limit: 64, + }, + { + kind: "pcap", + facet: "dns-addresses", + query: "a.b", + query_index: 1, + query_labels_hex: ["61", "62"], + offset: 0, + limit: 64, + }, + { + kind: "pcap", + facet: "dns-addresses", + query: "a.b", + query_index: 0, + query_labels_hex: ["61", "62"], + offset: 0, + limit: 64, + }, + { + kind: "pcap", + facet: "dns-addresses", + query: "a.b", + query_index: 99, + offset: 0, + limit: 64, + }, + { + kind: "pcap", + facet: "dns-addresses", + query: "unique.example", + query_labels_hex: null, + offset: 0, + limit: 64, + }, + ]; + + const sealedResults = views.map((view) => + projectAnalysisView(sealed, view), + ); + expect(parseSpy).toHaveBeenCalledTimes(1); + for (const [index, view] of views.entries()) { + const sealedResult = sealedResults[index]!; + const unsealedResult = projectAnalysisView(unsealed, view); + expect(sealedResult.ok).toBe(unsealedResult.ok); + if (sealedResult.ok && unsealedResult.ok) + expect(sealedResult.value).toEqual(unsealedResult.value); + } + expect(parseSpy).toHaveBeenCalledTimes(1 + views.length); + } finally { + parseSpy.mockRestore(); + } +}); diff --git a/src/domain/analysisView/pcapCaptureView.ts b/src/domain/analysisView/pcapCaptureView.ts index 8cd1d2e8b2..2e28e8d8aa 100644 --- a/src/domain/analysisView/pcapCaptureView.ts +++ b/src/domain/analysisView/pcapCaptureView.ts @@ -1,7 +1,8 @@ import { analysisViewInputError } from "./analysisViewErrors.js"; import { z } from "zod"; import { pcapResultSchemas } from "../pcap/pcapAnalysis.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; +import { isImmutableJsonSnapshot } from "../immutableJson.js"; import type { AnalysisError } from "../analysisErrorBase.js"; import { err, ok, type Result } from "../result.js"; import type { AnalysisViewParent } from "./analysisViewParent.js"; @@ -119,13 +120,16 @@ export const pcapSummarySchema = captureSchema .nullable(), }); type Capture = z.output; +type DnsQuery = Capture["dns_queries"][number]; type PcapView = z.output; type Page = z.output; +const readCaptureParent = createAnalysisViewResultReader(captureSchema); + const parseParent = ( parent: AnalysisViewParent, ): Result => { - const parsed = parseAnalysisViewResult(captureSchema, parent); + const parsed = readCaptureParent(parent); if (!parsed.ok) return parsed; const subject = evidenceFileTarget(parent); if (subject == null || subject.sha256 !== parsed.value.target.sha256) @@ -168,6 +172,67 @@ const summarize = ({ }, }); +const equalLabelsHex = ( + left: readonly string[] | null, + right: readonly string[] | null, +): boolean => + left === right || + (left !== null && + right !== null && + left.length === right.length && + left.every((label, index) => label === right[index])); + +const dnsQueriesByName = new WeakMap< + Capture, + ReadonlyMap +>(); + +const indexedDnsQueries = ( + capture: Capture, +): ReadonlyMap => { + let byName = dnsQueriesByName.get(capture); + if (byName !== undefined) return byName; + const grouped = new Map(); + for (const entry of capture.dns_queries) { + const existing = grouped.get(entry.query); + if (existing === undefined) grouped.set(entry.query, [entry]); + else existing.push(entry); + } + byName = grouped; + dnsQueriesByName.set(capture, byName); + return byName; +}; + +const matchesDnsAddressQuery = ( + candidate: DnsQuery, + view: Extract, +): boolean => + candidate.query === view.query && + (view.query_labels_hex === undefined || + equalLabelsHex(candidate.query_labels_hex, view.query_labels_hex)); + +const selectDnsQuery = ( + capture: Capture, + view: Extract, +): DnsQuery | undefined => { + if (view.query_index !== undefined) { + const candidate = capture.dns_queries[view.query_index]; + return candidate !== undefined && matchesDnsAddressQuery(candidate, view) + ? candidate + : undefined; + } + const candidates = isImmutableJsonSnapshot(capture) + ? (indexedDnsQueries(capture).get(view.query) ?? []) + : capture.dns_queries; + let matched: DnsQuery | undefined; + for (const candidate of candidates) { + if (!matchesDnsAddressQuery(candidate, view)) continue; + if (matched !== undefined) return undefined; + matched = candidate; + } + return matched; +}; + const selectRows = ( capture: Capture, view: Exclude, @@ -223,15 +288,8 @@ const selectRows = ( total: capture.unattributed_dns_addresses.length, }); case "dns-addresses": { - const matches = capture.dns_queries.filter( - (query, index) => - query.query === view.query && - (view.query_index === undefined || index === view.query_index) && - (view.query_labels_hex === undefined || - JSON.stringify(query.query_labels_hex) === - JSON.stringify(view.query_labels_hex)), - ); - if (matches.length !== 1) + const matched = selectDnsQuery(capture, view); + if (matched === undefined) return err( analysisViewInputError([ { @@ -245,9 +303,9 @@ const selectRows = ( return ok({ page: { facet: view.facet, - items: slice(matches[0]!.response_addresses), + items: slice(matched.response_addresses), }, - total: matches[0]!.response_addresses.length, + total: matched.response_addresses.length, }); } } diff --git a/src/domain/analysisView/protobufCaptureView.test.ts b/src/domain/analysisView/protobufCaptureView.test.ts index 06ce8c02e9..1dd24c53d4 100644 --- a/src/domain/analysisView/protobufCaptureView.test.ts +++ b/src/domain/analysisView/protobufCaptureView.test.ts @@ -1,11 +1,16 @@ -import { expect, it } from "vitest"; +import { expect, it, vi } from "vitest"; import { changedEvidenceSubject } from "../../../tests/fixtures/evidenceSubject.js"; import { createEvidence } from "../evidence.js"; +import { + freezeJsonSnapshot, + isImmutableJsonSnapshot, +} from "../immutableJson.js"; +import * as webNetworkCapture from "../webNetworkCapture.js"; import { projectAnalysisView } from "./analysisView.js"; -import { webNetworkCaptureSchema } from "../webNetworkCapture.js"; +import * as protobufCaptureView from "./protobufCaptureView.js"; const capture = async () => { - const report = webNetworkCaptureSchema.parse({ + const report = webNetworkCapture.webNetworkCaptureSchema.parse({ artifact: { path: "/recordings/a.har", bytes: 100, sha256: "b".repeat(64) }, decoder: { id: "projection-fixture", @@ -228,3 +233,118 @@ it("omits large values by default, returns requested text inline and preserves p }).ok, ).toBe(false); }); + +it("reuses one frozen capture snapshot across repeated webNetworkCapture and protobuf pages", async () => { + const { report, parent } = await capture(); + const sharedReported = { + request: { method: "GET", url: "https://example.test" }, + }; + const record0 = report.records[0]!; + const multi = webNetworkCapture.webNetworkCaptureSchema.parse({ + ...report, + total_records: 2, + records: [ + { ...record0, ordinal: 0, reported: sharedReported }, + { + ...record0, + ordinal: 1, + location: { kind: "json-pointer", pointer: "/log/entries/1" }, + reported: sharedReported, + }, + ], + }); + const sealedSnapshot = freezeJsonSnapshot({ + ...multi, + records: multi.records.map((entry) => ({ + ...entry, + reported: sharedReported, + })), + }); + const sealedParent = { + ...parent, + sealedResult: true, + normalizedResult: sealedSnapshot, + }; + const unsealedParent = { + ...parent, + sealedResult: false, + normalizedResult: structuredClone(multi), + }; + + const parseSpy = vi.spyOn( + webNetworkCapture.webNetworkCaptureSchema, + "safeParse", + ); + const passedReports: unknown[] = []; + const originalProject = protobufCaptureView.projectProtobufCapturePage; + const protobufSpy = vi + .spyOn(protobufCaptureView, "projectProtobufCapturePage") + .mockImplementation((parsedReport, view) => { + passedReports.push(parsedReport); + return originalProject(parsedReport, view); + }); + try { + const summary = projectAnalysisView(sealedParent, { kind: "summary" }); + const page1 = projectAnalysisView(sealedParent, { + kind: "protobuf", + collection: "fields", + field_numbers: [1, 2], + offset: 0, + limit: 2, + }); + const page2 = projectAnalysisView( + { ...sealedParent }, + { + kind: "protobuf", + collection: "fields", + field_numbers: [1, 2], + offset: 2, + limit: 2, + }, + ); + const preview = projectAnalysisView(sealedParent, { + kind: "capture", + detail: "preview", + offset: 0, + limit: 2, + }); + expect(parseSpy).toHaveBeenCalledTimes(1); + expect(protobufSpy).toHaveBeenCalledTimes(2); + expect(passedReports).toHaveLength(2); + expect(isImmutableJsonSnapshot(passedReports[0])).toBe(true); + expect(passedReports[1]).toBe(passedReports[0]); + + expect(summary).toEqual( + projectAnalysisView(unsealedParent, { kind: "summary" }), + ); + expect(page1).toEqual( + projectAnalysisView(unsealedParent, { + kind: "protobuf", + collection: "fields", + field_numbers: [1, 2], + offset: 0, + limit: 2, + }), + ); + expect(page2).toEqual( + projectAnalysisView(unsealedParent, { + kind: "protobuf", + collection: "fields", + field_numbers: [1, 2], + offset: 2, + limit: 2, + }), + ); + expect(preview).toEqual( + projectAnalysisView(unsealedParent, { + kind: "capture", + detail: "preview", + offset: 0, + limit: 2, + }), + ); + } finally { + parseSpy.mockRestore(); + protobufSpy.mockRestore(); + } +}); diff --git a/src/domain/analysisView/wasmArtifactView.ts b/src/domain/analysisView/wasmArtifactView.ts index 2211c04a59..43d729c2e1 100644 --- a/src/domain/analysisView/wasmArtifactView.ts +++ b/src/domain/analysisView/wasmArtifactView.ts @@ -2,7 +2,7 @@ import { analysisViewInputError } from "./analysisViewErrors.js"; import { z } from "zod"; import { uniqueSorted } from "../canonicalOrdering.js"; import { err, ok } from "../result.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import { wasmArtifactSchema, wasmArtifactMatchesSubject, @@ -72,6 +72,8 @@ export const wasmSummarySchema = z.strictObject({ limitation_count: z.int().nonnegative(), }); +const readWasmArtifact = createAnalysisViewResultReader(wasmArtifactSchema); + /** Read the exact retained WABT forms with source identity and explicit uncertainty. */ export const projectWasmArtifactView = ( parent: AnalysisViewParent, @@ -90,7 +92,7 @@ export const projectWasmArtifactView = ( }, ]), ); - const parsed = parseAnalysisViewResult(wasmArtifactSchema, parent); + const parsed = readWasmArtifact(parent); if (!parsed.ok) return parsed; const report = parsed.value; if ( diff --git a/src/domain/analysisView/webNetworkCaptureView.ts b/src/domain/analysisView/webNetworkCaptureView.ts index 485501bcc0..7f30b2eee6 100644 --- a/src/domain/analysisView/webNetworkCaptureView.ts +++ b/src/domain/analysisView/webNetworkCaptureView.ts @@ -5,7 +5,7 @@ import { import { analysisViewInputError } from "./analysisViewErrors.js"; import { z } from "zod"; import type { AnalysisError } from "../analysisErrorBase.js"; -import { parseAnalysisViewResult } from "./analysisViewParent.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; import type { JsonValue } from "../jsonValue.js"; import { err, ok, type Result } from "../result.js"; import { @@ -460,13 +460,15 @@ const preview = (record: WebNetworkCaptureRecord, format: string) => { }; }; -const captureParser = { safeParse: safeParseOwnedWebNetworkCapture }; +const readCaptureParent = createAnalysisViewResultReader({ + safeParse: safeParseOwnedWebNetworkCapture, +}); /** Authenticate the retained report and its subject at one owning boundary. */ const parseCaptureParent = ( parent: AnalysisViewParent, ): Result => { - const parsed = parseAnalysisViewResult(captureParser, parent); + const parsed = readCaptureParent(parent); if (!parsed.ok) return parsed; const report = parsed.value; const subject = evidenceFileTarget(parent); @@ -544,7 +546,8 @@ export const projectWebNetworkCaptureView = ( "Decoding covers selected retained bodies only. Exhausting wire fields does not establish schema completeness or business meaning; compressed bodies and unsupported schema facets remain unknown.", ], }); - if (view.kind === "summary") + if (view.kind === "summary") { + const protobufSummary = summarizeProtobuf(report.records); return ok({ kind: "summary" as const, view, @@ -559,15 +562,14 @@ export const projectWebNetworkCaptureView = ( ...(report.protobuf_coverage === undefined ? {} : { protobuf_coverage: report.protobuf_coverage }), - ...(summarizeProtobuf(report.records) === undefined - ? {} - : { protobuf: summarizeProtobuf(report.records)! }), + ...(protobufSummary === undefined ? {} : { protobuf: protobufSummary }), ...(report.format === "qlog" ? { qlog: summarizeQlogCapture(report.qlog) } : {}), }, coverage: completeWithinViewCoverage(report.records.length), }); + } if (view.kind === "qlog") { if (report.format !== "qlog") return err(