diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index 0f047d3740f..e0aeca760ba 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -62,9 +62,8 @@ override is `source: "runtime"`. The structured field is `update_mode: "runtime" | `native.matching_representation_bytes` | `REA_NATIVE_MATCHING_REPRESENTATION_BYTES` | `src/domain/analysisResourceLimits.ts` | 100663296 | 1 | 1073741824 | per operation | | `delivery.agent_result_budget_bytes` | `REA_AGENT_RESULT_BUDGET_BYTES` | `src/domain/analysisResourceLimits.ts` | 32768 | 4096 | 10485760 | per operation | -`delivery.agent_result_budget_bytes` is a delivery budget, not an admission -limit: an over-budget result is retained and delivered as its summary with an -`inspect_analysis_view` cursor, never refused. +See [Agent result budget](limits-and-recovery.md#agent-result-budget) for +`delivery.agent_result_budget_bytes` delivery and recovery behavior. An out-of-range `update_analysis_settings` value is rejected by the setting's schema. Invalid launch seeds that the global environment parser accepts as diff --git a/src/application/analysisView/EvidenceJsonView.test.ts b/src/application/analysisView/EvidenceJsonView.test.ts index 78d38d02bfa..6d220a8c973 100644 --- a/src/application/analysisView/EvidenceJsonView.test.ts +++ b/src/application/analysisView/EvidenceJsonView.test.ts @@ -1,10 +1,14 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createEvidence, type Evidence } from "../../domain/evidence.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { EvidenceLedger } from "../investigation/EvidenceLedger.js"; import { inspectAnalysisViewValidated } from "./AnalysisViewService.js"; -import { DEFAULT_EVIDENCE_JSON_PAGE_BYTES } from "../../domain/analysisView/evidenceJsonView.js"; +import { + DEFAULT_EVIDENCE_JSON_PAGE_BYTES, + EvidenceJsonSerializationCache, + projectEvidenceJsonView, +} from "../../domain/analysisView/evidenceJsonView.js"; import { DEFAULT_AGENT_RESULT_BUDGET_BYTES } from "../../domain/analysisResourceLimits.js"; const parentEvidence = (): Evidence => @@ -80,6 +84,183 @@ describe("evidence-json view", () => { } }); + it("pages a record it does not cache from a window, matching the cached pages", () => { + // A mutable inline parent is never cached, so each page streams the + // serialization and keeps only the requested window. + const inline = parentEvidence(); + const ledger = new EvidenceLedger(); + expect(ledger.record(parentEvidence()).ok).toBe(true); + const text = JSON.stringify(inline); + const streamed = (offset: number, limit: number | undefined) => { + const projected = projectEvidenceJsonView( + { + evidenceId: inline.evidence_id, + operation: inline.operation, + predicateType: inline.predicate_type, + normalizedResult: inline.normalized_result, + limitations: inline.limitations, + evidence: inline, + } as never, + { + kind: "evidence-json", + offset, + ...(limit === undefined ? {} : { limit }), + }, + ); + if (!projected.ok) throw projected.error; + return projected.value; + }; + for (const limit of [1, 7, 64, undefined]) { + let offset = 0; + let joined = ""; + for (;;) { + const value = streamed(offset, limit); + if (limit !== undefined) + expect(value.text).toBe( + page(ledger, inline.evidence_id, offset, limit).text, + ); + joined += value.text; + if (value.coverage.next_offset === null) break; + offset = value.coverage.next_offset; + } + expect(joined).toBe(text); + } + }); + + const retainedParent = ( + ledger: EvidenceLedger, + label: string, + rows = 120, + ) => { + const evidence = createEvidence( + { path: `/fixture/${label}.bin`, sha256: "d".repeat(64), format: "elf" }, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "inspect_byte_entropy", + parameters: {}, + result: { + rows: Array.from({ length: rows }, (_, index) => ({ + index, + label: `${label} ${String(index)} \u{1F600}`, + })), + }, + limitations: [], + }, + ); + expect(ledger.record(evidence).ok).toBe(true); + const retained = ledger.forAnalysis(evidence.evidence_id)!; + return { + evidenceId: retained.evidence_id, + operation: retained.operation, + predicateType: retained.predicate_type, + normalizedResult: retained.normalized_result, + limitations: retained.limitations, + evidence: retained, + }; + }; + + const joinPages = ( + parent: ReturnType, + cache: EvidenceJsonSerializationCache, + limit: number, + ): string => { + let offset = 0; + let joined = ""; + for (;;) { + const projected = projectEvidenceJsonView( + parent as never, + { kind: "evidence-json", offset, limit }, + cache, + ); + if (!projected.ok) throw projected.error; + joined += projected.value.text; + if (projected.value.coverage.next_offset === null) return joined; + offset = projected.value.coverage.next_offset; + } + }; + + it("pages a retained record past the cache size from a window without caching it", () => { + const ledger = new EvidenceLedger(); + // jsonParts yields parts of up to 16 Ki code units; this record spans + // many, so the window can keep far fewer than the whole record. + const parent = retainedParent(ledger, "large", 4000); + const text = JSON.stringify(parent.evidence); + // The scan collects whole parts until the total passes the cache, then + // keeps only the window: pages before and after that point must match. + const cache = new EvidenceJsonSerializationCache( + Math.floor(text.length / 2), + ); + for (const limit of [4096, 50_000]) { + expect(joinPages(parent, cache, limit)).toBe(text); + } + expect(cache.holds(parent.evidence)).toBe(false); + expect(cache.cachedCodeUnits).toBe(0); + // Past the cache size the scan keeps only parts around the window, not + // a transient copy of the whole record. + const page = cache.serialize(parent.evidence as never, 0, 8); + const kept = page.chunks.reduce((units, chunk) => units + chunk.length, 0); + expect(page.totalLength).toBe(text.length); + expect(kept).toBeLessThan(text.length / 2); + }); + + it("evicts the least recently used record to stay within the cache size", () => { + const ledger = new EvidenceLedger(); + const first = retainedParent(ledger, "rec-a"); + const second = retainedParent(ledger, "rec-b"); + const third = retainedParent(ledger, "rec-c"); + // Equal-length labels give every record the same serialized size. + const size = JSON.stringify(first.evidence).length; + expect(JSON.stringify(second.evidence).length).toBe(size); + const cache = new EvidenceJsonSerializationCache(size * 2 + 64); + const read = (parent: typeof first) => + projectEvidenceJsonView( + parent as never, + { kind: "evidence-json", offset: 0, limit: 8 }, + cache, + ); + read(first); + read(second); + expect(cache.holds(first.evidence)).toBe(true); + expect(cache.holds(second.evidence)).toBe(true); + // Reading the first again makes the second the least recently used. + read(first); + read(third); + expect(cache.holds(first.evidence)).toBe(true); + expect(cache.holds(second.evidence)).toBe(false); + expect(cache.holds(third.evidence)).toBe(true); + expect(cache.cachedCodeUnits).toBeLessThanOrEqual(cache.maximumCodeUnits); + // An evicted record still pages exactly from a fresh scan. + expect(joinPages(second, cache, 97)).toBe(JSON.stringify(second.evidence)); + }); + + it("unregisters evicted entries from FinalizationRegistry during repeated churn", () => { + const ledger = new EvidenceLedger(); + const first = retainedParent(ledger, "churn-a"); + const second = retainedParent(ledger, "churn-b"); + const size = JSON.stringify(first.evidence).length; + const cache = new EvidenceJsonSerializationCache(size + 64); + const unregister = vi.spyOn(FinalizationRegistry.prototype, "unregister"); + try { + for (let round = 0; round < 4; round += 1) { + projectEvidenceJsonView( + first as never, + { kind: "evidence-json", offset: 0, limit: 8 }, + cache, + ); + projectEvidenceJsonView( + second as never, + { kind: "evidence-json", offset: 0, limit: 8 }, + cache, + ); + } + // 8 insertions into a 1-record cache trigger 7 evictions, each unregistered. + expect(unregister).toHaveBeenCalledTimes(7); + expect(cache.cachedCodeUnits).toBe(size); + } finally { + unregister.mockRestore(); + } + }); + it("keeps a surrogate pair whole even in a one-unit page", () => { const parent = parentEvidence(); const ledger = new EvidenceLedger(); diff --git a/src/domain/analysisView/evidenceJsonView.ts b/src/domain/analysisView/evidenceJsonView.ts index 1f5c83b3769..e8b0a162391 100644 --- a/src/domain/analysisView/evidenceJsonView.ts +++ b/src/domain/analysisView/evidenceJsonView.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import type { Evidence } from "../evidence.js"; +import { Budget } from "../budget.js"; import { isImmutableJsonSnapshot } from "../immutableJson.js"; import { DEFAULT_AGENT_RESULT_BUDGET_BYTES } from "../analysisResourceLimits.js"; import { jsonParts } from "../jsonSerialization.js"; @@ -56,36 +57,143 @@ interface SerializedEvidenceJson { } /** - * One chunked serialization per immutable retained record, built with - * `jsonParts` so records exceeding Node's single-string limit remain pageable. - * Paging is then O(log(chunks) + limit) per call after the first; a mutable - * inline parent is serialized per call because nothing proves it is unchanged. + * Code units of serialized Evidence kept across calls, summed over records. + * It is a delivery cache, not an admission limit: a record that does not fit + * is still paged, by a streaming pass that keeps only the requested window. */ -const serialized = new WeakMap(); +export const EVIDENCE_JSON_CACHE_CODE_UNITS = 16 * 1024 * 1024; -const buildSerializedChunks = (evidence: Evidence): SerializedEvidenceJson => { - const chunks: string[] = []; - const starts: number[] = []; +/** Units kept around a window: one before it for surrogate checks, one after. */ +const WINDOW_MARGIN_CODE_UNITS = 2; + +/** + * Serialize `evidence` once with `jsonParts`, so records past Node's single + * string limit stay pageable. It keeps every part while the total fits + * `wholeLimit`; past that it keeps only parts overlapping `[from, to)`, so + * memory stays bounded by the window. Offsets in `starts` stay absolute. + */ +const scanSerializedChunks = ( + evidence: Evidence, + wholeLimit: number, + from: number, + to: number, +): SerializedEvidenceJson & { readonly whole: boolean } => { + let chunks: string[] = []; + let starts: number[] = []; + let whole = true; let totalLength = 0; for (const part of jsonParts(evidence)) { if (part.length === 0) continue; - starts.push(totalLength); - chunks.push(part); + const start = totalLength; totalLength += part.length; + if (whole && totalLength > wholeLimit) { + whole = false; + const kept = chunks.flatMap((chunk, index) => + starts[index]! + chunk.length > from && starts[index]! < to + ? [[chunk, starts[index]!] as const] + : [], + ); + chunks = kept.map(([chunk]) => chunk); + starts = kept.map(([, at]) => at); + } + if (whole || (totalLength > from && start < to)) { + starts.push(start); + chunks.push(part); + } } starts.push(totalLength); - return { chunks, starts, totalLength }; + return { chunks, starts, totalLength, whole }; }; -const serializeEvidence = (evidence: Evidence): SerializedEvidenceJson => { - if (!isImmutableJsonSnapshot(evidence)) - return buildSerializedChunks(evidence); - const known = serialized.get(evidence); - if (known !== undefined) return known; - const doc = buildSerializedChunks(evidence); - serialized.set(evidence, doc); - return doc; -}; +interface CacheEntry { + /** Weak, so a cached record is released when its owner releases it. */ + readonly record: WeakRef; + readonly codeUnits: number; +} + +/** + * Whole serializations of immutable records, least recently used first, so + * repeated paging of a record is O(log(chunks) + limit). Their total stays + * within the cache's code units. Records are held weakly: the cache never + * extends a record's lifetime, and a collected record's units are released. + * A mutable inline parent is never cached because nothing proves it is + * unchanged; it and any record too large to fit are paged from a window. + */ +export class EvidenceJsonSerializationCache { + readonly #documents = new WeakMap< + object, + { readonly document: SerializedEvidenceJson; readonly entry: CacheEntry } + >(); + readonly #order = new Set(); + readonly #collected = new FinalizationRegistry((entry) => { + if (this.#order.delete(entry)) this.#budget.refund(entry.codeUnits); + }); + readonly #budget: Budget; + + constructor(readonly maximumCodeUnits = EVIDENCE_JSON_CACHE_CODE_UNITS) { + this.#budget = new Budget(maximumCodeUnits); + } + + /** Code units of the whole serializations currently cached. */ + get cachedCodeUnits(): number { + return this.#budget.used; + } + + /** Whether `record`'s whole serialization is cached. */ + holds(record: object): boolean { + return this.#documents.has(record); + } + + /** The serialization one page of `evidence` reads. */ + serialize( + evidence: Evidence, + offset: number, + limit: number | undefined, + ): SerializedEvidenceJson { + const cacheable = isImmutableJsonSnapshot(evidence); + if (cacheable) { + const known = this.#documents.get(evidence); + if (known !== undefined) { + this.#order.delete(known.entry); + this.#order.add(known.entry); + return known.document; + } + } + // A default page is at most DEFAULT_EVIDENCE_JSON_PAGE_BYTES escaped + // bytes, and every code unit escapes to at least one byte. + const window = limit ?? DEFAULT_EVIDENCE_JSON_PAGE_BYTES; + const document = scanSerializedChunks( + evidence, + cacheable ? this.maximumCodeUnits : 0, + Math.max(0, offset - WINDOW_MARGIN_CODE_UNITS), + offset + window + WINDOW_MARGIN_CODE_UNITS, + ); + if (document.whole && cacheable) this.#remember(evidence, document); + return document; + } + + #remember(record: object, document: SerializedEvidenceJson): void { + const charged = this.#budget.chargeEvicting(document.totalLength, () => { + const oldest = this.#order.values().next().value; + if (oldest === undefined) return undefined; + this.#order.delete(oldest); + this.#collected.unregister(oldest); + const evicted = oldest.record.deref(); + if (evicted !== undefined) this.#documents.delete(evicted); + return oldest.codeUnits; + }); + if (!charged) return; + const entry: CacheEntry = { + record: new WeakRef(record), + codeUnits: document.totalLength, + }; + this.#documents.set(record, { document, entry }); + this.#order.add(entry); + this.#collected.register(record, entry, entry); + } +} + +const sharedSerializations = new EvidenceJsonSerializationCache(); /** Chunk index containing UTF-16 offset `index` (`0 <= index < doc.totalLength`). */ const locateChunk = (doc: SerializedEvidenceJson, index: number): number => { @@ -200,6 +308,7 @@ const pageEnd = ( export const projectEvidenceJsonView = ( parent: AnalysisViewParent, view: EvidenceJsonViewRequest, + serializations: EvidenceJsonSerializationCache = sharedSerializations, ) => { if (parent.evidence === undefined) return err( @@ -212,7 +321,11 @@ export const projectEvidenceJsonView = ( }, ]), ); - const doc = serializeEvidence(parent.evidence); + const doc = serializations.serialize( + parent.evidence, + view.offset, + view.limit, + ); const start = Math.min(view.offset, doc.totalLength); if (splitsPair(doc, start)) return err(