diff --git a/src/application/analysisView/EvidenceJsonView.test.ts b/src/application/analysisView/EvidenceJsonView.test.ts index 51d4d510f1e..c4f7d17fe9f 100644 --- a/src/application/analysisView/EvidenceJsonView.test.ts +++ b/src/application/analysisView/EvidenceJsonView.test.ts @@ -8,6 +8,7 @@ import { EvidenceJsonSerializationCache, projectEvidenceJsonView, } from "../../domain/analysisView/evidenceJsonView.js"; +import * as jsonSerialization from "../../domain/jsonSerialization.js"; import { MINIMUM_AGENT_RESULT_BUDGET_BYTES } from "../../domain/analysisResourceLimits.js"; /** Text bytes of a domain page whose limit is omitted. */ @@ -189,8 +190,8 @@ describe("evidence-json view", () => { // 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. + // Read the whole record twice with different limits, rewinding the window + // for the second pass. const cache = new EvidenceJsonSerializationCache( Math.floor(text.length / 2), ); @@ -199,8 +200,7 @@ describe("evidence-json view", () => { } 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. + // The resumed serializer keeps only parts around the selected window. 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); @@ -208,7 +208,42 @@ describe("evidence-json view", () => { // A smaller window inside the last one, as a page shrunk to its budget // reads, reuses that window instead of scanning the record again. expect(cache.serialize(parent.evidence as never, 0, 4)).toBe(page); - expect(cache.serialize(parent.evidence as never, 8, 8)).not.toBe(page); + + const fullCache = new EvidenceJsonSerializationCache(); + const lastPair = text.lastIndexOf("😀"); + for (const offset of [lastPair, lastPair + 1, text.length + 10, 0]) { + const view = { kind: "evidence-json", offset, limit: 1 } as const; + expect( + projectEvidenceJsonView(parent as never, view, PAGE_BYTES, cache), + ).toEqual( + projectEvidenceJsonView(parent as never, view, PAGE_BYTES, fullCache), + ); + } + }); + + it("serializes an oversized retained record at most twice across forward pages", () => { + const parent = retainedParent(new EvidenceLedger(), "forward", 4000); + const expected = JSON.stringify(parent.evidence); + const cache = new EvidenceJsonSerializationCache( + Math.floor(expected.length / 4), + ); + const { jsonParts } = jsonSerialization; + let serialized = 0; + const parts = vi + .spyOn(jsonSerialization, "jsonParts") + .mockImplementation(function* (value, pretty) { + for (const part of jsonParts(value, pretty)) { + if (value === parent.evidence) serialized += part.length; + yield part; + } + }); + try { + expect(joinPages(parent, cache, 4096)).toBe(expected); + expect(serialized).toBeGreaterThanOrEqual(expected.length); + expect(serialized).toBeLessThanOrEqual(expected.length * 2); + } finally { + parts.mockRestore(); + } }); it("evicts the least recently used record to stay within the cache size", () => { diff --git a/src/domain/analysisView/evidenceJsonView.ts b/src/domain/analysisView/evidenceJsonView.ts index 11816faa67c..db8b77bbc18 100644 --- a/src/domain/analysisView/evidenceJsonView.ts +++ b/src/domain/analysisView/evidenceJsonView.ts @@ -41,7 +41,7 @@ type EvidenceJsonViewRequest = z.output; interface SerializedEvidenceJson { readonly chunks: readonly string[]; - /** Cumulative UTF-16 code unit start of each chunk, ending with `totalLength`. */ + /** Absolute UTF-16 code unit start of each retained chunk. */ readonly starts: readonly number[]; readonly totalLength: number; } @@ -49,7 +49,7 @@ interface SerializedEvidenceJson { /** * 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. + * is still paged from a bounded streaming window. */ export const EVIDENCE_JSON_CACHE_CODE_UNITS = 16 * 1024 * 1024; @@ -91,7 +91,6 @@ const scanSerializedChunks = ( chunks.push(part); } } - starts.push(totalLength); return { chunks, starts, totalLength, whole }; }; @@ -101,13 +100,63 @@ interface CacheEntry { readonly codeUnits: number; } +/** Resume forward reads without keeping the serialized document in memory. */ +class EvidenceJsonWindow { + #parts: Generator; + #position = 0; + #from = 0; + #chunks: readonly string[] = []; + #starts: readonly number[] = []; + + constructor( + evidence: Evidence, + readonly totalLength: number, + ) { + this.#parts = jsonParts(evidence); + } + + read(evidence: Evidence, from: number, to: number): SerializedEvidenceJson { + if (from < this.#from) { + this.#parts = jsonParts(evidence); + this.#position = 0; + this.#chunks = []; + this.#starts = []; + } + this.#from = from; + const chunks: string[] = []; + const starts: number[] = []; + for (let index = 0; index < this.#chunks.length; index += 1) { + const chunk = this.#chunks[index]!; + const start = this.#starts[index]!; + if (start + chunk.length > from) { + chunks.push(chunk); + starts.push(start); + } + } + while (this.#position < Math.min(to, this.totalLength)) { + const part = this.#parts.next(); + if (part.done) break; + const start = this.#position; + this.#position += part.value.length; + if (this.#position > from) { + chunks.push(part.value); + starts.push(start); + } + } + this.#chunks = chunks; + this.#starts = starts; + return { chunks, starts, totalLength: this.totalLength }; + } +} + /** * 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. + * unchanged and is paged by a fresh scan. The latest oversized immutable + * record has a rolling window, owned weakly by that record. */ export class EvidenceJsonSerializationCache { readonly #documents = new WeakMap< @@ -115,6 +164,8 @@ export class EvidenceJsonSerializationCache { { readonly document: SerializedEvidenceJson; readonly entry: CacheEntry } >(); readonly #order = new Set(); + readonly #windows = new WeakMap(); + #windowOwner?: WeakRef; readonly #collected = new FinalizationRegistry((entry) => { if (this.#order.delete(entry)) this.#budget.refund(entry.codeUnits); }); @@ -165,6 +216,10 @@ export class EvidenceJsonSerializationCache { to <= last.to ) return last.document; + const activeWindow = this.#windows.get(evidence); + if (activeWindow !== undefined) + return activeWindow.read(evidence, from, to); + const document = scanSerializedChunks( evidence, cacheable ? this.maximumCodeUnits : 0, @@ -172,8 +227,19 @@ export class EvidenceJsonSerializationCache { to, ); if (document.whole && cacheable) this.#remember(evidence, document); - else if (cacheable) + else if (cacheable) { + // Coverage needs the full length on the first page. Subsequent pages + // share that length and a forward serializer, without retaining its + // source through a strong reference outside this weak-keyed entry. + const previous = this.#windowOwner?.deref(); + if (previous !== undefined) this.#windows.delete(previous); + this.#windows.set( + evidence, + new EvidenceJsonWindow(evidence, document.totalLength), + ); + this.#windowOwner = new WeakRef(evidence); this.#lastWindow = { record: new WeakRef(evidence), from, to, document }; + } return document; }