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 <vincentkoc@ieee.org>
This commit is contained in:
ShuaixinHuangandVincent Koc authored and GitHub committed 2026-11-30 19:43:40 +08:00
1 parent f5055cd2ed
commit 5f15fdf457
8 files changed
+127 -15

No files matched your search

@@ -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(
@@ -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();
@@ -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<string, number>();
#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.
@@ -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,
}),
);
};
@@ -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();
+16 -5
View File
@@ -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<EvidenceInspectionRecords, "records">,
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<EvidenceBundle, "records" | "unknowns">,
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<EvidenceInspectionRecords, "records">,
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<EvidenceInspectionRecords, "records">,
filters: EvidenceRecordFilters = {},
options: {
readonly traversal?:
+1 -2
View File
@@ -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",
@@ -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) => {