From 5f15fdf457a890a149cbe574cce96e32422c1904 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Mon, 30 Nov 2026 19:43:40 +0800 Subject: [PATCH] perf(evidence): inspect retained records without building a bundle (#15219) * perf(evidence): inspect retained records without building a bundle * perf(evidence): reuse ordered inspection records across pages * docs(evidence): clarify sealed inspection records --------- Co-authored-by: Vincent Koc --- src/application/binary/BinarySessionPort.ts | 2 + .../binary/BinarySessionRecords.ts | 5 ++ .../investigation/EvidenceLedger.ts | 18 ++++++ .../investigation/InspectEvidenceBundle.ts | 28 ++++++--- .../investigation/InvestigationRecords.ts | 5 ++ src/domain/evidenceRecordSummary.ts | 21 +++++-- src/server/sessionToolBindings.ts | 3 +- .../mcp/evidenceRecordSelectionMcp.test.ts | 60 ++++++++++++++++++- 8 files changed, 127 insertions(+), 15 deletions(-) diff --git a/src/application/binary/BinarySessionPort.ts b/src/application/binary/BinarySessionPort.ts index 620be67aad5..fd49f6a3eea 100644 --- a/src/application/binary/BinarySessionPort.ts +++ b/src/application/binary/BinarySessionPort.ts @@ -1,4 +1,5 @@ import type { Evidence } from "../../domain/evidence.js"; +import type { EvidenceInspectionRecords } from "../../domain/evidenceRecordSummary.js"; import type { EspFlashSelection } from "../../domain/firmware/espFlashLocation.js"; import type { InvestigationRecordPort } from "../investigation/InvestigationRecordPort.js"; import type { RecoveryAdmission } from "../investigation/InvestigationRetention.js"; @@ -65,6 +66,7 @@ export interface BinarySessionPort extends AnalysisOperationPort, InvestigationRecordPort { /** Borrow the current immutable Evidence records without constructing a bundle. */ recordsForAnalysis(): readonly Evidence[]; + evidenceInspectionRecords(): EvidenceInspectionRecords; readonly admitRecoveryObservation: RecoveryAdmission; /** Execute only against a positively ready, already-created provider client. */ executeIfProviderReady( diff --git a/src/application/binary/BinarySessionRecords.ts b/src/application/binary/BinarySessionRecords.ts index b97e80dd87f..bb4a6e6091b 100644 --- a/src/application/binary/BinarySessionRecords.ts +++ b/src/application/binary/BinarySessionRecords.ts @@ -1,3 +1,4 @@ +import type { EvidenceInspectionRecords } from "../../domain/evidenceRecordSummary.js"; import { bindSnapshotReplayExecution } from "./SessionEvidenceReuse.js"; import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js"; import { analysisProfilesEqual } from "../../domain/analysisProfile.js"; @@ -172,6 +173,10 @@ export abstract class BinarySessionRecords { return this.#records.exportEvidenceBundle(); } + evidenceInspectionRecords(): EvidenceInspectionRecords { + return this.#records.evidenceInspectionRecords(); + } + /** Borrow the record owner's immutable bundle for read-only workflows. */ immutableEvidenceBundle(): EvidenceBundle { return this.#records.immutableEvidenceBundle(); diff --git a/src/application/investigation/EvidenceLedger.ts b/src/application/investigation/EvidenceLedger.ts index 678e7300709..68213d66121 100644 --- a/src/application/investigation/EvidenceLedger.ts +++ b/src/application/investigation/EvidenceLedger.ts @@ -1,3 +1,4 @@ +import type { EvidenceInspectionRecords } from "../../domain/evidenceRecordSummary.js"; import { InvalidResidualUnknownGraphError } from "../../domain/residualUnknownGraphError.js"; import { z } from "zod"; import { Budget } from "../../domain/budget.js"; @@ -88,6 +89,7 @@ export class EvidenceLedger { #sortedUnknownHeads: readonly ResidualUnknown[] | undefined; #recordBytes = new Map(); #cachedImmutableBundle: EvidenceBundle | undefined; + #cachedInspectionRecords: EvidenceInspectionRecords | undefined; readonly #retained: Budget; constructor( private readonly retentionPolicy: InvestigationRetentionPolicy = {}, @@ -326,6 +328,20 @@ export class EvidenceLedger { return [...this.#records.values()]; } + /** Read the facts used by partial Evidence inspection in canonical ID order. */ + evidenceInspectionRecords(): EvidenceInspectionRecords { + // Ingestion already deeply seals each record; only the ordered container is new. + this.#cachedInspectionRecords ??= Object.freeze({ + records: Object.freeze( + [...this.#records.values()].sort((left, right) => + compareUnicodeCodePoints(left.evidence_id, right.evidence_id), + ), + ), + unknownRevisions: this.#unknownRevisions.size, + }); + return this.#cachedInspectionRecords; + } + /** Check whether one immutable Evidence ID is present in this ledger. */ has(evidenceId: string): boolean { return this.#records.has(evidenceId); @@ -575,6 +591,7 @@ export class EvidenceLedger { this.#records.clear(); this.#unknownRevisions.clear(); this.#cachedImmutableBundle = undefined; + this.#cachedInspectionRecords = undefined; this.#unknownHeads.clear(); this.#sortedUnknownHeads = undefined; this.#retained.restore(0); @@ -768,6 +785,7 @@ export class EvidenceLedger { #commitAccounting(changes: RetentionChanges): void { this.#cachedImmutableBundle = undefined; + this.#cachedInspectionRecords = undefined; for (const [id, bytes] of changes.recordBytes) this.#recordBytes.set(id, bytes); // #admitChanges admitted the delta against the same, unchanged allowance. diff --git a/src/application/investigation/InspectEvidenceBundle.ts b/src/application/investigation/InspectEvidenceBundle.ts index f897e6ffa2b..1c75087b4de 100644 --- a/src/application/investigation/InspectEvidenceBundle.ts +++ b/src/application/investigation/InspectEvidenceBundle.ts @@ -6,6 +6,7 @@ import { selectEvidenceRecords, summarizeEvidenceBundle, type EvidenceBundleSummary, + type EvidenceInspectionRecords, type EvidenceLinkInspection, type EvidenceRecordFilters, type EvidenceRecordSelection, @@ -24,7 +25,12 @@ const DELIVERY_FIELDS = [ /** Select complete delivery, discovery metadata, complete records, or link membership. */ export const inspectEvidenceBundle = ( - bundle: EvidenceBundle, + source: + | EvidenceBundle + | { + immutableEvidenceBundle(): EvidenceBundle; + evidenceInspectionRecords(): EvidenceInspectionRecords; + }, options: { readonly detail: InspectionDetail; readonly filters?: EvidenceRecordFilters | undefined; @@ -76,6 +82,16 @@ export const inspectEvidenceBundle = ( }), ), ); + if (options.detail === "complete") + return ok( + "immutableEvidenceBundle" in source + ? source.immutableEvidenceBundle() + : source, + ); + const bundle = + "evidenceInspectionRecords" in source + ? source.evidenceInspectionRecords() + : source; if (options.detail === "records") return ok( selectEvidenceRecords(bundle, options.filters, { @@ -94,11 +110,9 @@ export const inspectEvidenceBundle = ( }), ); return ok( - options.detail === "summary" - ? summarizeEvidenceBundle(bundle, options.filters, { - offset: options.offset, - limit: options.limit, - }) - : bundle, + summarizeEvidenceBundle(bundle, options.filters, { + offset: options.offset, + limit: options.limit, + }), ); }; diff --git a/src/application/investigation/InvestigationRecords.ts b/src/application/investigation/InvestigationRecords.ts index 7880aab8b49..028ad08b6d4 100644 --- a/src/application/investigation/InvestigationRecords.ts +++ b/src/application/investigation/InvestigationRecords.ts @@ -1,3 +1,4 @@ +import type { EvidenceInspectionRecords } from "../../domain/evidenceRecordSummary.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; import type { Evidence } from "../../domain/evidence.js"; import type { EvidenceBundle } from "../../domain/evidenceBundle.js"; @@ -108,6 +109,10 @@ export class InvestigationRecords return this.#evidence.export(); } + evidenceInspectionRecords(): EvidenceInspectionRecords { + return this.#evidence.evidenceInspectionRecords(); + } + /** Borrow an authenticated immutable bundle snapshot without copying its records. */ immutableEvidenceBundle(): EvidenceBundle { return this.#evidence.immutableBundle(); diff --git a/src/domain/evidenceRecordSummary.ts b/src/domain/evidenceRecordSummary.ts index bc54171d118..a0064378b1e 100644 --- a/src/domain/evidenceRecordSummary.ts +++ b/src/domain/evidenceRecordSummary.ts @@ -10,6 +10,12 @@ import { import type { EvidenceBundle } from "./evidenceBundle.js"; import { nativeValueFlowMetadataSchema } from "./native/nativeValueFlow.js"; +/** Canonically ordered records and the committed Unknown revision count. */ +export interface EvidenceInspectionRecords { + readonly records: readonly Evidence[]; + readonly unknownRevisions: number; +} + /** Exact retained-record selectors; selection never resolves a provider address. */ export const evidenceRecordFiltersSchema = z.strictObject({ evidence_id: prefixedDigestSchema("ev").optional(), @@ -146,7 +152,7 @@ const selectedFilters = ( /** One owner for exact filter semantics, in canonical bundle (Evidence ID) order. */ function* matchingEvidenceRecords( - bundle: EvidenceBundle, + bundle: Pick, filters: EvidenceRecordFilters, ): Generator<{ readonly evidence: Evidence; @@ -184,7 +190,9 @@ const directLinksOf = ({ evidence_links: links }: Evidence): string[] => /** Discover retained Evidence without reading or copying its complete payloads. */ export const summarizeEvidenceBundle = ( - bundle: EvidenceBundle, + bundle: + | EvidenceInspectionRecords + | Pick, filters: EvidenceRecordFilters = {}, options: { readonly offset?: number | undefined; @@ -227,7 +235,10 @@ export const summarizeEvidenceBundle = ( filters: selectedFilters(filters), total_retained_records: bundle.records.length, matching_records: matchingRecords, - unknown_revisions: bundle.unknowns.length, + unknown_revisions: + "unknownRevisions" in bundle + ? bundle.unknownRevisions + : bundle.unknowns.length, direct_links: directLinks, missing_direct_links: missingDirectLinks, records, @@ -278,7 +289,7 @@ export type EvidenceRecordSelection = z.infer< /** Select one page of complete authenticated records without copying the rest of the ledger. */ export const selectEvidenceRecords = ( - bundle: EvidenceBundle, + bundle: Pick, filters: EvidenceRecordFilters = {}, page: { readonly offset?: number | undefined; @@ -380,7 +391,7 @@ export type EvidenceLinkInspection = z.infer< /** Read link membership without copying or parsing any record payload. */ export const inspectEvidenceLinks = ( - bundle: EvidenceBundle, + bundle: Pick, filters: EvidenceRecordFilters = {}, options: { readonly traversal?: diff --git a/src/server/sessionToolBindings.ts b/src/server/sessionToolBindings.ts index e5687e287a8..91c96872211 100644 --- a/src/server/sessionToolBindings.ts +++ b/src/server/sessionToolBindings.ts @@ -589,8 +589,7 @@ export const bindSessionRecordTools = ({ get_evidence_bundle: { admission: "sdk", admitted: true, - value: async (input) => - inspectEvidenceBundle(session.immutableEvidenceBundle(), input), + value: async (input) => inspectEvidenceBundle(session, input), }, list_unknowns: { admission: "sdk", diff --git a/tests/boundary/mcp/evidenceRecordSelectionMcp.test.ts b/tests/boundary/mcp/evidenceRecordSelectionMcp.test.ts index 91f550c1725..918e6e5ac2b 100644 --- a/tests/boundary/mcp/evidenceRecordSelectionMcp.test.ts +++ b/tests/boundary/mcp/evidenceRecordSelectionMcp.test.ts @@ -1,7 +1,8 @@ +import { inspectEvidenceBundle } from "../../../src/application/investigation/InspectEvidenceBundle.js"; import { withCanonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { afterAll, expect, it } from "vitest"; +import { afterAll, expect, it, vi } from "vitest"; import { z } from "zod"; import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js"; import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js"; @@ -116,6 +117,63 @@ const connect = async ( return { client, session, reply, select }; }; +it("inspects retained pages without constructing an Evidence bundle", async () => { + const { client, session, reply } = await connect({ + records: [...LEDGER].reverse(), + }); + const unknown = await client.callTool({ + name: "record_unknown", + arguments: { + question: "Which source generated this artifact?", + domain: "provenance", + severity: "medium", + required_authority: "shipped-artifact", + required_confidence: "observed", + required_environment: null, + recommended_probes: [], + relationships: [], + }, + }); + expect(unknown.isError).not.toBe(true); + const canonicalBundle = session.immutableEvidenceBundle(); + expect(canonicalBundle.unknowns).toHaveLength(1); + const snapshot = session.evidenceInspectionRecords(); + expect(snapshot).toBe(session.evidenceInspectionRecords()); + expect(Object.isFrozen(snapshot.records)).toBe(true); + const builder = vi.spyOn(session, "immutableEvidenceBundle"); + try { + for (const detail of ["summary", "records", "links"] as const) { + const options = { detail, offset: 0, limit: 1 }; + const expected = inspectEvidenceBundle(canonicalBundle, options); + if (!expected.ok) throw expected.error; + const result = await reply(options); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toMatchObject({ + result: expected.value, + }); + } + expect(builder).not.toHaveBeenCalled(); + const complete = await reply({ detail: "complete" }); + expect(complete.structuredContent).toMatchObject({ + result: canonicalBundle, + }); + expect(builder).toHaveBeenCalledOnce(); + expect(session.evidenceInspectionRecords()).toBe(snapshot); + expect(session.recordEvidence(unretainedSource).ok).toBe(true); + expect(session.evidenceInspectionRecords()).not.toBe(snapshot); + const page = await reply({ + detail: "records", + filters: { evidence_id: unretainedSource.evidence_id }, + }); + expect(page.structuredContent).toMatchObject({ + result: { records: [unretainedSource] }, + }); + expect(builder).toHaveBeenCalledOnce(); + } finally { + builder.mockRestore(); + } +}); + it.each(["compact"] as const)( "returns selected complete records with retained identities (%s)", async (profile) => {