diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index 8d90e0f598..fe0a31d855 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -51,6 +51,122 @@ const gated = (rows: readonly TimedCaptureRow[], tool: string) => { const RENAMED = renamedBook(FIRST_BOOK, "Renamed Book", 3); +it.each([ + ["read", "1", null], + ["read", "2", { ordinal: 4, pointer: "" }], + ["source", "1", null], + ["source", "2", { ordinal: 5, pointer: "" }], +] as const)( + "does not borrow an entity read across an overlapping %s write to book %s", + (phase, target, expected) => { + const rows = [ + [ + "GET", + "/api/books", + [ + { id: 1, name: "A" }, + { id: 2, name: "B" }, + ], + 200, + undefined, + 0, + 5, + ], + ["GET", "/api/books/1", { id: 1, name: "A" }, 200, undefined, 1, 5], + ["GET", "/api/books/2", { id: 2, name: "B" }, 200, undefined, 2, 5], + ...(phase === "source" + ? [ + [ + "POST", + `/api/books/${target}/archive`, + null, + 204, + {}, + 3, + 10_000, + ] as const, + ] + : []), + [ + "PATCH", + "/api/books/1", + null, + 204, + { name: "Z" }, + phase === "source" ? 4 : 3, + 5, + ], + [ + "GET", + "/api/books/1", + { id: 1, name: "Z" }, + 200, + undefined, + phase === "source" ? 5 : 4, + phase === "source" ? 5 : 1_500, + ], + ...(phase === "read" + ? [ + [ + "POST", + `/api/books/${target}/archive`, + null, + 204, + {}, + 5, + 5, + ] as const, + ] + : []), + [ + "GET", + "/api/books/1", + { id: 1, name: "Z" }, + 200, + undefined, + phase === "source" ? 14 : 6, + 5, + ], + ] as const; + const entries = rows.map( + ([method, path, body, status, request, time, duration]) => ({ + startedDateTime: new Date( + Date.UTC(2026, 0, 1, 0, 0, time), + ).toISOString(), + time: duration, + request: { + method, + url: `http://app.example${path}`, + bodySize: + request === undefined + ? 0 + : Buffer.byteLength(JSON.stringify(request)), + ...(request === undefined + ? {} + : { + postData: { + mimeType: "application/json", + text: JSON.stringify(request), + }, + }), + }, + response: { + status, + content: { mimeType: "application/json", text: JSON.stringify(body) }, + }, + }), + ); + const capture = analysisViewCaptureEvidence( + environmentManifestCaptureFixture(entries), + ); + const plan = environmentStateViewOf(capture).writes.find( + ({ tool }) => tool === "patch_books_by_id", + ); + expect(plan?.observation).toEqual(expected); + if (target === "1") expect(plan?.served).toBe(false); + }, +); + /** A book whose constant names organisation 1, created at exchange `seconds`. */ const tiedToOrgOne = (id: number, name: string, seconds: number): Book => ({ ...book(id, name, bookClock(seconds)), @@ -1532,6 +1648,7 @@ describe("resolved encoded item observations", () => { const search: ObservationSearch = { records, chronology: new StateRecordChronology(records, "record-order"), + overlapsWrite: () => false, from: 0, viewOf: () => itemView, withBody: (_ordinal, use) => use({ id: "%61", name: "After" }), diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 28c6527cc4..178415eef0 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -338,6 +338,7 @@ export class EnvironmentStateWriteSimulation { record.path, this.#input.chronology.endMs(record), this.#input.chronology.startMs(record), + record.ordinal, ); this.#input.records.forEach((record, index) => this.#step(record, index)); const views = new Map( @@ -409,6 +410,7 @@ export class EnvironmentStateWriteSimulation { }, records: this.#input.records, chronology: this.#input.chronology, + overlapsWrite: (record, exclude) => this.#overlapsWrite(record, exclude), viewOf: (ordinal) => { const view = this.#input.views.get( this.#toolOf.get(ordinal)?.name ?? "", @@ -576,7 +578,7 @@ export class EnvironmentStateWriteSimulation { /** Whether an item read shows an entity an unmodelled write made, or one left unknown, again rather than checks it. */ #resynced(view: StateView, record: StateRecordFacts, index: number): boolean { if (view.shape !== "item") return false; - if (this.#writeOverlapsRead(record)) return true; + if (this.#overlapsWrite(record)) return true; const adopted = this.#unseen.adopt(view, { record, index }); if (adopted !== undefined) { this.#taint.known(adopted.type, adopted.collection, adopted.id); @@ -687,7 +689,7 @@ export class EnvironmentStateWriteSimulation { if (original === undefined) return; let view = this.#sorted.comparisonView(this.omitted.view(original)); if (projectedRead(view, record, this.#input.io)) return; - if (this.#writeOverlapsRead(record)) return; + if (this.#overlapsWrite(record)) return; const borrowers = this.#observations.get(record.ordinal); if ( this.#viewOf(original).shape !== "recorded" && @@ -830,11 +832,12 @@ export class EnvironmentStateWriteSimulation { } /** An overlapping captured write cannot supply a stable read baseline. */ - #writeOverlapsRead(read: StateRecordFacts): boolean { + #overlapsWrite(read: StateRecordFacts, exclude?: number): boolean { return this.#writeCompletion.runningAt( read.path, this.#input.chronology.startMs(read), this.#input.chronology.endMs(read), + exclude, ); } diff --git a/src/domain/analysisView/environmentStateWriteCompletion.test.ts b/src/domain/analysisView/environmentStateWriteCompletion.test.ts index 68e59028fa..d45b0dd237 100644 --- a/src/domain/analysisView/environmentStateWriteCompletion.test.ts +++ b/src/domain/analysisView/environmentStateWriteCompletion.test.ts @@ -25,7 +25,7 @@ it("preserves the existing prefix relation, including non-transitive decoding an ]; for (const write of candidates) { const completion = new CapturedWriteCompletion(() => {}); - completion.write(write, undefined); + completion.write(write, undefined, -Infinity, 1); for (const read of candidates) expect(completion.runningAt(read, 100), `${write} -> ${read}`).toBe( prefixRelated(write, read), @@ -35,31 +35,31 @@ it("preserves the existing prefix relation, including non-transitive decoding an it("retains unknown completion and isolates unrelated writes while aggregating known ends", () => { const completion = new CapturedWriteCompletion(() => {}); - completion.write("/api/books/1", 20); - completion.write("/api/books/1", 30); - completion.write("/api/books/2", undefined); - completion.write("/api/books/2", 10); + completion.write("/api/books/1", 20, -Infinity, 2); + completion.write("/api/books/1", 30, -Infinity, 3); + completion.write("/api/books/2", undefined, -Infinity, 4); + completion.write("/api/books/2", 10, -Infinity, 5); expect(completion.runningAt("/api/books/1", 29)).toBe(true); expect(completion.runningAt("/api/books/1", 30)).toBe(false); expect(completion.runningAt("/api/books/1", undefined)).toBe(true); expect(completion.runningAt("/api/books/2", 100)).toBe(true); expect(completion.runningAt("/api/books", 100)).toBe(true); expect(completion.runningAt("/api/authors", undefined)).toBe(false); - completion.write("/", undefined); + completion.write("/", undefined, -Infinity, 6); expect(completion.runningAt("/api/authors", 100)).toBe(true); }); it("uses explicit record-order coordinates without treating absent writes as pending", () => { const completion = new CapturedWriteCompletion(() => {}); expect(completion.runningAt("/api/books", undefined)).toBe(false); - completion.write("/api/books", 1); + completion.write("/api/books", 1, -Infinity, 7); expect(completion.runningAt("/api/books/1", 2)).toBe(false); }); it("looks up a concrete path without reinterpreting every retained write path", () => { const completion = new CapturedWriteCompletion(() => {}); for (let id = 0; id < 128; id += 1) - completion.write(`/api/books/${String(id)}`, undefined); + completion.write(`/api/books/${String(id)}`, undefined, -Infinity, id); const decoded = vi.spyOn(paths, "decodedSegment"); try { expect(completion.runningAt("/api/books/64", 100)).toBe(true); @@ -77,12 +77,14 @@ it("reserves retained prefix growth before publishing an unbudgeted edge", () => if (bytes > remaining) throw refused; remaining -= bytes; }); - completion.write("/api/books/1", 10); + completion.write("/api/books/1", 10, -Infinity, 9); remaining = 0; // Updating an indexed path retains no new keys or nodes. - completion.write("/api/books/1", 20); + completion.write("/api/books/1", 20, -Infinity, 10); expect(completion.runningAt("/api/books/1", 19)).toBe(true); - expect(() => completion.write("/api/authors/1", undefined)).toThrow(refused); + expect(() => + completion.write("/api/authors/1", undefined, -Infinity, 11), + ).toThrow(refused); expect(completion.runningAt("/api/authors/1", 100)).toBe(false); expect(completion.runningAt("/api", 100)).toBe(false); expect(completion.runningAt("/", 100)).toBe(false); @@ -92,8 +94,8 @@ it("reserves retained prefix growth before publishing an unbudgeted edge", () => it("queries both interval boundaries across future writes in chronology order", () => { const completion = new CapturedWriteCompletion(() => {}); - completion.write("/api/books/1", 15, 10); - completion.write("/api/books/1", undefined, 30); + completion.write("/api/books/1", 15, 10, 12); + completion.write("/api/books/1", undefined, 30, 13); expect(completion.runningAt("/api/books/1", 5, 10)).toBe(false); expect(completion.runningAt("/api/books/1", 5, 11)).toBe(true); expect(completion.runningAt("/api/books/1", 15, 30)).toBe(false); @@ -104,9 +106,47 @@ it("queries both interval boundaries across future writes in chronology order", it("keeps a simultaneous unknown write ambiguous for a point read, unlike a known point write", () => { const completion = new CapturedWriteCompletion(() => {}); - completion.write("/api/books/1", undefined, 10); - completion.write("/api/books/2", 10, 10); + completion.write("/api/books/1", undefined, 10, 14); + completion.write("/api/books/2", 10, 10, 15); expect(completion.runningAt("/api/books/1", 10, 10)).toBe(true); expect(completion.runningAt("/api/books/2", 10, 10)).toBe(false); expect(completion.runningAt("/api/books/3", 10, 10)).toBe(false); }); + +it("excludes only the source write while retaining simultaneous and unknown competitors", () => { + const completion = new CapturedWriteCompletion(() => {}); + completion.write("/api/books/1", 20, 10, 1); + expect(completion.runningAt("/api/books/1", 10, 20, 1)).toBe(false); + completion.write("/api/books/1", 12, 10, 2); + expect(completion.runningAt("/api/books/1", 10, 20, 1)).toBe(true); + expect(completion.runningAt("/api/books/1", 12, 20, 1)).toBe(false); + completion.write("/api/books/1", undefined, 10, 3); + expect(completion.runningAt("/api/books/1", 100, 101, 1)).toBe(true); + expect(completion.runningAt("/api/books/1", 100, 101, 3)).toBe(false); + expect(completion.runningAt("/api/books/2", 10, 20, 1)).toBe(false); +}); + +it("matches raw interval overlap when excluding each write", () => { + const writes = [ + { id: 1, start: 0, end: 20 }, + { id: 2, start: 1, end: 5 }, + { id: 3, start: 1, end: undefined }, + { id: 4, start: 4, end: 4 }, + ]; + const completion = new CapturedWriteCompletion(() => {}); + for (const write of writes) + completion.write("/api/books/1", write.end, write.start, write.id); + for (const start of [0, 1, 4, 5, 20, 30]) + for (const end of [start, start + 1, 30]) + for (const excluded of [undefined, ...writes.map(({ id }) => id)]) { + const expected = writes.some( + (write) => + write.id !== excluded && + (write.start < end || (start === end && write.start === end)) && + (write.end === undefined || write.end > start), + ); + expect(completion.runningAt("/api/books/1", start, end, excluded)).toBe( + expected, + ); + } +}); diff --git a/src/domain/analysisView/environmentStateWriteCompletion.ts b/src/domain/analysisView/environmentStateWriteCompletion.ts index dec7dde716..58bbc2bcc1 100644 --- a/src/domain/analysisView/environmentStateWriteCompletion.ts +++ b/src/domain/analysisView/environmentStateWriteCompletion.ts @@ -5,32 +5,43 @@ import { segmentsOf, } from "./environmentStateRules.js"; -/** Ordered write starts and the latest completion among writes through each start. */ +/** Ordered starts and the two latest completions from distinct writes through each start, allowing one exclusion. */ class CompletionHistory { readonly #starts: number[] = []; - readonly #ends: (number | undefined)[] = []; + readonly #ends: { + readonly id: number; + readonly end: number | undefined; + }[][] = []; constructor(private readonly retain: (bytes: number) => void) {} reserve(start: number): void { - if (this.#starts.at(-1) !== start) this.retain(ENTRY_BYTES); + // Reserve the prefix summary array and up to two distinct write entries. + if (this.#starts.at(-1) !== start) this.retain(ENTRY_BYTES * 3); } - append(start: number, end: number | undefined): void { - const previous = this.#ends.at(-1); - const maximum = - end === undefined || (this.#ends.length > 0 && previous === undefined) - ? undefined - : Math.max(previous ?? -Infinity, end); - if (this.#starts.at(-1) === start) - this.#ends[this.#ends.length - 1] = maximum; + append(start: number, end: number | undefined, id: number): void { + const entries = [...(this.#ends.at(-1) ?? []), { id, end }].sort( + (a, b) => (b.end ?? Infinity) - (a.end ?? Infinity), + ); + const best = entries + .filter( + (entry, index) => + entries.findIndex((item) => item.id === entry.id) === index, + ) + .slice(0, 2); + if (this.#starts.at(-1) === start) this.#ends[this.#ends.length - 1] = best; else { this.#starts.push(start); - this.#ends.push(maximum); + this.#ends.push(best); } } - overlaps(start: number | undefined, end: number | undefined): boolean { + overlaps( + start: number | undefined, + end: number | undefined, + exclude?: number, + ): boolean { // Admit same-start writes for a point observation; a known zero-length write // is still excluded by its completion below. Otherwise starts at read end are disjoint. // Find writes begun before the read completed. Unknown read completion @@ -48,9 +59,14 @@ class CompletionHistory { else high = middle; } if (low === 0) return false; - const completion = this.#ends[low - 1]; + const completion = this.#ends[low - 1]?.find( + (entry) => entry.id !== exclude, + ); return ( - completion === undefined || start === undefined || completion > start + completion !== undefined && + (completion.end === undefined || + start === undefined || + completion.end > start) ); } } @@ -113,7 +129,13 @@ export class CapturedWriteCompletion { } /** Admit writes in nondecreasing chronology start order. */ - write(path: string, end: number | undefined, start = -Infinity): void { + write( + path: string, + end: number | undefined, + start: number | undefined, + id: number, + ): void { + start ??= -Infinity; let node = this.#root; const ancestors = [node]; // Finish budgeted path admission before publishing any completion summary. @@ -127,13 +149,18 @@ export class CapturedWriteCompletion { ); histories.push((node.terminal ??= new CompletionHistory(this.retain))); for (const history of histories) history.reserve(start); - for (const history of histories) history.append(start, end); + for (const history of histories) history.append(start, end, id); } /** Unknown completion or read start cannot prove that a related write finished. */ - runningAt(path: string, start: number | undefined, end = Infinity): boolean { + runningAt( + path: string, + start: number | undefined, + end = Infinity, + exclude?: number, + ): boolean { const running = (history: CompletionHistory | undefined): boolean => - history?.overlaps(start, end) === true; + history?.overlaps(start, end, exclude) === true; let nodes = new Set([this.#root]); for (const segment of segmentsOf(path)) { const next = new Set(); diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 53c9380954..003255ba5b 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -6,7 +6,6 @@ import { isObject, locateItem, at, - same, type JsonObject, type ParsedRequestBody, requestJson, @@ -176,6 +175,10 @@ export interface EffectContext { readonly io: WriteIo; readonly records: readonly StateRecordFacts[]; readonly chronology: StateRecordChronology; + readonly overlapsWrite: ( + record: StateRecordFacts, + exclude?: number, + ) => boolean; /** Whether a record may change state: a write the capture does not show reading only. */ readonly isWrite: (record: StateRecordFacts) => boolean; readonly viewOf: (ordinal: number) => StateView | undefined; @@ -317,6 +320,7 @@ export const searchFrom = (context: EffectContext, step: WriteStep) => ({ records: context.records, from: step.index, chronology: context.chronology, + overlapsWrite: context.overlapsWrite, viewOf: context.viewOf, withBody: context.io.withBody, queryOf: context.io.queryOf, diff --git a/src/domain/analysisView/environmentStateWriteObserve.ts b/src/domain/analysisView/environmentStateWriteObserve.ts index f05591d9d4..1b693d16cf 100644 --- a/src/domain/analysisView/environmentStateWriteObserve.ts +++ b/src/domain/analysisView/environmentStateWriteObserve.ts @@ -180,6 +180,11 @@ export interface ObservationSearch { readonly from: number; /** Completion must be established before a read may supply a write observation. */ readonly chronology: StateRecordChronology; + /** A read overlapping a related captured write cannot establish its result. */ + readonly overlapsWrite: ( + record: StateRecordFacts, + exclude?: number, + ) => boolean; readonly viewOf: (ordinal: number) => StateView | undefined; readonly withBody: ( ordinal: number, @@ -241,11 +246,17 @@ export const laterObservation = ( ) => boolean; }, ): Observed | undefined => { + const source = search.records[search.from]!; + if (search.overlapsWrite(source, source.ordinal)) return undefined; for (const record of search.records.slice(search.from + 1)) { if (target.isWrite(record)) return undefined; // The same overlap the check path ignores: the write was still running when this read began. if ( - !search.chronology.completedBefore(search.records[search.from]!, record) + !search.chronology.completedBefore( + search.records[search.from]!, + record, + ) || + search.overlapsWrite(record) ) continue; const view = search.viewOf(record.ordinal);