From b49177e425f102570572a70f98880112c07c8c1a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 10:58:40 -0700 Subject: [PATCH 01/68] fix(environment): keep read-only POSTs out of the write list A POST that repeats the latest read of its path, tunnels only read operations, names a lookup in its path's last meaningful word, or renews a session no longer counts as a state write: it is replayed, does not cut initial windows, and does not end observation searches. A tool stays a write when a related read line changes across one of its calls. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 7 +- .../agent-environments/state-writes/spec.md | 30 +- docs/web-network-captures.md | 2 +- .../environment/environmentState.ts | 18 +- .../environmentStateWriteAnswer.test.ts | 15 + .../EnvironmentStateExtraction.ts | 42 ++- .../EnvironmentStateWriteSimulation.ts | 19 +- .../environmentStateQueryCalls.test.ts | 188 ++++++++++++ .../environmentStateQueryCalls.ts | 279 ++++++++++++++++++ .../analysisView/environmentStateRules.ts | 2 +- .../environmentStateWriteCreate.ts | 3 +- .../environmentStateWriteEffects.ts | 7 +- .../environmentStateWrites.test.ts | 35 +++ 13 files changed, 618 insertions(+), 29 deletions(-) create mode 100644 src/domain/analysisView/environmentStateQueryCalls.test.ts create mode 100644 src/domain/analysisView/environmentStateQueryCalls.ts diff --git a/docs/agent-environments.md b/docs/agent-environments.md index b4b8b575047..b8eecac07bb 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -443,8 +443,11 @@ state answer carries the base record's status, content type and `replay` provenance with `truncated: false`; one whose JSON would exceed 256 KiB is refused as a `resource_constraint` tool error rather than cut. Extraction does not state-back a document whose rendered JSON exceeds 256 KiB; that read stays -recorded (`rendered-oversize`) and replays the captured body. Query `POST`s -stay served and answer from their recordings with the reason `query-body`. +recorded (`rendered-oversize`) and replays the captured body. Query `POST`s, +and `POST` tools the capture shows only reading (a lookup answering as a `GET` +did, an RPC tunnel naming read operations, a session renewal), stay served and +answer from their recordings with the reason `query-body`; they are not write +tools. A line establishes whole-collection membership only from the beginning: `offset`, `start`, `_start` and `page` must be zero when present. Positive or diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index c50fc4d69a9..6aa333c9015 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -31,9 +31,37 @@ a reset give the same state. The view adds two members to its result: - `writes`: one plan per manifest tool whose method may change state - (`changesState`); + (`changesState`), less the `POST` tools the capture shows only reading (below); - `write_clock`: the instant the served clock starts from. +**Calls that only read.** A `POST` tool whose calls read state is no write: it +gets no plan, stays a recorded view with the reason `query-body`, is served by +replay, and its calls bound no initial-recording window and end no observation +search. The capture shows it by the first of these that applies: + +1. every successful call answers as the latest earlier successful `GET` of its + path did, with no write between (a status lookup posting the jobs it names); +2. every call names read operations only, in its body's `operation` or + `operations[].operation`, else its query's `operation`, `op` or `action` + (`batch` and similar only wrap them); an operation reads when its words name + one of `list`, `get`, `count`, `aggregate`, `info`, `search`, `find`, `read`, + `query`, `schema`, `describe`, `fetch` or `lookup`, and none of `create`, + `insert`, `update`, `delete`, `remove`, `upsert`, `add`, `set`, `save` and + similar; +3. a path segment's last meaningful word, split on `_`, `-`, `.` and case and + skipping trailing `data`, `info` and `results`, is a query word (`search`, + `query`, `list`, `find`, `lookup`, `count`, `aggregate`, `stats`, `ids`, + `selection`, `discover`, …): `selection_data` names a lookup, while + `query-history` names a history and stays a write; +4. a path segment renews or opens a session: `auth-refresh`, + `auth-with-password`, `login`, `logout`, `refresh` or `token`. + +A tool stays a write when a `GET` line whose path its call's path relates to +(segment by segment, a parameter matching any value) reads differently just +before and just after one of its calls with no other write between. Reads of +unrelated paths do not count, so a session renewal stays read-only although an +endpoint under the same root regenerates values on every read. + **Effects.** Each plan classifies its tool: | Effect | Tool | Target | diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index 5a5f75ef420..d85772c030b 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -612,7 +612,7 @@ recording of each request line from the state, comparing JSON values without regard to member order; a volatile field compares its recorded value. Each plan lists the `checked_record_ordinals`. Otherwise the tool is a recorded view with reason `envelope-varies`, `fields-differ` or `list-differs`; the other -reasons are `query-body` (a query `POST`), `no-init-recording`, +reasons are `query-body` (a query `POST`, or one the capture shows only reading), `no-init-recording`, `body-unusable`, `no-identity` (an item read without a proved identity), `path-varies` (another read under more than one path, as a template with a parameter before its end), `query-varies` (another read of one path under diff --git a/src/application/environment/environmentState.ts b/src/application/environment/environmentState.ts index bd91e0e8e7d..fcc4bf5a0b1 100644 --- a/src/application/environment/environmentState.ts +++ b/src/application/environment/environmentState.ts @@ -51,16 +51,22 @@ export interface EnvironmentState { readonly writeClock: string | null; } -/** The write plans a catalog serves from: none before a state is derived. */ -type ServedWrites = Pick; +/** The write plans a catalog serves from, and the views naming calls that only read: none before a state is derived. */ +type ServedWrites = Pick & + Partial>; -/** Serving from the state serves read tools and the write tools whose effect the capture confirmed. */ +/** Serving from the state serves read tools, calls the capture shows reading only, and the write tools whose effect it confirmed. */ const servedFromState = ( tool: EnvironmentManifestTool, state: ServedWrites, -): boolean => - !changesState(tool.method, tool.path_template) || - state.writes.get(tool.name)?.served === true; +): boolean => { + const view = state.views?.get(tool.name); + return ( + !changesState(tool.method, tool.path_template) || + (view?.shape === "recorded" && view.reason === "query-body") || + state.writes.get(tool.name)?.served === true + ); +}; /** The tools an environment serves and the data plane its card declares. */ export interface ServedCatalog { diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index ca94f28472d..a9c2349a4f2 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1549,3 +1549,18 @@ describe("asset sequence inference", () => { ).toEqual(gamma); }); }); + +describe("served catalog of calls that only read", () => { + it("serves a lookup POST the capture shows reading only, by replay", () => { + const { source, state } = servedFrom([ + ...BOOK_INIT_ROWS, + ["POST", "/api/books/ids", [FIRST_BOOK], 200, { ids: [1] }], + ]); + const catalog = servedCatalog(source, state, "books"); + if (!catalog.ok) throw catalog.error; + expect(catalog.value.tools.map((tool) => tool.name)).toContain( + "post_books_ids", + ); + expect(state.writes.has("post_books_ids")).toBe(false); + }); +}); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index a05402a3e4f..7c224502dc9 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -14,7 +14,6 @@ import { isObject, isParam, isQueryPost, - isStateWrite, jsonBytes, lastSegmentValue, STATE_BODY_LIMIT_BYTES, @@ -56,6 +55,7 @@ import { } from "./environmentStateGate.js"; import { StateWriteCutoffs } from "./environmentStateWriteCutoffs.js"; import { extractWrites } from "./environmentStateWrites.js"; +import { stateWritesOf } from "./environmentStateQueryCalls.js"; class StateBudgetExhausted extends Error {} @@ -81,8 +81,10 @@ export class EnvironmentStateExtraction { readonly #budget: StateBudget; readonly #position: ReadonlyMap; readonly #byOrdinal: ReadonlyMap; - readonly #writes: readonly StateRecordFacts[]; - readonly #writeWithin: ReturnType; + /** POST tools whose calls the capture shows read state rather than change it. */ + #readOnly: ReadonlySet = new Set(); + #writes: readonly StateRecordFacts[] = []; + #writeWithin: ReturnType = writeSpanCheck([]); readonly #bases: ReadonlyMap; #writeCutoffs: StateWriteCutoffs | undefined; readonly #initLimits = new Map(); @@ -116,14 +118,26 @@ export class EnvironmentStateExtraction { this.#byOrdinal = new Map( input.records.map((record) => [record.ordinal, record]), ); - this.#writes = input.records.filter(isStateWrite); - this.#writeWithin = writeSpanCheck(this.#writes); this.#bases = apiBaseLengths(input.tools.map((tool) => tool.path_template)); } + /** The timeline's state writes, less the calls of tools that only read. */ + #findWrites(): void { + ({ readOnly: this.#readOnly, writes: this.#writes } = stateWritesOf( + this.#tools, + this.#records, + { + response: (ordinal) => this.#withBody(ordinal, (body) => body), + request: (ordinal) => this.#requestBody(ordinal), + }, + )); + this.#writeWithin = writeSpanCheck(this.#writes); + } + /** The extracted state, or null when the representation budget is exhausted. */ run(): ExtractedState | null { try { + this.#findWrites(); if (this.#writes.length > 0) this.#writeCutoffs = new StateWriteCutoffs( this.#writes, @@ -166,15 +180,12 @@ export class EnvironmentStateExtraction { ...extractWrites(state, { tools: this.#tools, records: this.#records, + readOnly: this.#readOnly, timed: this.#timeline === "recorded-start-time", volatileOf: (type) => this.#volatileOf(type), io: { withBody: (ordinal, use) => this.#withBody(ordinal, use), - requestBody: (ordinal) => { - const parsed = this.#budget.requestBody(ordinal); - if (parsed === null) throw new StateBudgetExhausted(); - return parsed.kind === "json" ? parsed.value : undefined; - }, + requestBody: (ordinal) => this.#requestBody(ordinal), emptyResponse: (ordinal) => this.#budget.emptyResponse(ordinal), retain: (bytes) => this.#retain(bytes), }, @@ -182,6 +193,12 @@ export class EnvironmentStateExtraction { }; } + #requestBody(ordinal: number): JsonValue | undefined { + const parsed = this.#budget.requestBody(ordinal); + if (parsed === null) throw new StateBudgetExhausted(); + return parsed.kind === "json" ? parsed.value : undefined; + } + #retain(bytes: number): void { if (!this.#budget.retain(bytes)) throw new StateBudgetExhausted(); } @@ -205,7 +222,10 @@ export class EnvironmentStateExtraction { #candidates(): Candidate[] { const candidates: Candidate[] = []; for (const tool of this.#tools) { - if (isQueryPost(tool.method, tool.path_template)) + if ( + isQueryPost(tool.method, tool.path_template) || + this.#readOnly.has(tool.name) + ) this.#recorded(tool, "query-body"); if (tool.method !== "GET") continue; const segments = segmentsOf(tool.path_template); diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 971e6d9cca2..3afa7a794e0 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -143,7 +143,11 @@ export class EnvironmentStateWriteSimulation { documents.set(normalizedPath(tool.path_template), tool.name); const types = new Set(this.#types.keys()); for (const tool of this.#input.tools) { - if (!changesState(tool.method, tool.path_template)) continue; + if ( + !changesState(tool.method, tool.path_template) || + this.#input.readOnly.has(tool.name) + ) + continue; const { effect, target } = classifyWrite(tool, types, documents); this.#input.io.retain(512); this.#drafts.set(tool.name, { @@ -170,14 +174,23 @@ export class EnvironmentStateWriteSimulation { #step(record: StateRecordFacts, index: number): void { const tool = this.#toolOf.get(record.ordinal); // A redirected or unanswered write may have changed state, but only a 2xx one shows its effect. - if (isStateWrite(record) && !succeeded(record)) + if (this.#isWrite(record) && !succeeded(record)) this.#unmodelled(record.path, index); - else if (isStateWrite(record)) this.#write(record, index, tool); + else if (this.#isWrite(record)) this.#write(record, index, tool); else if (tool?.method === "GET") this.#read(record, index, tool); } + /** Whether a record may change state: a state write whose tool the capture does not show reading only. */ + #isWrite(record: StateRecordFacts): boolean { + return ( + isStateWrite(record) && + !this.#input.readOnly.has(this.#toolOf.get(record.ordinal)?.name ?? "") + ); + } + #context(writer: string): EffectContext { return { + isWrite: (record) => this.#isWrite(record), state: this.#state, io: this.#input.io, records: this.#input.records, diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts new file mode 100644 index 00000000000..9f789bc0ba1 --- /dev/null +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it } from "vitest"; + +import type { JsonValue } from "../jsonValue.js"; +import { readOnlyTools } from "./environmentStateQueryCalls.js"; +import type { + StateRecordFacts, + StateToolFacts, +} from "./environmentStateRules.js"; + +interface Call { + readonly method: string; + readonly path: string; + readonly query?: string; + readonly status?: number; + readonly response?: JsonValue; + readonly request?: JsonValue; + readonly tool: string; + readonly template?: string; +} + +/** The read-only tools of a timeline of calls, ordinals in order. */ +const readOnlyOf = (calls: readonly Call[]): string[] => { + const records: StateRecordFacts[] = calls.map((call, index) => ({ + ordinal: index, + method: call.method, + path: call.path, + query: call.query, + status: call.status ?? 200, + start: index, + end: index, + })); + const tools = new Map(); + calls.forEach((call, index) => { + const known = tools.get(call.tool); + tools.set(call.tool, { + name: call.tool, + method: call.method, + path_template: call.template ?? call.path, + record_ordinals: [...(known?.record_ordinals ?? []), index], + }); + }); + return [ + ...readOnlyTools([...tools.values()], records, { + response: (ordinal) => calls[ordinal]?.response, + request: (ordinal) => calls[ordinal]?.request, + }), + ].sort(); +}; + +const JOBS = [{ id: "night-watch", status: "running" }]; + +describe("POSTs that read state", () => { + it("reads a POST answering as the latest GET of its path did, with no write between", () => { + const get = { + method: "GET", + path: "/v1/jobs/statuses", + tool: "get_statuses", + response: JOBS, + }; + const post = { + method: "POST", + path: "/v1/jobs/statuses", + tool: "post_statuses", + request: { jobs: ["night-watch"] }, + }; + expect(readOnlyOf([get, { ...post, response: JOBS }])).toEqual([ + "post_statuses", + ]); + expect(readOnlyOf([get, { ...post, response: [] }])).toEqual([]); + const write = { + method: "PUT", + path: "/v1/job/night-watch", + tool: "put_job", + response: {}, + }; + expect(readOnlyOf([get, write, { ...post, response: JOBS }])).toEqual([]); + }); + + it("reads an RPC tunnel whose calls name only read operations, in the body or the query", () => { + const tunnel = (operations: string[]): Call => ({ + method: "POST", + path: "/api/v2/internal/nc/base1", + query: "?operation=batch", + template: "/api/v2/internal/nc/{uid}", + tool: "post_internal", + request: { + operations: operations.map((operation) => ({ operation, query: {} })), + }, + response: { results: [] }, + }); + expect(readOnlyOf([tunnel(["tableSyncList", "listScripts"])])).toEqual([ + "post_internal", + ]); + expect( + readOnlyOf([tunnel(["tableList"]), tunnel(["tableCreate"])]), + ).toEqual([]); + // A container operation names no operation of its own. + expect(readOnlyOf([{ ...tunnel([]), request: {} }])).toEqual([]); + const queried = { + method: "POST", + path: "/rpc", + query: "?op=getUser", + tool: "post_rpc", + response: {}, + }; + expect(readOnlyOf([queried])).toEqual(["post_rpc"]); + }); + + it("reads a POST whose path names a lookup word, split on underscores, hyphens and case", () => { + const post = (path: string, tool: string, template = path): Call => ({ + method: "POST", + path, + template, + tool, + response: [], + }); + expect( + readOnlyOf([ + post("/api/documents/selection_data/", "post_selection"), + post( + "/api/v4/channels/c1/members/ids", + "post_member_ids", + "/api/v4/channels/{uid}/members/ids", + ), + post("/v1/discover", "post_discover"), + post("/api/members", "post_members"), + ]), + ).toEqual(["post_discover", "post_member_ids", "post_selection"]); + }); + + it("reads a lookup by a segment's last meaningful word, so a query history stays a write", () => { + const post = (path: string, tool: string): Call => ({ + method: "POST", + path, + tool, + response: {}, + }); + expect( + readOnlyOf([ + post("/api/query-history", "post_query_history"), + post("/api/documents/selection_data/", "post_selection"), + post("/api/search-results", "post_search_results"), + ]), + ).toEqual(["post_search_results", "post_selection"]); + }); + + it("reads a session renewal, not a create in the same collection tree", () => { + const post = (path: string, tool: string): Call => ({ + method: "POST", + path, + tool, + response: { token: "x" }, + }); + expect( + readOnlyOf([ + post("/api/collections/_superusers/auth-refresh", "post_auth_refresh"), + post("/api/collections/notes/records", "post_records"), + ]), + ).toEqual(["post_auth_refresh"]); + }); + + it("keeps a lookup-named POST a write when a read its path relates to changes across it alone", () => { + const read = (members: string[]): Call => ({ + method: "GET", + path: "/api/members", + tool: "get_members", + response: members, + }); + const post: Call = { + method: "POST", + path: "/api/members/ids", + tool: "post_ids", + response: ["a"], + }; + expect(readOnlyOf([read(["a"]), post, read(["a", "b"])])).toEqual([]); + expect(readOnlyOf([read(["a"]), post, read(["a"])])).toEqual(["post_ids"]); + // Another write between explains the change, so the POST stays read-only. + const other: Call = { + method: "PUT", + path: "/api/members/b", + tool: "put_member", + response: {}, + }; + expect(readOnlyOf([read(["a"]), post, other, read(["a", "b"])])).toEqual([ + "post_ids", + ]); + }); +}); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts new file mode 100644 index 00000000000..419789289f9 --- /dev/null +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -0,0 +1,279 @@ +import type { JsonValue } from "../jsonValue.js"; +import { + changesState, + isObject, + isParam, + isStateWrite, + QUERY_SEGMENTS, + same, + segmentsOf, + type StateRecordFacts, + type StateToolFacts, +} from "./environmentStateRules.js"; +import { prefixRelated } from "./environmentStateWriteRules.js"; + +/** The words of a segment or operation name: split on `_`, `-`, `.` and camelCase, in lower case. */ +const words = (text: string): string[] => + text + .split(/[_\-.\s]+/u) + .flatMap((part) => part.split(/(?<=[a-z0-9])(?=[A-Z])/u)) + .map((word) => word.toLowerCase()) + .filter((word) => word.length > 0); + +/** Path words that name a lookup rather than a change. */ +const QUERY_WORDS = new Set([ + ...[...QUERY_SEGMENTS].flatMap(words), + "ids", + "selection", + "discover", +]); +/** Trailing words that only qualify what a segment names, so the word before them decides. */ +const NEUTRAL_WORDS = new Set(["data", "info", "results"]); +/** Whole path segments that renew or open a session rather than change state. */ +const SESSION_SEGMENTS = new Set([ + "auth-refresh", + "auth-with-password", + "login", + "logout", + "refresh", + "token", +]); +const READ_OPERATION_WORDS = new Set([ + "list", + "get", + "count", + "aggregate", + "info", + "search", + "find", + "read", + "query", + "schema", + "describe", + "fetch", + "lookup", +]); +const WRITE_OPERATION_WORDS = new Set([ + "create", + "insert", + "update", + "delete", + "remove", + "upsert", + "add", + "set", + "save", + "patch", + "put", + "post", + "write", + "move", + "copy", + "duplicate", + "import", + "run", + "execute", + "trigger", + "send", + "reset", + "clear", + "archive", + "restore", +]); +/** Operation names that only wrap the operations a request body names. */ +const OPERATION_CONTAINERS = new Set(["batch", "bulk", "multi"]); +const OPERATION_PARAMETERS = ["operation", "op", "action"]; + +/** What deciding read-only calls reads besides the tools and the timeline. */ +export interface QueryCallIo { + readonly response: (ordinal: number) => JsonValue | undefined; + readonly request: (ordinal: number) => JsonValue | undefined; +} + +const succeeded = (record: StateRecordFacts): boolean => + record.status !== null && record.status >= 200 && record.status < 300; + +/** The operations an RPC call names: its body's `operation` or `operations[].operation`, else its query's, containers aside. */ +const operationsOf = ( + record: StateRecordFacts, + body: JsonValue | undefined, +): string[] => { + const named = isObject(body) + ? [ + body.operation, + ...(Array.isArray(body.operations) + ? body.operations.map((entry) => + isObject(entry) ? entry.operation : undefined, + ) + : []), + ].filter((name): name is string => typeof name === "string") + : []; + if (named.length > 0) return named; + const query = new URLSearchParams(record.query ?? ""); + return OPERATION_PARAMETERS.flatMap((name) => query.getAll(name)).filter( + (name) => !OPERATION_CONTAINERS.has(name.toLowerCase()), + ); +}; + +/** An operation that reads: it names a read word and no write word. */ +const readsOnly = (operation: string): boolean => { + const named = words(operation); + return ( + named.some((word) => READ_OPERATION_WORDS.has(word)) && + !named.some((word) => WRITE_OPERATION_WORDS.has(word)) + ); +}; + +/** + * POST tools whose recorded calls read state rather than change it, by the strongest evidence that + * applies: a response repeating the latest read of the same path with no write between, an RPC + * tunnel naming only read operations, a path word naming a lookup, or a session segment. A tool + * is kept a write when a read line its path relates to changes across one of its calls. + */ +export const readOnlyTools = ( + tools: readonly StateToolFacts[], + records: readonly StateRecordFacts[], + io: QueryCallIo, +): Set => { + const position = new Map( + records.map((record, index) => [record.ordinal, index]), + ); + const readOnly = new Set(); + for (const tool of tools) { + if ( + tool.method !== "POST" || + !changesState(tool.method, tool.path_template) + ) + continue; + const own = new Set(tool.record_ordinals); + const calls = tool.record_ordinals + .map((ordinal) => records[position.get(ordinal) ?? -1]) + .filter((record): record is StateRecordFacts => record !== undefined); + if (!calls.some(succeeded)) continue; + const between = (from: number, to: number): boolean => + records + .slice(from + 1, to) + .some((record) => !own.has(record.ordinal) && isStateWrite(record)); + const evidence = + repeatsRead(calls, records, { position, between, io }) || + namesReadOperations(calls, io) || + namesLookup(tool.path_template); + if ( + evidence && + !changesReadsAcross(calls, records, { position, between, io }) + ) + readOnly.add(tool.name); + } + return readOnly; +}; + +interface Timeline { + readonly position: ReadonlyMap; + readonly between: (from: number, to: number) => boolean; + readonly io: QueryCallIo; +} + +/** Every successful call answers as the latest earlier successful GET of its path did, with no write between. */ +const repeatsRead = ( + calls: readonly StateRecordFacts[], + records: readonly StateRecordFacts[], + { position, between, io }: Timeline, +): boolean => + calls.filter(succeeded).every((call) => { + const at = position.get(call.ordinal)!; + const read = records + .slice(0, at) + .findLast( + (record) => + record.method === "GET" && + record.path === call.path && + succeeded(record), + ); + if (read === undefined || between(position.get(read.ordinal)!, at)) + return false; + const answered = io.response(call.ordinal); + return answered !== undefined && same(answered, io.response(read.ordinal)); + }); + +/** Every call names only read operations. */ +const namesReadOperations = ( + calls: readonly StateRecordFacts[], + io: QueryCallIo, +): boolean => + calls.every((call) => { + const operations = operationsOf(call, io.request(call.ordinal)); + return operations.length > 0 && operations.every(readsOnly); + }); + +/** A path segment names a lookup by its last meaningful word, or is a session segment. */ +const namesLookup = (template: string): boolean => + segmentsOf(template).some( + (segment) => + !isParam(segment) && + (SESSION_SEGMENTS.has(segment.toLowerCase()) || + QUERY_WORDS.has(lastMeaningfulWord(segment) ?? "")), + ); + +/** A segment's last word that is not a trailing neutral word: `selection_data` names a selection, `query-history` a history. */ +const lastMeaningfulWord = (segment: string): string | undefined => + words(segment).findLast((word) => !NEUTRAL_WORDS.has(word)); + +/** A GET line whose path a call's path relates to reads differently just before and just after it, with no other write between. */ +const changesReadsAcross = ( + calls: readonly StateRecordFacts[], + records: readonly StateRecordFacts[], + { position, between, io }: Timeline, +): boolean => + calls.filter(succeeded).some((call) => { + const at = position.get(call.ordinal)!; + const lineOf = (record: StateRecordFacts): string => + `${record.path}${record.query ?? ""}`; + const related = records.filter( + (record) => + record.method === "GET" && + succeeded(record) && + prefixRelated(call.path, record.path), + ); + return [...new Set(related.map(lineOf))].some((line) => { + const before = related.findLast( + (record) => + lineOf(record) === line && position.get(record.ordinal)! < at, + ); + const after = related.find( + (record) => + lineOf(record) === line && position.get(record.ordinal)! > at, + ); + if (before === undefined || after === undefined) return false; + const from = position.get(before.ordinal)!; + const to = position.get(after.ordinal)!; + if (between(from, at) || between(at, to)) return false; + const earlier = io.response(before.ordinal); + const later = io.response(after.ordinal); + return ( + earlier !== undefined && later !== undefined && !same(earlier, later) + ); + }); + }); + +/** The timeline's state writes, less the calls of tools whose calls only read, and those tools. */ +export const stateWritesOf = ( + tools: readonly StateToolFacts[], + records: readonly StateRecordFacts[], + io: QueryCallIo, +): { + readonly readOnly: ReadonlySet; + readonly writes: readonly StateRecordFacts[]; +} => { + const readOnly = readOnlyTools(tools, records, io); + const reads = new Set( + tools + .filter((tool) => readOnly.has(tool.name)) + .flatMap((tool) => tool.record_ordinals), + ); + return { + readOnly, + writes: records.filter( + (record) => isStateWrite(record) && !reads.has(record.ordinal), + ), + }; +}; diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 1ece75e3e36..4b2ca22a8d6 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -177,7 +177,7 @@ export interface ExtractedState { const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]); /** A POST whose path names one of these segments queries state rather than changing it. */ -const QUERY_SEGMENTS = new Set([ +export const QUERY_SEGMENTS = new Set([ "search", "query", "list", diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 511e0344741..7aeabf1254a 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -4,7 +4,6 @@ import { collectionPathOf, isObject, isParam, - isStateWrite, normalizedPath, scalarText, segmentsOf, @@ -94,7 +93,7 @@ const createdObservation = ( ...target, ...(id === undefined ? {} : { id }), held, - isWrite: isStateWrite, + isWrite: context.isWrite, }); if (later !== undefined) context.observed(later.ordinal); return later; diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 8d9b3ca9427..19c3d36b61f 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -2,7 +2,6 @@ import type { JsonValue } from "../jsonValue.js"; import { ok } from "../result.js"; import { isObject, - isStateWrite, locateItem, at, same, @@ -89,6 +88,8 @@ export interface WriteIo { export interface WriteSimulationInput { readonly tools: readonly StateToolFacts[]; readonly records: readonly StateRecordFacts[]; + /** POST tools whose calls read state rather than change it. */ + readonly readOnly: ReadonlySet; readonly timed: boolean; readonly views: ReadonlyMap; readonly types: readonly StateType[]; @@ -104,6 +105,8 @@ export interface EffectContext { readonly io: WriteIo; readonly records: readonly StateRecordFacts[]; readonly timed: 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; readonly idField: (type: string) => string; /** Mark a later read as a create's or update's observation, so it does not check that write. */ @@ -255,7 +258,7 @@ const updatedObservation = ( idField: entity.idField, id: entity.id, held: () => true, - isWrite: isStateWrite, + isWrite: context.isWrite, sameItem: (record) => { const found = itemTarget(context.state, entity.type, record); return found.collection === entity.collection && found.id === entity.id; diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 0db51fbfab4..3da0f98eb01 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1259,3 +1259,38 @@ describe("what a list query read shows of writes", () => { }); }); }); + +describe("calls the capture shows reading only", () => { + const LOOKUP: TimedCaptureRow = [ + "POST", + "/api/books/ids", + [FIRST_BOOK, SECOND_BOOK], + 200, + { ids: [1, 2] }, + ]; + + it("replays a lookup POST and plans no write for it", () => { + const state = stateOf([...BOOK_INIT_ROWS, LOOKUP]); + expect(state.writes.map((plan) => plan.tool)).not.toContain( + "post_books_ids", + ); + expect(state.views).toContainEqual({ + tool: "post_books_ids", + shape: "recorded", + reason: "query-body", + }); + }); + + it("keeps a read after a lookup POST among the initial recordings", () => { + // The lookup changes nothing, so the second book's only read, after it, still seeds the state. + const state = stateOf([ + ["GET", "/api/books/1", FIRST_BOOK], + LOOKUP, + ["GET", "/api/books/2", SECOND_BOOK], + ]); + expect(state.entities.map((entity) => entity.id).sort()).toEqual([ + "1", + "2", + ]); + }); +}); From d5a1fa98e5b8a7e49ab419d56bbdc82487772073 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 11:10:48 -0700 Subject: [PATCH 02/68] fix(environment): take an entity an unplanned write made when a read first shows it A successful item read of an entity the gate's copy never held, after a write no built plan models, puts the entity into the copy instead of failing the read, so later writes to it are checked as usual. An entity a modelled write touched is never taken back. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-writes/spec.md | 12 +++ .../EnvironmentStateWriteSimulation.test.ts | 64 ++++++++++++ .../EnvironmentStateWriteSimulation.ts | 39 ++++++-- .../environmentStateWriteAdoption.ts | 98 +++++++++++++++++++ 4 files changed, 203 insertions(+), 10 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteAdoption.ts diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 6aa333c9015..0601a895c36 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -256,6 +256,18 @@ unknown. Writes that changed it since its last check are checked only on the members they sent, less those the view treats as volatile, which show nothing of a write. +A write no built plan models can also make an entity the copy never held, such +as a row an import or a nested create added: a write of a tool with no create, +update, delete or document plan, or a call of a tool whose plan was never built. +A successful item read of an entity the copy has never held (no initial entity, +and none a modelled write created, changed or removed) that names it by the +type's identity, when such a write ran since that entity or its collection was +last checked, shows that entity: the copy takes its recorded values instead of +failing the read, and later writes to it are modelled and checked as usual. An +entity a modelled write touched is never taken back this way, and a built plan's +call that serving would not apply, such as a create outside its tied +collection, keeps its evidence. + **Reads.** A read is checked when the served environment would answer it from the state: diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index 362b96a3670..516507befad 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -2207,6 +2207,70 @@ describe("volatile fields", () => { }); }); +describe("entities an unmodelled write made", () => { + const IMPORT: TimedCaptureRow = [ + "POST", + "/api/imports", + { queued: true }, + 202, + { source: "csv" }, + ]; + const RENAME: TimedCaptureRow = [ + "PATCH", + "/api/books/1", + renamedBook(FIRST_BOOK, "Renamed Book", 3), + 200, + { name: "Renamed Book" }, + ]; + const deletedAfterRead = (before: readonly TimedCaptureRow[]) => [ + ...BOOK_INIT_ROWS, + ...before, + ["GET", "/api/books/3", THIRD_BOOK] as TimedCaptureRow, + ["DELETE", "/api/books/3", "", 204] as TimedCaptureRow, + ["GET", "/api/books/3", BOOK_NOT_FOUND, 404] as TimedCaptureRow, + ]; + + it("serves a delete of a book an unmodelled import made, which a later item read showed", () => { + // The rename ends the initial reads, so the third book is no initial one. + expect( + gated(deletedAfterRead([RENAME, IMPORT]), "delete_books_by_id"), + ).toMatchObject({ served: true, checked_record_ordinals: [7] }); + }); + + it("takes a book the state never held only when a write the gate does not model came first", () => { + expect( + gated(deletedAfterRead([RENAME, IMPORT]), "delete_books_by_id"), + ).toMatchObject({ served: true, checked_record_ordinals: [7] }); + // Only a modelled rename came first, so nothing explains the third book and the delete finds none. + expect( + gated(deletedAfterRead([RENAME]), "delete_books_by_id"), + ).toMatchObject({ + served: false, + checked_record_ordinals: [], + }); + }); + + it("takes back no book a modelled delete removed, so a list showing it again confirms no delete", () => { + expect( + gated(deletedAfterRead([RENAME, IMPORT]), "delete_books_by_id"), + ).toMatchObject({ served: true }); + const rows: TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + ["POST", "/api/books", THIRD_BOOK, 201, { name: "Third Book" }], + ["GET", "/api/books/3", THIRD_BOOK], + ["DELETE", "/api/books/3", "", 204], + IMPORT, + // The import put the deleted book back; the copy must not take it as one the import made. + ["GET", "/api/books/3", THIRD_BOOK], + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK, THIRD_BOOK]], + ]; + expect(gated(rows, "delete_books_by_id")).toMatchObject({ + served: false, + checked_record_ordinals: [], + }); + }); +}); + describe("an unmodelled write under another collection spelling", () => { it("keeps a confirmed update when the write spells the held collection plainly", () => { const acme = (name: string, status: string) => ({ diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 3afa7a794e0..5c1cd6eca68 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -12,6 +12,7 @@ import { type StateType, type StateView, } from "./environmentStateRules.js"; +import { UnseenEntities } from "./environmentStateWriteAdoption.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; import { OmittedFields } from "./environmentStateWriteOmitted.js"; @@ -54,6 +55,7 @@ import { applyDocument } from "./environmentStateWriteDocument.js"; import { applyDelete, applyUpdate, + built, type EffectContext, type EffectResult, type WriteDraft, @@ -116,10 +118,18 @@ export class EnvironmentStateWriteSimulation { readonly #inserted = new Map(); /** Creates whose insert rule a passing list check relied on, so it is no longer changed. */ readonly #placed = new Set(); + /** Entities writes no plan models made, taken when an item read first shows them. */ + readonly #unseen: UnseenEntities; constructor(input: WriteSimulationInput) { this.#input = input; this.#state = new SimulatedState(input.entities, input.documents); + this.#unseen = new UnseenEntities(input.entities, { + state: this.#state, + io: input.io, + lastCheck: this.#lastCheck, + idField: (type) => this.#types.get(type)?.id_field, + }); for (const type of input.types) this.#types.set(type.collection_template, type); for (const tool of input.tools) @@ -230,12 +240,17 @@ export class EnvironmentStateWriteSimulation { effect === "none" ) { this.#unmodelled(record.path, index); + this.#unseen.unplanned(index); return; } const observeOnly = draft.plan.reason !== null; if (!observeOnly) draft.calls += 1; const step: WriteStep = { record, index, tool, observeOnly }; - this.#settle(APPLY[effect](this.#context(tool.name), draft, step), { + const result = APPLY[effect](this.#context(tool.name), draft, step); + // A call of a tool whose plan was never built is no more modelled than one of a tool without a plan. + if (result.kind === "unknown" && !built(draft)) + this.#unseen.unplanned(index); + this.#settle(result, { index, tool: tool.name, path: record.path, @@ -257,12 +272,11 @@ export class EnvironmentStateWriteSimulation { this.#unmodelled(write.path, write.index); return; } - if (result.entity !== undefined) - this.#taint.known( - result.entity.type, - result.entity.collection, - result.entity.id, - ); + if (result.entity !== undefined) { + this.#unseen.touched(result.entity); + const { type, collection, id } = result.entity; + this.#taint.known(type, collection, id); + } if (result.kind === "observed") { this.#effects.observed(this.#touched, result.targets); // A recorded outcome replaces the entity's values, not its collection's membership. @@ -302,9 +316,14 @@ export class EnvironmentStateWriteSimulation { this.#state.put(updatedEntity(entity, { ...entity.fields, ...object })); } - /** Whether an item read is of an entity left unknown that it shows again rather than checks. */ - #resynced(view: StateView, record: StateRecordFacts): boolean { + /** 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; + const adopted = this.#unseen.adopt(view, { record, index }); + if (adopted !== undefined) { + this.#taint.known(adopted.type, adopted.collection, adopted.id); + return true; + } const { collection, id } = itemTarget(this.#state, view.type, record); if (!this.#taint.unknown(view.type, collection, id)) return false; // A read begun while a modelled write to the entity still ran may show either state, so it neither checks nor shows it. @@ -383,7 +402,7 @@ export class EnvironmentStateWriteSimulation { const view = this.omitted.view(original); if (projectedRead(view, record, this.#input.io)) return; const borrowers = this.#observations.get(record.ordinal); - if (!borrowers && this.#resynced(view, record)) return; + if (!borrowers && this.#resynced(view, record, index)) return; let outcome = this.#check(view, record); if (outcome === undefined) return; let keys = [...outcome.targets, ...outcome.unheld]; diff --git a/src/domain/analysisView/environmentStateWriteAdoption.ts b/src/domain/analysisView/environmentStateWriteAdoption.ts new file mode 100644 index 00000000000..89bd83d8e74 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteAdoption.ts @@ -0,0 +1,98 @@ +import { + at, + isObject, + scalarText, + type StateEntity, + type StateRecordFacts, + type StateView, +} from "./environmentStateRules.js"; +import { + collectionTarget, + entityTarget, + itemTarget, + succeeded, + type SimulatedState, +} from "./environmentStateWriteChecks.js"; +import type { WriteIo } from "./environmentStateWriteEffects.js"; + +/** + * Entities a write no built plan models made, such as rows an import or a nested create added: the + * copy takes one when a successful item read first shows it, rather than failing the read. A call + * of a built plan that serving would not apply keeps its evidence. + */ +export class UnseenEntities { + /** Targets of the entities the copy has held: the initial ones and any a modelled write or an adoption touched. */ + readonly #held: Set; + /** Timeline indexes of successful writes no built plan models. */ + readonly #unplannedAt: number[] = []; + + constructor( + initial: readonly StateEntity[], + private readonly facts: { + readonly state: SimulatedState; + readonly io: Pick; + readonly lastCheck: ReadonlyMap; + readonly idField: (type: string) => string | undefined; + }, + ) { + this.#held = new Set( + initial.map((entity) => + entityTarget(entity.type, entity.collection, entity.id), + ), + ); + } + + /** Note an entity a modelled write created, changed or removed, which no read takes back. */ + touched(entity: Pick): void { + this.#held.add(entityTarget(entity.type, entity.collection, entity.id)); + } + + /** Note a successful write no built plan models. */ + unplanned(index: number): void { + this.#unplannedAt.push(index); + } + + /** + * Put into the copy the entity a successful item read shows that the copy never held, when an + * unplanned write ran since the entity or its collection was last checked; the entity taken, if any. + */ + adopt( + view: Extract, + read: { readonly record: StateRecordFacts; readonly index: number }, + ): StateEntity | undefined { + const { record, index } = read; + const { state, lastCheck } = this.facts; + if (!succeeded(record)) return undefined; + const { collection, id } = itemTarget(state, view.type, record); + const key = entityTarget(view.type, collection, id); + if (this.#held.has(key) || state.entity(view.type, collection, id)) + return undefined; + const since = Math.max( + lastCheck.get(key) ?? -1, + lastCheck.get(collectionTarget(view.type, collection)) ?? -1, + ); + if (!this.#unplannedAt.some((write) => write > since && write < index)) + return undefined; + const object = this.facts.io.withBody(record.ordinal, (body) => + body === undefined || body === null ? undefined : at(body, view.pointer), + ); + const idField = this.facts.idField(view.type); + if ( + !isObject(object) || + idField === undefined || + scalarText(object[idField]) !== id + ) + return undefined; + const entity = { + type: view.type, + collection, + id, + fields: object, + view_fields: [], + record_ordinals: [], + }; + state.put(entity); + this.#held.add(key); + return entity; + } +} From 004b064b85465e40944df7ac0cf65a07f44dc6d1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 11:24:00 -0700 Subject: [PATCH 03/68] fix(environment): plan a create into the type its returned id is read under A POST whose path names no state type becomes a create into the type whose item read first names an id its response returned, when the id is new to the state; serving creates in that read's collection. A successful POST that returned an id a type's reads only show after it also ends that type's initial window, so entities a capture created stay out of the initial state. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-view/spec.md | 5 +- .../agent-environments/state-writes/spec.md | 9 + .../environmentStateWriteAnswer.test.ts | 26 ++ .../environmentStateWriteAnswer.ts | 10 +- .../EnvironmentStateExtraction.ts | 49 ++-- .../EnvironmentStateWriteSimulation.ts | 9 +- .../environmentStateWriteCreate.ts | 6 +- .../environmentStateWriteEffects.ts | 2 + .../environmentStateWriteLinks.ts | 252 ++++++++++++++++++ .../environmentStateWrites.test.ts | 79 ++++++ 10 files changed, 422 insertions(+), 25 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteLinks.ts diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index d0d1874d6b5..7175a9655eb 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -25,7 +25,10 @@ later increments. any start time is missing, and say which. Bound each type's state by the first write under its root (API base, version segments, one segment); a query `POST` is not a write, a read overlapping the write is left out, and a write - whose URL was redacted bounds every type, with a limitation counting it. + whose URL was redacted bounds every type, with a limitation counting it. A + successful `POST` elsewhere bounds a type's state too when its response named + an id (four characters or more) that the type's reads show only after it: the + `POST` made that entity, so it is not in the initial state. - Prove an item type's identity field from the requested path value its responses repeat; otherwise infer it from a fixed list of identity names that every listed item carries distinctly, which needs at least one listed item. diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 0601a895c36..d13c0a56aa7 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -72,6 +72,15 @@ endpoint under the same root regenerates values on every read. | `document` | `PUT`, `PATCH` or `POST` to a document view's path | that document | | `none` | anything else | reason `no-state-target` | +A `POST` whose path gives it no target is a `create` into the type its returned +id is read under: its exemplar's response names an id (a scalar, an identity +member, a sole member, or an identity member of an object member, four +characters or more), and the first later successful item read naming that id +belongs to a state type. The entity must be new: neither the initial state nor +any earlier read holds that id. The plan records that read's collection, and +serving creates there, since the call's own path names no collection of the +type. + **Exemplar.** A plan is built from its first successful (2xx) recorded call, the exemplar. diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index a9c2349a4f2..f3056f4964c 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1564,3 +1564,29 @@ describe("served catalog of calls that only read", () => { expect(state.writes.has("post_books_ids")).toBe(false); }); }); + +describe("creates read under another path", () => { + it("creates into the collection a linked create's returned id was read under", () => { + const note = (id: number, title: string) => ({ id, title }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const notes = servedFrom([ + ["GET", "/api/notes", [alpha, beta]], + ["GET", "/api/notes/1001", alpha], + ["GET", "/api/notes/1002", beta], + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", gamma], + ["GET", "/api/notes", [alpha, beta, gamma]], + ]); + expect( + notes.answer("post_drafts_publish", { body: { title: "Delta" } }), + ).toMatchObject({ status: 201 }); + // The capture's own create is not in the initial state, so the served one takes the next id. + const delta = note(1003, "Delta"); + expect(notes.answer("get_notes_by_id", { id: "1003" }).body).toEqual(delta); + expect(notes.answer("get_notes").body).toEqual([alpha, beta, delta]); + }); +}); diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index ccfdf104a96..fceed4cab8a 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -14,6 +14,7 @@ import { nextInteger, } from "../../domain/analysisView/environmentStateWriteExplain.js"; import { callRenewal } from "../../domain/analysisView/environmentStateWriteGenerated.js"; +import { linkedCollection } from "../../domain/analysisView/environmentStateWriteLinks.js"; import { pathValuesOf, type GeneratedRule, @@ -283,12 +284,9 @@ const answerCreate = ( const { tool, plan } = request; const type = plan.target ?? ""; const idField = serving.store.type(type)?.id_field ?? ""; - const collection = createdCollection( - serving, - request.tool, - request.args, - plan.target ?? "", - ); + const collection = + linkedCollection(plan, tool.path_template) ?? + createdCollection(serving, request.tool, request.args, plan.target ?? ""); const observed = observedEntity(serving, plan); if (collection === undefined || observed === undefined) return err( diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 7c224502dc9..637261184a9 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -12,7 +12,6 @@ import { IDENTITY_NAMES, identityCandidates, isObject, - isParam, isQueryPost, jsonBytes, lastSegmentValue, @@ -20,12 +19,10 @@ import { listItems, locateItem, locateList, - normalizedPath, projectsFields, rootOf, same, scalarText, - segmentsOf, writeSpanCheck, type ExtractedState, type JsonObject, @@ -54,6 +51,13 @@ import { type StatePlan, } from "./environmentStateGate.js"; import { StateWriteCutoffs } from "./environmentStateWriteCutoffs.js"; +import { + createdIdsOf, + creationLimit, + readType, + respondedIds, + type CreatedIds, +} from "./environmentStateWriteLinks.js"; import { extractWrites } from "./environmentStateWrites.js"; import { stateWritesOf } from "./environmentStateQueryCalls.js"; @@ -88,6 +92,8 @@ export class EnvironmentStateExtraction { readonly #bases: ReadonlyMap; #writeCutoffs: StateWriteCutoffs | undefined; readonly #initLimits = new Map(); + /** Successful POSTs with the ids their responses named, read once on first use. */ + #created: CreatedIds[] | undefined; readonly #identity = new Map< string, { readonly field: string; readonly basis: StateType["id_basis"] } @@ -228,27 +234,40 @@ export class EnvironmentStateExtraction { ) this.#recorded(tool, "query-body"); if (tool.method !== "GET") continue; - const segments = segmentsOf(tool.path_template); - const item = segments.length > 0 && isParam(segments.at(-1)!); - candidates.push({ - tool, - item, - type: item - ? `/${segments.slice(0, -1).join("/")}` - : normalizedPath(tool.path_template), - }); + candidates.push({ tool, ...readType(tool.path_template) }); } return candidates; } - /** The first write whose root relates to the template's bounds its init recordings. */ + /** The first write whose root relates to the template's, or that made one of its entities, bounds its init recordings. */ #initLimit(template: string): StateRecordFacts | undefined { if (this.#writeCutoffs === undefined) return undefined; if (this.#initLimits.has(template)) return this.#initLimits.get(template); const first = this.#writeCutoffs.first(rootOf(template, this.#bases)); + const limit = + creationLimit( + this.#creations(), + { + type: template, + tools: this.#tools, + records: this.#byOrdinal, + position: (record) => this.#position.get(record.ordinal)!, + body: (ordinal) => this.#withBody(ordinal, (body) => body), + }, + first, + ) ?? first; this.#retain(ENTRY_BYTES + textBytes(template.length)); - this.#initLimits.set(template, first); - return first; + this.#initLimits.set(template, limit); + return limit; + } + + #creations(): CreatedIds[] { + this.#created ??= createdIdsOf(this.#writes, (ordinal) => { + const ids = this.#withBody(ordinal, respondedIds); + this.#retain(ENTRY_BYTES + textBytes(ids.join("").length)); + return ids; + }); + return this.#created; } /** Initial-state admission is shared with later projection-evidence selection. */ diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 5c1cd6eca68..4ac63b0e7ad 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -13,6 +13,7 @@ import { type StateView, } from "./environmentStateRules.js"; import { UnseenEntities } from "./environmentStateWriteAdoption.js"; +import { linkedTarget } from "./environmentStateWriteLinks.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; import { OmittedFields } from "./environmentStateWriteOmitted.js"; @@ -158,7 +159,12 @@ export class EnvironmentStateWriteSimulation { this.#input.readOnly.has(tool.name) ) continue; - const { effect, target } = classifyWrite(tool, types, documents); + const link = linkedTarget(tool, classifyWrite(tool, types, documents), { + ...this.#input, + viewOf: (ordinal) => + this.#input.views.get(this.#toolOf.get(ordinal)?.name ?? ""), + }); + const { effect, target } = link; this.#input.io.retain(512); this.#drafts.set(tool.name, { plan: { @@ -173,6 +179,7 @@ export class EnvironmentStateWriteSimulation { calls: 0, updates: [], sequences: new Map(), + linked: link.collection, }); } this.#input.records.forEach((record, index) => this.#step(record, index)); diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 7aeabf1254a..6fa0df4dfb6 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -153,7 +153,8 @@ const buildCreate = ( ), body: explained.body, rules: explained.rules, - collection: explained.tied ? evidence.collection : null, + collection: + explained.tied || draft.linked !== undefined ? evidence.collection : null, insert: draft.candidates[0]!, }); draft.observed = evidence.observed.object; @@ -329,7 +330,8 @@ export const applyCreate = ( const idField = context.idField(type); const spelled = normalizedPath(step.record.path); // Serving writes a create into the collection it chooses for the path, and a tied plan refuses any other, so a create there is not counted. - const collection = servedCollection(context, step, type) ?? spelled; + const collection = + draft.linked ?? servedCollection(context, step, type) ?? spelled; if ( built(draft) && draft.plan.collection !== null && diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 19c3d36b61f..d75ca51775f 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -66,6 +66,8 @@ export interface WriteDraft { readonly updates: UpdateCall[]; /** The last value each sequence took, by field and, for a collection's sequence, collection; the next call must follow it. */ readonly sequences: Map; + /** The collection a create writes into when its own path names no state type: the one its returned id was read under. */ + readonly linked?: string | undefined; } /** A write observation plus the fields its selected read view actually covers, if any. */ diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts new file mode 100644 index 00000000000..0e5cf6d00df --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -0,0 +1,252 @@ +import type { JsonValue } from "../jsonValue.js"; +import { + collectionPathOf, + IDENTITY_NAMES, + isObject, + isParam, + lastSegmentValue, + normalizedPath, + scalarText, + segmentsOf, + type StateEntity, + type StateRecordFacts, + type StateToolFacts, + type StateView, +} from "./environmentStateRules.js"; +import type { WriteEffect } from "./environmentStateWriteRules.js"; + +/** The shortest id that names one entity rather than counting one. */ +const MIN_ID_LENGTH = 4; + +const succeeded = (record: StateRecordFacts): boolean => + record.status !== null && record.status >= 200 && record.status < 300; + +/** An object's identity-named scalar members. */ +const identityValues = (object: JsonValue | undefined): string[] => + isObject(object) + ? IDENTITY_NAMES.flatMap((name) => { + const value = scalarText(object[name]); + return value === undefined ? [] : [value]; + }) + : []; + +/** + * The ids a write's response names for an entity it made, long enough to name one: a scalar body, + * an identity-named or sole scalar member, or an identity-named member of an object member (an envelope). + */ +export const respondedIds = (body: JsonValue | undefined): string[] => { + if (body === undefined || body === null) return []; + const ids: string[] = []; + if (!isObject(body)) { + const value = scalarText(body); + if (value !== undefined) ids.push(value); + } else { + ids.push(...identityValues(body)); + const members = Object.values(body); + const sole = members.length === 1 ? scalarText(members[0]) : undefined; + if (sole !== undefined) ids.push(sole); + for (const member of members) ids.push(...identityValues(member)); + } + return [...new Set(ids)].filter((id) => id.length >= MIN_ID_LENGTH); +}; + +/** The identity-named scalar values a read's body shows at any depth, or its path's id for an item read. */ +const shownIds = ( + record: StateRecordFacts, + item: boolean, + body: () => JsonValue | undefined, +): Set => { + if (item) return new Set([lastSegmentValue(record.path)]); + const shown = new Set(); + const pending: JsonValue[] = []; + const root = body(); + if (root !== undefined) pending.push(root); + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + if (Array.isArray(next)) pending.push(...next); + else if (isObject(next)) { + for (const id of identityValues(next)) shown.add(id); + pending.push(...Object.values(next)); + } + } + return shown; +}; + +/** A successful POST and the ids its response named. */ +export interface CreatedIds { + readonly record: StateRecordFacts; + readonly ids: readonly string[]; +} + +/** The successful POSTs among a timeline's writes, with the ids their responses named. */ +export const createdIdsOf = ( + writes: readonly StateRecordFacts[], + idsOf: (ordinal: number) => string[], +): CreatedIds[] => + writes.flatMap((record) => { + if (record.method !== "POST" || !succeeded(record)) return []; + const ids = idsOf(record.ordinal); + return ids.length === 0 ? [] : [{ record, ids }]; + }); + +/** The state type a GET tool reads and whether it reads one item: its path less a trailing parameter. */ +export const readType = ( + template: string, +): { readonly item: boolean; readonly type: string } => { + const segments = segmentsOf(template); + const item = segments.length > 0 && isParam(segments.at(-1)!); + return { + item, + type: item + ? `/${segments.slice(0, -1).join("/")}` + : normalizedPath(template), + }; +}; + +/** + * The earliest POST that made an entity a type's reads first show after it, before `until`: such a + * POST changes the type although its path is elsewhere, so it bounds the type's initial recordings. + */ +export const creationLimit = ( + creations: readonly CreatedIds[], + reads: { + readonly type: string; + readonly tools: readonly StateToolFacts[]; + readonly records: ReadonlyMap; + readonly position: (record: StateRecordFacts) => number; + readonly body: (ordinal: number) => JsonValue | undefined; + }, + until: StateRecordFacts | undefined, +): StateRecordFacts | undefined => { + if (creations.length === 0) return undefined; + const end = until === undefined ? Infinity : reads.position(until); + const readers = reads.tools.flatMap((tool) => { + const read = readType(tool.path_template); + return tool.method === "GET" && read.type === reads.type + ? [{ tool, item: read.item }] + : []; + }); + const shown = readers.flatMap(({ tool, item }) => + tool.record_ordinals.flatMap((ordinal) => { + const record = reads.records.get(ordinal); + return record === undefined || !succeeded(record) + ? [] + : [ + { + at: reads.position(record), + ids: shownIds(record, item, () => reads.body(ordinal)), + }, + ]; + }), + ); + for (const creation of [...creations].sort( + (left, right) => reads.position(left.record) - reads.position(right.record), + )) { + const at = reads.position(creation.record); + if (at >= end) break; + const fresh = creation.ids.filter( + (id) => + !shown.some((read) => read.at < at && read.ids.has(id)) && + shown.some((read) => read.at > at && read.at < end && read.ids.has(id)), + ); + if (fresh.length > 0) return creation.record; + } + return undefined; +}; + +/** + * The state type and collection a POST whose path names none creates into: that of the first later + * successful item read naming an id its first successful call returned, when neither the initial + * state nor any earlier read held that id. + */ +export const linkedCreate = (input: { + readonly tool: StateToolFacts; + readonly records: readonly StateRecordFacts[]; + readonly viewOf: (ordinal: number) => StateView | undefined; + readonly entities: readonly StateEntity[]; + readonly respondedIds: (ordinal: number) => readonly string[]; +}): { readonly type: string; readonly collection: string } | undefined => { + const { tool, records } = input; + const own = new Set(tool.record_ordinals); + const first = records.findIndex( + (record) => own.has(record.ordinal) && succeeded(record), + ); + if (first === -1) return undefined; + const ids = new Set(input.respondedIds(records[first]!.ordinal)); + if (ids.size === 0) return undefined; + for (const record of records.slice(0, first)) + if ( + record.method === "GET" && + succeeded(record) && + ids.has(lastSegmentValue(record.path)) + ) + return undefined; + for (const record of records.slice(first + 1)) { + const view = input.viewOf(record.ordinal); + if ( + record.method !== "GET" || + !succeeded(record) || + view?.shape !== "item" || + !ids.has(lastSegmentValue(record.path)) + ) + continue; + const id = lastSegmentValue(record.path); + const held = input.entities.some( + (entity) => entity.type === view.type && entity.id === id, + ); + return held + ? undefined + : { type: view.type, collection: collectionPathOf(record, true) }; + } + return undefined; +}; + +/** The collection a create plan writes into when its tool's own path names no state type: the one its returned id was read under. */ +export const linkedCollection = ( + plan: { + readonly effect: string; + readonly target: string | null; + readonly collection: string | null; + }, + template: string, +): string | undefined => + plan.effect === "create" && + plan.target !== null && + plan.collection !== null && + plan.target !== normalizedPath(template) + ? plan.collection + : undefined; + +/** A write's effect and target, where a POST its path gives no target becomes a create into the type its returned id is first read under. */ +export const linkedTarget = ( + tool: StateToolFacts, + classified: { readonly effect: WriteEffect; readonly target: string | null }, + input: { + readonly records: readonly StateRecordFacts[]; + readonly viewOf: (ordinal: number) => StateView | undefined; + readonly entities: readonly StateEntity[]; + readonly io: { + readonly withBody: ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ) => T; + }; + }, +): { + readonly effect: WriteEffect; + readonly target: string | null; + readonly collection?: string; +} => { + const link = + classified.effect === "none" && tool.method === "POST" + ? linkedCreate({ + tool, + records: input.records, + viewOf: input.viewOf, + entities: input.entities, + respondedIds: (ordinal) => input.io.withBody(ordinal, respondedIds), + }) + : undefined; + return link === undefined + ? classified + : { effect: "create", target: link.type, collection: link.collection }; +}; diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 3da0f98eb01..17c946c6d90 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1294,3 +1294,82 @@ describe("calls the capture shows reading only", () => { ]); }); }); + +describe("creates read under another path", () => { + const note = (id: number, title: string) => ({ id, title }); + const A = note(1001, "Alpha"); + const B = note(1002, "Beta"); + const C = note(1003, "Gamma"); + const notesOf = (state: StateView) => + state.entities + .filter((entity) => entity.type === "/api/notes") + .map((entity) => entity.id); + const published = (before: readonly TimedCaptureRow[]): TimedCaptureRow[] => [ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + ...before, + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], + ]; + + it("plans a POST to another path as a create into the type its returned id is first read under", () => { + const state = stateOf(published([])); + expect(planOf(state, "post_drafts_publish")).toMatchObject({ + effect: "create", + target: "/api/notes", + collection: "/api/notes", + }); + expect(notesOf(state)).toEqual(["1001", "1002"]); + }); + + it("ends a type's initial reads at a POST elsewhere that made one of its entities", () => { + const state = stateOf([ + ["GET", "/api/notes", [A, B]], + ["POST", "/api/imports", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes", [A, B, C]], + ]); + expect(notesOf(state)).toEqual(["1001", "1002"]); + expect( + state.types.find((type) => type.collection_template === "/api/notes"), + ).toMatchObject({ init_before_ordinal: 1 }); + }); + + it("links no create whose returned id a read showed before it", () => { + const shownBefore = published([ + [ + "PATCH", + "/api/notes/1001", + note(1001, "Alpha 2"), + 200, + { title: "Alpha 2" }, + ], + ["GET", "/api/notes/1003", C], + ]); + expect(planOf(stateOf(shownBefore), "post_drafts_publish")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + expect(planOf(stateOf(published([])), "post_drafts_publish")).toMatchObject( + { effect: "create" }, + ); + }); + + it("links no create whose returned id the initial state holds", () => { + const held = stateOf([ + ["GET", "/api/notes", [A, B, C]], + ["GET", "/api/notes/1001", A], + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", C], + ]); + expect(planOf(held, "post_drafts_publish")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + expect(notesOf(held)).toEqual(["1001", "1002", "1003"]); + expect(planOf(stateOf(published([])), "post_drafts_publish")).toMatchObject( + { effect: "create" }, + ); + }); +}); From d8f9c05264dd8267d12a4462e3b632ed89fef5d2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 11:41:41 -0700 Subject: [PATCH 04/68] fix(environment): end a type's initial reads at the write its reads disagree across When a type's reads disagree across a write under another root, the type's initial window now ends at the earliest write within that change and the state is extracted again, instead of leaving every view of the type replayed. The cut composes with the creation cut; the earlier wins. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-view/spec.md | 5 +- docs/web-network-captures.md | 11 ++- .../EnvironmentStateExtraction.ts | 68 +++++++++++++++--- .../analysisView/environmentStateMerge.ts | 24 +++++-- .../analysisView/environmentStateRewrites.ts | 31 ++++++++ .../analysisView/environmentStateView.test.ts | 72 +++++++++---------- .../environmentStateWrites.test.ts | 53 ++++++++++++++ 7 files changed, 208 insertions(+), 56 deletions(-) create mode 100644 src/domain/analysisView/environmentStateRewrites.ts diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 7175a9655eb..144f84d64b2 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -48,8 +48,9 @@ later increments. latest values win over list views', differing views keep their own values, and a value that changed between repeats of one request line with no recorded write is volatile and keeps the latest; a change across a write under another - root, including between two tools of the type, leaves every tool of the type - recorded. Compare list membership, including empty lists, and field presence before selecting each request line's latest recording; a change across a write also leaves the type recorded. Different query strings remain distinct; omitted fields do not erase their earlier observations on other request lines. + root, including between two tools of the type, ends the type's initial reads + at the earliest write within the change, and the state is extracted again + once; a type whose reads still disagree keeps every tool recorded. Compare list membership, including empty lists, and field presence before selecting each request line's latest recording; a change across a write ends the type's initial reads the same way. Different query strings remain distinct; omitted fields do not erase their earlier observations on other request lines. - An item or list view whose recordings always spell a clock field's instant otherwise than the entity's stored value (`Z` against `+00:00`, another separator or fraction width) names that spelling in `clock_formats`; a field diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index d85772c030b..c9999e4af25 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -592,9 +592,14 @@ collection path: an item view's latest values win over a list view's, a view whose latest values differ keeps them in `view_fields`, and a field whose value changed between one tool's observations with no recorded write between is named in the type's `volatile_fields`, keeping the latest value. A value that changed -across a write under another root may be that write's effect, so every tool of -its type is a recorded view with reason `fields-differ`; so is a value one tool -read before a write and another tool read after it. Repeated reads of one full request line also keep the type recorded when list membership changes across a write, including transitions to or from an empty list, or when entity fields are added or removed. Different query strings remain distinct request lines. Sparse responses do not erase the last observation of a field supplied by another request line. Entities are ordered +across a write under another root may be that write's effect, so the type's +initial reads end at the earliest write within the change, reads that overlap +it are left out, and the state is extracted again once; the same holds for a +value one tool read before a write and another tool read after it, and for +repeated reads of one full request line whose list membership changes across a +write, including transitions to or from an empty list, or whose entity fields +are added or removed. A type whose reads still disagree keeps every tool a +recorded view with reason `fields-differ`. Different query strings remain distinct request lines. Sparse responses do not erase the last observation of a field supplied by another request line. Entities are ordered by type, collection and first sighting; that order is a list's state order. Every entity cites its `record_ordinals`. diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 637261184a9..b34a6884a18 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -44,6 +44,7 @@ import { type ObservedEntity, type StateObservation, } from "./environmentStateMerge.js"; +import { rewriteCuts, type RewriteSpan } from "./environmentStateRewrites.js"; import { checkItemPlan, checkListPlan, @@ -104,6 +105,9 @@ export class EnvironmentStateExtraction { readonly #volatile = new Map>(); /** Types with a value that changed across a recorded write, which may be that write's effect. */ readonly #rewritten = new Set(); + /** The recordings either side of each such change, and per type the write its initial reads end at. */ + #spans: RewriteSpan[] = []; + #cuts: ReadonlyMap = new Map(); readonly #merged = new Map(); /** Merged entities by type and collection, built once on first use after merging. */ #collections: Map | undefined; @@ -153,14 +157,8 @@ export class EnvironmentStateExtraction { this.#position.get(right.ordinal)!, (bytes) => this.#retain(bytes), ); - const candidates = this.#candidates(); - for (const candidate of candidates.filter((entry) => entry.item)) - this.#planItem(candidate); - for (const candidate of candidates.filter((entry) => !entry.item)) - this.#planList(candidate); - for (const plan of this.#plans) this.#observePlan(plan); - this.#classifyChanges(); - this.#merge(); + let candidates = this.#plan(); + if (this.#cutRewrites()) candidates = this.#plan(); const gate = this.#gateContext(); for (const plan of this.#plans) if (this.#rewritten.has(plan.type)) @@ -177,6 +175,38 @@ export class EnvironmentStateExtraction { } } + /** Plan and observe every candidate, then merge the observed entities. */ + #plan(): Candidate[] { + const candidates = this.#candidates(); + for (const candidate of candidates.filter((entry) => entry.item)) + this.#planItem(candidate); + for (const candidate of candidates.filter((entry) => !entry.item)) + this.#planList(candidate); + for (const plan of this.#plans) this.#observePlan(plan); + this.#classifyChanges(); + this.#merge(); + return candidates; + } + + /** End each rewritten type's initial reads at the earliest write its reads disagree across, and clear the plans to make them again. */ + #cutRewrites(): boolean { + this.#cuts = rewriteCuts( + this.#spans.filter((span) => this.#rewritten.has(span.type)), + this.#writes, + this.#byOrdinal, + ); + if (this.#cuts.size === 0) return false; + for (const map of [this.#initLimits, this.#identity, this.#views]) + map.clear(); + for (const map of [this.#entities, this.#volatile, this.#merged]) + map.clear(); + this.#rewritten.clear(); + this.#plans.length = 0; + this.#spans = []; + this.#collections = undefined; + return true; + } + /** The write plans the capture's own timeline confirms against the extracted state. */ #withWrites( state: Omit, @@ -244,7 +274,7 @@ export class EnvironmentStateExtraction { if (this.#writeCutoffs === undefined) return undefined; if (this.#initLimits.has(template)) return this.#initLimits.get(template); const first = this.#writeCutoffs.first(rootOf(template, this.#bases)); - const limit = + const bound = creationLimit( this.#creations(), { @@ -256,6 +286,13 @@ export class EnvironmentStateExtraction { }, first, ) ?? first; + const cut = this.#cuts.get(template); + const limit = + cut !== undefined && + (bound === undefined || + this.#position.get(cut.ordinal)! < this.#position.get(bound.ordinal)!) + ? cut + : bound; this.#retain(ENTRY_BYTES + textBytes(template.length)); this.#initLimits.set(template, limit); return limit; @@ -538,8 +575,18 @@ export class EnvironmentStateExtraction { for (const object of objects) if (!previous.ids.delete(scalarText(object[field])!)) changed = true; if (previous.ids.size > 0) changed = true; - if (earlier !== undefined && changed && this.#writeWithin(earlier, record)) + if ( + earlier !== undefined && + changed && + this.#writeWithin(earlier, record) + ) { this.#rewritten.add(plan.type); + this.#spans.push({ + type: plan.type, + earlier: earlier.ordinal, + later: record.ordinal, + }); + } previous.ids.clear(); for (const object of objects) previous.ids.add(scalarText(object[field])!); previous.record = record; @@ -595,6 +642,7 @@ export class EnvironmentStateExtraction { (earlier, later) => this.#writeWithin(recordOf(earlier), recordOf(later)), ); for (const type of changes.rewritten) this.#rewritten.add(type); + this.#spans.push(...changes.spans); for (const [type, names] of changes.volatile) this.#volatile.set(type, names); } diff --git a/src/domain/analysisView/environmentStateMerge.ts b/src/domain/analysisView/environmentStateMerge.ts index cca91fb5b75..406fe7a965a 100644 --- a/src/domain/analysisView/environmentStateMerge.ts +++ b/src/domain/analysisView/environmentStateMerge.ts @@ -79,7 +79,8 @@ export const mergeObservedEntity = (entity: ObservedEntity): StateEntity => { * How observed values changed, per entity in timeline order. A shared field that differs from the * previous repeat of the same request line is volatile, unless a recorded write lies between them; * a field that differs from its previous observation on another line across a write rewrites the - * type. Either across a write means the reads do not agree on one initial state. + * type. Either across a write means the reads do not agree on one initial state; each such pair of + * observations is a span the type's initial reads can end before. */ export const classifyEntityChanges = ( entities: Iterable, @@ -88,9 +89,23 @@ export const classifyEntityChanges = ( ): { readonly rewritten: ReadonlySet; readonly volatile: ReadonlyMap>; + readonly spans: readonly { + readonly type: string; + readonly earlier: number; + readonly later: number; + }[]; } => { const rewritten = new Set(); const volatile = new Map>(); + const spans: { type: string; earlier: number; later: number }[] = []; + const rewrite = ( + type: string, + earlier: StateObservation, + later: StateObservation, + ) => { + rewritten.add(type); + spans.push({ type, earlier: earlier.ordinal, later: later.ordinal }); + }; const changed = (before: StateObservation, after: StateObservation) => Object.keys(after.object).filter( (name) => @@ -113,7 +128,8 @@ export const classifyEntityChanges = ( if (repeat !== undefined) { if (writeBetween(repeat, after)) { // Key additions/removals are changes too, even when every shared field is unchanged. - if (!same(repeat.object, after.object)) rewritten.add(entity.type); + if (!same(repeat.object, after.object)) + rewrite(entity.type, repeat, after); } else for (const name of changed(repeat, after)) volatile.set( @@ -130,11 +146,11 @@ export const classifyEntityChanges = ( !same(previous.observation.object[name], after.object[name]) && writeBetween(previous.observation, after) ) - rewritten.add(entity.type); + rewrite(entity.type, previous.observation, after); lastOfField.set(name, sighting); } lastOfLine.set(line, after); }); } - return { rewritten, volatile }; + return { rewritten, volatile, spans }; }; diff --git a/src/domain/analysisView/environmentStateRewrites.ts b/src/domain/analysisView/environmentStateRewrites.ts new file mode 100644 index 00000000000..061d580275e --- /dev/null +++ b/src/domain/analysisView/environmentStateRewrites.ts @@ -0,0 +1,31 @@ +import type { StateRecordFacts } from "./environmentStateRules.js"; + +/** Two recordings of a type that disagree across a write. */ +export interface RewriteSpan { + readonly type: string; + readonly earlier: number; + readonly later: number; +} + +/** + * Per type whose reads disagree across writes, the earliest write within any such span: one that + * began before the later recording ended and ended after the earlier began, in timeline order. + */ +export const rewriteCuts = ( + spans: readonly RewriteSpan[], + writes: readonly StateRecordFacts[], + byOrdinal: ReadonlyMap, +): Map => { + const cuts = new Map(); + for (const span of spans) { + const earlier = byOrdinal.get(span.earlier); + const later = byOrdinal.get(span.later); + if (earlier === undefined || later === undefined) continue; + const index = writes.findIndex( + (write) => write.start < later.end && write.end > earlier.start, + ); + if (index !== -1) + cuts.set(span.type, Math.min(index, cuts.get(span.type) ?? index)); + } + return new Map([...cuts].map(([type, index]) => [type, writes[index]!])); +}; diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index f92775ee80f..98f9c52bb79 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -196,7 +196,7 @@ it("keeps the latest value of a field that changed with no related write and nam ); }); -it("leaves a type recorded when a value changed across a write under another root", () => { +it("ends a type's state at a write under another root its value changed across", () => { const state = stateOf( captureOf([ ["GET", "/api/search", [{ id: 1, title: "Granite Ledger" }]], @@ -204,16 +204,16 @@ it("leaves a type recorded when a value changed across a write under another roo ["GET", "/api/search", [{ id: 1, title: "Saltmarsh Depot" }]], ]), ); - expect(state.types).toEqual([]); - expect(state.entities).toEqual([]); - expect(viewOf(state, "get_search")).toEqual({ - tool: "get_search", - shape: "recorded", - reason: "fields-differ", - }); + expect(state.types).toMatchObject([ + { collection_template: "/api/search", init_before_ordinal: 1 }, + ]); + expect(state.entities).toMatchObject([ + { id: "1", fields: { title: "Granite Ledger" } }, + ]); + expect(viewOf(state, "get_search")).toMatchObject({ shape: "list" }); }); -it("leaves a type recorded when a value changed across a write already in flight", () => { +it("leaves out of a type's state a read made while the write its value changed across was in flight", () => { const exchange = ([method, path, seconds, time, title]: readonly [ string, string, @@ -254,7 +254,7 @@ it("leaves a type recorded when a value changed across a write already in flight expect(viewOf(state, "get_search")).toEqual({ tool: "get_search", shape: "recorded", - reason: "fields-differ", + reason: "no-init-recording", }); }); @@ -839,7 +839,7 @@ it("does not take a later recording that is itself an entity as the list", () => expect(state.entities).toEqual([]); }); -it("leaves a type recorded when two of its tools read different values across a write", () => { +it("ends a type's state at a write two of its tools read different values across", () => { const state = stateOf( captureOf([ ["GET", "/api/search", [{ id: 1, title: "Granite Ledger" }]], @@ -847,16 +847,17 @@ it("leaves a type recorded when two of its tools read different values across a ["GET", "/api/search/1", { id: 1, title: "Saltmarsh Depot" }], ]), ); - expect(state.types).toEqual([]); - expect(state.entities).toEqual([]); + expect(state.types).toMatchObject([ + { collection_template: "/api/search", init_before_ordinal: 1 }, + ]); + expect(state.entities).toMatchObject([ + { id: "1", fields: { title: "Granite Ledger" } }, + ]); expect( state.views.map((view) => view.shape === "recorded" ? [view.tool, view.reason] : view.tool, ), - ).toEqual([ - ["get_search", "fields-differ"], - ["get_search_by_id", "fields-differ"], - ]); + ).toEqual(["get_search", ["get_search_by_id", "no-init-recording"]]); }); it.each(["old", "new"])( @@ -871,14 +872,9 @@ it.each(["old", "new"])( ]), ); if (title === "new") { - expect(state.types).toEqual([]); - expect(state.entities).toEqual([]); - expect( - state.views.every( - (view) => - view.shape === "recorded" && view.reason === "fields-differ", - ), - ).toBe(true); + expect(state.types).toMatchObject([{ init_before_ordinal: 1 }]); + expect(state.entities[0]?.fields.title).toBe("old"); + expect(viewOf(state, "get_search")).toMatchObject({ shape: "list" }); } else { expect(viewOf(state, "get_search_by_id")).toMatchObject({ shape: "item", @@ -978,7 +974,7 @@ it.each([ [[{ id: 1 }], []], [[{ id: 1 }], [{ id: 2 }]], ] as const)( - "keeps changed list membership across another root's write recorded (%j -> %j)", + "ends a list's state at another root's write its membership changed across (%j -> %j)", (before, after) => { const state = stateOf( captureOf([ @@ -987,12 +983,15 @@ it.each([ ["GET", "/api/search", [...after]], ]), ); - expect(state.types).toEqual([]); - expect(state.entities).toEqual([]); - expect(viewOf(state, "get_search")).toEqual({ - tool: "get_search", - shape: "recorded", - reason: "fields-differ", + // An empty initial list proves no identity, so it is held as a document. + expect(state.types.map((type) => type.init_before_ordinal)).toEqual( + before.length > 0 ? [1] : [], + ); + expect(state.entities.map((entity) => entity.id)).toEqual( + before.map((item) => String(item.id)), + ); + expect(viewOf(state, "get_search")).toMatchObject({ + shape: before.length > 0 ? "list" : "document", }); }, ); @@ -1114,7 +1113,7 @@ it.each([ [{ id: 1 }, { id: 1, title: "Created" }], [{ id: 1, title: "Original" }, { id: 1 }], ])( - "keeps fields added or removed across another root's write recorded (%j -> %j)", + "ends a type's state at another root's write it gained or lost fields across (%j -> %j)", (before, after) => { const state = stateOf( captureOf([ @@ -1123,11 +1122,10 @@ it.each([ ["GET", "/api/search/1", after], ]), ); - expect(state.types).toEqual([]); - expect(state.entities).toEqual([]); + expect(state.types).toMatchObject([{ init_before_ordinal: 1 }]); + expect(state.entities).toMatchObject([{ fields: before }]); expect(viewOf(state, "get_search_by_id")).toMatchObject({ - shape: "recorded", - reason: "fields-differ", + shape: "item", }); }, ); diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 17c946c6d90..926dc98f72c 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1295,6 +1295,59 @@ describe("calls the capture shows reading only", () => { }); }); +describe("types whose reads disagree across a write", () => { + const recipe = (id: number, name: string, views: number) => ({ + id, + name, + views, + }); + + it("plans a type its reads disagree on across an unrelated write from the reads before it, and serves its create", () => { + const state = stateOf([ + ["GET", "/api/recipes", [recipe(1, "Soup", 1), recipe(2, "Stew", 4)]], + ["GET", "/api/recipes/1", recipe(1, "Soup", 1)], + // Logging a view bumps the counter, so the reads after it disagree with those before. + ["POST", "/api/view-log", { ok: true }, 200, { recipe: 1 }], + ["GET", "/api/recipes/1", recipe(1, "Soup", 2)], + ["POST", "/api/recipes", recipe(3, "Broth", 0), 201, { name: "Broth" }], + ["GET", "/api/recipes/3", recipe(3, "Broth", 0)], + ]); + expect(state.types).toMatchObject([ + { collection_template: "/api/recipes", init_before_ordinal: 2 }, + ]); + expect(planOf(state, "post_recipes")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + + it("ends a type's state at the earlier of a write its reads disagree across and a create that made one of its entities", () => { + const rows = (disagreeFirst: boolean): TimedCaptureRow[] => { + const disagreement: TimedCaptureRow[] = [ + ["POST", "/api/view-log", { ok: true }, 200, { recipe: 1 }], + ["GET", "/api/recipes/1", recipe(1, "Soup", 2)], + ]; + const creation: TimedCaptureRow[] = [ + ["POST", "/api/imports", { id: "rcp-0042" }, 201, { name: "Broth" }], + ["GET", "/api/recipes", [recipe(1, "Soup", 1), { id: "rcp-0042" }]], + ]; + return [ + ["GET", "/api/recipes", [recipe(1, "Soup", 1)]], + ["GET", "/api/recipes/1", recipe(1, "Soup", 1)], + ...(disagreeFirst + ? [...disagreement, ...creation] + : [...creation, ...disagreement]), + ]; + }; + expect(stateOf(rows(true)).types).toMatchObject([ + { init_before_ordinal: 2 }, + ]); + expect(stateOf(rows(false)).types).toMatchObject([ + { init_before_ordinal: 2 }, + ]); + }); +}); + describe("creates read under another path", () => { const note = (id: number, title: string) => ({ id, title }); const A = note(1001, "Alpha"); From 64e472a769b974501bbb8db19183d1ac6fc6978a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 12:17:21 -0700 Subject: [PATCH 05/68] fix(environment): replay request lines that show entities in another form A read line that shows the same entities in another form, by an extra query parameter that adds or drops members, or conflicts with a base line on a shared entity, is a variant: it leaves the view's checks and the entity observations, the view names it with the query keys that pick it out, and a call matching those keys replays its recording. A filter role whose name matches no field needs two agreeing values. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 14 +- .../agent-environments/list-queries/spec.md | 4 +- .../agent-environments/state-view/spec.md | 16 + .../agent-environments/write-coverage/spec.md | 3 + docs/web-network-captures.md | 8 +- .../environment/environmentStateAnswer.ts | 47 ++- .../environmentStateWriteAnswer.test.ts | 15 + .../EnvironmentStateExtraction.ts | 23 ++ .../analysisView/environmentStateGate.ts | 24 +- .../environmentStateListQuery.test.ts | 12 + .../analysisView/environmentStateListQuery.ts | 33 +- .../analysisView/environmentStateRules.ts | 43 ++- .../analysisView/environmentStateVariants.ts | 306 ++++++++++++++++++ .../analysisView/environmentStateView.ts | 28 +- .../environmentStateWriteObserve.ts | 22 +- .../environmentStateWrites.test.ts | 79 +++++ tests/fixtures/environmentStateWrites.ts | 20 ++ 17 files changed, 639 insertions(+), 58 deletions(-) create mode 100644 src/domain/analysisView/environmentStateVariants.ts diff --git a/docs/agent-environments.md b/docs/agent-environments.md index b8eecac07bb..3a32320aa04 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -422,12 +422,12 @@ member reports which applied: Each read tool answers according to its view in the state: -| View | Answer | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | -| `list` | When the arguments name one of the lines the view checked exactly (its latest recordings before the first related write; every path and query value equal to the recording's, and every recorded query parameter supplied), that recorded envelope with its array rendered from the state: every entity of the collection in state order for `membership: "all"` or a line `all_record_ordinals` names, or the recorded members still held. A call with no query argument answers from such a line of the collection its path arguments name that only pages its list, with `replay.exact_match` false. On a line the view's `query` answers, and for a call whose every query argument has a role there (an argument-less call aside), the answer is the query evaluated over the state: filtered, searched, sorted and paged, with counters at the number listed and `query.totals` at the number matched, and `state.membership: "query"`; such a call answers on a query or whole line of its collection with `replay.exact_match` false. A value an `inert` parameter never recorded, or a parameter without a role, replays its recording. A member lacking a field every recording carried makes the call a tool error rather than a partial list. | -| `document` | When the arguments name the document's checked line exactly, the state's value for it; a tool error when the state holds none. | -| `recorded` | The recording, as replay answers it. | +| View | Answer | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`, except that a call matching one of the view's `projected_query_keys` replays its recording. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | +| `list` | When the arguments name one of the lines the view checked exactly (its latest recordings before the first related write; every path and query value equal to the recording's, and every recorded query parameter supplied), that recorded envelope with its array rendered from the state: every entity of the collection in state order for `membership: "all"` or a line `all_record_ordinals` names, or the recorded members still held. A call with no query argument answers from such a line of the collection its path arguments name that only pages its list, with `replay.exact_match` false. On a line the view's `query` answers, and for a call whose every query argument has a role there (an argument-less call aside), the answer is the query evaluated over the state: filtered, searched, sorted and paged, with counters at the number listed and `query.totals` at the number matched, and `state.membership: "query"`; such a call answers on a query or whole line of its collection with `replay.exact_match` false. A value an `inert` parameter never recorded, a parameter without a role, or a call matching one of the view's `projected_query_keys`, replays its recording. A member lacking a field every recording carried makes the call a tool error rather than a partial list. | +| `document` | When the arguments name the document's checked line exactly, the state's value for it; a tool error when the state holds none. | +| `recorded` | The recording, as replay answers it. | An item or list view that always spells a clock field otherwise than the entity's stored value names that spelling in `clock_formats`, and a value it @@ -438,7 +438,7 @@ A list or document call that names no checked line, including a line recorded after a write or with other query values, answers from the recording. Every answer has the replay shape plus `state`: `{"source": "state", "view": …}` naming the entity, collection or document path, or `{"source": "recording", -"reason": …}` with the view's reason, `no-view`, `unrecorded-request`, `page-exceeded` (a call naming a page of a whole list that the collection has outgrown) or `projection` (a call to an item tool whose recordings asked for some fields only, naming such a parameter for an entity the state holds; the answer is a recording, so it does not show served writes). A +"reason": …}` with the view's reason, `no-view`, `unrecorded-request`, `page-exceeded` (a call naming a page of a whole list that the collection has outgrown), `projection` (a call to an item tool whose recordings asked for some fields only, naming such a parameter for an entity the state holds, or a call matching a `projected_query_keys` key that asks for some fields only) or `variant` (a call matching another `projected_query_keys` key: a parameter, or a value of one, only lines showing the entities in another representation named, or leaving out a parameter every other line named). A `projection` or `variant` answer is a recording, so it does not show served writes. A state answer carries the base record's status, content type and `replay` provenance with `truncated: false`; one whose JSON would exceed 256 KiB is refused as a `resource_constraint` tool error rather than cut. Extraction does diff --git a/docs/specs/agent-environments/list-queries/spec.md b/docs/specs/agent-environments/list-queries/spec.md index e14edd6ff80..d2af65457f4 100644 --- a/docs/specs/agent-environments/list-queries/spec.md +++ b/docs/specs/agent-environments/list-queries/spec.md @@ -44,7 +44,9 @@ filter or inert. No two parameters of one call take the same `sort`, `direction` depend on which applied last, and serving supplies a call's values in name order rather than as recorded, so such a combination explains no line and such a call replays its recording. A line with more than 12 query parameters is left unexplained, which bounds the search; names such as `__proto__` are kept as the query's own members. The lines' roles -merge: lines that disagree drop the parameter, inert values gather, search fields unite. The merged query keeps the +merge: lines that disagree drop the parameter, inert values gather, search fields unite. A filter on a field not +named like its parameter (`shelf`, or `shelf_id`, for `shelf`) can match by coincidence, so it stands only when lines +giving the parameter two different values agree on it; otherwise the parameter takes no role. The merged query keeps the lines it reproduces, envelope and fields included; any other line keeps its recorded members. The view's `query` names the roles, those lines, and the envelope members that count every match before paging (`totals`); a `number`-of-items member such as `numberOfElements` counts the page. diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 144f84d64b2..7ec35ea748a 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -38,6 +38,22 @@ later increments. and serving replays any call to that tool that names a projection parameter for an entity the state holds. The write gate also leaves out any read that names one and leaves out a field its view requires. +- A request line of an item or list view is a representation variant when it + shows an entity another line shows with other members, or names a parameter + the base lines do not (paging aside) while its objects carry a member no base + object carries or lack one every base object carries; a list line asking for + some fields only is one whenever a base line does not. Base lines are taken + first: lines naming no such parameter, then lines asking for every field, + then the line most others agree with. A variant leaves the view's checks and + the entity observations when a query key tells it apart: a parameter only + variants name, a value no base line gives a parameter, or a parameter every + base line names that a variant leaves out. The view lists its latest + recordings in `projected_record_ordinals` and the keys in + `projected_query_keys`; serving replays a call matching a key with the reason + `variant` (`projection` when the key asks for some fields only), so the + answer is a recording and shows no served write. The write gate neither + checks nor learns from a successful read matching a key; a 400, 404 or 410 + such a read answers is still the absence it checks. - A field every recording of a view carried is required: serving refuses an entity lacking it. Once a successful read the write gate checks, naming no projection parameter, shows the application leaves the field out of an entity diff --git a/docs/specs/agent-environments/write-coverage/spec.md b/docs/specs/agent-environments/write-coverage/spec.md index cfcb5094e70..6f0f25f56e6 100644 --- a/docs/specs/agent-environments/write-coverage/spec.md +++ b/docs/specs/agent-environments/write-coverage/spec.md @@ -36,6 +36,9 @@ what the writes did: Identity-free projection evidence after the initial-state cutoff is retained too, without seeding later values into initial entities. Failed responses are classified before the projection-replay shortcut, so a projected absence can confirm a delete or contradict an unexplained disappearance. + A list line asking for some fields only, and any item or list line showing its entities in another representation + (an expanding or reducing query), is replayed the same way when a query key tells it from the view's other lines + (`projected_query_keys`, reason `variant`); such calls replay recordings and do not show served writes. - **Sequences.** A sequence value may be `-`-separated digit groups of one width of at least two digits, not a date, version or address. The next value keeps the exemplar's groups and zero padding; digits that outgrow them lead. A later create must record its value spelled that way. A held value whose digits outgrew the mask (`100-00` after diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index c9999e4af25..0dca008f805 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -615,7 +615,13 @@ Every entity cites its `record_ordinals`. An item or list plan is kept only when it reproduces the latest initial recording of each request line from the state, comparing JSON values without regard to member order; a volatile field compares its recorded value. Each -plan lists the `checked_record_ordinals`. Otherwise the tool is a recorded view +plan lists the `checked_record_ordinals`. A request line that shows the +entities in another representation (an expanding or reducing query, or one +asking for some fields only) is left out of those checks when a query key tells +it from the others: the plan lists its latest recordings in +`projected_record_ordinals` and the keys in `projected_query_keys` (`name`, +with a `value` or `absent: true`), and serving replays calls matching them. +Otherwise the tool is a recorded view with reason `envelope-varies`, `fields-differ` or `list-differs`; the other reasons are `query-body` (a query `POST`, or one the capture shows only reading), `no-init-recording`, `body-unusable`, `no-identity` (an item read without a proved identity), diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 408db4ff0ab..55690dfa0a4 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -1,4 +1,3 @@ -import { environmentToolArguments } from "./environmentTools.js"; import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumulator.js"; import { collectionMatch, @@ -22,6 +21,7 @@ import { type StateView, } from "../../domain/analysisView/environmentStateRules.js"; import { pageBound } from "../../domain/analysisView/environmentStatePaging.js"; +import { matchesReplayKey } from "../../domain/analysisView/environmentStateVariants.js"; import { isAbsence } from "../../domain/analysisView/environmentStateWriteChecks.js"; import { evaluateQuery, @@ -66,7 +66,8 @@ export type StateProvenance = | "no-view" | "unrecorded-request" | "page-exceeded" - | "projection"; + | "projection" + | "variant"; } | { readonly source: "state"; @@ -147,17 +148,24 @@ const fromRecording = ( : replayed; }; -/** Whether a call names a projection parameter of an item view with projected reads, which the state's whole entities cannot answer. */ -const asksProjection = ( - view: StateItemView, - tool: EnvironmentManifestTool, - args: ReplayArguments, -): boolean => - view.projected_record_ordinals !== undefined && - [...environmentToolArguments(tool).query].some( - ([name, argument]) => - isProjectionParameter(name) && args[argument] !== undefined, - ); +/** Why a call replays the view's replayed reads (`projection` for some fields only, `variant` for another representation), or undefined when the state answers it. */ +const replayedCall = ( + view: StateItemView | StateListView, + call: ReadonlyMap, +): "projection" | "variant" | undefined => { + if (view.projected_record_ordinals === undefined) return undefined; + const keys = view.projected_query_keys; + if (keys === undefined || keys.length === 0) + return view.shape === "item" && [...call.keys()].some(isProjectionParameter) + ? "projection" + : undefined; + const values = new Map([...call].map(([name, value]) => [name, [value]])); + const matched = keys.filter((key) => matchesReplayKey([key], values)); + if (matched.length === 0) return undefined; + return matched.some((key) => isProjectionParameter(key.name)) + ? "projection" + : "variant"; +}; /** A recorded body the state renders into, usable exactly when extraction could use it. */ export const recordedJson = ( @@ -306,9 +314,10 @@ const answerItem = ( collection: `/${call.segments.map(({ text }) => text).join("/")}`, id: call.id, }); - // A projection of an entity the state holds replays as the capture's projected reads did. - if (asksProjection(view, tool, args)) - return fromRecording(source, tool, args, "projection"); + // A projection or another representation of an entity the state holds replays as the capture's reads did. + const replayed = replayedCall(view, callQuery(tool, args)); + if (replayed !== undefined) + return fromRecording(source, tool, args, replayed); const shown = shownEntity( tool, view, @@ -476,6 +485,12 @@ const answerCheckedLine = ( view: StateListView | StateDocumentView, args: ReplayArguments, ): Result => { + const replayed = + view.shape === "list" + ? replayedCall(view, callQuery(tool, args)) + : undefined; + if (replayed !== undefined) + return fromRecording(serving.source, tool, args, replayed); const named = checkedLine( serving.source, tool, diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index f3056f4964c..77785907b71 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -11,6 +11,7 @@ import { BOOK_ROWS, DELETE_NOT_FOUND, DETAILED_LIST_ROWS, + EXPANDED_LIST_ROWS, FIRST_BOOK, OMITTED_FIELD_ROWS, PROJECTED_ROWS, @@ -27,6 +28,7 @@ import { book, bookClock, detailedBook, + expandedBook, UNCHAPTERED_ROWS, VERSIONED_ROWS, numberedUuid, @@ -294,6 +296,19 @@ describe("wider write coverage", () => { }); }); + it("replays a call naming a parameter only the expanded line names, and lists a served create on the plain one", () => { + const books = servedFrom(EXPANDED_LIST_ROWS); + const created = books.answer("post_books", CREATE_NEW_BOOK).body as Book; + expect(books.answer("get_books")).toMatchObject({ + body: [FIRST_BOOK, SECOND_BOOK, created], + state: { source: "state", view: "list" }, + }); + expect(books.answer("get_books", { expand: "shelf" })).toMatchObject({ + body: [FIRST_BOOK, SECOND_BOOK].map(expandedBook), + state: { source: "recording", reason: "variant" }, + }); + }); + it("numbers created books after the largest held asset number, in its digit groups", () => { const books = servedFrom(ASSET_ROWS); const create = (name: string) => diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index b34a6884a18..ee4a1ca5376 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -60,6 +60,11 @@ import { type CreatedIds, } from "./environmentStateWriteLinks.js"; import { extractWrites } from "./environmentStateWrites.js"; +import { + dropObservations, + lineShapes, + withoutVariants, +} from "./environmentStateVariants.js"; import { stateWritesOf } from "./environmentStateQueryCalls.js"; class StateBudgetExhausted extends Error {} @@ -183,11 +188,29 @@ export class EnvironmentStateExtraction { for (const candidate of candidates.filter((entry) => !entry.item)) this.#planList(candidate); for (const plan of this.#plans) this.#observePlan(plan); + this.#dropVariants(); this.#classifyChanges(); this.#merge(); return candidates; } + /** Leave each plan's representation variants to replay: out of its lines and the observed entities. */ + #dropVariants(): void { + const shapes = lineShapes(this.#entities.values()); + this.#retain(ENTRY_BYTES * (shapes.size + 1)); + for (const [index, plan] of this.#plans.entries()) { + const split = withoutVariants(plan, { + shapeOf: (record) => shapes.get(record.ordinal), + queryOf: (ordinal) => this.#byOrdinal.get(ordinal)?.query, + position: (ordinal) => this.#position.get(ordinal)!, + }); + if (split === undefined) continue; + this.#retain(ENTRY_BYTES * (split.dropped.size + 2)); + this.#plans[index] = split.plan; + dropObservations(this.#entities, split.dropped); + } + } + /** End each rewritten type's initial reads at the earliest write its reads disagree across, and clear the plans to make them again. */ #cutRewrites(): boolean { this.#cuts = rewriteCuts( diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index b1662e1e48d..4675b9cfe29 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -14,7 +14,9 @@ import { scalarText, type JsonObject, type RecordedViewReason, + type ReplayKey, type StateEntity, + type StateItemView, type StateRecordFacts, type StateToolFacts, type StateView, @@ -43,10 +45,25 @@ export interface StatePlan { readonly recordings: readonly StateRecordFacts[]; /** The latest of them per request line, in timeline order. */ readonly latest: readonly StateRecordFacts[]; - /** Item reads left to replay because they asked for some fields only. */ + /** Reads left to replay: item reads that asked for some fields only, and representation variants. */ readonly projected?: readonly number[]; + /** The query keys that pick calls of the replayed reads out. */ + readonly projectedKeys?: readonly ReplayKey[]; } +/** A view's replayed reads and their keys, when it has any. */ +const replayedReads = ( + plan: StatePlan, +): Pick => + plan.projected === undefined || plan.projected.length === 0 + ? {} + : { + projected_record_ordinals: [...plan.projected], + ...(plan.projectedKeys === undefined || plan.projectedKeys.length === 0 + ? {} + : { projected_query_keys: [...plan.projectedKeys] }), + }; + /** What the gate reads from an extraction; `withBody` drops each body's temporary work after `use`. */ export interface StateGateContext { readonly withBody: ( @@ -256,9 +273,7 @@ export const checkItemPlan = ( required_fields: union.required, envelope_ordinal: plan.latest[0]!.ordinal, checked_record_ordinals: plan.latest.map((record) => record.ordinal), - ...(plan.projected === undefined || plan.projected.length === 0 - ? {} - : { projected_record_ordinals: [...plan.projected] }), + ...replayedReads(plan), ...spellings.view, }; }; @@ -550,6 +565,7 @@ export const checkListPlan = ( counters, ...(query === undefined ? {} : { query }), checked_record_ordinals: plan.latest.map((record) => record.ordinal), + ...replayedReads(plan), ...spellings.view, }; }; diff --git a/src/domain/analysisView/environmentStateListQuery.test.ts b/src/domain/analysisView/environmentStateListQuery.test.ts index 3139bc67547..f2b229870c1 100644 --- a/src/domain/analysisView/environmentStateListQuery.test.ts +++ b/src/domain/analysisView/environmentStateListQuery.test.ts @@ -230,6 +230,18 @@ describe("learning a list's query", () => { // Serving supplies a call's values in name order. expect(ids("?limit=1&size=2", learned!.parameters)).toEqual(["1"]); }); + + it("adopts a filter on a field named unlike its parameter only once lines with two values agree on it", () => { + const owner = (...lines: QueryLine[]) => + learnQuery(lines)?.parameters["owner"]; + expect(owner(line("?owner=a", [1, 3], 50))).toBeUndefined(); + expect( + owner(line("?owner=a", [1, 3], 50), line("?owner=b", [2], 51)), + ).toEqual({ role: "filter", field: "shelf" }); + expect(learnQuery([line("?shelf_id=a", [1, 3], 52)])?.parameters).toEqual({ + shelf_id: { role: "filter", field: "shelf" }, + }); + }); }); describe("queries the state can always answer", () => { diff --git a/src/domain/analysisView/environmentStateListQuery.ts b/src/domain/analysisView/environmentStateListQuery.ts index 8a93b3f4199..5d913abe977 100644 --- a/src/domain/analysisView/environmentStateListQuery.ts +++ b/src/domain/analysisView/environmentStateListQuery.ts @@ -550,16 +550,45 @@ const mergeRoles = ( return Object.fromEntries(merged); }; +/** Whether a filtered field is named like its parameter, an id suffix aside: `category`, `site_id` for `site`. */ +const namedLike = (field: string, name: string): boolean => { + const [left, right] = [normalized(field), normalized(name)]; + return left === right || right === `${left}id` || left === `${right}id`; +}; + +/** The roles less any filter on a field named unlike its parameter that only one recorded value supports, since one line can match by coincidence. */ +const trustedRoles = ( + parameters: Record, + explained: readonly { + readonly line: QueryLine; + readonly parameters: Record; + }[], +): Record => + Object.fromEntries( + Object.entries(parameters).filter(([name, role]) => { + if (role.role !== "filter" || namedLike(role.field, name)) return true; + const values = new Set( + explained + .filter((entry) => entry.parameters[name]?.role === "filter") + .map((entry) => entry.line.values.get(name)), + ); + return values.size >= 2; + }), + ); + /** The query model that lists exactly what each explained line recorded, or undefined when none does. */ export const learnQuery = ( lines: readonly QueryLine[], ): Pick | undefined => { const explained = lines.flatMap((line) => { const parameters = explainLine(line); - return parameters === undefined ? [] : [parameters]; + return parameters === undefined ? [] : [{ line, parameters }]; }); if (explained.length === 0) return undefined; - const parameters = mergeRoles(explained); + const parameters = trustedRoles( + mergeRoles(explained.map((entry) => entry.parameters)), + explained, + ); const record_ordinals = lines .filter((line) => listsAsRecorded(line, parameters)) .map((line) => line.ordinal); diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 4b2ca22a8d6..285fd9bcd8b 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -107,12 +107,26 @@ interface EntityViewPlan { readonly clock_formats?: Readonly> | undefined; } -export type StateItemView = EntityViewPlan & { - readonly shape: "item"; - readonly envelope_ordinal: number; - /** Recorded reads that asked for some fields only and did not return the item, which replay answers. */ +/** A query key that picks out replayed reads: a parameter, a parameter with one value, or a parameter left out. */ +export interface ReplayKey { + readonly name: string; + readonly value?: string | undefined; + readonly absent?: true | undefined; +} + +/** Recorded reads a view leaves to replay, and the query keys that pick calls of them out. */ +interface ReplayedReads { + /** Reads that asked for some fields only, or show entities in another representation than the checked lines. */ readonly projected_record_ordinals?: number[] | undefined; -}; + /** A call whose query matches one of these replays; absent on views that only left out projections. */ + readonly projected_query_keys?: ReplayKey[] | undefined; +} + +export type StateItemView = EntityViewPlan & + ReplayedReads & { + readonly shape: "item"; + readonly envelope_ordinal: number; + }; /** A query parameter that asks for some fields only (`fields`, `fields[...]`, `select`, `$select`). */ export const isProjectionParameter = (name: string): boolean => { @@ -130,15 +144,16 @@ export const projectsFields = (query: string | undefined): boolean => query !== undefined && [...new URLSearchParams(query).keys()].some(isProjectionParameter); -export type StateListView = EntityViewPlan & { - readonly shape: "list"; - readonly membership: "all" | "recorded"; - /** With recorded membership, the checked lines that each list their whole collection. */ - readonly all_record_ordinals?: number[] | undefined; - readonly counters: string[]; - /** The query the view's other lines follow, when one explains any of them. */ - readonly query?: ListQuery | undefined; -}; +export type StateListView = EntityViewPlan & + ReplayedReads & { + readonly shape: "list"; + readonly membership: "all" | "recorded"; + /** With recorded membership, the checked lines that each list their whole collection. */ + readonly all_record_ordinals?: number[] | undefined; + readonly counters: string[]; + /** The query the view's other lines follow, when one explains any of them. */ + readonly query?: ListQuery | undefined; + }; /** Whether a list view answers on a checked line with every entity of the collection. */ export const listsAll = (view: StateListView, ordinal: number): boolean => diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts new file mode 100644 index 00000000000..60be63da09b --- /dev/null +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -0,0 +1,306 @@ +import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import type { StatePlan } from "./environmentStateGate.js"; +import type { ObservedEntity } from "./environmentStateMerge.js"; +import { + projectsFields, + type ReplayKey, + type StateRecordFacts, +} from "./environmentStateRules.js"; + +/** Query names that page a list rather than choose how it shows its entities. */ +const PAGING = new Set([ + "limit", + "offset", + "page", + "per_page", + "perpage", + "page_size", + "pagesize", + "size", + "start", + "_start", + "_end", + "cursor", + "pagenumber", + "pageindex", + "skip", + "take", + "top", + "$top", + "$skip", +]); + +/** What one recorded line's objects showed: each entity's member names, and the members any and every object carried. */ +export interface LineShape { + readonly entities: ReadonlyMap; + readonly carried: ReadonlySet; + readonly common: ReadonlySet | undefined; +} + +/** Each name a query names, with every value it took. */ +export const queryValues = ( + query: string | null | undefined, +): Map => { + const values = new Map(); + for (const [name, value] of new URLSearchParams(query ?? "")) + values.set(name, [...(values.get(name) ?? []), value]); + return values; +}; + +const shapingNames = (query: string | null | undefined): string[] => + [...queryValues(query).keys()].filter( + (name) => !PAGING.has(name.toLowerCase()), + ); + +/** The shape each observed recording showed of its entities, by ordinal. */ +export const lineShapes = ( + entities: Iterable, +): Map => { + const shapes = new Map< + number, + { + entities: Map; + carried: Set; + common: Set | undefined; + } + >(); + for (const entity of entities) + for (const observation of entity.observations) { + const members = Object.keys(observation.object); + let shape = shapes.get(observation.ordinal); + if (shape === undefined) { + shape = { entities: new Map(), carried: new Set(), common: undefined }; + shapes.set(observation.ordinal, shape); + } + shape.entities.set( + JSON.stringify([entity.type, entity.collection, entity.id]), + [...members].sort(compare).join(","), + ); + for (const member of members) shape.carried.add(member); + shape.common = + shape.common === undefined + ? new Set(members) + : new Set(members.filter((member) => shape!.common!.has(member))); + } + return shapes; +}; + +const EMPTY: LineShape = { + entities: new Map(), + carried: new Set(), + common: undefined, +}; + +/** Whether two lines show a shared entity with different members. */ +const conflicts = (left: LineShape, right: LineShape): boolean => + [...left.entities].some( + ([key, members]) => + right.entities.has(key) && right.entities.get(key) !== members, + ); + +/** The latest lines that show the plan's entities in another representation than its base lines, as an expanding or reducing query does. */ +export const variantLines = ( + latest: readonly StateRecordFacts[], + shapeOf: (record: StateRecordFacts) => LineShape | undefined, + list: boolean, +): StateRecordFacts[] => { + if (latest.length < 2) return []; + const shape = (record: StateRecordFacts): LineShape => + shapeOf(record) ?? EMPTY; + const agreeing = new Map( + latest.map((record) => [ + record, + latest.filter( + (other) => other !== record && !conflicts(shape(record), shape(other)), + ).length, + ]), + ); + const size = (record: StateRecordFacts): number => shape(record).carried.size; + const rank = (record: StateRecordFacts): number[] => [ + shapingNames(record.query).length === 0 ? 0 : 1, + projectsFields(record.query ?? undefined) ? 1 : 0, + -agreeing.get(record)!, + shapingNames(record.query).length, + size(record), + ]; + // Base lines first: no shaping query, then no projection, then the line most others agree with. + const ordered = [...latest].sort((left, right) => { + const [a, b] = [rank(left), rank(right)]; + const differs = a.findIndex((value, index) => value !== b[index]); + return differs === -1 ? 0 : a[differs]! - b[differs]!; + }); + const base: StateRecordFacts[] = []; + const variants: StateRecordFacts[] = []; + for (const record of ordered) { + if (base.length > 0 && isVariant(record, base, { shape, list })) + variants.push(record); + else base.push(record); + } + return variants; +}; + +/** Whether a line shows a base line's entity with other members, asks a list for some fields only, or names a new shaping parameter while its objects carry or lack members the base lines do not. */ +const isVariant = ( + record: StateRecordFacts, + base: readonly StateRecordFacts[], + facts: { + readonly shape: (record: StateRecordFacts) => LineShape; + readonly list: boolean; + }, +): boolean => { + const { shape, list } = facts; + const mine = shape(record); + if (base.some((line) => conflicts(mine, shape(line)))) return true; + if ( + list && + projectsFields(record.query ?? undefined) && + base.some((line) => !projectsFields(line.query ?? undefined)) + ) + return true; + const baseNames = new Set(base.flatMap((line) => shapingNames(line.query))); + if (!shapingNames(record.query).some((name) => !baseNames.has(name))) + return false; + const carried = new Set(base.flatMap((line) => [...shape(line).carried])); + const commons = base.flatMap((line) => { + const common = shape(line).common; + return common === undefined ? [] : [common]; + }); + const common = + commons.length === 0 + ? undefined + : [...commons[0]!].filter((member) => + commons.every((set) => set.has(member)), + ); + return ( + [...mine.carried].some((member) => !carried.has(member)) || + (mine.common !== undefined && + common !== undefined && + common.some((member) => !mine.common!.has(member))) + ); +}; + +/** The keys that tell replayed lines from base lines: a parameter or value only replayed lines give, or a parameter every base line names that one leaves out. */ +export const replayKeys = ( + base: readonly (string | null | undefined)[], + replayed: readonly (string | null | undefined)[], +): ReplayKey[] => { + const baseValues = base.map(queryValues); + const named = new Set(baseValues.flatMap((values) => [...values.keys()])); + const everywhere = [...named].filter( + (name) => + !PAGING.has(name.toLowerCase()) && + baseValues.every((values) => values.has(name)), + ); + const keys = new Map(); + const add = (key: ReplayKey): void => { + keys.set( + JSON.stringify([key.name, key.value ?? null, key.absent ?? false]), + key, + ); + }; + for (const query of replayed) { + const values = queryValues(query); + for (const [name, given] of values) { + if (PAGING.has(name.toLowerCase())) continue; + const unseen = given.filter( + (value) => + !baseValues.some( + (other) => other.get(name)?.includes(value) === true, + ), + ); + if (!named.has(name)) add({ name }); + else for (const value of unseen) add({ name, value }); + } + for (const name of everywhere) + if (!values.has(name)) add({ name, absent: true }); + } + return [...keys.values()].sort( + (left, right) => + compare(left.name, right.name) || + compare(left.value ?? "", right.value ?? "") || + Number(left.absent ?? false) - Number(right.absent ?? false), + ); +}; + +/** Whether a call's query names a replay key: the parameter, the parameter with that value, or leaves out an absent key's parameter. */ +export const matchesReplayKey = ( + keys: readonly ReplayKey[], + call: ReadonlyMap, +): boolean => + keys.some((key) => + key.absent === true + ? !call.has(key.name) + : key.value === undefined + ? call.has(key.name) + : call.get(key.name)?.includes(key.value) === true, + ); + +const requestLine = (record: StateRecordFacts): string => + record.path + (record.query ?? ""); + +/** The plan with the variants a key picks out moved to its replayed reads and their recordings dropped, or undefined when it replays nothing. */ +export const withoutVariants = ( + plan: StatePlan, + facts: { + readonly shapeOf: (record: StateRecordFacts) => LineShape | undefined; + readonly queryOf: (ordinal: number) => string | null | undefined; + readonly position: (ordinal: number) => number; + }, +): + | { readonly plan: StatePlan; readonly dropped: ReadonlySet } + | undefined => { + const found = variantLines(plan.latest, facts.shapeOf, !plan.item); + const unkeyed = plan.latest.filter((record) => !found.includes(record)); + const variants = found.filter( + (record) => + replayKeys( + unkeyed.map((line) => line.query), + [record.query], + ).length > 0, + ); + const projected = plan.projected ?? []; + if (variants.length === 0 && projected.length === 0) return undefined; + const lines = new Set(variants.map(requestLine)); + const latest = plan.latest.filter( + (record) => !lines.has(requestLine(record)), + ); + const replayed = [ + ...projected, + ...variants.map((record) => record.ordinal), + ].sort((left, right) => facts.position(left) - facts.position(right)); + const dropped = new Set( + plan.recordings + .filter((record) => lines.has(requestLine(record))) + .map((record) => record.ordinal), + ); + return { + plan: { + ...plan, + recordings: plan.recordings.filter( + (record) => !dropped.has(record.ordinal), + ), + latest, + projected: replayed, + projectedKeys: replayKeys( + latest.map((record) => record.query), + replayed.map(facts.queryOf), + ), + }, + dropped, + }; +}; + +/** Forget the observations of dropped recordings, and entities only they showed. */ +export const dropObservations = ( + entities: Map, + dropped: ReadonlySet, +): void => { + for (const [key, entity] of entities) { + const kept = entity.observations.filter( + (observation) => !dropped.has(observation.ordinal), + ); + if (kept.length === entity.observations.length) continue; + if (kept.length === 0) entities.delete(key); + else entities.set(key, { ...entity, observations: kept }); + } +}; diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 544fb89f899..83cff6eb961 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -119,6 +119,26 @@ const entityViewFields = { "How the view spells clock fields it always spells otherwise than the entities' stored values; a stored value the view never recorded is spelled this way.", ), }; +const replayedReadFields = { + projected_record_ordinals: z + .array(z.number().int().nonnegative()) + .optional() + .describe( + "Recorded reads left to replay: they asked for some fields only (`fields`, `select`), or show the entities in another representation than the checked lines (an augmenting or reducing query). Replayed calls do not show served writes.", + ), + projected_query_keys: z + .array( + z.strictObject({ + name: z.string(), + value: z.string().optional(), + absent: z.literal(true).optional(), + }), + ) + .optional() + .describe( + "Query keys that pick calls of the replayed reads out: a parameter only they name, a value only they give a parameter, or (absent) a parameter every checked line names and they leave out. A call matching any key replays.", + ), +}; const viewSchema = z.discriminatedUnion("shape", [ z.strictObject({ ...entityViewFields, @@ -130,12 +150,7 @@ const viewSchema = z.discriminatedUnion("shape", [ .describe( "Record whose response, with the entity object replaced, every item response shares.", ), - projected_record_ordinals: z - .array(z.number().int().nonnegative()) - .optional() - .describe( - "Recorded reads that asked for some fields only (`fields`, `select`) and did not return the item; calls naming a projection replay.", - ), + ...replayedReadFields, }), z.strictObject({ ...entityViewFields, @@ -159,6 +174,7 @@ const viewSchema = z.discriminatedUnion("shape", [ .describe( "How the view's other checked lines select and order entities, when filters, a search, a sort or paging explain them; absent when none does.", ), + ...replayedReadFields, }), z.strictObject({ tool: z.string(), diff --git a/src/domain/analysisView/environmentStateWriteObserve.ts b/src/domain/analysisView/environmentStateWriteObserve.ts index d7bf89768dd..2ac5aa86f53 100644 --- a/src/domain/analysisView/environmentStateWriteObserve.ts +++ b/src/domain/analysisView/environmentStateWriteObserve.ts @@ -14,6 +14,7 @@ import { type StateRecordFacts, type StateView, } from "./environmentStateRules.js"; +import { matchesReplayKey, queryValues } from "./environmentStateVariants.js"; /** Where an observed entity object was found: the record and a JSON pointer into its response. */ export interface Observed { @@ -94,20 +95,27 @@ export interface ObservationSearch { ) => T; } -/** Whether a read asked for some fields only and shows no whole entity: an item view replays such reads, or the read leaves out a field its view requires. */ +/** Whether serving replays a read rather than answering it from the state: it matches a replay key, or asked for some fields only and shows no whole entity. */ export const projectedRead = ( view: StateView, record: StateRecordFacts, io: Pick, ): boolean => { + if (view.shape !== "item" && view.shape !== "list") return false; + // An absence or error holds no entity, so it is never a partial one and stays evidence. + if (!succeeded(record)) return false; + const keyed = (view.projected_query_keys ?? []).length > 0; if ( - (view.shape !== "item" && view.shape !== "list") || - !projectsFields(record.query) + keyed && + matchesReplayKey(view.projected_query_keys!, queryValues(record.query)) + ) + return true; + if (!projectsFields(record.query)) return false; + if ( + view.shape === "item" && + view.projected_record_ordinals !== undefined && + !keyed ) - return false; - // An absence or error holds no entity, so it is never a partial one. - if (!succeeded(record)) return false; - if (view.shape === "item" && view.projected_record_ordinals !== undefined) return true; return io.withBody(record.ordinal, (body) => { const objects = diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 926dc98f72c..268dc67ae1d 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -12,6 +12,7 @@ import { BOOK_ROWS, BOOK_WRITE_CLOCK, DETAILED_LIST_ROWS, + EXPANDED_LIST_ROWS, FIRST_BOOK, OMITTED_FIELD_ROWS, PROJECTED_ROWS, @@ -31,6 +32,7 @@ import { bookClock, detailedBook, environmentStateViewOf, + expandedBook, rawCaptureEvidence, renamedBook, type Book, @@ -215,6 +217,83 @@ describe("wider write coverage", () => { }); }); + it("leaves a list line that expands its books to replay, serving the create the plain list confirms", () => { + const state = stateOf(EXPANDED_LIST_ROWS); + expect(state.views.find((view) => view.tool === "get_books")).toMatchObject( + { + shape: "list", + checked_record_ordinals: [0], + projected_record_ordinals: [1], + projected_query_keys: [{ name: "expand" }], + }, + ); + expect(planOf(state, "post_books")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + + it("leaves a list line that asks for some fields only to replay", () => { + const view = stateOf([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + [ + "GET", + "/api/books?fields=id,name", + [ + { id: 1, name: "First Book" }, + { id: 2, name: "Second Book" }, + ], + ], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ]).views.find((candidate) => candidate.tool === "get_books"); + expect(view).toMatchObject({ + shape: "list", + checked_record_ordinals: [0], + projected_record_ordinals: [1], + projected_query_keys: [{ name: "fields" }], + }); + }); + + it("tells a line that adds a parameter apart by the members its books show, not by the parameters it shares", () => { + const view = stateOf([ + ["GET", "/api/books?sort=name&limit=1", [FIRST_BOOK]], + ["GET", "/api/books?sort=name&q=first", [FIRST_BOOK]], + [ + "GET", + "/api/books?sort=name&with=stats&offset=1", + [{ ...SECOND_BOOK, stats: { reads: 4 } }], + ], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ]).views.find((candidate) => candidate.tool === "get_books"); + expect(view).toMatchObject({ + shape: "list", + checked_record_ordinals: [0, 1], + projected_record_ordinals: [2], + projected_query_keys: [{ name: "with" }], + }); + }); + + it("confirms a delete by a missing book's read on a line that expands its shelf", () => { + const state = stateOf([ + ...BOOK_INIT_ROWS, + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ["DELETE", "/api/books/2", "", 204], + ["GET", "/api/books/2?expand=shelf", BOOK_NOT_FOUND, 404], + ]); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).toMatchObject({ + projected_record_ordinals: [3], + projected_query_keys: [{ name: "expand" }], + }); + expect(planOf(state, "delete_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + it("serves creates whose number follows the largest held one in its digit groups", () => { expect(planOf(stateOf(ASSET_ROWS), "post_books")).toMatchObject({ served: true, diff --git a/tests/fixtures/environmentStateWrites.ts b/tests/fixtures/environmentStateWrites.ts index 4b9bb9f7409..910f7c07d72 100644 --- a/tests/fixtures/environmentStateWrites.ts +++ b/tests/fixtures/environmentStateWrites.ts @@ -126,6 +126,26 @@ export const PROJECTED_ROWS: readonly TimedCaptureRow[] = [ ["GET", "/api/books/2?fields=name", { name: "Second Book" }], ]; +/** A book as a list asked to expand its shelf shows it. */ +export const expandedBook = (entity: Book): Book => ({ + ...entity, + shelf: { id: 7, name: "Main Hall" }, +}); + +/** The list read plainly and with its shelves expanded, then a create the plain list shows. */ +export const EXPANDED_LIST_ROWS: readonly TimedCaptureRow[] = [ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + [ + "GET", + "/api/books?expand=shelf", + [FIRST_BOOK, SECOND_BOOK].map(expandedBook), + ], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["POST", "/api/books", THIRD_BOOK_AT_4, 201, { name: "Third Book" }], + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK, THIRD_BOOK_AT_4]], +]; + /** A book numbered as an asset, in digit groups. */ export const assetBook = (entity: Book, asset: string): Book => ({ ...entity, From 28c3ae97a9c8b8a45771cc396d2d3516b26c1518 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 12:27:39 -0700 Subject: [PATCH 06/68] docs(environment): specify and record the state-target changes Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/plan.md | 14 +++++ .../agent-environments/state-targets/spec.md | 45 +++++++++++++++ .../agent-environments/state-targets/tasks.md | 10 ++++ .../state-targets/verification.md | 56 +++++++++++++++++++ 4 files changed, 125 insertions(+) create mode 100644 docs/specs/agent-environments/state-targets/plan.md create mode 100644 docs/specs/agent-environments/state-targets/spec.md create mode 100644 docs/specs/agent-environments/state-targets/tasks.md create mode 100644 docs/specs/agent-environments/state-targets/verification.md diff --git a/docs/specs/agent-environments/state-targets/plan.md b/docs/specs/agent-environments/state-targets/plan.md new file mode 100644 index 00000000000..30f95099828 --- /dev/null +++ b/docs/specs/agent-environments/state-targets/plan.md @@ -0,0 +1,14 @@ +# Implementation plan + +1. **Read-only POSTs.** A module decides once per extraction which POST tools only read, used by the write filter, + init cutoffs and the write simulation. +2. **Adoption.** The write simulation tracks held entities and writes no built plan models, and takes an unseen + entity at its first successful item read. +3. **Linked creates.** A module links a POST's returned id to the state type it is first read under; the extraction + cuts that type's initial window at the POST, and the create plan records the read's collection. +4. **Rewrite cuts.** The merge reports the spans behind a type's rewrite; the extraction cuts the type's initial window + at the earliest write within them and plans once more. +5. **Variant lines.** A module classifies request lines by the members their objects show; plans drop variants, views + name them with their query keys, and serving and the write gate replay calls that match. +6. **Tests and docs.** Each step's tests fail on the step before; the state-view, state-writes, list-queries and + write-coverage specs and the environment docs describe the new behaviour. diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md new file mode 100644 index 00000000000..f35faba421c --- /dev/null +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -0,0 +1,45 @@ +# Give more write tools a state target + +Issue: https://github.com/morluto/rea/issues/4933 + +## Outcome + +Across the 50 published capture-built environments, 91 of 195 write tools got no state target: the gate refused them +before looking at their evidence, because their path named no state type, item or document. A diagnosis traced each to +its cause in the recordings and the code. The five largest shared causes: + +- **Read-only POSTs counted as writes.** A lookup, an RPC tunnel naming read operations, or a session refresh was + planned as an unserved write and cut initial windows. +- **Entities a write the gate does not model made.** A later read of such an entity failed its check instead of + holding it, so writes to it stayed unobserved. +- **Creates read under another path.** A create whose path is no state type (`POST /Playlists` read as `/Items/{Id}`) + had no target, and its entity leaked into the initial state of the type it is read under. +- **Types whose reads disagree across an unrelated write.** Every view of the type stayed replayed. +- **Request lines that show entities in another form.** An extra query parameter that adds or drops members + (`?counts=true`, `?expand=`, `?fields=`) failed the whole view. + +## Behaviour + +- **Read-only calls.** A POST is not a state write when its response repeats the latest read of its path with no + write between, it tunnels only read operations, its path's last meaningful word names a lookup, or it renews a + session; it is replayed. It stays a write when a related read line changes across one of its calls. +- **Adopted entities.** A successful item read of an entity the gate's copy never held, after a write no built plan + models, puts the entity into the copy; an entity a modelled write touched is never taken back. +- **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first + names an id its response returned, when the id is new; serving creates in that read's collection. A successful POST + that returned an id a type's reads only show after it ends that type's initial window. +- **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at + the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. +- **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's + checks and the entity observations, and the view names it with the query keys that pick it out + (`projected_query_keys`, on item and list views). A call matching those keys replays its recording, so it does not + show served writes; a 400, 404 or 410 on such a line is still evidence. A filter role whose name matches no field + needs two agreeing values. + +## Acceptance + +- Over the 50 published captures, write tools with no state target fall from 91 to 61 and served write tools rise from + 46 to 61, with none lost; every served write tool applies. +- Read calls recorded before the first write that state serving answers keep matching their recordings; each newly + state-backed view answers them as recorded, except where replay itself does not. +- The Grafana and Mailpit environments no longer hold, in their initial state, entities their captures created. diff --git a/docs/specs/agent-environments/state-targets/tasks.md b/docs/specs/agent-environments/state-targets/tasks.md new file mode 100644 index 00000000000..890980ae40e --- /dev/null +++ b/docs/specs/agent-environments/state-targets/tasks.md @@ -0,0 +1,10 @@ +# Tasks + +- [x] Keep read-only POSTs out of the write list. +- [x] Take an entity a write no plan models made when a read first shows it. +- [x] Plan a create into the type its returned id is read under, and cut that type's initial window. +- [x] End a type's initial reads at the write its reads disagree across. +- [x] Replay request lines that show entities in another form. +- [x] Add tests that fail on the step before each change. +- [x] Measure the 50 published captures, the served smoke and the serving of recorded reads after each step. +- [x] Run static, formatting, duplication, documentation and test gates. diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md new file mode 100644 index 00000000000..e9429098885 --- /dev/null +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -0,0 +1,56 @@ +# Verification + +Executed on macOS with Node v22.23.1, one change at a time on main, over the 50 published capture-built environments +(each app's latest capture). The served smoke rebuilds each manifest with the tree under test and applies every served +write tool; the serving check answers every recorded read made before the capture's first write through state serving +and compares it with the recording. + +## Gates + +- `npm run build:cached`, `npm run check:fast` (typecheck and lint, no new warnings in the changed files), + `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and + `npm run mcp-catalog:check`: passed. +- `npm run jscpd`: 3.45% duplicated lines over 4028 files. +- `npx vitest run --project domain --project services`: 8788 passed, 6 pre-existing skips. +- `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve + and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and + tool schema validity: 8 files, 88 passed. + +## Measurements + +| Step | Write tools | Served | No state target | State-backed read views | Recorded reads matching | +| --------------- | ----------- | ------ | --------------- | ----------------------- | ----------------------- | +| main | 195 | 46 | 91 | 1,098 | 1,833 of 1,886 | +| read-only POSTs | 189 | 46 | 84 | 1,104 | 1,911 of 1,964 | +| adoption | 189 | 47 | 84 | 1,104 | 1,911 of 1,964 | +| linked creates | 189 | 48 | 80 | 1,105 | 1,911 of 1,964 | +| rewrite cuts | 189 | 51 | 77 | 1,110 | 1,922 of 1,975 | +| variant lines | 189 | 61 | 61 | 1,150 | 2,068 of 2,126 | + +The served smoke applies every served write tool at each step. No read view loses its state backing, and no served +write tool is lost. + +- **Read-only POSTs:** six tools leave the write list (Mattermost `members/ids`, Miniflux `discover`, NocoDB's two + internal tunnels, Paperless `selection_data`, PocketBase `auth-refresh`); Paperless's notes create gains a target. + Grafana's `query-history` stays a write. Nomad `jobs/statuses` repeats its GET, but its integers exceed JSON's + exact range, so it stays a write. +- **Adoption:** Grocy's product delete is served; Mealie's recipe delete moves from no observation to unconfirmed. +- **Linked creates:** Jellyfin's item delete is served; its playlist create and item update, and Mailpit's send, gain + targets. Grafana's `/api/search` and Mailpit's messages no longer hold the dashboard and message their captures + created. +- **Rewrite cuts:** Tandoor's recipe create, update and delete are served. +- **Variant lines:** Baserow's row create, update and delete, Keycloak's user delete, Miniflux's category create and + update, PocketBase's create, update and delete, and Vikunja's task delete are served. Ghost's post create and update, + Keycloak's user update, Miniflux's category delete, n8n's tag create and Vikunja's task update gain targets. + +Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five +(Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged +Paperless document list answers all five documents, a PocketBase item without `expand` answers without it, and a +NetBox `site_id` filter learned from one line is not adopted. + +## Not included + +- Making a value that differs between two request lines volatile: it contradicts the spec's distinct query strings and + made 11 recorded reads answer otherwise than replay. +- Item actions (`/{type}/{id}/archive`), bulk writes at a collection path, templating literal ids by value, and + envelope masking: each needs further recording evidence or a separate change. From 48d7faee9015b5985d0e0cd75fb952f6d7a3af05 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 14:37:08 -0700 Subject: [PATCH 07/68] fix(environment): keep a read-only POST a write when its evidence is incomplete Body-level container operations are skipped like query ones, a lookup is named only by the path's last literal segment and never alongside a write word, a tool with a redirected or unanswered call is not reclassified, and the mutation veto is resolved over all candidates at once so another read-only call cannot explain a read change. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 5 +- .../agent-environments/state-writes/spec.md | 37 ++++---- .../environmentStateQueryCalls.test.ts | 86 ++++++++++++++++++- .../environmentStateQueryCalls.ts | 79 +++++++++++------ 4 files changed, 160 insertions(+), 47 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index f35faba421c..fe3dd6baa25 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -21,8 +21,9 @@ its cause in the recordings and the code. The five largest shared causes: ## Behaviour - **Read-only calls.** A POST is not a state write when its response repeats the latest read of its path with no - write between, it tunnels only read operations, its path's last meaningful word names a lookup, or it renews a - session; it is replayed. It stays a write when a related read line changes across one of its calls. + write between, it tunnels only read operations, its last literal segment names a lookup and no write, or it renews + a session; it is replayed. It stays a write when one of its calls was redirected or unanswered, or when a related + read line changes across one of its calls with no write but other read-only calls between. - **Adopted entities.** A successful item read of an entity the gate's copy never held, after a write no built plan models, puts the entity into the copy; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index d13c0a56aa7..5212838472e 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -43,24 +43,29 @@ search. The capture shows it by the first of these that applies: path did, with no write between (a status lookup posting the jobs it names); 2. every call names read operations only, in its body's `operation` or `operations[].operation`, else its query's `operation`, `op` or `action` - (`batch` and similar only wrap them); an operation reads when its words name - one of `list`, `get`, `count`, `aggregate`, `info`, `search`, `find`, `read`, - `query`, `schema`, `describe`, `fetch` or `lookup`, and none of `create`, - `insert`, `update`, `delete`, `remove`, `upsert`, `add`, `set`, `save` and - similar; -3. a path segment's last meaningful word, split on `_`, `-`, `.` and case and - skipping trailing `data`, `info` and `results`, is a query word (`search`, - `query`, `list`, `find`, `lookup`, `count`, `aggregate`, `stats`, `ids`, - `selection`, `discover`, …): `selection_data` names a lookup, while - `query-history` names a history and stays a write; -4. a path segment renews or opens a session: `auth-refresh`, + (`batch` and similar only wrap them, in either place, so a call needs at + least one other); an operation reads when its words name one of `list`, + `get`, `count`, `aggregate`, `info`, `search`, `find`, `read`, `query`, + `schema`, `describe`, `fetch` or `lookup`, and none of `create`, `insert`, + `update`, `delete`, `remove`, `upsert`, `add`, `set`, `save` and similar; +3. the path's last literal segment has a query word as its last meaningful + word, split on `_`, `-`, `.` and case and skipping trailing `data`, `info` + and `results` (`search`, `query`, `list`, `find`, `lookup`, `count`, + `aggregate`, `stats`, `ids`, `selection`, `discover`, …), and no write word: + `selection_data` names a lookup, while `query-history` names a history, + `create_lookup` a create and `selection_data/import` an import, and each + stays a write; +4. the path's last literal segment renews or opens a session: `auth-refresh`, `auth-with-password`, `login`, `logout`, `refresh` or `token`. -A tool stays a write when a `GET` line whose path its call's path relates to -(segment by segment, a parameter matching any value) reads differently just -before and just after one of its calls with no other write between. Reads of -unrelated paths do not count, so a session renewal stays read-only although an -endpoint under the same root regenerates values on every read. +A tool stays a write when one of its calls was redirected or went unanswered, +since nothing shows what it did. It also stays a write when a `GET` line whose +path its call's path relates to (segment by segment, a parameter matching any +value) reads differently just before and just after one of its calls with no +other write between; the other read-only tools' calls are no writes there, so +the tools are dropped until none is vetoed. Reads of unrelated paths do not +count, so a session renewal stays read-only although an endpoint under the +same root regenerates values on every read. **Effects.** Each plan classifies its tool: diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index 9f789bc0ba1..82ed0f1ae3b 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -11,7 +11,7 @@ interface Call { readonly method: string; readonly path: string; readonly query?: string; - readonly status?: number; + readonly status?: number | null; readonly response?: JsonValue; readonly request?: JsonValue; readonly tool: string; @@ -25,7 +25,7 @@ const readOnlyOf = (calls: readonly Call[]): string[] => { method: call.method, path: call.path, query: call.query, - status: call.status ?? 200, + status: call.status === undefined ? 200 : call.status, start: index, end: index, })); @@ -106,6 +106,23 @@ describe("POSTs that read state", () => { expect(readOnlyOf([queried])).toEqual(["post_rpc"]); }); + it("skips a container operation in the body as in the query, still needing a real read", () => { + const rpc = (request: JsonValue): Call => ({ + method: "POST", + path: "/rpc", + tool: "post_rpc", + request, + response: {}, + }); + const batch = (operation: string): JsonValue => ({ + operation: "batch", + operations: [{ operation }], + }); + expect(readOnlyOf([rpc(batch("getUser"))])).toEqual(["post_rpc"]); + expect(readOnlyOf([rpc(batch("createUser"))])).toEqual([]); + expect(readOnlyOf([rpc({ operation: "batch" })])).toEqual([]); + }); + it("reads a POST whose path names a lookup word, split on underscores, hyphens and case", () => { const post = (path: string, tool: string, template = path): Call => ({ method: "POST", @@ -144,6 +161,28 @@ describe("POSTs that read state", () => { ).toEqual(["post_search_results", "post_selection"]); }); + it("reads a lookup only by the last literal segment, so a trailing write action stays a write", () => { + const post = (path: string, tool: string, template = path): Call => ({ + method: "POST", + path, + template, + tool, + response: {}, + }); + expect( + readOnlyOf([ + post("/api/documents/selection_data/import", "post_import"), + post("/api/saved-query/create", "post_saved_query"), + post("/api/views/create_lookup", "post_create_lookup"), + post( + "/api/lookup_data/users", + "post_lookup", + "/api/lookup_data/{kind}", + ), + ]), + ).toEqual(["post_lookup"]); + }); + it("reads a session renewal, not a create in the same collection tree", () => { const post = (path: string, tool: string): Call => ({ method: "POST", @@ -158,7 +197,9 @@ describe("POSTs that read state", () => { ]), ).toEqual(["post_auth_refresh"]); }); +}); +describe("POSTs that read state but stay writes", () => { it("keeps a lookup-named POST a write when a read its path relates to changes across it alone", () => { const read = (members: string[]): Call => ({ method: "GET", @@ -185,4 +226,45 @@ describe("POSTs that read state", () => { "post_ids", ]); }); + + it("keeps a lookup-named POST a write when only another read-only POST sits between it and a changed read", () => { + const read = (members: string[]): Call => ({ + method: "GET", + path: "/api/members", + tool: "get_members", + response: members, + }); + const post: Call = { + method: "POST", + path: "/api/members/ids", + tool: "post_ids", + response: ["a"], + }; + const refresh: Call = { + method: "POST", + path: "/api/collections/_superusers/auth-refresh", + tool: "post_auth_refresh", + response: { token: "x" }, + }; + expect(readOnlyOf([read(["a"]), post, refresh, read(["a", "b"])])).toEqual([ + "post_auth_refresh", + ]); + expect(readOnlyOf([read(["a"]), refresh, post, read(["a", "b"])])).toEqual([ + "post_auth_refresh", + ]); + }); + + it("keeps a POST a write when one of its calls was redirected or went unanswered", () => { + const post = (status: number | null): Call => ({ + method: "POST", + path: "/api/members/ids", + tool: "post_ids", + status, + response: ["a"], + }); + expect(readOnlyOf([post(200), post(302)])).toEqual([]); + expect(readOnlyOf([post(200), post(null)])).toEqual([]); + // A refused call changed nothing, so it does not hold the tool. + expect(readOnlyOf([post(200), post(400)])).toEqual(["post_ids"]); + }); }); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 419789289f9..cbfb1dd6a28 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -93,25 +93,36 @@ export interface QueryCallIo { const succeeded = (record: StateRecordFacts): boolean => record.status !== null && record.status >= 200 && record.status < 300; +/** A call that may have changed state without a 2xx answer saying what it did: redirected or unanswered. */ +const unresolved = (record: StateRecordFacts): boolean => + isStateWrite(record) && !succeeded(record); + +/** The names among these that are operations rather than containers wrapping them. */ +const realOperations = (names: readonly (JsonValue | undefined)[]): string[] => + names.filter( + (name): name is string => + typeof name === "string" && !OPERATION_CONTAINERS.has(name.toLowerCase()), + ); + /** The operations an RPC call names: its body's `operation` or `operations[].operation`, else its query's, containers aside. */ const operationsOf = ( record: StateRecordFacts, body: JsonValue | undefined, ): string[] => { const named = isObject(body) - ? [ + ? realOperations([ body.operation, ...(Array.isArray(body.operations) ? body.operations.map((entry) => isObject(entry) ? entry.operation : undefined, ) : []), - ].filter((name): name is string => typeof name === "string") + ]) : []; if (named.length > 0) return named; const query = new URLSearchParams(record.query ?? ""); - return OPERATION_PARAMETERS.flatMap((name) => query.getAll(name)).filter( - (name) => !OPERATION_CONTAINERS.has(name.toLowerCase()), + return realOperations( + OPERATION_PARAMETERS.flatMap((name) => query.getAll(name)), ); }; @@ -127,8 +138,9 @@ const readsOnly = (operation: string): boolean => { /** * POST tools whose recorded calls read state rather than change it, by the strongest evidence that * applies: a response repeating the latest read of the same path with no write between, an RPC - * tunnel naming only read operations, a path word naming a lookup, or a session segment. A tool - * is kept a write when a read line its path relates to changes across one of its calls. + * tunnel naming only read operations, a last path word naming a lookup, or a session segment. A + * tool with a redirected or unanswered call stays a write, as does one a read line its path relates + * to changes across, no write but the other read-only tools' calls between. */ export const readOnlyTools = ( tools: readonly StateToolFacts[], @@ -138,33 +150,44 @@ export const readOnlyTools = ( const position = new Map( records.map((record, index) => [record.ordinal, index]), ); - const readOnly = new Set(); + const writesBetween = + (skip: ReadonlySet) => + (from: number, to: number): boolean => + records + .slice(from + 1, to) + .some((record) => !skip.has(record.ordinal) && isStateWrite(record)); + const candidates = new Map(); for (const tool of tools) { if ( tool.method !== "POST" || !changesState(tool.method, tool.path_template) ) continue; - const own = new Set(tool.record_ordinals); const calls = tool.record_ordinals .map((ordinal) => records[position.get(ordinal) ?? -1]) .filter((record): record is StateRecordFacts => record !== undefined); - if (!calls.some(succeeded)) continue; - const between = (from: number, to: number): boolean => - records - .slice(from + 1, to) - .some((record) => !own.has(record.ordinal) && isStateWrite(record)); - const evidence = + if (!calls.some(succeeded) || calls.some(unresolved)) continue; + const between = writesBetween(new Set(tool.record_ordinals)); + if ( repeatsRead(calls, records, { position, between, io }) || namesReadOperations(calls, io) || - namesLookup(tool.path_template); - if ( - evidence && - !changesReadsAcross(calls, records, { position, between, io }) + namesLookup(tool.path_template) ) - readOnly.add(tool.name); + candidates.set(tool.name, calls); + } + // No candidate's call explains a read change across another's, so drop vetoed candidates until none is. + for (let vetoed = true; vetoed;) { + const between = writesBetween( + new Set([...candidates.values()].flat().map((call) => call.ordinal)), + ); + vetoed = false; + for (const [name, calls] of candidates) + if (changesReadsAcross(calls, records, { position, between, io })) { + candidates.delete(name); + vetoed = true; + } } - return readOnly; + return new Set(candidates.keys()); }; interface Timeline { @@ -205,14 +228,16 @@ const namesReadOperations = ( return operations.length > 0 && operations.every(readsOnly); }); -/** A path segment names a lookup by its last meaningful word, or is a session segment. */ -const namesLookup = (template: string): boolean => - segmentsOf(template).some( - (segment) => - !isParam(segment) && - (SESSION_SEGMENTS.has(segment.toLowerCase()) || - QUERY_WORDS.has(lastMeaningfulWord(segment) ?? "")), +/** The path's last literal segment is a session segment, or names a lookup by its last meaningful word and no write word. */ +const namesLookup = (template: string): boolean => { + const last = segmentsOf(template).findLast((segment) => !isParam(segment)); + if (last === undefined) return false; + return ( + SESSION_SEGMENTS.has(last.toLowerCase()) || + (QUERY_WORDS.has(lastMeaningfulWord(last) ?? "") && + !words(last).some((word) => WRITE_OPERATION_WORDS.has(word))) ); +}; /** A segment's last word that is not a trailing neutral word: `selection_data` names a selection, `query-history` a history. */ const lastMeaningfulWord = (segment: string): string | undefined => From 5d48df7bfc2f7a69fdd843ffa333b25233b39e27 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 14:48:04 -0700 Subject: [PATCH 08/68] fix(environment): answer a field selection only when the state shows it exactly Serving tests a field selection before any variant key: a projection value a replayed read gave, or one no checked line gave other than `*`, replays. A list sets aside a line asking for some fields only before the identity proof, and a dropped variant's membership change no longer rewrites the type. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 14 ++--- .../agent-environments/state-targets/spec.md | 10 ++-- .../agent-environments/state-view/spec.md | 22 ++++---- .../agent-environments/write-coverage/spec.md | 8 +-- docs/web-network-captures.md | 3 +- .../environment/environmentStateAnswer.ts | 32 ++++++++---- .../environmentStateWriteAnswer.test.ts | 44 ++++++++++++++++ .../EnvironmentStateExtraction.ts | 34 +++++++----- .../analysisView/environmentStateRules.ts | 2 +- .../analysisView/environmentStateVariants.ts | 40 ++++++++------ .../analysisView/environmentStateView.ts | 2 +- .../environmentStateWrites.test.ts | 52 +++++++++++++++++++ 12 files changed, 200 insertions(+), 63 deletions(-) diff --git a/docs/agent-environments.md b/docs/agent-environments.md index 3a32320aa04..772f6c397c9 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -422,12 +422,12 @@ member reports which applied: Each read tool answers according to its view in the state: -| View | Answer | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`, except that a call matching one of the view's `projected_query_keys` replays its recording. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | -| `list` | When the arguments name one of the lines the view checked exactly (its latest recordings before the first related write; every path and query value equal to the recording's, and every recorded query parameter supplied), that recorded envelope with its array rendered from the state: every entity of the collection in state order for `membership: "all"` or a line `all_record_ordinals` names, or the recorded members still held. A call with no query argument answers from such a line of the collection its path arguments name that only pages its list, with `replay.exact_match` false. On a line the view's `query` answers, and for a call whose every query argument has a role there (an argument-less call aside), the answer is the query evaluated over the state: filtered, searched, sorted and paged, with counters at the number listed and `query.totals` at the number matched, and `state.membership: "query"`; such a call answers on a query or whole line of its collection with `replay.exact_match` false. A value an `inert` parameter never recorded, a parameter without a role, or a call matching one of the view's `projected_query_keys`, replays its recording. A member lacking a field every recording carried makes the call a tool error rather than a partial list. | -| `document` | When the arguments name the document's checked line exactly, the state's value for it; a tool error when the state holds none. | -| `recorded` | The recording, as replay answers it. | +| View | Answer | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`, except that a call matching one of the view's `projected_query_keys`, or on a view with `projected_record_ordinals` asking for some fields only with a value other than `*` no checked line gave or one a replayed read gave, replays its recording. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | +| `list` | When the arguments name one of the lines the view checked exactly (its latest recordings before the first related write; every path and query value equal to the recording's, and every recorded query parameter supplied), that recorded envelope with its array rendered from the state: every entity of the collection in state order for `membership: "all"` or a line `all_record_ordinals` names, or the recorded members still held. A call with no query argument answers from such a line of the collection its path arguments name that only pages its list, with `replay.exact_match` false. On a line the view's `query` answers, and for a call whose every query argument has a role there (an argument-less call aside), the answer is the query evaluated over the state: filtered, searched, sorted and paged, with counters at the number listed and `query.totals` at the number matched, and `state.membership: "query"`; such a call answers on a query or whole line of its collection with `replay.exact_match` false. A value an `inert` parameter never recorded, a parameter without a role, a call matching one of the view's `projected_query_keys`, or a field selection the checked lines do not show (as for `item`), replays its recording. A member lacking a field every recording carried makes the call a tool error rather than a partial list. | +| `document` | When the arguments name the document's checked line exactly, the state's value for it; a tool error when the state holds none. | +| `recorded` | The recording, as replay answers it. | An item or list view that always spells a clock field otherwise than the entity's stored value names that spelling in `clock_formats`, and a value it @@ -438,7 +438,7 @@ A list or document call that names no checked line, including a line recorded after a write or with other query values, answers from the recording. Every answer has the replay shape plus `state`: `{"source": "state", "view": …}` naming the entity, collection or document path, or `{"source": "recording", -"reason": …}` with the view's reason, `no-view`, `unrecorded-request`, `page-exceeded` (a call naming a page of a whole list that the collection has outgrown), `projection` (a call to an item tool whose recordings asked for some fields only, naming such a parameter for an entity the state holds, or a call matching a `projected_query_keys` key that asks for some fields only) or `variant` (a call matching another `projected_query_keys` key: a parameter, or a value of one, only lines showing the entities in another representation named, or leaving out a parameter every other line named). A `projection` or `variant` answer is a recording, so it does not show served writes. A +"reason": …}` with the view's reason, `no-view`, `unrecorded-request`, `page-exceeded` (a call naming a page of a whole list that the collection has outgrown), `projection` (a call to an item or list tool with replayed reads asking for a selection of fields the checked lines do not show, or leaving out a projection parameter every checked line names) or `variant` (a call matching another `projected_query_keys` key: a parameter, or a value of one, only lines showing the entities in another representation named, or leaving out a parameter every other line named). A `projection` or `variant` answer is a recording, so it does not show served writes. A state answer carries the base record's status, content type and `replay` provenance with `truncated: false`; one whose JSON would exceed 256 KiB is refused as a `resource_constraint` tool error rather than cut. Extraction does diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index fe3dd6baa25..9ede7ca82dc 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -32,10 +32,12 @@ its cause in the recordings and the code. The five largest shared causes: - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's - checks and the entity observations, and the view names it with the query keys that pick it out - (`projected_query_keys`, on item and list views). A call matching those keys replays its recording, so it does not - show served writes; a 400, 404 or 410 on such a line is still evidence. A filter role whose name matches no field - needs two agreeing values. + checks, the entity observations and the membership changes that cut a type's initial window, and the view names it + with the query keys that pick it out (`projected_query_keys`, on item and list views). Beside a line showing whole + entities, a list line asking for some fields only is set aside before the identity proof the same way. A call + matching those keys replays its recording, so it does not show served writes; a 400, 404 or 410 on such a line is + still evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line + gave, and no replayed read gave it. A filter role whose name matches no field needs two agreeing values. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 7ec35ea748a..3a218dac665 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -34,23 +34,27 @@ later increments. every listed item carries distinctly, which needs at least one listed item. An item read that asked for some fields only (`fields`, `fields[...]`, `select`, `$select`) and does not return the item is left out of the proof - and of the view's checks; the view lists it in `projected_record_ordinals`, - and serving replays any call to that tool that names a projection parameter - for an entity the state holds. The write gate also leaves out any read that - names one and leaves out a field its view requires. + and of the view's checks; the view lists it in `projected_record_ordinals`. + Beside a line showing whole entities, a list line asking for some fields only + is listed there too, and proves no identity or membership. On a view with + such replayed reads, serving replays a call naming a projection parameter for + an entity the state holds unless every value it gives is `*` or one a checked + line gave, and no replayed read gave it. The write gate also leaves out any + read that names one and leaves out a field its view requires. - A request line of an item or list view is a representation variant when it shows an entity another line shows with other members, or names a parameter the base lines do not (paging aside) while its objects carry a member no base - object carries or lack one every base object carries; a list line asking for - some fields only is one whenever a base line does not. Base lines are taken + object carries or lack one every base object carries. Base lines are taken first: lines naming no such parameter, then lines asking for every field, - then the line most others agree with. A variant leaves the view's checks and - the entity observations when a query key tells it apart: a parameter only + then the line most others agree with. A variant leaves the view's checks, the + entity observations and the membership changes that would end the type's + initial reads when a query key tells it apart: a parameter only variants name, a value no base line gives a parameter, or a parameter every base line names that a variant leaves out. The view lists its latest recordings in `projected_record_ordinals` and the keys in `projected_query_keys`; serving replays a call matching a key with the reason - `variant` (`projection` when the key asks for some fields only), so the + `variant` (`projection` when it leaves out a projection parameter every base + line names; a projection value is tested as above), so the answer is a recording and shows no served write. The write gate neither checks nor learns from a successful read matching a key; a 400, 404 or 410 such a read answers is still the absence it checks. diff --git a/docs/specs/agent-environments/write-coverage/spec.md b/docs/specs/agent-environments/write-coverage/spec.md index 6f0f25f56e6..a8641915df6 100644 --- a/docs/specs/agent-environments/write-coverage/spec.md +++ b/docs/specs/agent-environments/write-coverage/spec.md @@ -36,9 +36,11 @@ what the writes did: Identity-free projection evidence after the initial-state cutoff is retained too, without seeding later values into initial entities. Failed responses are classified before the projection-replay shortcut, so a projected absence can confirm a delete or contradict an unexplained disappearance. - A list line asking for some fields only, and any item or list line showing its entities in another representation - (an expanding or reducing query), is replayed the same way when a query key tells it from the view's other lines - (`projected_query_keys`, reason `variant`); such calls replay recordings and do not show served writes. + A list line asking for some fields only beside one showing whole entities is replayed the same way and proves no + identity or membership; an item or list line showing its entities in another representation (an expanding or + reducing query) is replayed when a query key tells it from the view's other lines (`projected_query_keys`, reason + `variant`). A call asking for some fields only replays unless every value it gives is `*` or one a checked line + gave, and no replayed read gave it; such calls replay recordings and do not show served writes. - **Sequences.** A sequence value may be `-`-separated digit groups of one width of at least two digits, not a date, version or address. The next value keeps the exemplar's groups and zero padding; digits that outgrow them lead. A later create must record its value spelled that way. A held value whose digits outgrew the mask (`100-00` after diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index 0dca008f805..7e36a2655df 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -620,7 +620,8 @@ entities in another representation (an expanding or reducing query, or one asking for some fields only) is left out of those checks when a query key tells it from the others: the plan lists its latest recordings in `projected_record_ordinals` and the keys in `projected_query_keys` (`name`, -with a `value` or `absent: true`), and serving replays calls matching them. +with a `value` or `absent: true`), and serving replays calls matching them and +calls asking for fields the checked lines do not show. Otherwise the tool is a recorded view with reason `envelope-varies`, `fields-differ` or `list-differs`; the other reasons are `query-body` (a query `POST`, or one the capture shows only reading), `no-init-recording`, diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 55690dfa0a4..dadb16ceeff 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -21,7 +21,10 @@ import { type StateView, } from "../../domain/analysisView/environmentStateRules.js"; import { pageBound } from "../../domain/analysisView/environmentStatePaging.js"; -import { matchesReplayKey } from "../../domain/analysisView/environmentStateVariants.js"; +import { + matchesReplayKey, + selectsOtherFields, +} from "../../domain/analysisView/environmentStateVariants.js"; import { isAbsence } from "../../domain/analysisView/environmentStateWriteChecks.js"; import { evaluateQuery, @@ -150,17 +153,28 @@ const fromRecording = ( /** Why a call replays the view's replayed reads (`projection` for some fields only, `variant` for another representation), or undefined when the state answers it. */ const replayedCall = ( + source: EnvironmentSource, view: StateItemView | StateListView, call: ReadonlyMap, ): "projection" | "variant" | undefined => { if (view.projected_record_ordinals === undefined) return undefined; - const keys = view.projected_query_keys; - if (keys === undefined || keys.length === 0) - return view.shape === "item" && [...call.keys()].some(isProjectionParameter) - ? "projection" - : undefined; const values = new Map([...call].map(([name, value]) => [name, [value]])); - const matched = keys.filter((key) => matchesReplayKey([key], values)); + const queries = (ordinals: readonly number[]) => + ordinals.map((ordinal) => source.exchanges.get(ordinal)?.query); + // A field selection is tested on its own: a variant key cannot name every value the checked lines do not show. + if ( + selectsOtherFields( + values, + queries(view.checked_record_ordinals), + queries(view.projected_record_ordinals), + ) + ) + return "projection"; + const matched = (view.projected_query_keys ?? []).filter( + (key) => + (key.absent === true || !isProjectionParameter(key.name)) && + matchesReplayKey([key], values), + ); if (matched.length === 0) return undefined; return matched.some((key) => isProjectionParameter(key.name)) ? "projection" @@ -315,7 +329,7 @@ const answerItem = ( id: call.id, }); // A projection or another representation of an entity the state holds replays as the capture's reads did. - const replayed = replayedCall(view, callQuery(tool, args)); + const replayed = replayedCall(source, view, callQuery(tool, args)); if (replayed !== undefined) return fromRecording(source, tool, args, replayed); const shown = shownEntity( @@ -487,7 +501,7 @@ const answerCheckedLine = ( ): Result => { const replayed = view.shape === "list" - ? replayedCall(view, callQuery(tool, args)) + ? replayedCall(serving.source, view, callQuery(tool, args)) : undefined; if (replayed !== undefined) return fromRecording(serving.source, tool, args, replayed); diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 77785907b71..1181f44d158 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -321,6 +321,50 @@ describe("wider write coverage", () => { }); }); +describe("field selections beside replayed reads", () => { + it("replays a field selection no checked line gave, and answers a selection of every field from the state", () => { + const books = servedFrom([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1?fields=*", FIRST_BOOK], + ["GET", "/api/books/2?fields=*", SECOND_BOOK], + ["GET", "/api/books/2?fields=name", { name: "Second Book" }], + ]); + expect( + books.answer("get_books_by_id", { id: "1", fields: "id" }), + ).toMatchObject({ state: { source: "recording", reason: "projection" } }); + expect( + books.answer("get_books_by_id", { id: "1", fields: "*" }), + ).toMatchObject({ + body: FIRST_BOOK, + state: { source: "state", view: "item" }, + }); + }); + + it("replays a field selection a replayed read gave, beside a variant key and a checked line giving it too", () => { + // One read asking for a book's name answered it whole; another left the id out. + const books = servedFrom([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/1?fields=name", FIRST_BOOK], + ["GET", "/api/books/2?fields=name", { name: "Second Book" }], + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ]); + expect( + books.answer("get_books_by_id", { id: "2", fields: "name" }), + ).toMatchObject({ + body: { name: "Second Book" }, + state: { source: "recording", reason: "projection" }, + }); + expect( + books.answer("get_books_by_id", { id: "1", expand: "shelf" }), + ).toMatchObject({ state: { source: "recording", reason: "variant" } }); + expect(books.answer("get_books_by_id", { id: "2" })).toMatchObject({ + body: SECOND_BOOK, + state: { source: "state", view: "item" }, + }); + }); +}); + describe("write coverage limits", () => { it("numbers past a mask's width again after the state is saved and loaded", () => { const books = servedFrom([ diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index ee4a1ca5376..9f544914cc8 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -194,10 +194,11 @@ export class EnvironmentStateExtraction { return candidates; } - /** Leave each plan's representation variants to replay: out of its lines and the observed entities. */ + /** Leave each plan's representation variants to replay: out of its lines, the observed entities and the membership changes. */ #dropVariants(): void { const shapes = lineShapes(this.#entities.values()); this.#retain(ENTRY_BYTES * (shapes.size + 1)); + const dropped = new Set(); for (const [index, plan] of this.#plans.entries()) { const split = withoutVariants(plan, { shapeOf: (record) => shapes.get(record.ordinal), @@ -208,7 +209,9 @@ export class EnvironmentStateExtraction { this.#retain(ENTRY_BYTES * (split.dropped.size + 2)); this.#plans[index] = split.plan; dropObservations(this.#entities, split.dropped); + for (const ordinal of split.dropped) dropped.add(ordinal); } + this.#spans = this.#spans.filter((span) => !dropped.has(span.later)); } /** End each rewritten type's initial reads at the earliest write its reads disagree across, and clear the plans to make them again. */ @@ -494,8 +497,11 @@ export class EnvironmentStateExtraction { */ #planList(candidate: Candidate): void { const { tool, type } = candidate; - const recordings = this.#initRecordingsOf(candidate); - if (recordings === undefined) return; + const initial = this.#initRecordingsOf(candidate); + if (initial === undefined) return; + // Beside a line showing whole entities, one asking for some fields only is replayed and proves nothing. + const whole = initial.filter((record) => !projectsFields(record.query)); + const recordings = whole.length > 0 ? whole : initial; const proved = this.#identity.get(type)?.field; const fieldsOf = (items: readonly JsonObject[]): string[] => proved === undefined @@ -545,7 +551,15 @@ export class EnvironmentStateExtraction { if (field === undefined || pointer === undefined) return; if (!this.#identity.has(type)) this.#identity.set(type, { field, basis: "field-name" }); - this.#addPlan(candidate, pointer, recordings); + this.#retain(ENTRY_BYTES * (initial.length - recordings.length)); + this.#addPlan( + candidate, + pointer, + recordings, + initial + .filter((record) => !recordings.includes(record)) + .map((record) => record.ordinal), + ); } #observePlan(plan: StatePlan): void { @@ -598,18 +612,12 @@ export class EnvironmentStateExtraction { for (const object of objects) if (!previous.ids.delete(scalarText(object[field])!)) changed = true; if (previous.ids.size > 0) changed = true; - if ( - earlier !== undefined && - changed && - this.#writeWithin(earlier, record) - ) { - this.#rewritten.add(plan.type); + if (earlier !== undefined && changed && this.#writeWithin(earlier, record)) this.#spans.push({ type: plan.type, earlier: earlier.ordinal, later: record.ordinal, }); - } previous.ids.clear(); for (const object of objects) previous.ids.add(scalarText(object[field])!); previous.record = record; @@ -655,7 +663,7 @@ export class EnvironmentStateExtraction { }); } - /** A change across any recorded write rewrites the type; one between repeats of a line with no write is volatile. */ + /** A change across any recorded write, in values or in a kept line's membership, rewrites the type; one between repeats of a line with no write is volatile. */ #classifyChanges(): void { const recordOf = (observation: StateObservation): StateRecordFacts => this.#byOrdinal.get(observation.ordinal)!; @@ -664,8 +672,8 @@ export class EnvironmentStateExtraction { (observation) => [observation.tool, requestLine(recordOf(observation))], (earlier, later) => this.#writeWithin(recordOf(earlier), recordOf(later)), ); - for (const type of changes.rewritten) this.#rewritten.add(type); this.#spans.push(...changes.spans); + for (const { type } of this.#spans) this.#rewritten.add(type); for (const [type, names] of changes.volatile) this.#volatile.set(type, names); } diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 285fd9bcd8b..939d408640e 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -118,7 +118,7 @@ export interface ReplayKey { interface ReplayedReads { /** Reads that asked for some fields only, or show entities in another representation than the checked lines. */ readonly projected_record_ordinals?: number[] | undefined; - /** A call whose query matches one of these replays; absent on views that only left out projections. */ + /** A call whose query matches one of these replays, a field selection by its values; absent on views that only left out projections. */ readonly projected_query_keys?: ReplayKey[] | undefined; } diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 60be63da09b..44832d39bba 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -2,6 +2,7 @@ import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js import type { StatePlan } from "./environmentStateGate.js"; import type { ObservedEntity } from "./environmentStateMerge.js"; import { + isProjectionParameter, projectsFields, type ReplayKey, type StateRecordFacts, @@ -102,7 +103,6 @@ const conflicts = (left: LineShape, right: LineShape): boolean => export const variantLines = ( latest: readonly StateRecordFacts[], shapeOf: (record: StateRecordFacts) => LineShape | undefined, - list: boolean, ): StateRecordFacts[] => { if (latest.length < 2) return []; const shape = (record: StateRecordFacts): LineShape => @@ -132,31 +132,21 @@ export const variantLines = ( const base: StateRecordFacts[] = []; const variants: StateRecordFacts[] = []; for (const record of ordered) { - if (base.length > 0 && isVariant(record, base, { shape, list })) + if (base.length > 0 && isVariant(record, base, shape)) variants.push(record); else base.push(record); } return variants; }; -/** Whether a line shows a base line's entity with other members, asks a list for some fields only, or names a new shaping parameter while its objects carry or lack members the base lines do not. */ +/** Whether a line shows a base line's entity with other members, or names a new shaping parameter while its objects carry or lack members the base lines do not. */ const isVariant = ( record: StateRecordFacts, base: readonly StateRecordFacts[], - facts: { - readonly shape: (record: StateRecordFacts) => LineShape; - readonly list: boolean; - }, + shape: (record: StateRecordFacts) => LineShape, ): boolean => { - const { shape, list } = facts; const mine = shape(record); if (base.some((line) => conflicts(mine, shape(line)))) return true; - if ( - list && - projectsFields(record.query ?? undefined) && - base.some((line) => !projectsFields(line.query ?? undefined)) - ) - return true; const baseNames = new Set(base.flatMap((line) => shapingNames(line.query))); if (!shapingNames(record.query).some((name) => !baseNames.has(name))) return false; @@ -235,6 +225,26 @@ export const matchesReplayKey = ( : call.get(key.name)?.includes(key.value) === true, ); +/** Whether a call asks for a selection of fields the checked lines do not show exactly: a projection value a replayed line gave, or one no checked line gave other than `*`. */ +export const selectsOtherFields = ( + call: ReadonlyMap, + checked: readonly (string | null | undefined)[], + replayed: readonly (string | null | undefined)[], +): boolean => { + const [base, other] = [checked.map(queryValues), replayed.map(queryValues)]; + const gave = (lines: Map[], name: string, value: string) => + lines.some((values) => values.get(name)?.includes(value) === true); + return [...call].some( + ([name, values]) => + isProjectionParameter(name) && + values.some( + (value) => + gave(other, name, value) || + (value !== "*" && !gave(base, name, value)), + ), + ); +}; + const requestLine = (record: StateRecordFacts): string => record.path + (record.query ?? ""); @@ -249,7 +259,7 @@ export const withoutVariants = ( ): | { readonly plan: StatePlan; readonly dropped: ReadonlySet } | undefined => { - const found = variantLines(plan.latest, facts.shapeOf, !plan.item); + const found = variantLines(plan.latest, facts.shapeOf); const unkeyed = plan.latest.filter((record) => !found.includes(record)); const variants = found.filter( (record) => diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 83cff6eb961..04c798d019f 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -136,7 +136,7 @@ const replayedReadFields = { ) .optional() .describe( - "Query keys that pick calls of the replayed reads out: a parameter only they name, a value only they give a parameter, or (absent) a parameter every checked line names and they leave out. A call matching any key replays.", + "Query keys that pick calls of the replayed reads out: a parameter only they name, a value only they give a parameter, or (absent) a parameter every checked line names and they leave out. A call matching any key replays; a projection parameter's value is tested on its own: a call replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it.", ), }; const viewSchema = z.discriminatedUnion("shape", [ diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 268dc67ae1d..33dbfe52e70 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1505,3 +1505,55 @@ describe("creates read under another path", () => { ); }); }); + +describe("lines left to replay", () => { + it("plans a list past a line that asks for some fields only and leaves the proved id out", () => { + const created = book(3, "Third Book", bookClock(4)); + const state = stateOf([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + [ + "GET", + "/api/books?fields=name", + [{ name: "First Book" }, { name: "Second Book" }], + ], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["POST", "/api/books", created, 201, { name: "Third Book" }], + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK, created]], + ]); + expect(state.views.find((view) => view.tool === "get_books")).toMatchObject( + { + shape: "list", + checked_record_ordinals: [0], + projected_record_ordinals: [1], + projected_query_keys: [{ name: "fields" }], + }, + ); + expect(planOf(state, "post_books")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + + it("keeps a list's whole line when only a replayed line's membership changed across a write", () => { + // The expanded line lists shelved books only; the whole list still shows both after the export. + const view = stateOf([ + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + [ + "GET", + "/api/books?expand=shelf", + [FIRST_BOOK, SECOND_BOOK].map(expandedBook), + ], + ["POST", "/api/exports", { queued: true }, 202, { format: "csv" }], + ["GET", "/api/books?expand=shelf", [expandedBook(FIRST_BOOK)]], + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ]).views.find((candidate) => candidate.tool === "get_books"); + expect(view).toMatchObject({ + shape: "list", + checked_record_ordinals: [5], + projected_record_ordinals: [4], + projected_query_keys: [{ name: "expand" }], + }); + }); +}); From ce2301d263138de9871faed04b3ed174a3db5c19 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 14:50:43 -0700 Subject: [PATCH 09/68] fix(environment): hold adopted entities and linked creates to what the recording shows An adopted entity is charged against the view's budget like a created one. A linked create holds only for its exemplar's path arguments: serving refuses others and the gate counts such a call as unmodelled. A response's identity-named id links at any length, but a short one only to a type read before the call. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 10 +- .../agent-environments/state-view/spec.md | 6 +- .../agent-environments/state-writes/spec.md | 23 ++-- .../environmentStateWriteAnswer.test.ts | 43 +++++++ .../environmentStateWriteAnswer.ts | 38 +++++- .../EnvironmentStateWriteSimulation.test.ts | 32 +++++ .../EnvironmentStateWriteSimulation.ts | 7 +- .../environmentStateWriteAdoption.ts | 14 ++- .../environmentStateWriteCreate.ts | 20 +++- .../environmentStateWriteLinks.ts | 113 ++++++++++++++---- .../environmentStateWrites.test.ts | 81 +++++++++++++ 11 files changed, 337 insertions(+), 50 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 9ede7ca82dc..ae129d9340d 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -25,10 +25,12 @@ its cause in the recordings and the code. The five largest shared causes: a session; it is replayed. It stays a write when one of its calls was redirected or unanswered, or when a related read line changes across one of its calls with no write but other read-only calls between. - **Adopted entities.** A successful item read of an entity the gate's copy never held, after a write no built plan - models, puts the entity into the copy; an entity a modelled write touched is never taken back. -- **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first - names an id its response returned, when the id is new; serving creates in that read's collection. A successful POST - that returned an id a type's reads only show after it ends that type's initial window. + models, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken + back. +- **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names + an id its response returned, when the id is new; serving creates in that read's collection, for the exemplar's path + arguments only. A successful POST that returned an id a type's reads only show after it ends that type's initial + window. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 3a218dac665..1c978e56838 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -27,8 +27,10 @@ later increments. `POST` is not a write, a read overlapping the write is left out, and a write whose URL was redacted bounds every type, with a limitation counting it. A successful `POST` elsewhere bounds a type's state too when its response named - an id (four characters or more) that the type's reads show only after it: the - `POST` made that entity, so it is not in the initial state. + an id (an identity member, or a bare or sole scalar of four characters or + more) that the type's reads show only after it: the `POST` made that entity, + so it is not in the initial state. An id shorter than four characters counts + only when the type was read before the `POST` and an item read names it after. - Prove an item type's identity field from the requested path value its responses repeat; otherwise infer it from a fixed list of identity names that every listed item carries distinctly, which needs at least one listed item. diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 5212838472e..244b9bf3f32 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -78,13 +78,16 @@ same root regenerates values on every read. | `none` | anything else | reason `no-state-target` | A `POST` whose path gives it no target is a `create` into the type its returned -id is read under: its exemplar's response names an id (a scalar, an identity -member, a sole member, or an identity member of an object member, four -characters or more), and the first later successful item read naming that id -belongs to a state type. The entity must be new: neither the initial state nor -any earlier read holds that id. The plan records that read's collection, and -serving creates there, since the call's own path names no collection of the -type. +id is read under: its exemplar's response names an id (an identity member of the +body or of an object member, or a scalar body or sole member of four characters +or more), and the first later successful item read naming that id belongs to a +state type. The entity must be new: neither the initial state nor any earlier +read holds that id. An id shorter than four characters may be any type's, so it +links only to a type a successful read showed before the call. The plan records +that read's collection, and serving creates there, since the call's own path +names no collection of the type. That collection holds only for the exemplar's +path arguments: serving refuses a call with others, and the gate counts such a +recorded call as a write no built plan models. **Exemplar.** A plan is built from its first successful (2xx) recorded call, the exemplar. @@ -272,12 +275,14 @@ of a write. A write no built plan models can also make an entity the copy never held, such as a row an import or a nested create added: a write of a tool with no create, -update, delete or document plan, or a call of a tool whose plan was never built. +update, delete or document plan, a call of a tool whose plan was never built, or +a linked create's call that serving would refuse. A successful item read of an entity the copy has never held (no initial entity, and none a modelled write created, changed or removed) that names it by the type's identity, when such a write ran since that entity or its collection was last checked, shows that entity: the copy takes its recorded values instead of -failing the read, and later writes to it are modelled and checked as usual. An +failing the read, and later writes to it are modelled and checked as usual. The +taken entity counts against the view's budget as a created one does. An entity a modelled write touched is never taken back this way, and a built plan's call that serving would not apply, such as a create outside its tied collection, keeps its evidence. diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 1181f44d158..f44f1f1a500 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1648,4 +1648,47 @@ describe("creates read under another path", () => { expect(notes.answer("get_notes_by_id", { id: "1003" }).body).toEqual(delta); expect(notes.answer("get_notes").body).toEqual([alpha, beta, delta]); }); + + it("refuses a linked create called with other path arguments than its recording sent", () => { + const note = (id: number, title: string) => ({ id, title }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const notes = servedFrom([ + ["GET", "/api/projects/11/notes", [alpha, beta]], + ["GET", "/api/projects/11/notes/1001", alpha], + ["GET", "/api/projects/11/notes/1002", beta], + [ + "POST", + "/api/projects/11/publish", + { id: 1003 }, + 201, + { title: "Gamma" }, + ], + ["GET", "/api/projects/11/notes/1003", gamma], + ["GET", "/api/projects/11/notes", [alpha, beta, gamma]], + ]); + const before = notes.snapshot(); + // No read showed where project 12's publish creates, so it is not put into project 11. + expect( + notes.refusal("post_projects_publish_by_id", { + id: "12", + body: { title: "Delta" }, + }), + ).toMatchObject({ + code: "invalid_request", + message: expect.stringContaining( + "creates into /api/projects/11/notes only with the path arguments its recording sent", + ), + }); + expect(notes.snapshot()).toBe(before); + expect( + notes.answer("post_projects_publish_by_id", { + id: "11", + body: { title: "Delta" }, + }), + ).toMatchObject({ status: 201 }); + }); }); diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index fceed4cab8a..b1aa71065ba 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -14,7 +14,10 @@ import { nextInteger, } from "../../domain/analysisView/environmentStateWriteExplain.js"; import { callRenewal } from "../../domain/analysisView/environmentStateWriteGenerated.js"; -import { linkedCollection } from "../../domain/analysisView/environmentStateWriteLinks.js"; +import { + linkedCollection, + sameLinkedSource, +} from "../../domain/analysisView/environmentStateWriteLinks.js"; import { pathValuesOf, type GeneratedRule, @@ -276,6 +279,33 @@ const writeAnswer = ( return stateAnswer(serving, { exchange, exact }, body.value ?? null, state); }; +/** The collection a create writes into: a linked plan's, only for its exemplar's path arguments, else the one the call's path selects. */ +const writtenCollection = ( + serving: StateServing, + request: WriteRequest, + call: WriteCall, +): Result => { + const { tool, plan } = request; + const linked = linkedCollection(plan, tool.path_template); + if (linked === undefined) + return ok( + createdCollection(serving, tool, request.args, plan.target ?? ""), + ); + const exemplar = + plan.exemplar_ordinal === null + ? undefined + : serving.source.exchanges.get(plan.exemplar_ordinal); + // No read showed where other path arguments create. + return sameLinkedSource(tool.path_template, exemplar?.path, call.pathValues) + ? ok(linked) + : err( + refused( + tool, + `Tool ${tool.name} creates into ${linked} only with the path arguments its recording sent.`, + ), + ); +}; + const answerCreate = ( serving: StateServing, request: WriteRequest, @@ -284,9 +314,9 @@ const answerCreate = ( const { tool, plan } = request; const type = plan.target ?? ""; const idField = serving.store.type(type)?.id_field ?? ""; - const collection = - linkedCollection(plan, tool.path_template) ?? - createdCollection(serving, request.tool, request.args, plan.target ?? ""); + const target = writtenCollection(serving, request, call); + if (!target.ok) return target; + const collection = target.value; const observed = observedEntity(serving, plan); if (collection === undefined || observed === undefined) return err( diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index 516507befad..dc74f56aa58 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -25,6 +25,8 @@ import { itemTarget, SimulatedState, } from "./environmentStateWriteChecks.js"; +import { UnseenEntities } from "./environmentStateWriteAdoption.js"; +import type { StateItemView } from "./environmentStateRules.js"; import { laterObservation, type ObservationSearch, @@ -2250,6 +2252,36 @@ describe("entities an unmodelled write made", () => { }); }); + it("counts an entity it takes against the view's allowance", () => { + let retained = 0; + const read = { ...THIRD_BOOK, notes: "x".repeat(10_000) }; + const unseen = new UnseenEntities([], { + state: new SimulatedState([], []), + io: { + withBody: (_ordinal, use) => use(read), + retain: (bytes) => (retained += bytes), + }, + lastCheck: new Map(), + idField: () => "id", + }); + unseen.unplanned(0); + retained = 0; + const view = { shape: "item", type: "/api/books", pointer: "" }; + const record = { + ordinal: 1, + method: "GET", + path: "/api/books/3", + query: undefined, + status: 200, + start: 1, + end: 1, + }; + expect( + unseen.adopt(view as unknown as StateItemView, { record, index: 1 }), + ).toMatchObject({ id: "3", fields: read }); + expect(retained).toBeGreaterThan(20_000); + }); + it("takes back no book a modelled delete removed, so a list showing it again confirms no delete", () => { expect( gated(deletedAfterRead([RENAME, IMPORT]), "delete_books_by_id"), diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 4ac63b0e7ad..142472be987 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -254,8 +254,11 @@ export class EnvironmentStateWriteSimulation { if (!observeOnly) draft.calls += 1; const step: WriteStep = { record, index, tool, observeOnly }; const result = APPLY[effect](this.#context(tool.name), draft, step); - // A call of a tool whose plan was never built is no more modelled than one of a tool without a plan. - if (result.kind === "unknown" && !built(draft)) + // A call of a tool whose plan was never built, or one a linked plan does not place, is no more modelled than one of a tool without a plan. + if ( + result.kind === "unknown" && + (!built(draft) || draft.linked !== undefined) + ) this.#unseen.unplanned(index); this.#settle(result, { index, diff --git a/src/domain/analysisView/environmentStateWriteAdoption.ts b/src/domain/analysisView/environmentStateWriteAdoption.ts index 89bd83d8e74..23a2a88dd9f 100644 --- a/src/domain/analysisView/environmentStateWriteAdoption.ts +++ b/src/domain/analysisView/environmentStateWriteAdoption.ts @@ -1,6 +1,8 @@ +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; import { at, isObject, + jsonBytes, scalarText, type StateEntity, type StateRecordFacts, @@ -30,7 +32,7 @@ export class UnseenEntities { initial: readonly StateEntity[], private readonly facts: { readonly state: SimulatedState; - readonly io: Pick; + readonly io: Pick; readonly lastCheck: ReadonlyMap; readonly idField: (type: string) => string | undefined; }, @@ -44,11 +46,15 @@ export class UnseenEntities { /** Note an entity a modelled write created, changed or removed, which no read takes back. */ touched(entity: Pick): void { - this.#held.add(entityTarget(entity.type, entity.collection, entity.id)); + const key = entityTarget(entity.type, entity.collection, entity.id); + if (this.#held.has(key)) return; + this.facts.io.retain(ENTRY_BYTES + textBytes(key.length)); + this.#held.add(key); } /** Note a successful write no built plan models. */ unplanned(index: number): void { + this.facts.io.retain(ENTRY_BYTES); this.#unplannedAt.push(index); } @@ -91,6 +97,10 @@ export class UnseenEntities { view_fields: [], record_ordinals: [], }; + // The copy keeps the read's object, which the body's own reservation no longer covers. + this.facts.io.retain( + ENTRY_BYTES * 4 + textBytes(key.length) + jsonBytes(object), + ); state.put(entity); this.#held.add(key); return entity; diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 6fa0df4dfb6..06a4e9b83ab 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -13,6 +13,7 @@ import { type SuppliedSegment, } from "./environmentStateRules.js"; import { createdFields } from "./environmentStateWriteApply.js"; +import { sameLinkedSource } from "./environmentStateWriteLinks.js"; import { collectionTarget, entityTarget, @@ -301,6 +302,20 @@ const servedCollection = ( : selectedCollection(segments, createCandidates(context, type)); }; +/** Whether a linked create's call sends the source path values its exemplar did, the only ones its link holds for. */ +const fromLinkedSource = ( + context: EffectContext, + draft: WriteDraft, + step: WriteStep, +): boolean => + sameLinkedSource( + step.tool.path_template, + context.records.find( + (record) => record.ordinal === draft.plan.exemplar_ordinal, + )?.path, + pathValuesOf(step.tool.path_template, step.record.path), + ); + /** Add a created entity to the state at the plan's insert position, or last before the plan has one. */ const insertCreated = ( context: EffectContext, @@ -332,10 +347,11 @@ export const applyCreate = ( // Serving writes a create into the collection it chooses for the path, and a tied plan refuses any other, so a create there is not counted. const collection = draft.linked ?? servedCollection(context, step, type) ?? spelled; + // A linked plan's collection holds only for its exemplar's source path, so serving refuses any other. if ( built(draft) && - draft.plan.collection !== null && - draft.plan.collection !== collection + ((draft.plan.collection !== null && draft.plan.collection !== collection) || + (draft.linked !== undefined && !fromLinkedSource(context, draft, step))) ) return UNKNOWN; const body = requestObject(context, step.record); diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 0e5cf6d00df..83d17cca75c 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -13,9 +13,12 @@ import { type StateToolFacts, type StateView, } from "./environmentStateRules.js"; -import type { WriteEffect } from "./environmentStateWriteRules.js"; +import { + pathValuesOf, + type WriteEffect, +} from "./environmentStateWriteRules.js"; -/** The shortest id that names one entity rather than counting one. */ +/** The shortest id that names one entity rather than counting one, or naming one of any type. */ const MIN_ID_LENGTH = 4; const succeeded = (record: StateRecordFacts): boolean => @@ -31,23 +34,24 @@ const identityValues = (object: JsonValue | undefined): string[] => : []; /** - * The ids a write's response names for an entity it made, long enough to name one: a scalar body, - * an identity-named or sole scalar member, or an identity-named member of an object member (an envelope). + * The ids a write's response names for an entity it made: an identity-named member of the body or of + * an object member (an envelope) at any length, or a scalar body or sole scalar member long enough to name one. */ export const respondedIds = (body: JsonValue | undefined): string[] => { if (body === undefined || body === null) return []; - const ids: string[] = []; - if (!isObject(body)) { - const value = scalarText(body); - if (value !== undefined) ids.push(value); - } else { - ids.push(...identityValues(body)); - const members = Object.values(body); - const sole = members.length === 1 ? scalarText(members[0]) : undefined; - if (sole !== undefined) ids.push(sole); - for (const member of members) ids.push(...identityValues(member)); - } - return [...new Set(ids)].filter((id) => id.length >= MIN_ID_LENGTH); + const named = (value: JsonValue | undefined): string[] => { + const text = scalarText(value); + return text !== undefined && text.length >= MIN_ID_LENGTH ? [text] : []; + }; + if (!isObject(body)) return named(body); + const members = Object.values(body); + return [ + ...new Set([ + ...identityValues(body), + ...(members.length === 1 ? named(members[0]) : []), + ...members.flatMap(identityValues), + ]), + ]; }; /** The identity-named scalar values a read's body shows at any depth, or its path's id for an item read. */ @@ -71,6 +75,40 @@ const shownIds = ( return shown; }; +/** One read of a type: where it ran, whether it reads one item, and the ids it shows. */ +interface ShownRead { + readonly at: number; + readonly item: boolean; + readonly ids: ReadonlySet; +} + +/** + * The ids a POST at `at` made that a type's reads show only after it, before `end`. A short id may be + * any type's, so it counts only when the type was read before the POST and an item read names it after. + */ +const freshIds = ( + ids: readonly string[], + shown: readonly ShownRead[], + at: number, + end: number, +): string[] => { + const seen = shown.some((read) => read.at < at); + return ids.filter((id) => { + const short = id.length < MIN_ID_LENGTH; + return ( + (!short || seen) && + !shown.some((read) => read.at < at && read.ids.has(id)) && + shown.some( + (read) => + read.at > at && + read.at < end && + (!short || read.item) && + read.ids.has(id), + ) + ); + }); +}; + /** A successful POST and the ids its response named. */ export interface CreatedIds { readonly record: StateRecordFacts; @@ -125,7 +163,7 @@ export const creationLimit = ( ? [{ tool, item: read.item }] : []; }); - const shown = readers.flatMap(({ tool, item }) => + const shown: ShownRead[] = readers.flatMap(({ tool, item }) => tool.record_ordinals.flatMap((ordinal) => { const record = reads.records.get(ordinal); return record === undefined || !succeeded(record) @@ -133,6 +171,7 @@ export const creationLimit = ( : [ { at: reads.position(record), + item, ids: shownIds(record, item, () => reads.body(ordinal)), }, ]; @@ -143,12 +182,8 @@ export const creationLimit = ( )) { const at = reads.position(creation.record); if (at >= end) break; - const fresh = creation.ids.filter( - (id) => - !shown.some((read) => read.at < at && read.ids.has(id)) && - shown.some((read) => read.at > at && read.at < end && read.ids.has(id)), - ); - if (fresh.length > 0) return creation.record; + if (freshIds(creation.ids, shown, at, end).length > 0) + return creation.record; } return undefined; }; @@ -156,7 +191,8 @@ export const creationLimit = ( /** * The state type and collection a POST whose path names none creates into: that of the first later * successful item read naming an id its first successful call returned, when neither the initial - * state nor any earlier read held that id. + * state nor any earlier read held that id. A short id may be any type's, so it links only to a type + * read before the call. */ export const linkedCreate = (input: { readonly tool: StateToolFacts; @@ -193,7 +229,18 @@ export const linkedCreate = (input: { const held = input.entities.some( (entity) => entity.type === view.type && entity.id === id, ); - return held + const unseen = + id.length < MIN_ID_LENGTH && + !records.slice(0, first).some((earlier) => { + const read = input.viewOf(earlier.ordinal); + return ( + earlier.method === "GET" && + succeeded(earlier) && + (read?.shape === "item" || read?.shape === "list") && + read.type === view.type + ); + }); + return held || unseen ? undefined : { type: view.type, collection: collectionPathOf(record, true) }; } @@ -216,6 +263,22 @@ export const linkedCollection = ( ? plan.collection : undefined; +/** Whether a linked create's call sends the path values its exemplar did: the read that linked its target followed only that call. */ +export const sameLinkedSource = ( + template: string, + exemplar: string | undefined, + call: ReadonlyMap | undefined, +): boolean => { + const recorded = + exemplar === undefined ? undefined : pathValuesOf(template, exemplar); + return ( + recorded !== undefined && + call !== undefined && + recorded.size === call.size && + [...recorded].every(([name, value]) => call.get(name) === value) + ); +}; + /** A write's effect and target, where a POST its path gives no target becomes a create into the type its returned id is first read under. */ export const linkedTarget = ( tool: StateToolFacts, diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 33dbfe52e70..e2aa8d3ef90 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1488,6 +1488,87 @@ describe("creates read under another path", () => { ); }); + /** A create linked under project 11, then a call for project 12, whose note a later item read and delete show. */ + const otherProject = (): TimedCaptureRow[] => { + const D = note(1004, "Delta"); + return [ + ["GET", "/api/projects/11/notes", [A, B]], + ["GET", "/api/projects/11/notes/1001", A], + ["GET", "/api/projects/11/notes/1002", B], + [ + "POST", + "/api/projects/11/publish", + { id: 1003 }, + 201, + { title: "Gamma" }, + ], + ["GET", "/api/projects/11/notes/1003", C], + ["GET", "/api/projects/11/notes", [A, B, C]], + ["POST", "/api/projects/12/publish", D, 201, { title: "Delta" }], + ["GET", "/api/projects/12/notes/1004", D], + ["GET", "/api/projects/11/notes", [A, B, C]], + ["DELETE", "/api/projects/12/notes/1004", "", 204], + ["GET", "/api/projects/12/notes/1004", { error: "Not found" }, 404], + ]; + }; + + it("puts no linked create's call that sends other path arguments into the linked collection", () => { + // Project 12's note never reaches project 11, so the later read of project 11 confirms the create. + expect( + planOf(stateOf(otherProject()), "post_projects_publish_by_id"), + ).toMatchObject({ + served: true, + collection: "/api/projects/11/notes", + checked_record_ordinals: [5], + contradicted_by: null, + }); + }); + + it("takes the entity such a call made when a read first shows it", () => { + expect( + planOf(stateOf(otherProject()), "delete_projects_notes_by_id_id_2"), + ).toMatchObject({ served: true, checked_record_ordinals: [10] }); + }); + + it("links a create whose response names a short id under an identity member", () => { + const [one, two, three] = [ + note(1, "Alpha"), + note(2, "Beta"), + note(3, "Gamma"), + ]; + const rows = (response: JsonValue): TimedCaptureRow[] => [ + ["GET", "/api/notes", [one, two]], + ["GET", "/api/notes/1", one], + ["GET", "/api/notes/2", two], + ["POST", "/api/drafts/publish", response, 201, { title: "Gamma" }], + ["GET", "/api/notes/3", three], + ["GET", "/api/notes", [one, two, three]], + ]; + expect( + planOf(stateOf(rows({ id: 3 })), "post_drafts_publish"), + ).toMatchObject({ effect: "create", target: "/api/notes", served: true }); + // A bare or unnamed short scalar may count rather than name, so it links nothing. + for (const response of [3, { created: 3 }]) + expect( + planOf(stateOf(rows(response)), "post_drafts_publish"), + ).toMatchObject({ effect: "none", reason: "no-state-target" }); + }); + + it("links a short id to no type that no read showed before the call", () => { + // Another type's id 1 may be the one the call returned, so the notes keep their initial reads. + const [one, two] = [note(1, "Alpha"), note(2, "Beta")]; + const state = stateOf([ + ["POST", "/api/imports", { id: 1 }, 201, { source: "csv" }], + ["GET", "/api/notes/1", one], + ["GET", "/api/notes", [one, two]], + ]); + expect(planOf(state, "post_imports")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + expect(notesOf(state)).toEqual(["1", "2"]); + }); + it("links no create whose returned id the initial state holds", () => { const held = stateOf([ ["GET", "/api/notes", [A, B, C]], From 6656816dd6c6410ecec90cd50dd88a239cad59d5 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 14:58:24 -0700 Subject: [PATCH 10/68] docs(environment): record the review fixes' measurements Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/verification.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index e9429098885..93ae2ff3dd4 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -10,8 +10,8 @@ and compares it with the recording. - `npm run build:cached`, `npm run check:fast` (typecheck and lint, no new warnings in the changed files), `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and `npm run mcp-catalog:check`: passed. -- `npm run jscpd`: 3.45% duplicated lines over 4028 files. -- `npx vitest run --project domain --project services`: 8788 passed, 6 pre-existing skips. +- `npm run jscpd`: 3.49% duplicated lines over 4055 files. +- `npx vitest run --project domain --project services`: 8962 passed, 6 pre-existing skips. - `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 88 passed. @@ -26,6 +26,7 @@ and compares it with the recording. | linked creates | 189 | 48 | 80 | 1,105 | 1,911 of 1,964 | | rewrite cuts | 189 | 51 | 77 | 1,110 | 1,922 of 1,975 | | variant lines | 189 | 61 | 61 | 1,150 | 2,068 of 2,126 | +| review fixes | 189 | 61 | 61 | 1,151 | 2,075 of 2,133 | The served smoke applies every served write tool at each step. No read view loses its state backing, and no served write tool is lost. @@ -42,6 +43,9 @@ write tool is lost. - **Variant lines:** Baserow's row create, update and delete, Keycloak's user delete, Miniflux's category create and update, PocketBase's create, update and delete, and Vikunja's task delete are served. Ghost's post create and update, Keycloak's user update, Miniflux's category delete, n8n's tag create and Vikunja's task update gain targets. +- **Review fixes:** no write verdict changes. A NocoDB records list whose `fields` line had rejected it becomes + state-backed, and all 7 of its recorded reads match. Without its guard, a short id would cut 23 Tandoor views' + initial windows at a `POST /api/view-log/` returning `{"id":1}`. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 22e27b1f13c5a05e20a846af17e26ddf070b2294 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 16:33:01 -0700 Subject: [PATCH 11/68] fix(environment): release a discarded planning pass before planning again A rewrite cut clears the first pass, so the budget rewinds to a checkpoint taken after the write cutoffs and created ids before the state is extracted again. Rewrite spans are charged and appended without spreading them into an argument list. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-view/spec.md | 3 +- .../EnvironmentStateAccumulator.ts | 1 + .../EnvironmentStateExtraction.ts | 16 ++++++-- .../WebNetworkProjectionAccumulator.ts | 8 ++++ .../analysisView/environmentStateRules.ts | 2 + .../analysisView/environmentStateView.test.ts | 37 +++++++++++++++++++ 6 files changed, 62 insertions(+), 5 deletions(-) diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 1c978e56838..be5406c9d94 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -94,7 +94,8 @@ later increments. semantics and write effects. - Charge the manifest's admission and grouping, every record line, every body as temporary bytes before decoding and parsing, and every kept value, within - the existing 96 MiB budget. + the existing 96 MiB budget. A planning pass that a rewrite cut discards + releases its charges before the state is extracted again. - Read response bodies through one domain owner shared with replay, and parse exact JSON through the owner of the exact-number policy. diff --git a/src/domain/analysisView/EnvironmentStateAccumulator.ts b/src/domain/analysisView/EnvironmentStateAccumulator.ts index fdb9d001f45..4d73d7da0d3 100644 --- a/src/domain/analysisView/EnvironmentStateAccumulator.ts +++ b/src/domain/analysisView/EnvironmentStateAccumulator.ts @@ -327,6 +327,7 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator requestBody: (ordinal) => this.#requestBody(ordinal), emptyResponse: (ordinal) => this.#emptyResponse(ordinal), retain: (bytes) => this.retain(bytes), + checkpoint: () => this.retainedCheckpoint(), release: () => this.releaseTemporary(), }, }).run(); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 9f544914cc8..d23512b3b66 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -98,7 +98,7 @@ export class EnvironmentStateExtraction { readonly #bases: ReadonlyMap; #writeCutoffs: StateWriteCutoffs | undefined; readonly #initLimits = new Map(); - /** Successful POSTs with the ids their responses named, read once on first use. */ + /** Successful POSTs with the ids their responses named, read once before planning. */ #created: CreatedIds[] | undefined; readonly #identity = new Map< string, @@ -153,7 +153,7 @@ export class EnvironmentStateExtraction { run(): ExtractedState | null { try { this.#findWrites(); - if (this.#writes.length > 0) + if (this.#writes.length > 0) { this.#writeCutoffs = new StateWriteCutoffs( this.#writes, this.#bases, @@ -162,8 +162,15 @@ export class EnvironmentStateExtraction { this.#position.get(right.ordinal)!, (bytes) => this.#retain(bytes), ); + this.#creations(); + } + // A rewrite cut discards the first planning pass, so what it retained is released before the second. + const release = this.#budget.checkpoint(); let candidates = this.#plan(); - if (this.#cutRewrites()) candidates = this.#plan(); + if (this.#cutRewrites()) { + release(); + candidates = this.#plan(); + } const gate = this.#gateContext(); for (const plan of this.#plans) if (this.#rewritten.has(plan.type)) @@ -672,7 +679,8 @@ export class EnvironmentStateExtraction { (observation) => [observation.tool, requestLine(recordOf(observation))], (earlier, later) => this.#writeWithin(recordOf(earlier), recordOf(later)), ); - this.#spans.push(...changes.spans); + this.#retain(ENTRY_BYTES * 4 * changes.spans.length); + for (const span of changes.spans) this.#spans.push(span); for (const { type } of this.#spans) this.#rewritten.add(type); for (const [type, names] of changes.volatile) this.#volatile.set(type, names); diff --git a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts index 2f9563f019e..2f37e013a09 100644 --- a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts +++ b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts @@ -47,6 +47,14 @@ export abstract class WebNetworkProjectionAccumulator { return true; } + /** Mark the retained bytes; the returned call releases what was retained since, once none of it is held. */ + protected retainedCheckpoint(): () => void { + const mark = this.#retainedBytes; + return () => { + this.#retainedBytes = Math.min(this.#retainedBytes, mark); + }; + } + /** Per-record strings and descriptors never become cumulative scratch. */ protected releaseTemporary(): void { this.#temporaryBytes = 0; diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 939d408640e..1fbbf610b37 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -44,6 +44,8 @@ export interface StateBudget { /** Whether a record's response had no body. */ readonly emptyResponse: (ordinal: number) => boolean; readonly retain: (bytes: number) => boolean; + /** Mark the retained bytes; the returned call releases what was retained since, once none of it is held. */ + readonly checkpoint: () => () => void; /** Drop the temporary work of the body just read. */ readonly release: () => void; } diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index 98f9c52bb79..ef291575f21 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -756,6 +756,43 @@ it("refuses when extraction would exceed the projection budget", () => { }); }); +it("releases a planning pass a rewrite cut discards before extracting the state again", () => { + const recipe = (id: number, views: number) => ({ + id, + name: `Recipe ${String(id)} simmered slowly with a long descriptive title`, + views, + }); + const shelf = Array.from({ length: 400 }, (_, index) => recipe(index + 1, 1)); + // Logging a view bumps the counter only when `views` changes, which cuts the type's reads at the log. + const capture = (views: number) => + captureOf([ + ["GET", "/api/recipes", shelf], + ["GET", "/api/recipes/1", recipe(1, 1)], + ["POST", "/api/view-log", { ok: true }, 200, { recipe: 1 }], + ["GET", "/api/recipes/1", recipe(1, views)], + ]); + const fits = (parent: AnalysisViewParent, bytes: number): boolean => + projectAnalysisView( + parent, + { kind: "environment-state", template_rules: [...ALL_RULES] }, + { state: new EnvironmentStateAccumulator(bytes, [...ALL_RULES]) }, + ).ok; + /** The smallest allowance, to a KiB, the capture's state projects within. */ + const allowance = (parent: AnalysisViewParent): number => { + let [low, high] = [0, 8 * 1024]; + while (high - low > 1) { + const middle = Math.floor((low + high) / 2); + if (fits(parent, middle * 1024)) high = middle; + else low = middle; + } + return high * 1024; + }; + expect(stateOf(capture(2)).types).toMatchObject([ + { collection_template: "/api/recipes", init_before_ordinal: 2 }, + ]); + expect(allowance(capture(2))).toBeLessThan(allowance(capture(1)) + 16 * 1024); +}); + it("ends every type's state at a write whose URL was redacted, and says so", () => { const parent = captureOf([ ["GET", "/api/items/1", { id: 1, title: "Granite Ledger" }], From 57029831168d4a27f9c5e2c6cad12e57382bb5f5 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 16:34:42 -0700 Subject: [PATCH 12/68] fix(environment): link no create whose id an earlier read showed, and read only whole batches A linked create is rejected when an earlier list of its type or read of its collection showed the returned id. Body ids are walked without spreading children into an argument list. An RPC call reads only when every operations entry names an operation of its own. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 6 +- .../agent-environments/state-writes/spec.md | 18 +++--- .../environmentStateQueryCalls.test.ts | 19 ++++++ .../environmentStateQueryCalls.ts | 41 ++++++++----- .../environmentStateWriteLinks.test.ts | 53 ++++++++++++++++ .../environmentStateWriteLinks.ts | 54 ++++++++++------- .../environmentStateWrites.test.ts | 60 +++++++++++++------ 7 files changed, 188 insertions(+), 63 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteLinks.test.ts diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index ae129d9340d..49d372e640c 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -28,9 +28,9 @@ its cause in the recordings and the code. The five largest shared causes: models, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names - an id its response returned, when the id is new; serving creates in that read's collection, for the exemplar's path - arguments only. A successful POST that returned an id a type's reads only show after it ends that type's initial - window. + an id its response returned, when the id is new: no earlier read of the id, its type's lists or that collection showed + it. Serving creates in that read's collection, for the exemplar's path arguments only. A successful POST that returned + an id a type's reads only show after it ends that type's initial window. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 244b9bf3f32..554e13bd649 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -44,7 +44,9 @@ search. The capture shows it by the first of these that applies: 2. every call names read operations only, in its body's `operation` or `operations[].operation`, else its query's `operation`, `op` or `action` (`batch` and similar only wrap them, in either place, so a call needs at - least one other); an operation reads when its words name one of `list`, + least one other, and every `operations` entry must name one of its own, so + an entry with no string operation or another container keeps the call a + write); an operation reads when its words name one of `list`, `get`, `count`, `aggregate`, `info`, `search`, `find`, `read`, `query`, `schema`, `describe`, `fetch` or `lookup`, and none of `create`, `insert`, `update`, `delete`, `remove`, `upsert`, `add`, `set`, `save` and similar; @@ -82,12 +84,14 @@ id is read under: its exemplar's response names an id (an identity member of the body or of an object member, or a scalar body or sole member of four characters or more), and the first later successful item read naming that id belongs to a state type. The entity must be new: neither the initial state nor any earlier -read holds that id. An id shorter than four characters may be any type's, so it -links only to a type a successful read showed before the call. The plan records -that read's collection, and serving creates there, since the call's own path -names no collection of the type. That collection holds only for the exemplar's -path arguments: serving refuses a call with others, and the gate counts such a -recorded call as a write no built plan models. +read holds that id, whether an item read of it, a list read of its type, or any +read of the item read's collection, with or without a query, whose body shows it +under an identity member. An id shorter than four characters may be any type's, +so it links only to a type a successful read showed before the call. The plan +records that read's collection, and serving creates there, since the call's own +path names no collection of the type. That collection holds only for the +exemplar's path arguments: serving refuses a call with others, and the gate +counts such a recorded call as a write no built plan models. **Exemplar.** A plan is built from its first successful (2xx) recorded call, the exemplar. diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index 82ed0f1ae3b..ff656673766 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -267,4 +267,23 @@ describe("POSTs that read state but stay writes", () => { // A refused call changed nothing, so it does not hold the tool. expect(readOnlyOf([post(200), post(400)])).toEqual(["post_ids"]); }); + + it("keeps a batch a write when one of its entries names no read operation of its own", () => { + const rpc = (operations: JsonValue): Call => ({ + method: "POST", + path: "/rpc", + tool: "post_rpc", + request: { operation: "batch", operations }, + response: {}, + }); + const read = { operation: "getUser" }; + expect(readOnlyOf([rpc([read, read])])).toEqual(["post_rpc"]); + expect(readOnlyOf([rpc([read, { method: "deleteUser" }])])).toEqual([]); + expect(readOnlyOf([rpc([read, "deleteUser"])])).toEqual([]); + expect(readOnlyOf([rpc([read, { operation: 7 }])])).toEqual([]); + expect( + readOnlyOf([rpc([read, { operation: "batch", operations: [] }])]), + ).toEqual([]); + expect(readOnlyOf([rpc({ first: read })])).toEqual([]); + }); }); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index cbfb1dd6a28..e3bb8772d59 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -97,27 +97,34 @@ const succeeded = (record: StateRecordFacts): boolean => const unresolved = (record: StateRecordFacts): boolean => isStateWrite(record) && !succeeded(record); +/** Whether a name is an operation's: a string that is no container wrapping others. */ +const isOperation = (name: JsonValue | undefined): name is string => + typeof name === "string" && !OPERATION_CONTAINERS.has(name.toLowerCase()); + /** The names among these that are operations rather than containers wrapping them. */ const realOperations = (names: readonly (JsonValue | undefined)[]): string[] => - names.filter( - (name): name is string => - typeof name === "string" && !OPERATION_CONTAINERS.has(name.toLowerCase()), - ); + names.filter(isOperation); -/** The operations an RPC call names: its body's `operation` or `operations[].operation`, else its query's, containers aside. */ +/** + * The operations an RPC call names: its body's `operation` or `operations[].operation`, else its + * query's, containers aside. Undefined when `operations` is no list or one of its entries names no + * operation of its own: no string, or another container. + */ const operationsOf = ( record: StateRecordFacts, body: JsonValue | undefined, -): string[] => { +): string[] | undefined => { + const listed = isObject(body) ? body.operations : undefined; + const entries = Array.isArray(listed) + ? listed.map((entry) => (isObject(entry) ? entry.operation : undefined)) + : []; + if ( + (listed !== undefined && !Array.isArray(listed)) || + !entries.every(isOperation) + ) + return undefined; const named = isObject(body) - ? realOperations([ - body.operation, - ...(Array.isArray(body.operations) - ? body.operations.map((entry) => - isObject(entry) ? entry.operation : undefined, - ) - : []), - ]) + ? realOperations([body.operation, ...entries]) : []; if (named.length > 0) return named; const query = new URLSearchParams(record.query ?? ""); @@ -225,7 +232,11 @@ const namesReadOperations = ( ): boolean => calls.every((call) => { const operations = operationsOf(call, io.request(call.ordinal)); - return operations.length > 0 && operations.every(readsOnly); + return ( + operations !== undefined && + operations.length > 0 && + operations.every(readsOnly) + ); }); /** The path's last literal segment is a session segment, or names a lookup by its last meaningful word and no write word. */ diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts new file mode 100644 index 00000000000..dc2c01d0522 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; + +import type { JsonValue } from "../jsonValue.js"; +import type { StateRecordFacts } from "./environmentStateRules.js"; +import { creationLimit } from "./environmentStateWriteLinks.js"; + +const record = ( + ordinal: number, + method: string, + path: string, +): StateRecordFacts => ({ + ordinal, + method, + path, + query: undefined, + status: 200, + start: ordinal, + end: ordinal, +}); + +describe("creation limits", () => { + it("reads the ids of a list body longer than a call's arguments can spread", () => { + // A million elements overflow the argument limit of a spread, here and in the test workers' larger stack. + const [list, post, later] = [ + record(0, "GET", "/api/metrics"), + record(1, "POST", "/api/imports"), + record(2, "GET", "/api/metrics"), + ]; + const bodies = new Map([ + [0, Array.from({ length: 1_000_000 }, () => 0)], + [2, [{ id: "1003" }]], + ]); + const limit = creationLimit( + [{ record: post, ids: ["1003"] }], + { + type: "/api/metrics", + tools: [ + { + name: "get_metrics", + method: "GET", + path_template: "/api/metrics", + record_ordinals: [0, 2], + }, + ], + records: new Map([list, post, later].map((at) => [at.ordinal, at])), + position: (at) => at.ordinal, + body: (ordinal) => bodies.get(ordinal), + }, + undefined, + ); + expect(limit).toBe(post); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 83d17cca75c..507a7ff766d 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -54,27 +54,29 @@ export const respondedIds = (body: JsonValue | undefined): string[] => { ]; }; -/** The identity-named scalar values a read's body shows at any depth, or its path's id for an item read. */ -const shownIds = ( - record: StateRecordFacts, - item: boolean, - body: () => JsonValue | undefined, -): Set => { - if (item) return new Set([lastSegmentValue(record.path)]); +/** The identity-named scalar values a body shows at any depth. */ +const identitiesIn = (root: JsonValue | undefined): Set => { const shown = new Set(); - const pending: JsonValue[] = []; - const root = body(); - if (root !== undefined) pending.push(root); + const pending: JsonValue[] = root === undefined ? [] : [root]; for (let next = pending.pop(); next !== undefined; next = pending.pop()) { - if (Array.isArray(next)) pending.push(...next); + // One push per child: spreading a large array would exceed the engine's argument limit. + if (Array.isArray(next)) for (const child of next) pending.push(child); else if (isObject(next)) { for (const id of identityValues(next)) shown.add(id); - pending.push(...Object.values(next)); + for (const child of Object.values(next)) pending.push(child); } } return shown; }; +/** The identity-named scalar values a read's body shows at any depth, or its path's id for an item read. */ +const shownIds = ( + record: StateRecordFacts, + item: boolean, + body: () => JsonValue | undefined, +): Set => + item ? new Set([lastSegmentValue(record.path)]) : identitiesIn(body()); + /** One read of a type: where it ran, whether it reads one item, and the ids it shows. */ interface ShownRead { readonly at: number; @@ -191,8 +193,8 @@ export const creationLimit = ( /** * The state type and collection a POST whose path names none creates into: that of the first later * successful item read naming an id its first successful call returned, when neither the initial - * state nor any earlier read held that id. A short id may be any type's, so it links only to a type - * read before the call. + * state nor any earlier read of that id, its type's lists or its collection showed that id. A short + * id may be any type's, so it links only to a type read before the call. */ export const linkedCreate = (input: { readonly tool: StateToolFacts; @@ -200,6 +202,7 @@ export const linkedCreate = (input: { readonly viewOf: (ordinal: number) => StateView | undefined; readonly entities: readonly StateEntity[]; readonly respondedIds: (ordinal: number) => readonly string[]; + readonly shownIds: (ordinal: number) => ReadonlySet; }): { readonly type: string; readonly collection: string } | undefined => { const { tool, records } = input; const own = new Set(tool.record_ordinals); @@ -226,9 +229,21 @@ export const linkedCreate = (input: { ) continue; const id = lastSegmentValue(record.path); - const held = input.entities.some( - (entity) => entity.type === view.type && entity.id === id, - ); + const collection = collectionPathOf(record, true); + const held = + input.entities.some( + (entity) => entity.type === view.type && entity.id === id, + ) || + records.slice(0, first).some((earlier) => { + const read = input.viewOf(earlier.ordinal); + return ( + earlier.method === "GET" && + succeeded(earlier) && + ((read?.shape === "list" && read.type === view.type) || + normalizedPath(earlier.path) === normalizedPath(collection)) && + input.shownIds(earlier.ordinal).has(id) + ); + }); const unseen = id.length < MIN_ID_LENGTH && !records.slice(0, first).some((earlier) => { @@ -240,9 +255,7 @@ export const linkedCreate = (input: { read.type === view.type ); }); - return held || unseen - ? undefined - : { type: view.type, collection: collectionPathOf(record, true) }; + return held || unseen ? undefined : { type: view.type, collection }; } return undefined; }; @@ -307,6 +320,7 @@ export const linkedTarget = ( viewOf: input.viewOf, entities: input.entities, respondedIds: (ordinal) => input.io.withBody(ordinal, respondedIds), + shownIds: (ordinal) => input.io.withBody(ordinal, identitiesIn), }) : undefined; return link === undefined diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index e2aa8d3ef90..f7a45cb9aca 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1427,25 +1427,26 @@ describe("types whose reads disagree across a write", () => { }); }); -describe("creates read under another path", () => { - const note = (id: number, title: string) => ({ id, title }); - const A = note(1001, "Alpha"); - const B = note(1002, "Beta"); - const C = note(1003, "Gamma"); - const notesOf = (state: StateView) => - state.entities - .filter((entity) => entity.type === "/api/notes") - .map((entity) => entity.id); - const published = (before: readonly TimedCaptureRow[]): TimedCaptureRow[] => [ - ["GET", "/api/notes", [A, B]], - ["GET", "/api/notes/1001", A], - ["GET", "/api/notes/1002", B], - ...before, - ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], - ["GET", "/api/notes/1003", C], - ["GET", "/api/notes", [A, B, C]], - ]; +const note = (id: number, title: string) => ({ id, title }); +const A = note(1001, "Alpha"); +const B = note(1002, "Beta"); +const C = note(1003, "Gamma"); +const notesOf = (state: StateView) => + state.entities + .filter((entity) => entity.type === "/api/notes") + .map((entity) => entity.id); +/** Two notes read, the given exchanges, then a POST elsewhere whose returned id the notes are read under. */ +const published = (before: readonly TimedCaptureRow[]): TimedCaptureRow[] => [ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + ...before, + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], +]; +describe("creates read under another path", () => { it("plans a POST to another path as a create into the type its returned id is first read under", () => { const state = stateOf(published([])); expect(planOf(state, "post_drafts_publish")).toMatchObject({ @@ -1587,6 +1588,29 @@ describe("creates read under another path", () => { }); }); +describe("creates whose returned id an earlier read showed", () => { + it("links no create whose returned id a list of its collection showed before it", () => { + const listed = (shown: JsonValue[]): TimedCaptureRow[] => + published([ + [ + "PATCH", + "/api/notes/1001", + note(1001, "Alpha 2"), + 200, + { title: "Alpha 2" }, + ], + ["GET", "/api/notes?include=archived", shown], + ]); + const alpha = note(1001, "Alpha 2"); + expect( + planOf(stateOf(listed([alpha, B, C])), "post_drafts_publish"), + ).toMatchObject({ effect: "none", reason: "no-state-target" }); + expect( + planOf(stateOf(listed([alpha, B])), "post_drafts_publish"), + ).toMatchObject({ effect: "create", target: "/api/notes" }); + }); +}); + describe("lines left to replay", () => { it("plans a list past a line that asks for some fields only and leaves the proved id out", () => { const created = book(3, "Third Book", bookClock(4)); From 0cf3b277b4f6d9c089fcf23dbae987c6be68c83a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 16:41:10 -0700 Subject: [PATCH 13/68] fix(environment): let the gate skip exactly the reads serving replays Serving's replay decision moves to the domain as replayReason, and the write gate uses it: a read serving replays can neither approve nor veto a write, and a read of every field beside a replayed selection is checked. A selection read missing a required field is still skipped, since part of an entity can neither confirm nor check it. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 3 +- .../agent-environments/state-view/spec.md | 7 +-- .../agent-environments/write-coverage/spec.md | 4 +- .../environment/environmentStateAnswer.ts | 36 +++------------- .../EnvironmentStateExtraction.ts | 1 + .../EnvironmentStateWriteSimulation.test.ts | 1 + .../analysisView/environmentStateVariants.ts | 39 ++++++++++++++++- .../environmentStateWriteEffects.ts | 2 + .../environmentStateWriteObserve.ts | 20 +++------ .../environmentStateWrites.test.ts | 43 +++++++++++++++++++ 10 files changed, 105 insertions(+), 51 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 49d372e640c..43abf76bbdd 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -39,7 +39,8 @@ its cause in the recordings and the code. The five largest shared causes: entities, a list line asking for some fields only is set aside before the identity proof the same way. A call matching those keys replays its recording, so it does not show served writes; a 400, 404 or 410 on such a line is still evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line - gave, and no replayed read gave it. A filter role whose name matches no field needs two agreeing values. + gave, and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same + decision. A filter role whose name matches no field needs two agreeing values. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index be5406c9d94..5f0378eefa1 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -41,8 +41,9 @@ later increments. is listed there too, and proves no identity or membership. On a view with such replayed reads, serving replays a call naming a projection parameter for an entity the state holds unless every value it gives is `*` or one a checked - line gave, and no replayed read gave it. The write gate also leaves out any - read that names one and leaves out a field its view requires. + line gave, and no replayed read gave it. The write gate leaves out exactly + the successful reads serving replays, and any read that names one and leaves + out a field its view requires, which serving would answer whole. - A request line of an item or list view is a representation variant when it shows an entity another line shows with other members, or names a parameter the base lines do not (paging aside) while its objects carry a member no base @@ -58,7 +59,7 @@ later increments. `variant` (`projection` when it leaves out a projection parameter every base line names; a projection value is tested as above), so the answer is a recording and shows no served write. The write gate neither - checks nor learns from a successful read matching a key; a 400, 404 or 410 + checks nor learns from a successful read serving replays; a 400, 404 or 410 such a read answers is still the absence it checks. - A field every recording of a view carried is required: serving refuses an entity lacking it. Once a successful read the write gate checks, naming no diff --git a/docs/specs/agent-environments/write-coverage/spec.md b/docs/specs/agent-environments/write-coverage/spec.md index a8641915df6..c02f452e3a1 100644 --- a/docs/specs/agent-environments/write-coverage/spec.md +++ b/docs/specs/agent-environments/write-coverage/spec.md @@ -31,8 +31,8 @@ what the writes did: is left out of the identity proof and the view's checks. The view lists it in `projected_record_ordinals`, and serving replays a call to that tool naming such a parameter, for an entity the state holds, with the reason `projection`; the replay shows the recording, not served writes. The write gate neither checks nor learns a write's effect from a - successful read that names such a parameter and leaves out a field its view requires; a 400, 404 or 410 such a read - answers is still the absence it checks. + successful read serving replays, nor from one that names such a parameter and leaves out a field its view requires; a + 400, 404 or 410 such a read answers is still the absence it checks. Identity-free projection evidence after the initial-state cutoff is retained too, without seeding later values into initial entities. Failed responses are classified before the projection-replay shortcut, so a projected absence can confirm a delete or contradict an unexplained disappearance. diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index dadb16ceeff..ca851a25b39 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -2,7 +2,6 @@ import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumul import { collectionMatch, collectionPathOf, - isProjectionParameter, decodedSegment, allLines, listItems, @@ -21,10 +20,7 @@ import { type StateView, } from "../../domain/analysisView/environmentStateRules.js"; import { pageBound } from "../../domain/analysisView/environmentStatePaging.js"; -import { - matchesReplayKey, - selectsOtherFields, -} from "../../domain/analysisView/environmentStateVariants.js"; +import { replayReason } from "../../domain/analysisView/environmentStateVariants.js"; import { isAbsence } from "../../domain/analysisView/environmentStateWriteChecks.js"; import { evaluateQuery, @@ -151,35 +147,17 @@ const fromRecording = ( : replayed; }; -/** Why a call replays the view's replayed reads (`projection` for some fields only, `variant` for another representation), or undefined when the state answers it. */ +/** Why a call replays the view's replayed reads, or undefined when the state answers it. */ const replayedCall = ( source: EnvironmentSource, view: StateItemView | StateListView, call: ReadonlyMap, -): "projection" | "variant" | undefined => { - if (view.projected_record_ordinals === undefined) return undefined; - const values = new Map([...call].map(([name, value]) => [name, [value]])); - const queries = (ordinals: readonly number[]) => - ordinals.map((ordinal) => source.exchanges.get(ordinal)?.query); - // A field selection is tested on its own: a variant key cannot name every value the checked lines do not show. - if ( - selectsOtherFields( - values, - queries(view.checked_record_ordinals), - queries(view.projected_record_ordinals), - ) - ) - return "projection"; - const matched = (view.projected_query_keys ?? []).filter( - (key) => - (key.absent === true || !isProjectionParameter(key.name)) && - matchesReplayKey([key], values), +): "projection" | "variant" | undefined => + replayReason( + view, + new Map([...call].map(([name, value]) => [name, [value]])), + (ordinal) => source.exchanges.get(ordinal)?.query, ); - if (matched.length === 0) return undefined; - return matched.some((key) => isProjectionParameter(key.name)) - ? "projection" - : "variant"; -}; /** A recorded body the state renders into, usable exactly when extraction could use it. */ export const recordedJson = ( diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index d23512b3b66..cf79551ab45 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -257,6 +257,7 @@ export class EnvironmentStateExtraction { requestBody: (ordinal) => this.#requestBody(ordinal), emptyResponse: (ordinal) => this.#budget.emptyResponse(ordinal), retain: (bytes) => this.#retain(bytes), + queryOf: (ordinal) => this.#byOrdinal.get(ordinal)?.query, }, }), }; diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index dc74f56aa58..d876632601c 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -1514,6 +1514,7 @@ describe("resolved encoded item observations", () => { from: 0, viewOf: () => itemView, withBody: (_ordinal, use) => use({ id: "%61", name: "After" }), + queryOf: () => undefined, }; expect(target).toEqual({ collection, id: "%61" }); diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 44832d39bba..fa50bdf4155 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -5,6 +5,8 @@ import { isProjectionParameter, projectsFields, type ReplayKey, + type StateItemView, + type StateListView, type StateRecordFacts, } from "./environmentStateRules.js"; @@ -213,7 +215,7 @@ export const replayKeys = ( }; /** Whether a call's query names a replay key: the parameter, the parameter with that value, or leaves out an absent key's parameter. */ -export const matchesReplayKey = ( +const matchesReplayKey = ( keys: readonly ReplayKey[], call: ReadonlyMap, ): boolean => @@ -226,7 +228,7 @@ export const matchesReplayKey = ( ); /** Whether a call asks for a selection of fields the checked lines do not show exactly: a projection value a replayed line gave, or one no checked line gave other than `*`. */ -export const selectsOtherFields = ( +const selectsOtherFields = ( call: ReadonlyMap, checked: readonly (string | null | undefined)[], replayed: readonly (string | null | undefined)[], @@ -245,6 +247,39 @@ export const selectsOtherFields = ( ); }; +/** Why serving replays a read call rather than answering it from the state (`projection` for some fields only, `variant` for another representation); the gate skips the same reads. */ +export const replayReason = ( + view: Pick< + StateItemView | StateListView, + | "checked_record_ordinals" + | "projected_record_ordinals" + | "projected_query_keys" + >, + call: ReadonlyMap, + queryOf: (ordinal: number) => string | null | undefined, +): "projection" | "variant" | undefined => { + if (view.projected_record_ordinals === undefined) return undefined; + // A field selection is tested on its own: a variant key cannot name every value the checked lines do not show. + if ( + [...call.keys()].some(isProjectionParameter) && + selectsOtherFields( + call, + view.checked_record_ordinals.map(queryOf), + view.projected_record_ordinals.map(queryOf), + ) + ) + return "projection"; + const matched = (view.projected_query_keys ?? []).filter( + (key) => + (key.absent === true || !isProjectionParameter(key.name)) && + matchesReplayKey([key], call), + ); + if (matched.length === 0) return undefined; + return matched.some((key) => isProjectionParameter(key.name)) + ? "projection" + : "variant"; +}; + const requestLine = (record: StateRecordFacts): string => record.path + (record.query ?? ""); diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index d75ca51775f..eafe4fed971 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -84,6 +84,7 @@ export interface WriteIo { readonly requestBody: (ordinal: number) => JsonValue | undefined; readonly emptyResponse: (ordinal: number) => boolean; readonly retain: (bytes: number) => void; + readonly queryOf: (ordinal: number) => string | null | undefined; } /** What the write gate reads: the manifest tools, the timeline, the read views and the initial state. */ @@ -218,6 +219,7 @@ export const searchFrom = (context: EffectContext, step: WriteStep) => ({ ...(context.timed ? { after: step.record.end } : {}), viewOf: context.viewOf, withBody: context.io.withBody, + queryOf: context.io.queryOf, }); /** The entity an update's response shows, located by its identity, else a later item read of the target the write resolved. */ diff --git a/src/domain/analysisView/environmentStateWriteObserve.ts b/src/domain/analysisView/environmentStateWriteObserve.ts index 2ac5aa86f53..d825705b0b1 100644 --- a/src/domain/analysisView/environmentStateWriteObserve.ts +++ b/src/domain/analysisView/environmentStateWriteObserve.ts @@ -14,7 +14,7 @@ import { type StateRecordFacts, type StateView, } from "./environmentStateRules.js"; -import { matchesReplayKey, queryValues } from "./environmentStateVariants.js"; +import { queryValues, replayReason } from "./environmentStateVariants.js"; /** Where an observed entity object was found: the record and a JSON pointer into its response. */ export interface Observed { @@ -93,30 +93,22 @@ export interface ObservationSearch { ordinal: number, use: (body: JsonValue | undefined) => T, ) => T; + readonly queryOf: (ordinal: number) => string | null | undefined; } -/** Whether serving replays a read rather than answering it from the state: it matches a replay key, or asked for some fields only and shows no whole entity. */ +/** Whether a successful read neither checks the state nor observes a write: serving replays it, or it asked for some fields only and shows no whole entity. */ export const projectedRead = ( view: StateView, record: StateRecordFacts, - io: Pick, + io: Pick, ): boolean => { if (view.shape !== "item" && view.shape !== "list") return false; // An absence or error holds no entity, so it is never a partial one and stays evidence. if (!succeeded(record)) return false; - const keyed = (view.projected_query_keys ?? []).length > 0; - if ( - keyed && - matchesReplayKey(view.projected_query_keys!, queryValues(record.query)) - ) + if (replayReason(view, queryValues(record.query), io.queryOf) !== undefined) return true; + // Serving answers such a selection with the whole entity, which part of one can neither confirm nor check. if (!projectsFields(record.query)) return false; - if ( - view.shape === "item" && - view.projected_record_ordinals !== undefined && - !keyed - ) - return true; return io.withBody(record.ordinal, (body) => { const objects = body === undefined || body === null diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index f7a45cb9aca..fbbdd79e0ef 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1662,3 +1662,46 @@ describe("lines left to replay", () => { }); }); }); + +describe("field selections the gate reads as serving answers them", () => { + it("approves no create from a read serving replays, a selection no checked line gave", () => { + const state = stateOf([ + ["GET", "/api/books/1?fields=*", FIRST_BOOK], + ["GET", "/api/books/2?fields=*", SECOND_BOOK], + ["GET", "/api/books/2?fields=name", { name: "Second Book" }], + ["POST", "/api/books", THIRD_BOOK, 201, { name: "Third Book" }], + [ + "GET", + "/api/books/3?fields=id,name,slug,created_at,updated_at", + THIRD_BOOK, + ], + ]); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).toMatchObject({ + projected_query_keys: [{ name: "fields", value: "name" }], + }); + expect(planOf(state, "post_books")).toMatchObject({ + served: false, + reason: "unconfirmed", + }); + }); + + it("checks an update against a read of every field, which serving answers from the state", () => { + const state = stateOf([ + ...BOOK_INIT_ROWS, + ["GET", "/api/books/2?fields=name", { name: "Second Book" }], + ["PATCH", "/api/books/1", RENAMED_BOOK, 200, { name: "Renamed Book" }], + ["GET", "/api/books/1?fields=*", FIRST_BOOK], + ["GET", "/api/books/1", RENAMED_BOOK], + ]); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).toMatchObject({ projected_query_keys: [{ name: "fields" }] }); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: false, + reason: "contradicted", + contradicted_by: 5, + }); + }); +}); From 197b1a3d8b2f9076ff0f92cf601bac8d38226a14 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 16:44:18 -0700 Subject: [PATCH 14/68] docs(environment): record the second review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 93ae2ff3dd4..bee1953819a 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -10,8 +10,8 @@ and compares it with the recording. - `npm run build:cached`, `npm run check:fast` (typecheck and lint, no new warnings in the changed files), `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and `npm run mcp-catalog:check`: passed. -- `npm run jscpd`: 3.49% duplicated lines over 4055 files. -- `npx vitest run --project domain --project services`: 8962 passed, 6 pre-existing skips. +- `npm run jscpd`: 3.49% duplicated lines over 4072 files. +- `npx vitest run --project domain --project services`: 8975 passed, 6 pre-existing skips. - `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 88 passed. @@ -46,6 +46,8 @@ write tool is lost. - **Review fixes:** no write verdict changes. A NocoDB records list whose `fields` line had rejected it becomes state-backed, and all 7 of its recorded reads match. Without its guard, a short id would cut 23 Tandoor views' initial windows at a `POST /api/view-log/` returning `{"id":1}`. + The second round (the gate skipping exactly the reads serving replays, earlier reads vetoing a linked create, whole + RPC batches, and releasing a discarded planning pass) changes no measurement. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 0ed9e8c0f08367bb66a94127af0ec5667d32b7a1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 19:00:26 -0700 Subject: [PATCH 15/68] fix(environment): read writes, links and creation cuts only from evidence that rules out other causes - A read-only POST repeats only a read that finished before it began; the veto compares the latest read finished before a call with the first begun after it, and counts a recorded absence on one side as a change. `modify` and `replace` are write words. - A redirected or unanswered write lets a later item read adopt the entity it may have made. - A creation cut counts a read still running when the POST began as after it, and a list read shows its listed entities' own ids, not those they nest. - A linked create's item read must come before any other tool's write. - Line shapes are charged to the budget as they are built. - A `fields=*` list line is whole, not a field selection. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 30 +++--- .../agent-environments/state-view/spec.md | 12 ++- .../agent-environments/state-writes/spec.md | 32 ++++--- .../EnvironmentStateExtraction.ts | 10 +- .../EnvironmentStateWriteSimulation.test.ts | 15 +++ .../EnvironmentStateWriteSimulation.ts | 8 +- .../environmentStateQueryCalls.test.ts | 91 ++++++++++++++++++- .../environmentStateQueryCalls.ts | 34 +++++-- .../analysisView/environmentStateRules.ts | 7 ++ .../analysisView/environmentStateVariants.ts | 22 +++-- .../analysisView/environmentStateView.test.ts | 30 ++++++ .../environmentStateWriteAdoption.ts | 4 +- .../environmentStateWriteLinks.test.ts | 68 +++++++++++++- .../environmentStateWriteLinks.ts | 58 ++++++++---- .../environmentStateWrites.test.ts | 60 ++++++++++++ 15 files changed, 405 insertions(+), 76 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 43abf76bbdd..7e9d9336e2b 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -20,27 +20,29 @@ its cause in the recordings and the code. The five largest shared causes: ## Behaviour -- **Read-only calls.** A POST is not a state write when its response repeats the latest read of its path with no - write between, it tunnels only read operations, its last literal segment names a lookup and no write, or it renews - a session; it is replayed. It stays a write when one of its calls was redirected or unanswered, or when a related - read line changes across one of its calls with no write but other read-only calls between. +- **Read-only calls.** A POST is not a state write when its response repeats the latest read of its path that finished + before it began, with no write between, it tunnels only read operations, its last literal segment names a lookup and + no write, or it renews a session; it is replayed. It stays a write when one of its calls was redirected or + unanswered, or when a related read line changes across one of its calls, or finds its entity there on one side only, + with no write but other read-only calls between; a read overlapping the call counts on neither side. - **Adopted entities.** A successful item read of an entity the gate's copy never held, after a write no built plan - models, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken - back. + models or one redirected or unanswered, puts the entity into the copy within the view's budget; an entity a modelled + write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names - an id its response returned, when the id is new: no earlier read of the id, its type's lists or that collection showed - it. Serving creates in that read's collection, for the exemplar's path arguments only. A successful POST that returned - an id a type's reads only show after it ends that type's initial window. + an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its type's + lists or that collection showed it. Serving creates in that read's collection, for the exemplar's path arguments only. + A successful POST that returned an id a type's reads only show once it began ends that type's initial window: a read + still running then may show it, and a list read shows its listed entities' own ids, not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's checks, the entity observations and the membership changes that cut a type's initial window, and the view names it with the query keys that pick it out (`projected_query_keys`, on item and list views). Beside a line showing whole - entities, a list line asking for some fields only is set aside before the identity proof the same way. A call - matching those keys replays its recording, so it does not show served writes; a 400, 404 or 410 on such a line is - still evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line - gave, and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same - decision. A filter role whose name matches no field needs two agreeing values. + entities, a list line asking for some fields only (a projection value other than `*`) is set aside before the + identity proof the same way. A call matching those keys replays its recording, so it does not show served writes; a + 400, 404 or 410 on such a line is still evidence. A call asking for some fields only replays unless every value it + gives is `*` or one a checked line gave, and no replayed read gave it. The write gate skips exactly the successful + reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 5f0378eefa1..5c1f1a74c46 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -28,9 +28,12 @@ later increments. whose URL was redacted bounds every type, with a limitation counting it. A successful `POST` elsewhere bounds a type's state too when its response named an id (an identity member, or a bare or sole scalar of four characters or - more) that the type's reads show only after it: the `POST` made that entity, - so it is not in the initial state. An id shorter than four characters counts - only when the type was read before the `POST` and an item read names it after. + more) that the type's reads show only once it began: the `POST` made that + entity, so it is not in the initial state. A read finished before the `POST` + began shows what was there, and one still running may show its effect. A list + read shows the ids its listed entities carry as their own identity members, not + those of entities they nest. An id shorter than four characters counts only + when the type was read before the `POST` and an item read names it after. - Prove an item type's identity field from the requested path value its responses repeat; otherwise infer it from a fixed list of identity names that every listed item carries distinctly, which needs at least one listed item. @@ -38,7 +41,8 @@ later increments. `select`, `$select`) and does not return the item is left out of the proof and of the view's checks; the view lists it in `projected_record_ordinals`. Beside a line showing whole entities, a list line asking for some fields only - is listed there too, and proves no identity or membership. On a view with + (a projection value other than `*`, which asks for all) is listed there too, + and proves no identity or membership. On a view with such replayed reads, serving replays a call naming a projection parameter for an entity the state holds unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate leaves out exactly diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 554e13bd649..34e047669cd 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -39,8 +39,9 @@ gets no plan, stays a recorded view with the reason `query-body`, is served by replay, and its calls bound no initial-recording window and end no observation search. The capture shows it by the first of these that applies: -1. every successful call answers as the latest earlier successful `GET` of its - path did, with no write between (a status lookup posting the jobs it names); +1. every successful call answers as the latest successful `GET` of its path + that finished before the call began did, with no write between (a status + lookup posting the jobs it names); 2. every call names read operations only, in its body's `operation` or `operations[].operation`, else its query's `operation`, `op` or `action` (`batch` and similar only wrap them, in either place, so a call needs at @@ -49,7 +50,8 @@ search. The capture shows it by the first of these that applies: write); an operation reads when its words name one of `list`, `get`, `count`, `aggregate`, `info`, `search`, `find`, `read`, `query`, `schema`, `describe`, `fetch` or `lookup`, and none of `create`, `insert`, - `update`, `delete`, `remove`, `upsert`, `add`, `set`, `save` and similar; + `update`, `modify`, `replace`, `delete`, `remove`, `upsert`, `add`, `set`, + `save` and similar, so `findAndModify` and `findOneAndReplace` stay writes; 3. the path's last literal segment has a query word as its last meaningful word, split on `_`, `-`, `.` and case and skipping trailing `data`, `info` and `results` (`search`, `query`, `list`, `find`, `lookup`, `count`, @@ -63,9 +65,12 @@ search. The capture shows it by the first of these that applies: A tool stays a write when one of its calls was redirected or went unanswered, since nothing shows what it did. It also stays a write when a `GET` line whose path its call's path relates to (segment by segment, a parameter matching any -value) reads differently just before and just after one of its calls with no -other write between; the other read-only tools' calls are no writes there, so -the tools are dropped until none is vetoed. Reads of unrelated paths do not +value) reads differently just before and just after one of its calls, or finds +its entity on one side only (a 400, 404 or 410 on the other), with no other +write between; the other read-only tools' calls are no writes there, so the +tools are dropped until none is vetoed. Those reads are the latest that +finished before the call began and the first that began after it ended, since +one overlapping the call may show either state. Reads of unrelated paths do not count, so a session renewal stays read-only although an endpoint under the same root regenerates values on every read. @@ -83,10 +88,12 @@ A `POST` whose path gives it no target is a `create` into the type its returned id is read under: its exemplar's response names an id (an identity member of the body or of an object member, or a scalar body or sole member of four characters or more), and the first later successful item read naming that id belongs to a -state type. The entity must be new: neither the initial state nor any earlier -read holds that id, whether an item read of it, a list read of its type, or any -read of the item read's collection, with or without a query, whose body shows it -under an identity member. An id shorter than four characters may be any type's, +state type. That read must come before any other tool's write, which may have +made what it shows, as a publish call makes a note from a draft. The entity must +be new: neither the initial state nor any earlier read holds that id, whether an +item read of it, a list read of its type, or any read of the item read's +collection, with or without a query, that lists it under an identity member of +its own (a body with no list counts an identity member at any depth). An id shorter than four characters may be any type's, so it links only to a type a successful read showed before the call. The plan records that read's collection, and serving creates there, since the call's own path names no collection of the type. That collection holds only for the @@ -279,8 +286,9 @@ of a write. A write no built plan models can also make an entity the copy never held, such as a row an import or a nested create added: a write of a tool with no create, -update, delete or document plan, a call of a tool whose plan was never built, or -a linked create's call that serving would refuse. +update, delete or document plan, a call of a tool whose plan was never built, a +linked create's call that serving would refuse, or any write redirected or left +unanswered. A successful item read of an entity the copy has never held (no initial entity, and none a modelled write created, changed or removed) that names it by the type's identity, when such a write ran since that entity or its collection was diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index cf79551ab45..3c06e86d9fb 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -21,6 +21,7 @@ import { locateList, projectsFields, rootOf, + selectsSomeFields, same, scalarText, writeSpanCheck, @@ -203,8 +204,9 @@ export class EnvironmentStateExtraction { /** Leave each plan's representation variants to replay: out of its lines, the observed entities and the membership changes. */ #dropVariants(): void { - const shapes = lineShapes(this.#entities.values()); - this.#retain(ENTRY_BYTES * (shapes.size + 1)); + const shapes = lineShapes(this.#entities.values(), (bytes) => + this.#retain(bytes), + ); const dropped = new Set(); for (const [index, plan] of this.#plans.entries()) { const split = withoutVariants(plan, { @@ -507,8 +509,8 @@ export class EnvironmentStateExtraction { const { tool, type } = candidate; const initial = this.#initRecordingsOf(candidate); if (initial === undefined) return; - // Beside a line showing whole entities, one asking for some fields only is replayed and proves nothing. - const whole = initial.filter((record) => !projectsFields(record.query)); + // Beside a line showing whole entities, one asking for some fields only is replayed and proves nothing; one asking for all is whole. + const whole = initial.filter((record) => !selectsSomeFields(record.query)); const recordings = whole.length > 0 ? whole : initial; const proved = this.#identity.get(type)?.field; const fieldsOf = (items: readonly JsonObject[]): string[] => diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index d876632601c..587c7681605 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -2253,6 +2253,21 @@ describe("entities an unmodelled write made", () => { }); }); + it("takes a book an import may have made though it was redirected or went unanswered", () => { + for (const status of [303, 0]) { + const unresolved: TimedCaptureRow = [ + "POST", + "/api/imports", + { queued: true }, + status, + { source: "csv" }, + ]; + expect( + gated(deletedAfterRead([RENAME, unresolved]), "delete_books_by_id"), + ).toMatchObject({ served: true, checked_record_ordinals: [7] }); + } + }); + it("counts an entity it takes against the view's allowance", () => { let retained = 0; const read = { ...THIRD_BOOK, notes: "x".repeat(10_000) }; diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 142472be987..e411e6a78ce 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -161,6 +161,7 @@ export class EnvironmentStateWriteSimulation { continue; const link = linkedTarget(tool, classifyWrite(tool, types, documents), { ...this.#input, + isWrite: (record) => this.#isWrite(record), viewOf: (ordinal) => this.#input.views.get(this.#toolOf.get(ordinal)?.name ?? ""), }); @@ -190,10 +191,11 @@ export class EnvironmentStateWriteSimulation { #step(record: StateRecordFacts, index: number): void { const tool = this.#toolOf.get(record.ordinal); - // A redirected or unanswered write may have changed state, but only a 2xx one shows its effect. - if (this.#isWrite(record) && !succeeded(record)) + // A redirected or unanswered write may have changed state, even made an entity, but only a 2xx one shows its effect. + if (this.#isWrite(record) && !succeeded(record)) { this.#unmodelled(record.path, index); - else if (this.#isWrite(record)) this.#write(record, index, tool); + this.#unseen.unplanned(index); + } else if (this.#isWrite(record)) this.#write(record, index, tool); else if (tool?.method === "GET") this.#read(record, index, tool); } diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index ff656673766..9ebd319600c 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -16,9 +16,11 @@ interface Call { readonly request?: JsonValue; readonly tool: string; readonly template?: string; + readonly start?: number; + readonly end?: number; } -/** The read-only tools of a timeline of calls, ordinals in order. */ +/** The read-only tools of a timeline of calls, ordinals in order; a call spans its index unless it gives its times. */ const readOnlyOf = (calls: readonly Call[]): string[] => { const records: StateRecordFacts[] = calls.map((call, index) => ({ ordinal: index, @@ -26,8 +28,8 @@ const readOnlyOf = (calls: readonly Call[]): string[] => { path: call.path, query: call.query, status: call.status === undefined ? 200 : call.status, - start: index, - end: index, + start: call.start ?? index, + end: call.end ?? index, })); const tools = new Map(); calls.forEach((call, index) => { @@ -286,4 +288,87 @@ describe("POSTs that read state but stay writes", () => { ).toEqual([]); expect(readOnlyOf([rpc({ first: read })])).toEqual([]); }); + + it("keeps an RPC call a write when it finds and then modifies or replaces", () => { + const rpc = (operation: string): Call => ({ + method: "POST", + path: "/rpc", + tool: "post_rpc", + request: { operation }, + response: {}, + }); + expect(readOnlyOf([rpc("findOne")])).toEqual(["post_rpc"]); + expect(readOnlyOf([rpc("findAndModify")])).toEqual([]); + expect(readOnlyOf([rpc("findOneAndReplace")])).toEqual([]); + }); +}); + +describe("the reads either side of a POST", () => { + it("compares a POST only with reads that finished before it began or began after it ended", () => { + const note = (title: string): Call => ({ + method: "GET", + path: "/v1/notes/7", + template: "/v1/notes/{id}", + tool: "get_note", + response: { id: 7, title }, + }); + const post: Call = { + method: "POST", + path: "/v1/notes/7", + template: "/v1/notes/{id}", + tool: "post_note", + request: { title: "Renamed" }, + response: { id: 7, title: "Renamed" }, + start: 10, + end: 20, + }; + const at = (call: Call, start: number, end: number): Call => ({ + ...call, + start, + end, + }); + const renamed = note("Renamed"); + const original = note("Draft"); + expect(readOnlyOf([at(renamed, 0, 5), post, at(renamed, 40, 41)])).toEqual([ + "post_note", + ]); + // A read still running when the POST began may already show its change. + expect(readOnlyOf([at(renamed, 0, 30), post, at(renamed, 40, 41)])).toEqual( + [], + ); + // A read begun before the POST ended may not show it yet, so the later read decides. + expect( + readOnlyOf([ + at(original, 0, 5), + { ...post, response: original.response! }, + at(original, 15, 25), + at(renamed, 40, 41), + ]), + ).toEqual([]); + }); + + it("keeps a POST a write when a read of its path finds the entity gone after it", () => { + const message = { id: 1001, body: "hello" }; + const get = (status: number, response: JsonValue): Call => ({ + method: "GET", + path: "/api/messages/1001", + template: "/api/messages/{id}", + tool: "get_message", + status, + response, + }); + const post: Call = { + method: "POST", + path: "/api/messages/1001", + template: "/api/messages/{id}", + tool: "post_message", + response: message, + }; + expect(readOnlyOf([get(200, message), post, get(200, message)])).toEqual([ + "post_message", + ]); + expect( + readOnlyOf([get(200, message), post, get(404, { error: "Not found" })]), + ).toEqual([]); + }); }); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index e3bb8772d59..b8ed7fbede2 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -10,6 +10,7 @@ import { type StateRecordFacts, type StateToolFacts, } from "./environmentStateRules.js"; +import { isAbsence } from "./environmentStateWriteChecks.js"; import { prefixRelated } from "./environmentStateWriteRules.js"; /** The words of a segment or operation name: split on `_`, `-`, `.` and camelCase, in lower case. */ @@ -57,6 +58,8 @@ const WRITE_OPERATION_WORDS = new Set([ "create", "insert", "update", + "modify", + "replace", "delete", "remove", "upsert", @@ -144,10 +147,10 @@ const readsOnly = (operation: string): boolean => { /** * POST tools whose recorded calls read state rather than change it, by the strongest evidence that - * applies: a response repeating the latest read of the same path with no write between, an RPC - * tunnel naming only read operations, a last path word naming a lookup, or a session segment. A - * tool with a redirected or unanswered call stays a write, as does one a read line its path relates - * to changes across, no write but the other read-only tools' calls between. + * applies: a response repeating the latest read of the same path finished before it, with no write + * between, an RPC tunnel naming only read operations, a last path word naming a lookup, or a session + * segment. A tool with a redirected or unanswered call stays a write, as does one a read line its + * path relates to changes across or finds gone after, no write but the other read-only tools' calls between. */ export const readOnlyTools = ( tools: readonly StateToolFacts[], @@ -203,7 +206,7 @@ interface Timeline { readonly io: QueryCallIo; } -/** Every successful call answers as the latest earlier successful GET of its path did, with no write between. */ +/** Every successful call answers as the latest successful GET of its path finished before it began did, with no write between. */ const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], @@ -217,7 +220,8 @@ const repeatsRead = ( (record) => record.method === "GET" && record.path === call.path && - succeeded(record), + succeeded(record) && + record.end <= call.start, ); if (read === undefined || between(position.get(read.ordinal)!, at)) return false; @@ -254,7 +258,11 @@ const namesLookup = (template: string): boolean => { const lastMeaningfulWord = (segment: string): string | undefined => words(segment).findLast((word) => !NEUTRAL_WORDS.has(word)); -/** A GET line whose path a call's path relates to reads differently just before and just after it, with no other write between. */ +/** + * A GET line whose path a call's path relates to reads differently, or finds its entity present on one + * side only, just before and just after it, with no other write between: the reads finished before it + * began and began after it ended, since one overlapping it may show either state. + */ const changesReadsAcross = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], @@ -267,22 +275,28 @@ const changesReadsAcross = ( const related = records.filter( (record) => record.method === "GET" && - succeeded(record) && + (succeeded(record) || isAbsence(record.status)) && prefixRelated(call.path, record.path), ); return [...new Set(related.map(lineOf))].some((line) => { const before = related.findLast( (record) => - lineOf(record) === line && position.get(record.ordinal)! < at, + lineOf(record) === line && + position.get(record.ordinal)! < at && + record.end <= call.start, ); const after = related.find( (record) => - lineOf(record) === line && position.get(record.ordinal)! > at, + lineOf(record) === line && + position.get(record.ordinal)! > at && + record.start >= call.end, ); if (before === undefined || after === undefined) return false; const from = position.get(before.ordinal)!; const to = position.get(after.ordinal)!; if (between(from, at) || between(at, to)) return false; + if (succeeded(before) !== succeeded(after)) return true; + if (!succeeded(before)) return false; const earlier = io.response(before.ordinal); const later = io.response(after.ordinal); return ( diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 1fbbf610b37..5d3f1196216 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -146,6 +146,13 @@ export const projectsFields = (query: string | undefined): boolean => query !== undefined && [...new URLSearchParams(query).keys()].some(isProjectionParameter); +/** Whether a recorded query asks for some fields only: a projection parameter with a value other than `*`, which asks for all. */ +export const selectsSomeFields = (query: string | undefined): boolean => + query !== undefined && + [...new URLSearchParams(query)].some( + ([name, value]) => isProjectionParameter(name) && value !== "*", + ); + export type StateListView = EntityViewPlan & ReplayedReads & { readonly shape: "list"; diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index fa50bdf4155..0af91d9cbef 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -1,4 +1,5 @@ import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; import type { StatePlan } from "./environmentStateGate.js"; import type { ObservedEntity } from "./environmentStateMerge.js"; import { @@ -55,9 +56,10 @@ const shapingNames = (query: string | null | undefined): string[] => (name) => !PAGING.has(name.toLowerCase()), ); -/** The shape each observed recording showed of its entities, by ordinal. */ +/** The shape each observed recording showed of its entities, by ordinal, each part counted against the budget before it is kept. */ export const lineShapes = ( entities: Iterable, + retain: (bytes: number) => void, ): Map => { const shapes = new Map< number, @@ -67,19 +69,27 @@ export const lineShapes = ( common: Set | undefined; } >(); + retain(ENTRY_BYTES); for (const entity of entities) for (const observation of entity.observations) { const members = Object.keys(observation.object); let shape = shapes.get(observation.ordinal); if (shape === undefined) { + // The shape's own entry and containers, with room for the members every object carries. + retain(ENTRY_BYTES * (4 + members.length)); shape = { entities: new Map(), carried: new Set(), common: undefined }; shapes.set(observation.ordinal, shape); } - shape.entities.set( - JSON.stringify([entity.type, entity.collection, entity.id]), - [...members].sort(compare).join(","), - ); - for (const member of members) shape.carried.add(member); + const key = JSON.stringify([entity.type, entity.collection, entity.id]); + const signature = [...members].sort(compare).join(","); + if (!shape.entities.has(key)) + retain(ENTRY_BYTES + textBytes(key.length + signature.length)); + shape.entities.set(key, signature); + for (const member of members) + if (!shape.carried.has(member)) { + retain(ENTRY_BYTES); + shape.carried.add(member); + } shape.common = shape.common === undefined ? new Set(members) diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index ef291575f21..ccc25066dc9 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -19,6 +19,7 @@ import { type AnalysisViewResult, } from "./analysisView.js"; import { EnvironmentStateAccumulator } from "./EnvironmentStateAccumulator.js"; +import type { ObservedEntity } from "./environmentStateMerge.js"; import { at, identityCandidates, @@ -26,6 +27,7 @@ import { type JsonObject, } from "./environmentStateRules.js"; import { environmentStateFields } from "./environmentStateView.js"; +import { lineShapes } from "./environmentStateVariants.js"; type State = Extract; const ALL_RULES = [ @@ -756,6 +758,34 @@ it("refuses when extraction would exceed the projection budget", () => { }); }); +it("counts the line shapes it builds against the budget as it builds them", () => { + const members = Object.fromEntries( + Array.from({ length: 40 }, (_, index) => [ + `member_with_a_long_name_${String(index)}`, + index, + ]), + ); + const entities: ObservedEntity[] = Array.from({ length: 50 }, (_, id) => ({ + type: "/api/items", + collection: "/api/items", + id: String(id), + order: [0, id], + observations: [1, 2].map((ordinal) => ({ + position: ordinal, + ordinal, + tool: "get_items", + item: false, + object: members, + })), + })); + let retained = 0; + lineShapes(entities, (bytes) => { + retained += bytes; + }); + // Each of the hundred observations keeps its entity's key and the names of its members. + expect(retained).toBeGreaterThan(100 * Object.keys(members).join(",").length); +}); + it("releases a planning pass a rewrite cut discards before extracting the state again", () => { const recipe = (id: number, views: number) => ({ id, diff --git a/src/domain/analysisView/environmentStateWriteAdoption.ts b/src/domain/analysisView/environmentStateWriteAdoption.ts index 23a2a88dd9f..2fbd2601d7f 100644 --- a/src/domain/analysisView/environmentStateWriteAdoption.ts +++ b/src/domain/analysisView/environmentStateWriteAdoption.ts @@ -25,7 +25,7 @@ import type { WriteIo } from "./environmentStateWriteEffects.js"; export class UnseenEntities { /** Targets of the entities the copy has held: the initial ones and any a modelled write or an adoption touched. */ readonly #held: Set; - /** Timeline indexes of successful writes no built plan models. */ + /** Timeline indexes of writes no built plan models, and of redirected or unanswered ones. */ readonly #unplannedAt: number[] = []; constructor( @@ -52,7 +52,7 @@ export class UnseenEntities { this.#held.add(key); } - /** Note a successful write no built plan models. */ + /** Note a write no built plan models, or one redirected or unanswered. */ unplanned(index: number): void { this.facts.io.retain(ENTRY_BYTES); this.#unplannedAt.push(index); diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index dc2c01d0522..99f4364de0f 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -8,16 +8,43 @@ const record = ( ordinal: number, method: string, path: string, + [start, end] = [ordinal, ordinal], ): StateRecordFacts => ({ ordinal, method, path, query: undefined, status: 200, - start: ordinal, - end: ordinal, + start, + end, }); +/** The creation limit of `/api/projects` over list reads and a POST returning `created`, in ordinal order. */ +const projectsLimit = ( + reads: readonly StateRecordFacts[], + post: StateRecordFacts, + bodies: ReadonlyMap, + created: readonly string[], +) => + creationLimit( + [{ record: post, ids: created }], + { + type: "/api/projects", + tools: [ + { + name: "get_projects", + method: "GET", + path_template: "/api/projects", + record_ordinals: reads.map((read) => read.ordinal), + }, + ], + records: new Map([...reads, post].map((at) => [at.ordinal, at])), + position: (at) => at.ordinal, + body: (ordinal) => bodies.get(ordinal), + }, + undefined, + ); + describe("creation limits", () => { it("reads the ids of a list body longer than a call's arguments can spread", () => { // A million elements overflow the argument limit of a spread, here and in the test workers' larger stack. @@ -50,4 +77,41 @@ describe("creation limits", () => { ); expect(limit).toBe(post); }); + + it("counts a read still running when the POST began as showing what it made", () => { + const earlier = record(0, "GET", "/api/projects", [0, 5]); + const post = record(2, "POST", "/api/imports", [20, 25]); + const bodies = new Map([ + [0, [{ id: "proj-0001" }]], + [1, [{ id: "proj-0001" }, { id: "proj-0002" }]], + ]); + // The second list began before the POST but ended after it began, so it may show the import. + const overlapping = record(1, "GET", "/api/projects", [10, 40]); + expect( + projectsLimit([earlier, overlapping], post, bodies, ["proj-0002"]), + ).toBe(post); + const finished = record(1, "GET", "/api/projects", [10, 15]); + expect( + projectsLimit([earlier, finished], post, bodies, ["proj-0002"]), + ).toBeUndefined(); + }); + + it("reads the ids a list shows from its listed entities, not the entities they nest", () => { + const [list, post, later] = [ + record(0, "GET", "/api/projects"), + record(1, "POST", "/api/users"), + record(2, "GET", "/api/projects"), + ]; + const project = (owner: string) => ({ + id: "proj-0001", + owner: { id: owner }, + }); + const bodies = new Map([ + [0, [project("user-0001")]], + [2, { projects: [project("user-0009")] }], + ]); + expect( + projectsLimit([list, later], post, bodies, ["user-0009"]), + ).toBeUndefined(); + }); }); diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 507a7ff766d..9de08120f85 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -5,6 +5,8 @@ import { isObject, isParam, lastSegmentValue, + listItems, + locateList, normalizedPath, scalarText, segmentsOf, @@ -69,41 +71,58 @@ const identitiesIn = (root: JsonValue | undefined): Set => { return shown; }; -/** The identity-named scalar values a read's body shows at any depth, or its path's id for an item read. */ +/** The ids a list read shows: its listed entities' own identity members, or any it shows at any depth when it lists none. */ +const listedIds = (body: JsonValue | undefined): Set => { + const pointer = body === undefined ? undefined : locateList(body, undefined); + const items = + body === undefined || pointer === undefined + ? undefined + : listItems(body, pointer); + return items === undefined + ? identitiesIn(body) + : new Set(items.flatMap(identityValues)); +}; + +/** The ids a read shows: its listed entities' for a list read, or its path's id for an item read. */ const shownIds = ( record: StateRecordFacts, item: boolean, body: () => JsonValue | undefined, ): Set => - item ? new Set([lastSegmentValue(record.path)]) : identitiesIn(body()); + item ? new Set([lastSegmentValue(record.path)]) : listedIds(body()); -/** One read of a type: where it ran, whether it reads one item, and the ids it shows. */ +/** One read of a type: where it ran, when it finished, whether it reads one item, and the ids it shows. */ interface ShownRead { readonly at: number; + readonly end: number; readonly item: boolean; readonly ids: ReadonlySet; } /** - * The ids a POST at `at` made that a type's reads show only after it, before `end`. A short id may be - * any type's, so it counts only when the type was read before the POST and an item read names it after. + * The ids a POST at `post.at` made that a type's reads show only after it began, before `until`: a + * read finished before the POST began shows what was there, and one still running may show its + * effect. A short id may be any type's, so it counts only when the type was read before the POST + * and an item read names it after. */ const freshIds = ( ids: readonly string[], shown: readonly ShownRead[], - at: number, - end: number, + post: { readonly at: number; readonly start: number }, + until: number, ): string[] => { - const seen = shown.some((read) => read.at < at); + const before = (read: ShownRead): boolean => + read.at < post.at && read.end <= post.start; + const seen = shown.some(before); return ids.filter((id) => { const short = id.length < MIN_ID_LENGTH; return ( (!short || seen) && - !shown.some((read) => read.at < at && read.ids.has(id)) && + !shown.some((read) => before(read) && read.ids.has(id)) && shown.some( (read) => - read.at > at && - read.at < end && + !before(read) && + read.at < until && (!short || read.item) && read.ids.has(id), ) @@ -173,6 +192,7 @@ export const creationLimit = ( : [ { at: reads.position(record), + end: record.end, item, ids: shownIds(record, item, () => reads.body(ordinal)), }, @@ -184,7 +204,8 @@ export const creationLimit = ( )) { const at = reads.position(creation.record); if (at >= end) break; - if (freshIds(creation.ids, shown, at, end).length > 0) + const post = { at, start: creation.record.start }; + if (freshIds(creation.ids, shown, post, end).length > 0) return creation.record; } return undefined; @@ -192,13 +213,14 @@ export const creationLimit = ( /** * The state type and collection a POST whose path names none creates into: that of the first later - * successful item read naming an id its first successful call returned, when neither the initial - * state nor any earlier read of that id, its type's lists or its collection showed that id. A short - * id may be any type's, so it links only to a type read before the call. + * successful item read naming an id its first successful call returned, before any other tool's + * write, when neither the initial state nor any earlier read of that id, its type's lists or its + * collection showed that id. A short id may be any type's, so it links only to a type read before the call. */ export const linkedCreate = (input: { readonly tool: StateToolFacts; readonly records: readonly StateRecordFacts[]; + readonly isWrite: (record: StateRecordFacts) => boolean; readonly viewOf: (ordinal: number) => StateView | undefined; readonly entities: readonly StateEntity[]; readonly respondedIds: (ordinal: number) => readonly string[]; @@ -220,6 +242,8 @@ export const linkedCreate = (input: { ) return undefined; for (const record of records.slice(first + 1)) { + // Another write may have made what a later read shows, so the search ends there. + if (!own.has(record.ordinal) && input.isWrite(record)) return undefined; const view = input.viewOf(record.ordinal); if ( record.method !== "GET" || @@ -298,6 +322,7 @@ export const linkedTarget = ( classified: { readonly effect: WriteEffect; readonly target: string | null }, input: { readonly records: readonly StateRecordFacts[]; + readonly isWrite: (record: StateRecordFacts) => boolean; readonly viewOf: (ordinal: number) => StateView | undefined; readonly entities: readonly StateEntity[]; readonly io: { @@ -317,10 +342,11 @@ export const linkedTarget = ( ? linkedCreate({ tool, records: input.records, + isWrite: input.isWrite, viewOf: input.viewOf, entities: input.entities, respondedIds: (ordinal) => input.io.withBody(ordinal, respondedIds), - shownIds: (ordinal) => input.io.withBody(ordinal, identitiesIn), + shownIds: (ordinal) => input.io.withBody(ordinal, listedIds), }) : undefined; return link === undefined diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index fbbdd79e0ef..a9c25bb64b4 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1588,6 +1588,42 @@ describe("creates read under another path", () => { }); }); +describe("creates a later write may explain", () => { + it("links no create past a later write, which may have made what the read shows", () => { + const drafted = (publish: boolean): TimedCaptureRow[] => [ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + ["POST", "/api/drafts", C, 201, { title: "Gamma" }], + ...(publish + ? ([ + [ + "POST", + "/api/drafts/1003/publish", + { id: 1003, status: "published" }, + 201, + ], + ] as TimedCaptureRow[]) + : []), + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], + ]; + const state = stateOf(drafted(true)); + // The publish call made the note, so the draft's POST creates none. + expect(planOf(state, "post_drafts")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + expect( + state.writes.find((plan) => plan.tool !== "post_drafts"), + ).toMatchObject({ effect: "create", target: "/api/notes" }); + expect(planOf(stateOf(drafted(false)), "post_drafts")).toMatchObject({ + effect: "create", + target: "/api/notes", + }); + }); +}); + describe("creates whose returned id an earlier read showed", () => { it("links no create whose returned id a list of its collection showed before it", () => { const listed = (shown: JsonValue[]): TimedCaptureRow[] => @@ -1640,6 +1676,30 @@ describe("lines left to replay", () => { }); }); + it("checks a list line asking for every field beside the plain one, as serving answers both from the state", () => { + const created = book(3, "Third Book", bookClock(4)); + const state = stateOf([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books?fields=*", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["POST", "/api/books", created, 201, { name: "Third Book" }], + ["GET", "/api/books?fields=*", [FIRST_BOOK, SECOND_BOOK, created]], + ]); + const view = state.views.find( + (candidate) => candidate.tool === "get_books", + ); + expect(view).toMatchObject({ + shape: "list", + checked_record_ordinals: [0, 1], + }); + expect(view).not.toHaveProperty("projected_record_ordinals"); + expect(planOf(state, "post_books")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + it("keeps a list's whole line when only a replayed line's membership changed across a write", () => { // The expanded line lists shelved books only; the whole list still shows both after the export. const view = stateOf([ From ed78be263cdbf580827104439479dbf65055eaab Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Thu, 22 Oct 2026 19:00:27 -0700 Subject: [PATCH 16/68] docs(environment): record the third review round's checks Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/verification.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index bee1953819a..6eaf14e7ac3 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -10,8 +10,8 @@ and compares it with the recording. - `npm run build:cached`, `npm run check:fast` (typecheck and lint, no new warnings in the changed files), `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and `npm run mcp-catalog:check`: passed. -- `npm run jscpd`: 3.49% duplicated lines over 4072 files. -- `npx vitest run --project domain --project services`: 8975 passed, 6 pre-existing skips. +- `npm run jscpd`: 3.49% duplicated lines over 4074 files. +- `npx vitest run --project domain --project services`: 8987 passed, 6 pre-existing skips. - `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 88 passed. @@ -27,6 +27,7 @@ and compares it with the recording. | rewrite cuts | 189 | 51 | 77 | 1,110 | 1,922 of 1,975 | | variant lines | 189 | 61 | 61 | 1,150 | 2,068 of 2,126 | | review fixes | 189 | 61 | 61 | 1,151 | 2,075 of 2,133 | +| third round | 189 | 61 | 62 | 1,151 | 2,075 of 2,133 | The served smoke applies every served write tool at each step. No read view loses its state backing, and no served write tool is lost. @@ -48,6 +49,9 @@ write tool is lost. initial windows at a `POST /api/view-log/` returning `{"id":1}`. The second round (the gate skipping exactly the reads serving replays, earlier reads vetoing a linked create, whole RPC batches, and releasing a discarded planning pass) changes no measurement. +- **Third round:** Mailpit's send, a linked create that was never observed, loses its target: other writes (marking + messages read, tagging) ran between it and the item read naming its id. No served write, read view or matching read + changes. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From c983edf2ab55e0f7f60aa09afd3ae08bfc2f16c9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 08:10:27 -0700 Subject: [PATCH 17/68] fix(environment): tie linked creates to their returned ids and order state by the lines left - A linked create is observed only in a read of an id its response returned, envelopes included, and serving takes its recorded path values in either spelling. - A list read shows a suffix-named identity (`projectId`) distinct across its entities. - A read-only POST compares the read that finished last before it began. - An entity's first sighting comes from the lines left after variant lines are dropped. - The pairwise variant pass stops at a work limit, leaving every line checked. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 28 +++++----- .../agent-environments/state-view/spec.md | 5 +- .../agent-environments/state-writes/spec.md | 17 +++--- .../environmentStateWriteAnswer.test.ts | 30 +++++++++++ .../EnvironmentStateExtraction.ts | 1 + .../analysisView/environmentStateMerge.ts | 2 + .../environmentStateQueryCalls.test.ts | 9 ++++ .../environmentStateQueryCalls.ts | 48 +++++++++++------ .../analysisView/environmentStateVariants.ts | 39 +++++++++++--- .../analysisView/environmentStateView.test.ts | 31 ++++++++++- .../environmentStateWriteCreate.ts | 36 ++++++++++--- .../environmentStateWriteLinks.test.ts | 21 ++++++++ .../environmentStateWriteLinks.ts | 52 +++++++++++++++---- .../environmentStateWrites.test.ts | 44 ++++++++++++++++ 14 files changed, 302 insertions(+), 61 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 7e9d9336e2b..d13feaac225 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -20,7 +20,7 @@ its cause in the recordings and the code. The five largest shared causes: ## Behaviour -- **Read-only calls.** A POST is not a state write when its response repeats the latest read of its path that finished +- **Read-only calls.** A POST is not a state write when its response repeats the read of its path that finished last before it began, with no write between, it tunnels only read operations, its last literal segment names a lookup and no write, or it renews a session; it is replayed. It stays a write when one of its calls was redirected or unanswered, or when a related read line changes across one of its calls, or finds its entity there on one side only, @@ -29,20 +29,24 @@ its cause in the recordings and the code. The five largest shared causes: models or one redirected or unanswered, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names - an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its type's - lists or that collection showed it. Serving creates in that read's collection, for the exemplar's path arguments only. - A successful POST that returned an id a type's reads only show once it began ends that type's initial window: a read - still running then may show it, and a list read shows its listed entities' own ids, not those they nest. + an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its + type's lists or that collection showed it. Its observation is a read of an id its response returned, in an envelope + too. Serving creates in that read's collection, for the exemplar's path arguments only, in either spelling. A + successful POST that returned an id a type's reads only show once it began ends that type's initial window: a read + still running then may show it, and a list read shows its listed entities' own ids (identity-named, or a + suffix-named field such as `projectId` distinct across two or more), not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's - checks, the entity observations and the membership changes that cut a type's initial window, and the view names it - with the query keys that pick it out (`projected_query_keys`, on item and list views). Beside a line showing whole - entities, a list line asking for some fields only (a projection value other than `*`) is set aside before the - identity proof the same way. A call matching those keys replays its recording, so it does not show served writes; a - 400, 404 or 410 on such a line is still evidence. A call asking for some fields only replays unless every value it - gives is `*` or one a checked line gave, and no replayed read gave it. The write gate skips exactly the successful - reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. + checks, the entity observations (an entity's first sighting comes from the lines left) and the membership changes + that cut a type's initial window, and the view names it with the query keys that pick it out + (`projected_query_keys`, on item and list views). Beside a line showing whole entities, a list line asking for some + fields only (a projection value other than `*`) is set aside before the identity proof the same way. A call matching + those keys replays its recording, so it does not show served writes; a 400, 404 or 410 on such a line is still + evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line gave, + and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same + decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more + than 2^24 entity lookups to compare pairwise keeps every line checked. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 5c1f1a74c46..e594ee63df6 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -31,8 +31,9 @@ later increments. more) that the type's reads show only once it began: the `POST` made that entity, so it is not in the initial state. A read finished before the `POST` began shows what was there, and one still running may show its effect. A list - read shows the ids its listed entities carry as their own identity members, not - those of entities they nest. An id shorter than four characters counts only + read shows the ids its listed entities carry as their own identity members, and + across two or more of them the first suffix-named field (`projectId`) distinct + on each, not those of entities they nest. An id shorter than four characters counts only when the type was read before the `POST` and an item read names it after. - Prove an item type's identity field from the requested path value its responses repeat; otherwise infer it from a fixed list of identity names that diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 34e047669cd..7a5a7286f15 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -39,8 +39,8 @@ gets no plan, stays a recorded view with the reason `query-body`, is served by replay, and its calls bound no initial-recording window and end no observation search. The capture shows it by the first of these that applies: -1. every successful call answers as the latest successful `GET` of its path - that finished before the call began did, with no write between (a status +1. every successful call answers as the successful `GET` of its path that + finished last before the call began did, with no write between (a status lookup posting the jobs it names); 2. every call names read operations only, in its body's `operation` or `operations[].operation`, else its query's `operation`, `op` or `action` @@ -68,9 +68,9 @@ path its call's path relates to (segment by segment, a parameter matching any value) reads differently just before and just after one of its calls, or finds its entity on one side only (a 400, 404 or 410 on the other), with no other write between; the other read-only tools' calls are no writes there, so the -tools are dropped until none is vetoed. Those reads are the latest that -finished before the call began and the first that began after it ended, since -one overlapping the call may show either state. Reads of unrelated paths do not +tools are dropped until none is vetoed. Those reads are the one that finished +last before the call began and the first that began after it ended, since one +overlapping the call may show either state. Reads of unrelated paths do not count, so a session renewal stays read-only although an endpoint under the same root regenerates values on every read. @@ -97,8 +97,11 @@ its own (a body with no list counts an identity member at any depth). An id shor so it links only to a type a successful read showed before the call. The plan records that read's collection, and serving creates there, since the call's own path names no collection of the type. That collection holds only for the -exemplar's path arguments: serving refuses a call with others, and the gate -counts such a recorded call as a write no built plan models. +exemplar's path arguments, each as recorded or in the other spelling once +percent-decoded: serving refuses a call with others, and the gate counts such a +recorded call as a write no built plan models. A linked create's call is +observed only in a read of an id its response returned, at the top or in an +envelope member, so another unseen item's read is never taken for it. **Exemplar.** A plan is built from its first successful (2xx) recorded call, the exemplar. diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index f44f1f1a500..259b8a74ad1 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1691,4 +1691,34 @@ describe("creates read under another path", () => { }), ).toMatchObject({ status: 201 }); }); + + it("takes a linked create's recorded path value in either spelling, as other state-backed calls do", () => { + const note = (id: number, title: string) => ({ id, title }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const project = "/api/projects/my%20org1"; + const other = note(2001, "Other"); + // A second project makes the project segment a path parameter. + const notes = servedFrom([ + ["GET", "/api/projects/my%20org2/notes", [other]], + ["GET", "/api/projects/my%20org2/notes/2001", other], + ["GET", `${project}/notes`, [alpha, beta]], + ["GET", `${project}/notes/1001`, alpha], + ["GET", `${project}/notes/1002`, beta], + ["POST", `${project}/publish`, { id: 1003 }, 201, { title: "Gamma" }], + ["GET", `${project}/notes/1003`, gamma], + ["GET", `${project}/notes`, [alpha, beta, gamma]], + ["POST", "/api/projects/my%20org2/publish", { ok: true }, 200, {}], + ]); + for (const spelling of ["my%20org1", "my org1"]) + expect( + notes.answer("post_projects_publish_by_project_id", { + project_id: spelling, + body: { title: "Delta" }, + }), + ).toMatchObject({ status: 201 }); + }); }); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 3c06e86d9fb..25866b1b049 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -666,6 +666,7 @@ export class EnvironmentStateExtraction { this.#retain(ENTRY_BYTES + jsonBytes(object)); entity.observations.push({ position, + index, ordinal: record.ordinal, tool: plan.tool.name, item: plan.item, diff --git a/src/domain/analysisView/environmentStateMerge.ts b/src/domain/analysisView/environmentStateMerge.ts index 406fe7a965a..272ed2f855b 100644 --- a/src/domain/analysisView/environmentStateMerge.ts +++ b/src/domain/analysisView/environmentStateMerge.ts @@ -9,6 +9,8 @@ import { /** One entity object as one tool recorded it. */ export interface StateObservation { readonly position: number; + /** Where in its read the entity was listed; 0 for an item read. */ + readonly index: number; readonly ordinal: number; readonly tool: string; readonly item: boolean; diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index 9ebd319600c..1aee8efaaca 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -345,6 +345,15 @@ describe("the reads either side of a POST", () => { at(renamed, 40, 41), ]), ).toEqual([]); + // Of the reads finished before the POST began, the one that finished last decides, not the one begun last. + expect( + readOnlyOf([ + at(original, 0, 9), + at(renamed, 1, 2), + post, + at(renamed, 40, 41), + ]), + ).toEqual([]); }); it("keeps a POST a write when a read of its path finds the entity gone after it", () => { diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index b8ed7fbede2..82fd6b05778 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -206,7 +206,22 @@ interface Timeline { readonly io: QueryCallIo; } -/** Every successful call answers as the latest successful GET of its path finished before it began did, with no write between. */ +/** Of these reads, the one that finished last before `call` began, a later one on a tie; records come in start order. */ +const lastFinishedBefore = ( + reads: readonly StateRecordFacts[], + call: StateRecordFacts, +): StateRecordFacts | undefined => { + let latest: StateRecordFacts | undefined; + for (const read of reads) + if ( + read.end <= call.start && + (latest === undefined || read.end >= latest.end) + ) + latest = read; + return latest; +}; + +/** Every successful call answers as the successful GET of its path that finished last before it began did, with no write between. */ const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], @@ -214,15 +229,17 @@ const repeatsRead = ( ): boolean => calls.filter(succeeded).every((call) => { const at = position.get(call.ordinal)!; - const read = records - .slice(0, at) - .findLast( - (record) => - record.method === "GET" && - record.path === call.path && - succeeded(record) && - record.end <= call.start, - ); + const read = lastFinishedBefore( + records + .slice(0, at) + .filter( + (record) => + record.method === "GET" && + record.path === call.path && + succeeded(record), + ), + call, + ); if (read === undefined || between(position.get(read.ordinal)!, at)) return false; const answered = io.response(call.ordinal); @@ -279,11 +296,12 @@ const changesReadsAcross = ( prefixRelated(call.path, record.path), ); return [...new Set(related.map(lineOf))].some((line) => { - const before = related.findLast( - (record) => - lineOf(record) === line && - position.get(record.ordinal)! < at && - record.end <= call.start, + const before = lastFinishedBefore( + related.filter( + (record) => + lineOf(record) === line && position.get(record.ordinal)! < at, + ), + call, ); const after = related.find( (record) => diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 0af91d9cbef..bc110063027 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -104,6 +104,9 @@ const EMPTY: LineShape = { common: undefined, }; +/** Entity lookups the pairwise variant pass may make; a plan whose lines need more keeps every line checked. */ +const VARIANT_WORK_LIMIT = 1 << 24; + /** Whether two lines show a shared entity with different members. */ const conflicts = (left: LineShape, right: LineShape): boolean => [...left.entities].some( @@ -111,14 +114,24 @@ const conflicts = (left: LineShape, right: LineShape): boolean => right.entities.has(key) && right.entities.get(key) !== members, ); -/** The latest lines that show the plan's entities in another representation than its base lines, as an expanding or reducing query does. */ +/** + * The latest lines that show the plan's entities in another representation than its base lines, as + * an expanding or reducing query does; none when comparing every pair of lines would exceed the work limit. + */ export const variantLines = ( latest: readonly StateRecordFacts[], shapeOf: (record: StateRecordFacts) => LineShape | undefined, ): StateRecordFacts[] => { if (latest.length < 2) return []; - const shape = (record: StateRecordFacts): LineShape => - shapeOf(record) ?? EMPTY; + const shapes = new Map( + latest.map((record) => [record, shapeOf(record) ?? EMPTY]), + ); + const entities = [...shapes.values()].reduce( + (sum, line) => sum + line.entities.size, + 0, + ); + if (latest.length * entities > VARIANT_WORK_LIMIT) return []; + const shape = (record: StateRecordFacts): LineShape => shapes.get(record)!; const agreeing = new Map( latest.map((record) => [ record, @@ -345,7 +358,7 @@ export const withoutVariants = ( }; }; -/** Forget the observations of dropped recordings, and entities only they showed. */ +/** Forget the observations of dropped recordings, and entities only they showed; an entity is first sighted where its kept observations show it first. */ export const dropObservations = ( entities: Map, dropped: ReadonlySet, @@ -355,7 +368,21 @@ export const dropObservations = ( (observation) => !dropped.has(observation.ordinal), ); if (kept.length === entity.observations.length) continue; - if (kept.length === 0) entities.delete(key); - else entities.set(key, { ...entity, observations: kept }); + if (kept.length === 0) { + entities.delete(key); + continue; + } + const first = kept.reduce((earliest, observation) => + observation.position < earliest.position || + (observation.position === earliest.position && + observation.index < earliest.index) + ? observation + : earliest, + ); + entities.set(key, { + ...entity, + order: [first.position, first.index], + observations: kept, + }); } }; diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index ccc25066dc9..02cb9fb965b 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -27,7 +27,7 @@ import { type JsonObject, } from "./environmentStateRules.js"; import { environmentStateFields } from "./environmentStateView.js"; -import { lineShapes } from "./environmentStateVariants.js"; +import { lineShapes, variantLines } from "./environmentStateVariants.js"; type State = Extract; const ALL_RULES = [ @@ -772,6 +772,7 @@ it("counts the line shapes it builds against the budget as it builds them", () = order: [0, id], observations: [1, 2].map((ordinal) => ({ position: ordinal, + index: id, ordinal, tool: "get_items", item: false, @@ -786,6 +787,34 @@ it("counts the line shapes it builds against the budget as it builds them", () = expect(retained).toBeGreaterThan(100 * Object.keys(members).join(",").length); }); +it("leaves every line checked rather than compare more lines than the variant pass allows", () => { + const lines = Array.from({ length: 3000 }, (_, ordinal) => ({ + ordinal, + method: "GET", + path: "/api/items", + query: `?view=${String(ordinal)}`, + status: 200, + start: ordinal, + end: ordinal, + })); + const shape = { + entities: new Map( + Array.from({ length: 4 }, (_, id) => [String(id), "id,name"]), + ), + carried: new Set(["id", "name"]), + common: new Set(["id", "name"]), + }; + let looked = 0; + expect( + variantLines(lines, () => { + looked += 1; + return shape; + }), + ).toEqual([]); + // Comparing every pair would look each line's shape up thousands of times. + expect(looked).toBeLessThan(10 * lines.length); +}); + it("releases a planning pass a rewrite cut discards before extracting the state again", () => { const recipe = (id: number, views: number) => ({ id, diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 06a4e9b83ab..46bb7b30255 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -13,7 +13,10 @@ import { type SuppliedSegment, } from "./environmentStateRules.js"; import { createdFields } from "./environmentStateWriteApply.js"; -import { sameLinkedSource } from "./environmentStateWriteLinks.js"; +import { + respondedIds, + sameLinkedSource, +} from "./environmentStateWriteLinks.js"; import { collectionTarget, entityTarget, @@ -70,7 +73,10 @@ const respondedId = ( return members.length === 1 ? scalarText(members[0]) : undefined; }; -/** The written entity a create's response or a later read shows. */ +/** + * The written entity a create's response or a later read shows. A linked create's read must name an + * id its response returned, as the read that linked it did, envelopes included. + */ const createdObservation = ( context: EffectContext, step: WriteStep, @@ -78,6 +84,7 @@ const createdObservation = ( readonly type: string; readonly collection: string; readonly idField: string; + readonly linked: boolean; }, ): Observed | undefined => { const held = (id: string) => @@ -86,17 +93,29 @@ const createdObservation = ( newEntityIn(step.record.ordinal, body, target.idField, held), ); if (own !== undefined) return own; - // A response that names the created id alone ties the later read to that id. - const id = context.io.withBody(step.record.ordinal, (body) => - respondedId(body, target.idField), - ); + const { id, ids } = context.io.withBody(step.record.ordinal, (body) => { + const returned = target.linked ? respondedIds(body) : []; + // A response that names the created id alone ties the later read to that id. + const named = + respondedId(body, target.idField) ?? + (returned.length === 1 ? returned[0] : undefined); + return { id: named, ids: returned }; + }); const later = laterObservation(searchFrom(context, step), { - ...target, + type: target.type, + collection: target.collection, + idField: target.idField, ...(id === undefined ? {} : { id }), held, isWrite: context.isWrite, }); - if (later !== undefined) context.observed(later.ordinal); + // A read named by the id is tied already; otherwise a linked create's read must name a returned id. + if ( + later === undefined || + (target.linked && id === undefined && !ids.includes(later.id)) + ) + return undefined; + context.observed(later.ordinal); return later; }; @@ -359,6 +378,7 @@ export const applyCreate = ( type, collection, idField, + linked: draft.linked !== undefined, }); if (observed === undefined) { fail(draft, step, body === undefined ? "body-unusable" : "no-observation"); diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index 99f4364de0f..ed935bc8b23 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -96,6 +96,27 @@ describe("creation limits", () => { ).toBeUndefined(); }); + it("reads a list's ids from a suffix-named field when no identity name identifies its entities", () => { + const [list, post, later] = [ + record(0, "GET", "/api/projects"), + record(1, "POST", "/api/imports"), + record(2, "GET", "/api/projects"), + ]; + const bodies = new Map([ + [0, [{ projectId: "proj-0001", name: "Alpha" }]], + [ + 2, + [ + { projectId: "proj-0001", name: "Alpha" }, + { projectId: "proj-0002", name: "Beta" }, + ], + ], + ]); + expect(projectsLimit([list, later], post, bodies, ["proj-0002"])).toBe( + post, + ); + }); + it("reads the ids a list shows from its listed entities, not the entities they nest", () => { const [list, post, later] = [ record(0, "GET", "/api/projects"), diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 9de08120f85..8d652c269c6 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -2,12 +2,14 @@ import type { JsonValue } from "../jsonValue.js"; import { collectionPathOf, IDENTITY_NAMES, + identityCandidates, isObject, isParam, lastSegmentValue, listItems, locateList, normalizedPath, + pathSegmentMatches, scalarText, segmentsOf, type StateEntity, @@ -71,16 +73,30 @@ const identitiesIn = (root: JsonValue | undefined): Set => { return shown; }; -/** The ids a list read shows: its listed entities' own identity members, or any it shows at any depth when it lists none. */ +/** + * The ids a list read shows: its listed entities' own identity-named members and, across two or + * more of them, the first suffix-named field (`projectId`) distinct on each, or any id it shows at + * any depth when it lists none. + */ const listedIds = (body: JsonValue | undefined): Set => { const pointer = body === undefined ? undefined : locateList(body, undefined); const items = body === undefined || pointer === undefined ? undefined : listItems(body, pointer); - return items === undefined - ? identitiesIn(body) - : new Set(items.flatMap(identityValues)); + if (items === undefined) return identitiesIn(body); + const suffixed = + items.length < 2 + ? undefined + : identityCandidates(items).find( + (name) => !IDENTITY_NAMES.includes(name), + ); + return new Set([ + ...items.flatMap(identityValues), + ...(suffixed === undefined + ? [] + : items.flatMap((item) => scalarText(item[suffixed]) ?? [])), + ]); }; /** The ids a read shows: its listed entities' for a list read, or its path's id for an item read. */ @@ -300,19 +316,35 @@ export const linkedCollection = ( ? plan.collection : undefined; -/** Whether a linked create's call sends the path values its exemplar did: the read that linked its target followed only that call. */ +/** + * Whether a linked create's call sends the path values its exemplar did, each as recorded or in the + * other spelling once percent-decoded: the read that linked its target followed only that call. + */ export const sameLinkedSource = ( template: string, exemplar: string | undefined, call: ReadonlyMap | undefined, ): boolean => { - const recorded = - exemplar === undefined ? undefined : pathValuesOf(template, exemplar); + if ( + exemplar === undefined || + call === undefined || + pathValuesOf(template, exemplar) === undefined + ) + return false; + const segments = segmentsOf(exemplar); + const recorded = new Map( + segmentsOf(template).flatMap((segment, index) => + isParam(segment) + ? [[segment.slice(1, -1), segments[index]!] as const] + : [], + ), + ); return ( - recorded !== undefined && - call !== undefined && recorded.size === call.size && - [...recorded].every(([name, value]) => call.get(name) === value) + [...recorded].every(([name, value]) => { + const given = call.get(name); + return given !== undefined && pathSegmentMatches(value, given); + }) ); }; diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index a9c25bb64b4..37de2f247c1 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1624,6 +1624,50 @@ describe("creates a later write may explain", () => { }); }); +describe("state order after a variant line is dropped", () => { + it("orders entities by the lines left, so a plain list listing them in another order lists them all", () => { + const view = stateOf([ + [ + "GET", + "/api/books?expand=shelf", + [expandedBook(SECOND_BOOK), expandedBook(FIRST_BOOK)], + ], + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ]).views.find((candidate) => candidate.tool === "get_books"); + expect(view).toMatchObject({ + shape: "list", + membership: "all", + projected_record_ordinals: [0], + }); + }); +}); + +describe("what a linked create observes", () => { + it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { + const D = note(1004, "Delta"); + const state = stateOf([ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + [ + "POST", + "/api/drafts/publish", + { data: { id: 1003 } }, + 201, + { title: "Gamma" }, + ], + // Another note the state never held, which the publish did not make. + ["GET", "/api/notes/1004", D], + ["GET", "/api/notes/1003", C], + ]); + expect(planOf(state, "post_drafts_publish")).toMatchObject({ + effect: "create", + target: "/api/notes", + observation: { ordinal: 5 }, + }); + }); +}); + describe("creates whose returned id an earlier read showed", () => { it("links no create whose returned id a list of its collection showed before it", () => { const listed = (shown: JsonValue[]): TimedCaptureRow[] => From fa9f69c5e57f8ae60426113146b7a1d66a1f4b61 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 08:15:08 -0700 Subject: [PATCH 18/68] docs(environment): record the fourth review round's checks Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/verification.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 6eaf14e7ac3..9d81b4dd56c 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -3,7 +3,9 @@ Executed on macOS with Node v22.23.1, one change at a time on main, over the 50 published capture-built environments (each app's latest capture). The served smoke rebuilds each manifest with the tree under test and applies every served write tool; the serving check answers every recorded read made before the capture's first write through state serving -and compares it with the recording. +and compares it with the recording. The serving check reads no records from the five browser-scenario captures (Art +Institute collection, LoC photos, Lychee, PhotoPrism, Pinry), so its read counts cover 45 apps; their 41 views count +among the state-backed views. ## Gates @@ -11,7 +13,7 @@ and compares it with the recording. `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and `npm run mcp-catalog:check`: passed. - `npm run jscpd`: 3.49% duplicated lines over 4074 files. -- `npx vitest run --project domain --project services`: 8987 passed, 6 pre-existing skips. +- `npx vitest run --project domain --project services`: 8992 passed, 6 pre-existing skips. - `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 88 passed. @@ -52,6 +54,11 @@ write tool is lost. - **Third round:** Mailpit's send, a linked create that was never observed, loses its target: other writes (marking messages read, tagging) ran between it and the item read naming its id. No served write, read view or matching read changes. +- **Fourth round:** no verdict, read view or recorded read changes. A purge of temporary files removed 32 of the local + captures, so this round was measured on captures restored from the published datasets, byte-identical where a local + copy survived; Baserow's, Grocy's and Keycloak's published captures predate the ones measured above. On that set the + previous head and this one both give 187 write tools, 62 served (smoke 62 of 62), 1,151 views and 2,085 of 2,155 + recorded reads matching. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 294fa3c3538325ee50e3990effd6cf3750f1616e Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 08:34:11 -0700 Subject: [PATCH 19/68] fix(environment): keep foreign keys, stale reads and double decoding out of write evidence - A list read counts a suffix-named field as its entities' ids only when no id-named field identifies them, so an `ownerId` beside `id` cuts no window. - A read-only POST is compared with the read that finished last among those no other write follows, so a consuming call stays a write. - A linked create's source path values compare as spelled on both sides, so no spelling is decoded twice. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 3 +- .../agent-environments/state-view/spec.md | 6 +- .../agent-environments/state-writes/spec.md | 8 +-- .../environmentStateWriteAnswer.test.ts | 35 ++++++++++++ .../environmentStateQueryCalls.test.ts | 47 ++++++++++++++++ .../environmentStateQueryCalls.ts | 10 +++- .../environmentStateWriteCreate.ts | 3 +- .../environmentStateWriteLinks.test.ts | 23 ++++++++ .../environmentStateWriteLinks.ts | 56 +++++++++++-------- 9 files changed, 157 insertions(+), 34 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index d13feaac225..1e9e787aba2 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -34,7 +34,8 @@ its cause in the recordings and the code. The five largest shared causes: too. Serving creates in that read's collection, for the exemplar's path arguments only, in either spelling. A successful POST that returned an id a type's reads only show once it began ends that type's initial window: a read still running then may show it, and a list read shows its listed entities' own ids (identity-named, or a - suffix-named field such as `projectId` distinct across two or more), not those they nest. + suffix-named field such as `projectId` distinct across two or more when no id-named field identifies them), not + those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index e594ee63df6..e3aec1951f1 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -32,8 +32,10 @@ later increments. entity, so it is not in the initial state. A read finished before the `POST` began shows what was there, and one still running may show its effect. A list read shows the ids its listed entities carry as their own identity members, and - across two or more of them the first suffix-named field (`projectId`) distinct - on each, not those of entities they nest. An id shorter than four characters counts only + across two or more of them, when no id-named field (`id`, `uuid`, …; not `key`, + `slug` or `name`) identifies them, the first suffix-named field (`projectId`) + distinct on each, so a foreign key beside an `id` is none of theirs, nor are the + ids of entities they nest. An id shorter than four characters counts only when the type was read before the `POST` and an item read names it after. - Prove an item type's identity field from the requested path value its responses repeat; otherwise infer it from a fixed list of identity names that diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 7a5a7286f15..9e028c48e23 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -40,8 +40,8 @@ replay, and its calls bound no initial-recording window and end no observation search. The capture shows it by the first of these that applies: 1. every successful call answers as the successful `GET` of its path that - finished last before the call began did, with no write between (a status - lookup posting the jobs it names); + finished last before the call began, of those with no write between, did (a + status lookup posting the jobs it names); 2. every call names read operations only, in its body's `operation` or `operations[].operation`, else its query's `operation`, `op` or `action` (`batch` and similar only wrap them, in either place, so a call needs at @@ -69,8 +69,8 @@ value) reads differently just before and just after one of its calls, or finds its entity on one side only (a 400, 404 or 410 on the other), with no other write between; the other read-only tools' calls are no writes there, so the tools are dropped until none is vetoed. Those reads are the one that finished -last before the call began and the first that began after it ended, since one -overlapping the call may show either state. Reads of unrelated paths do not +last before the call began, of those no other write follows, and the first that +began after it ended, since one overlapping the call may show either state. Reads of unrelated paths do not count, so a session renewal stays read-only although an endpoint under the same root regenerates values on every read. diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 259b8a74ad1..ef0a9987ecb 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1692,6 +1692,41 @@ describe("creates read under another path", () => { ).toMatchObject({ status: 201 }); }); + it("counts a linked create's call from a source that names the exemplar's only after decoding twice as another source's", () => { + const note = (id: number, title: string) => ({ id, title }); + const [alpha, beta, gamma, delta] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + note(1004, "Delta"), + ]; + const other = note(2001, "Other"); + const project = "/api/projects/team1"; + // A second project makes the project segment a path parameter. + const notes = servedFrom([ + ["GET", "/api/projects/team2/notes", [other]], + ["GET", "/api/projects/team2/notes/2001", other], + ["GET", `${project}/notes`, [alpha, beta]], + ["GET", `${project}/notes/1001`, alpha], + ["GET", `${project}/notes/1002`, beta], + ["POST", `${project}/publish`, { id: 1003 }, 201, { title: "Gamma" }], + ["GET", `${project}/notes/1003`, gamma], + ["GET", `${project}/notes`, [alpha, beta, gamma]], + // `team%2531` decodes once to `team%31`, another project than `team1`. + [ + "POST", + "/api/projects/team%2531/publish", + delta, + 201, + { title: "Delta" }, + ], + ["GET", `${project}/notes`, [alpha, beta, gamma]], + ]); + expect( + notes.state.writes.get("post_projects_publish_by_project_id"), + ).toMatchObject({ served: true, contradicted_by: null }); + }); + it("takes a linked create's recorded path value in either spelling, as other state-backed calls do", () => { const note = (id: number, title: string) => ({ id, title }); const [alpha, beta, gamma] = [ diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index 1aee8efaaca..ee36be19729 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -356,6 +356,53 @@ describe("the reads either side of a POST", () => { ).toEqual([]); }); + it("compares a POST with a read begun after another write, which shows that write's effect", () => { + const message = { id: 1001, body: "hello" }; + const get = ( + start: number, + end: number, + status = 200, + response: JsonValue = message, + ): Call => ({ + method: "GET", + path: "/api/messages/1001", + template: "/api/messages/{id}", + tool: "get_message", + status, + response, + start, + end, + }); + const put: Call = { + method: "PUT", + path: "/api/messages/1001", + template: "/api/messages/{id}", + tool: "put_message", + response: message, + start: 1, + end: 2, + }; + const consume: Call = { + method: "POST", + path: "/api/messages/1001/ids", + template: "/api/messages/{id}/ids", + tool: "post_ids", + response: ["1001"], + start: 10, + end: 11, + }; + // The read that finished last began before the PUT; the shorter one after it shows the message survived the PUT. + expect( + readOnlyOf([ + get(0, 9), + put, + get(3, 4), + consume, + get(12, 13, 404, { error: "Not found" }), + ]), + ).toEqual([]); + }); + it("keeps a POST a write when a read of its path finds the entity gone after it", () => { const message = { id: 1001, body: "hello" }; const get = (status: number, response: JsonValue): Call => ({ diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 82fd6b05778..69693382570 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -221,7 +221,7 @@ const lastFinishedBefore = ( return latest; }; -/** Every successful call answers as the successful GET of its path that finished last before it began did, with no write between. */ +/** Every successful call answers as the successful GET of its path that finished last before it began, of those with no write between, did. */ const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], @@ -236,7 +236,8 @@ const repeatsRead = ( (record) => record.method === "GET" && record.path === call.path && - succeeded(record), + succeeded(record) && + !between(position.get(record.ordinal)!, at), ), call, ); @@ -296,10 +297,13 @@ const changesReadsAcross = ( prefixRelated(call.path, record.path), ); return [...new Set(related.map(lineOf))].some((line) => { + // A read before another write shows the state that write changed, so only later ones count. const before = lastFinishedBefore( related.filter( (record) => - lineOf(record) === line && position.get(record.ordinal)! < at, + lineOf(record) === line && + position.get(record.ordinal)! < at && + !between(position.get(record.ordinal)!, at), ), call, ); diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 6d99ecb334e..c41ba5afa4e 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -15,6 +15,7 @@ import { } from "./environmentStateRules.js"; import { createdFields } from "./environmentStateWriteApply.js"; import { + recordedPathValues, respondedIds, sameLinkedSource, } from "./environmentStateWriteLinks.js"; @@ -333,7 +334,7 @@ const fromLinkedSource = ( context.records.find( (record) => record.ordinal === draft.plan.exemplar_ordinal, )?.path, - pathValuesOf(step.tool.path_template, step.record.path), + recordedPathValues(step.tool.path_template, step.record.path), ); /** Add a created entity to the state at the plan's insert position, or last before the plan has one. */ diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index ed935bc8b23..6dbdcc7aed1 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -117,6 +117,29 @@ describe("creation limits", () => { ); }); + it("reads no suffix-named field as a list's ids when an id field already identifies its entities", () => { + const [list, post, later] = [ + record(0, "GET", "/api/projects"), + record(1, "POST", "/api/users/user-0003/activate"), + record(2, "GET", "/api/projects"), + ]; + const project = (id: string, ownerId: string) => ({ id, ownerId }); + const bodies = new Map([ + [ + 0, + [project("proj-0001", "user-0001"), project("proj-0002", "user-0002")], + ], + [ + 2, + [project("proj-0001", "user-0003"), project("proj-0002", "user-0002")], + ], + ]); + // The owner the user call returned is no project the call made. + expect( + projectsLimit([list, later], post, bodies, ["user-0003"]), + ).toBeUndefined(); + }); + it("reads the ids a list shows from its listed entities, not the entities they nest", () => { const [list, post, later] = [ record(0, "GET", "/api/projects"), diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 8d652c269c6..d0306ce60c0 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -25,6 +25,9 @@ import { /** The shortest id that names one entity rather than counting one, or naming one of any type. */ const MIN_ID_LENGTH = 4; +/** Identity names that describe an entity rather than number it, so its own suffix-named id may sit beside them. */ +const DESCRIPTIVE_NAMES: ReadonlySet = new Set(["key", "slug", "name"]); + const succeeded = (record: StateRecordFacts): boolean => record.status !== null && record.status >= 200 && record.status < 300; @@ -75,8 +78,9 @@ const identitiesIn = (root: JsonValue | undefined): Set => { /** * The ids a list read shows: its listed entities' own identity-named members and, across two or - * more of them, the first suffix-named field (`projectId`) distinct on each, or any id it shows at - * any depth when it lists none. + * more of them when no id-named field identifies them, the first suffix-named field (`projectId`) + * distinct on each, so a foreign key beside an `id` is no id of theirs; any id it shows at any depth + * when it lists none. */ const listedIds = (body: JsonValue | undefined): Set => { const pointer = body === undefined ? undefined : locateList(body, undefined); @@ -85,12 +89,12 @@ const listedIds = (body: JsonValue | undefined): Set => { ? undefined : listItems(body, pointer); if (items === undefined) return identitiesIn(body); - const suffixed = - items.length < 2 - ? undefined - : identityCandidates(items).find( - (name) => !IDENTITY_NAMES.includes(name), - ); + const candidates = items.length < 2 ? [] : identityCandidates(items); + const suffixed = candidates.some( + (name) => IDENTITY_NAMES.includes(name) && !DESCRIPTIVE_NAMES.has(name), + ) + ? undefined + : candidates.find((name) => !IDENTITY_NAMES.includes(name)); return new Set([ ...items.flatMap(identityValues), ...(suffixed === undefined @@ -316,29 +320,35 @@ export const linkedCollection = ( ? plan.collection : undefined; +/** The values a recorded path gives its template's parameters as spelled, undecoded; undefined when it does not fit. */ +export const recordedPathValues = ( + template: string, + path: string, +): Map | undefined => { + if (pathValuesOf(template, path) === undefined) return undefined; + const segments = segmentsOf(path); + return new Map( + segmentsOf(template).flatMap((segment, index) => + isParam(segment) + ? [[segment.slice(1, -1), segments[index]!] as const] + : [], + ), + ); +}; + /** * Whether a linked create's call sends the path values its exemplar did, each as recorded or in the - * other spelling once percent-decoded: the read that linked its target followed only that call. + * other spelling once percent-decoded: the read that linked its target followed only that call. The + * call's values come as spelled, so neither side is decoded twice. */ export const sameLinkedSource = ( template: string, exemplar: string | undefined, call: ReadonlyMap | undefined, ): boolean => { - if ( - exemplar === undefined || - call === undefined || - pathValuesOf(template, exemplar) === undefined - ) - return false; - const segments = segmentsOf(exemplar); - const recorded = new Map( - segmentsOf(template).flatMap((segment, index) => - isParam(segment) - ? [[segment.slice(1, -1), segments[index]!] as const] - : [], - ), - ); + const recorded = + exemplar === undefined ? undefined : recordedPathValues(template, exemplar); + if (recorded === undefined || call === undefined) return false; return ( recorded.size === call.size && [...recorded].every(([name, value]) => { From ce9a153aaba97b9be6ee83c7b08eff94eaf1bf52 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 08:34:13 -0700 Subject: [PATCH 20/68] docs(environment): record the fifth review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 9d81b4dd56c..2c6ad4227b6 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -59,6 +59,8 @@ write tool is lost. copy survived; Baserow's, Grocy's and Keycloak's published captures predate the ones measured above. On that set the previous head and this one both give 187 write tools, 62 served (smoke 62 of 62), 1,151 views and 2,085 of 2,155 recorded reads matching. +- **Fifth round** (on main `6a34be41`): no verdict, read view or recorded read changes on the same restored captures, + once the serving check passes a repeated query value as an array, as main now expects. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 169842bf5d609c9efbf95bcda8f0bb9e5eede24a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:10:35 -0700 Subject: [PATCH 21/68] fix(environment): compare linked sources by position, decode path fields once and bound read and variant scans - A linked create's source values compare segment by segment, so a template naming two parameters alike cannot accept a changed first one. - Serving fills a linked create's path fields with its arguments decoded once, as the gate learned them. - The read-only check reads each related line's records once per call, between the nearest other writes. - Member signatures are JSON arrays, so a name holding the separator still conflicts; the variant work limit counts line pairs as well as entities. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 12 +- .../agent-environments/state-writes/spec.md | 4 +- .../environmentStateWriteAnswer.test.ts | 77 ++++++++++++ .../environmentStateWriteAnswer.ts | 35 +++++- .../environmentStateQueryCalls.test.ts | 52 ++++++++ .../environmentStateQueryCalls.ts | 115 +++++++++--------- .../analysisView/environmentStateVariants.ts | 104 ++++++++++------ .../analysisView/environmentStateView.test.ts | 79 ++++++++++++ .../environmentStateWriteLinks.ts | 17 +-- 9 files changed, 379 insertions(+), 116 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 1e9e787aba2..1f439553fab 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -31,11 +31,11 @@ its cause in the recordings and the code. The five largest shared causes: - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its type's lists or that collection showed it. Its observation is a read of an id its response returned, in an envelope - too. Serving creates in that read's collection, for the exemplar's path arguments only, in either spelling. A - successful POST that returned an id a type's reads only show once it began ends that type's initial window: a read - still running then may show it, and a list read shows its listed entities' own ids (identity-named, or a - suffix-named field such as `projectId` distinct across two or more when no id-named field identifies them), not - those they nest. + too. Serving creates in that read's collection, for the exemplar's path arguments only (segment by segment, in + either spelling), and fills path fields with the arguments decoded once. A successful POST that returned an id a + type's reads only show once it began ends that type's initial window: a read still running then may show it, and a + list read shows its listed entities' own ids (identity-named, or a suffix-named field such as `projectId` distinct + across two or more when no id-named field identifies them), not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's @@ -47,7 +47,7 @@ its cause in the recordings and the code. The five largest shared causes: evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more - than 2^24 entity lookups to compare pairwise keeps every line checked. + than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. ## Acceptance diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 9e028c48e23..1ba1e633172 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -97,8 +97,8 @@ its own (a body with no list counts an identity member at any depth). An id shor so it links only to a type a successful read showed before the call. The plan records that read's collection, and serving creates there, since the call's own path names no collection of the type. That collection holds only for the -exemplar's path arguments, each as recorded or in the other spelling once -percent-decoded: serving refuses a call with others, and the gate counts such a +exemplar's path arguments, compared segment by segment, each as recorded or in +the other spelling once percent-decoded: serving refuses a call with others, and the gate counts such a recorded call as a write no built plan models. A linked create's call is observed only in a read of an id its response returned, at the top or in an envelope member, so another unseen item's read is never taken for it. diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index ef0a9987ecb..3a9610c2199 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1691,6 +1691,83 @@ describe("creates read under another path", () => { }), ).toMatchObject({ status: 201 }); }); +}); + +describe("path values of creates read under another path", () => { + it("refuses a linked create that changes one of two path values its template names alike", () => { + const note = (id: number, title: string) => ({ id, title }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const group = "/api/projects/11/groups/5"; + const notes = servedFrom([ + ["GET", `${group}/notes`, [alpha, beta]], + ["GET", `${group}/notes/1001`, alpha], + ["GET", `${group}/notes/1002`, beta], + ["POST", `${group}/publish`, { id: 1003 }, 201, { title: "Gamma" }], + ["GET", `${group}/notes/1003`, gamma], + ["GET", `${group}/notes`, [alpha, beta, gamma]], + ]); + const publish = notes.source.manifest.tools.find( + (tool) => tool.method === "POST", + )!; + expect(publish.path_template).toBe( + "/api/projects/{numeric}/groups/{numeric}/publish", + ); + const [project, groupArgument] = + environmentToolArguments(publish).path.values(); + expect(notes.state.writes.get(publish.name)).toMatchObject({ + served: true, + collection: `${group}/notes`, + }); + // Project 12's group 5 is another source, though the group value matches. + expect( + notes.refusal(publish.name, { + [project!]: "12", + [groupArgument!]: "5", + body: { title: "Delta" }, + }), + ).toMatchObject({ code: "invalid_request" }); + }); + + it("fills a linked create's path field with the decoded value, whichever spelling the call uses", () => { + const note = (id: number, title: string) => ({ + id, + title, + project: "my org1", + }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const other = { id: 2001, title: "Other", project: "my org2" }; + const project = "/api/projects/my%20org1"; + for (const spelling of ["my%20org1", "my org1"]) { + // A second project makes the project segment a path parameter. + const notes = servedFrom([ + ["GET", "/api/projects/my%20org2/notes", [other]], + ["GET", "/api/projects/my%20org2/notes/2001", other], + ["GET", `${project}/notes`, [alpha, beta]], + ["GET", `${project}/notes/1001`, alpha], + ["GET", `${project}/notes/1002`, beta], + ["POST", `${project}/publish`, { id: 1003 }, 201, { title: "Gamma" }], + ["GET", `${project}/notes/1003`, gamma], + ["GET", `${project}/notes`, [alpha, beta, gamma]], + ["POST", "/api/projects/my%20org2/publish", { ok: true }, 200, {}], + ]); + notes.answer("post_projects_publish_by_project_id", { + project_id: spelling, + body: { title: "Delta" }, + }); + const created = notes.store + .snapshot() + .rea_state.entities.filter((entity) => entity.fields.title === "Delta"); + expect(created).toMatchObject([{ fields: { project: "my org1" } }]); + } + }); it("counts a linked create's call from a source that names the exemplar's only after decoding twice as another source's", () => { const note = (id: number, title: string) => ({ id, title }); diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index 7bc228e333f..1e59476ba75 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -33,6 +33,7 @@ import { } from "../../domain/analysisView/environmentStateWriteValues.js"; import { collectionMatch, + decodedSegment, isObject, scalarText, type JsonObject, @@ -288,11 +289,24 @@ const writeAnswer = ( return stateAnswer(serving, { exchange, exact }, body.value ?? null, state); }; +/** The path arguments a call supplies as given, by the template segment each fills. */ +const pathArguments = ( + tool: EnvironmentManifestTool, + args: ReplayArguments, +): Map => { + const names = environmentToolArguments(tool).path; + return new Map( + tool.params.flatMap((param) => { + const value = args[names.get(param.name) ?? param.name]; + return typeof value === "string" ? [[param.index, value] as const] : []; + }), + ); +}; + /** The collection a create writes into: a linked plan's, only for its exemplar's path arguments, else the one the call's path selects. */ const writtenCollection = ( serving: StateServing, request: WriteRequest, - call: WriteCall, ): Result => { const { tool, plan } = request; const linked = linkedCollection(plan, tool.path_template); @@ -305,7 +319,11 @@ const writtenCollection = ( ? undefined : serving.source.exchanges.get(plan.exemplar_ordinal); // No read showed where other path arguments create. - return sameLinkedSource(tool.path_template, exemplar?.path, call.pathValues) + return sameLinkedSource( + tool.path_template, + exemplar?.path, + pathArguments(tool, request.args), + ) ? ok(linked) : err( refused( @@ -323,7 +341,7 @@ const answerCreate = ( const { tool, plan } = request; const type = plan.target ?? ""; const idField = serving.store.type(type)?.id_field ?? ""; - const target = writtenCollection(serving, request, call); + const target = writtenCollection(serving, request); if (!target.ok) return target; const collection = target.value; const observed = observedEntity(serving, plan); @@ -347,10 +365,17 @@ const answerCreate = ( collection: members, observed, }); - // The gate learned path rules from the recorded path, decoded; the collection is this call's. + // The gate learned path rules from the recorded path, decoded once; the collection is this call's, else its own arguments. const created = { ...call, - pathValues: pathValuesOf(tool.path_template, collection) ?? call.pathValues, + pathValues: + pathValuesOf(tool.path_template, collection) ?? + new Map( + [...call.pathValues].map(([name, value]) => [ + name, + decodedSegment(value), + ]), + ), }; const fields = createdFields(plan, observed, created, values.generate); if (!fields.ok) return err(refused(tool, fields.error)); diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index ee36be19729..ca3d4cd4d9a 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -428,3 +428,55 @@ describe("the reads either side of a POST", () => { ).toEqual([]); }); }); + +describe("read-only decisions over many lines", () => { + it("reads each related line's records once per call, however many lines the lookup's path relates to", () => { + let reads = 0; + const lines = 2000; + const records: StateRecordFacts[] = Array.from( + { length: lines + 1 }, + (_, index) => { + const read = index < lines; + const record = { + ordinal: index, + method: read ? "GET" : "POST", + path: read ? "/api/members" : "/api/members/ids", + status: 200, + start: index, + end: index, + }; + const query = read ? `?page=${String(index)}` : undefined; + return Object.defineProperty(record, "query", { + enumerable: true, + get: () => { + reads += 1; + return query; + }, + }) as StateRecordFacts; + }, + ); + const tools: StateToolFacts[] = [ + { + name: "get_members", + method: "GET", + path_template: "/api/members", + record_ordinals: records + .slice(0, lines) + .map((record) => record.ordinal), + }, + { + name: "post_ids", + method: "POST", + path_template: "/api/members/ids", + record_ordinals: [lines], + }, + ]; + expect([ + ...readOnlyTools(tools, records, { + response: () => [], + request: () => undefined, + }), + ]).toEqual(["post_ids"]); + expect(reads).toBeLessThan(20 * records.length); + }); +}); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 69693382570..93013590923 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -160,12 +160,18 @@ export const readOnlyTools = ( const position = new Map( records.map((record, index) => [record.ordinal, index]), ); - const writesBetween = + /** The timeline indexes of the nearest state writes either side of `at`, the skipped calls aside: -1 and the length when none. */ + const nearestWrites = (skip: ReadonlySet) => - (from: number, to: number): boolean => - records - .slice(from + 1, to) - .some((record) => !skip.has(record.ordinal) && isStateWrite(record)); + (at: number): { readonly before: number; readonly after: number } => { + const writes = (index: number): boolean => + !skip.has(records[index]!.ordinal) && isStateWrite(records[index]!); + let before = at - 1; + while (before >= 0 && !writes(before)) before -= 1; + let after = at + 1; + while (after < records.length && !writes(after)) after += 1; + return { before, after }; + }; const candidates = new Map(); for (const tool of tools) { if ( @@ -177,9 +183,9 @@ export const readOnlyTools = ( .map((ordinal) => records[position.get(ordinal) ?? -1]) .filter((record): record is StateRecordFacts => record !== undefined); if (!calls.some(succeeded) || calls.some(unresolved)) continue; - const between = writesBetween(new Set(tool.record_ordinals)); + const writes = nearestWrites(new Set(tool.record_ordinals)); if ( - repeatsRead(calls, records, { position, between, io }) || + repeatsRead(calls, records, { position, writes, io }) || namesReadOperations(calls, io) || namesLookup(tool.path_template) ) @@ -187,12 +193,12 @@ export const readOnlyTools = ( } // No candidate's call explains a read change across another's, so drop vetoed candidates until none is. for (let vetoed = true; vetoed;) { - const between = writesBetween( + const writes = nearestWrites( new Set([...candidates.values()].flat().map((call) => call.ordinal)), ); vetoed = false; for (const [name, calls] of candidates) - if (changesReadsAcross(calls, records, { position, between, io })) { + if (changesReadsAcross(calls, records, { position, writes, io })) { candidates.delete(name); vetoed = true; } @@ -202,7 +208,11 @@ export const readOnlyTools = ( interface Timeline { readonly position: ReadonlyMap; - readonly between: (from: number, to: number) => boolean; + /** The nearest other writes either side of a timeline index. */ + readonly writes: (at: number) => { + readonly before: number; + readonly after: number; + }; readonly io: QueryCallIo; } @@ -225,24 +235,23 @@ const lastFinishedBefore = ( const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], - { position, between, io }: Timeline, + { position, writes, io }: Timeline, ): boolean => calls.filter(succeeded).every((call) => { const at = position.get(call.ordinal)!; + // Only reads after the last other write show the state the call met. const read = lastFinishedBefore( records - .slice(0, at) + .slice(writes(at).before + 1, at) .filter( (record) => record.method === "GET" && record.path === call.path && - succeeded(record) && - !between(position.get(record.ordinal)!, at), + succeeded(record), ), call, ); - if (read === undefined || between(position.get(read.ordinal)!, at)) - return false; + if (read === undefined) return false; const answered = io.response(call.ordinal); return answered !== undefined && same(answered, io.response(read.ordinal)); }); @@ -278,52 +287,48 @@ const lastMeaningfulWord = (segment: string): string | undefined => /** * A GET line whose path a call's path relates to reads differently, or finds its entity present on one - * side only, just before and just after it, with no other write between: the reads finished before it - * began and began after it ended, since one overlapping it may show either state. + * side only, just before and just after it, with no other write between: the read that finished last + * before it began and the first begun after it ended, since one overlapping it may show either state. + * One pass over the reads between the nearest other writes serves every line. */ const changesReadsAcross = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], - { position, between, io }: Timeline, + { position, writes, io }: Timeline, ): boolean => calls.filter(succeeded).some((call) => { const at = position.get(call.ordinal)!; - const lineOf = (record: StateRecordFacts): string => - `${record.path}${record.query ?? ""}`; - const related = records.filter( - (record) => - record.method === "GET" && - (succeeded(record) || isAbsence(record.status)) && - prefixRelated(call.path, record.path), - ); - return [...new Set(related.map(lineOf))].some((line) => { - // A read before another write shows the state that write changed, so only later ones count. - const before = lastFinishedBefore( - related.filter( - (record) => - lineOf(record) === line && - position.get(record.ordinal)! < at && - !between(position.get(record.ordinal)!, at), - ), - call, - ); - const after = related.find( - (record) => - lineOf(record) === line && - position.get(record.ordinal)! > at && - record.start >= call.end, - ); - if (before === undefined || after === undefined) return false; - const from = position.get(before.ordinal)!; - const to = position.get(after.ordinal)!; - if (between(from, at) || between(at, to)) return false; - if (succeeded(before) !== succeeded(after)) return true; - if (!succeeded(before)) return false; - const earlier = io.response(before.ordinal); - const later = io.response(after.ordinal); - return ( - earlier !== undefined && later !== undefined && !same(earlier, later) - ); + const { before: lastWrite, after: nextWrite } = writes(at); + const before = new Map(); + const after = new Map(); + for (let index = lastWrite + 1; index < nextWrite; index += 1) { + const record = records[index]!; + if ( + index === at || + record.method !== "GET" || + !(succeeded(record) || isAbsence(record.status)) || + !prefixRelated(call.path, record.path) + ) + continue; + const line = `${record.path}${record.query ?? ""}`; + const latest = before.get(line); + if (index < at) { + if ( + record.end <= call.start && + (latest === undefined || record.end >= latest.end) + ) + before.set(line, record); + } else if (record.start >= call.end && !after.has(line)) + after.set(line, record); + } + return [...after].some(([line, later]) => { + const earlier = before.get(line); + if (earlier === undefined) return false; + if (succeeded(earlier) !== succeeded(later)) return true; + if (!succeeded(earlier)) return false; + const was = io.response(earlier.ordinal); + const now = io.response(later.ordinal); + return was !== undefined && now !== undefined && !same(was, now); }); }); diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index bc110063027..6b0d5121bac 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -81,7 +81,8 @@ export const lineShapes = ( shapes.set(observation.ordinal, shape); } const key = JSON.stringify([entity.type, entity.collection, entity.id]); - const signature = [...members].sort(compare).join(","); + // A JSON array, since a member name may hold any separator. + const signature = JSON.stringify([...members].sort(compare)); if (!shape.entities.has(key)) retain(ENTRY_BYTES + textBytes(key.length + signature.length)); shape.entities.set(key, signature); @@ -104,7 +105,7 @@ const EMPTY: LineShape = { common: undefined, }; -/** Entity lookups the pairwise variant pass may make; a plan whose lines need more keeps every line checked. */ +/** Line pairs and entity lookups the variant pass may make; a plan whose lines need more keeps every line checked. */ const VARIANT_WORK_LIMIT = 1 << 24; /** Whether two lines show a shared entity with different members. */ @@ -114,6 +115,31 @@ const conflicts = (left: LineShape, right: LineShape): boolean => right.entities.has(key) && right.entities.get(key) !== members, ); +/** The base lines so far, with their shaping parameter names, the members their objects carry and those every one carries. */ +interface BaseLines { + readonly lines: StateRecordFacts[]; + readonly names: Set; + readonly carried: Set; + common: Set | undefined; +} + +/** Add a base line, keeping the totals a later line is compared with. */ +const addBase = ( + base: BaseLines, + record: StateRecordFacts, + shape: LineShape, +): void => { + base.lines.push(record); + for (const name of shapingNames(record.query)) base.names.add(name); + for (const member of shape.carried) base.carried.add(member); + const { common } = shape; + if (common !== undefined) + base.common = + base.common === undefined + ? new Set(common) + : new Set([...base.common].filter((member) => common.has(member))); +}; + /** * The latest lines that show the plan's entities in another representation than its base lines, as * an expanding or reducing query does; none when comparing every pair of lines would exceed the work limit. @@ -130,36 +156,45 @@ export const variantLines = ( (sum, line) => sum + line.entities.size, 0, ); - if (latest.length * entities > VARIANT_WORK_LIMIT) return []; + // Each line is compared with every other, pair by pair and entity by entity. + if (latest.length * (latest.length + entities) > VARIANT_WORK_LIMIT) + return []; const shape = (record: StateRecordFacts): LineShape => shapes.get(record)!; - const agreeing = new Map( - latest.map((record) => [ - record, - latest.filter( + const ranks = new Map( + latest.map((record) => { + const names = shapingNames(record.query).length; + const agreeing = latest.filter( (other) => other !== record && !conflicts(shape(record), shape(other)), - ).length, - ]), + ).length; + return [ + record, + [ + names === 0 ? 0 : 1, + projectsFields(record.query ?? undefined) ? 1 : 0, + -agreeing, + names, + shape(record).carried.size, + ], + ]; + }), ); - const size = (record: StateRecordFacts): number => shape(record).carried.size; - const rank = (record: StateRecordFacts): number[] => [ - shapingNames(record.query).length === 0 ? 0 : 1, - projectsFields(record.query ?? undefined) ? 1 : 0, - -agreeing.get(record)!, - shapingNames(record.query).length, - size(record), - ]; // Base lines first: no shaping query, then no projection, then the line most others agree with. const ordered = [...latest].sort((left, right) => { - const [a, b] = [rank(left), rank(right)]; + const [a, b] = [ranks.get(left)!, ranks.get(right)!]; const differs = a.findIndex((value, index) => value !== b[index]); return differs === -1 ? 0 : a[differs]! - b[differs]!; }); - const base: StateRecordFacts[] = []; + const base: BaseLines = { + lines: [], + names: new Set(), + carried: new Set(), + common: undefined, + }; const variants: StateRecordFacts[] = []; for (const record of ordered) { - if (base.length > 0 && isVariant(record, base, shape)) + if (base.lines.length > 0 && isVariant(record, base, shape)) variants.push(record); - else base.push(record); + else addBase(base, record, shape(record)); } return variants; }; @@ -167,30 +202,19 @@ export const variantLines = ( /** Whether a line shows a base line's entity with other members, or names a new shaping parameter while its objects carry or lack members the base lines do not. */ const isVariant = ( record: StateRecordFacts, - base: readonly StateRecordFacts[], + base: BaseLines, shape: (record: StateRecordFacts) => LineShape, ): boolean => { const mine = shape(record); - if (base.some((line) => conflicts(mine, shape(line)))) return true; - const baseNames = new Set(base.flatMap((line) => shapingNames(line.query))); - if (!shapingNames(record.query).some((name) => !baseNames.has(name))) + if (base.lines.some((line) => conflicts(mine, shape(line)))) return true; + if (!shapingNames(record.query).some((name) => !base.names.has(name))) return false; - const carried = new Set(base.flatMap((line) => [...shape(line).carried])); - const commons = base.flatMap((line) => { - const common = shape(line).common; - return common === undefined ? [] : [common]; - }); - const common = - commons.length === 0 - ? undefined - : [...commons[0]!].filter((member) => - commons.every((set) => set.has(member)), - ); + const { common } = mine; return ( - [...mine.carried].some((member) => !carried.has(member)) || - (mine.common !== undefined && - common !== undefined && - common.some((member) => !mine.common!.has(member))) + [...mine.carried].some((member) => !base.carried.has(member)) || + (common !== undefined && + base.common !== undefined && + [...base.common].some((member) => !common.has(member))) ); }; diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index 8e080a47a70..f79cdd04cbd 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -827,6 +827,85 @@ it("leaves every line checked rather than compare more lines than the variant pa expect(looked).toBeLessThan(10 * lines.length); }); +it("tells apart member names that hold the separator, so a line spelling them otherwise is a variant", () => { + const line = (ordinal: number, query: string) => ({ + ordinal, + method: "GET", + path: "/api/items/1", + query, + status: 200, + start: ordinal, + end: ordinal, + }); + const observed = (ordinal: number, object: JsonObject) => ({ + position: ordinal, + index: 0, + ordinal, + tool: "get_items_by_id", + item: true, + object, + }); + const shapes = lineShapes( + [ + { + type: "/api/items", + collection: "/api/items", + id: "1", + order: [1, 0], + observations: [ + observed(1, { id: 1, a: 1, b: 2 }), + observed(2, { id: 1, "a,b": 3 }), + ], + }, + ], + () => undefined, + ); + expect( + variantLines([line(1, "?view=x"), line(2, "?view=y")], (record) => + shapes.get(record.ordinal), + ), + ).toHaveLength(1); +}); + +it("leaves every line checked when comparing many mostly empty lines would exceed the variant pass's work", () => { + let reads = 0; + const lines = Array.from({ length: 4200 }, (_, ordinal) => { + const record = { + ordinal, + method: "GET", + path: "/api/items", + status: 200, + start: ordinal, + end: ordinal, + }; + return Object.defineProperty(record, "query", { + enumerable: true, + get: () => { + reads += 1; + return `?page=${String(ordinal)}`; + }, + }) as typeof record & { readonly query: string }; + }); + const empty = { + entities: new Map(), + carried: new Set(), + common: undefined, + }; + const shown = { + entities: new Map([ + ["1", "id"], + ["2", "id"], + ]), + carried: new Set(["id"]), + common: new Set(["id"]), + }; + expect( + variantLines(lines, (record) => (record.ordinal === 0 ? shown : empty)), + ).toEqual([]); + // Comparing every pair would read each line's query thousands of times. + expect(reads).toBeLessThan(10 * lines.length); +}); + it("releases a planning pass a rewrite cut discards before extracting the state again", () => { const recipe = (id: number, views: number) => ({ id, diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index d0306ce60c0..7a04dc86aa9 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -320,18 +320,19 @@ export const linkedCollection = ( ? plan.collection : undefined; -/** The values a recorded path gives its template's parameters as spelled, undecoded; undefined when it does not fit. */ +/** + * The values a recorded path gives its template's parameters as spelled, undecoded, by segment + * position, since a template may name two parameters alike; undefined when it does not fit. + */ export const recordedPathValues = ( template: string, path: string, -): Map | undefined => { +): Map | undefined => { if (pathValuesOf(template, path) === undefined) return undefined; const segments = segmentsOf(path); return new Map( segmentsOf(template).flatMap((segment, index) => - isParam(segment) - ? [[segment.slice(1, -1), segments[index]!] as const] - : [], + isParam(segment) ? [[index, segments[index]!] as const] : [], ), ); }; @@ -344,15 +345,15 @@ export const recordedPathValues = ( export const sameLinkedSource = ( template: string, exemplar: string | undefined, - call: ReadonlyMap | undefined, + call: ReadonlyMap | undefined, ): boolean => { const recorded = exemplar === undefined ? undefined : recordedPathValues(template, exemplar); if (recorded === undefined || call === undefined) return false; return ( recorded.size === call.size && - [...recorded].every(([name, value]) => { - const given = call.get(name); + [...recorded].every(([index, value]) => { + const given = call.get(index); return given !== undefined && pathSegmentMatches(value, given); }) ); From e3c5b2361549a4587df897fc85d2e292e7579d59 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:10:37 -0700 Subject: [PATCH 22/68] docs(environment): record the sixth review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 2c6ad4227b6..4c8cf82aef0 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -13,7 +13,7 @@ among the state-backed views. `npm run format:check`, `npx knip`, `npm run scan:todos`, `npm run docs:check`, `npm run verify:test-discovery` and `npm run mcp-catalog:check`: passed. - `npm run jscpd`: 3.49% duplicated lines over 4074 files. -- `npx vitest run --project domain --project services`: 8992 passed, 6 pre-existing skips. +- `npx vitest run --project domain --project services`: 8992 passed, 6 pre-existing skips, on main `ed069bb9`. - `npm run test:prepare`, then `npm run test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 88 passed. @@ -61,6 +61,7 @@ write tool is lost. recorded reads matching. - **Fifth round** (on main `6a34be41`): no verdict, read view or recorded read changes on the same restored captures, once the serving check passes a repeated query value as an array, as main now expects. +- **Sixth round:** no verdict, read view or recorded read changes on the restored captures. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From ca3eead47683890d55bb2dfb6d641d3683ff7bb4 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:52:33 -0700 Subject: [PATCH 23/68] fix(environment): replay late and variant-only items, fill linked path fields from the exemplar and charge membership spans - An item line first recorded after the initial window that names a new shaping parameter and shows other members is a replayed variant, like an initial one. - An item only a replayed line showed, which the state never started with, answers with its own recording; one the state held and lost stays missing. - A linked create fills its path fields from its exemplar's path decoded once, whichever accepted spelling the call sends. - Each membership change span is charged against the budget before it is kept. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 13 +-- .../agent-environments/state-view/spec.md | 5 +- .../agent-environments/state-writes/spec.md | 4 +- .../environment/environmentStateAnswer.ts | 31 ++++++- .../environmentStateWriteAnswer.test.ts | 60 ++++++++++++++ .../environmentStateWriteAnswer.ts | 55 +++++++++---- .../EnvironmentStateExtraction.ts | 69 ++++++++++++---- .../analysisView/environmentStateVariants.ts | 80 ++++++++++++------- .../analysisView/environmentStateView.test.ts | 62 ++++++++++---- .../environmentStateWrites.test.ts | 20 +++++ 10 files changed, 312 insertions(+), 87 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 1f439553fab..3283f83f664 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -32,10 +32,10 @@ its cause in the recordings and the code. The five largest shared causes: an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its type's lists or that collection showed it. Its observation is a read of an id its response returned, in an envelope too. Serving creates in that read's collection, for the exemplar's path arguments only (segment by segment, in - either spelling), and fills path fields with the arguments decoded once. A successful POST that returned an id a - type's reads only show once it began ends that type's initial window: a read still running then may show it, and a - list read shows its listed entities' own ids (identity-named, or a suffix-named field such as `projectId` distinct - across two or more when no id-named field identifies them), not those they nest. + either spelling), and fills path fields with its exemplar's path values decoded once. A successful POST that + returned an id a type's reads only show once it began ends that type's initial window: a read still running then may + show it, and a list read shows its listed entities' own ids (identity-named, or a suffix-named field such as + `projectId` distinct across two or more when no id-named field identifies them), not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's @@ -47,7 +47,10 @@ its cause in the recordings and the code. The five largest shared causes: evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more - than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. + than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. An item line first recorded + after the initial window is a variant too when it names a new shaping parameter and its object carries or lacks + members the planned lines' do not, and an item only a replayed line showed, which the state never started with, + answers with its own recording. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index e3aec1951f1..d0a992ae3be 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -45,7 +45,10 @@ later increments. and of the view's checks; the view lists it in `projected_record_ordinals`. Beside a line showing whole entities, a list line asking for some fields only (a projection value other than `*`, which asks for all) is listed there too, - and proves no identity or membership. On a view with + and proves no identity or membership. So is an item line first recorded after + the type's initial reads that names a shaping parameter none of the planned + lines named while its object carries or lacks members theirs do not, such as a + later `?expand=shelf` read. On a view with such replayed reads, serving replays a call naming a projection parameter for an entity the state holds unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate leaves out exactly diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 1ba1e633172..463290691bc 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -99,7 +99,9 @@ records that read's collection, and serving creates there, since the call's own path names no collection of the type. That collection holds only for the exemplar's path arguments, compared segment by segment, each as recorded or in the other spelling once percent-decoded: serving refuses a call with others, and the gate counts such a -recorded call as a write no built plan models. A linked create's call is +recorded call as a write no built plan models. Its path fields take the +exemplar's path values decoded once, the source it accepts, whichever spelling +the call sends. A linked create's call is observed only in a read of an id its response returned, at the top or in an envelope member, so another unseen item's read is never taken for it. diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 5705915868f..7c3c6f31412 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -219,6 +219,22 @@ export const itemCall = ( }; /** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written. */ +/** Whether the state started with the item a call names, which a served delete may since have removed. */ +const startedWithItem = ( + store: EnvironmentStateStore, + type: string, + call: ItemCall, +): boolean => { + const ids = new Set([decodedSegment(call.id), call.id]); + return store + .startedWith(type) + .some( + (entity) => + ids.has(entity.id) && + collectionMatch(entity.collection, call.segments) !== undefined, + ); +}; + export const namedEntity = ( store: EnvironmentStateStore, type: string, @@ -306,14 +322,23 @@ const answerItem = ( if (call === undefined) return err(refused(tool, `Tool ${tool.name} needs every path argument.`)); const entity = namedEntity(store, view.type, call); - if (entity === undefined) + // A projection or another representation of an entity the state holds replays as the capture's reads did. + const replayed = replayedCall(source, view, callQuery(tool, args)); + if (entity === undefined) { + // An item only a replayed line showed, which the state never started with, answers with its own recording. + if ( + replayed !== undefined && + !startedWithItem(store, view.type, call) && + selectReplayExchange(tool, source.exchanges, args, observedQuery) + ?.exact === true + ) + return fromRecording(source, tool, args, replayed, observedQuery); return missingAnswer(serving, tool, { type: view.type, collection: `/${call.segments.map(({ text }) => text).join("/")}`, id: call.id, }); - // A projection or another representation of an entity the state holds replays as the capture's reads did. - const replayed = replayedCall(source, view, callQuery(tool, args)); + } if (replayed !== undefined) return fromRecording(source, tool, args, replayed, observedQuery); const shown = shownEntity( diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 3a9610c2199..1ddfcdc5cdd 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -321,6 +321,27 @@ describe("wider write coverage", () => { }); }); +describe("items only a replayed line showed", () => { + it("replays the recorded read of an item only a variant line showed, and still finds an unrecorded one missing", () => { + const books = servedFrom([ + ["GET", "/api/books", [FIRST_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ["GET", "/api/books/2?expand=shelf", expandedBook(SECOND_BOOK)], + ]); + expect( + books.answer("get_books_by_id", { id: "2", expand: "shelf" }), + ).toMatchObject({ + status: 200, + body: expandedBook(SECOND_BOOK), + state: { source: "recording", reason: "variant" }, + }); + expect( + books.call("get_books_by_id", { id: "3", expand: "shelf" }), + ).not.toMatchObject({ ok: true, value: { status: 200 } }); + }); +}); + describe("field selections beside replayed reads", () => { it("replays a field selection no checked line gave, and answers a selection of every field from the state", () => { const books = servedFrom([ @@ -1834,3 +1855,42 @@ describe("path values of creates read under another path", () => { ).toMatchObject({ status: 201 }); }); }); + +describe("path fields of creates read under another path", () => { + it("fills a linked create's path field from its exemplar decoded once, whichever accepted spelling the call uses", () => { + const note = (id: number, title: string) => ({ + id, + title, + project: "team%31", + }); + const [alpha, beta, gamma] = [ + note(1001, "Alpha"), + note(1002, "Beta"), + note(1003, "Gamma"), + ]; + const other = { id: 2001, title: "Other", project: "team2" }; + // The recorded segment `team%2531` names the project `team%31`. + const project = "/api/projects/team%2531"; + for (const spelling of ["team%2531", "team%31"]) { + const notes = servedFrom([ + ["GET", "/api/projects/team2/notes", [other]], + ["GET", "/api/projects/team2/notes/2001", other], + ["GET", `${project}/notes`, [alpha, beta]], + ["GET", `${project}/notes/1001`, alpha], + ["GET", `${project}/notes/1002`, beta], + ["POST", `${project}/publish`, { id: 1003 }, 201, { title: "Gamma" }], + ["GET", `${project}/notes/1003`, gamma], + ["GET", `${project}/notes`, [alpha, beta, gamma]], + ["POST", "/api/projects/team2/publish", { ok: true }, 200, {}], + ]); + notes.answer("post_projects_publish_by_project_id", { + project_id: spelling, + body: { title: "Delta" }, + }); + const created = notes.store + .snapshot() + .rea_state.entities.filter((entity) => entity.fields.title === "Delta"); + expect(created).toMatchObject([{ fields: { project: "team%31" } }]); + } + }); +}); diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index 1e59476ba75..6f62edf7f37 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -303,6 +303,15 @@ const pathArguments = ( ); }; +/** The path of the recorded call a plan was built from. */ +const exemplarPath = ( + serving: StateServing, + plan: StateWritePlan, +): string | undefined => + plan.exemplar_ordinal === null + ? undefined + : serving.source.exchanges.get(plan.exemplar_ordinal)?.path; + /** The collection a create writes into: a linked plan's, only for its exemplar's path arguments, else the one the call's path selects. */ const writtenCollection = ( serving: StateServing, @@ -314,14 +323,10 @@ const writtenCollection = ( return ok( createdCollection(serving, tool, request.args, plan.target ?? ""), ); - const exemplar = - plan.exemplar_ordinal === null - ? undefined - : serving.source.exchanges.get(plan.exemplar_ordinal); // No read showed where other path arguments create. return sameLinkedSource( tool.path_template, - exemplar?.path, + exemplarPath(serving, plan), pathArguments(tool, request.args), ) ? ok(linked) @@ -333,6 +338,36 @@ const writtenCollection = ( ); }; +/** + * The path values a create's path fields take, decoded once as the gate learned them: a linked + * create accepts its exemplar's source only, so it takes that; another the collection this call + * selects, else its own arguments. + */ +const createdPathValues = ( + serving: StateServing, + request: WriteRequest, + call: WriteCall, + collection: string, +): ReadonlyMap => { + const { tool, plan } = request; + const exemplar = + linkedCollection(plan, tool.path_template) === undefined + ? undefined + : exemplarPath(serving, plan); + return ( + (exemplar === undefined + ? undefined + : pathValuesOf(tool.path_template, exemplar)) ?? + pathValuesOf(tool.path_template, collection) ?? + new Map( + [...call.pathValues].map(([name, value]) => [ + name, + decodedSegment(value), + ]), + ) + ); +}; + const answerCreate = ( serving: StateServing, request: WriteRequest, @@ -365,17 +400,9 @@ const answerCreate = ( collection: members, observed, }); - // The gate learned path rules from the recorded path, decoded once; the collection is this call's, else its own arguments. const created = { ...call, - pathValues: - pathValuesOf(tool.path_template, collection) ?? - new Map( - [...call.pathValues].map(([name, value]) => [ - name, - decodedSegment(value), - ]), - ), + pathValues: createdPathValues(serving, request, call, collection), }; const fields = createdFields(plan, observed, created, values.generate); if (!fields.ok) return err(refused(tool, fields.error)); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 4e386e46963..488755857cf 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -63,9 +63,14 @@ import { } from "./environmentStateWriteLinks.js"; import { extractWrites } from "./environmentStateWrites.js"; import { + addLine, dropObservations, lineShapes, + namesNewParameter, + noLines, + showsOtherMembers, withoutVariants, + type LineTotals, } from "./environmentStateVariants.js"; import { stateWritesOf } from "./environmentStateQueryCalls.js"; @@ -85,6 +90,12 @@ const entityKey = (type: string, collection: string, id: string): string => const requestLine = (record: StateRecordFacts): string => record.path + (record.query ?? ""); +/** The member names of the object at a pointer, none when it holds no object. */ +const membersAt = (body: JsonValue, pointer: string): Set => { + const object = at(body, pointer); + return new Set(isObject(object) ? Object.keys(object) : []); +}; + /** Derive the init state and render plans from manifest tools and timeline-ordered records. */ export class EnvironmentStateExtraction { readonly #tools: readonly StateToolFacts[]; @@ -409,11 +420,16 @@ export class EnvironmentStateExtraction { }); } - /** Later identity-free projections are evidence of replay, never initial entities. Read only those query bodies. */ + /** + * Later identity-free projections, and later lines that show the entity in another representation + * than the planned lines (a new shaping parameter, members theirs lack or always carry), are + * evidence of replay, never initial entities. Read only those query bodies. + */ #addLateProjections( tool: StateToolFacts, type: string, projected: number[], + planned: LineTotals, ): void { const limit = this.#initLimit(type); if (limit === undefined) return; @@ -424,18 +440,23 @@ export class EnvironmentStateExtraction { record.status === null || record.status < 200 || record.status >= 300 || - !projectsFields(record.query) || this.#beforeInitLimit(record, limit) ) continue; - if ( - this.#withBody( - ordinal, - (body) => - body !== undefined && - locateItem(body, lastSegmentValue(record.path)) === undefined, - ) - ) { + const projecting = projectsFields(record.query); + if (!projecting && !namesNewParameter(record.query, planned)) continue; + const replayed = this.#withBody(ordinal, (body) => { + if (body === undefined) return false; + const located = locateItem(body, lastSegmentValue(record.path)); + if (projecting) return located === undefined; + if (located === undefined) return false; + const members = membersAt(body, located.pointer); + return showsOtherMembers( + { carried: members, common: members }, + planned, + ); + }); + if (replayed) { this.#retain(ENTRY_BYTES); projected.push(ordinal); } @@ -451,12 +472,19 @@ export class EnvironmentStateExtraction { let keys: string[] | undefined; const kept: StateRecordFacts[] = []; const projected: number[] = []; + // The planned lines' representation, which a later line's is compared with. + const planned = noLines(); for (const record of recordings) { - const located = this.#withBody(record.ordinal, (body) => - body === undefined - ? null - : locateItem(body, lastSegmentValue(record.path)), - ); + const located = this.#withBody(record.ordinal, (body) => { + if (body === undefined) return null; + const found = locateItem(body, lastSegmentValue(record.path)); + if (found !== undefined) { + const members = membersAt(body, found.pointer); + this.#retain(ENTRY_BYTES * (1 + members.size)); + addLine(planned, record.query, { carried: members, common: members }); + } + return found; + }); if (located === null) { this.#recorded(tool, "body-unusable"); return; @@ -494,7 +522,7 @@ export class EnvironmentStateExtraction { return; } this.#identity.set(type, { field, basis: "path-parameter" }); - this.#addLateProjections(tool, type, projected); + this.#addLateProjections(tool, type, projected, planned); projected.sort( (left, right) => this.#position.get(left)! - this.#position.get(right)!, ); @@ -623,12 +651,19 @@ export class EnvironmentStateExtraction { for (const object of objects) if (!previous.ids.delete(scalarText(object[field])!)) changed = true; if (previous.ids.size > 0) changed = true; - if (earlier !== undefined && changed && this.#writeWithin(earlier, record)) + if ( + earlier !== undefined && + changed && + this.#writeWithin(earlier, record) + ) { + // Each kept span is charged as an entity change's is. + this.#retain(ENTRY_BYTES * 4); this.#spans.push({ type: plan.type, earlier: earlier.ordinal, later: record.ordinal, }); + } previous.ids.clear(); for (const object of objects) previous.ids.add(scalarText(object[field])!); previous.record = record; diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 6b0d5121bac..735b8811817 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -115,31 +115,61 @@ const conflicts = (left: LineShape, right: LineShape): boolean => right.entities.has(key) && right.entities.get(key) !== members, ); -/** The base lines so far, with their shaping parameter names, the members their objects carry and those every one carries. */ -interface BaseLines { - readonly lines: StateRecordFacts[]; +/** What lines compared later are compared with: the shaping parameter names they named, the members their objects carried, and those every one carried. */ +export interface LineTotals { readonly names: Set; readonly carried: Set; common: Set | undefined; } -/** Add a base line, keeping the totals a later line is compared with. */ -const addBase = ( - base: BaseLines, - record: StateRecordFacts, - shape: LineShape, +/** Totals over no lines yet. */ +export const noLines = (): LineTotals => ({ + names: new Set(), + carried: new Set(), + common: undefined, +}); + +/** Count one more line into the totals. */ +export const addLine = ( + totals: LineTotals, + query: string | null | undefined, + shape: Pick, ): void => { - base.lines.push(record); - for (const name of shapingNames(record.query)) base.names.add(name); - for (const member of shape.carried) base.carried.add(member); + for (const name of shapingNames(query)) totals.names.add(name); + for (const member of shape.carried) totals.carried.add(member); const { common } = shape; if (common !== undefined) - base.common = - base.common === undefined + totals.common = + totals.common === undefined ? new Set(common) - : new Set([...base.common].filter((member) => common.has(member))); + : new Set([...totals.common].filter((member) => common.has(member))); +}; + +/** Whether a query names a shaping parameter, paging aside, that none of the counted lines named. */ +export const namesNewParameter = ( + query: string | null | undefined, + totals: LineTotals, +): boolean => shapingNames(query).some((name) => !totals.names.has(name)); + +/** Whether a line's objects carry a member the counted lines' never did, or lack one theirs always carried. */ +export const showsOtherMembers = ( + shape: Pick, + totals: LineTotals, +): boolean => { + const { common } = shape; + return ( + [...shape.carried].some((member) => !totals.carried.has(member)) || + (common !== undefined && + totals.common !== undefined && + [...totals.common].some((member) => !common.has(member))) + ); }; +/** The base lines so far, with their totals. */ +interface BaseLines extends LineTotals { + readonly lines: StateRecordFacts[]; +} + /** * The latest lines that show the plan's entities in another representation than its base lines, as * an expanding or reducing query does; none when comparing every pair of lines would exceed the work limit. @@ -184,17 +214,15 @@ export const variantLines = ( const differs = a.findIndex((value, index) => value !== b[index]); return differs === -1 ? 0 : a[differs]! - b[differs]!; }); - const base: BaseLines = { - lines: [], - names: new Set(), - carried: new Set(), - common: undefined, - }; + const base: BaseLines = { ...noLines(), lines: [] }; const variants: StateRecordFacts[] = []; for (const record of ordered) { if (base.lines.length > 0 && isVariant(record, base, shape)) variants.push(record); - else addBase(base, record, shape(record)); + else { + base.lines.push(record); + addLine(base, record.query, shape(record)); + } } return variants; }; @@ -207,15 +235,7 @@ const isVariant = ( ): boolean => { const mine = shape(record); if (base.lines.some((line) => conflicts(mine, shape(line)))) return true; - if (!shapingNames(record.query).some((name) => !base.names.has(name))) - return false; - const { common } = mine; - return ( - [...mine.carried].some((member) => !base.carried.has(member)) || - (common !== undefined && - base.common !== undefined && - [...base.common].some((member) => !common.has(member))) - ); + return namesNewParameter(record.query, base) && showsOtherMembers(mine, base); }; /** The keys that tell replayed lines from base lines: a parameter or value only replayed lines give, or a parameter every base line names that one leaves out. */ diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index f79cdd04cbd..04532b8fb9a 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -906,6 +906,52 @@ it("leaves every line checked when comparing many mostly empty lines would excee expect(reads).toBeLessThan(10 * lines.length); }); +/** The smallest allowance, to a KiB, a capture's state projects within. */ +const allowance = (parent: AnalysisViewParent): number => { + const fits = (bytes: number): boolean => + projectAnalysisView( + parent, + { kind: "environment-state", template_rules: [...ALL_RULES] }, + { state: new EnvironmentStateAccumulator(bytes, [...ALL_RULES]) }, + ).ok; + let [low, high] = [0, 8 * 1024]; + while (high - low > 1) { + const middle = Math.floor((low + high) / 2); + if (fits(middle * 1024)) high = middle; + else low = middle; + } + return high * 1024; +}; + +it("counts each change of a line's membership across a write against the budget", () => { + const tags = 64; + // Each tag's list is read three times across two writes; the third read shows the first book again or keeps the second. + const capture = (third: number) => + captureOf([ + ...Array.from({ length: tags }, (_, tag): TimedCaptureRow => [ + "GET", + `/api/books?tag=${String(tag)}`, + [{ id: 1 }], + ]), + ["POST", "/api/view-log", { ok: true }, 200, { tag: 0 }], + ...Array.from({ length: tags }, (_, tag): TimedCaptureRow => [ + "GET", + `/api/books?tag=${String(tag)}`, + [{ id: 2 }], + ]), + ["POST", "/api/view-log", { ok: true }, 200, { tag: 1 }], + ...Array.from({ length: tags }, (_, tag): TimedCaptureRow => [ + "GET", + `/api/books?tag=${String(tag)}`, + [{ id: third }], + ]), + ]); + // Both captures keep the same entities and observations; only the second change of each line differs. + expect(allowance(capture(1)) - allowance(capture(2))).toBeGreaterThanOrEqual( + tags * 256, + ); +}); + it("releases a planning pass a rewrite cut discards before extracting the state again", () => { const recipe = (id: number, views: number) => ({ id, @@ -921,22 +967,6 @@ it("releases a planning pass a rewrite cut discards before extracting the state ["POST", "/api/view-log", { ok: true }, 200, { recipe: 1 }], ["GET", "/api/recipes/1", recipe(1, views)], ]); - const fits = (parent: AnalysisViewParent, bytes: number): boolean => - projectAnalysisView( - parent, - { kind: "environment-state", template_rules: [...ALL_RULES] }, - { state: new EnvironmentStateAccumulator(bytes, [...ALL_RULES]) }, - ).ok; - /** The smallest allowance, to a KiB, the capture's state projects within. */ - const allowance = (parent: AnalysisViewParent): number => { - let [low, high] = [0, 8 * 1024]; - while (high - low > 1) { - const middle = Math.floor((low + high) / 2); - if (fits(parent, middle * 1024)) high = middle; - else low = middle; - } - return high * 1024; - }; expect(stateOf(capture(2)).types).toMatchObject([ { collection_template: "/api/recipes", init_before_ordinal: 2 }, ]); diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 37de2f247c1..4178c572ac5 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1642,6 +1642,26 @@ describe("state order after a variant line is dropped", () => { }); }); +describe("item lines first recorded after a write", () => { + it("replays an item line that shows another representation, though first recorded after a write", () => { + const created = book(3, "Third Book", bookClock(4)); + const state = stateOf([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["POST", "/api/books", created, 201, { name: "Third Book" }], + ["GET", "/api/books/3", created], + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ]); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).toMatchObject({ + projected_record_ordinals: [5], + projected_query_keys: [{ name: "expand" }], + }); + }); +}); + describe("what a linked create observes", () => { it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { const D = note(1004, "Delta"); From eb9344bd9e81baefb7d0d5840b23de4402f22aa9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:52:35 -0700 Subject: [PATCH 24/68] docs(environment): record the seventh review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 4c8cf82aef0..e428b3b876d 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -62,6 +62,9 @@ write tool is lost. - **Fifth round** (on main `6a34be41`): no verdict, read view or recorded read changes on the same restored captures, once the serving check passes a repeated query value as an array, as main now expects. - **Sixth round:** no verdict, read view or recorded read changes on the restored captures. +- **Seventh round** (on main `96ea32b7`): WordPress's post create moves from side-effect to unconfirmed, still unserved: + its only later read, `/wp-json/wp/v2/posts/22?context=edit`, shows the edit representation (`generated_slug`), so it + is now replayed rather than checked. No served write, read view or recorded read changes. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 94b8c5576b1804fbd0264b3c5ac5e88c3722fba6 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:51:24 -0700 Subject: [PATCH 25/68] fix(environment): blame a failed read on the writes whose fields it disagrees on A failed item read with no interfering unmodelled write contradicts its creates and deletes, and an update only when a field the update wrote or its response showed differs. A create is contradicted when a later read embeds it elsewhere and the state does not. A create member is fixed to its recorded value when a constant it would have to change derives from it: its text inside a constant, a referenced entity's name, or an instant beside a sent date, matched by related field names. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-writes/spec.md | 38 +- .../EnvironmentStateWriteSimulation.ts | 42 +- .../environmentStateWriteAttribution.ts | 5 + .../environmentStateWriteBlame.test.ts | 240 ++++++++++++ .../environmentStateWriteBlame.ts | 365 ++++++++++++++++++ .../environmentStateWriteChecks.ts | 14 + .../environmentStateWriteCopies.test.ts | 201 ++++++++++ .../environmentStateWriteCopies.ts | 201 ++++++++-- .../environmentStateWriteCreate.ts | 1 + .../environmentStateWriteExplain.ts | 29 +- 10 files changed, 1089 insertions(+), 47 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteBlame.test.ts create mode 100644 src/domain/analysisView/environmentStateWriteBlame.ts create mode 100644 src/domain/analysisView/environmentStateWriteCopies.test.ts diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 463290691bc..c7625fdc59b 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -152,15 +152,27 @@ identity the client sends is an echo: value, as a delimited token (for example a URL that ends in the new id or in a slug the call sent under another name). It is rebuilt around the new value. An echoed value is not a token, nor is a copy of one: it may recur in - unrelated text. A copied member whose value also sits in text no template - rebuilds around it (beside another source in one template, or in a constant) - is accepted only with its recorded value. + unrelated text. A copied or echoed member whose value also sits in text no + template rebuilds around it (beside another source in one template, or in a + constant) is accepted only with its recorded value. 10. **Constant.** Otherwise the exemplar's value. When a constant, or the text a template keeps, contains a path value of the exemplar's call as a delimited token, the create is served only for calls naming the exemplar's collection. +A constant may also derive from a member without holding its text, when the +constant is named after the member: with a reference's `Id` or `_id` left off, +one name's letters and digits begin the other's (`parentId` and `parentName`, +`dateEndDate` and `dateEnd`), three or more of them. Such a member is accepted +only with its recorded value when it names another entity the copy holds (by +its id, among the types whose paths hold the member's name when any does; a +value shorter than 8 characters only under a member named as a reference, such +as `parentId` or `parent_id`) whose own string of 8 or more characters the +constant repeats under another name, neither name reading as a reference; or +when it sends a date or time that the constant's instant lies within two days +of (an end date stored as a time in another zone). + **Body members of a create.** A member is either accepted or not: - **Accepted.** An echoed member, a member copied whole into a field of another @@ -369,9 +381,27 @@ refuses to answer with. does not excuse a newer write the list shows undone. An item read checks the writes an unmodelled write did follow only on the members they sent, and a list with such a write is not checked again: the unmodelled write may explain the rest. +- A failed item read with no such unmodelled write contradicts the writes that + changed the whole entity (its create or delete). When one of them is + exercised, each exercised update is checked instead on the fields its effect + holds, and confirmed when those show as the copy holds them and its latest + call's response shows every other field it and the read both show (but + volatile ones and those other updates wrote) as the read does: serving + answers an update from the copy, so a response that shows the entity + otherwise would be answered wrongly. When the read differs on a field the + copy holds that no exercised update wrote, any of the writes may have caused + it, and each is contradicted. +- A failed item read whose field newly embeds an entity a create made (an + object in the field, or within it, naming it by its id and by another of its + strings of 3 or more characters, 8 or more when the id is shorter than 8), + which the copy's value lacks, contradicts that create: serving would not show + the change it made there. - A mismatch on an entity or collection that no write changed contradicts, as `side-effect`, the modelled writes since that previous check whose paths - are segment-prefix related to the read's path. + are segment-prefix related to the read's path. When a refused write's + recorded outcome since then left the entity lacking a field every recording + of its view carried, the create that made it is contradicted too: an outcome + merges only what its answer showed. - After a failed item check, the copy takes the read's recorded values (or drops the entity on a recorded absence). A list whose check failed is not checked again. diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index e411e6a78ce..ffcd77ab5d8 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -13,6 +13,7 @@ import { type StateView, } from "./environmentStateRules.js"; import { UnseenEntities } from "./environmentStateWriteAdoption.js"; +import { FailedReadBlame } from "./environmentStateWriteBlame.js"; import { linkedTarget } from "./environmentStateWriteLinks.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; @@ -121,6 +122,7 @@ export class EnvironmentStateWriteSimulation { readonly #placed = new Set(); /** Entities writes no plan models made, taken when an item read first shows them. */ readonly #unseen: UnseenEntities; + readonly #blame: FailedReadBlame; constructor(input: WriteSimulationInput) { this.#input = input; @@ -131,6 +133,17 @@ export class EnvironmentStateWriteSimulation { lastCheck: this.#lastCheck, idField: (type) => this.#types.get(type)?.id_field, }); + this.#blame = new FailedReadBlame({ + state: this.#state, + io: input.io, + records: input.records, + touched: this.#touched, + pending: this.#touchedSince, + effects: this.#effects, + inserted: this.#inserted, + idField: (type) => this.#types.get(type)?.id_field, + volatileOf: input.volatileOf, + }); for (const type of input.types) this.#types.set(type.collection_template, type); for (const tool of input.tools) @@ -291,6 +304,7 @@ export class EnvironmentStateWriteSimulation { } if (result.kind === "observed") { this.#effects.observed(this.#touched, result.targets); + this.#blame.rebased(result.targets[0]!, write.index); // A recorded outcome replaces the entity's values, not its collection's membership. this.#touched.delete(result.targets[0]!); return; @@ -302,8 +316,10 @@ export class EnvironmentStateWriteSimulation { fields: result.fields, }); this.#log.push(write); - if (result.inserted !== undefined) - this.#inserted.set(result.inserted, write.tool); + if (result.inserted === undefined) return; + this.#inserted.set(result.inserted, write.tool); + if (result.entity !== undefined) + this.#blame.inserted(result.entity, write.tool); } /** @@ -582,22 +598,22 @@ export class EnvironmentStateWriteSimulation { readonly exercised: ReadonlySet; readonly view: StateView; }): void { - if (failed.exercised.size > 0) - for (const name of failed.exercised) { - const draft = this.#drafts.get(name)!; - draft.contradictedBy ??= failed.record.ordinal; - } - else { - const since = Math.min( - ...failed.keys.map((key) => this.#lastCheck.get(key) ?? -1), - ); + const ordinal = failed.record.ordinal; + const since = Math.min( + ...failed.keys.map((key) => this.#lastCheck.get(key) ?? -1), + ); + const blame = this.#blame.of({ ...failed, since }); + for (const name of blame.confirmed) + this.#drafts.get(name)!.confirmed.push(ordinal); + for (const name of blame.contradicted) + this.#drafts.get(name)!.contradictedBy ??= ordinal; + if (failed.exercised.size === 0) for (const write of this.#log) if ( - write.index > since && + write.index > blame.after && prefixRelated(write.path, failed.record.path) ) this.#drafts.get(write.tool)!.sideEffect = true; - } if (failed.view.shape !== "item") for (const key of failed.keys) this.#taint.fail(key); } diff --git a/src/domain/analysisView/environmentStateWriteAttribution.ts b/src/domain/analysisView/environmentStateWriteAttribution.ts index 9df901921b8..7791bfc0b4e 100644 --- a/src/domain/analysisView/environmentStateWriteAttribution.ts +++ b/src/domain/analysisView/environmentStateWriteAttribution.ts @@ -210,6 +210,11 @@ export class WriteEffects { } } + /** The fields a tool's effect on an entity still holds: null for a create's or delete's whole effect, undefined when none remains. */ + changedOn(key: string, tool: string): readonly string[] | null | undefined { + return this.#changed.get(key)?.get(tool); + } + /** Whether a read showing `fields` of a target shows anything of a tool's effect there: a create's or delete's always, an update's through a field it changed; unknown claims count as shown. */ shows( tool: string, diff --git a/src/domain/analysisView/environmentStateWriteBlame.test.ts b/src/domain/analysisView/environmentStateWriteBlame.test.ts new file mode 100644 index 00000000000..045989dd047 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteBlame.test.ts @@ -0,0 +1,240 @@ +import { describe, expect, it } from "vitest"; + +import { + timedCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { + FIRST_BOOK, + SECOND_BOOK, + THIRD_BOOK, + environmentStateViewOf, + renamedBook, + type Book, +} from "../../../tests/fixtures/environmentStateWrites.js"; + +const planOf = (rows: readonly TimedCaptureRow[], tool: string) => { + const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find( + (candidate) => candidate.tool === tool, + ); + if (plan === undefined) throw new Error(`No write plan for ${tool}`); + return plan; +}; + +/** A book as its item reads show it, with the shelves its write responses leave out. */ +const shelved = (entry: Book): Book => ({ + ...entry, + shelves: [{ id: 7, name: "Main Hall" }], +}); + +const RENAMED_THIRD = renamedBook(THIRD_BOOK, "Renamed Third", 4); + +/** Shelved books, a create and an update whose responses leave the shelves out, then a read of the created book. */ +const createdThenRenamed = ( + renamed: Book, + read: Book = shelved(RENAMED_THIRD), +): TimedCaptureRow[] => [ + ["GET", "/api/books", [shelved(FIRST_BOOK), shelved(SECOND_BOOK)]], + ["GET", "/api/books/1", shelved(FIRST_BOOK)], + ["GET", "/api/books/2", shelved(SECOND_BOOK)], + ["POST", "/api/books", THIRD_BOOK, 201, { name: "Third Book" }], + ["PATCH", "/api/books/3", renamed, 200, { name: "Renamed Third" }], + ["GET", "/api/books/3", read], +]; + +describe("blame for a failed item read", () => { + it("contradicts the create that left a field out and serves the update whose own fields the read shows", () => { + const rows = createdThenRenamed(RENAMED_THIRD); + expect(planOf(rows, "post_books")).toMatchObject({ + reason: "contradicted", + contradicted_by: 5, + }); + expect(planOf(rows, "patch_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + }); + + it("contradicts an update whose response shows a field it did not send otherwise than the read", () => { + const covered = (entry: Book, cover: string): Book => ({ ...entry, cover }); + const rows = createdThenRenamed( + covered(RENAMED_THIRD, "plain"), + covered(shelved(RENAMED_THIRD), "framed"), + ); + rows[3] = [ + "POST", + "/api/books", + covered(THIRD_BOOK, "plain"), + 201, + { name: "Third Book" }, + ]; + expect(planOf(rows, "patch_books_by_id")).toMatchObject({ + reason: "contradicted", + contradicted_by: 5, + }); + }); + + it("contradicts the create, not as a side effect, when a refused update's outcome is all the read can blame", () => { + const paged = (entry: Book, pages: number): Book => ({ ...entry, pages }); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books", [shelved(paged(FIRST_BOOK, 3))]], + ["GET", "/api/books/1", shelved(paged(FIRST_BOOK, 3))], + ["POST", "/api/books", paged(THIRD_BOOK, 0), 201, { name: "Third Book" }], + // The page count changes unsent by no rule, so the update is refused and its outcome taken as recorded. + [ + "PUT", + "/api/books/3", + paged(renamedBook(THIRD_BOOK, "Renamed Third", 3), 12), + 200, + { name: "Renamed Third" }, + ], + [ + "GET", + "/api/books/3", + shelved(paged(renamedBook(THIRD_BOOK, "Renamed Third", 3), 12)), + ], + ]; + expect(planOf(rows, "put_books_by_id")).toMatchObject({ + reason: "unexplained-change", + }); + expect(planOf(rows, "post_books")).toMatchObject({ + reason: "contradicted", + contradicted_by: 4, + }); + }); + + it("contradicts a create whose entity a read of another collection newly embeds", () => { + const page = { id: 8, title: "New page", book_id: 1 }; + const old = { id: 7, title: "Old page", book_id: 1 }; + const withPages = (pages: readonly (typeof page)[]): Book => ({ + ...FIRST_BOOK, + pages: pages.map(({ id, title }) => ({ id, title })), + }); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books/1", withPages([old])], + ["GET", "/api/pages/7", old], + ["POST", "/api/pages", page, 201, { title: "New page", book_id: 1 }], + ["GET", "/api/pages/8", page], + ["GET", "/api/books/1", withPages([old, page])], + ]; + expect(planOf(rows, "post_pages")).toMatchObject({ + reason: "contradicted", + contradicted_by: 4, + }); + }); +}); + +describe("differences a failed item read cannot pin on one write", () => { + it("contradicts an update when the read differs on a field the state holds and no update wrote", () => { + const staged = (entry: Book, status: string): Book => ({ + ...entry, + status, + }); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books", [staged(FIRST_BOOK, "published")]], + ["GET", "/api/books/1", staged(FIRST_BOOK, "published")], + [ + "POST", + "/api/books", + staged(THIRD_BOOK, "draft"), + 201, + { name: "Third Book" }, + ], + [ + "PATCH", + "/api/books/3", + { + id: 3, + name: "Renamed Third", + slug: "renamed-third", + updated_at: RENAMED_THIRD.updated_at!, + }, + 200, + { name: "Renamed Third" }, + ], + ["GET", "/api/books/3", staged(RENAMED_THIRD, "review")], + ]; + expect(planOf(rows, "patch_books_by_id")).toMatchObject({ + reason: "contradicted", + contradicted_by: 4, + }); + }); + + it("does not excuse a side effect a refused update's answer did not show", () => { + const counted = ( + entry: Book, + page_count: number, + revision: number, + ): Book => ({ + ...entry, + page_count, + revision, + }); + const renamed = { ...FIRST_BOOK, name: "Renamed" }; + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books/1", counted(FIRST_BOOK, 2, 6)], + ["GET", "/api/books/1/pages/5", { id: 5, title: "Old page" }], + [ + "POST", + "/api/books/1/pages", + { id: 6, title: "New page" }, + 201, + { title: "New page" }, + ], + ["GET", "/api/books/1/pages/6", { id: 6, title: "New page" }], + // The revision jumps by no rule, so the update is refused; its answer leaves the page count out. + [ + "PUT", + "/api/books/1", + { id: 1, name: "Renamed", revision: 9 }, + 200, + { name: "Renamed" }, + ], + ["GET", "/api/books/1", counted(renamed, 3, 9)], + ]; + expect(planOf(rows, "put_books_by_id")).toMatchObject({ + reason: "unexplained-change", + }); + expect(planOf(rows, "post_books_pages_by_id")).toMatchObject({ + reason: "side-effect", + }); + }); + + it("does not take a small id and a short string another read shows for the created entity", () => { + const note = { id: 3, kind: "memo" }; + const authored = (id: number): Book => ({ + ...FIRST_BOOK, + authors: [{ id, kind: "memo" }], + }); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books/1", authored(2)], + ["GET", "/api/notes/1", { id: 1, kind: "memo" }], + ["POST", "/api/notes", note, 201, { kind: "memo" }], + ["GET", "/api/notes/3", note], + ["GET", "/api/books/1", authored(3)], + ]; + expect(planOf(rows, "post_notes")).toMatchObject({ + served: true, + checked_record_ordinals: [3], + }); + }); + + it("contradicts a create whose entity a read of another collection holds directly in a field", () => { + const page = { id: 8, title: "Chapter One Draft", book_id: 1 }; + const latest = (id: number, title: string): Book => ({ + ...FIRST_BOOK, + latest_page: { id, title }, + }); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books/1", latest(7, "Prologue Notes")], + ["GET", "/api/pages/7", { id: 7, title: "Prologue Notes", book_id: 1 }], + ["POST", "/api/pages", page, 201, { title: page.title, book_id: 1 }], + ["GET", "/api/pages/8", page], + ["GET", "/api/books/1", latest(8, page.title)], + ]; + expect(planOf(rows, "post_pages")).toMatchObject({ + reason: "contradicted", + contradicted_by: 4, + }); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteBlame.ts b/src/domain/analysisView/environmentStateWriteBlame.ts new file mode 100644 index 00000000000..dfe8b22b171 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteBlame.ts @@ -0,0 +1,365 @@ +import type { JsonValue } from "../jsonValue.js"; +import { + at, + isObject, + locateItem, + missingRequiredFields, + renderStateEntity, + same, + scalarText, + type JsonObject, + type StateEntity, + type StateRecordFacts, + type StateView, +} from "./environmentStateRules.js"; +import { + writtenFieldChecks, + type PendingTargets, + type TouchedTargets, + type WriteEffects, +} from "./environmentStateWriteAttribution.js"; +import { + entityTarget, + itemTarget, + type SimulatedState, +} from "./environmentStateWriteChecks.js"; +import type { WriteIo, WrittenEntity } from "./environmentStateWriteEffects.js"; +import { ENTRY_BYTES } from "./webNetworkRouteTemplates.js"; + +/** Shorter strings are too common for a matching member to tie an embedded object to an entity. */ +const EMBED_MATCH_MIN_LENGTH = 3; + +/** A shorter id, as a small integer, names many entities, so the matching member must be this long. */ +const EMBED_SHORT_ID_MATCH_LENGTH = 8; + +/** What blaming a failed read looks up: the simulated state, the writes since each check, and the timeline. */ +export interface BlameFacts { + readonly state: SimulatedState; + readonly io: Pick; + readonly records: readonly StateRecordFacts[]; + readonly touched: TouchedTargets; + readonly pending: PendingTargets; + readonly effects: WriteEffects; + /** Entities a create inserted, by target, with the create's tool. */ + readonly inserted: ReadonlyMap; + readonly idField: (type: string) => string | undefined; + readonly volatileOf: (type: string) => ReadonlySet; +} + +/** A failed read's attribution: the writes it contradicts and confirms, and the timeline index after which related writes are its side effects. */ +export interface Blame { + readonly contradicted: ReadonlySet; + readonly confirmed: readonly string[]; + readonly after: number; +} + +/** A failed item read: its view and target, the state's entity, and the object the read shows. */ +interface FailedItem { + readonly view: Extract; + readonly target: string; + readonly entity: StateEntity | undefined; + readonly object: JsonObject | undefined; +} + +/** An entity a create inserted, with the create's tool. */ +interface CreatedEntity extends WrittenEntity { + readonly tool: string; +} + +/** + * Attributes a failed read that no unmodelled write explains: to the writes it exercised, field by + * field when a whole-entity writer takes it, to a create whose entity it embeds elsewhere, and, when + * it exercised none, to the create of an entity a refused write's recorded outcome left lacking a + * required field. + */ +export class FailedReadBlame { + readonly #facts: BlameFacts; + readonly #created: CreatedEntity[] = []; + /** When a refused write's recorded outcome last replaced each entity's values. */ + readonly #rebased = new Map(); + + constructor(facts: BlameFacts) { + this.#facts = facts; + } + + /** Note an entity a create inserted. */ + inserted(entity: WrittenEntity, tool: string): void { + this.#facts.io.retain(ENTRY_BYTES); + this.#created.push({ ...entity, tool }); + } + + /** Note a refused write's recorded outcome replacing an entity's values. */ + rebased(target: string, index: number): void { + if (!this.#rebased.has(target)) this.#facts.io.retain(ENTRY_BYTES); + this.#rebased.set(target, index); + } + + of(failed: { + readonly view: StateView; + readonly record: StateRecordFacts; + readonly exercised: ReadonlySet; + /** The timeline index of the targets' previous check. */ + readonly since: number; + }): Blame { + const item = this.#item(failed.view, failed.record); + const contradicted = new Set(this.#embedding(item, failed.exercised)); + if (failed.exercised.size > 0) { + const blame = this.#fields(item, failed.exercised); + for (const name of blame?.contradicted ?? failed.exercised) + contradicted.add(name); + return { + contradicted, + confirmed: blame?.confirmed ?? [], + after: failed.since, + }; + } + const rebased = + item === undefined ? -1 : (this.#rebased.get(item.target) ?? -1); + const create = + rebased > failed.since + ? this.#facts.inserted.get(item!.target) + : undefined; + // A recorded outcome merges what its answer showed, so a required field it left out is still the create's. + if (create !== undefined && this.#lacksFields(item!)) + contradicted.add(create); + return { contradicted, confirmed: [], after: failed.since }; + } + + #item(view: StateView, record: StateRecordFacts): FailedItem | undefined { + if (view.shape !== "item") return undefined; + const { state, io } = this.#facts; + const { collection, id } = itemTarget(state, view.type, record); + const object = io.withBody(record.ordinal, (body) => + body === undefined || body === null ? undefined : at(body, view.pointer), + ); + return { + view, + target: entityTarget(view.type, collection, id), + entity: state.entity(view.type, collection, id), + object: isObject(object) ? object : undefined, + }; + } + + /** Field-attributed blame: whole-entity writers take the difference, each update is checked on the fields its effect holds. */ + #fields(item: FailedItem | undefined, exercised: ReadonlySet) { + if (item?.entity === undefined || item.object === undefined) + return undefined; + const { touched, pending, effects, records } = this.#facts; + const partial = new Map(); + const responses = new Map(); + for (const name of exercised) { + const sent = touched.get(item.target)?.get(name); + if (sent === undefined || sent === null) continue; + const changed = effects.changedOn(item.target, name); + partial.set(name, Array.isArray(changed) ? changed : sent); + const call = pending.get(item.target)?.at.get(name); + const response = + call === undefined + ? undefined + : this.#responseObject(records[call]!, item.entity.id); + if (response !== undefined) responses.set(name, response); + } + return fieldBlame( + { + entity: item.entity, + view: item.view, + object: item.object, + volatile: this.#facts.volatileOf(item.view.type), + }, + { exercised, partial, responses }, + ); + } + + /** The entity a write's response shows, located by its id. */ + #responseObject( + record: StateRecordFacts, + id: string, + ): JsonObject | undefined { + return this.#facts.io.withBody(record.ordinal, (body) => { + const located = body === undefined ? undefined : locateItem(body, id); + const object = + located === undefined ? undefined : at(body!, located.pointer); + return isObject(object) ? object : undefined; + }); + } + + /** The creates, other than those the read exercised, whose entity a failed item read newly embeds in another field. */ + #embedding( + item: FailedItem | undefined, + exercised: ReadonlySet, + ): string[] { + if (item?.object === undefined) return []; + const { state, idField } = this.#facts; + return embeddingCreates( + { object: item.object, entity: item.entity, type: item.view.type }, + this.#created.filter((created) => !exercised.has(created.tool)), + (created) => { + const held = state.entity(created.type, created.collection, created.id); + const field = idField(created.type); + return held === undefined || field === undefined + ? undefined + : { fields: held.fields, idField: field }; + }, + ); + } + + /** Whether the state's entity lacks a field every read of its view shows. */ + #lacksFields(item: FailedItem): boolean { + return ( + item.entity !== undefined && + missingRequiredFields( + item.entity, + item.view, + this.#facts.volatileOf(item.view.type), + ).length > 0 + ); + } +} + +/** + * How a failed item read with no interfering write attributes its difference: the writes that own + * the whole entity take it, and each update is checked on the fields its effect still holds, so an + * update whose own fields show as the state holds them, and whose response shows the entity as the + * read does, is confirmed. Undefined when no whole-entity writer was exercised, since the + * difference would then be no write's. + */ +const fieldBlame = ( + read: { + readonly entity: StateEntity; + readonly view: Extract; + readonly object: JsonObject; + readonly volatile: ReadonlySet; + }, + writes: { + readonly exercised: ReadonlySet; + /** Each exercised update's fields on the entity; whole-entity writers are absent. */ + readonly partial: ReadonlyMap; + /** The entity as each update's latest call answered it, when its response showed it. */ + readonly responses: ReadonlyMap; + }, +): + | { readonly contradicted: string[]; readonly confirmed: string[] } + | undefined => { + const whole = [...writes.exercised].filter( + (name) => !writes.partial.has(name), + ); + if (writes.partial.size === 0 || whole.length === 0) return undefined; + // A field the state holds and no exercised update wrote may differ by any exercised write's effect. + const written = new Set([...writes.partial.values()].flat()); + const shown = renderStateEntity(read.entity, read.view, read.volatile); + if ( + Object.keys(read.object).some( + (field) => + Object.hasOwn(shown, field) && + !read.volatile.has(field) && + !written.has(field) && + !same(shown[field], read.object[field]), + ) + ) + return undefined; + const outcomes = writtenFieldChecks(read.entity, read.view, read.object, { + volatile: read.volatile, + writes: writes.partial, + }); + // Serving answers an update from the state, so a response showing an unwritten field otherwise than the read would be answered wrongly. + const answered = (name: string): boolean => { + const response = writes.responses.get(name); + const others = new Set( + [...writes.partial] + .filter(([other]) => other !== name) + .flatMap(([, fields]) => fields), + ); + return ( + response === undefined || + Object.keys(response).every( + (field) => + !Object.hasOwn(read.object, field) || + read.volatile.has(field) || + others.has(field) || + same(response[field], read.object[field]), + ) + ); + }; + const confirmed = [...writes.partial.keys()].filter( + (name) => outcomes.get(name) === true && answered(name), + ); + return { + contradicted: [...writes.exercised].filter( + (name) => !confirmed.includes(name), + ), + confirmed, + }; +}; + +/** Whether a value is or holds an object naming the entity by its id and by one more of its strings, a long one when the id is short. */ +const embeds = ( + value: JsonValue | undefined, + entity: JsonObject, + idField: string, +): boolean => { + const id = scalarText(entity[idField]); + if (id === undefined || value === undefined) return false; + const length = + id.length < EMBED_SHORT_ID_MATCH_LENGTH + ? EMBED_SHORT_ID_MATCH_LENGTH + : EMBED_MATCH_MIN_LENGTH; + const pending: JsonValue[] = [value]; + for (let item = pending.pop(); item !== undefined; item = pending.pop()) { + if ( + isObject(item) && + scalarText(item[idField]) === id && + Object.entries(item).some( + ([key, member]) => + key !== idField && + typeof member === "string" && + member.length >= length && + entity[key] === member, + ) + ) + return true; + const children = Array.isArray(item) + ? item + : isObject(item) + ? Object.values(item) + : []; + for (const child of children) pending.push(child); + } + return false; +}; + +/** + * The creates whose entity a failed item read newly embeds: a field the read shows otherwise than the + * state holds it, with an object naming the created entity the state's value lacks, is a change the + * create made to another collection (a reverse embed) that serving would not show. + */ +const embeddingCreates = ( + read: { + readonly object: JsonObject; + readonly entity: StateEntity | undefined; + readonly type: string; + }, + created: readonly CreatedEntity[], + heldOf: ( + created: CreatedEntity, + ) => { readonly fields: JsonObject; readonly idField: string } | undefined, +): string[] => { + const tools = new Set(); + for (const entity of created) { + if (tools.has(entity.tool)) continue; + if (entity.type === read.type && entity.id === read.entity?.id) continue; + const held = heldOf(entity); + if (held === undefined) continue; + for (const [field, value] of Object.entries(read.object)) { + const before = read.entity?.fields[field]; + if ( + !same(before, value) && + embeds(value, held.fields, held.idField) && + !embeds(before, held.fields, held.idField) + ) { + tools.add(entity.tool); + break; + } + } + } + return [...tools]; +}; diff --git a/src/domain/analysisView/environmentStateWriteChecks.ts b/src/domain/analysisView/environmentStateWriteChecks.ts index 7526160d67a..6fd8eb9f444 100644 --- a/src/domain/analysisView/environmentStateWriteChecks.ts +++ b/src/domain/analysisView/environmentStateWriteChecks.ts @@ -50,6 +50,8 @@ export class SimulatedState { readonly #documents = new Map(); readonly #removed: RemovedTarget[] = []; readonly #served = new ServedOrder(); + /** Each held id's targets, of any type. */ + readonly #named = new Map>(); constructor( entities: readonly StateEntity[], @@ -85,6 +87,13 @@ export class SimulatedState { .filter((entity) => entity.type === type); } + /** The entities of any type held under an id. */ + named(id: string): StateEntity[] { + return [...(this.#named.get(id) ?? [])].map((key) => + this.#entities.get(key)!, + ); + } + knownCollections(type: string): readonly string[] { return this.#served.known(type); } @@ -95,6 +104,10 @@ export class SimulatedState { const known = this.#entities.has(key); this.#entities.set(key, entity); if (known) return; + this.#named.set( + entity.id, + (this.#named.get(entity.id) ?? new Set()).add(key), + ); const collection = collectionTarget(entity.type, entity.collection); const order = this.#collections.get(collection) ?? []; const at = index ?? order.length; @@ -107,6 +120,7 @@ export class SimulatedState { remove(entity: StateEntity): void { const key = entityTarget(entity.type, entity.collection, entity.id); this.#entities.delete(key); + this.#named.get(entity.id)?.delete(key); this.#served.remove(key); const collection = collectionTarget(entity.type, entity.collection); const order = this.#collections.get(collection) ?? []; diff --git a/src/domain/analysisView/environmentStateWriteCopies.test.ts b/src/domain/analysisView/environmentStateWriteCopies.test.ts new file mode 100644 index 00000000000..9406f327f64 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteCopies.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from "vitest"; + +import type { JsonObject, StateEntity } from "./environmentStateRules.js"; +import { + explainCreate, + explainUpdate, +} from "./environmentStateWriteExplain.js"; + +const START = Date.UTC(2026, 9, 18, 20, 48, 0); +const ACCOUNT = "6ad52f2f4e2aff8fd"; + +/** An entity the state holds in its type's only collection. */ +const held = (type: string, fields: JsonObject): StateEntity => ({ + type, + collection: type, + id: String(fields.id), + fields, + view_fields: [], + record_ordinals: [], +}); + +const lookup = + (...entities: readonly StateEntity[]) => + (id: string): StateEntity[] => + entities.filter((entity) => entity.id === id); + +const ACCOUNTS = lookup( + held("/api/v1/Account", { id: ACCOUNT, name: "Copperfield Annex" }), +); + +const create = ( + entity: JsonObject, + body: JsonObject, + named: (id: string) => readonly StateEntity[] = ACCOUNTS, +) => + explainCreate({ + entity, + call: { path: "/tasks", pathValues: new Map(), body }, + idField: "id", + startMs: START, + collection: [], + type: [], + named, + }).body; + +describe("members a created field derives from", () => { + it("accepts a reference only with its recorded value when a field named after it repeats the named entity's name", () => { + const body = create( + { + id: 9, + name: "Task", + parentId: ACCOUNT, + parentName: "Copperfield Annex", + }, + { name: "Task", parentId: ACCOUNT }, + ); + expect(body.accepted).toEqual(["name"]); + expect(body.fixed).toEqual([{ member: "parentId", sent: ACCOUNT }]); + }); + + it("accepts a date only with its recorded value when a field named after it lies a time zone from it", () => { + const body = create( + { + id: 9, + name: "Task", + dateEndDate: "2026-11-30", + dateEnd: "2026-12-01 00:00:00", + }, + { name: "Task", dateEndDate: "2026-11-30" }, + ); + expect(body.fixed).toEqual([{ member: "dateEndDate", sent: "2026-11-30" }]); + }); + + it("accepts an echoed member only with its recorded value when a constant holds its text", () => { + const url = "https://scratch.example.test/rea-capture-1"; + const body = create( + { + id: 9, + url, + snapshot: `https://web.archive.org/web/20261021200820/${url}`, + }, + { url }, + ); + expect(body.fixed).toEqual([{ member: "url", sent: url }]); + }); +}); + +it( + "finds the echoed members a wide body's constants hold without searching each text for each", + { timeout: 5_000 }, + () => { + const n = 8_000; + const body = Object.fromEntries( + Array.from({ length: n }, (_, index) => [ + `e${String(index)}`, + `echoed value ${String(index).padStart(6, "0")}`, + ]), + ); + const constants = Object.fromEntries( + Array.from({ length: n }, (_, index) => [ + `k${String(index)}`, + `constant text ${String(index)}`, + ]), + ); + const result = create( + { + id: 1, + ...body, + ...constants, + last: `see ${body[`e${String(n - 1)}`]!}`, + }, + body, + () => [], + ); + expect(result.fixed).toEqual([ + { member: `e${String(n - 1)}`, sent: body[`e${String(n - 1)}`] }, + ]); + }, +); + +describe("coincidences no member derives a created field from", () => { + it("keeps a reference accepted when a constant repeats another reference of the named entity", () => { + const channel = "1bdxw3qoyj8zjyyhdjbdobdf4r"; + const user = "c10c054bc2a4478bb78e0210549376b1"; + const body = create( + { id: "p1", channel_id: channel, user_id: user, message: "hi" }, + { channel_id: channel, message: "hi" }, + lookup( + held("/api/v4/channels", { + id: channel, + creator_id: user, + name: "town-square", + }), + ), + ); + expect(body.accepted).toEqual(["channel_id", "message"]); + }); + + it("keeps a reference accepted when the field repeating the named entity's text is named after something else", () => { + const thread = "7f3c2a9e1b4d4c0a"; + const body = create( + { id: 9, thread_id: thread, author_name: "Rea Admin" }, + { thread_id: thread }, + lookup(held("/api/threads", { id: thread, owner_display: "Rea Admin" })), + ); + expect(body.accepted).toEqual(["thread_id"]); + }); + + it("keeps a date accepted when the instant near it is named after something else", () => { + const body = create( + { id: 9, dueDate: "2026-11-30", created_on: "2026-11-29" }, + { dueDate: "2026-11-30" }, + ); + expect(body.accepted).toEqual(["dueDate"]); + }); + + it("reads a short value as an id only under a member named as a reference", () => { + const body = create( + { id: 9, paid: 7, paidNote: "Settled in March" }, + { paid: 7 }, + lookup(held("/api/invoices", { id: 7, note: "Settled in March" })), + ); + expect(body.accepted).toEqual(["paid"]); + }); + + it("looks a short id up among the types named after its member", () => { + const body = create( + { id: 9, product_id: 3, product_name: "Pantry Shelf" }, + { product_id: 3 }, + lookup( + held("/api/objects/products", { id: 3, name: "Cheddar Cheese" }), + held("/api/objects/locations", { id: 3, name: "Pantry Shelf" }), + ), + ); + expect(body.accepted).toEqual(["product_id"]); + }); +}); + +it("accepts an update's re-sent reference with any value, as the entity it names may differ per call", () => { + const before = { + id: 42, + title: "a", + parentId: ACCOUNT, + parentName: "Copperfield Annex", + }; + const body = explainUpdate({ + before, + after: { ...before, title: "b" }, + call: { + path: "/tasks/42", + pathValues: new Map([["task", "42"]]), + body: { title: "b", parentId: ACCOUNT }, + }, + method: "PATCH", + idField: "id", + id: "42", + startMs: START, + others: [], + }).body; + expect(body.accepted).toEqual(["title", "parentId"]); +}); diff --git a/src/domain/analysisView/environmentStateWriteCopies.ts b/src/domain/analysisView/environmentStateWriteCopies.ts index b07406b7c63..d920ffd1249 100644 --- a/src/domain/analysisView/environmentStateWriteCopies.ts +++ b/src/domain/analysisView/environmentStateWriteCopies.ts @@ -1,11 +1,13 @@ +import type { JsonValue } from "../jsonValue.js"; import { pointerTokens, scalarText, type JsonObject, + type StateEntity, } from "./environmentStateRules.js"; import { GENERATED } from "./environmentStateWriteGenerated.js"; import type { FieldRule } from "./environmentStateWriteRules.js"; -import { delimitedOffsets } from "./environmentStateWriteValues.js"; +import { delimitedOffsets, readClock } from "./environmentStateWriteValues.js"; /** Shorter body strings are too common to show that a field copied one. */ export const COPY_MIN_LENGTH = 8; @@ -48,7 +50,39 @@ export const storedMembers = ( }), ); -/** Copy rules whose value also sits in text no template rebuilds around it, so a call changing their member would leave that text stale. */ +/** A letter or digit, which joins a token to the text around it. */ +const WORD = /[\p{L}\p{N}]/u; + +const joins = (character: string | undefined): boolean => + character !== undefined && WORD.test(character); + +/** + * The texts that hold each token delimited, read in one pass per text: from each start after a + * delimiter, each length a token has that a delimiter ends, rather than a search per token and text. + */ +const holdersOf = ( + texts: ReadonlyMap, + tokens: ReadonlySet, +): Map> => { + const lengths = [...new Set([...tokens].map((token) => token.length))].sort( + (left, right) => left - right, + ); + const holders = new Map>(); + for (const [field, text] of texts) + for (let at = 0; at < text.length; at += 1) { + if (joins(text[at - 1])) continue; + for (const length of lengths) { + if (at + length > text.length) break; + if (joins(text[at + length])) continue; + const token = text.slice(at, at + length); + if (tokens.has(token)) + holders.set(token, (holders.get(token) ?? new Set()).add(field)); + } + } + return holders; +}; + +/** Copy or echo rules whose value also sits in text no template rebuilds around it, so a call changing their member would leave that text stale. */ export const strandedCopies = ( rules: readonly FieldRule[], entity: JsonObject, @@ -59,27 +93,150 @@ export const strandedCopies = ( rule.rule === "template" ? [[rule.field, rule.from] as const] : [], ), ); - return new Set( - rules.flatMap((rule) => { - const token = scalarText(entity[rule.field]); - const text = (field: string): string | undefined => { + const sources = rules.flatMap((rule) => { + const token = scalarText(entity[rule.field]); + return (rule.rule === "copy" || rule.rule === "echo") && + token !== undefined && + token.length >= COPY_MIN_LENGTH + ? [{ field: rule.field, token }] + : []; + }); + const holders = holdersOf( + new Map( + texts.flatMap((field) => { const value = entity[field]; - return field === rule.field || typeof value !== "string" - ? undefined - : value; - }; - return rule.rule === "copy" && - token !== undefined && - token.length >= COPY_MIN_LENGTH && - texts.some((field) => { - const value = text(field); - return ( - rebuilt.get(field) !== rule.field && - value !== undefined && - delimitedOffsets(value, token).length > 0 - ); - }) - ? [rule.field] + return typeof value === "string" ? [[field, value] as const] : []; + }), + ), + new Set(sources.map((source) => source.token)), + ); + return new Set( + sources.flatMap(({ field, token }) => + [...(holders.get(token) ?? [])].some( + (holder) => holder !== field && rebuilt.get(holder) !== field, + ) + ? [field] + : [], + ), + ); +}; + +/** A member name that reads as a reference to another entity: `parentId`, `parent_id`. */ +const REFERENCE_NAME = /(?:[a-z0-9]Id|[a-z0-9]ID|_id|_ID)$/; + +/** The shortest stem that ties a field's name to a member's. */ +const STEM_MIN_LENGTH = 3; + +/** A name's stem: letters and digits in lower case, less a reference's `Id`. */ +const stemOf = (name: string): string => + name + .replace(REFERENCE_NAME, (suffix) => suffix.slice(0, -2)) + .replace(/_$/u, "") + .toLowerCase() + .replace(/[^a-z0-9]/gu, ""); + +/** Whether a field's name relates to a member's: one stem begins the other (`parentId` and `parentName`, `dateEndDate` and `dateEnd`). */ +const related = (member: string, field: string): boolean => { + const [left, right] = [stemOf(member), stemOf(field)]; + return ( + Math.min(left.length, right.length) >= STEM_MIN_LENGTH && + (left.startsWith(right) || right.startsWith(left)) + ); +}; + +/** The entities a member's value names: of the types whose paths hold its stem, when any does. */ +const namedBy = ( + member: string, + id: string, + named: (id: string) => readonly StateEntity[], +): readonly StateEntity[] => { + const candidates = named(id); + const stem = stemOf(member); + const scoped = candidates.filter((entity) => + entity.type + .toLowerCase() + .replace(/[^a-z0-9]/gu, "") + .includes(stem), + ); + return scoped.length > 0 ? scoped : candidates; +}; + +/** + * Body members naming another entity whose own text a field named after the member repeats under + * another name (a parent's name beside its id): a call naming another entity would leave that field + * stale. A value shorter than a copy names an entity only under a member named as a reference. + */ +export const referencedMembers = ( + body: JsonObject, + entity: JsonObject, + texts: readonly string[], + named: (id: string) => readonly StateEntity[], +): Set => { + const members = new Set(); + for (const [member, sent] of Object.entries(body)) { + const id = scalarText(sent); + if ( + id === undefined || + (id.length < COPY_MIN_LENGTH && !REFERENCE_NAME.test(member)) + ) + continue; + const referenced = namedBy(member, id, named).filter( + (other) => other.fields !== entity, + ); + if (referenced.length === 0) continue; + // A reference repeated under another reference's name is the same entity named twice, not its text. + const repeats = (field: string): boolean => { + const value = entity[field]; + return ( + typeof value === "string" && + value.length >= COPY_MIN_LENGTH && + !REFERENCE_NAME.test(field) && + referenced.some((other) => + Object.entries(other.fields).some( + ([key, text]) => + key !== field && !REFERENCE_NAME.test(key) && text === value, + ), + ) + ); + }; + if (texts.some((field) => related(member, field) && repeats(field))) + members.add(member); + } + return members; +}; + +/** A date the call sent and an instant derived from it differ by at most a time zone and a day boundary. */ +const DERIVED_INSTANT_MS = 2 * 86_400_000; + +const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; + +/** The instant a string spells: an ISO date, or a time readClock reads. */ +const instantOf = (value: JsonValue | undefined): number | undefined => { + if (typeof value !== "string") return undefined; + return DATE_ONLY.test(value) + ? Date.parse(`${value}T00:00:00Z`) + : readClock(value)?.ms; +}; + +/** Body members sending a date or time that a constant named after the member lies within two days of: the application derived it, so another value would leave it stale. */ +export const instantMembers = ( + body: JsonObject, + entity: JsonObject, + constants: readonly string[], +): Set => { + const instants = constants.flatMap((field) => { + const at = instantOf(entity[field]); + return at === undefined ? [] : [{ field, at }]; + }); + return new Set( + Object.entries(body).flatMap(([member, sent]) => { + const ms = instantOf(sent); + return ms !== undefined && + instants.some( + ({ field, at }) => + Math.abs(at - ms) <= DERIVED_INSTANT_MS && related(member, field), + ) + ? [member] : []; }), ); diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index c41ba5afa4e..4ea0c8fd326 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -145,6 +145,7 @@ const buildCreate = ( startMs: startOf(context, step), collection: members, type: fieldsOf(context.state.ofType(type)), + named: (id) => context.state.named(id), }); const clocks = explained.rules.flatMap((rule) => rule.rule === "clock" ? [rule.field] : [], diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index 63f92b5cab3..f64e0c72bb8 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -7,6 +7,7 @@ import { same, scalarText, type JsonObject, + type StateEntity, } from "./environmentStateRules.js"; import type { FieldRule, @@ -25,6 +26,8 @@ import { } from "./environmentStateWriteValues.js"; import { COPY_MIN_LENGTH, + instantMembers, + referencedMembers, storedMembers, strandedCopies, templateRule, @@ -48,6 +51,8 @@ export interface CreateEvidence { readonly startMs: number | undefined; readonly collection: readonly JsonObject[]; readonly type: readonly JsonObject[]; + /** The entities of any type the state holds under an id. */ + readonly named?: (id: string) => readonly StateEntity[]; } /** What explaining a create looks values up in, built once per request body. */ @@ -240,19 +245,27 @@ export const explainCreate = ( const templates = rules.flatMap((rule) => rule.rule === "template" ? [rule.field] : [], ); - // A member whose copy a template cannot rebuild is accepted only with its recorded value. - const stranded = strandedCopies(rules, evidence.entity, [ - ...constants, - ...templates, + // A member whose value a template cannot rebuild, or that a constant derives from, is accepted only with its recorded value. + const texts = [...constants, ...templates]; + const stranded = strandedCopies(rules, evidence.entity, texts); + const referenced = new Set([ + ...referencedMembers( + evidence.call.body, + evidence.entity, + constants, + evidence.named ?? (() => []), + ), + ...instantMembers(evidence.call.body, evidence.entity, constants), ]); + const stored = storedMembers( + rules.filter((rule) => !stranded.has(rule.field)), + evidence.entity, + ); return { rules, body: bodyOf( evidence.call.body, - storedMembers( - rules.filter((rule) => !stranded.has(rule.field)), - evidence.entity, - ), + new Set([...stored].filter((member) => !referenced.has(member))), Object.keys(evidence.call.body), ), // A template rebuilds only its generated value, so other text it keeps ties it like a constant. From fcf8d1a600127f2f9823f15894381660b413815b Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:56:26 -0700 Subject: [PATCH 26/68] fix(environment): explain unsent update changes and nested clocks by what the recording shows An update's unsent change can be a modified-by stamp beside a created-by counterpart, a value derived from the one sent member stored nowhere (accepted only while the target holds the recorded before-value), or a sent clock the call left in its own second. Objects whose clocks all moved with the request are nested clocks, opaque tokens of a type's own length are generated, and an enveloped body is learned as its one object. A write takes only its recorded query, an echoed reference to a nested object and a state word paired with other fields stay at their recorded values, and a slug is tried before a token. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 2 +- .../agent-environments/state-writes/spec.md | 71 ++- docs/web-network-captures.md | 15 +- .../environmentStateWriteAnswer.test.ts | 171 ++++++ .../environmentStateWriteAnswer.ts | 48 +- .../analysisView/environmentStateView.ts | 26 +- .../environmentStateWriteApply.test.ts | 4 +- .../environmentStateWriteApply.ts | 37 +- .../environmentStateWriteCalls.ts | 13 +- .../environmentStateWriteCreate.ts | 30 +- .../environmentStateWriteEffects.ts | 67 ++- .../environmentStateWriteExplain.ts | 114 ++-- .../environmentStateWriteRules.ts | 29 + .../environmentStateWriteStamps.test.ts | 505 ++++++++++++++++ .../environmentStateWriteStamps.ts | 545 ++++++++++++++++++ .../environmentStateWriteValues.ts | 10 + .../environmentStateWrites.test.ts | 74 +++ 17 files changed, 1665 insertions(+), 96 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteStamps.test.ts create mode 100644 src/domain/analysisView/environmentStateWriteStamps.ts diff --git a/docs/agent-environments.md b/docs/agent-environments.md index 8559c5cd175..266bcb849b0 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -478,7 +478,7 @@ every MCP session and `data/get` then see: | Effect | Call | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `create` | Adds an entity to the collection the path names, built from the observed entity with each ruled field taken from the call or generated, at the plan's `insert` position. A plan tied to its exemplar's collection writes only there. | -| `update` | Sets the sent members on the entity the path names, constants for members accepted only with their recorded value, and the clock, increment, slug, unique and renewed changes the plan models. | +| `update` | Sets the sent members on the entity the path names, constants for members accepted only with their recorded value, and the clock, nested clock, increment, slug, stamp, derived, unique and renewed changes the plan models. | | `delete` | Removes the entity the path names. | | `document` | Merges the body into the plan's document object, or replaces it for `PUT`. | diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index c7625fdc59b..77739fe60d5 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -111,7 +111,16 @@ the exemplar. - **Request body.** The exemplar's request body must be a JSON object that could enter the state: a JSON-like media type, complete UTF-8 text within 256 KiB, exact numbers, no `__proto__` member. Otherwise the reason is - `body-unusable`. A `DELETE` takes no body. + `body-unusable`. A `DELETE` takes no body. A create's or update's body + whose only member wraps one object in a one-element array (Ghost's + `{"posts":[{...}]}`) is that object, and the plan records the member as + `body.envelope`: serving takes only a body wrapped that way. +- **Query.** Serving takes only the query parameters the exemplar sent, with + its values, since they may change what the body does (Ghost reads `html` + only with `?source=html`); a call with others is refused. The gate treats a + later recorded call sent with another query, or wrapped otherwise, as a + write its plan does not explain: it brings the entity to what the call + recorded, without attribution. - **The written entity.** The entity is observed in the exemplar's response, located by its identity value at the root, in one member, or in a one-element array, as item views locate it. When the response does not carry @@ -140,14 +149,25 @@ identity the client sends is an echo: classes. 6. **Clock.** A timestamp within 10 minutes of the exemplar's start time. The format is kept: ISO-8601 with its separator, fraction digits and zone, or - epoch seconds or milliseconds. + epoch seconds or milliseconds. An object whose every clock lies between 1 + second before the start time (a whole second's truncation) and 2 seconds + after it, in one format, is a nested clock when the type's other entities + hold that field as objects agreeing with it in every other member and + holding other clocks: served, those members take the write's clock and the + others are kept. A reference to another entity, which differs by entity or + was made before the request, is not one. 7. **Sequence.** An integer one greater than the largest value of the field in the collection, else in the type. The integer may be written as `-`-separated digit groups of one width of at least two digits (an asset number `000-005`; not a date, version or address); a served value keeps the recorded value's groups and zero padding, and digits that outgrow them lead. A later call must record the value spelled that way. -8. **Unique.** A UUID-shaped string that no other entity of the type shares. +8. **Unique.** A UUID-shaped string that no other entity of the type shares, + or an opaque token (16 to 64 letters, digits, `_` or `-`, with letters and + digits both) that no other field of the entity repeats, where every other + entity of the type holds a token of the same length and none this one. + Serving generates a token of the same length, character classes and + separator positions. 9. **Template.** A string containing a generated value, or else a copied value, as a delimited token (for example a URL that ends in the new id or in a slug the call sent under another name). It is rebuilt around the new @@ -179,6 +199,14 @@ of (an end date stored as a time in another zone). name and stored under none of its own, or the identity field's value. A member copied whole must have the JSON type of the field it is copied into. Every member the exemplar sent is required. +- **Accepted only as recorded.** An echoed member naming the object the entity + nests under the field it refers to (`collection_id` and a `collection` + object), whose other members serving would keep as recorded; and a state + word other fields go with: a lowercase word several entities share, where + every entity in another state holds a field the new one leaves null, or the + reverse (Ghost's `status: "draft"` beside `published_at: null`), unless the + tool's recorded calls sent other values of it. Updates take a member naming + a nested object only as recorded too. - **Not accepted.** A member the application stored with a different value (transformed), or one it did not show. A call that sends such a member is a tool error naming the accepted members. @@ -200,15 +228,38 @@ as sent in another letter case is the sent value, not a fresh one. A member a la which the plan's observation does not show, keeps the JSON type that call stored it as (the body's `kinds`), as an exemplar's member keeps the observation's. `PUT` requires every member the exemplar sent; `PATCH` and `POST` require at -least one. A field the exemplar's update changed without sending it is -explained as one of: +least one. A sent clock the call left as it was, stored in whole seconds and +naming the second the call ran in, is a `held-clock` the application stamps +anew (Ghost's `updated_at`, which a client sends back as it read it), when it is +the only such member the call sent: a call must send it as the entity holds it, +or it is refused, and it is served as the write's clock. A field the exemplar's +update changed without sending it is explained as one of: - clock; +- a nested clock: an object the entity held whose only changes are clocks + within 10 minutes of the start time, in one format, where the type's other + entities hold that field as objects agreeing in every other member. The gate + stores the object the first later read of the entity shows when it differs + from the write's only in those members, each within 2 seconds, as Metabase + answers an update with one instant and stores another. Serving refuses it on + an entity holding no such object; - an increment by one; -- a slug of an echoed member; -- `unique`: a UUID in place of another UUID, that no other entity of the type - holds and the call sent nowhere in its body (a version the application assigns - on every update); +- a slug of an echoed member, judged before a token, since a renamed slug is + spelled like one; +- `unique`: a UUID in place of another UUID, or an opaque token in place of + another of the same length, that no other entity of the type holds and the + call sent nowhere in its body (a version the application assigns on every + update); +- `stamp`: the acting user on a field named `modified…by`, `updated…by`, + `edited…by` or `changed…by` (or `last…`), stored on every call, when the + entity already held the value under its `created…by` counterpart + (`modifiedByName` and `createdByName`), and the call sent no member naming + the same thing (`modifiedById`); +- `derived`: when the call sent exactly one member the entity stores nowhere, + a value showing that member's text, markup aside (at least 8 characters): a + field Ghost derives from the `html` it was sent. The member is accepted only + with its recorded value, and a call sending it is served only on an entity + holding the value the recorded call found (`from`), else refused; - `renewed`: an array or object whose only changes are UUIDs replaced by ones that neither it nor another entity of the type held, as child rows an update rewrites are. The rule names the pointers it renewed at (`*` for any array @@ -219,7 +270,7 @@ explained as one of: A field the entity lacked before is a change too when the view that observed the update had shown the entity, so a field the application fills in on update -follows its rule. Any other change is `unexplained-change`. An increment or a slug applies to +follows its rule. Any other change is `unexplained-change`. An increment, a slug, a stamp or a derived value applies to every call that could take it, and `unique` and `renewed` to every call, so the plan is also `unexplained-change` when such a rule would give a call of the tool another value than the one it recorded, a recorded call kept a `unique` or diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index b0c9ed6937d..7cfe1155691 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -675,14 +675,19 @@ explains it: generated `identity` (a sequence, UUID or token, by the recorded value's shape), `echo` of a body member, `copy` of a body string of 8 or more characters, a `path` value, a `slug` of a body member, a `clock` value within 10 minutes of the request in its recorded format, a `sequence` one past the -largest value of its collection or type, a `unique` UUID, or a `template` around -a generated value; other fields keep the observed value. An update's members +largest value of its collection or type, a `unique` UUID or opaque token, a +`nested-clock` object whose clocks the request stamped, or a `template` around +a generated value; other fields keep the observed value. A body that wraps one +object in a one-element array is that object, wrapped so on every call +(`body.envelope`). An update's members echo when stored as sent; a member stored differently is accepted only with its recorded value (`body.fixed`) and stores the value the call that showed it recorded (the `value` of its `constant` rule), and a field it changed without -sending must be a clock, an increment or a slug, or the plan is -`unexplained-change`; an increment or slug must hold for every call of the -tool. Every member the first call sent is required, except by `PATCH` and +sending must be a clock, a nested clock, an increment, a slug, a fresh `unique` +value, a `stamp` of the acting user or a value `derived` from the one member it +stores nowhere, or the plan is `unexplained-change`; an increment, slug, stamp +or derived value must hold for every call of the tool. A write is served only +with the query its first call sent. Every member the first call sent is required, except by `PATCH` and `POST` updates. A read on a line `query` answers is checked against the query evaluated over diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 1ddfcdc5cdd..c377446fbbe 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -1856,6 +1856,177 @@ describe("path values of creates read under another path", () => { }); }); +/** A card whose token is a NanoID and whose edit info a create stamps, created at exchange 3 and read back. */ +const tokenCard = (id: number, token: string, at: string) => ({ + id, + name: `Card ${String(id)}`, + token, + edit: { at, by: "rea" }, +}); +const CARD_ROWS: readonly TimedCaptureRow[] = [ + [ + "GET", + "/api/cards", + [ + tokenCard(1, "chYl65ZvCJ9U6yNk-YyqK", "2026-10-01T09:00:00.000Z"), + tokenCard(2, "Qx81mP0aZkT3vB7n-Lw2e", "2026-10-01T10:00:00.000Z"), + ], + ], + [ + "GET", + "/api/cards/1", + tokenCard(1, "chYl65ZvCJ9U6yNk-YyqK", "2026-10-01T09:00:00.000Z"), + ], + [ + "GET", + "/api/cards/2", + tokenCard(2, "Qx81mP0aZkT3vB7n-Lw2e", "2026-10-01T10:00:00.000Z"), + ], + [ + "POST", + "/api/cards", + tokenCard(3, "cdMLcknG-Lcu6oWL-3ZgA", `${bookClock(3).slice(0, -1)}.030Z`), + 201, + { name: "Card 3" }, + ], + [ + "GET", + "/api/cards/3", + tokenCard(3, "cdMLcknG-Lcu6oWL-3ZgA", `${bookClock(3).slice(0, -1)}.030Z`), + ], +]; + +/** Notes whose update sends html the application stores nowhere and derives the excerpt from, and sends back the clock it read. */ +const note = (id: number, title: string, excerpt: string) => ({ + id, + title, + excerpt, + updated_at: bookClock(3), +}); +const EDITED_NOTE = note(1, "First (edited)", "Edited body text."); +const NOTE_ROWS: readonly TimedCaptureRow[] = [ + [ + "GET", + "/api/notes", + [note(1, "First", "Old body text."), note(2, "Second", "Custom excerpt.")], + ], + ["GET", "/api/notes/1", note(1, "First", "Old body text.")], + ["GET", "/api/notes/2", note(2, "Second", "Custom excerpt.")], + [ + "PATCH", + "/api/notes/1?source=html", + EDITED_NOTE, + 200, + { + title: "First (edited)", + html: "

Edited body text.

", + updated_at: bookClock(3), + }, + ], + ["GET", "/api/notes/1", EDITED_NOTE], +]; + +describe("served values an application stamps", () => { + it("takes an enveloped body as the capture sent it, and refuses one sent bare", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "PATCH", + "/api/books/1", + { books: [renamedBook(FIRST_BOOK, "Renamed Book", 3)] }, + 200, + { books: [{ name: "Renamed Book" }] }, + ], + ["GET", "/api/books/1", renamedBook(FIRST_BOOK, "Renamed Book", 3)], + ]); + const before = books.snapshot(); + expect( + books.refusal("patch_books_by_id", { + id: "2", + body: { name: "Second Edition" }, + }).message, + ).toContain('wrapped as {"books":[{...}]}'); + expect(books.snapshot()).toBe(before); + const answered = books.answer("patch_books_by_id", { + id: "2", + body: { books: [{ name: "Second Edition" }] }, + }); + expect(answered).toMatchObject({ + status: 200, + body: { + books: [{ id: 2, name: "Second Edition", slug: "second-edition" }], + }, + }); + expect(books.answer("get_books_by_id", { id: "2" }).body).toMatchObject({ + name: "Second Edition", + }); + }); + + it("generates a token spelled like the type's and stamps the edit info with the served clock", () => { + const cards = servedFrom(CARD_ROWS); + const created = cards.answer("post_cards", { body: { name: "Card 4" } }) + .body as { token: string; edit: { at: string; by: string } }; + expect(created.token).toMatch( + /^[A-Za-z0-9]{8}-[A-Za-z0-9]{7}-[A-Za-z0-9]{4}$/u, + ); + expect([ + "chYl65ZvCJ9U6yNk-YyqK", + "Qx81mP0aZkT3vB7n-Lw2e", + "cdMLcknG-Lcu6oWL-3ZgA", + ]).not.toContain(created.token); + expect(created.edit.by).toBe("rea"); + expect(created.edit.at).not.toBe(`${bookClock(3).slice(0, -1)}.030Z`); + expect(created.edit.at).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u, + ); + }); + + it("derives a value only on an entity holding what it was derived from, with the recorded query and the held clock", () => { + const notes = servedFrom(NOTE_ROWS); + const edit = ( + id: string, + updated: string, + query: { source?: string } = { source: "html" }, + ) => ({ + id, + ...query, + body: { + title: "Renamed", + html: "

Edited body text.

", + updated_at: updated, + }, + }); + const before = notes.snapshot(); + expect( + notes.refusal("patch_notes_by_id", edit("2", bookClock(3))).message, + ).toContain("derives excerpt"); + expect( + notes.refusal("patch_notes_by_id", edit("1", bookClock(3), {})).message, + ).toContain("takes only the query its recording sent (source=html)"); + expect( + notes.refusal("patch_notes_by_id", edit("1", "2026-01-01T00:00:00Z")) + .message, + ).toContain("must repeat the value the entity holds"); + expect(notes.snapshot()).toBe(before); + const answered = notes.answer("patch_notes_by_id", edit("1", bookClock(3))); + expect(answered).toMatchObject({ + status: 200, + body: { id: 1, title: "Renamed", excerpt: "Edited body text." }, + }); + expect((answered.body as { updated_at: string }).updated_at).not.toBe( + bookClock(3), + ); + // Without the member the value derives from, the update keeps the excerpt the note holds. + expect( + notes.answer("patch_notes_by_id", { + id: "2", + source: "html", + body: { title: "Second (renamed)", updated_at: bookClock(3) }, + }).body, + ).toMatchObject({ title: "Second (renamed)", excerpt: "Custom excerpt." }); + }); +}); + describe("path fields of creates read under another path", () => { it("fills a linked create's path field from its exemplar decoded once, whichever accepted spelling the call uses", () => { const note = (id: number, title: string) => ({ diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index 6f62edf7f37..d6061f4f85e 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -14,6 +14,11 @@ import { nextInteger, } from "../../domain/analysisView/environmentStateWriteExplain.js"; import { callRenewal } from "../../domain/analysisView/environmentStateWriteGenerated.js"; +import { + nestedClockValue, + queryProblem, + unenveloped, +} from "../../domain/analysisView/environmentStateWriteStamps.js"; import { linkedCollection, sameLinkedSource, @@ -26,9 +31,7 @@ import { } from "../../domain/analysisView/environmentStateWriteRules.js"; import { formatClock, - isUuid, - seededToken, - seededUuid, + seededLike, spelledLike, } from "../../domain/analysisView/environmentStateWriteValues.js"; import { @@ -49,7 +52,7 @@ import { type ReplayArguments, } from "./environmentReplay.js"; import type { EnvironmentManifestTool } from "./environmentSource.js"; -import { callSegments } from "./environmentStateCallLines.js"; +import { callQuery, callSegments } from "./environmentStateCallLines.js"; import { itemCall, missingAnswer, @@ -111,15 +114,25 @@ const unloadable = ( `${holder} would hold a value that is not exactly representable JSON, which data/add could not load back.`, ); -/** The call's body: an object, nothing, or a refusal for any other value or one holding a value the state cannot hold. */ +/** The call's body: an object, unwrapped from the envelope the capture sent it in, nothing, or a refusal for any other value or one holding a value the state cannot hold. */ const callBody = ({ tool, args, + plan, }: WriteRequest): Result => { const name = environmentToolArguments(tool).body; - const value = name === undefined ? undefined : args[name]; - if (value === undefined) return ok(undefined); - if (!isObject(value as JsonValue)) + const sent = name === undefined ? undefined : args[name]; + if (sent === undefined) return ok(undefined); + const envelope = plan.body?.envelope ?? ""; + const value = unenveloped(sent as JsonValue, plan.body?.envelope); + if (value === undefined) + return err( + refused( + tool, + `Tool ${tool.name} takes its JSON object body wrapped as {"${envelope}":[{...}]}, as the capture sent it.`, + ), + ); + if (!isObject(value)) return err(refused(tool, `Tool ${tool.name} takes a JSON object body.`)); const member = unloadableMember(value as JsonObject); return member === undefined @@ -207,7 +220,14 @@ const generator = ( `${store.state.evidenceId}:${request.tool.name}:${rule.field}:${String(write.count)}:${String(attempt)}`; switch (rule.rule) { case "clock": + case "held-clock": return ok(formatClock(write.clockMs, rule.format)); + case "nested-clock": + return nestedClockValue( + (target.current ?? target.observed)[rule.field], + rule, + formatClock(write.clockMs, rule.format), + ); case "sequence": return ok( spelledLike( @@ -226,7 +246,7 @@ const generator = ( ); case "unique": return unused(rule.field, (attempt) => - seededUuid(seed(attempt), String(exemplar)), + seededLike(seed(attempt), exemplar), ); case "renewed": return ok( @@ -252,9 +272,7 @@ const generator = ( ), ); return unused(rule.field, (attempt) => - rule.generator === "uuid" || isUuid(exemplar) - ? seededUuid(seed(attempt), String(exemplar)) - : seededToken(seed(attempt), String(exemplar)), + seededLike(seed(attempt), exemplar, rule.generator === "uuid"), ); } }; @@ -630,6 +648,12 @@ export const answerWrite = ( "The state write model cannot apply repeated query parameters; the state is unchanged.", ), ); + const query = queryProblem( + serving.source.exchanges.get(request.plan.exemplar_ordinal ?? -1)?.query, + callQuery(request.tool, request.args), + ); + if (query !== undefined) + return err(refused(request.tool, `Tool ${request.tool.name} ${query}`)); const body = callBody(request); if (!body.ok) return body; const call: WriteCall = { diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 08ddfd8df89..887ca51b162 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -224,6 +224,17 @@ const fieldRuleSchema = z.discriminatedUnion("rule", [ rule: z.literal("clock"), format: clockFormatSchema, }), + z.strictObject({ + ...ruled, + rule: z.literal("nested-clock"), + members: z.array(z.string()).min(1), + format: clockFormatSchema, + }), + z.strictObject({ + ...ruled, + rule: z.literal("held-clock"), + format: clockFormatSchema, + }), z.strictObject({ ...ruled, rule: z.literal("echo") }), z.strictObject({ ...ruled, rule: z.literal("copy"), from: z.string() }), z.strictObject({ ...ruled, rule: z.literal("path"), from: z.string() }), @@ -235,6 +246,18 @@ const fieldRuleSchema = z.discriminatedUnion("rule", [ rule: z.literal("constant"), value: jsonValueSchema, }), + z.strictObject({ + ...ruled, + rule: z.literal("stamp"), + value: jsonValueSchema, + }), + z.strictObject({ + ...ruled, + rule: z.literal("derived"), + value: jsonValueSchema, + from: jsonValueSchema, + member: z.string(), + }), ]); const insertRuleSchema = z.union([ z.strictObject({ rule: z.enum(["first", "last"]) }), @@ -297,10 +320,11 @@ const writePlanSchema = z.strictObject({ kind: z.enum(["array", "boolean", "number", "object", "string"]), }), ), + envelope: z.string().optional(), }) .nullable() .describe( - "Body members the application stored as sent (accepted), members accepted only with their recorded value (fixed), members every call sends (required), and the JSON type a later call stored an accepted member as when the observation does not show it (kinds).", + "Body members the application stored as sent (accepted), members accepted only with their recorded value (fixed), members every call sends (required), the JSON type a later call stored an accepted member as when the observation does not show it (kinds), and the member a call wraps its object in as a one-element array (envelope).", ), rules: z .array(fieldRuleSchema) diff --git a/src/domain/analysisView/environmentStateWriteApply.test.ts b/src/domain/analysisView/environmentStateWriteApply.test.ts index c34ee590dd6..e21d3d7c569 100644 --- a/src/domain/analysisView/environmentStateWriteApply.test.ts +++ b/src/domain/analysisView/environmentStateWriteApply.test.ts @@ -49,6 +49,8 @@ const generator = () => { unique: "ref-9", renewed: ["renewed-9"], clock: NOW, + "nested-clock": { at: NOW }, + "held-clock": NOW, }; const generate = (rule: GeneratedRule) => { asked.push(rule); @@ -96,7 +98,7 @@ it.each<[string, JsonObject | undefined, string]>([ [ "a fixed member with another value", { title: "B", priority: "LOW" }, - `Member priority is accepted only with the value the capture sent, because the application stored it differently (${LISTED}).`, + `Member priority is accepted only with the value the capture sent, because the application stored it differently or other recorded fields go with it (${LISTED}).`, ], [ "a number for a string", diff --git a/src/domain/analysisView/environmentStateWriteApply.ts b/src/domain/analysisView/environmentStateWriteApply.ts index 1c764f97ca8..58b84a42cb1 100644 --- a/src/domain/analysisView/environmentStateWriteApply.ts +++ b/src/domain/analysisView/environmentStateWriteApply.ts @@ -20,6 +20,7 @@ import type { WriteCall, WriteResponse, } from "./environmentStateWriteRules.js"; +import { stampProblem } from "./environmentStateWriteStamps.js"; import { integerOf, isUuid, @@ -127,7 +128,7 @@ export const bodyProblem = ( } if (fixed.has(member)) { if (!same(fixed.get(member), value)) - return `Member ${member} is accepted only with the value the capture sent, because the application stored it differently (${bodyContract(body)}).`; + return `Member ${member} is accepted only with the value the capture sent, because the application stored it differently or other recorded fields go with it (${bodyContract(body)}).`; continue; } if (!body.accepted.includes(member)) @@ -183,6 +184,8 @@ const ruledValue = ( case "unique": case "renewed": case "clock": + case "nested-clock": + case "held-clock": return generate(rule); case "echo": return ok(Object.hasOwn(body, rule.field) ? body[rule.field] : undefined); @@ -223,7 +226,7 @@ const templated = ( : undefined; }; -/** Apply the rules that derive from fields already written: slugs and templates. */ +/** Apply the rules that derive from fields already written or the call: slugs, templates and stamps. */ const derive = ( rules: readonly FieldRule[], observed: JsonObject, @@ -237,7 +240,9 @@ const derive = ( } else if (rule.rule === "template") { const value = templated(observed, written, rule); if (value !== undefined) written[rule.field] = value; - } + } else if (rule.rule === "stamp") written[rule.field] = rule.value; + else if (rule.rule === "derived" && Object.hasOwn(sent, rule.member)) + written[rule.field] = rule.value; } }; @@ -278,6 +283,20 @@ export const createdFields = ( return ok(written); }; +/** Rules an update gives a new value on every call. */ +const REGENERATED: ReadonlySet = new Set([ + "clock", + "nested-clock", + "held-clock", + "unique", +]); +const regenerated = ( + rule: FieldRule, +): rule is Extract< + GeneratedRule, + { rule: "clock" | "nested-clock" | "held-clock" | "unique" } +> => REGENERATED.has(rule.rule); + /** The fields of an updated entity: sent echoed members, the constants the plan recorded, generated and derived changes. */ export const updatedFields = ( plan: Pick, @@ -288,10 +307,11 @@ export const updatedFields = ( const { before, observed } = entity; if (plan.body === null) return err("The tool has no modelled body."); const sent = call.body ?? {}; - const problem = bodyProblem(plan.body, call, { - entity: { ...observed, ...before }, - id: call.id, - }); + const problem = + bodyProblem(plan.body, call, { + entity: { ...observed, ...before }, + id: call.id, + }) ?? stampProblem(plan.rules, before, sent); if (problem !== undefined) return err(problem); const members = Object.keys(sent).filter( (member) => member !== plan.body?.identity, @@ -311,8 +331,7 @@ export const updatedFields = ( if (was !== undefined) written[rule.field] = spelledLike(before[rule.field]!, was + 1); } else if ( - rule.rule === "clock" || - rule.rule === "unique" || + regenerated(rule) || // Child rows are renewed only on an entity that holds them. (rule.rule === "renewed" && Object.hasOwn(before, rule.field)) ) { diff --git a/src/domain/analysisView/environmentStateWriteCalls.ts b/src/domain/analysisView/environmentStateWriteCalls.ts index fef1279e11f..531d36ebbb5 100644 --- a/src/domain/analysisView/environmentStateWriteCalls.ts +++ b/src/domain/analysisView/environmentStateWriteCalls.ts @@ -11,7 +11,10 @@ import { integerOf, slugOf } from "./environmentStateWriteValues.js"; /** Whether a rule changes its field on calls that do not send it: serving applies it to every call that could. */ export const unsentChange = (rule: FieldRule): boolean => - rule.rule === "increment" || rule.rule === "slug"; + rule.rule === "increment" || + rule.rule === "slug" || + rule.rule === "stamp" || + rule.rule === "derived"; /** Whether serving gives a rule's field a new value on every call, so no call may have kept it. */ export const regenerates = (rule: FieldRule): boolean => @@ -67,7 +70,10 @@ export const contradictsEarlierCalls = ( const ruled = new Set(draft.plan.rules.map((rule) => rule.field)); return rules.some( (rule) => - (unsentChange(rule) || regenerates(rule) || rule.rule === "clock") && + (unsentChange(rule) || + regenerates(rule) || + rule.rule === "clock" || + rule.rule === "nested-clock") && !ruled.has(rule.field) && draft.updates.some(({ shown, sent, kept }) => { if (regenerates(rule)) return kept.includes(rule.field); @@ -77,6 +83,9 @@ export const contradictsEarlierCalls = ( if (rule.rule === "increment") return integerOf(value) !== undefined; // Serving stamps a clock on every call, so a field an earlier call kept contradicts it. if (rule.rule === "clock") return true; + if (rule.rule === "stamp") return !same(value, rule.value); + if (rule.rule === "derived") + return sent.has(rule.member) && !same(value, rule.value); const from = rule.rule === "slug" ? sent.get(rule.from) : undefined; return typeof from === "string" && slugOf(from) !== value; }), diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 4ea0c8fd326..8d91d1f2e9b 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -14,6 +14,12 @@ import { type SuppliedSegment, } from "./environmentStateRules.js"; import { createdFields } from "./environmentStateWriteApply.js"; +import { + envelopeMember, + envelopeOf, + isOpaqueToken, + variedMembers, +} from "./environmentStateWriteStamps.js"; import { recordedPathValues, respondedIds, @@ -146,6 +152,12 @@ const buildCreate = ( collection: members, type: fieldsOf(context.state.ofType(type)), named: (id) => context.state.named(id), + varied: variedMembers( + step.tool.record_ordinals.map((ordinal) => { + const body = context.io.requestBody(ordinal); + return envelopeOf(body)?.object ?? body; + }), + ), }); const clocks = explained.rules.flatMap((rule) => rule.rule === "clock" ? [rule.field] : [], @@ -174,7 +186,10 @@ const buildCreate = ( { idField, id: evidence.observed.id }, ), ), - body: explained.body, + body: { + ...explained.body, + ...envelopeMember(context.io.requestBody(step.record.ordinal)), + }, rules: explained.rules, collection: explained.tied || draft.linked !== undefined ? evidence.collection : null, @@ -228,7 +243,7 @@ const followsSequences = ( ); }); -/** Whether a later call's generated values take the forms serving generates them in: clocks in the learned format, unique values and UUID identities as UUIDs, and sequences in order. */ +/** Whether a later call's generated values take the forms serving generates them in: clocks in the learned format, unique values as the exemplar's kind of token, UUID identities as UUIDs, and sequences in order. */ const followsGenerated = ( context: EffectContext, draft: WriteDraft, @@ -240,9 +255,16 @@ const followsGenerated = ( return ( JSON.stringify(readClock(value)?.format) === JSON.stringify(rule.format) ); + if (rule.rule === "nested-clock") + return rule.members.every( + (member) => + isObject(value ?? null) && + JSON.stringify(readClock((value as JsonObject)[member])?.format) === + JSON.stringify(rule.format), + ); if (rule.rule === "unique") return ( - isUuid(value) && + (isUuid(value) || isOpaqueToken(value, draft.observed?.[rule.field])) && !context.state .ofType(created.type) .some((held) => held.fields[rule.field] === value) @@ -376,7 +398,7 @@ export const applyCreate = ( (draft.linked !== undefined && !fromLinkedSource(context, draft, step))) ) return UNKNOWN; - const body = requestObject(context, step.record); + const body = requestObject(context, step.record, draft); const observed = createdObservation(context, step, { type, collection, diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index e9298ff110b..abfccc1e311 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -41,6 +41,11 @@ import { viewFields, type Observed, } from "./environmentStateWriteObserve.js"; +import { + envelopeMember, + plannedObject, + restampedFields, +} from "./environmentStateWriteStamps.js"; import { readClock } from "./environmentStateWriteValues.js"; import { pathValuesOf, @@ -191,13 +196,22 @@ export const refuse = ( if (!step.observeOnly) draft.plan.reason = reason; }; +/** A call's body object; an entity write's is unwrapped from a one-element envelope, and once its plan is built only one sent with the exemplar's query and wrapping counts, as serving takes it. */ export const requestObject = ( context: EffectContext, record: StateRecordFacts, -): JsonObject | undefined => { - const body = context.io.requestBody(record.ordinal); - return isObject(body) ? body : undefined; -}; + draft?: WriteDraft, +): JsonObject | undefined => + plannedObject( + { body: context.io.requestBody(record.ordinal), query: record.query }, + draft && { + built: built(draft), + envelope: draft.plan.body?.envelope, + query: context.records.find( + (other) => other.ordinal === draft.plan.exemplar_ordinal, + )?.query, + }, + ); export const callOf = ( step: WriteStep, @@ -223,6 +237,25 @@ export const searchFrom = (context: EffectContext, step: WriteStep) => ({ queryOf: context.io.queryOf, }); +/** The later item reads of the entity a write resolved, as a forward search finds them. */ +const itemReads = ( + context: EffectContext, + entity: { + readonly type: string; + readonly idField: string; + readonly collection: string; + readonly id: string; + }, +) => ({ + ...entity, + held: () => true, + isWrite: context.isWrite, + sameItem: (record: StateRecordFacts) => { + const found = itemTarget(context.state, entity.type, record); + return found.collection === entity.collection && found.id === entity.id; + }, +}); + /** The entity an update's response shows, located by its identity, else a later item read of the target the write resolved. */ const updatedObservation = ( context: EffectContext, @@ -258,16 +291,7 @@ const updatedObservation = ( ) return own; const later = laterObservation(searchFrom(context, step), { - type: entity.type, - collection: entity.collection, - idField: entity.idField, - id: entity.id, - held: () => true, - isWrite: context.isWrite, - sameItem: (record) => { - const found = itemTarget(context.state, entity.type, record); - return found.collection === entity.collection && found.id === entity.id; - }, + ...itemReads(context, entity), // With an answer or without one, only a read whose view shows every learned clock shows what this call stamped. covers: (view) => required.every((field) => view.fields.includes(field)), }); @@ -346,7 +370,10 @@ const buildUpdate = ( id: evidence.after.id, }), ), - body: evidence.explained.body, + body: { + ...evidence.explained.body, + ...envelopeMember(context.io.requestBody(ordinal)), + }, rules: evidence.explained.rules, }); draft.observed = evidence.after.object; @@ -393,7 +420,7 @@ export const applyUpdate = ( ); return { kind: "observed", targets, entity: target }; }; - const body = requestObject(context, step.record); + const body = requestObject(context, step.record, draft); if (step.observeOnly || body === undefined) { fail(draft, step, "body-unusable"); return recorded(); @@ -425,12 +452,18 @@ export const applyUpdate = ( return recorded(); } buildUpdate(context, draft, step, { after, explained, idField }); + const stored = restampedFields( + searchFrom(context, step), + itemReads(context, { type, idField, collection, id }), + after.object, + draft.plan.rules, + ); // Serving reads the plan's observation, so the gate does too; generated values are this call's. const written = updatedFields( draft.plan, { before: entity.fields, observed: draft.observed! }, { ...call, id }, - (rule) => ok(after.object[rule.field]), + (rule) => ok(stored[rule.field]), ); const kept = keptFields(entity.fields, after.object); const disagrees = diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index f64e0c72bb8..e257be7a931 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -38,9 +38,16 @@ import { GENERATED, renewedRule, } from "./environmentStateWriteGenerated.js"; - -/** A clock value counts as written by the request when it lies this close to the request's start. */ -const CLOCK_WINDOW_MS = 10 * 60_000; +import { + createdNestedClock, + createdToken, + derivedRule, + freshToken, + isClockNear, + nestedClockRule, + pinnedEchoes, + stampRule, +} from "./environmentStateWriteStamps.js"; /** What explaining a create reads: the observed entity, the call that wrote it and the entities it joined. */ export interface CreateEvidence { @@ -53,6 +60,8 @@ export interface CreateEvidence { readonly type: readonly JsonObject[]; /** The entities of any type the state holds under an id. */ readonly named?: (id: string) => readonly StateEntity[]; + /** Members whose values the tool's recorded calls varied. */ + readonly varied?: ReadonlySet; } /** What explaining a create looks values up in, built once per request body. */ @@ -97,18 +106,6 @@ const indexBody = (body: JsonObject): BodyIndex => { return { copies, slugs }; }; -const isClockNear = ( - value: JsonValue, - startMs: number | undefined, -): boolean => { - const clock = readClock(value); - return ( - clock !== undefined && - startMs !== undefined && - Math.abs(clock.ms - startMs) <= CLOCK_WINDOW_MS - ); -}; - /** One more than the largest integer the members hold in the field, or undefined when none holds one. */ export const nextInteger = ( members: readonly JsonObject[], @@ -183,7 +180,9 @@ const generatedRule = ( evidence.type.every((member) => member[field] !== value) ) return { field, rule: "unique" }; - return undefined; + if (createdToken(field, evidence.entity, evidence.type)) + return { field, rule: "unique" }; + return createdNestedClock(field, value, evidence); }; /** Body members the application stored as sent, and the others with what they were sent. */ @@ -257,6 +256,10 @@ export const explainCreate = ( ), ...instantMembers(evidence.call.body, evidence.entity, constants), ]); + const pinned = pinnedEchoes(evidence.entity, evidence.call.body, { + type: evidence.type, + varied: evidence.varied ?? new Set(), + }); const stored = storedMembers( rules.filter((rule) => !stranded.has(rule.field)), evidence.entity, @@ -265,7 +268,11 @@ export const explainCreate = ( rules, body: bodyOf( evidence.call.body, - new Set([...stored].filter((member) => !referenced.has(member))), + new Set( + [...stored].filter( + (member) => !referenced.has(member) && !pinned.has(member), + ), + ), Object.keys(evidence.call.body), ), // A template rebuilds only its generated value, so other text it keeps ties it like a constant. @@ -303,6 +310,12 @@ const changeRule = ( if (readClock(after) !== undefined && isClockNear(after, evidence.startMs)) return { field, rule: "clock", format: readClock(after)!.format }; if (freshUuid(evidence, field)) return { field, rule: "unique" }; + // A renamed slug is spelled like a token, so the slug comes first. + const member = typeof after === "string" ? slugs.get(after) : undefined; + if (member !== undefined) return { field, rule: "slug", from: member }; + if (freshToken(evidence, field)) return { field, rule: "unique" }; + const nested = nestedClockRule(field, { before, after }, evidence); + if (nested !== undefined) return nested; // Child rows only: a single UUID that changed is a reference or a generated value, judged above. const renewed = Array.isArray(before) || isObject(before) @@ -312,10 +325,45 @@ const changeRule = ( const was = integerOf(before); if (was !== undefined && integerOf(after) === was + 1) return { field, rule: "increment" }; - const member = typeof after === "string" ? slugs.get(after) : undefined; - return member === undefined - ? undefined - : { field, rule: "slug", from: member }; + return stampRule(evidence, field) ?? derivedRule(evidence, field); +}; + +/** A sent clock the call left as it was, stored in whole seconds and naming the second the call ran in: the application stamps it anew, and the client sent back the one it read. */ +const heldClock = ( + evidence: UpdateEvidence, + member: string, + sent: JsonValue, +): boolean => { + const clock = readClock(sent); + return ( + clock !== undefined && + evidence.startMs !== undefined && + clock.ms % 1000 === 0 && + clock.subMillisecond === 0 && + Math.abs(clock.ms - evidence.startMs) < 1000 && + same(evidence.before[member], sent) && + same(evidence.after[member], sent) + ); +}; + +/** How an update stored a sent member: stamped anew as the one held clock it sent back, echoed, renewed as a fresh UUID, or as a constant. */ +const sentRule = ( + evidence: UpdateEvidence, + member: string, + held: readonly string[], +): FieldRule => { + const sent = evidence.call.body[member]!; + if (held.length === 1 && held[0] === member) + return { + field: member, + rule: "held-clock", + format: readClock(sent)!.format, + }; + if (same(evidence.after[member], sent)) + return { field: member, rule: "echo" }; + return freshUuid(evidence, member) + ? { field: member, rule: "unique" } + : { field: member, rule: "constant", value: evidence.after[member]! }; }; /** Each slug an echoed string member slugs to, from the first such member. */ @@ -347,6 +395,11 @@ export const explainUpdate = ( // A member the application replaces with a value it generates is accepted with any value. const generated = new Set(); let identity: string | null = null; + // Two clocks sent back unchanged in the call's second cannot both be ones it stamps anew, as a whole-object PUT shows. + const held = Object.keys(body).filter( + (member) => + member !== evidence.idField && heldClock(evidence, member, body[member]!), + ); for (const [member, sent] of Object.entries(body)) { // The identity is the entity's key: the path's id repeated is the identity member; another value is one the application ignored, or used to re-key the entity, which no rule models. if (member === evidence.idField) { @@ -356,18 +409,10 @@ export const explainUpdate = ( continue; } if (!Object.hasOwn(evidence.after, member)) continue; - if (same(evidence.after[member], sent)) { - echoed.add(member); - rules.push({ field: member, rule: "echo" }); - } else if (freshUuid(evidence, member)) { - generated.add(member); - rules.push({ field: member, rule: "unique" }); - } else - rules.push({ - field: member, - rule: "constant", - value: evidence.after[member]!, - }); + const rule = sentRule(evidence, member, held); + rules.push(rule); + if (rule.rule === "echo") echoed.add(member); + else if (rule.rule !== "constant") generated.add(member); } // Serving keeps every field an update does not write, so one a read shows the update removed is a change no rule models. if (evidence.readFields !== undefined) @@ -392,11 +437,12 @@ export const explainUpdate = ( } // Serving renews one UUID alike in every field, so the call must have. unexplained.push(...unexplainedRenewals(rules, evidence)); + const pinned = pinnedEchoes(evidence.after, body, { varied: new Set() }); const shaped = bodyOf( Object.fromEntries( Object.entries(body).filter(([member]) => member !== identity), ), - new Set([...echoed, ...generated]), + new Set([...echoed, ...generated].filter((member) => !pinned.has(member))), evidence.method === "PUT" ? Object.keys(body).filter((member) => member !== identity) : [], diff --git a/src/domain/analysisView/environmentStateWriteRules.ts b/src/domain/analysisView/environmentStateWriteRules.ts index 441478f5875..dc685b5b79e 100644 --- a/src/domain/analysisView/environmentStateWriteRules.ts +++ b/src/domain/analysisView/environmentStateWriteRules.ts @@ -47,6 +47,19 @@ export type GeneratedRule = readonly field: string; readonly rule: "clock"; readonly format: ClockFormat; + } + /** An object value whose members hold the write's clock, the others kept. */ + | { + readonly field: string; + readonly rule: "nested-clock"; + readonly members: string[]; + readonly format: ClockFormat; + } + /** A sent clock the application stamps anew, which a call must send as the entity holds it. */ + | { + readonly field: string; + readonly rule: "held-clock"; + readonly format: ClockFormat; }; /** How one field of a written entity gets its value; fields no rule names keep the observed value. */ @@ -63,6 +76,20 @@ export type FieldRule = readonly field: string; readonly rule: "constant"; readonly value: JsonValue; + } + /** An update stores `value`, the acting user's, without being sent it. */ + | { + readonly field: string; + readonly rule: "stamp"; + readonly value: JsonValue; + } + /** An update that sends `member` stores `value`, derived from it, on an entity holding `from` there. */ + | { + readonly field: string; + readonly rule: "derived"; + readonly value: JsonValue; + readonly from: JsonValue; + readonly member: string; }; /** Where a create places its entity in its collection's order. */ @@ -86,6 +113,8 @@ export interface WriteBody { readonly identity: string | null; /** The JSON type a later call stored an accepted member as, for members the observation does not show. */ readonly kinds: { readonly member: string; readonly kind: JsonKind }[]; + /** The member a call wraps its object in, as a one-element array. */ + readonly envelope?: string | undefined; } /** What a write answers: the written entity or its identity rendered into a recorded body, no body, or the recorded body. */ diff --git a/src/domain/analysisView/environmentStateWriteStamps.test.ts b/src/domain/analysisView/environmentStateWriteStamps.test.ts new file mode 100644 index 00000000000..3533561c49a --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteStamps.test.ts @@ -0,0 +1,505 @@ +import { describe, expect, it } from "vitest"; +import type { JsonObject } from "./environmentStateRules.js"; +import { + explainCreate, + explainUpdate, + type CreateEvidence, + type UpdateEvidence, +} from "./environmentStateWriteExplain.js"; +import type { FieldRule } from "./environmentStateWriteRules.js"; +import { + envelopeOf, + nestedClockValue, + queryKey, + stampProblem, + storedRestamp, +} from "./environmentStateWriteStamps.js"; + +const START = Date.UTC(2026, 2, 4, 5, 6, 0); +const at = (ms: number): string => new Date(ms).toISOString(); +const EDITOR = { id: 1, email: "rea@example.test" }; + +const created = ( + entity: JsonObject, + body: JsonObject, + type: readonly JsonObject[] = [], + varied: ReadonlySet = new Set(), +): CreateEvidence => ({ + entity, + call: { path: "/items", pathValues: new Map(), body }, + idField: "id", + startMs: START, + collection: [], + type, + varied, +}); + +const updated = ( + before: JsonObject, + after: JsonObject, + body: JsonObject, + others: readonly JsonObject[] = [], +): UpdateEvidence => ({ + before, + after, + call: { path: "/items/42", pathValues: new Map([["item", "42"]]), body }, + method: "PATCH", + idField: "id", + id: "42", + startMs: START, + others, +}); + +const ruleFor = ( + rules: readonly FieldRule[], + field: string, +): FieldRule | undefined => rules.find((rule) => rule.field === field); + +describe("values an update stamps without being sent them", () => { + it("stamps the acting user on a modified-by field its created-by counterpart already names", () => { + const result = explainUpdate( + updated( + { + id: "42", + name: "Draft", + createdByName: "Rea Admin", + modifiedByName: null, + }, + { + id: "42", + name: "Final", + createdByName: "Rea Admin", + modifiedByName: "Rea Admin", + }, + { name: "Final" }, + ), + ); + expect(result.unexplained).toEqual([]); + expect(ruleFor(result.rules, "modifiedByName")).toEqual({ + field: "modifiedByName", + rule: "stamp", + value: "Rea Admin", + }); + }); + + it("stamps no field that only shares a name's ending with one holding the value, nor one naming what the call sent", () => { + const loose = explainUpdate( + updated( + { + id: "42", + createdByName: "Rea Admin", + assignedUserName: null, + locationName: "Pantry", + categoryName: "Dry", + }, + { + id: "42", + createdByName: "Rea Admin", + assignedUserName: "Rea Admin", + locationName: "Pantry", + categoryName: "Pantry", + }, + { note: "x" }, + ), + ); + expect(loose.unexplained).toEqual(["assignedUserName", "categoryName"]); + const referenced = explainUpdate( + updated( + { id: "42", createdByName: "Rea Admin", modifiedByName: null }, + { + id: "42", + createdByName: "Rea Admin", + modifiedByName: "Rea Admin", + modifiedById: "7", + }, + { modifiedById: "7" }, + ), + ); + expect(referenced.unexplained).toContain("modifiedByName"); + }); + + it("derives a value from the one member the call stores nowhere when the value shows that member's text", () => { + const result = explainUpdate( + updated( + { id: "42", title: "Post", excerpt: "Old body." }, + { id: "42", title: "Post (edited)", excerpt: "Edited body text." }, + { title: "Post (edited)", html: "

Edited body text.

" }, + ), + ); + expect(result.unexplained).toEqual([]); + expect(ruleFor(result.rules, "excerpt")).toEqual({ + field: "excerpt", + rule: "derived", + value: "Edited body text.", + from: "Old body.", + member: "html", + }); + }); + + it("derives nothing a member's text does not show, nor beside a second member stored nowhere", () => { + const unrelated = explainUpdate( + updated( + { id: "42", title: "Post", excerpt: "Old body.", visibility: "public" }, + { + id: "42", + title: "Post", + excerpt: "Edited body text.", + visibility: "members", + }, + { title: "Post", html: "

Edited body text.

" }, + ), + ); + expect(unrelated.unexplained).toEqual(["visibility"]); + const twoMembers = explainUpdate( + updated( + { id: "42", title: "Post", excerpt: "Old body." }, + { id: "42", title: "Post", excerpt: "Edited body text." }, + { + title: "Post", + html: "

Edited body text.

", + note: "kept nowhere", + }, + ), + ); + expect(twoMembers.unexplained).toEqual(["excerpt"]); + }); + + it("refuses a derived value for an entity holding another than the recorded one, and a held clock sent otherwise than held", () => { + const rules: FieldRule[] = [ + { + field: "excerpt", + rule: "derived", + value: "New.", + from: "Old body.", + member: "html", + }, + { + field: "updated_at", + rule: "held-clock", + format: { kind: "iso", separator: "T", fraction: 3, zone: "Z" }, + }, + ]; + const before = { + excerpt: "Old body.", + updated_at: "2026-03-04T05:06:00.000Z", + }; + expect( + stampProblem(rules, before, { + html: "

New.

", + updated_at: before.updated_at, + }), + ).toBeUndefined(); + expect( + stampProblem( + rules, + { ...before, excerpt: "Custom." }, + { html: "

New.

" }, + ), + ).toContain("derives excerpt"); + expect( + stampProblem(rules, before, { updated_at: "2026-01-01T00:00:00.000Z" }), + ).toContain("must repeat the value"); + expect( + stampProblem( + rules, + { ...before, excerpt: "Custom." }, + { title: "No html" }, + ), + ).toBeUndefined(); + }); +}); + +describe("clocks an update sends back unchanged", () => { + it("stamps anew the one clock a call sent back in whole seconds within the call's second", () => { + const second = "2026-03-04T05:06:00.000Z"; + const held = explainUpdate( + updated( + { id: "42", title: "Post", updated_at: second }, + { id: "42", title: "Post (edited)", updated_at: second }, + { title: "Post (edited)", updated_at: second }, + ), + ); + expect(ruleFor(held.rules, "updated_at")).toEqual({ + field: "updated_at", + rule: "held-clock", + format: { kind: "iso", separator: "T", fraction: 3, zone: "Z" }, + }); + expect(held.body.accepted).toContain("updated_at"); + }); + + it("stores as sent a finer clock, and both of two clocks a whole object sent back", () => { + const finer = "2026-03-04T05:05:59.4970762Z"; + const echoed = explainUpdate( + updated( + { id: "42", title: "Item", DateCreated: finer }, + { id: "42", title: "Item (edited)", DateCreated: finer }, + { title: "Item (edited)", DateCreated: finer }, + ), + ); + expect(ruleFor(echoed.rules, "DateCreated")).toEqual({ + field: "DateCreated", + rule: "echo", + }); + const second = "2026-03-04T05:06:00.000Z"; + const whole = explainUpdate( + updated( + { id: "42", title: "Post", created_at: second, updated_at: second }, + { + id: "42", + title: "Post (edited)", + created_at: second, + updated_at: second, + }, + { title: "Post (edited)", created_at: second, updated_at: second }, + ), + ); + expect(ruleFor(whole.rules, "created_at")?.rule).toBe("echo"); + expect(ruleFor(whole.rules, "updated_at")?.rule).toBe("echo"); + }); +}); + +describe("objects whose clocks a write stamps", () => { + const editInfo = (ms: number) => ({ timestamp: at(ms), ...EDITOR }); + + it("stamps the clocks of an object a create wrote, where the type shows the same object stamped otherwise", () => { + const result = explainCreate( + created( + { id: 7, name: "Tally", editInfo: editInfo(START + 30) }, + { name: "Tally" }, + [{ id: 2, name: "Old", editInfo: editInfo(START - 86_400_000) }], + ), + ); + expect(ruleFor(result.rules, "editInfo")).toEqual({ + field: "editInfo", + rule: "nested-clock", + members: ["timestamp"], + format: { kind: "iso", separator: "T", fraction: 3, zone: "Z" }, + }); + }); + + it("stamps no object other entities hold otherwise, nor a parent made just before the request", () => { + const parent = (ms: number, id: number) => ({ + id, + name: `Parent ${String(id)}`, + created_at: at(ms), + }); + const references = explainCreate( + created({ id: 7, parent: parent(START + 30, 9) }, { name: "Child" }, [ + { id: 2, parent: parent(START - 86_400_000, 3) }, + ]), + ); + expect(ruleFor(references.rules, "parent")).toBeUndefined(); + const earlier = explainCreate( + created({ id: 7, editInfo: editInfo(START - 1_500) }, { name: "Tally" }, [ + { id: 2, editInfo: editInfo(START - 86_400_000) }, + ]), + ); + expect(ruleFor(earlier.rules, "editInfo")).toBeUndefined(); + }); + + it("restamps an object an update changed only in clocks, and not one it gave an object to", () => { + const others = [{ id: "43", editInfo: editInfo(START - 86_400_000) }]; + const restamped = explainUpdate( + updated( + { id: "42", name: "Tally", editInfo: editInfo(START - 60_000) }, + { id: "42", name: "Tally 2", editInfo: editInfo(START + 40) }, + { name: "Tally 2" }, + others, + ), + ); + expect(ruleFor(restamped.rules, "editInfo")).toMatchObject({ + rule: "nested-clock", + members: ["timestamp"], + }); + const filled = explainUpdate( + updated( + { id: "42", name: "Tally", editInfo: null }, + { id: "42", name: "Tally 2", editInfo: editInfo(START + 40) }, + { name: "Tally 2" }, + others, + ), + ); + expect(filled.unexplained).toEqual(["editInfo"]); + }); + + it("serves a nested clock only on an entity holding the object, keeping its other members", () => { + const rule: Extract = { + field: "editInfo", + rule: "nested-clock", + members: ["timestamp"], + format: { kind: "iso", separator: "T", fraction: 3, zone: "Z" }, + }; + expect(nestedClockValue({ timestamp: "old", id: 3 }, rule, "now")).toEqual({ + ok: true, + value: { timestamp: "now", id: 3 }, + }); + expect(nestedClockValue(null, rule, "now").ok).toBe(false); + }); + + it("stores a nested clock as a read restamped it, within seconds and in those members only", () => { + const own = { timestamp: "2026-10-18T20:39:29.464Z", id: 1 }; + const read = { id: 1, timestamp: "2026-10-18T20:39:29.453678Z" }; + expect(storedRestamp(own, read, ["timestamp"])).toEqual(read); + expect( + storedRestamp(own, { ...read, id: 2 }, ["timestamp"]), + ).toBeUndefined(); + expect( + storedRestamp(own, { ...read, timestamp: "2026-10-18T20:39:35.000Z" }, [ + "timestamp", + ]), + ).toBeUndefined(); + }); +}); + +describe("generated tokens", () => { + it("generates opaque tokens like the ones the type holds, unless another field repeats the value", () => { + const nanoid = explainCreate( + created( + { id: 7, name: "Tally", entity_id: "cdMLcknG-Lcu6oWL-3ZgA" }, + { name: "Tally" }, + [{ id: 2, entity_id: "chYl65ZvCJ9U6yNk-YyqK" }], + ), + ); + expect(ruleFor(nanoid.rules, "entity_id")).toEqual({ + field: "entity_id", + rule: "unique", + }); + const repeated = explainCreate( + created( + { + id: "6ad47ba51023b5000108740b", + title: "Post", + comment_id: "6ad47ba51023b5000108740b", + }, + { title: "Post" }, + [ + { + id: "6ad47b5c1023b500010873e3", + comment_id: "6ad47b5c1023b500010873e3", + }, + ], + ), + ); + expect(ruleFor(repeated.rules, "comment_id")?.rule).not.toBe("unique"); + const etag = explainUpdate( + updated( + { id: "42", Name: "Item", Etag: "3f4bd8a5a1c74f2fbd4c1e2d9a6b7c80" }, + { id: "42", Name: "Item 2", Etag: "9e1c5b7a2d4f4a8e8c3b6d1f0a2e4c69" }, + { Name: "Item 2" }, + [{ id: "43", Etag: "5a6b7c8d9e0f41a2b3c4d5e6f7a8b9c0" }], + ), + ); + expect(ruleFor(etag.rules, "Etag")).toEqual({ + field: "Etag", + rule: "unique", + }); + }); + + it("slugs a renamed title before reading the slug as a fresh token", () => { + const result = explainUpdate( + updated( + { + id: "42", + title: "Quarterly report 2025", + slug: "quarterly-report-2025", + }, + { + id: "42", + title: "Quarterly report 2026", + slug: "quarterly-report-2026", + }, + { title: "Quarterly report 2026" }, + ), + ); + expect(ruleFor(result.rules, "slug")).toEqual({ + field: "slug", + rule: "slug", + from: "title", + }); + }); +}); + +describe("members accepted only as recorded", () => { + const card = { + id: 7, + name: "Tally", + collection_id: 8, + collection: { id: 8, name: "Ledger" }, + }; + + it("takes only the recorded value of a member naming an object the entity nests", () => { + const result = explainCreate( + created(card, { name: "Tally", collection_id: 8 }), + ); + expect(result.body.accepted).toEqual(["name"]); + expect(result.body.fixed).toEqual([{ member: "collection_id", sent: 8 }]); + const update = explainUpdate( + updated( + { ...card, id: "42" }, + { ...card, id: "42", name: "Tally 2" }, + { name: "Tally 2", collection_id: 8 }, + ), + ); + expect(update.body.fixed.map(({ member }) => member)).toEqual([ + "collection_id", + ]); + }); + + it("takes only the recorded state other fields go with, unless the recorded calls varied it", () => { + const post = { id: 9, title: "New", status: "draft", published_at: null }; + const others = [ + { + id: 1, + title: "A", + status: "published", + published_at: "2026-01-01T00:00:00Z", + }, + { + id: 2, + title: "B", + status: "published", + published_at: "2026-01-02T00:00:00Z", + }, + ]; + const pinned = explainCreate( + created(post, { title: "New", status: "draft" }, others), + ); + expect(pinned.body.fixed).toEqual([{ member: "status", sent: "draft" }]); + const varied = explainCreate( + created( + post, + { title: "New", status: "draft" }, + others, + new Set(["status"]), + ), + ); + expect(varied.body.accepted).toEqual(["title", "status"]); + // A value each entity holds its own of names it, not a state. + const slugged = explainCreate( + created( + { id: 9, slug: "new-post", published_at: null }, + { slug: "new-post" }, + [ + { id: 1, slug: "a-post", published_at: "2026-01-01T00:00:00Z" }, + { id: 2, slug: "b-post", published_at: "2026-01-02T00:00:00Z" }, + ], + ), + ); + expect(slugged.body.accepted).toEqual(["slug"]); + }); +}); + +describe("call shapes", () => { + it("reads a body that wraps one object in a one-element array as that object, and spells one query one way", () => { + expect(envelopeOf({ posts: [{ title: "Post" }] })).toEqual({ + member: "posts", + object: { title: "Post" }, + }); + expect( + envelopeOf({ posts: [{ title: "A" }, { title: "B" }] }), + ).toBeUndefined(); + expect(envelopeOf({ posts: [{ title: "A" }], meta: {} })).toBeUndefined(); + expect(queryKey("?source=html&b=2")).toBe(queryKey("b=2&source=html")); + expect(queryKey(null)).toBe(""); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteStamps.ts b/src/domain/analysisView/environmentStateWriteStamps.ts new file mode 100644 index 00000000000..3fb87420fd6 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteStamps.ts @@ -0,0 +1,545 @@ +import type { JsonValue } from "../jsonValue.js"; +import { err, ok, type Result } from "../result.js"; +import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import { + IDENTITY_NAMES, + isObject, + same, + scalarText, + type JsonObject, +} from "./environmentStateRules.js"; +import { + laterObservation, + type ObservationSearch, +} from "./environmentStateWriteObserve.js"; +import type { FieldRule } from "./environmentStateWriteRules.js"; +import { isUuid, readClock } from "./environmentStateWriteValues.js"; + +/** A clock value counts as written by the request when it lies this close to the request's start. */ +const CLOCK_WINDOW_MS = 10 * 60_000; + +/** A created object's clocks lie at most this long after the request that stamped them, as a read's restamp of a write's lies from it. */ +const NESTED_WINDOW_MS = 2_000; + +/** A clock stored in whole seconds may read up to this long before the request that stamped it. */ +const TRUNCATION_MS = 1_000; + +/** An opaque generated token: letters and digits, optionally `_` or `-`, long enough to name one entity. */ +const OPAQUE_TOKEN = /^[A-Za-z0-9_-]{16,64}$/u; + +/** Verbs a field naming who last changed an entity starts with, where its `created` counterpart names who made it. */ +const CHANGED_BY: ReadonlySet = new Set([ + "modified", + "updated", + "edited", + "changed", +]); + +/** Trailing words that name a reference rather than what it refers to. */ +const REFERENCE_WORDS: ReadonlySet = new Set(["id", "ids", "name"]); + +/** The shortest sent text a derived value must show to come from it. */ +const DERIVED_TEXT_MIN = 8; + +/** A value naming one of a few states, as `draft` or `published` does. */ +const STATE_WORD = /^[a-z][a-z_-]{0,23}$/u; + +export const isClockNear = ( + value: JsonValue, + startMs: number | undefined, +): boolean => { + const clock = readClock(value); + return ( + clock !== undefined && + startMs !== undefined && + Math.abs(clock.ms - startMs) <= CLOCK_WINDOW_MS + ); +}; + +/** Whether a value is an opaque token other than a UUID or clock, spelled like the exemplar when one is given. */ +export const isOpaqueToken = ( + value: JsonValue | undefined, + exemplar?: JsonValue, +): value is string => + typeof value === "string" && + OPAQUE_TOKEN.test(value) && + /[0-9]/u.test(value) && + /[A-Za-z]/u.test(value) && + (exemplar === undefined || + (typeof exemplar === "string" && exemplar.length === value.length)) && + !isUuid(value) && + readClock(value) === undefined; + +/** A body that wraps one object in a one-element array under its only member, as `{"posts":[{...}]}` does: the member and the object. */ +export const envelopeOf = ( + body: JsonValue | undefined, +): { readonly member: string; readonly object: JsonObject } | undefined => { + if (!isObject(body)) return undefined; + const members = Object.keys(body); + const wrapped = members.length === 1 ? body[members[0]!] : undefined; + return Array.isArray(wrapped) && wrapped.length === 1 && isObject(wrapped[0]!) + ? { member: members[0]!, object: wrapped[0] } + : undefined; +}; + +/** The envelope a body wraps its object in, as a write plan's body records it. */ +export const envelopeMember = ( + body: JsonValue | undefined, +): { readonly envelope?: string } => { + const wrapped = envelopeOf(body); + return wrapped === undefined ? {} : { envelope: wrapped.member }; +}; + +/** A call's body as a plan with this envelope takes it: the object it wraps, the body itself without one, or undefined when the envelope is missing. */ +export const unenveloped = ( + body: JsonValue | undefined, + envelope: string | undefined, +): JsonValue | undefined => { + if (envelope === undefined) return body; + const wrapped = envelopeOf(body); + return wrapped?.member === envelope ? wrapped.object : undefined; +}; + +/** A call's body object as its plan takes it: an entity write's unwrapped from its envelope, and once the plan is built only one sent with the exemplar's query and wrapping. */ +export const plannedObject = ( + call: { + readonly body: JsonValue | undefined; + readonly query: string | null | undefined; + }, + plan: + | { + readonly built: boolean; + readonly envelope: string | undefined; + readonly query: string | null | undefined; + } + | undefined, +): JsonObject | undefined => { + // Serving takes only the query the exemplar sent, which may change what the body does. + if (plan?.built === true && queryKey(plan.query) !== queryKey(call.query)) + return undefined; + const envelope = + plan === undefined + ? undefined + : plan.built + ? plan.envelope + : envelopeOf(call.body)?.member; + const object = unenveloped(call.body, envelope); + return object !== undefined && isObject(object) ? object : undefined; +}; + +/** A query's parameters in one order, so two spellings of one query compare equal. */ +export const queryKey = ( + query: string | URLSearchParams | null | undefined, +): string => + new URLSearchParams( + [...new URLSearchParams(query ?? "")].sort( + ([a, x], [b, y]) => compare(a, b) || compare(x, y), + ), + ).toString(); + +/** Why a write call's query is not the one its recording sent, which may change what the body does; undefined when it is. */ +export const queryProblem = ( + recorded: string | null | undefined, + call: ReadonlyMap, +): string | undefined => { + const want = queryKey(recorded); + return want === queryKey(new URLSearchParams([...call])) + ? undefined + : `takes only the query its recording sent (${want === "" ? "none" : want}).`; +}; + +/** Whether the type's other entities hold the field as objects agreeing with this one but in the members, which hold other clocks. */ +const sharedBesides = ( + field: string, + object: JsonObject, + members: readonly string[], + others: readonly JsonObject[], +): boolean => { + const held = others.flatMap((other) => { + const value = other[field]; + return value !== undefined && isObject(value) ? [value] : []; + }); + return ( + held.length > 0 && + held.every((other) => + [...new Set([...Object.keys(other), ...Object.keys(object)])].every( + (key) => + members.includes(key) + ? readClock(other[key]) !== undefined && + !same(other[key], object[key]) + : same(other[key], object[key]), + ), + ) + ); +}; + +/** The nested-clock rule for an object whose members hold clocks in one format, when the type shows them stamped per entity. */ +const nestedRule = ( + field: string, + object: JsonObject, + members: readonly string[], + others: readonly JsonObject[], +): FieldRule | undefined => { + const formats = new Set( + members.map((key) => JSON.stringify(readClock(object[key])?.format)), + ); + return members.length > 0 && + formats.size === 1 && + sharedBesides(field, object, members, others) + ? { + field, + rule: "nested-clock", + members: [...members], + format: readClock(object[members[0]!])!.format, + } + : undefined; +}; + +/** The rule for an object field an update changed only in clocks the request wrote. */ +export const nestedClockRule = ( + field: string, + values: { readonly before: JsonValue | undefined; readonly after: JsonValue }, + evidence: { + readonly startMs: number | undefined; + readonly others: readonly JsonObject[]; + }, +): FieldRule | undefined => { + const { before, after } = values; + if (before === undefined || !isObject(before) || !isObject(after)) + return undefined; + const changed = [ + ...new Set([...Object.keys(before), ...Object.keys(after)]), + ].filter((key) => !same(before[key], after[key])); + return changed.every( + (key) => + Object.hasOwn(after, key) && isClockNear(after[key]!, evidence.startMs), + ) + ? nestedRule(field, after, changed, evidence.others) + : undefined; +}; + +/** On a create, an object whose every clock the request stamped, where the type's other entities show the same object stamped otherwise. */ +export const createdNestedClock = ( + field: string, + value: JsonValue, + evidence: { + readonly startMs: number | undefined; + readonly type: readonly JsonObject[]; + }, +): FieldRule | undefined => { + const { startMs } = evidence; + if (!isObject(value) || startMs === undefined) return undefined; + const members = Object.keys(value).filter( + (key) => readClock(value[key]) !== undefined, + ); + // A clock read before the request, past a whole second's truncation, belongs to an entity made earlier. + const stamped = members.every((key) => { + const ms = readClock(value[key])!.ms; + return ms >= startMs - TRUNCATION_MS && ms <= startMs + NESTED_WINDOW_MS; + }); + return stamped ? nestedRule(field, value, members, evidence.type) : undefined; +}; + +/** A served nested clock: the object the entity holds, or the observed one for a create, with its stamped members set to the clock. */ +export const nestedClockValue = ( + base: JsonValue | undefined, + rule: Extract, + clock: JsonValue, +): Result => + base !== undefined && isObject(base) + ? ok({ + ...base, + ...Object.fromEntries(rule.members.map((member) => [member, clock])), + }) + : err(`The entity holds no ${rule.field} object for the write to stamp.`); + +/** A created token no other entity holds and no other field repeats, where every other entity holds one of its length. */ +export const createdToken = ( + field: string, + entity: JsonObject, + type: readonly JsonObject[], +): boolean => { + const value = entity[field]; + return ( + isOpaqueToken(value) && + type.length > 0 && + !Object.entries(entity).some( + ([other, held]) => other !== field && held === value, + ) && + type.every( + (member) => + member[field] !== value && isOpaqueToken(member[field], value), + ) + ); +}; + +/** What judging an unsent change reads: the entity before and after, the call's body and the type's other entities. */ +interface ChangeEvidence { + readonly before: JsonObject; + readonly after: JsonObject; + readonly call: { readonly body: JsonObject }; + readonly others: readonly JsonObject[]; +} + +/** An update's new opaque token: not sent, not held elsewhere, spelled like the one it replaced. */ +export const freshToken = ( + evidence: ChangeEvidence, + field: string, +): boolean => { + const before = evidence.before[field]; + const after = evidence.after[field]; + return ( + isOpaqueToken(after, before) && + isOpaqueToken(before) && + before !== after && + !Object.values(evidence.call.body).includes(after) && + !Object.entries(evidence.after).some( + ([name, value]) => name !== field && value === after, + ) && + !evidence.others.some((other) => other[field] === after) + ); +}; + +/** A name's words, lower case: camel case, `_`, `-` and spaces split them. */ +const wordsOf = (name: string): string[] => + name + .replace(/([a-z0-9])([A-Z])/gu, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/u) + .filter((word) => word.length > 0); + +/** A name without the trailing words that make it a reference: `assignedUserId` and `assignedUserName` share `assigned user`. */ +const stemOf = (name: string): string => { + const words = wordsOf(name); + while (words.length > 1 && REFERENCE_WORDS.has(words.at(-1)!)) words.pop(); + return words.join(" "); +}; + +/** The words of the `created…by` counterpart of a `modified…by`-style field, as `createdByName` is `modifiedByName`'s. */ +const creatorOf = (field: string): string | undefined => { + const words = wordsOf(field); + const at = words[0] === "last" ? 1 : 0; + return CHANGED_BY.has(words[at] ?? "") && words[at + 1] === "by" + ? ["created", ...words.slice(at + 1)].join(" ") + : undefined; +}; + +/** The acting user an update stamps on a `modified…by`-style field, as the entity's `created…by` counterpart already names them. */ +export const stampRule = ( + evidence: ChangeEvidence, + field: string, +): FieldRule | undefined => { + const after = evidence.after[field]; + const creator = creatorOf(field); + if (typeof after !== "string" || after.length === 0 || creator === undefined) + return undefined; + // A field naming what the call sent refers to that, not to the acting user. + if ( + Object.keys(evidence.call.body).some( + (member) => stemOf(member) === stemOf(field), + ) + ) + return undefined; + return Object.entries(evidence.before).some( + ([other, value]) => value === after && wordsOf(other).join(" ") === creator, + ) + ? { field, rule: "stamp", value: after } + : undefined; +}; + +/** A sent string's text, markup aside: what a value derived from it shows. */ +const textOf = (value: JsonValue | undefined): string | undefined => + typeof value === "string" + ? value + .replace(/<[^>]*>/gu, " ") + .replace(/\s+/gu, " ") + .trim() + : undefined; + +/** A value an update derived from the one member it sent and stores nowhere: one that shows that member's text. */ +export const derivedRule = ( + evidence: ChangeEvidence, + field: string, +): FieldRule | undefined => { + const after = evidence.after[field]; + if (after === undefined || readClock(after) !== undefined) return undefined; + const { body } = evidence.call; + const unstored = Object.keys(body).filter( + (member) => + !Object.hasOwn(evidence.after, member) && + !Object.hasOwn(evidence.before, member), + ); + const text = unstored.length === 1 ? textOf(body[unstored[0]!]) : undefined; + const shown = typeof after === "string" ? after : JSON.stringify(after); + return text !== undefined && + text.length >= DERIVED_TEXT_MIN && + shown.includes(text) + ? { + field, + rule: "derived", + value: after, + from: evidence.before[field] ?? null, + member: unstored[0]!, + } + : undefined; +}; + +/** Why a call cannot take an update's rules: a derived value for an entity holding another than the recorded one, or a held clock sent otherwise than the entity holds it. */ +export const stampProblem = ( + rules: readonly FieldRule[], + before: JsonObject, + sent: JsonObject, +): string | undefined => { + for (const rule of rules) { + if ( + rule.rule === "derived" && + Object.hasOwn(sent, rule.member) && + !same(before[rule.field] ?? null, rule.from) + ) + return `Member ${rule.member} is accepted only on an entity whose ${rule.field} is as the recorded call found it, since the application derives ${rule.field} from it.`; + if ( + rule.rule === "held-clock" && + Object.hasOwn(sent, rule.field) && + !same(sent[rule.field], before[rule.field]) + ) + return `Member ${rule.field} must repeat the value the entity holds, as the recorded call did.`; + } + return undefined; +}; + +/** The members whose values the tool's recorded calls varied. */ +export const variedMembers = ( + bodies: readonly (JsonValue | undefined)[], +): Set => { + const seen = new Map(); + const varied = new Set(); + for (const body of bodies) + if (body !== undefined && isObject(body)) + for (const [member, value] of Object.entries(body)) { + const text = JSON.stringify(value); + if (seen.has(member) && seen.get(member) !== text) varied.add(member); + seen.set(member, text); + } + return varied; +}; + +/** The identity values of the objects an entity nests, by the stem of the field each sits under: what a member like `collection_id` names. */ +const nestedIdentities = (entity: JsonObject): Map> => { + const index = new Map>(); + for (const [field, nested] of Object.entries(entity)) { + if (!isObject(nested)) continue; + const texts = IDENTITY_NAMES.flatMap((name) => { + const text = scalarText(nested[name]); + return text === undefined ? [] : [text]; + }); + if (texts.length === 0) continue; + const stem = stemOf(field); + index.set(stem, new Set([...(index.get(stem) ?? []), ...texts])); + } + return index; +}; + +/** Whether a state word goes with other values elsewhere: one entities share, where every entity in another state holds a field the new one leaves null, or the reverse. */ +const stateOf = ( + entity: JsonObject, + member: string, + value: JsonValue, + type: readonly JsonObject[], +): boolean => { + if (typeof value !== "string" || !STATE_WORD.test(value)) return false; + const held = type.flatMap((other) => + Object.hasOwn(other, member) ? [JSON.stringify(other[member])] : [], + ); + // A value every entity holds its own of names it, not a state. + if (new Set(held).size === held.length) return false; + const others = type.filter( + (other) => Object.hasOwn(other, member) && !same(other[member], value), + ); + const unset = (held: JsonValue | undefined) => (held ?? null) === null; + return ( + others.length > 0 && + Object.keys(entity).some( + (field) => + field !== member && + others.every((other) => unset(other[field]) !== unset(entity[field])), + ) + ); +}; + +/** + * Echoed members accepted only with their recorded value: one naming an object the entity nests, which serving + * would keep as recorded, and on a create a state other fields go with, unless the recorded calls varied it. + */ +export const pinnedEchoes = ( + entity: JsonObject, + body: JsonObject, + context: { + readonly type?: readonly JsonObject[]; + readonly varied: ReadonlySet; + }, +): Set => { + const nested = nestedIdentities(entity); + // A member names the object nested under the field it refers to, as `collection_id` does `collection`. + const namesNested = (member: string, value: JsonValue): boolean => { + const text = scalarText(value); + return text !== undefined && nested.get(stemOf(member))?.has(text) === true; + }; + return new Set( + Object.entries(body).flatMap(([member, value]) => + !context.varied.has(member) && + (namesNested(member, value) || + (context.type !== undefined && + stateOf(entity, member, value, context.type))) + ? [member] + : [], + ), + ); +}; + +/** An update's fields as stored: each nested clock as the first later read of the entity shows it restamped, else as the call showed it. */ +export const restampedFields = ( + search: ObservationSearch, + target: Parameters[1], + shown: JsonObject, + rules: readonly FieldRule[], +): JsonObject => { + const nested = rules.flatMap((rule) => + rule.rule === "nested-clock" ? [rule] : [], + ); + if (nested.length === 0) return shown; + const later = laterObservation(search, target); + const fields = { ...shown }; + for (const rule of nested) { + const read = storedRestamp( + shown[rule.field], + later?.object[rule.field], + rule.members, + ); + if (read !== undefined) fields[rule.field] = read; + } + return fields; +}; + +/** A read's object where it differs from a write's only in the stamped members, each within seconds: the instant the application stored. */ +export const storedRestamp = ( + own: JsonValue | undefined, + read: JsonValue | undefined, + members: readonly string[], +): JsonValue | undefined => { + if (own === undefined || read === undefined) return undefined; + if (!isObject(own) || !isObject(read)) return undefined; + for (const key of new Set([...Object.keys(own), ...Object.keys(read)])) { + if (!members.includes(key)) { + if (!same(own[key], read[key])) return undefined; + continue; + } + const [written, stored] = [readClock(own[key]), readClock(read[key])]; + if ( + written === undefined || + stored === undefined || + Math.abs(written.ms - stored.ms) > NESTED_WINDOW_MS + ) + return undefined; + } + return read; +}; diff --git a/src/domain/analysisView/environmentStateWriteValues.ts b/src/domain/analysisView/environmentStateWriteValues.ts index 6048e649171..5e16ebd68fb 100644 --- a/src/domain/analysisView/environmentStateWriteValues.ts +++ b/src/domain/analysisView/environmentStateWriteValues.ts @@ -344,6 +344,16 @@ const tokenAlphabet = (exemplar: string): string => { return alphabet === "" ? LOWER : alphabet; }; +/** A seeded value spelled like the recorded one: a UUID for a UUID or when asked for one, else a token. */ +export const seededLike = ( + seed: string, + exemplar: JsonValue, + uuid = false, +): string => + uuid || isUuid(exemplar) + ? seededUuid(seed, String(exemplar)) + : seededToken(seed, String(exemplar)); + /** A token as long as the recorded one, from its alphabet, keeping its other characters in place. */ export const seededToken = (seed: string, exemplar: string): string => { const alphabet = tokenAlphabet(exemplar); diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 4178c572ac5..4b25d16c056 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1829,3 +1829,77 @@ describe("field selections the gate reads as serving answers them", () => { }); }); }); + +/** A create and an update whose bodies and responses wrap the book in a one-element array. */ +const ENVELOPED_ROWS: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + [ + "POST", + "/api/books", + { books: [THIRD_BOOK] }, + 201, + { books: [{ name: "Third Book" }] }, + ], + ["GET", "/api/books/3", THIRD_BOOK], + [ + "PATCH", + "/api/books/1", + { books: [RENAMED_BOOK] }, + 200, + { books: [{ name: "Renamed Book" }] }, + ], + ["GET", "/api/books/1", RENAMED_BOOK], +]; + +/** A card whose edit info an update restamps: its response and its read-back name instants milliseconds apart. */ +const cardEdit = (milliseconds: number) => ({ + at: new Date(Date.parse(bookClock(3)) + milliseconds).toISOString(), + by: "rea", +}); +const FIRST_CARD = { + id: 1, + name: "First Card", + edit: { at: "2026-10-01T09:00:00.000Z", by: "rea" }, +}; +const SECOND_CARD = { ...FIRST_CARD, id: 2, name: "Second Card" }; + +describe("values an application stamps", () => { + it("serves a create and an update whose bodies wrap the book in a one-element array, as the capture sent them", () => { + const state = stateOf(ENVELOPED_ROWS); + expect(planOf(state, "post_books")).toMatchObject({ + served: true, + body: { accepted: ["name"], envelope: "books" }, + }); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: true, + body: { accepted: ["name"], envelope: "books" }, + }); + }); + + it("serves an update that restamps a nested clock, storing the instant its read-back shows", () => { + const edited = { ...FIRST_CARD, name: "First Card (edited)" }; + const state = stateOf([ + ["GET", "/api/cards", [FIRST_CARD, SECOND_CARD]], + ["GET", "/api/cards/1", FIRST_CARD], + ["GET", "/api/cards/2", SECOND_CARD], + [ + "PUT", + "/api/cards/1", + { ...edited, edit: cardEdit(64) }, + 200, + { name: "First Card (edited)" }, + ], + ["GET", "/api/cards/1", { ...edited, edit: cardEdit(53) }], + ]); + expect(planOf(state, "put_cards_by_id")).toMatchObject({ + served: true, + rules: expect.arrayContaining([ + expect.objectContaining({ + field: "edit", + rule: "nested-clock", + members: ["at"], + }), + ]), + }); + }); +}); From b1ca2547f8c3037c75bd7446df4718cf6550f922 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 09:59:47 -0700 Subject: [PATCH 27/68] fix(environment): order collections by whole lines and sort only arrays a read-back proves sorted A collection's initial order comes from the first list line that shows every entity its type's sightings do and applies no order. A view renders a string-array field sorted only after a counted read-back shows the written values in an order that neither the written order nor existing-values-first explains, and never once a read showed it unsorted. Sort and direction parameters share one vocabulary and are never learned as inert, and a create placed by disagreeing sorts or a random id falls back to last. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/list-queries/spec.md | 9 +- .../agent-environments/state-coverage/spec.md | 6 +- .../agent-environments/state-view/spec.md | 17 ++ .../agent-environments/state-writes/spec.md | 14 +- .../environmentStateWriteAnswer.test.ts | 32 +++ .../EnvironmentStateExtraction.ts | 5 + .../EnvironmentStateWriteSimulation.ts | 31 +- .../environmentStateInitialOrder.test.ts | 86 ++++++ .../environmentStateInitialOrder.ts | 58 ++++ .../environmentStateListQuery.test.ts | 27 ++ .../analysisView/environmentStateListQuery.ts | 34 +-- .../environmentStateOrderParameters.test.ts | 62 ++++ .../environmentStateOrderParameters.ts | 120 ++++++++ .../analysisView/environmentStateRules.ts | 30 +- .../analysisView/environmentStateView.ts | 6 + .../environmentStateWriteCreate.ts | 20 +- .../environmentStateWriteExplain.test.ts | 60 ++++ .../environmentStateWriteExplain.ts | 51 +++- .../environmentStateWriteSorted.test.ts | 42 +++ .../environmentStateWriteSorted.ts | 264 ++++++++++++++++++ .../environmentStateWrites.test.ts | 200 +++++++++++++ .../analysisView/environmentStateWrites.ts | 4 +- 22 files changed, 1127 insertions(+), 51 deletions(-) create mode 100644 src/domain/analysisView/environmentStateInitialOrder.test.ts create mode 100644 src/domain/analysisView/environmentStateInitialOrder.ts create mode 100644 src/domain/analysisView/environmentStateOrderParameters.test.ts create mode 100644 src/domain/analysisView/environmentStateOrderParameters.ts create mode 100644 src/domain/analysisView/environmentStateWriteSorted.test.ts create mode 100644 src/domain/analysisView/environmentStateWriteSorted.ts diff --git a/docs/specs/agent-environments/list-queries/spec.md b/docs/specs/agent-environments/list-queries/spec.md index d2af65457f4..e180f7a5b4e 100644 --- a/docs/specs/agent-environments/list-queries/spec.md +++ b/docs/specs/agent-environments/list-queries/spec.md @@ -24,7 +24,7 @@ the line recorded, from the collection's initial entities, explains it: nothing else matched); an empty term matches everything, and a term that matched no field leaves the parameter inert until another line's term does; - `sort` by the field the value names, with `-` or an `asc`/`desc` suffix, and `direction` for a separate `asc`/`desc` - parameter: numbers by value, text ignoring case, null last ascending, ties (case-only differences included) in state + (or `ascending`/`descending`) parameter: numbers by value, text ignoring case, null last ascending, ties (case-only differences included) in state order; an empty selection needs no sort; - `limit`, `offset` and `page` (counted from 1 or 0 only when the line distinguishes them) for paging; zero or a negative limit lists every match; @@ -39,8 +39,11 @@ Query totals retain their numeric or canonical decimal-string type. Unknown or d `state.source` distinguishes a computed response from recording replay; `replay.exact_match` describes only the retained source envelope and can be false for a correctly computed new query. -Parameter names decide which roles are tried (`sort` for `orderBy`, `search` for `q`), and any parameter may be a -filter or inert. No two parameters of one call take the same `sort`, `direction` or paging role: the answer would +Parameter names decide which roles are tried (`sort` for `orderBy`, `search` for `q`), and any other parameter may be a +filter or inert. A name asking for an order in any common spelling (`_sort`, `sort[]`, `sort[0][field]`, `sorters[...]`, +`sort-column`, `sortKey`, `orderBy`) is only a `sort`; a direction name (`_order`, `sortDirection`, `dir`) given a direction +is only a `direction`, and given anything else is an ordinary parameter; `reverse` is never inert unless false. The same +vocabulary decides which lines set a collection's initial order (see the state view). No two parameters of one call take the same `sort`, `direction` or paging role: the answer would depend on which applied last, and serving supplies a call's values in name order rather than as recorded, so such a combination explains no line and such a call replays its recording. A line with more than 12 query parameters is left unexplained, which bounds the search; names such as `__proto__` are kept as the query's own members. The lines' roles diff --git a/docs/specs/agent-environments/state-coverage/spec.md b/docs/specs/agent-environments/state-coverage/spec.md index 0477bb9f503..b4157ed7d34 100644 --- a/docs/specs/agent-environments/state-coverage/spec.md +++ b/docs/specs/agent-environments/state-coverage/spec.md @@ -45,8 +45,10 @@ tool, view kind, provider, network activity or write effect. value. Objects at the root or in one member keep precedence. `at` and `replaceAt` read and replace exactly these forms besides the root and one member, so the gate and renderers run unchanged. -- An entity's state order is its earliest sighting on the timeline and it cites - its records in timeline order, whichever plan observed it first. +- An entity's state order is its place on the first whole line its collection's + application order lists, else its earliest sighting on the timeline (see + the state view); it cites its records in timeline order, whichever plan + observed it first. - Each tool description reads `METHOD template; ; recorded statuses …; replays retained records […]; evidence ev_…` after the untrusted-catalog warning. `` describes one level deep the first cited `2xx` record diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index d0a992ae3be..e8983c4ddfa 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -93,6 +93,23 @@ later increments. under the view's separator, with its own fraction digits padded with zeros to the view's width and none dropped; an epoch spelling is computed from the instant. +- An item or list view names in `sorted_arrays` the fields it lists as string + arrays in code-point order whatever order they were written in (tags kept as + a set). Only the write gate learns it. A field is a candidate when every + initial entity shows it as a sorted string array or null, one with two + distinct strings, and no read the gate counts has listed it unsorted with two + distinct strings. It is learned from a counted read that fails with the + stored order and passes with the field sorted, and only when that read lists + a written array in an order that is neither the written one nor values the + initial state held first, then the new ones as written (an application + ordering by tag id or creation shows that order too). The stored value keeps + the written order, so a write's own answer echoes it; every view of the type + for which the field is still a candidate sorts it as well. +- A collection's initial order is the order of the first line that lists every + entity any initial read shows in it and names no sort, direction (`sort[]`, + `_sort`, `sort-column`, `sortKey`, `orderBy` and like spellings) or random + parameter (`random`, `rand`, `shuffle`, `seed`); a collection without such a + line keeps its entities' earliest sightings. - A list has `all` membership only when no item-total envelope member (`total`, `count` and their compounds, not page counts) differs from the number of entities it lists and no `has_more`, `next` or next-page token is set. diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 77739fe60d5..3575b6a7542 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -307,7 +307,13 @@ and the state is left unchanged. collection's order: sorted by the identity field or a clock field (ascending or descending), `first` or `last`. The rule is the first candidate consistent with both the initial `all`-membership recordings and the position a later -recorded list shows. With no evidence, the rule is `last`. +recorded list shows. With no evidence, the rule is `last`. A sort by a +random identity (version 4 UUIDs, or generated ids every creation clock lists +in another order) is a candidate only after `last`: the recorded order by it is +a coincidence until a list shows a create placed by it; time-ordered ids +(ObjectId, ULID, TSID, version 7 UUIDs) keep it. When the sorts the recorded +order admits would place the created entity differently, none is claimed +before `last` until a later list settles it. ## The gate @@ -456,6 +462,12 @@ refuses to answer with. - After a failed item check, the copy takes the read's recorded values (or drops the entity on a recorded absence). A list whose check failed is not checked again. +- A failed item or list read the gate counts passes when the view lists some + string-array fields sorted and its order rules out the written one and the + order the values were first held in (see `sorted_arrays` in the state view); + the type's views keep the fewest such fields the read needs, and the read + checks the writes it exercises. A counted read listing such a field unsorted + rules it out for its view. - A list that fails only for where one create placed its entity passes when another of that create's insert candidates reproduces it, which then becomes the plan's rule, unless an earlier list check relied on the rule diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index c377446fbbe..07921f9a426 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -2065,3 +2065,35 @@ describe("path fields of creates read under another path", () => { } }); }); + +describe("array fields a view lists sorted", () => { + it("answers the update with the written order and later reads with it sorted", () => { + const tagged = (entry: Book, tags: string[]): Book => ({ ...entry, tags }); + const books = servedFrom([ + [ + "GET", + "/api/books", + [tagged(FIRST_BOOK, ["alpha", "beta"]), tagged(SECOND_BOOK, ["gamma"])], + ], + ["GET", "/api/books/1", tagged(FIRST_BOOK, ["alpha", "beta"])], + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["gamma"])], + [ + "PATCH", + "/api/books/2", + tagged(SECOND_BOOK, ["zeta", "delta"]), + 200, + { tags: ["zeta", "delta"] }, + ], + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["delta", "zeta"])], + ]); + expect( + books.answer("patch_books_by_id", { + id: "1", + body: { tags: ["omega", "beta"] }, + }).body, + ).toMatchObject({ tags: ["omega", "beta"] }); + expect(books.answer("get_books_by_id", { id: "1" }).body).toMatchObject({ + tags: ["beta", "omega"], + }); + }); +}); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 488755857cf..332cd78955f 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -46,6 +46,7 @@ import { type ObservedEntity, type StateObservation, } from "./environmentStateMerge.js"; +import { orderByWholeLines } from "./environmentStateInitialOrder.js"; import { rewriteCuts, type RewriteSpan } from "./environmentStateRewrites.js"; import { checkItemPlan, @@ -209,6 +210,10 @@ export class EnvironmentStateExtraction { this.#planList(candidate); for (const plan of this.#plans) this.#observePlan(plan); this.#dropVariants(); + orderByWholeLines( + this.#entities.values(), + (ordinal) => this.#byOrdinal.get(ordinal)?.query, + ); this.#classifyChanges(); this.#merge(); return candidates; diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index ffcd77ab5d8..12985b15cdf 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -18,6 +18,7 @@ import { linkedTarget } from "./environmentStateWriteLinks.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; import { OmittedFields } from "./environmentStateWriteOmitted.js"; +import { SortedArrays } from "./environmentStateWriteSorted.js"; import { checkDocumentRead, checkItemRead, @@ -100,6 +101,8 @@ export class EnvironmentStateWriteSimulation { readonly #effects = new WriteEffects(); /** Fields reads show the application leaves out, which serving then does not require. */ readonly omitted = new OmittedFields((bytes) => this.#input.io.retain(bytes)); + /** Array fields reads showed a view lists sorted. */ + readonly #sorted: SortedArrays; readonly #lastCheck = new Map(); /** When the latest modelled write to each target since its last check ended. */ readonly #touchedSince: PendingTargets = new Map(); @@ -150,6 +153,11 @@ export class EnvironmentStateWriteSimulation { for (const ordinal of tool.record_ordinals) this.#toolOf.set(ordinal, tool); this.#checkedLines = checkedLines(input); + this.#sorted = new SortedArrays(input.views.values(), input.entities, { + state: this.#state, + io: input.io, + idField: (type) => this.#types.get(type)?.id_field, + }); this.#taint = new WriteTaint( [...this.#types.keys()], new Map( @@ -231,7 +239,7 @@ export class EnvironmentStateWriteSimulation { const view = this.#input.views.get( this.#toolOf.get(ordinal)?.name ?? "", ); - return view === undefined ? undefined : this.omitted.view(view); + return view === undefined ? undefined : this.#viewOf(view); }, idField: (type) => this.#types.get(type)!.id_field, observed: (ordinal) => @@ -424,10 +432,20 @@ export class EnvironmentStateWriteSimulation { return servedLine(this.#checkedLines.get(view.tool), record); } + /** The view as the gate currently knows it: without the fields reads showed omitted, with the arrays they showed sorted. */ + #viewOf(view: StateView): StateView { + return this.#sorted.view(this.omitted.view(view)); + } + + /** The views as reads showed them. */ + views(views: readonly StateView[]): StateView[] { + return this.#sorted.views(this.omitted.views(views)); + } + #read(record: StateRecordFacts, index: number, tool: StateToolFacts): void { const original = this.#input.views.get(tool.name); if (original === undefined) return; - const view = this.omitted.view(original); + let view = this.#viewOf(original); if (projectedRead(view, record, this.#input.io)) return; const borrowers = this.#observations.get(record.ordinal); if (!borrowers && this.#resynced(view, record, index)) return; @@ -441,6 +459,15 @@ export class EnvironmentStateWriteSimulation { runningAt(this.#touchedSince, key, record.start), ); if (blocked(keys)) return; + // A read the gate counts can show the view lists a written array sorted, or rule that out. + outcome = this.#sorted.retry( + view, + { record, outcome }, + (candidate) => this.#check(candidate, record), + blocked, + ); + view = this.#viewOf(original); + keys = [...outcome.targets, ...outcome.unheld]; let exercised = exercisedBy(this.#touched, keys, borrowers); if (borrowers !== undefined) { this.omitted.keep(view, outcome); diff --git a/src/domain/analysisView/environmentStateInitialOrder.test.ts b/src/domain/analysisView/environmentStateInitialOrder.test.ts new file mode 100644 index 00000000000..31a4280a2b2 --- /dev/null +++ b/src/domain/analysisView/environmentStateInitialOrder.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; + +import { orderByWholeLines } from "./environmentStateInitialOrder.js"; +import type { + ObservedEntity, + StateObservation, +} from "./environmentStateMerge.js"; + +/** One sighting: a list line's entry at `index`, or an item read when `item`. */ +const sighting = ( + ordinal: number, + index: number, + item = false, +): StateObservation => ({ + position: ordinal, + index, + ordinal, + tool: item ? "get_books_by_id" : "get_books", + item, + object: {}, +}); + +const entity = (id: string, ...observations: StateObservation[]) => ({ + type: "/api/books", + collection: "/api/books", + id, + order: [observations[0]!.position, observations[0]!.index] as const, + observations, +}); + +/** The entities' ids in initial order once the whole lines rank them, given each line's query. */ +const ordered = ( + entities: ObservedEntity[], + queries: Readonly>, +): string[] => { + orderByWholeLines(entities, (ordinal) => queries[ordinal]); + return entities + .toSorted( + (left, right) => + left.order[0] - right.order[0] || left.order[1] - right.order[1], + ) + .map((candidate) => candidate.id); +}; + +describe("initial order from whole lines", () => { + it("takes the first whole line that applies no sort, random or seed parameter", () => { + const queries = { + 0: "random=true", + 1: "sort[]=name", + 2: "sort-column=name", + 3: "sortKey=name", + 4: "orderDirection=desc", + 5: "seed=7", + 6: "page=1", + }; + const lines = Object.keys(queries).map(Number); + // Every line lists both; the earlier ones apply an order of their own. + const at = (first: string) => + lines.map((ordinal) => + sighting(ordinal, (ordinal === 6) === (first === "b") ? 0 : 1), + ); + expect( + ordered([entity("a", ...at("a")), entity("b", ...at("b"))], queries), + ).toEqual(["b", "a"]); + }); + + it("does not take a line that lists part of the collection, or an item read", () => { + const entities = [ + entity("a", sighting(0, 0, true), sighting(2, 1)), + entity("b", sighting(1, 0), sighting(2, 2)), + entity("c", sighting(2, 0)), + ]; + expect(ordered(entities, { 1: "name=b" })).toEqual(["c", "a", "b"]); + }); + + it("keeps the earliest sightings of a collection no whole default line lists", () => { + const entities = [ + entity("a", sighting(1, 0), sighting(2, 1)), + entity("b", sighting(0, 0, true), sighting(2, 0)), + ]; + expect(ordered(entities, { 1: "status=open", 2: "sort=name" })).toEqual([ + "b", + "a", + ]); + }); +}); diff --git a/src/domain/analysisView/environmentStateInitialOrder.ts b/src/domain/analysisView/environmentStateInitialOrder.ts new file mode 100644 index 00000000000..374b79c5c71 --- /dev/null +++ b/src/domain/analysisView/environmentStateInitialOrder.ts @@ -0,0 +1,58 @@ +import type { ObservedEntity } from "./environmentStateMerge.js"; +import { appliesOrder } from "./environmentStateOrderParameters.js"; + +/** Query parameters that ask for a random order. */ +const RANDOM = new Set(["random", "rand", "shuffle", "seed"]); + +/** Whether a recorded query leaves the order to the application: no sort, direction or random parameter. */ +const defaultOrder = (query: string | null | undefined): boolean => + [...new URLSearchParams(query ?? "").keys()].every( + (name) => !appliesOrder(name) && !RANDOM.has(name.toLowerCase()), + ); + +/** + * Order each collection's entities as the earliest whole list line in the application's own order + * shows them: a line that lists every entity any initial read shows in the collection and applies no + * sort, direction or random parameter. A collection without such a line keeps its earliest sightings. + */ +export const orderByWholeLines = ( + entities: Iterable, + queryOf: (ordinal: number) => string | null | undefined, +): void => { + const collections = new Map(); + for (const entity of entities) { + const key = `${entity.type}\u0000${entity.collection}`; + const members = collections.get(key); + if (members === undefined) collections.set(key, [entity]); + else members.push(entity); + } + for (const members of collections.values()) { + const lines = new Map(); + for (const entity of members) + for (const observation of entity.observations) { + if (observation.item) continue; + const line = lines.get(observation.ordinal); + if (line === undefined) + lines.set(observation.ordinal, { + position: observation.position, + listed: 1, + }); + else line.listed += 1; + } + let first: [number, number] | undefined; + for (const [ordinal, line] of lines) + if ( + line.listed === members.length && + (first === undefined || line.position < first[1]) && + defaultOrder(queryOf(ordinal)) + ) + first = [ordinal, line.position]; + if (first === undefined) continue; + for (const entity of members) { + const sighting = entity.observations.find( + (observation) => !observation.item && observation.ordinal === first[0], + )!; + entity.order = [sighting.position, sighting.index]; + } + } +}; diff --git a/src/domain/analysisView/environmentStateListQuery.test.ts b/src/domain/analysisView/environmentStateListQuery.test.ts index 9d87265d310..f4790ce5a44 100644 --- a/src/domain/analysisView/environmentStateListQuery.test.ts +++ b/src/domain/analysisView/environmentStateListQuery.test.ts @@ -374,3 +374,30 @@ describe("queries the state can always answer", () => { }); }); }); + +describe("parameters that ask for an order", () => { + it("reads a sort field in any spelling as a sort, never as a parameter without effect", () => { + expect(explainLine(line("?_sort=id&_order=DESC", [4, 3, 2, 1]))).toEqual({ + _sort: { role: "sort" }, + _order: { role: "direction" }, + }); + expect( + explainLine(line("?sortKey=id&sortDirection=descending", [4, 3, 2, 1])), + ).toEqual({ + sortKey: { role: "sort" }, + sortDirection: { role: "direction" }, + }); + // A sort value naming no field leaves the line unexplained rather than without effect. + expect(explainLine(line("?_sort=newest", [1, 2, 3, 4]))).toBeUndefined(); + }); + + it("reads a direction name given no direction as an ordinary parameter", () => { + expect(explainLine(line("?direction=shared-by", [1, 2, 3, 4]))).toEqual({ + direction: { role: "inert", values: ["shared-by"] }, + }); + expect(explainLine(line("?reverse=false", [1, 2, 3, 4]))).toEqual({ + reverse: { role: "inert", values: ["false"] }, + }); + expect(explainLine(line("?reverse=true", [1, 2, 3, 4]))).toBeUndefined(); + }); +}); diff --git a/src/domain/analysisView/environmentStateListQuery.ts b/src/domain/analysisView/environmentStateListQuery.ts index 920c5ae8128..599859911c1 100644 --- a/src/domain/analysisView/environmentStateListQuery.ts +++ b/src/domain/analysisView/environmentStateListQuery.ts @@ -1,6 +1,7 @@ import type { JsonValue } from "../jsonValue.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { literalSubstringPredicate } from "../analysisSearch.js"; +import { directionOf, orderRole } from "./environmentStateOrderParameters.js"; import { isObject, pointerTo, @@ -39,26 +40,6 @@ export interface QueryLine { readonly entities: readonly StateEntity[]; } -const SORT = new Set([ - "order", - "orderby", - "order_by", - "ordering", - "sort", - "sortby", - "sort_by", -]); -const DIRECTION = new Set([ - "dir", - "direction", - "order", - "orderdirection", - "order_direction", - "sortdir", - "sort_dir", - "sortorder", - "sort_order", -]); const LIMIT = new Set([ "count", "itemsperpage", @@ -81,7 +62,6 @@ const SEARCH = new Set([ "searchterm", "term", ]); -const DIRECTIONS = new Set(["asc", "desc"]); const IDENTIFYING = ["id", "slug", "name"]; /** At most this many role combinations are tried for one line. */ const MAX_COMBINATIONS = 256; @@ -207,8 +187,9 @@ const readCall = ( call.selections.push(contains(parameter.fields, value)); } else if (parameter.role === "sort") call.sort = value; else if (parameter.role === "direction") { - if (!DIRECTIONS.has(value.toLowerCase())) return undefined; - call.direction = value.toLowerCase(); + const direction = directionOf(value); + if (direction === undefined) return undefined; + call.direction = direction; } else if (parameter.role === "inert") { if (!parameter.values.includes(value)) return undefined; } else if (number === undefined) return undefined; @@ -395,10 +376,9 @@ const choicesFor = ( (SEARCH.has(key) && !plainSearch(value)) ) return []; - if (DIRECTION.has(key) && DIRECTIONS.has(value.toLowerCase())) - choices.push({ role: "direction" }); - else if (SORT.has(key)) choices.push({ role: "sort" }); - else if (LIMIT.has(key)) choices.push({ role: "limit" }); + const order = orderRole(name, value); + if (order !== undefined) return order === "none" ? [] : [{ role: order }]; + if (LIMIT.has(key)) choices.push({ role: "limit" }); else if (OFFSET.has(key)) choices.push({ role: "offset" }); else if (key === "page") choices.push({ role: "page", first: 1 }, { role: "page", first: 0 }); diff --git a/src/domain/analysisView/environmentStateOrderParameters.test.ts b/src/domain/analysisView/environmentStateOrderParameters.test.ts new file mode 100644 index 00000000000..419dc2b0eeb --- /dev/null +++ b/src/domain/analysisView/environmentStateOrderParameters.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { + appliesOrder, + directionOf, + namesDirection, +} from "./environmentStateOrderParameters.js"; + +describe("parameters that ask for an order", () => { + it.each([ + "sort", + "sort[]", + "sort[0][field]", + "sorters[0][field]", + "_sort", + "_order", + "sort-column", + "sort-direction", + "sortKey", + "sortDirection", + "orderBy", + "order_direction", + "ordering", + "dir", + "reverse", + ])("reads %s as asking for an order", (name) => { + expect(appliesOrder(name)).toBe(true); + }); + + it.each(["order_id", "orderNumber", "sorted", "status", "q", "reversed"])( + "reads %s as asking for none", + (name) => { + expect(appliesOrder(name)).toBe(false); + }, + ); +}); + +describe("directions", () => { + it.each([ + "dir", + "sortDirection", + "sort-direction", + "order_direction", + "sort_order", + "reverse", + ])("reads %s as naming only a direction", (name) => { + expect(namesDirection(name)).toBe(true); + }); + + it.each(["order", "sort", "_sort", "sortKey", "orderBy"])( + "reads %s as naming a sort field", + (name) => { + expect(namesDirection(name)).toBe(false); + }, + ); + + it("reads a direction in short or long spelling", () => { + expect( + ["ASC", "descending", "Ascending", "newest"].map(directionOf), + ).toEqual(["asc", "desc", "asc", undefined]); + }); +}); diff --git a/src/domain/analysisView/environmentStateOrderParameters.ts b/src/domain/analysisView/environmentStateOrderParameters.ts new file mode 100644 index 00000000000..612f3c7df82 --- /dev/null +++ b/src/domain/analysisView/environmentStateOrderParameters.ts @@ -0,0 +1,120 @@ +/** Parameter names a list query reads as the field it sorts by. */ +export const SORT: ReadonlySet = new Set([ + "order", + "orderby", + "order_by", + "ordering", + "sort", + "sortby", + "sort_by", +]); +/** Parameter names a list query reads as the direction it sorts in, given `asc` or `desc`. */ +export const DIRECTION: ReadonlySet = new Set([ + "dir", + "direction", + "order", + "orderdirection", + "order_direction", + "sortdir", + "sort_dir", + "sortorder", + "sort_order", +]); + +/** Sort and direction names with their separators dropped, as `order_by` is spelled `orderBy` too. */ +const ORDER_NAMES = new Set( + [...SORT, ...DIRECTION].map((name) => name.replaceAll("_", "")), +); +/** Words that open a name asking for an order. */ +const ORDER_STARTS = new Set([ + "order", + "ordering", + "sort", + "sorter", + "sorters", + "sorts", +]); +/** Words that may follow them in such a name: `sort-column`, `sortKey`. */ +const ORDER_WORDS = new Set([ + "asc", + "by", + "column", + "desc", + "dir", + "direction", + "field", + "key", + "mode", + "order", + "type", +]); + +/** Direction names with their separators dropped, and those of them that name no sort field. */ +const DIRECTION_NAMES = new Set( + [...DIRECTION].map((name) => name.replaceAll("_", "")), +); +const DIRECTION_ONLY = new Set( + [...DIRECTION] + .filter((name) => !SORT.has(name)) + .map((name) => name.replaceAll("_", "")), +); + +/** A parameter name's words, bracketed parts dropped: `sort[0][field]` is `sort`, `sortKey` is `sort`, `key`. */ +const wordsOf = (name: string): string[] => + name + .replace(/\[[^\]]*\]/gu, "") + .split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/u) + .filter((word) => word.length > 0) + .map((word) => word.toLowerCase()); + +/** Whether a query parameter asks for an order, in any common spelling: `sort[0][field]`, `_sort`, `sort-direction`, `sortKey`, `orderBy`, `reverse`. */ +export const appliesOrder = (name: string): boolean => { + const words = wordsOf(name); + if (words.length === 0) return false; + return ( + (words.length === 1 && words[0] === "reverse") || + ORDER_NAMES.has(words.join("")) || + (ORDER_STARTS.has(words[0]!) && + words.slice(1).every((word) => ORDER_WORDS.has(word))) + ); +}; + +/** Whether a parameter names only the direction of an order, as `dir`, `sortDirection` or `reverse` do, not the field it sorts by. */ +export const namesDirection = (name: string): boolean => { + const words = wordsOf(name); + const last = words.at(-1); + return ( + DIRECTION_ONLY.has(words.join("")) || + last === "dir" || + last === "direction" || + (words.length === 1 && last === "reverse") + ); +}; + +/** The direction a value names, `asc` or `desc`, in short or long spelling. */ +export const directionOf = (value: string): "asc" | "desc" | undefined => { + const lower = value.toLowerCase(); + if (lower === "asc" || lower === "ascending") return "asc"; + if (lower === "desc" || lower === "descending") return "desc"; + return undefined; +}; + +/** + * The role a parameter asking for an order plays given a value: the field to sort by, a direction given + * one, or `none` for a reversal it cannot apply; undefined for any other parameter, and for a direction + * name given no direction, which is an ordinary parameter. An order parameter is never without effect. + */ +export const orderRole = ( + name: string, + value: string, +): "sort" | "direction" | "none" | undefined => { + if (!appliesOrder(name)) return undefined; + const directional = + namesDirection(name) || DIRECTION_NAMES.has(wordsOf(name).join("")); + if (directional && directionOf(value) !== undefined) return "direction"; + if (!namesDirection(name)) return "sort"; + return name.toLowerCase() === "reverse" && + !["", "0", "false"].includes(value.toLowerCase()) + ? "none" + : undefined; +}; diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index d08e5e9d169..e5e32fd9d39 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -1,5 +1,6 @@ import type { ListQuery } from "./environmentStateListQuery.js"; import { canonicalJson } from "../comparisonSemantics.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import type { JsonValue } from "../jsonValue.js"; import type { StateWritePlan } from "./environmentStateWriteRules.js"; import { @@ -107,6 +108,8 @@ interface EntityViewPlan { readonly checked_record_ordinals: number[]; /** How the view spells the clock fields it always spells otherwise than the entities' stored values. */ readonly clock_formats?: Readonly> | undefined; + /** Fields whose string arrays the view lists in code-point order, whatever order they were written in. */ + readonly sorted_arrays?: string[] | undefined; } /** A query key that picks out replayed reads: a parameter, a parameter with one value, or a parameter left out. */ @@ -623,7 +626,10 @@ export const listItems = ( /** One entity as a view shows it: the view's fields it has, view-specific values first; volatile fields take `observed` values when given. */ export const renderStateEntity = ( entity: StateEntity, - view: Pick, + view: Pick< + EntityViewPlan, + "tool" | "fields" | "clock_formats" | "sorted_arrays" + >, volatileFields: ReadonlySet, observed?: JsonObject, ): JsonObject => { @@ -631,6 +637,7 @@ export const renderStateEntity = ( entity.view_fields.find((candidate) => candidate.tool === view.tool) ?.fields ?? {}; const formats = view.clock_formats ?? {}; + const sorted = new Set(view.sorted_arrays); return Object.fromEntries( view.fields.flatMap((name): [string, JsonValue][] => { const source = @@ -641,18 +648,23 @@ export const renderStateEntity = ( : entity.fields; if (!Object.hasOwn(source, name)) return []; // A stored value the view never recorded, such as a written one, takes the view's spelling. - return [ - [ - name, - source === entity.fields && Object.hasOwn(formats, name) - ? respellClock(source[name]!, formats[name]!) - : source[name]!, - ], - ]; + const value = + source === entity.fields && Object.hasOwn(formats, name) + ? respellClock(source[name]!, formats[name]!) + : source[name]!; + return [[name, sorted.has(name) ? inSetOrder(value) : value]]; }), ); }; +/** Whether a value is an array of strings. */ +export const isStringArray = (value: JsonValue): value is string[] => + Array.isArray(value) && value.every((item) => typeof item === "string"); + +/** A string array in code-point order, as a view that keeps the field as a set lists it; any other value as it is. */ +const inSetOrder = (value: JsonValue): JsonValue => + isStringArray(value) ? value.toSorted(compareUnicodeCodePoints) : value; + /** The fields every recording of a view carried that the entity, as serving renders it, lacks; serving refuses to answer with such an entity. */ export const missingRequiredFields = ( entity: StateEntity, diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 887ca51b162..10f461da1db 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -119,6 +119,12 @@ const entityViewFields = { .describe( "How the view spells clock fields it always spells otherwise than the entities' stored values; a stored value the view never recorded is spelled this way.", ), + sorted_arrays: z + .array(z.string()) + .optional() + .describe( + "Fields whose string arrays the view lists in code-point order, whatever order they were written in; learned from a read that shows a written array sorted.", + ), }; const replayedReadFields = { projected_record_ordinals: z diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 8d91d1f2e9b..f1779fde0fa 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -48,6 +48,7 @@ import { explainCreate, insertCandidates, insertIndex, + randomIdentities, nextInteger, responseShapeOf, } from "./environmentStateWriteExplain.js"; @@ -168,9 +169,22 @@ const buildCreate = ( ["string", "number"].includes(typeof member[field]), ), ); - draft.candidates = insertCandidates(members, [ - ...new Set([idField, ...clocks, ...scalars]), - ]); + const generated = explained.rules.some( + (rule) => + rule.rule === "identity" && + rule.field === idField && + rule.generator !== "sequence", + ); + draft.candidates = insertCandidates( + members, + [...new Set([idField, ...clocks, ...scalars])], + { + ...(generated && randomIdentities(members, idField, clocks) + ? { random: idField } + : {}), + created: evidence.observed.object, + }, + ); retainFixed(context, explained.body.fixed); Object.assign(draft.plan, { exemplar_ordinal: step.record.ordinal, diff --git a/src/domain/analysisView/environmentStateWriteExplain.test.ts b/src/domain/analysisView/environmentStateWriteExplain.test.ts index 00ce524ae91..a5b145794a4 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.test.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.test.ts @@ -7,6 +7,7 @@ import { explainCreate, explainUpdate, insertCandidates, + randomIdentities, insertIndex, responseShapeOf, type CreateEvidence, @@ -584,6 +585,65 @@ it("offers each strictly ordered field in its direction, then last and first", ( expect(insertCandidates([], ["id"])).toEqual(fallback); }); +it("offers a sort by a random identity only after last", () => { + const members = [ + { id: "0a7f", at: "2026-03-01T00:00:00Z" }, + { id: "5c21", at: "2026-03-02T00:00:00Z" }, + ]; + expect(insertCandidates(members, ["id", "at"], { random: "id" })).toEqual([ + { rule: "sorted", field: "at", direction: "ascending" }, + { rule: "last" }, + { rule: "sorted", field: "id", direction: "ascending" }, + { rule: "first" }, + ]); +}); + +it("claims no sort before last when the consistent sorts place the created entity differently", () => { + const members = [ + { id: 1, name: "Alpha", at: "2026-03-02T00:00:00Z" }, + { id: 2, name: "Delta", at: "2026-03-01T00:00:00Z" }, + ]; + const created = { id: 3, name: "Bravo", at: "2026-03-03T00:00:00Z" }; + expect(insertCandidates(members, ["id", "name", "at"], { created })).toEqual([ + { rule: "last" }, + { rule: "sorted", field: "id", direction: "ascending" }, + { rule: "sorted", field: "name", direction: "ascending" }, + { rule: "sorted", field: "at", direction: "descending" }, + { rule: "first" }, + ]); + const agreeing = { id: 3, name: "Echo", at: "2026-02-28T00:00:00Z" }; + expect( + insertCandidates(members, ["id", "name", "at"], { created: agreeing })[0], + ).toEqual({ rule: "sorted", field: "id", direction: "ascending" }); +}); + +it.each([ + [ + "version 4 UUIDs", + [ + "9b2f1c3e-0d4a-4b6e-8f1a-2c3d4e5f6a7b", + "1c0e8a2b-7f3d-4e9a-b1c2-d3e4f5a6b7c8", + ], + ["2026-03-01T00:00:00Z", "2026-03-02T00:00:00Z"], + true, + ], + [ + "ids every clock lists otherwise", + ["k2", "a9"], + ["2026-03-01T00:00:00Z", "2026-03-02T00:00:00Z"], + true, + ], + [ + "time-ordered ids", + ["0a1", "0b2"], + ["2026-03-01T00:00:00Z", "2026-03-02T00:00:00Z"], + false, + ], +])("reads %s as random: %s", (_, ids, clocks, random) => { + const members = ids.map((id, index) => ({ id, at: clocks[index]! })); + expect(randomIdentities(members, "id", ["at"])).toBe(random); +}); + it("uses retained submillisecond precision to recognize and place sorted timestamps", () => { const members = [ { at: "2026-03-04T05:00:00.123000002Z" }, diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index e257be7a931..c23bdccc9f1 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -511,10 +511,44 @@ const orderedBy = ( ); }); -/** Insert rules consistent with a collection's recorded order: sorted by identity or clock fields when shown, then last and first. */ +/** A version 4 UUID, which is random and so orders nothing. */ +const UUID_V4 = + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu; + +/** + * Whether a collection's identities order nothing: version 4 UUIDs, or values every creation clock + * lists in another order. Time-ordered ids (ObjectId, ULID, TSID, version 7 UUIDs) follow a clock. + */ +export const randomIdentities = ( + members: readonly JsonObject[], + idField: string, + clocks: readonly string[], +): boolean => { + const ids = members.map((member) => scalarText(member[idField]) ?? ""); + if (ids.length > 0 && ids.every((id) => UUID_V4.test(id))) return true; + if (members.length < 2 || clocks.length === 0) return false; + const byId = members.toSorted( + (left, right) => compareValues(left[idField], right[idField]) ?? 0, + ); + return clocks.every((clock) => + byId.some( + (member, index) => + index > 0 && + (compareValues(byId[index - 1]![clock], member[clock]) ?? 1) > 0, + ), + ); +}; + +/** + * Insert rules consistent with a collection's recorded order: sorted by identity or clock fields when + * shown, then last and first. Sorts by a field of random values come after last, since they order + * nothing until a read shows a create placed by them; when the other sorts place the created entity + * differently, none is claimed before last. + */ export const insertCandidates = ( members: readonly JsonObject[], fields: readonly string[], + placing: { readonly random?: string; readonly created?: JsonObject } = {}, ): InsertRule[] => { const sorted: InsertRule[] = []; if (members.length >= 2) @@ -522,7 +556,20 @@ export const insertCandidates = ( for (const direction of ["ascending", "descending"] as const) if (orderedBy(members, field, direction)) sorted.push({ rule: "sorted", field, direction }); - return [...sorted, { rule: "last" }, { rule: "first" }]; + const byRandom = (rule: InsertRule) => + rule.rule === "sorted" && rule.field === placing.random; + const early = sorted.filter((rule) => !byRandom(rule)); + const { created } = placing; + const tied = + created !== undefined && + new Set(early.map((rule) => insertIndex(rule, members, created))).size > 1; + return [ + ...(tied ? [] : early), + { rule: "last" }, + ...(tied ? early : []), + ...sorted.filter(byRandom), + { rule: "first" }, + ]; }; /** Where an entity with these fields enters a collection under an insert rule. */ diff --git a/src/domain/analysisView/environmentStateWriteSorted.test.ts b/src/domain/analysisView/environmentStateWriteSorted.test.ts new file mode 100644 index 00000000000..82457d01e96 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteSorted.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vitest"; + +import type { JsonValue } from "../jsonValue.js"; +import type { StateEntity } from "./environmentStateRules.js"; +import { sortableFields } from "./environmentStateWriteSorted.js"; + +const VIEW = { tool: "get_books", fields: ["id", "tags"] }; + +/** Books whose `tags` hold these values, as the initial state does. */ +const books = (...values: JsonValue[]): StateEntity[] => + values.map((tags, index) => ({ + type: "/api/books", + collection: "/api/books", + id: String(index + 1), + fields: { id: index + 1, tags }, + view_fields: [], + record_ordinals: [], + })); + +describe("array fields a view could list sorted", () => { + it("offers a field every entity shows as a sorted string array or null, one with two distinct values", () => { + expect( + sortableFields(VIEW, books(["alpha", "beta"], null, ["gamma"])), + ).toEqual(["tags"]); + }); + + it.each([ + ["an unsorted array", [["beta", "alpha"], ["gamma"]]], + [ + "mixed types", + [ + ["alpha", 3], + ["beta", "gamma"], + ], + ], + ["arrays of objects", [[{ name: "alpha" }, { name: "beta" }]]], + ["no two distinct values", [["alpha"], ["beta", "beta"]]], + ["a value that is no array", [["alpha", "beta"], "gamma"]], + ])("offers none for %s", (_, values) => { + expect(sortableFields(VIEW, books(...(values as JsonValue[])))).toEqual([]); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteSorted.ts b/src/domain/analysisView/environmentStateWriteSorted.ts new file mode 100644 index 00000000000..e10b340c543 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteSorted.ts @@ -0,0 +1,264 @@ +import type { JsonValue } from "../jsonValue.js"; +import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import { + at, + isObject, + isStringArray, + listItems, + scalarText, + type JsonObject, + type StateEntity, + type StateItemView, + type StateListView, + type StateRecordFacts, + type StateView, +} from "./environmentStateRules.js"; +import type { + CheckOutcome, + SimulatedState, +} from "./environmentStateWriteChecks.js"; +import type { WriteIo } from "./environmentStateWriteEffects.js"; +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; + +/** Whether a string array is in code-point order. */ +const inOrder = (values: readonly string[]): boolean => + values.every( + (value, index) => index === 0 || compare(values[index - 1]!, value) <= 0, + ); + +/** A string array with at least two distinct values, the only kind that shows an order. */ +const ordered = (value: JsonValue | undefined): value is string[] => + value !== undefined && isStringArray(value) && new Set(value).size >= 2; + +/** An entity's value of a field as one view shows it: its own recorded value, else the stored one. */ +const shownBy = ( + entity: StateEntity, + tool: string, + field: string, +): JsonValue | undefined => { + const own = entity.view_fields.find( + (candidate) => candidate.tool === tool, + )?.fields; + return own !== undefined && Object.hasOwn(own, field) + ? own[field] + : entity.fields[field]; +}; + +/** Fields every initial entity shows, as the view renders it, as a sorted string array or null, one with two distinct strings. */ +export const sortableFields = ( + view: Pick, + entities: readonly StateEntity[], +): string[] => + view.fields.filter((field) => { + let distinct = false; + for (const entity of entities) { + const value = shownBy(entity, view.tool, field); + if (value === undefined || value === null) continue; + if (!isStringArray(value) || !inOrder(value)) return false; + distinct ||= new Set(value).size >= 2; + } + return distinct; + }); + +/** + * Whether a sorted read of a written array could as well list values by when the application first + * held them: those the initial state held first, then the rest in written order, as an application + * ordering by tag id or creation would. + */ +const creationOrderFits = ( + shown: readonly string[], + written: readonly string[], + existing: ReadonlySet, +): boolean => { + const firstNew = shown.findIndex((value) => !existing.has(value)); + const fresh = written.filter((value) => !existing.has(value)); + return ( + firstNew < 0 || + (shown.slice(firstNew).every((value) => !existing.has(value)) && + shown.slice(firstNew).every((value, index) => value === fresh[index])) + ); +}; + +interface Candidates { + readonly type: string; + readonly fields: string[]; +} + +/** + * Array fields a view lists sorted however they were written, as APIs that keep tags as sets do. + * A field is learned only from a read the gate counts that fails with the stored order and passes + * with it sorted, where the order could not be the written one or the order the application first + * held the values in; one counted read listing it unsorted rules it out for that view. The stored + * value keeps the written order, so a write's response still echoes it; every view of the type that + * could sort the field sorts it once one does. + */ +export class SortedArrays { + readonly #candidates = new Map(); + readonly #adopted = new Map(); + /** Values each type's initial entities held, per candidate field. */ + readonly #existing = new Map>(); + + constructor( + views: Iterable, + entities: readonly StateEntity[], + private readonly facts: { + readonly state: SimulatedState; + readonly io: Pick; + readonly idField: (type: string) => string | undefined; + }, + ) { + for (const view of views) { + if (view.shape !== "item" && view.shape !== "list") continue; + const own = entities.filter((entity) => entity.type === view.type); + const fields = sortableFields(view, own); + if (fields.length === 0) continue; + this.#candidates.set(view.tool, { type: view.type, fields }); + for (const field of fields) this.#noteExisting(view.type, field, own); + facts.io.retain( + ENTRY_BYTES + + fields.reduce((bytes, field) => bytes + textBytes(field.length), 0), + ); + } + } + + /** The view with the array fields it was shown to sort. */ + view(view: View): View { + const adopted = this.#adopted.get(view.tool); + return adopted === undefined ? view : { ...view, sorted_arrays: adopted }; + } + + /** The views with the array fields each was shown to sort. */ + views(views: readonly StateView[]): StateView[] { + return views.map((view) => this.view(view)); + } + + /** + * Note what a read the gate counts shows, then retry it if it failed: the outcome with the fewest + * candidate fields sorted that make it pass, which the type's views then keep; the outcome as it + * was when none does, the passing check is blocked or the read's order is ambiguous. + */ + retry( + view: StateView, + read: { readonly record: StateRecordFacts; readonly outcome: CheckOutcome }, + check: (view: StateView) => CheckOutcome | undefined, + blocked: (targets: readonly string[]) => boolean, + ): CheckOutcome { + const failed = read.outcome; + if (view.shape !== "item" && view.shape !== "list") return failed; + const shown = this.#shown(view, read.record); + this.#ruleOut(view.tool, shown); + const candidates = this.#candidates.get(view.tool)?.fields; + if (failed.pass || candidates === undefined) return failed; + const passing = (fields: readonly string[]) => { + const outcome = check({ + ...view, + sorted_arrays: [...(view.sorted_arrays ?? []), ...fields], + }); + return outcome?.pass === true && + !blocked([...outcome.targets, ...outcome.unheld]) + ? outcome + : undefined; + }; + let outcome = passing(candidates); + if (outcome === undefined) return failed; + let needed = candidates; + for (const field of candidates) { + const fewer = needed.filter((name) => name !== field); + const retried = fewer.length === 0 ? undefined : passing(fewer); + if (retried !== undefined) [needed, outcome] = [fewer, retried]; + } + if (!needed.every((field) => this.#telling(view, shown, field))) + return failed; + this.#adopt(view.type, needed); + return outcome; + } + + /** The entity objects a read recorded at the view's pointer. */ + #shown(view: StateItemView | StateListView, record: StateRecordFacts) { + return this.facts.io.withBody(record.ordinal, (body): JsonObject[] => { + if (body === undefined || body === null) return []; + if (view.shape === "list") + return (listItems(body, view.pointer) ?? []).filter(isObject); + const object = at(body, view.pointer); + return isObject(object) ? [object] : []; + }); + } + + /** A read listing a candidate field unsorted shows its view does not sort it. */ + #ruleOut(tool: string, shown: readonly JsonObject[]): void { + const entry = this.#candidates.get(tool); + if (entry === undefined) return; + const left = entry.fields.filter((field) => + shown.every((object) => { + const value = object[field]; + return !ordered(value) || inOrder(value); + }), + ); + if (left.length === 0) this.#candidates.delete(tool); + else if (left.length < entry.fields.length) + this.#candidates.set(tool, { ...entry, fields: left }); + } + + /** Whether a read shows a written array in an order neither the written one nor the order the values were first held in. */ + #telling( + view: StateItemView | StateListView, + shown: readonly JsonObject[], + field: string, + ): boolean { + const idField = this.facts.idField(view.type) ?? ""; + const existing = this.#existing.get(`${view.type}\u0000${field}`)!; + return shown.some((object) => { + const value = object[field]; + const id = scalarText(object[idField]); + if (!ordered(value) || id === undefined) return false; + return this.facts.state.ofType(view.type).some((entity) => { + const written = entity.id === id ? entity.fields[field] : undefined; + return ( + written !== undefined && + isStringArray(written) && + written.length === value.length && + written.some((item, index) => item !== value[index]) && + !creationOrderFits(value, written, existing) + ); + }); + }); + } + + /** Sort the fields in every view of the type that could sort them. */ + #adopt(type: string, fields: readonly string[]): void { + for (const [tool, entry] of this.#candidates) { + if (entry.type !== type) continue; + const taken = entry.fields.filter((field) => fields.includes(field)); + if (taken.length === 0) continue; + this.#adopted.set(tool, [...(this.#adopted.get(tool) ?? []), ...taken]); + const left = entry.fields.filter((field) => !taken.includes(field)); + if (left.length === 0) this.#candidates.delete(tool); + else this.#candidates.set(tool, { ...entry, fields: left }); + } + } + + #noteExisting( + type: string, + field: string, + entities: readonly StateEntity[], + ): void { + const key = `${type}\u0000${field}`; + let values = this.#existing.get(key); + if (values === undefined) this.#existing.set(key, (values = new Set())); + const held = entities.flatMap((entity) => + [ + entity.fields[field], + ...entity.view_fields.map((view) => view.fields[field]), + ].flatMap((value) => + value !== undefined && value !== null && isStringArray(value) + ? value + : [], + ), + ); + for (const item of held) + if (!values.has(item)) { + this.facts.io.retain(textBytes(item.length)); + values.add(item); + } + } +} diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 4b25d16c056..bff02260e17 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1903,3 +1903,203 @@ describe("values an application stamps", () => { }); }); }); + +/** A book with tags, as an application that keeps tags as a set lists them. */ +const tagged = (entry: Book, tags: string[]): Book => ({ ...entry, tags }); +const TAGGED_INIT_ROWS: TimedCaptureRow[] = [ + [ + "GET", + "/api/books", + [tagged(FIRST_BOOK, ["alpha", "beta"]), tagged(SECOND_BOOK, ["gamma"])], + ], + ["GET", "/api/books/1", tagged(FIRST_BOOK, ["alpha", "beta"])], + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["gamma"])], + [ + "PATCH", + "/api/books/2", + tagged(SECOND_BOOK, ["zeta", "delta"]), + 200, + { tags: ["zeta", "delta"] }, + ], +]; + +describe("array fields a view lists sorted", () => { + it("serves an update whose read-back lists the written tags sorted, and every view of the type sorts them", () => { + const state = stateOf([ + ...TAGGED_INIT_ROWS, + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["delta", "zeta"])], + ]); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [4], + }); + for (const tool of ["get_books_by_id", "get_books"]) + expect(state.views.find((view) => view.tool === tool)).toMatchObject({ + sorted_arrays: ["tags"], + }); + }); + + it("learns no sorting from a read after another the gate counted listed the field unsorted", () => { + const state = stateOf([ + ...TAGGED_INIT_ROWS, + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["zeta", "delta"])], + [ + "PATCH", + "/api/books/1", + tagged(FIRST_BOOK, ["omega", "beta"]), + 200, + { tags: ["omega", "beta"] }, + ], + ["GET", "/api/books/1", tagged(FIRST_BOOK, ["beta", "omega"])], + ]); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: false, + reason: "contradicted", + }); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).not.toHaveProperty("sorted_arrays"); + }); + + it("learns no sorting from a read whose order fits the values held first, then the new ones as written", () => { + // `alpha` was held before the update and `zeta` was not: a store ordering tags by when it made them lists them so too. + const state = stateOf([ + ...TAGGED_INIT_ROWS.slice(0, 3), + [ + "PATCH", + "/api/books/2", + tagged(SECOND_BOOK, ["zeta", "alpha"]), + 200, + { tags: ["zeta", "alpha"] }, + ], + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["alpha", "zeta"])], + ]); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: false, + reason: "contradicted", + }); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).not.toHaveProperty("sorted_arrays"); + }); + + it("keeps the written order a read-back shows, though every initial array was sorted", () => { + const state = stateOf([ + ...TAGGED_INIT_ROWS, + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["zeta", "delta"])], + ]); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [4], + }); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).not.toHaveProperty("sorted_arrays"); + }); +}); + +describe("initial order", () => { + it("orders a collection as a whole list line that applies no sort lists it, after an item read and filtered or sorted lines", () => { + const alpha = book(1, "Alpha", "2026-10-01T09:00:00Z"); + const charlie = book(2, "Charlie", "2026-10-01T10:00:00Z"); + const bravo = book(3, "Bravo", "2026-10-01T11:00:00Z"); + const state = stateOf([ + ["GET", "/api/books/2", charlie], + ["GET", "/api/books?name=Alpha", [alpha]], + ["GET", "/api/books?ordering=name", [alpha, bravo, charlie]], + ["GET", "/api/books", [bravo, alpha, charlie]], + ["GET", "/api/books/1", alpha], + ["GET", "/api/books/3", bravo], + ]); + expect( + state.entities + .filter((entity) => entity.type === "/api/books") + .map((entity) => entity.id), + ).toEqual(["3", "1", "2"]); + }); +}); + +describe("insert rules the recorded order cannot settle", () => { + const listed = (id: string, name: string, created: string) => ({ + id, + name, + created_at: created, + }); + const rowsFor = ( + members: { id: string; name: string; created_at: string }[], + created: { id: string; name: string; created_at: string }, + ): TimedCaptureRow[] => [ + ["GET", "/api/items", members], + ...members.map((member): TimedCaptureRow => [ + "GET", + `/api/items/${member.id}`, + member, + ]), + ["POST", "/api/items", created, 201, { name: created.name }], + ["GET", `/api/items/${created.id}`, created], + ]; + + it("places a create last, not by identity, when its identities are random UUIDs", () => { + const at = "2026-10-01T09:00:00Z"; + const plan = planOf( + stateOf( + rowsFor( + [ + listed("1c0e8a2b-7f3d-4e9a-b1c2-d3e4f5a6b7c8", "Delta", at), + listed("5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d", "Alpha", at), + listed("9b2f1c3e-0d4a-4b6e-8f1a-2c3d4e5f6a7b", "Charlie", at), + ], + listed("e5d6e7f8-1a2b-4c3d-9e4f-5a6b7c8d9e0f", "Echo", bookClock(4)), + ), + ), + "post_items", + ); + expect(plan).toMatchObject({ served: true, insert: { rule: "last" } }); + }); + + it("keeps sorting by an identity a creation clock follows", () => { + const plan = planOf( + environmentStateViewOf( + timedCaptureEvidence( + rowsFor( + [ + listed( + "6ad47b491023b50001087124", + "Alpha", + "2026-10-01T09:00:00Z", + ), + listed( + "6ad47b491023b50001087125", + "Bravo", + "2026-10-01T10:00:00Z", + ), + ], + listed("6ad47b491023b50001087130", "Charlie", bookClock(3)), + ), + ), + ["opaque-token"], + ), + "post_items", + ); + expect(plan).toMatchObject({ + served: true, + insert: { rule: "sorted", field: "id", direction: "ascending" }, + }); + }); + + it("places a create last when the orders the list admits put it in different places", () => { + const plan = planOf( + stateOf( + rowsFor( + [ + listed("2", "Alpha", "2026-10-01T10:00:00Z"), + listed("1", "Delta", "2026-10-01T09:00:00Z"), + ], + listed("3", "Bravo", bookClock(3)), + ), + ), + "post_items", + ); + expect(plan).toMatchObject({ served: true, insert: { rule: "last" } }); + }); +}); diff --git a/src/domain/analysisView/environmentStateWrites.ts b/src/domain/analysisView/environmentStateWrites.ts index 1628104a4f7..e0c4a7d052d 100644 --- a/src/domain/analysisView/environmentStateWrites.ts +++ b/src/domain/analysisView/environmentStateWrites.ts @@ -26,7 +26,7 @@ const clockStart = ( /** * The write plans a capture's own timeline confirms against an extracted state, the served clock's - * start, and the views without the fields reads showed the application leaves out. + * start, and the views without the fields reads showed the application leaves out, with the arrays they showed sorted. */ export const extractWrites = ( state: Pick, @@ -46,6 +46,6 @@ export const extractWrites = ( return { writes, write_clock: clockStart(input.records, input.timed), - views: simulation.omitted.views(state.views), + views: simulation.views(state.views), }; }; From 189152d92380d4cf1c228a993625e1cc327f6d73 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:10:57 -0700 Subject: [PATCH 28/68] feat(environment): serve bulk writes at a collection and target item actions A DELETE, PUT or PATCH at a collection, or a POST at its delete path, whose body names held entities by id is applied to each named entity, and serving refuses it unless every id is held. A POST to an entity's action path that answers nothing or the entity is an update of it; it is served only when a recorded call found each scalar it sets already at that value. Served bulk bodies advertise their items, and compare probes pass them. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 6 + .../agent-environments/state-writes/spec.md | 49 ++- docs/web-network-captures.md | 14 +- .../environment/environmentCompare.ts | 31 +- .../environmentCompareBulk.test.ts | 50 +++ .../environment/environmentCompareMatch.ts | 31 +- .../environment/environmentState.ts | 10 +- .../environment/environmentStateAnswer.ts | 6 +- .../environmentStateBulkAnswer.test.ts | 94 +++++ .../environment/environmentStateBulkAnswer.ts | 215 +++++++++++ .../environmentStateWriteAnswer.ts | 26 +- .../environmentStateWriteDescription.ts | 46 ++- .../environment/environmentToolAnswer.ts | 5 +- .../environment/environmentTools.ts | 46 ++- .../EnvironmentStateWriteSimulation.ts | 43 ++- .../analysisView/environmentStateView.ts | 18 + .../environmentStateWriteAddress.test.ts | 232 ++++++++++++ .../environmentStateWriteAddress.ts | 345 ++++++++++++++++++ .../environmentStateWriteApply.ts | 24 +- .../analysisView/environmentStateWriteBulk.ts | 111 ++++++ .../environmentStateWriteCalls.ts | 79 +++- .../environmentStateWriteDelete.ts | 65 ++++ .../environmentStateWriteEffects.ts | 155 ++++---- .../environmentStateWriteExplain.ts | 21 +- .../environmentStateWriteRules.ts | 25 ++ .../environmentStateWriteVerdict.ts | 12 +- tests/boundary/mcp/toolSchemaValidity.test.ts | 29 ++ 27 files changed, 1637 insertions(+), 151 deletions(-) create mode 100644 src/application/environment/environmentCompareBulk.test.ts create mode 100644 src/application/environment/environmentStateBulkAnswer.test.ts create mode 100644 src/application/environment/environmentStateBulkAnswer.ts create mode 100644 src/domain/analysisView/environmentStateWriteAddress.test.ts create mode 100644 src/domain/analysisView/environmentStateWriteAddress.ts create mode 100644 src/domain/analysisView/environmentStateWriteBulk.ts create mode 100644 src/domain/analysisView/environmentStateWriteDelete.ts diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 3283f83f664..7bd248354cd 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -51,6 +51,12 @@ its cause in the recordings and the code. The five largest shared causes: after the initial window is a variant too when it names a new shaping parameter and its object carries or lacks members the planned lines' do not, and an item only a replayed line showed, which the state never started with, answers with its own recording. +- **Item actions.** A write to an item path plus a literal segment that names no collection, whose calls answer nothing + or the entity (never a 201, and with every field its item read always shows), updates that entity; a scalar it + changes without sending is set on every call. It is served only once a call found every field it sets already at + that value, so a toggle is never served. An action never takes a read another write to the entity still needs. +- **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying + the id field, deletes or updates each one; serving takes the body as recorded, a `DELETE` included. ## Acceptance diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 3575b6a7542..a97f7862567 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -84,6 +84,43 @@ same root regenerates values on every read. | `document` | `PUT`, `PATCH` or `POST` to a document view's path | that document | | `none` | anything else | reason `no-state-target` | +**Item actions.** A `POST`, `PUT` or `PATCH` to an item path plus one literal +segment (`/{type}/{id}/archive`) is an `update` of the entity the item path +names, recorded as `address: {by: "action", segment}`, when the segment names +no collection (no state type ends in it, and it is not `delete`, `remove` or +`destroy`) and every successful call answered nothing or that entity: never a +201, and an object holding the id at the type's id field where an item read of +the type shows its entity, with every field that read always shows. A call +answering anything else made a sub-resource, as a comment `POST` does, and +stays `none`. An action's unsent change of a scalar that no other rule +explains takes the value its observation showed, a `set` rule applied on every +call (`archived: true`); a changed object, list or instant has no rule, so the +plan is `unexplained-change`. An action is served only when it sets something +and a recorded call found every field it sets already at that value, since one +change cannot tell a set from a toggle; otherwise it stays `unconfirmed`. Its +call may send no body. An action is observed in its own response, or in a +later item read only while no other tool's modelled write to the entity awaits +a check: that read then checks the other write, and the action's call is one +the gate does not model. + +**Bulk writes.** A `DELETE`, `PUT` or `PATCH` at a type's +`collection_template`, or a `POST` to it plus `delete`, `remove` or `destroy`, +names its entities in its body: an array of ids of one JSON kind, or of +objects carrying the type's `id_field`, at the root or as the body's one array +member (`{"IDs": […], "Read": true}`, `[{"Id": 9}]`). Every successful call +must name them the same way, recorded as `address: {by: "ids", member, kind}` +or `{by: "elements", member}`. A path whose last segment is the type's +singular or plural (`/messages` for `/message`) writes that type. An `ids` +member applies the body's other members to every id, an element its own +members; a root id array updates nothing. Each named entity gets the effect as +an item call would, checked by the same reads; one the state does not hold +leaves the call unmodelled there. A bulk update's observation must show the +members the call sent. Serving answers any ids only when the exemplar's +response fits: no body, a body naming none of the recorded ids and holding no +number equal to how many it named (a count), or an array with one element per +id, each showing it as the first does; otherwise the reason is +`body-unusable`. + A `POST` whose path gives it no target is a `create` into the type its returned id is read under: its exemplar's response names an id (an identity member of the body or of an object member, or a scalar body or sole member of four characters @@ -583,7 +620,17 @@ covers its arguments; otherwise it keeps the recorded page members. **Provenance.** Write answers carry `state: {source: "state", view: "create" | "update" | "delete", type, collection, id}`, or `{source: "state", view: -"document-write", path}`. +"document-write", path}`. A bulk answer adds `ids`, every entity it wrote in +body order, `id` naming the first. + +**Bulk and action calls.** A served bulk tool takes its body as recorded (an +array of objects or of ids of the recorded kind, or an object), a `DELETE` +included, and `environment-compare` sends a probe's body to it; every id must +name an entity the state holds, else the call is refused and the state is +unchanged. A bulk +update with a `unique` or `renewed` rule writes one entity per call, since one +call draws those values once. A served item action's path names its entity +before the action segment. **Data plane and export.** diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index 7cfe1155691..7023dddef5f 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -665,8 +665,10 @@ recorded lines; a line they do not reproduce keeps its recorded members. `writes` lists one plan per tool whose request may change state, in tool order. Its `effect` is `create` for a `POST` to a type's `collection_template`, `update` for a `PUT`, `PATCH` or `POST` to that template -plus one trailing parameter, `delete` for a `DELETE` to it, `document` for a -`PUT`, `PATCH` or `POST` to a document's path, and otherwise `none` with reason +plus one trailing parameter, or to that item path plus one action segment, +`delete` for a `DELETE` to it, `document` for a `PUT`, `PATCH` or `POST` to a +document's path, an `update` or `delete` of each entity a write at the +collection names by id in its body, and otherwise `none` with reason `no-state-target`. A plan is built from the tool's first successful call: its request body must be a usable JSON object (as response bodies are usable), and the written entity must show in that call's response or in a later read before @@ -684,9 +686,11 @@ echo when stored as sent; a member stored differently is accepted only with its recorded value (`body.fixed`) and stores the value the call that showed it recorded (the `value` of its `constant` rule), and a field it changed without sending must be a clock, a nested clock, an increment, a slug, a fresh `unique` -value, a `stamp` of the acting user or a value `derived` from the one member it -stores nowhere, or the plan is `unexplained-change`; an increment, slug, stamp -or derived value must hold for every call of the tool. A write is served only +value, a `stamp` of the acting user, a value `derived` from the one member it +stores nowhere, or for an item action a `set` of a scalar to the value it +showed, or the plan is `unexplained-change`; an increment, slug, stamp, derived +value or set must hold for every call of the tool, and an action is served +only once a call found what it sets already set. A write is served only with the query its first call sent. Every member the first call sent is required, except by `PATCH` and `POST` updates. diff --git a/src/application/environment/environmentCompare.ts b/src/application/environment/environmentCompare.ts index 2c0e4705995..ccde948387b 100644 --- a/src/application/environment/environmentCompare.ts +++ b/src/application/environment/environmentCompare.ts @@ -21,7 +21,9 @@ import { import { collectionScope, literalPositions, + bodyTools, matchProbeRequest, + probeArguments, parameterScopes, type ProbeToolCall, } from "./environmentCompareMatch.js"; @@ -52,10 +54,7 @@ import { environmentToolAnswer, type EnvironmentToolAnswer, } from "./environmentToolAnswer.js"; -import { - environmentToolArguments, - type EnvironmentToolDefinition, -} from "./environmentTools.js"; +import { type EnvironmentToolDefinition } from "./environmentTools.js"; import { same } from "../../domain/analysisView/environmentStateRules.js"; /** One probe capture file: its label for the report and its parsed JSON. */ @@ -216,7 +215,7 @@ const answersCall = ( !selectsRecordedLine(call.tool, exchange, args) ) return false; - const body = environmentToolArguments(call.tool).body; + const body = probeArguments(call.tool, run.bodies).body; // A tool with no body parameter matches; one that takes a body matches only the body this call sent, including none. if (body === undefined) return true; return same(run.recordedBodies.get(exchange.ordinal), args[body]); @@ -246,6 +245,8 @@ interface ProbeRun { readonly store: EnvironmentStateStore | undefined; /** The tools the environment offers, by name, with their input checks. */ readonly served: ReadonlyMap; + /** The served tools that take a body their method does not, as a bulk delete names its entities. */ + readonly bodies: ReadonlySet; readonly map: IdMap; readonly normalised: Normalised; } @@ -298,22 +299,20 @@ const compareStep = ( // Matched in the environment's terms, so a tool whose path holds a seeded id literally still matches. Scopes and // literals come from the live path: translating a parent id first would name a different collection than learning did. const liveSegments = request.path.slice(1).split("/"); - const fitted = matchProbeRequest(manifest, request); + const fitted = matchProbeRequest(manifest, request, run.bodies); const scopes = fitted === undefined ? undefined : parameterScopes(fitted.tool, liveSegments); const literals = fitted === undefined ? undefined : literalPositions(fitted.tool); - const call = matchProbeRequest(manifest, { - ...request, - path: translatePath( - request.path, - run.map, - (index) => scopes?.get(index), - (index) => literals?.has(index) === true, - ), - }); + const path = translatePath( + request.path, + run.map, + (index) => scopes?.get(index), + (index) => literals?.has(index) === true, + ); + const call = matchProbeRequest(manifest, { ...request, path }, run.bodies); if (call === undefined) return report(call, { env_status: null, @@ -460,6 +459,7 @@ export const compareEnvironment = (input: { inputCheck(definition), ]), ); + const bodies = bodyTools(catalog.value.tools); const recorded = parseCaptureEvidence( operation, input.captureValue, @@ -507,6 +507,7 @@ export const compareEnvironment = (input: { answer: environmentToolAnswer(source, store), store, served, + bodies, map: new IdMap(), normalised: emptyNormalised(), }; diff --git a/src/application/environment/environmentCompareBulk.test.ts b/src/application/environment/environmentCompareBulk.test.ts new file mode 100644 index 00000000000..040904996a8 --- /dev/null +++ b/src/application/environment/environmentCompareBulk.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; + +import { + timedCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { + environmentServeSource, + environmentStateServeFixture, +} from "../../../tests/fixtures/environmentServe.js"; +import { + BOOK_INIT_ROWS, + BOOK_NOT_FOUND, + FIRST_BOOK, +} from "../../../tests/fixtures/environmentStateWrites.js"; +import { compareEnvironment } from "./environmentCompare.js"; + +const RECORDED: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], +]; + +describe("environment comparison of bulk writes", () => { + it("sends a probe's bulk delete body to the served tool, which answers it from the state", () => { + const fixture = environmentStateServeFixture( + timedCaptureEvidence(RECORDED), + ); + const report = compareEnvironment({ + source: environmentServeSource(fixture), + captureValue: fixture.capture, + probes: [ + { + label: "bulk-delete", + value: timedCaptureEvidence([ + ["GET", "/api/books/1", FIRST_BOOK], + ["DELETE", "/api/books", [{ id: 1 }], 200, [{ id: 1 }]], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ]), + }, + ], + operation: "environment-compare", + }); + if (!report.ok) throw report.error; + const [, deleted, read] = report.value.probes[0]!.results; + expect(deleted).toMatchObject({ env_status: 200, equal: true }); + expect(read).toMatchObject({ env_status: 404, equal: true }); + }); +}); diff --git a/src/application/environment/environmentCompareMatch.ts b/src/application/environment/environmentCompareMatch.ts index 9eaae565472..1a06e7d1830 100644 --- a/src/application/environment/environmentCompareMatch.ts +++ b/src/application/environment/environmentCompareMatch.ts @@ -6,7 +6,10 @@ import type { EnvironmentManifest, EnvironmentManifestTool, } from "./environmentSource.js"; -import { environmentToolArguments } from "./environmentTools.js"; +import { + environmentToolArguments, + type EnvironmentToolDefinition, +} from "./environmentTools.js"; const FORMAT_RULES: ReadonlySet = new Set([ "numeric", @@ -136,10 +139,32 @@ const fitOf = ( return { tool, literals }; }; -/** The tool of the request's method whose template fits the path with the most literal segments; the manifest's order breaks ties. */ +/** A tool's arguments as the served catalog offers them: a body too when `bodies` names it. */ +export const probeArguments = ( + tool: EnvironmentManifestTool, + bodies: ReadonlySet, +) => environmentToolArguments(tool, bodies.has(tool.name) ? true : undefined); + +/** The served tools whose catalog takes a body, by name, as a bulk delete names its entities in one. */ +export const bodyTools = ( + definitions: readonly EnvironmentToolDefinition[], +): Set => + new Set( + definitions.flatMap((definition) => + Object.hasOwn( + definition.inputSchema.properties, + environmentToolArguments(definition.tool, true).body!, + ) + ? [definition.name] + : [], + ), + ); + +/** The tool of the request's method whose template fits the path with the most literal segments; the manifest's order breaks ties. `bodies` names the tools a served catalog gives a body beyond their method's. */ export const matchProbeRequest = ( manifest: EnvironmentManifest, request: ProbeRequest, + bodies: ReadonlySet = new Set(), ): ProbeToolCall | undefined => { const segments = request.path.slice(1).split("/"); let best: Fit | undefined; @@ -154,7 +179,7 @@ export const matchProbeRequest = ( } if (best === undefined) return undefined; const { tool } = best; - const names = environmentToolArguments(tool); + const names = probeArguments(tool, bodies); const args: Record = {}; const pathArguments: string[] = []; for (const param of tool.params) { diff --git a/src/application/environment/environmentState.ts b/src/application/environment/environmentState.ts index fcc4bf5a0b1..d54e54b2039 100644 --- a/src/application/environment/environmentState.ts +++ b/src/application/environment/environmentState.ts @@ -25,7 +25,10 @@ import { } from "./environmentSource.js"; import { STATE_INTAKE_LIMIT_BYTES } from "./environmentStateDocument.js"; import { initialStateBytes } from "./environmentStateStore.js"; -import { describeWrite } from "./environmentStateWriteDescription.js"; +import { + describeWrite, + writeBody, +} from "./environmentStateWriteDescription.js"; import { environmentToolDefinitions, type EnvironmentDataPlane, @@ -101,7 +104,10 @@ export const servedCatalog = ( dataPlane, ...(state === undefined ? {} - : { describe: (tool) => describeWrite(state.writes.get(tool.name)) }), + : { + describe: (tool) => describeWrite(state.writes.get(tool.name)), + body: (tool) => writeBody(state.writes.get(tool.name)), + }), }, ); return tools.ok ? ok({ tools: tools.value, dataPlane }) : tools; diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 7c3c6f31412..ccb278d02af 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -99,6 +99,8 @@ export type StateProvenance = readonly type: string; readonly collection: string; readonly id: string; + /** Every entity a bulk call wrote, in body order; `id` is the first. */ + readonly ids?: readonly string[]; }; /** A replay answer that also says whether the state or a recording produced it. */ @@ -206,12 +208,14 @@ export interface ItemCall { readonly id: string; } -/** What an item call names, or undefined when a path argument is missing. */ +/** What an item call names, or undefined when a path argument is missing; an item action's id comes before its action segment. */ export const itemCall = ( tool: EnvironmentManifestTool, args: ReplayArguments, + action = false, ): ItemCall | undefined => { const segments = callSegments(tool, args); + if (action && segments?.pop()?.supplied !== false) return undefined; const last = segments?.pop(); return segments !== undefined && last?.supplied === true ? { segments, id: last.text } diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts new file mode 100644 index 00000000000..545cddb049e --- /dev/null +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from "vitest"; + +import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js"; +import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js"; +import { + BOOK_INIT_ROWS, + BOOK_NOT_FOUND, + FIRST_BOOK, + SECOND_BOOK, + type Book, +} from "../../../tests/fixtures/environmentStateWrites.js"; +import { servedCatalog } from "./environmentState.js"; + +const BULK_DELETE_ROWS: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], +]; + +/** A book with an `archived` flag, which an item action sets. */ +const shelved = (entity: Book, archived: boolean) => ({ ...entity, archived }); + +describe("served bulk writes", () => { + it("deletes every row a call names, answering one element per row", () => { + const books = servedFrom(BULK_DELETE_ROWS); + expect( + books.answer("delete_books", { body: [{ id: 1 }, { id: 2 }] }), + ).toMatchObject({ + status: 200, + body: [{ id: 1 }, { id: 2 }], + state: { + source: "state", + view: "delete", + type: "/api/books", + ids: ["1", "2"], + }, + }); + expect(books.store.ofType("/api/books")).toEqual([]); + }); + + it("refuses a call naming a row the state does not hold, leaving the state unchanged", () => { + const books = servedFrom(BULK_DELETE_ROWS); + const before = books.snapshot(); + expect( + books.refusal("delete_books", { body: [{ id: 1 }, { id: 9 }] }), + ).toMatchObject({ + message: expect.stringContaining("holds no /api/books entity 9"), + }); + expect(books.snapshot()).toBe(before); + }); + + it("advertises the body a bulk delete takes as the array its recording sent", () => { + const books = servedFrom(BULK_DELETE_ROWS); + const catalog = servedCatalog(books.source, books.state, "books"); + if (!catalog.ok) throw catalog.error; + const tool = catalog.value.tools.find( + (definition) => definition.name === "delete_books", + ); + expect(tool?.inputSchema.properties["body"]).toMatchObject({ + type: "array", + items: { type: "object" }, + }); + }); +}); + +describe("served item actions", () => { + it("sets what the action changed on the entity the path names", () => { + const books = servedFrom([ + [ + "GET", + "/api/books", + [shelved(FIRST_BOOK, false), shelved(SECOND_BOOK, false)], + ], + ["GET", "/api/books/1", shelved(FIRST_BOOK, false)], + ["GET", "/api/books/2", shelved(SECOND_BOOK, false)], + ["POST", "/api/books/1/archive", shelved(FIRST_BOOK, true)], + ["GET", "/api/books/1", shelved(FIRST_BOOK, true)], + ["POST", "/api/books/1/archive", shelved(FIRST_BOOK, true)], + ["GET", "/api/books/1", shelved(FIRST_BOOK, true)], + ]); + expect(books.answer("post_books_archive_by_id", { id: "2" })).toMatchObject( + { + status: 200, + body: shelved(SECOND_BOOK, true), + state: { source: "state", view: "update", id: "2" }, + }, + ); + expect(books.answer("get_books_by_id", { id: "2" })).toMatchObject({ + body: shelved(SECOND_BOOK, true), + state: { source: "state" }, + }); + }); +}); diff --git a/src/application/environment/environmentStateBulkAnswer.ts b/src/application/environment/environmentStateBulkAnswer.ts new file mode 100644 index 00000000000..9a1d2358535 --- /dev/null +++ b/src/application/environment/environmentStateBulkAnswer.ts @@ -0,0 +1,215 @@ +import { namedEntities } from "../../domain/analysisView/environmentStateWriteAddress.js"; +import { + updatedEntity, + updatedFields, + writtenResponse, +} from "../../domain/analysisView/environmentStateWriteApply.js"; +import type { + FieldRule, + WriteResponse, +} from "../../domain/analysisView/environmentStateWriteRules.js"; +import { + isParam, + segmentsOf, + type JsonObject, + type StateEntity, + type SuppliedSegment, +} from "../../domain/analysisView/environmentStateRules.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import type { JsonValue } from "../../domain/jsonValue.js"; +import { err, ok, type Result } from "../../domain/result.js"; +import { callSegments } from "./environmentStateCallLines.js"; +import { + namedEntity, + refused, + type StateAnswer, + type StateServing, +} from "./environmentStateAnswer.js"; +import { + isLoadableValue, + unloadableMember, +} from "./environmentStateDocument.js"; +import { + generator, + observedEntity, + pathValues, + unloadable, + writeAnswer, + type WriteRequest, +} from "./environmentStateWriteAnswer.js"; +import { + environmentToolArguments, + hasRepeatedQueryArgument, +} from "./environmentTools.js"; + +/** Rules whose generated value is drawn once per call, which one call cannot give several entities. */ +const DRAWN_ONCE = new Set(["unique", "renewed"]); + +/** The collection a bulk call's path names, with the type's spelling of its last segment, and no delete segment after it. */ +const collectionSegments = ( + segments: readonly SuppliedSegment[], + target: string, +): SuppliedSegment[] => { + const typed = segmentsOf(target); + const collection = segments.slice(0, typed.length); + const last = typed.at(-1)!; + if (!isParam(last)) + collection[typed.length - 1] = { text: last, supplied: false }; + return collection; +}; + +/** A bulk answer from the recorded one: one element per written entity, rendered as the first recorded element shows its entity. */ +const bulkResponse = ( + response: WriteResponse, + recorded: JsonValue | undefined, + written: readonly { readonly fields: JsonObject; readonly id: string }[], +): Result => { + if (response.shape === "empty") return ok(undefined); + const [template] = Array.isArray(recorded) ? recorded : []; + if (template === undefined) + return err("The recorded response shows no element to render."); + const elements: JsonValue[] = []; + for (const entity of written) { + const element = writtenResponse( + { ...response, pointer: "" }, + template, + entity, + ); + if (!element.ok) return element; + elements.push(element.value ?? null); + } + return ok(elements); +}; + +/** The held entities a bulk call names, with the members each gets, or a refusal for an entity the state does not hold. */ +const namedTargets = ( + serving: StateServing, + request: WriteRequest, +): Result< + { readonly entity: StateEntity; readonly body: JsonObject | undefined }[], + AnalysisError +> => { + const { tool, plan, args } = request; + const { address } = plan; + const type = plan.target ?? ""; + const name = environmentToolArguments(tool, true).body; + const body = name === undefined ? undefined : (args[name] as JsonValue); + if (body !== undefined && !isLoadableValue(body)) + return err(unloadable(tool, "The body")); + const named = + address === undefined || address.by === "action" + ? undefined + : namedEntities(address, body, serving.store.type(type)?.id_field ?? ""); + if (named === undefined) + return err( + refused( + tool, + `Tool ${tool.name} names the entities it writes by their ids in its body, as its recording did.`, + ), + ); + const segments = callSegments(tool, args); + if (segments === undefined) + return err(refused(tool, `Tool ${tool.name} needs every path argument.`)); + const collection = collectionSegments(segments, type); + const targets = []; + for (const { id, body: members } of named) { + const entity = namedEntity(serving.store, type, { + segments: collection, + id, + }); + if (entity === undefined) + return err( + refused( + tool, + `The state holds no ${type} entity ${id}; the state is unchanged.`, + ), + ); + targets.push({ entity, body: members }); + } + return ok(targets); +}; + +/** Apply one served bulk call to every entity its body names and answer it; a refused call leaves the state unchanged. */ +export const answerBulk = ( + serving: StateServing, + request: WriteRequest, +): Result => { + const { tool, plan, args } = request; + if (hasRepeatedQueryArgument(tool, args)) + return err( + refused( + tool, + "The state write model cannot apply repeated query parameters; the state is unchanged.", + ), + ); + const targets = namedTargets(serving, request); + if (!targets.ok) return targets; + const update = plan.effect === "update"; + if ( + update && + targets.value.length > 1 && + plan.rules.some((rule) => DRAWN_ONCE.has(rule.rule)) + ) + return err( + refused( + tool, + `Tool ${tool.name} generates a value per call, so it writes one entity per call here.`, + ), + ); + const [first] = targets.value; + const observed = observedEntity(serving, plan) ?? {}; + const values = generator(serving, request, { + name: first!.entity.collection, + collection: serving.store.inCollection( + first!.entity.type, + first!.entity.collection, + ), + observed, + }); + const written: StateEntity[] = []; + for (const { entity, body } of targets.value) { + if (!update) { + written.push(entity); + continue; + } + const fields = updatedFields( + plan, + { before: entity.fields, observed }, + { + path: tool.path_template, + pathValues: pathValues(tool, args), + body, + id: entity.id, + }, + values.generate, + ); + if (!fields.ok) return err(refused(tool, fields.error)); + const field = unloadableMember(fields.value); + if (field !== undefined) return err(unloadable(tool, `Field ${field}`)); + written.push(updatedEntity(entity, fields.value)); + } + const answer = writeAnswer( + serving, + request, + (recorded) => bulkResponse(plan.response!, recorded, written), + { + source: "state", + view: update ? "update" : "delete", + type: first!.entity.type, + collection: first!.entity.collection, + id: first!.entity.id, + ids: written.map((entity) => entity.id), + }, + ); + if (!answer.ok) return answer; + for (const entity of written) { + if (!update) { + serving.store.remove(entity); + continue; + } + const updated = serving.store.update(entity); + if (!updated.ok) return updated; + } + serving.store.commitWrite(values.taken); + return answer; +}; diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index d6061f4f85e..80c08dcb944 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -79,7 +79,7 @@ import { const GENERATION_ATTEMPTS = 64; /** One served write call: the tool, its plan and its arguments. */ -interface WriteRequest { +export interface WriteRequest { readonly tool: EnvironmentManifestTool; readonly plan: StateWritePlan; readonly args: ReplayArguments; @@ -87,7 +87,7 @@ interface WriteRequest { } /** The path values a call supplies, keyed by template segment as write plans name them. */ -const pathValues = ( +export const pathValues = ( tool: EnvironmentManifestTool, args: ReplayArguments, ): Map => { @@ -105,7 +105,7 @@ const pathValues = ( }; /** A refusal for a value `data/add` would refuse, so `data/get` always reports a state that loads back. */ -const unloadable = ( +export const unloadable = ( tool: EnvironmentManifestTool, holder: string, ): AnalysisError => @@ -141,7 +141,7 @@ const callBody = ({ }; /** The entity a recorded observation shows: the values a create keeps and an update's constants. */ -const observedEntity = ( +export const observedEntity = ( serving: StateServing, plan: StateWritePlan, ): JsonObject | undefined => { @@ -170,7 +170,7 @@ const nextHeld = ( * value, and UUIDs and tokens seeded by the state Evidence, tool, field and write count, * skipping values the type already holds. */ -const generator = ( +export const generator = ( serving: StateServing, request: WriteRequest, target: { @@ -280,10 +280,14 @@ const generator = ( }; /** A write's answer on its recorded response's status and content type: a rendered body, none, or the recorded one. */ -const writeAnswer = ( +export const writeAnswer = ( serving: StateServing, request: WriteRequest, - rendered: { readonly fields: JsonObject | undefined; readonly id: string }, + rendered: + | { readonly fields: JsonObject | undefined; readonly id: string } + | (( + recorded: JsonValue | undefined, + ) => Result), state: StateProvenance, ): Result => { const { plan, tool, args } = request; @@ -302,7 +306,11 @@ const writeAnswer = ( )?.exact === true; if (plan.response.shape === "recorded") return ok({ ...replayAnswer(serving.source, exchange, exact), state }); - const body = writtenResponse(plan.response, recordedJson(exchange), rendered); + const recorded = recordedJson(exchange); + const body = + typeof rendered === "function" + ? rendered(recorded) + : writtenResponse(plan.response, recorded, rendered); if (!body.ok) return err(refused(tool, body.error)); return stateAnswer(serving, { exchange, exact }, body.value ?? null, state); }; @@ -477,7 +485,7 @@ const targetEntity = ( request: WriteRequest, ): Result> => { const { tool, plan, args } = request; - const call = itemCall(tool, args); + const call = itemCall(tool, args, plan.address?.by === "action"); if (call === undefined) return err( err(refused(tool, `Tool ${tool.name} needs every path argument.`)), diff --git a/src/application/environment/environmentStateWriteDescription.ts b/src/application/environment/environmentStateWriteDescription.ts index c3892fd41be..d0ab2286a7d 100644 --- a/src/application/environment/environmentStateWriteDescription.ts +++ b/src/application/environment/environmentStateWriteDescription.ts @@ -2,7 +2,11 @@ import type { StateWritePlan, WriteBody, } from "../../domain/analysisView/environmentStateWriteRules.js"; -import { describeList, quotedName } from "./environmentTools.js"; +import { + describeList, + quotedName, + type EnvironmentToolProperty, +} from "./environmentTools.js"; /** Captured member names, quoted and sampled as response fields are; the plan in the state Evidence holds every one. */ const members = (names: readonly string[]): string => @@ -12,6 +16,7 @@ const members = (names: readonly string[]): string => const bodyClause = ( body: WriteBody, effect: StateWritePlan["effect"], + action = false, ): string => { const parts: string[] = []; if (body.accepted.length > 0) @@ -22,7 +27,7 @@ const bodyClause = ( ); if (body.required.length > 0) parts.push(`required: ${members(body.required)}`); - else if (effect === "update") parts.push("send at least one"); + else if (effect === "update" && !action) parts.push("send at least one"); return parts.length === 0 ? "" : ` (${parts.join("; ")})`; }; @@ -31,7 +36,17 @@ export const describeWrite = ( plan: StateWritePlan | undefined, ): string | undefined => { if (plan?.served !== true) return undefined; - const body = plan.body === null ? "" : bodyClause(plan.body, plan.effect); + const { address } = plan; + const body = + plan.body === null + ? "" + : bodyClause(plan.body, plan.effect, address?.by === "action"); + if (address !== undefined && address.by !== "action") + return plan.effect === "delete" + ? "removes the entities its body names by id from the served environment state, modelled on the recorded calls" + : `changes the entities its body names by id in the served environment state${body}, modelled on the recorded calls`; + if (address?.by === "action") + return `applies ${quotedName(address.segment)} to the entity the path names in the served environment state${body}, modelled on the recorded calls`; switch (plan.effect) { case "create": return `creates an entity of ${plan.target ?? ""} in the served environment state${body}, modelled on the recorded calls`; @@ -45,3 +60,28 @@ export const describeWrite = ( return undefined; } }; + +/** The body a served bulk write takes: the recorded form naming its entities by id, an array or an object. */ +export const writeBody = ( + plan: StateWritePlan | undefined, +): EnvironmentToolProperty | undefined => { + const address = plan?.served === true ? plan.address : undefined; + if (address === undefined || address.by === "action") return undefined; + const ids = + address.by === "ids" + ? "an array of entity ids" + : "an array of objects each carrying its entity's id field"; + const items = { + type: address.by === "ids" ? address.kind : "object", + } as const; + return address.member === null + ? { + type: "array", + items, + description: `Request body: ${ids}, as recorded.`, + } + : { + type: "object", + description: `Request body: ${quotedName(address.member)} holds ${ids}, as recorded.`, + }; +}; diff --git a/src/application/environment/environmentToolAnswer.ts b/src/application/environment/environmentToolAnswer.ts index 16b4330f306..2394949b030 100644 --- a/src/application/environment/environmentToolAnswer.ts +++ b/src/application/environment/environmentToolAnswer.ts @@ -10,6 +10,7 @@ import type { EnvironmentSource, } from "./environmentSource.js"; import { answerFromState } from "./environmentStateAnswer.js"; +import { answerBulk } from "./environmentStateBulkAnswer.js"; import type { EnvironmentStateStore } from "./environmentStateStore.js"; import { answerWrite } from "./environmentStateWriteAnswer.js"; @@ -30,8 +31,10 @@ export const environmentToolAnswer = ( replayEnvironmentTool(source, tool, args, observedQuery) : (tool, args, observedQuery) => { const plan = store.state.writes.get(tool.name); + const bulk = + plan?.address !== undefined && plan.address.by !== "action"; return plan?.served === true - ? answerWrite( + ? (bulk ? answerBulk : answerWrite)( { source, store }, { tool, diff --git a/src/application/environment/environmentTools.ts b/src/application/environment/environmentTools.ts index 0ad2a426188..b13df7f8276 100644 --- a/src/application/environment/environmentTools.ts +++ b/src/application/environment/environmentTools.ts @@ -27,7 +27,7 @@ export const REPLAY_CATALOG_INSTRUCTIONS = /** JSON Schema advertised for one tool argument. */ export interface EnvironmentToolProperty { readonly type?: "string" | "object" | "array"; - readonly items?: { readonly type: "string" }; + readonly items?: { readonly type: "string" | "number" | "object" }; readonly oneOf?: readonly ( | { readonly type: "string" } | { readonly type: "array"; readonly items: { readonly type: "string" } } @@ -280,6 +280,7 @@ const freeName = ( /** Path parameters keep their names; a query name or the write body that would collide is renamed, so every input stays addressable. */ export const environmentToolArguments = ( tool: EnvironmentManifestTool, + body = WRITE_METHODS.has(tool.method), ): EnvironmentToolArguments => { const taken = new Set(); const path = new Map(); @@ -305,9 +306,7 @@ export const environmentToolArguments = ( return { path, query, - body: WRITE_METHODS.has(tool.method) - ? freeName(taken, "body", "request_") - : undefined, + body: body ? freeName(taken, "body", "request_") : undefined, }; }; @@ -327,6 +326,10 @@ export const hasRepeatedQueryArgument = ( function* environmentToolProperties( tool: EnvironmentManifestTool, args: EnvironmentToolArguments, + body: EnvironmentToolProperty = { + type: "object", + description: bodyDescription(tool), + }, ): IterableIterator { for (const param of tool.params) yield [ @@ -349,12 +352,7 @@ function* environmentToolProperties( }, false, ]; - if (args.body !== undefined) - yield [ - args.body, - { type: "object", description: bodyDescription(tool) }, - false, - ]; + if (args.body !== undefined) yield [args.body, body, false]; } /** Serialization reservation calibrated with 1500 fields and eight concurrent SDK discovery requests. */ @@ -381,8 +379,27 @@ export interface EnvironmentCatalogOptions { readonly dataPlane?: EnvironmentDataPlane; /** What a served tool does, in place of how it answers; undefined keeps the answering sentence. */ readonly describe?: (tool: EnvironmentManifestTool) => string | undefined; + /** The body a served tool takes in place of the method's, as a bulk write names its entities in it. */ + readonly body?: ( + tool: EnvironmentManifestTool, + ) => EnvironmentToolProperty | undefined; } +/** The body a tool takes in a catalog: a served plan's, else the method's. */ +const catalogBody = ( + tool: EnvironmentManifestTool, + body: EnvironmentCatalogOptions["body"], +): { + readonly property: EnvironmentToolProperty | undefined; + readonly withBody: boolean; +} => { + const property = body?.(tool); + return { + property, + withBody: WRITE_METHODS.has(tool.method) || property !== undefined, + }; +}; + /** Admit complete discovery before binding; six bytes per UTF-16 unit covers JSON escaping and UTF-8 expansion. */ export const environmentToolDefinitions = ( source: EnvironmentSource, @@ -391,6 +408,7 @@ export const environmentToolDefinitions = ( operation = ENVIRONMENT_SERVE_OPERATION, dataPlane = "none", describe, + body, }: EnvironmentCatalogOptions = {}, ): Result< readonly EnvironmentToolDefinition[], @@ -439,21 +457,21 @@ export const environmentToolDefinitions = ( !text(tool.name) ) return refused(); + const { property: taken, withBody } = catalogBody(tool, body); const count = - tool.params.length + - tool.query_parameter_names.length + - (WRITE_METHODS.has(tool.method) ? 1 : 0); + tool.params.length + tool.query_parameter_names.length + Number(withBody); // A lower bound rejects enormous argument lists before constructing their alias map. if (!reserve(count * EMPTY_PROPERTY_BYTES)) return refused(); // The response summary is bounded by its samples and charged with the whole description. const description = toolDescription(source, tool, describe, answers); if (!text(description)) return refused(); - const args = environmentToolArguments(tool); + const args = environmentToolArguments(tool, withBody); const properties = new Map(); const required: string[] = []; for (const [argument, property, mandatory] of environmentToolProperties( tool, args, + taken, )) { if ( !text(argument) || diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 12985b15cdf..bf26d2af222 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -14,6 +14,7 @@ import { } from "./environmentStateRules.js"; import { UnseenEntities } from "./environmentStateWriteAdoption.js"; import { FailedReadBlame } from "./environmentStateWriteBlame.js"; +import { addressedWrite } from "./environmentStateWriteAddress.js"; import { linkedTarget } from "./environmentStateWriteLinks.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; @@ -53,10 +54,11 @@ import { type TouchedTargets, writtenFieldChecks, } from "./environmentStateWriteAttribution.js"; +import { applyBulk } from "./environmentStateWriteBulk.js"; import { applyCreate } from "./environmentStateWriteCreate.js"; import { applyDocument } from "./environmentStateWriteDocument.js"; +import { applyDelete } from "./environmentStateWriteDelete.js"; import { - applyDelete, applyUpdate, built, type EffectContext, @@ -186,12 +188,22 @@ export class EnvironmentStateWriteSimulation { viewOf: (ordinal) => this.#input.views.get(this.#toolOf.get(ordinal)?.name ?? ""), }); - const { effect, target } = link; + const addressed = + link.effect === "none" + ? addressedWrite(tool, { + ...this.#input, + types, + idField: (type) => this.#types.get(type)?.id_field, + views: this.#input.views.values(), + }) + : undefined; + const { effect, target } = addressed ?? link; this.#input.io.retain(512); this.#drafts.set(tool.name, { plan: { ...unservedPlan(tool.name, effect, target, "no-state-target"), reason: effect === "none" ? "no-state-target" : null, + ...(addressed === undefined ? {} : { address: addressed.address }), }, observed: undefined, candidates: [], @@ -201,6 +213,7 @@ export class EnvironmentStateWriteSimulation { calls: 0, updates: [], sequences: new Map(), + steady: new Set(), linked: link.collection, }); } @@ -253,6 +266,10 @@ export class EnvironmentStateWriteSimulation { this.#input.documents.find((document) => document.tool === tool), startedWith: (type) => this.#input.entities.filter((entity) => entity.type === type), + pending: (target) => + [...(this.#touched.get(target)?.keys() ?? [])].some( + (name) => name !== writer, + ), }; } @@ -276,19 +293,25 @@ export class EnvironmentStateWriteSimulation { const observeOnly = draft.plan.reason !== null; if (!observeOnly) draft.calls += 1; const step: WriteStep = { record, index, tool, observeOnly }; - const result = APPLY[effect](this.#context(tool.name), draft, step); + const context = this.#context(tool.name); + const { address } = draft.plan; + const results = + address !== undefined && address.by !== "action" + ? applyBulk(context, draft, step) + : [APPLY[effect](context, draft, step)]; // A call of a tool whose plan was never built, or one a linked plan does not place, is no more modelled than one of a tool without a plan. if ( - result.kind === "unknown" && + results.some((result) => result.kind === "unknown") && (!built(draft) || draft.linked !== undefined) ) this.#unseen.unplanned(index); - this.#settle(result, { - index, - tool: tool.name, - path: record.path, - end: record.end, - }); + for (const result of results) + this.#settle(result, { + index, + tool: tool.name, + path: record.path, + end: record.end, + }); } /** Attribute an applied effect to its tool; a recorded outcome is the state's new baseline; an unknown one taints. */ diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 10f461da1db..8b11017c071 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -264,6 +264,7 @@ const fieldRuleSchema = z.discriminatedUnion("rule", [ from: jsonValueSchema, member: z.string(), }), + z.strictObject({ ...ruled, rule: z.literal("set"), value: jsonValueSchema }), ]); const insertRuleSchema = z.union([ z.strictObject({ rule: z.enum(["first", "last"]) }), @@ -349,6 +350,23 @@ const writePlanSchema = z.strictObject({ .array(ordinalSchema) .describe("Later reads that reproduced from the state after this write."), contradicted_by: ordinalSchema.nullable(), + address: z + .discriminatedUnion("by", [ + z.strictObject({ by: z.literal("action"), segment: z.string() }), + z.strictObject({ + by: z.literal("ids"), + member: z.string().nullable(), + kind: z.enum(["number", "string"]), + }), + z.strictObject({ + by: z.literal("elements"), + member: z.string().nullable(), + }), + ]) + .optional() + .describe( + "How a call names its entities when its path does not end in one: the action segment after the item's id, or the body's ids as an array of one JSON `kind` or as objects carrying the id field, at the root or under `member`.", + ), }); export const environmentStateFields = { diff --git a/src/domain/analysisView/environmentStateWriteAddress.test.ts b/src/domain/analysisView/environmentStateWriteAddress.test.ts new file mode 100644 index 00000000000..674f3fbabb1 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteAddress.test.ts @@ -0,0 +1,232 @@ +import { describe, expect, it } from "vitest"; + +import { + timedCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { + BOOK_INIT_ROWS, + BOOK_NOT_FOUND, + FIRST_BOOK, + SECOND_BOOK, + environmentStateViewOf, + renamedBook, + type Book, +} from "../../../tests/fixtures/environmentStateWrites.js"; + +const planOf = (rows: readonly TimedCaptureRow[], tool: string) => { + const plan = environmentStateViewOf(timedCaptureEvidence(rows)).writes.find( + (candidate) => candidate.tool === tool, + ); + if (plan === undefined) throw new Error(`No write plan for ${tool}`); + return plan; +}; + +const RENAMED_AT_3 = renamedBook(FIRST_BOOK, "Renamed Book", 3); + +/** A book with an `archived` flag, which an item action sets. */ +const shelved = (entity: Book, archived: boolean) => ({ ...entity, archived }); + +const SHELVED_INIT_ROWS: readonly TimedCaptureRow[] = [ + [ + "GET", + "/api/books", + [shelved(FIRST_BOOK, false), shelved(SECOND_BOOK, false)], + ], + ["GET", "/api/books/1", shelved(FIRST_BOOK, false)], + ["GET", "/api/books/2", shelved(SECOND_BOOK, false)], +]; + +describe("bulk writes at a collection", () => { + it("serves a delete whose body names its rows, as the reads after it confirm", () => { + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ], + "delete_books", + ), + ).toMatchObject({ + effect: "delete", + target: "/api/books", + served: true, + address: { by: "elements", member: null }, + response: { ordinal: 3, shape: "entity", pointer: "/0" }, + checked_record_ordinals: [4, 5], + }); + }); + + it("updates each id a body's id array names with the members it shares", () => { + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["PATCH", "/api/books", "", 204, { ids: [1], name: "Renamed Book" }], + ["GET", "/api/books/1", RENAMED_AT_3], + ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], + ], + "patch_books", + ), + ).toMatchObject({ + effect: "update", + target: "/api/books", + served: true, + address: { by: "ids", member: "ids" }, + observation: { ordinal: 4, pointer: "" }, + checked_record_ordinals: [5], + }); + }); + + it("serves no bulk call whose response names its ids in a form serving cannot render for others", () => { + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", { deleted: [2] }, 200, { ids: [2] }], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ], + "delete_books", + ), + ).toMatchObject({ served: false, reason: "body-unusable" }); + }); + it("serves no bulk call whose recorded response counts the entities it wrote", () => { + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", { deleted: 1 }, 200, { ids: [2] }], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ], + "delete_books", + ), + ).toMatchObject({ served: false, reason: "body-unusable" }); + }); +}); + +describe("item actions", () => { + const ARCHIVED = shelved(FIRST_BOOK, true); + + it("serves an action once a call shows it sets, not toggles, what it changed", () => { + expect( + planOf( + [ + ...SHELVED_INIT_ROWS, + ["POST", "/api/books/1/archive", ARCHIVED], + ["GET", "/api/books/1", ARCHIVED], + ["POST", "/api/books/1/archive", ARCHIVED], + ["GET", "/api/books/1", ARCHIVED], + ], + "post_books_archive_by_id", + ), + ).toMatchObject({ + effect: "update", + target: "/api/books", + served: true, + address: { by: "action", segment: "archive" }, + rules: [{ field: "archived", rule: "set", value: true }], + // The second call finds the book archived already, so the read after it shows nothing of it. + checked_record_ordinals: [4], + }); + }); + + it("serves no action seen changing its field only once, which may toggle it", () => { + expect( + planOf( + [ + ...SHELVED_INIT_ROWS, + ["POST", "/api/books/1/star", ARCHIVED], + ["GET", "/api/books/1", ARCHIVED], + ["POST", "/api/books/1/star", "", 204], + ["GET", "/api/books", [shelved(SECOND_BOOK, false)]], + ], + "post_books_star_by_id", + ), + ).toMatchObject({ served: false, reason: "unconfirmed" }); + }); + + it("serves no action that only stamps a time, as a refresh does", () => { + const refreshed = { ...FIRST_BOOK, updated_at: "2026-10-17T18:00:03Z" }; + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["POST", "/api/books/1/publish", refreshed], + ["GET", "/api/books/1", refreshed], + ], + "post_books_publish_by_id", + ), + ).toMatchObject({ served: false }); + }); + + it("refuses an action whose call changed a nested object, which another write denormalised", () => { + const shelf = (name: string) => ({ + ...shelved(FIRST_BOOK, false), + shelf: { id: 4, name }, + }); + expect( + planOf( + [ + ["GET", "/api/books", [shelf("Old"), shelved(SECOND_BOOK, false)]], + ["GET", "/api/books/1", shelf("Old")], + ["GET", "/api/books/2", shelved(SECOND_BOOK, false)], + ["POST", "/api/books/1/archive", { ...shelf("New"), archived: true }], + ["GET", "/api/books/1", { ...shelf("New"), archived: true }], + ], + "post_books_archive_by_id", + ), + ).toMatchObject({ served: false, reason: "unexplained-change" }); + }); + + it("takes a POST answering another entity, a 201 or one sharing the path's id, for a sub-resource", () => { + const rows: TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + [ + "POST", + "/api/books/1/comments", + { id: 1, text: "Nice" }, + 201, + { + text: "Nice", + }, + ], + [ + "POST", + "/api/books/1/notes", + { id: 1, text: "Kept" }, + 200, + { + text: "Kept", + }, + ], + ]; + expect(planOf(rows, "post_books_comments_by_id")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + expect(planOf(rows, "post_books_notes_by_id")).toMatchObject({ + effect: "none", + reason: "no-state-target", + }); + }); + + it("leaves an action unmodelled where another write to the entity still awaits the read after it", () => { + const rows: TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + ["PATCH", "/api/books/1", RENAMED_AT_3, 200, { name: "Renamed Book" }], + ["POST", "/api/books/1/publish", "", 204], + ["GET", "/api/books/1", RENAMED_AT_3], + ]; + expect(planOf(rows, "patch_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [5], + }); + expect(planOf(rows, "post_books_publish_by_id")).toMatchObject({ + effect: "update", + served: false, + reason: "no-observation", + }); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteAddress.ts b/src/domain/analysisView/environmentStateWriteAddress.ts new file mode 100644 index 00000000000..ed24687d64b --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteAddress.ts @@ -0,0 +1,345 @@ +import type { JsonValue } from "../jsonValue.js"; +import { + at, + isObject, + isParam, + locateItem, + normalizedPath, + scalarText, + segmentsOf, + type JsonObject, + type StateRecordFacts, + type StateToolFacts, + type StateView, +} from "./environmentStateRules.js"; +import { entityTarget, succeeded } from "./environmentStateWriteChecks.js"; +import { + pathValuesOf, + type BodyAddress, + type StateWritePlan, + type WriteAddress, + type WriteEffect, +} from "./environmentStateWriteRules.js"; + +/** Last segments of a POST at a collection that deletes the entities its body names. */ +const BULK_DELETE_SEGMENTS = new Set(["delete", "remove", "destroy"]); + +/** What classifying an addressed write reads: the state types, their id fields and item views, and the tool's recorded calls. */ +export interface AddressFacts { + readonly types: ReadonlySet; + readonly idField: (type: string) => string | undefined; + /** Where item reads of a type show its entity, and the fields each always shows. */ + readonly itemViews: (type: string) => readonly { + readonly pointer: string; + readonly required: readonly string[]; + }[]; + /** The tool's successful calls. */ + readonly calls: readonly StateRecordFacts[]; + readonly withBody: ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ) => T; + readonly requestBody: (ordinal: number) => JsonValue | undefined; + readonly emptyResponse: (ordinal: number) => boolean; +} + +/** An addressed write's effect, the type it writes and how its calls name the entities. */ +export interface AddressedWrite { + readonly effect: WriteEffect; + readonly target: string; + readonly address: WriteAddress; +} + +const sameSegment = (left: string, right: string): boolean => + left.toLowerCase() === right.toLowerCase(); + +/** Whether a literal segment names a collection: a state type ends in it. */ +const namesCollection = ( + segment: string, + types: ReadonlySet, +): boolean => + [...types].some((type) => { + const last = segmentsOf(type).at(-1); + return last !== undefined && sameSegment(last, segment); + }); + +/** + * A POST, PUT or PATCH to `/{type}/{id}/{segment}` that changes the entity it names: the segment + * names no collection, and every successful call answered nothing or the entity, where an item + * read of its type shows it and with every field that read always shows. A call that answers + * another entity, or a 201, made a sub-resource. + */ +export const itemAction = ( + tool: Pick, + facts: AddressFacts, +): AddressedWrite | undefined => { + if (!["POST", "PUT", "PATCH"].includes(tool.method)) return undefined; + const segments = segmentsOf(tool.path_template); + const [item, segment] = segments.slice(-2); + if ( + segments.length < 3 || + item === undefined || + segment === undefined || + !isParam(item) || + isParam(segment) || + BULK_DELETE_SEGMENTS.has(segment.toLowerCase()) || + namesCollection(segment, facts.types) + ) + return undefined; + const target = normalizedPath(`/${segments.slice(0, -2).join("/")}`); + const idField = facts.idField(target); + if ( + !facts.types.has(target) || + idField === undefined || + facts.calls.length === 0 + ) + return undefined; + const views = facts.itemViews(target); + const showsEntity = (record: StateRecordFacts): boolean => { + const id = pathValuesOf(tool.path_template, record.path)?.get( + item.slice(1, -1), + ); + if (id === undefined || record.status === 201) return false; + if (facts.emptyResponse(record.ordinal)) return true; + return facts.withBody(record.ordinal, (body) => { + if (body === undefined || body === null) return true; + const located = locateItem(body, id); + const object = + located === undefined ? undefined : at(body, located.pointer); + return ( + located?.keys.includes(idField) === true && + isObject(object) && + views.some( + (view) => + (view.pointer === located.pointer || located.pointer === "") && + view.required.every((field) => Object.hasOwn(object, field)), + ) + ); + }); + }; + return facts.calls.every(showsEntity) + ? { effect: "update", target, address: { by: "action", segment } } + : undefined; +}; + +/** The state type a collection path writes to: the type at the path, or at the path with its last segment singular or plural. */ +const collectionType = ( + segments: readonly string[], + types: ReadonlySet, +): string | undefined => { + const path = normalizedPath(`/${segments.join("/")}`); + if (types.has(path)) return path; + const last = segments.at(-1); + if (last === undefined || isParam(last)) return undefined; + const other = last.endsWith("s") ? last.slice(0, -1) : `${last}s`; + const counterpart = normalizedPath( + `/${[...segments.slice(0, -1), other].join("/")}`, + ); + return other.length > 0 && types.has(counterpart) ? counterpart : undefined; +}; + +/** How a body names entities by their ids, if it does: an array of ids, or of objects carrying the id field, at the root or as the one array member. */ +export const addressOf = ( + body: JsonValue | undefined, + idField: string, +): BodyAddress | undefined => { + const form = ( + value: JsonValue | undefined, + member: string | null, + ): BodyAddress | undefined => { + if (!Array.isArray(value) || value.length === 0) return undefined; + const kinds = new Set(value.map((entry) => typeof entry)); + const [kind] = kinds; + if ( + kinds.size === 1 && + (kind === "string" || kind === "number") && + (member === null || /ids?$/i.test(member)) + ) + return { by: "ids", member, kind }; + return value.every( + (entry) => isObject(entry) && scalarText(entry[idField]) !== undefined, + ) + ? { by: "elements", member } + : undefined; + }; + if (Array.isArray(body)) return form(body, null); + if (!isObject(body)) return undefined; + const arrays = Object.entries(body).filter(([, value]) => + Array.isArray(value), + ); + if (arrays.length !== 1) return undefined; + const [[member, value]] = arrays as [[string, JsonValue]]; + const found = form(value, member); + // Shared members apply to every id an array names; objects carry their own. + return found?.by === "elements" && Object.keys(body).length > 1 + ? undefined + : found; +}; + +/** + * A DELETE, PUT or PATCH at a type's collection, or a POST to its `delete` segment, whose every + * successful call names held entities by id in its body, the same way. + */ +export const bulkWrite = ( + tool: Pick, + facts: AddressFacts, +): AddressedWrite | undefined => { + const segments = segmentsOf(tool.path_template); + const last = segments.at(-1) ?? ""; + const verb = tool.method === "POST" && BULK_DELETE_SEGMENTS.has(last); + const effect: WriteEffect | undefined = + tool.method === "DELETE" || verb + ? "delete" + : ["PUT", "PATCH"].includes(tool.method) + ? "update" + : undefined; + if (effect === undefined) return undefined; + const target = collectionType( + verb ? segments.slice(0, -1) : segments, + facts.types, + ); + const idField = target === undefined ? undefined : facts.idField(target); + if (target === undefined || idField === undefined) return undefined; + const forms = facts.calls.map((record) => + addressOf(facts.requestBody(record.ordinal), idField), + ); + const [first] = forms; + if ( + first === undefined || + forms.some((form) => JSON.stringify(form) !== JSON.stringify(first)) + ) + return undefined; + // An id array names entities only; an update needs members to apply. + if (effect === "update" && first.by === "ids" && first.member === null) + return undefined; + return { effect, target, address: first }; +}; + +/** One entity a bulk call names and the members it writes to it. */ +export interface NamedEntity { + readonly id: string; + readonly body: JsonObject | undefined; +} + +/** The entities a bulk call's body names, each once, with the members each gets; undefined when the body does not take the address's form. */ +export const namedEntities = ( + address: BodyAddress, + body: JsonValue | undefined, + idField: string, +): NamedEntity[] | undefined => { + const found = addressOf(body, idField); + if ( + found === undefined || + found.by !== address.by || + found.member !== address.member + ) + return undefined; + const entries = ( + address.member === null ? body : (body as JsonObject)[address.member] + ) as JsonValue[]; + const shared = + address.member === null || !isObject(body) + ? undefined + : Object.fromEntries( + Object.entries(body).filter(([member]) => member !== address.member), + ); + const named = entries.map((entry) => + address.by === "ids" + ? { id: scalarText(entry)!, body: shared } + : { id: scalarText((entry as JsonObject)[idField])!, body: entry }, + ) as NamedEntity[]; + return new Set(named.map(({ id }) => id)).size === named.length + ? named + : undefined; +}; + +/** The collection path a bulk call writes in: its path, without a delete segment, with the type's spelling of the last segment. */ +export const bulkCollection = (target: string, path: string): string => { + const written = segmentsOf(path); + const depth = segmentsOf(target).length; + const collection = written.slice(0, depth); + const spelled = segmentsOf(target).at(-1)!; + if (!isParam(spelled)) collection[depth - 1] = spelled; + return `/${collection.join("/")}`; +}; + +/** An item action call's path without its action segment: the item path its entity is read under. */ +export const actionItemPath = (path: string): string => + `/${segmentsOf(path).slice(0, -1).join("/")}`; + +/** An item action or a bulk write at a collection, for a tool whose path names no target. */ +export const addressedWrite = ( + tool: StateToolFacts, + input: Pick & { + readonly views: Iterable; + readonly records: readonly StateRecordFacts[]; + readonly io: Pick< + AddressFacts, + "withBody" | "requestBody" | "emptyResponse" + >; + }, +): AddressedWrite | undefined => { + const ordinals = new Set(tool.record_ordinals); + const views = [...input.views]; + const facts: AddressFacts = { + types: input.types, + idField: input.idField, + itemViews: (type) => + views.flatMap((view) => + view.shape === "item" && view.type === type + ? [{ pointer: view.pointer, required: view.required_fields }] + : [], + ), + calls: input.records.filter( + (record) => ordinals.has(record.ordinal) && succeeded(record), + ), + withBody: input.io.withBody, + requestBody: input.io.requestBody, + emptyResponse: input.io.emptyResponse, + }; + return itemAction(tool, facts) ?? bulkWrite(tool, facts); +}; + +/** + * What an update's observation must show, and whether it may be a later read: a bulk call's + * response may name its entities only, so it must show what the call sent; an item action never + * takes a read another write to the entity still needs as its check. + */ +export const observationNeeds = ( + plan: Pick, + named: { + readonly type: string; + readonly idField: string; + readonly collection: string; + readonly id: string; + readonly body: JsonObject | undefined; + }, + pending: (target: string) => boolean, +): { + readonly required: string[]; + readonly borrow: boolean; + readonly action: boolean; +} => { + const { address } = plan; + const clocks = plan.rules.flatMap((rule) => + rule.rule === "clock" ? [rule.field] : [], + ); + if (address === undefined) + return { required: clocks, borrow: true, action: false }; + if (address.by !== "action") + return { + required: [ + ...clocks, + ...Object.keys(named.body ?? {}).filter( + (member) => member !== named.idField, + ), + ], + borrow: true, + action: false, + }; + return { + required: clocks, + borrow: !pending(entityTarget(named.type, named.collection, named.id)), + action: true, + }; +}; diff --git a/src/domain/analysisView/environmentStateWriteApply.ts b/src/domain/analysisView/environmentStateWriteApply.ts index 58b84a42cb1..aa53446bd56 100644 --- a/src/domain/analysisView/environmentStateWriteApply.ts +++ b/src/domain/analysisView/environmentStateWriteApply.ts @@ -297,9 +297,20 @@ const regenerated = ( { rule: "clock" | "nested-clock" | "held-clock" | "unique" } > => REGENERATED.has(rule.rule); +/** The value an echo or constant rule writes for a sent member, or a set rule on every call; undefined when it writes none. */ +const statedValue = ( + rule: FieldRule, + sent: JsonObject, +): JsonValue | undefined => { + if (rule.rule === "set") return rule.value; + if (rule.rule !== "echo" && rule.rule !== "constant") return undefined; + if (!Object.hasOwn(sent, rule.field)) return undefined; + return rule.rule === "echo" ? sent[rule.field] : rule.value; +}; + /** The fields of an updated entity: sent echoed members, the constants the plan recorded, generated and derived changes. */ export const updatedFields = ( - plan: Pick, + plan: Pick, entity: { readonly before: JsonObject; readonly observed: JsonObject }, call: WriteCall & { readonly id: string }, generate: GenerateValue, @@ -316,17 +327,16 @@ export const updatedFields = ( const members = Object.keys(sent).filter( (member) => member !== plan.body?.identity, ); - if (members.length === 0) + // An item action names its change in its path, so it may send nothing. + if (members.length === 0 && plan.address?.by !== "action") return err( `The call sends none of the members an update applies (${bodyContract(plan.body)}).`, ); const written: JsonObject = { ...before }; for (const rule of plan.rules) { - if (rule.rule === "echo" || rule.rule === "constant") { - if (!Object.hasOwn(sent, rule.field)) continue; - written[rule.field] = - rule.rule === "echo" ? sent[rule.field]! : rule.value; - } else if (rule.rule === "increment") { + const stated = statedValue(rule, sent); + if (stated !== undefined) written[rule.field] = stated; + else if (rule.rule === "increment") { const was = integerOf(before[rule.field]); if (was !== undefined) written[rule.field] = spelledLike(before[rule.field]!, was + 1); diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts new file mode 100644 index 00000000000..82ffe0c1ee7 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -0,0 +1,111 @@ +import type { JsonValue } from "../jsonValue.js"; +import { + at, + isObject, + locateItem, + scalarText, +} from "./environmentStateRules.js"; +import { + bulkCollection, + namedEntities, + type NamedEntity, +} from "./environmentStateWriteAddress.js"; +import { itemTarget } from "./environmentStateWriteChecks.js"; +import { deleteEntity } from "./environmentStateWriteDelete.js"; +import { + built, + fail, + refuse, + updateEntity, + UNKNOWN, + type EffectContext, + type EffectResult, + type WriteDraft, + type WriteStep, +} from "./environmentStateWriteEffects.js"; +import type { WriteResponse } from "./environmentStateWriteRules.js"; + +/** Whether any scalar in a body passes the test. */ +const holds = ( + body: JsonValue | undefined, + test: (scalar: JsonValue) => boolean, +): boolean => { + const pending: JsonValue[] = body === undefined ? [] : [body]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + if (Array.isArray(next)) for (const child of next) pending.push(child); + else if (isObject(next)) + for (const child of Object.values(next)) pending.push(child); + else if (test(next)) return true; + } + return false; +}; + +/** + * Whether serving can answer a bulk call with this response for any ids: no body, one that names + * none of them and counts nothing it wrote, or an array with one element per named entity, each + * showing its id where the first does. + */ +export const bulkResponseFits = ( + response: WriteResponse, + body: JsonValue | undefined, + named: readonly NamedEntity[], +): boolean => { + if (response.shape === "empty") return true; + const ids = new Set(named.map(({ id }) => id)); + if (response.shape === "recorded") + return !holds( + body, + (scalar) => ids.has(scalarText(scalar) ?? "") || scalar === named.length, + ); + if (response.pointer !== "/0" || !Array.isArray(body)) return false; + return ( + body.length === named.length && + named.every(({ id }, index) => { + const element = body[index]; + if (response.shape === "identity") return scalarText(element) === id; + const located = + element === undefined ? undefined : locateItem(element, id); + return located?.pointer === "" && isObject(at(element!, "")); + }) + ); +}; + +/** Apply a recorded bulk call to each entity its body names; one it names without holding leaves the call unmodelled there. */ +export const applyBulk = ( + context: EffectContext, + draft: WriteDraft, + step: WriteStep, +): EffectResult[] => { + const type = draft.plan.target!; + const { address } = draft.plan; + const body = context.io.requestBody(step.record.ordinal); + const named = + address === undefined || address.by === "action" + ? undefined + : namedEntities(address, body, context.idField(type)); + if (named === undefined) { + fail(draft, step, "body-unusable"); + return [UNKNOWN]; + } + const collection = bulkCollection(type, step.record.path); + const wasBuilt = built(draft); + const results = named.map(({ id, body: members }) => { + const target = itemTarget(context.state, type, { + path: `${collection}/${encodeURIComponent(id)}`, + }); + return draft.plan.effect === "delete" + ? deleteEntity(context, draft, step, target) + : updateEntity(context, draft, step, { ...target, body: members }); + }); + // The plan's response is the exemplar's; serving answers any ids with it only in a shape it can render for them. + const { response } = draft.plan; + if ( + !wasBuilt && + response !== null && + !context.io.withBody(step.record.ordinal, (recorded) => + bulkResponseFits(response, recorded, named), + ) + ) + refuse(draft, step, "body-unusable"); + return results; +}; diff --git a/src/domain/analysisView/environmentStateWriteCalls.ts b/src/domain/analysisView/environmentStateWriteCalls.ts index 531d36ebbb5..ae7757d5ce6 100644 --- a/src/domain/analysisView/environmentStateWriteCalls.ts +++ b/src/domain/analysisView/environmentStateWriteCalls.ts @@ -1,3 +1,4 @@ +import { jsonTextCodeUnits } from "../jsonSerialization.js"; import type { JsonValue } from "../jsonValue.js"; import { same, type JsonObject } from "./environmentStateRules.js"; import { storedKinds } from "./environmentStateWriteApply.js"; @@ -14,7 +15,8 @@ export const unsentChange = (rule: FieldRule): boolean => rule.rule === "increment" || rule.rule === "slug" || rule.rule === "stamp" || - rule.rule === "derived"; + rule.rule === "derived" || + rule.rule === "set"; /** Whether serving gives a rule's field a new value on every call, so no call may have kept it. */ export const regenerates = (rule: FieldRule): boolean => @@ -44,6 +46,20 @@ export const disagreesWithCall = ( (regenerates(rule) && call.kept.includes(rule.field)), ); +/** The fields a call found already at the value a set rule gives them: the action sets them rather than toggling them. */ +export const steadyFields = ( + rules: readonly FieldRule[], + before: JsonObject, + after: JsonObject, +): string[] => + rules.flatMap((rule) => + rule.rule === "set" && + same(before[rule.field], rule.value) && + same(after[rule.field], rule.value) + ? [rule.field] + : [], + ); + /** A call's scalar members by name, as much of it as later rules are checked against. */ export const scalars = (object: JsonObject): Map => new Map( @@ -81,6 +97,7 @@ export const contradictsEarlierCalls = ( const value = shown.get(rule.field); if (value === undefined) return false; if (rule.rule === "increment") return integerOf(value) !== undefined; + if (rule.rule === "set") return !same(value, rule.value); // Serving stamps a clock on every call, so a field an earlier call kept contradicts it. if (rule.rule === "clock") return true; if (rule.rule === "stamp") return !same(value, rule.value); @@ -144,3 +161,63 @@ export const conflictsWithPlan = ( }) ); }; + +/** A modelled update's result: a later read that also shows an unmodelled change checks only the members it sent. */ +export const appliedUpdate = ( + plan: Pick, + at: { + readonly targets: string[]; + readonly target: { + readonly type: string; + readonly collection: string; + readonly id: string; + }; + }, + before: JsonObject, + call: { readonly written: JsonObject; readonly body: JsonObject }, +) => { + const { written, body } = call; + const sent = Object.keys(body).filter( + (member) => member !== plan.body?.identity, + ); + const derived = Object.keys(written).filter( + (field) => + !Object.hasOwn(before, field) || !same(written[field], before[field]), + ); + const changed = { + fields: [...new Set([...sent, ...derived])], + accumulated: plan.rules.flatMap((rule) => + rule.rule === "increment" ? [rule.field] : [], + ), + }; + return { + kind: "applied" as const, + targets: at.targets, + entity: at.target, + fields: sent, + changed, + }; +}; + +/** Keep what a modelled update call showed, which later calls' rules must reproduce, and the fields it found already set. */ +export const rememberCall = ( + retain: (bytes: number) => void, + draft: { + readonly plan: { readonly rules: readonly FieldRule[] }; + readonly updates: UpdateCall[]; + readonly steady: Set; + }, + call: { + readonly before: JsonObject; + readonly after: JsonObject; + readonly sent: JsonObject; + readonly kept: readonly string[]; + }, +): void => { + const { kept } = call; + const facts = { shown: scalars(call.after), sent: scalars(call.sent), kept }; + retain(64 + jsonTextCodeUnits([...facts.shown, ...facts.sent, kept]) * 2); + draft.updates.push(facts); + for (const field of steadyFields(draft.plan.rules, call.before, call.after)) + draft.steady.add(field); +}; diff --git a/src/domain/analysisView/environmentStateWriteDelete.ts b/src/domain/analysisView/environmentStateWriteDelete.ts new file mode 100644 index 00000000000..7db2a285dd3 --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteDelete.ts @@ -0,0 +1,65 @@ +import { + collectionTarget, + entityTarget, + itemTarget, +} from "./environmentStateWriteChecks.js"; +import { + built, + fail, + UNKNOWN, + type EffectContext, + type EffectResult, + type WriteDraft, + type WriteStep, +} from "./environmentStateWriteEffects.js"; +import { responseShapeOf } from "./environmentStateWriteExplain.js"; + +/** Apply a recorded delete: the held entity leaves its collection. */ +export const applyDelete = ( + context: EffectContext, + draft: WriteDraft, + step: WriteStep, +): EffectResult => + deleteEntity( + context, + draft, + step, + itemTarget(context.state, draft.plan.target!, step.record), + ); + +/** Remove the held entity a call names. */ +export const deleteEntity = ( + context: EffectContext, + draft: WriteDraft, + step: WriteStep, + named: { readonly collection: string; readonly id: string }, +): EffectResult => { + const type = draft.plan.target!; + const { collection, id } = named; + const entity = context.state.entity(type, collection, id); + if (entity === undefined) { + fail(draft, step, "no-observation"); + return UNKNOWN; + } + const { ordinal } = step.record; + if (!built(draft) && !step.observeOnly) + Object.assign(draft.plan, { + exemplar_ordinal: ordinal, + response: context.io.withBody(ordinal, (body) => + responseShapeOf(ordinal, body, context.io.emptyResponse(ordinal), { + idField: context.idField(type), + id, + }), + ), + }); + context.state.remove(entity); + const targets = [ + entityTarget(type, collection, id), + collectionTarget(type, collection), + ]; + return { + kind: step.observeOnly ? "observed" : "applied", + targets, + entity: { type, collection, id }, + }; +}; diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index abfccc1e311..b833fce1897 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -5,7 +5,6 @@ import { isObject, locateItem, at, - same, type JsonObject, type StateDocument, type StateEntity, @@ -30,7 +29,8 @@ import { contradictsEarlierCalls, disagreesWithCall, keptFields, - scalars, + rememberCall, + appliedUpdate, type UpdateCall, conflictsWithPlan, refinedBody, @@ -47,6 +47,10 @@ import { restampedFields, } from "./environmentStateWriteStamps.js"; import { readClock } from "./environmentStateWriteValues.js"; +import { + actionItemPath, + observationNeeds, +} from "./environmentStateWriteAddress.js"; import { pathValuesOf, type FieldRule, @@ -74,6 +78,8 @@ export interface WriteDraft { readonly sequences: Map; /** The collection a create writes into when its own path names no state type: the one its returned id was read under. */ readonly linked?: string | undefined; + /** Fields an item action's call found already at the value it sets them to. */ + readonly steady: Set; } /** A write observation plus the fields its selected read view actually covers, if any. */ @@ -126,6 +132,8 @@ export interface EffectContext { readonly initialDocument: (tool: string) => StateDocument | undefined; /** The entities of a type the initial state held, whose values a sequence never reuses. */ readonly startedWith: (type: string) => readonly StateEntity[]; + /** Whether another tool's modelled write to the target awaits a check, which a later read must still make. */ + readonly pending: (target: string) => boolean; } /** One recorded write: the record, its timeline index, its tool, and whether its plan only takes the recorded outcome. */ @@ -266,8 +274,12 @@ const updatedObservation = ( readonly collection: string; readonly id: string; }, - required: readonly string[], + observing: { + readonly required: readonly string[]; + readonly borrow: boolean; + }, ): UpdateObservation | undefined => { + const { required, borrow } = observing; const own = context.io.withBody( step.record.ordinal, (body): Observed | undefined => { @@ -290,6 +302,7 @@ const updatedObservation = ( required.every((field) => Object.hasOwn(own.object, field)) ) return own; + if (!borrow) return undefined; const later = laterObservation(searchFrom(context, step), { ...itemReads(context, entity), // With an answer or without one, only a read whose view shows every learned clock shows what this call stamped. @@ -341,6 +354,25 @@ export const retainFixed = ( if (fixed.length > 0) context.io.retain(64 + jsonTextCodeUnits(fixed) * 2); }; +/** An update's targets, and its recorded outcome: the entity takes what its observation shows, attributed to no tool. */ +const outcomes = ( + context: EffectContext, + entity: StateEntity, + shown: JsonObject, +) => { + const { type, collection, id } = entity; + const targets = [ + entityTarget(type, collection, id), + collectionTarget(type, collection), + ]; + const target = { type, collection, id }; + const recorded = (): EffectResult => { + context.state.put(updatedEntity(entity, { ...entity.fields, ...shown })); + return { kind: "observed", targets, entity: target }; + }; + return { targets, target, recorded }; +}; + /** Build an update plan from its exemplar, or add what a later call showed. */ const buildUpdate = ( context: EffectContext, @@ -388,11 +420,39 @@ export const applyUpdate = ( context: EffectContext, draft: WriteDraft, step: WriteStep, +): EffectResult => { + const action = draft.plan.address?.by === "action"; + // The entity as serving names it. + const named = itemTarget(context.state, draft.plan.target!, { + path: action ? actionItemPath(step.record.path) : step.record.path, + }); + // An item action names its change in its path, so it may send no body. + const body = + action && context.io.requestBody(step.record.ordinal) === undefined + ? {} + : requestObject(context, step.record, draft); + return updateEntity(context, draft, step, { ...named, body }); +}; + +/** Apply a recorded update to the held entity a call names, with the members it wrote to that entity. */ +export const updateEntity = ( + context: EffectContext, + draft: WriteDraft, + step: WriteStep, + named: { + readonly collection: string; + readonly id: string; + readonly body: JsonObject | undefined; + }, ): EffectResult => { const type = draft.plan.target!; const idField = context.idField(type); - // The entity as serving names it. - const { collection, id } = itemTarget(context.state, type, step.record); + const { collection, id, body } = named; + const needs = observationNeeds( + draft.plan, + { ...named, type, idField }, + context.pending, + ); const entity = context.state.entity(type, collection, id); const after = entity === undefined @@ -401,26 +461,13 @@ export const applyUpdate = ( context, step, { type, idField, collection, id }, - draft.plan.rules.flatMap((rule) => - rule.rule === "clock" ? [rule.field] : [], - ), + needs, ); if (entity === undefined || after === undefined) { fail(draft, step, "no-observation"); return UNKNOWN; } - const targets = [ - entityTarget(type, collection, id), - collectionTarget(type, collection), - ]; - const target = { type, collection, id }; - const recorded = (): EffectResult => { - context.state.put( - updatedEntity(entity, { ...entity.fields, ...after.object }), - ); - return { kind: "observed", targets, entity: target }; - }; - const body = requestObject(context, step.record, draft); + const { targets, target, recorded } = outcomes(context, entity, after.object); if (step.observeOnly || body === undefined) { fail(draft, step, "body-unusable"); return recorded(); @@ -438,6 +485,7 @@ export const applyUpdate = ( ...(after.readFields === undefined ? {} : { readFields: after.readFields }), others: otherFields(context.state.ofType(type), { collection, id }), shown: shownBefore(context.viewOf, entity, after.ordinal), + action: needs.action, }); if (explained.unexplained.length > 0 && !unknown) { refuse(draft, step, "unexplained-change"); @@ -476,29 +524,18 @@ export const applyUpdate = ( if (!written.ok || (disagrees && !unknown)) refuse(draft, step, "unexplained-change"); if (!written.ok || disagrees || unknown) return recorded(); - const facts = { shown: scalars(after.object), sent: scalars(body), kept }; - context.io.retain( - 64 + jsonTextCodeUnits([...facts.shown, ...facts.sent, kept]) * 2, - ); - draft.updates.push(facts); + rememberCall(context.io.retain, draft, { + before: entity.fields, + after: after.object, + sent: body, + kept, + }); context.io.retain(64 + jsonTextCodeUnits(written.value) * 2); context.state.put(updatedEntity(entity, written.value)); - // A later read that also shows an unmodelled change checks only the members this call sent. - const sent = Object.keys(body).filter( - (member) => member !== draft.plan.body?.identity, - ); - const derived = Object.keys(written.value).filter( - (field) => - !Object.hasOwn(entity.fields, field) || - !same(written.value[field], entity.fields[field]), - ); - const changed = { - fields: [...new Set([...sent, ...derived])], - accumulated: draft.plan.rules.flatMap((rule) => - rule.rule === "increment" ? [rule.field] : [], - ), - }; - return { kind: "applied", targets, entity: target, fields: sent, changed }; + return appliedUpdate(draft.plan, { targets, target }, entity.fields, { + written: written.value, + body, + }); }; /** Serving regenerates a learned clock on every update, so recorded calls must advance it. */ @@ -534,39 +571,3 @@ const contradictsPlan = ( contradictsEarlierCalls(draft, explained.rules) || contradictsGeneratedClock(before, after, draft.plan.rules, explained.rules) || conflictsWithPlan(draft.plan, explained); - -/** Apply a recorded delete: the held entity leaves its collection. */ -export const applyDelete = ( - context: EffectContext, - draft: WriteDraft, - step: WriteStep, -): EffectResult => { - const type = draft.plan.target!; - const { collection, id } = itemTarget(context.state, type, step.record); - const entity = context.state.entity(type, collection, id); - if (entity === undefined) { - fail(draft, step, "no-observation"); - return UNKNOWN; - } - const { ordinal } = step.record; - if (!built(draft) && !step.observeOnly) - Object.assign(draft.plan, { - exemplar_ordinal: ordinal, - response: context.io.withBody(ordinal, (body) => - responseShapeOf(ordinal, body, context.io.emptyResponse(ordinal), { - idField: context.idField(type), - id, - }), - ), - }); - context.state.remove(entity); - const targets = [ - entityTarget(type, collection, id), - collectionTarget(type, collection), - ]; - return { - kind: step.observeOnly ? "observed" : "applied", - targets, - entity: { type, collection, id }, - }; -}; diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index c23bdccc9f1..feb396666eb 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -297,6 +297,8 @@ export interface UpdateEvidence { readonly others: readonly JsonObject[]; /** The fields of the observing read's view when that view showed the entity before, so one the entity lacked was added. */ readonly shown?: readonly string[]; + /** An item action, whose unsent changes take the values it showed. */ + readonly action?: boolean; } /** The rule a field the update changed without sending follows, if any; `slugs` maps each echoed member's slug to the first such member. */ @@ -325,7 +327,24 @@ const changeRule = ( const was = integerOf(before); if (was !== undefined && integerOf(after) === was + 1) return { field, rule: "increment" }; - return stampRule(evidence, field) ?? derivedRule(evidence, field); + return ( + stampRule(evidence, field) ?? + derivedRule(evidence, field) ?? + actionRule(evidence, field) + ); +}; + +/** An item action sets a scalar it names; a changed object, list or instant is another write's doing or a regenerated value. */ +const actionRule = ( + evidence: UpdateEvidence, + field: string, +): FieldRule | undefined => { + const after = evidence.after[field]!; + return evidence.action === true && + (after === null || typeof after !== "object") && + readClock(after) === undefined + ? { field, rule: "set", value: after } + : undefined; }; /** A sent clock the call left as it was, stored in whole seconds and naming the second the call ran in: the application stamps it anew, and the client sent back the one it read. */ diff --git a/src/domain/analysisView/environmentStateWriteRules.ts b/src/domain/analysisView/environmentStateWriteRules.ts index dc685b5b79e..4b70317bece 100644 --- a/src/domain/analysisView/environmentStateWriteRules.ts +++ b/src/domain/analysisView/environmentStateWriteRules.ts @@ -90,6 +90,12 @@ export type FieldRule = readonly value: JsonValue; readonly from: JsonValue; readonly member: string; + } + /** An item action stores `value` on every call, sent or not. */ + | { + readonly field: string; + readonly rule: "set"; + readonly value: JsonValue; }; /** Where a create places its entity in its collection's order. */ @@ -117,6 +123,23 @@ export interface WriteBody { readonly envelope?: string | undefined; } +/** + * How a write names its entities when its path does not end in one: an action segment after the + * item's id, or ids in the body of a write at the collection, as an array of one JSON kind (`ids`) + * or as objects carrying the type's id field (`elements`), at the body's root or under one member. + */ +export type WriteAddress = + | { readonly by: "action"; readonly segment: string } + | { + readonly by: "ids"; + readonly member: string | null; + readonly kind: "number" | "string"; + } + | { readonly by: "elements"; readonly member: string | null }; + +/** How a bulk write names its entities in its body. */ +export type BodyAddress = Exclude; + /** What a write answers: the written entity or its identity rendered into a recorded body, no body, or the recorded body. */ export interface WriteResponse { readonly ordinal: number; @@ -147,6 +170,8 @@ export interface StateWritePlan { readonly merge: "merge" | "replace" | null; readonly checked_record_ordinals: number[]; readonly contradicted_by: number | null; + /** Set when the call's path does not end in the entity's id. */ + readonly address?: WriteAddress | undefined; } /** The tool facts classification reads. */ diff --git a/src/domain/analysisView/environmentStateWriteVerdict.ts b/src/domain/analysisView/environmentStateWriteVerdict.ts index d0d7c1fb613..32f903ed388 100644 --- a/src/domain/analysisView/environmentStateWriteVerdict.ts +++ b/src/domain/analysisView/environmentStateWriteVerdict.ts @@ -38,6 +38,15 @@ const renders = ( ); }; +/** Whether an item action sets something, and a call showed each field it sets already at that value, so the action sets rather than toggles it. */ +const steady = (plan: StateWritePlan, draft: WriteDraft): boolean => { + if (plan.address?.by !== "action") return true; + const set = plan.rules.flatMap((rule) => + rule.rule === "set" ? [rule.field] : [], + ); + return set.length > 0 && set.every((field) => draft.steady.has(field)); +}; + /** A replayed write's plan, served only when it was called, nothing contradicted it, a read confirmed it and its answers can render. */ export const writeVerdict = ( draft: WriteDraft, @@ -50,7 +59,8 @@ export const writeVerdict = ( plan.reason = "contradicted"; plan.contradicted_by = draft.contradictedBy; } else if (draft.sideEffect) plan.reason = "side-effect"; - else if (draft.confirmed.length === 0) plan.reason = "unconfirmed"; + else if (draft.confirmed.length === 0 || !steady(plan, draft)) + plan.reason = "unconfirmed"; else if (!renders(plan, input)) plan.reason = "incomplete-entities"; } plan.served = plan.reason === null; diff --git a/tests/boundary/mcp/toolSchemaValidity.test.ts b/tests/boundary/mcp/toolSchemaValidity.test.ts index b2b1553878e..2f1c052f97a 100644 --- a/tests/boundary/mcp/toolSchemaValidity.test.ts +++ b/tests/boundary/mcp/toolSchemaValidity.test.ts @@ -14,6 +14,13 @@ import { booleanLiteralSchemaError, } from "../../fixtures/mcpClientSchemaConstraints.js"; import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js"; +import { servedCatalog } from "../../../src/application/environment/environmentState.js"; +import { servedFrom } from "../../fixtures/environmentStateServing.js"; +import { + BOOK_INIT_ROWS, + BOOK_NOT_FOUND, + FIRST_BOOK, +} from "../../fixtures/environmentStateWrites.js"; interface ToolSchemas { readonly name: string; @@ -433,6 +440,28 @@ const advertiseAndEnforceProcessEnvironmentKeyConstraint = }; describe("MCP JSON Schema validity", () => { + it("advertises served environment catalogs, bulk bodies included, in schemas clients accept", () => { + const served = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + const catalog = servedCatalog(served.source, served.state, "books"); + if (!catalog.ok) throw catalog.error; + expect( + catalog.value.tools.some((tool) => tool.name === "delete_books"), + ).toBe(true); + expect( + schemaErrors( + catalog.value.tools.map((tool) => ({ + name: tool.name, + inputSchema: tool.inputSchema as unknown as Record, + })), + ), + ).toEqual([]); + }); + it("preserves empty-array validation in the advertised representation", () => { const schema = z.toJSONSchema(emptyArraySchema); const ajv = new Ajv2020({ strict: false, validateFormats: false }); From 147ff45d7486dd12fd0ca605c29eba1d541e5a7a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:17:55 -0700 Subject: [PATCH 29/68] fix(environment): decide late item lines against the lines left, charge replay keys and bisect rewrite cuts - Item lines first recorded after the initial reads are decided once variants are dropped, against the lines left: a new shaping parameter showing other members, or a selection of some fields leaving members out, replays. - Each replay key is charged against the budget before it is kept. - A rewrite span's earliest write is found by bisection over the writes. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 7 +- .../agent-environments/state-view/spec.md | 8 +- .../EnvironmentStateExtraction.ts | 79 ++++++++----------- .../analysisView/environmentStateGate.ts | 10 +++ .../analysisView/environmentStateRewrites.ts | 25 +++++- .../analysisView/environmentStateVariants.ts | 65 ++++++++++++--- .../analysisView/environmentStateView.test.ts | 63 ++++++++++++++- .../environmentStateWrites.test.ts | 42 ++++++++++ 8 files changed, 232 insertions(+), 67 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 3283f83f664..849d6960294 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -48,9 +48,10 @@ its cause in the recordings and the code. The five largest shared causes: and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. An item line first recorded - after the initial window is a variant too when it names a new shaping parameter and its object carries or lacks - members the planned lines' do not, and an item only a replayed line showed, which the state never started with, - answers with its own recording. + after the initial window is a variant too, judged against the lines left once variants are dropped: when it names a + new shaping parameter and its object carries or lacks members theirs do not, or selects some fields and leaves out + members they always show, and an item only a replayed line showed, which the state never started with, answers with + its own recording. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index d0a992ae3be..94416f3465d 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -46,9 +46,11 @@ later increments. Beside a line showing whole entities, a list line asking for some fields only (a projection value other than `*`, which asks for all) is listed there too, and proves no identity or membership. So is an item line first recorded after - the type's initial reads that names a shaping parameter none of the planned - lines named while its object carries or lacks members theirs do not, such as a - later `?expand=shelf` read. On a view with + the type's initial reads, judged against the lines left once variants are + dropped: one that names a shaping parameter none of them named while its + object carries or lacks members theirs do not, such as a later + `?expand=shelf` read, or one that selects some fields and leaves out members + they always show, such as a later `?fields=id,name` read. On a view with such replayed reads, serving replays a call naming a projection parameter for an entity the state holds unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate leaves out exactly diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 488755857cf..95163329fa9 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -50,6 +50,7 @@ import { rewriteCuts, type RewriteSpan } from "./environmentStateRewrites.js"; import { checkItemPlan, checkListPlan, + type LateLine, type StateGateContext, type StatePlan, } from "./environmentStateGate.js"; @@ -63,14 +64,10 @@ import { } from "./environmentStateWriteLinks.js"; import { extractWrites } from "./environmentStateWrites.js"; import { - addLine, dropObservations, lineShapes, - namesNewParameter, - noLines, - showsOtherMembers, + shapesOtherwise, withoutVariants, - type LineTotals, } from "./environmentStateVariants.js"; import { stateWritesOf } from "./environmentStateQueryCalls.js"; @@ -225,6 +222,7 @@ export class EnvironmentStateExtraction { shapeOf: (record) => shapes.get(record.ordinal), queryOf: (ordinal) => this.#byOrdinal.get(ordinal)?.query, position: (ordinal) => this.#position.get(ordinal)!, + retain: (bytes) => this.#retain(bytes), }); if (split === undefined) continue; this.#retain(ENTRY_BYTES * (split.dropped.size + 2)); @@ -409,30 +407,31 @@ export class EnvironmentStateExtraction { candidate: Candidate, pointer: string, recordings: readonly StateRecordFacts[], - projected: readonly number[] = [], + replayed: Pick = {}, ): void { this.#plans.push({ ...candidate, pointer, recordings, latest: this.#latestPerLine(recordings), - projected, + projected: replayed.projected ?? [], + late: replayed.late ?? [], }); } /** - * Later identity-free projections, and later lines that show the entity in another representation - * than the planned lines (a new shaping parameter, members theirs lack or always carry), are - * evidence of replay, never initial entities. Read only those query bodies. + * Later identity-free projections are evidence of replay, never initial entities; later lines that + * show the identity and name a shaping or projection parameter are kept, with their members, for + * the variant pass to decide against the lines left. Read only those query bodies. */ #addLateProjections( tool: StateToolFacts, type: string, projected: number[], - planned: LineTotals, - ): void { + ): LateLine[] { const limit = this.#initLimit(type); - if (limit === undefined) return; + const late: LateLine[] = []; + if (limit === undefined) return late; for (const ordinal of tool.record_ordinals) { const record = this.#byOrdinal.get(ordinal); if ( @@ -444,23 +443,25 @@ export class EnvironmentStateExtraction { ) continue; const projecting = projectsFields(record.query); - if (!projecting && !namesNewParameter(record.query, planned)) continue; - const replayed = this.#withBody(ordinal, (body) => { - if (body === undefined) return false; + // A selection of every field (`fields=*`) shows the entity whole, so only a partial one may replay. + const selecting = selectsSomeFields(record.query); + const shaping = shapesOtherwise(record.query); + if (!projecting && !shaping) continue; + const line = this.#withBody(ordinal, (body) => { + if (body === undefined) return undefined; const located = locateItem(body, lastSegmentValue(record.path)); - if (projecting) return located === undefined; - if (located === undefined) return false; + if (located === undefined) return projecting ? null : undefined; + if (!selecting && !shaping) return undefined; const members = membersAt(body, located.pointer); - return showsOtherMembers( - { carried: members, common: members }, - planned, - ); + this.#retain(ENTRY_BYTES * (2 + members.size)); + return { record, members, projecting: selecting }; }); - if (replayed) { + if (line === null) { this.#retain(ENTRY_BYTES); projected.push(ordinal); - } + } else if (line !== undefined) late.push(line); } + return late; } /** Item tools prove a type's identity field by the path value their bodies repeat. */ @@ -472,19 +473,12 @@ export class EnvironmentStateExtraction { let keys: string[] | undefined; const kept: StateRecordFacts[] = []; const projected: number[] = []; - // The planned lines' representation, which a later line's is compared with. - const planned = noLines(); for (const record of recordings) { - const located = this.#withBody(record.ordinal, (body) => { - if (body === undefined) return null; - const found = locateItem(body, lastSegmentValue(record.path)); - if (found !== undefined) { - const members = membersAt(body, found.pointer); - this.#retain(ENTRY_BYTES * (1 + members.size)); - addLine(planned, record.query, { carried: members, common: members }); - } - return found; - }); + const located = this.#withBody(record.ordinal, (body) => + body === undefined + ? null + : locateItem(body, lastSegmentValue(record.path)), + ); if (located === null) { this.#recorded(tool, "body-unusable"); return; @@ -522,11 +516,11 @@ export class EnvironmentStateExtraction { return; } this.#identity.set(type, { field, basis: "path-parameter" }); - this.#addLateProjections(tool, type, projected, planned); + const late = this.#addLateProjections(tool, type, projected); projected.sort( (left, right) => this.#position.get(left)! - this.#position.get(right)!, ); - this.#addPlan(candidate, pointer, kept, projected); + this.#addPlan(candidate, pointer, kept, { projected, late }); } /** @@ -591,14 +585,11 @@ export class EnvironmentStateExtraction { if (!this.#identity.has(type)) this.#identity.set(type, { field, basis: "field-name" }); this.#retain(ENTRY_BYTES * (initial.length - recordings.length)); - this.#addPlan( - candidate, - pointer, - recordings, - initial + this.#addPlan(candidate, pointer, recordings, { + projected: initial .filter((record) => !recordings.includes(record)) .map((record) => record.ordinal), - ); + }); } #observePlan(plan: StatePlan): void { diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index 4675b9cfe29..5e5df3cdfba 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -35,6 +35,14 @@ import { startsAtBeginning } from "./environmentStatePaging.js"; import { readClock, type ClockFormat } from "./environmentStateWriteValues.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; +/** A successful item read first recorded after the initial reads, with the members its object carries. */ +export interface LateLine { + readonly record: StateRecordFacts; + readonly members: ReadonlySet; + /** Whether it asks for some fields (`fields`, `select`, …). */ + readonly projecting: boolean; +} + /** A read tool whose recordings locate entities of one type at one pointer. */ export interface StatePlan { readonly tool: StateToolFacts; @@ -47,6 +55,8 @@ export interface StatePlan { readonly latest: readonly StateRecordFacts[]; /** Reads left to replay: item reads that asked for some fields only, and representation variants. */ readonly projected?: readonly number[]; + /** Item lines first recorded after the initial reads whose identity they show, decided against the lines left once variants are dropped. */ + readonly late?: readonly LateLine[]; /** The query keys that pick calls of the replayed reads out. */ readonly projectedKeys?: readonly ReplayKey[]; } diff --git a/src/domain/analysisView/environmentStateRewrites.ts b/src/domain/analysisView/environmentStateRewrites.ts index 061d580275e..b80bd834187 100644 --- a/src/domain/analysisView/environmentStateRewrites.ts +++ b/src/domain/analysisView/environmentStateRewrites.ts @@ -16,15 +16,32 @@ export const rewriteCuts = ( writes: readonly StateRecordFacts[], byOrdinal: ReadonlyMap, ): Map => { + // The latest end among each prefix of writes, so the first write ending after a time is found by bisection. + const reach: number[] = []; + for (const write of writes) + reach.push(Math.max(reach.at(-1) ?? Number.NEGATIVE_INFINITY, write.end)); + const starts = writes.map((write) => write.start); + /** The first index whose value passes `test`, which once true stays true. */ + const first = ( + values: readonly number[], + test: (value: number) => boolean, + ) => { + let [low, high] = [0, values.length]; + while (low < high) { + const middle = (low + high) >>> 1; + if (test(values[middle]!)) high = middle; + else low = middle + 1; + } + return low; + }; const cuts = new Map(); for (const span of spans) { const earlier = byOrdinal.get(span.earlier); const later = byOrdinal.get(span.later); if (earlier === undefined || later === undefined) continue; - const index = writes.findIndex( - (write) => write.start < later.end && write.end > earlier.start, - ); - if (index !== -1) + // Writes come in start order: those begun before the later recording ended are a prefix. + const index = first(reach, (end) => end > earlier.start); + if (index < first(starts, (start) => start >= later.end)) cuts.set(span.type, Math.min(index, cuts.get(span.type) ?? index)); } return new Map([...cuts].map(([type, index]) => [type, writes[index]!])); diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 735b8811817..5d4fd413fc3 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -1,6 +1,6 @@ import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; -import type { StatePlan } from "./environmentStateGate.js"; +import type { LateLine, StatePlan } from "./environmentStateGate.js"; import type { ObservedEntity } from "./environmentStateMerge.js"; import { isProjectionParameter, @@ -51,6 +51,11 @@ export const queryValues = ( return values; }; +/** Whether a query names a parameter that may change how a line shows its entities, paging and field selections aside. */ +export const shapesOtherwise = (query: string | null | undefined): boolean => + shapingNames(query).some((name) => !isProjectionParameter(name)); + +/** The query names that may change how a line shows its entities: all but paging. */ const shapingNames = (query: string | null | undefined): string[] => [...queryValues(query).keys()].filter( (name) => !PAGING.has(name.toLowerCase()), @@ -116,21 +121,21 @@ const conflicts = (left: LineShape, right: LineShape): boolean => ); /** What lines compared later are compared with: the shaping parameter names they named, the members their objects carried, and those every one carried. */ -export interface LineTotals { +interface LineTotals { readonly names: Set; readonly carried: Set; common: Set | undefined; } /** Totals over no lines yet. */ -export const noLines = (): LineTotals => ({ +const noLines = (): LineTotals => ({ names: new Set(), carried: new Set(), common: undefined, }); /** Count one more line into the totals. */ -export const addLine = ( +const addLine = ( totals: LineTotals, query: string | null | undefined, shape: Pick, @@ -146,13 +151,13 @@ export const addLine = ( }; /** Whether a query names a shaping parameter, paging aside, that none of the counted lines named. */ -export const namesNewParameter = ( +const namesNewParameter = ( query: string | null | undefined, totals: LineTotals, ): boolean => shapingNames(query).some((name) => !totals.names.has(name)); /** Whether a line's objects carry a member the counted lines' never did, or lack one theirs always carried. */ -export const showsOtherMembers = ( +const showsOtherMembers = ( shape: Pick, totals: LineTotals, ): boolean => { @@ -242,6 +247,7 @@ const isVariant = ( export const replayKeys = ( base: readonly (string | null | undefined)[], replayed: readonly (string | null | undefined)[], + retain: (bytes: number) => void = () => undefined, ): ReplayKey[] => { const baseValues = base.map(queryValues); const named = new Set(baseValues.flatMap((values) => [...values.keys()])); @@ -252,10 +258,15 @@ export const replayKeys = ( ); const keys = new Map(); const add = (key: ReplayKey): void => { - keys.set( - JSON.stringify([key.name, key.value ?? null, key.absent ?? false]), - key, - ); + const id = JSON.stringify([ + key.name, + key.value ?? null, + key.absent ?? false, + ]); + if (keys.has(id)) return; + // Each key is kept with its text, so it is charged before it is. + retain(ENTRY_BYTES * 2 + textBytes(id.length)); + keys.set(id, key); }; for (const query of replayed) { const values = queryValues(query); @@ -357,6 +368,7 @@ export const withoutVariants = ( readonly shapeOf: (record: StateRecordFacts) => LineShape | undefined; readonly queryOf: (ordinal: number) => string | null | undefined; readonly position: (ordinal: number) => number; + readonly retain: (bytes: number) => void; }, ): | { readonly plan: StatePlan; readonly dropped: ReadonlySet } @@ -370,12 +382,15 @@ export const withoutVariants = ( [record.query], ).length > 0, ); - const projected = plan.projected ?? []; - if (variants.length === 0 && projected.length === 0) return undefined; const lines = new Set(variants.map(requestLine)); const latest = plan.latest.filter( (record) => !lines.has(requestLine(record)), ); + const projected = [ + ...(plan.projected ?? []), + ...lateReplays(plan.late ?? [], latest, facts.shapeOf), + ]; + if (variants.length === 0 && projected.length === 0) return undefined; const replayed = [ ...projected, ...variants.map((record) => record.ordinal), @@ -396,12 +411,38 @@ export const withoutVariants = ( projectedKeys: replayKeys( latest.map((record) => record.query), replayed.map(facts.queryOf), + facts.retain, ), }, dropped, }; }; +/** + * The later item lines serving replays, decided against the lines left: a selection of some fields + * that leaves out members they always show, or a line naming a shaping parameter none of them names + * while its object carries or lacks members theirs do not. + */ +const lateReplays = ( + late: readonly LateLine[], + base: readonly StateRecordFacts[], + shapeOf: (record: StateRecordFacts) => LineShape | undefined, +): number[] => { + if (late.length === 0) return []; + const totals = noLines(); + for (const record of base) + addLine(totals, record.query, shapeOf(record) ?? EMPTY); + return late.flatMap(({ record, members, projecting }) => + (projecting || + shapingNames(record.query).some( + (name) => !isProjectionParameter(name) && !totals.names.has(name), + )) && + showsOtherMembers({ carried: members, common: members }, totals) + ? [record.ordinal] + : [], + ); +}; + /** Forget the observations of dropped recordings, and entities only they showed; an entity is first sighted where its kept observations show it first. */ export const dropObservations = ( entities: Map, diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index 04532b8fb9a..346de1db863 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -27,7 +27,12 @@ import { type JsonObject, } from "./environmentStateRules.js"; import { environmentStateFields } from "./environmentStateView.js"; -import { lineShapes, variantLines } from "./environmentStateVariants.js"; +import { + lineShapes, + replayKeys, + variantLines, +} from "./environmentStateVariants.js"; +import { rewriteCuts } from "./environmentStateRewrites.js"; type State = Extract; const ALL_RULES = [ @@ -952,6 +957,62 @@ it("counts each change of a line's membership across a write against the budget" ); }); +it("counts each replay key it keeps against the budget", () => { + let retained = 0; + const names = Array.from( + { length: 500 }, + (_, index) => `view_${String(index)}`, + ); + const keys = replayKeys( + ["?view=plain"], + [`?${names.map((name) => `${name}=1`).join("&")}`], + (bytes) => { + retained += bytes; + }, + ); + expect(keys.length).toBeGreaterThan(names.length); + expect(retained).toBeGreaterThanOrEqual(keys.length * 128); +}); + +it("finds each span's earliest write without scanning the writes before it", () => { + let reads = 0; + const timed = (ordinal: number, start: number, end: number) => { + const record = { + ordinal, + method: "POST", + path: "/api/log", + query: undefined, + status: 200, + }; + return Object.defineProperties(record, { + start: { enumerable: true, get: () => ((reads += 1), start) }, + end: { enumerable: true, get: () => ((reads += 1), end) }, + }) as typeof record & { readonly start: number; readonly end: number }; + }; + const count = 2000; + const writes = Array.from({ length: count }, (_, index) => + timed(index, index * 10, index * 10 + 1), + ); + const reads_ = new Map( + Array.from({ length: count }, (_, index) => { + const ordinal = count + index; + return [ + ordinal, + timed(ordinal, index * 10 + 5, index * 10 + 12), + ] as const; + }), + ); + const spans = [...reads_.keys()].map((earlier, index) => ({ + type: `/api/type_${String(index)}`, + earlier, + later: earlier, + })); + reads = 0; + const cuts = rewriteCuts(spans, writes, reads_); + expect(cuts.size).toBe(count - 1); + expect(reads).toBeLessThan(200 * count); +}); + it("releases a planning pass a rewrite cut discards before extracting the state again", () => { const recipe = (id: number, views: number) => ({ id, diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 4178c572ac5..af50d91f5c8 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1662,6 +1662,48 @@ describe("item lines first recorded after a write", () => { }); }); +describe("item lines first recorded after a write, against the lines left", () => { + const created = book(3, "Third Book", bookClock(4)); + const lines = (late: TimedCaptureRow): TimedCaptureRow[] => [ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ["POST", "/api/books", created, 201, { name: "Third Book" }], + ["GET", "/api/books/3", created], + late, + ]; + const itemView = (rows: TimedCaptureRow[]) => + stateOf(rows).views.find((view) => view.tool === "get_books_by_id"); + + it("compares a later line with the lines left after variants are dropped, not the dropped ones", () => { + // The early `expand` line is dropped as a variant, so `include` shows a shelf the lines left never show. + expect( + itemView( + lines(["GET", "/api/books/2?include=shelf", expandedBook(SECOND_BOOK)]), + ), + ).toMatchObject({ + projected_record_ordinals: [3, 6], + projected_query_keys: expect.arrayContaining([{ name: "include" }]), + }); + }); + + it("replays a later selection of some fields that keeps the identity but leaves members out", () => { + expect( + itemView( + lines([ + "GET", + "/api/books/2?fields=id,name", + { id: 2, name: "Second Book" }, + ]), + ), + ).toMatchObject({ + projected_record_ordinals: [3, 6], + projected_query_keys: expect.arrayContaining([{ name: "fields" }]), + }); + }); +}); + describe("what a linked create observes", () => { it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { const D = note(1004, "Delta"); From 8876143103d125fe4244b92d2a1ec4e02a20bc79 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:17:57 -0700 Subject: [PATCH 30/68] docs(environment): record the eighth review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index e428b3b876d..cc815f63170 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -65,6 +65,7 @@ write tool is lost. - **Seventh round** (on main `96ea32b7`): WordPress's post create moves from side-effect to unconfirmed, still unserved: its only later read, `/wp-json/wp/v2/posts/22?context=edit`, shows the edit representation (`generated_slug`), so it is now replayed rather than checked. No served write, read view or recorded read changes. +- **Eighth round** (on main `3e7e102a`): no verdict, read view or recorded read changes on the restored captures. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 6037875bdea18c552fc98f1eec6506e799ff3943 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:18:55 -0700 Subject: [PATCH 31/68] fix(environment): set aside response members a path mints anew on every read A top-level UUID or clock that differs on every repeat of one path's successful reads, with no write between, is left out of that path's item, list and document comparisons and named in the view's per_response_members. Serving keeps the recorded value. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 2 +- .../agent-environments/state-targets/spec.md | 5 + .../agent-environments/state-view/spec.md | 7 + .../agent-environments/state-writes/spec.md | 3 +- docs/web-network-captures.md | 4 +- .../EnvironmentStateExtraction.ts | 20 ++ .../EnvironmentStateWriteSimulation.ts | 8 +- .../analysisView/environmentStateGate.test.ts | 1 + .../analysisView/environmentStateGate.ts | 130 +++-------- .../analysisView/environmentStateListFacts.ts | 118 ++++++++++ .../environmentStateResponseMembers.test.ts | 136 ++++++++++++ .../environmentStateResponseMembers.ts | 206 ++++++++++++++++++ .../analysisView/environmentStateRules.ts | 3 + .../analysisView/environmentStateView.ts | 8 + .../environmentStateWriteChecks.ts | 10 +- 15 files changed, 546 insertions(+), 115 deletions(-) create mode 100644 src/domain/analysisView/environmentStateListFacts.ts create mode 100644 src/domain/analysisView/environmentStateResponseMembers.test.ts create mode 100644 src/domain/analysisView/environmentStateResponseMembers.ts diff --git a/docs/agent-environments.md b/docs/agent-environments.md index 266bcb849b0..a25eaef6f1c 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -433,7 +433,7 @@ Each read tool answers according to its view in the state: | View | Answer | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`, except that a call matching one of the view's `projected_query_keys`, or on a view with `projected_record_ordinals` asking for some fields only with a value other than `*` no checked line gave or one a replayed read gave, replays its recording. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | +| `item` | The entity the path arguments name, rendered into the recorded envelope of `envelope_ordinal`, whose `per_response_members` (such as a request id), like a list's or a document's, keep their recorded values. Arguments match as replay matches them: each collection segment equals the held collection's segment as written or after percent-decoding, and the identity is the last argument percent-decoded, then as written; values are never re-split on `/`. Any entity the state holds answers, including one `data/add` loaded; query arguments only decide `replay.exact_match`, except that a call matching one of the view's `projected_query_keys`, or on a view with `projected_record_ordinals` asking for some fields only with a value other than `*` no checked line gave or one a replayed read gave, replays its recording. An entity the state does not hold answers the tool's latest recorded 400, 404 or 410 response with `state.view` `missing`, or is a tool error when none was recorded; one lacking a field every recording carried is a tool error, unless a read showed the application leaves that field out; a body is never invented. | | `list` | When the arguments name one of the lines the view checked exactly (its latest recordings before the first related write; every path and query value equal to the recording's, and every recorded query parameter supplied), that recorded envelope with its array rendered from the state: every entity of the collection in state order for `membership: "all"` or a line `all_record_ordinals` names, or the recorded members still held. A call with no query argument answers from such a line of the collection its path arguments name that only pages its list, with `replay.exact_match` false. On a line the view's `query` answers, and for a call whose every query argument has a role there (an argument-less call aside), the answer is the query evaluated over the state: filtered, searched, sorted and paged, with counters at the number listed and `query.totals` at the number matched, and `state.membership: "query"`; such a call answers on a query or whole line of its collection with `replay.exact_match` false. A value an `inert` parameter never recorded, a parameter without a role, a call matching one of the view's `projected_query_keys`, or a field selection the checked lines do not show (as for `item`), replays its recording. A member lacking a field every recording carried makes the call a tool error rather than a partial list. | | `document` | When the arguments name the document's checked line exactly, the state's value for it; a tool error when the state holds none. | | `recorded` | The recording, as replay answers it. | diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 7bd248354cd..58396b77116 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -57,6 +57,11 @@ its cause in the recordings and the code. The five largest shared causes: that value, so a toggle is never served. An action never takes a read another write to the entity still needs. - **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying the id field, deletes or updates each one; serving takes the body as recorded, a `DELETE` included. +- **Per-response members.** A top-level member whose value is a UUID or a clock is minted per response on a path when + it differs on every repeat of that path's successful GET lines with no write between, and across the capture it + differed on at least two repeats and never stayed the same. Only views of that path, or item views whose collection + is that path, leave it out: item envelopes, and the write gate's item, list and document reads, compare without it. + The view names it in `per_response_members`, and serving keeps the recorded value. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index e8983c4ddfa..69b90058574 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -77,6 +77,13 @@ later increments. the state holds (APIs that omit empty or false members), no view of the type requires it. Never treat an envelope that is itself an entity as a list. +- A top-level UUID or clock member that differs on every repeat of a path's + successful GET lines with no write between, and across the capture differed + on at least two repeats and never stayed the same, is minted per response + there (a request id). Views of that path, and item views whose collection is + that path, name it in `per_response_members`; an item plan's shared envelope + compares without it, and serving keeps the recorded value. A member minted on + one path is never left out of another path's views. - Merge observations into one entity per collection and identity: item views' latest values win over list views', differing views keep their own values, and a value that changed between repeats of one request line with no recorded diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index a97f7862567..52036d22d89 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -411,7 +411,8 @@ call that serving would not apply, such as a create outside its tied collection, keeps its evidence. **Reads.** A read is checked when the served environment would answer it -from the state: +from the state (an item, list or document read compares without the view's +`per_response_members`): - an item read of a state-backed item view, of the entity serving would name: in a held collection the read's path matches, each segment verbatim or either diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index 7023dddef5f..afdb6df14d7 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -611,9 +611,9 @@ Every entity cites its `record_ordinals`. | Shape | Plan | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares | +| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares, leaving out the `per_response_members` each response there mints: a top-level UUID or clock that differed on every repeat of its path's reads, or its collection's, with no write between, and never stayed the same on a repeat elsewhere; list views name theirs too | | `list` | The array at `pointer`, its `fields`, `membership` (`all`: every entity of the collection in state order, when each recording listed exactly that, had no query or only paging parameters (`limit`, `offset`, `page`, `per_page`, `perpage`, `page_size`, `pagesize`, `size`, `start`, `_start`, `_end`), no item-total member (`total`, `count`, `totalCount`, `item_count`, `totalcount`, `itemcount`, `numberOfElements`, but not `total_pages` or `per_page`; a number or a string of digits) differing from the number listed, and no `has_more`, `next` or next-page token member set; `recorded`: the entities each recording listed, except on the lines `all_record_ordinals` names, which each meet those conditions on their own and list every entity), and `counters` that equal the number listed | -| `document` | The latest initial value of a list tool whose responses hold no identified list, when its initial reads share one request line; held in `documents` with that `path`, whether or not the capture writes it, unless its value changed across any recorded write between those reads (`fields-differ`) | +| `document` | The latest initial value of a list tool whose responses hold no identified list, when its initial reads share one request line; held in `documents` with that `path`, whether or not the capture writes it, unless its value changed across any recorded write between those reads (`fields-differ`); its `per_response_members` are the members of the value each response on that path mints | | `recorded` | A `reason` the tool replays its recordings instead | An item or list plan is kept only when it reproduces the latest initial diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 332cd78955f..115817af958 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -74,6 +74,13 @@ import { type LineTotals, } from "./environmentStateVariants.js"; import { stateWritesOf } from "./environmentStateQueryCalls.js"; +import { + declaredMembers, + envelopeMembers, + mintedFor, + perResponseMembers, + type MintedMembers, +} from "./environmentStateResponseMembers.js"; class StateBudgetExhausted extends Error {} @@ -127,6 +134,7 @@ export class EnvironmentStateExtraction { /** The recordings either side of each such change, and per type the write its initial reads end at. */ #spans: RewriteSpan[] = []; #cuts: ReadonlyMap = new Map(); + #minted: MintedMembers | undefined; readonly #merged = new Map(); /** Merged entities by type and collection, built once on first use after merging. */ #collections: Map | undefined; @@ -742,7 +750,15 @@ export class EnvironmentStateExtraction { } #gateContext(): StateGateContext { + this.#minted ??= perResponseMembers({ + records: this.#records, + withBody: (ordinal, use) => this.#withBody(ordinal, use), + writeWithin: this.#writeWithin, + retain: (bytes) => this.#retain(bytes), + checkpoint: () => this.#budget.checkpoint(), + }); return { + minted: this.#minted, withBody: (ordinal, use) => this.#withBody(ordinal, use), retain: (bytes) => this.#retain(bytes), entity: (type, collection, id) => @@ -828,10 +844,14 @@ export class EnvironmentStateExtraction { value, record_ordinal: record.ordinal, }); + const minted = mintedFor(this.#minted ?? new Map(), [record], false); this.#views.set(tool.name, { tool: tool.name, shape: "document", checked_record_ordinals: [record.ordinal], + ...declaredMembers(envelopeMembers(value, minted), (bytes) => + this.#retain(bytes), + ), }); } return documents.sort((left, right) => compare(left.tool, right.tool)); diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index bf26d2af222..0c250d691d6 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -15,6 +15,7 @@ import { import { UnseenEntities } from "./environmentStateWriteAdoption.js"; import { FailedReadBlame } from "./environmentStateWriteBlame.js"; import { addressedWrite } from "./environmentStateWriteAddress.js"; +import { withoutMembers } from "./environmentStateResponseMembers.js"; import { linkedTarget } from "./environmentStateWriteLinks.js"; import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; @@ -407,7 +408,7 @@ export class EnvironmentStateWriteSimulation { if (view.shape !== "item" && line === undefined) return undefined; if (view.shape === "document") return this.#input.io.withBody(record.ordinal, (body) => - checkDocumentRead(this.#state, view.tool, record, body), + checkDocumentRead(this.#state, view, record, body), ); const item = view.shape === "item"; const target = item @@ -430,10 +431,11 @@ export class EnvironmentStateWriteSimulation { // The served answer keeps the envelope of the item view's or the line's base recording. const base = item ? view.envelope_ordinal : line!.ordinal; const ordinals = { base, read: record.ordinal }; + const minted = view.per_response_members; return withBodies(this.#input.io.withBody, ordinals, (served, body) => { const check = { - body, - base: served, + body: body === undefined ? body : withoutMembers(body, minted), + base: served === undefined ? served : withoutMembers(served, minted), idField: this.#types.get(view.type)?.id_field ?? "", volatile: this.#input.volatileOf(view.type), collection, diff --git a/src/domain/analysisView/environmentStateGate.test.ts b/src/domain/analysisView/environmentStateGate.test.ts index 8993e81287b..50a29b48636 100644 --- a/src/domain/analysisView/environmentStateGate.test.ts +++ b/src/domain/analysisView/environmentStateGate.test.ts @@ -48,6 +48,7 @@ const check = ( inCollection: () => entities, volatileOf: () => new Set(), idField: () => "id", + minted: new Map(), }; const view = checkItemPlan(context, { tool: { diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index 4675b9cfe29..2145cfcfbd1 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -1,4 +1,3 @@ -import { canonicalJson } from "../comparisonSemantics.js"; import type { JsonValue } from "../jsonValue.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { @@ -9,7 +8,6 @@ import { listItems, renderStateEntity, renderStateList, - replaceAt, same, scalarText, type JsonObject, @@ -31,8 +29,18 @@ import { type QueryLine, } from "./environmentStateListQuery.js"; import { singleQueryValues } from "../recordedTransportUrl.js"; -import { startsAtBeginning } from "./environmentStatePaging.js"; import { readClock, type ClockFormat } from "./environmentStateWriteValues.js"; +import { + declaredMembers, + mintedEnvelope, + mintedFor, + type MintedMembers, +} from "./environmentStateResponseMembers.js"; +import { + isItemTotal, + listFacts, + nameTokens, +} from "./environmentStateListFacts.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; /** A read tool whose recordings locate entities of one type at one pointer. */ @@ -79,6 +87,8 @@ export interface StateGateContext { readonly inCollection: (type: string, collection: string) => StateEntity[]; readonly volatileOf: (type: string) => ReadonlySet; readonly idField: (type: string) => string; + /** By path, the top-level members each response there mints; views of other paths keep them. */ + readonly minted: MintedMembers; } /** Ordered key union and always-present keys, grown one object at a time. */ @@ -205,8 +215,9 @@ const itemMismatch = ( plan: StatePlan, check: { readonly view: { readonly tool: string; readonly fields: string[] }; - readonly envelope: { skeleton?: string }; + readonly envelope: { skeleton?: string; members?: string[] }; readonly spellings: ClockSpellings; + readonly minted: ReadonlySet; }, record: StateRecordFacts, ): RecordedViewReason | undefined => { @@ -220,13 +231,15 @@ const itemMismatch = ( const object = body === undefined ? undefined : at(body, plan.pointer); if (entity === undefined || body === undefined || !isObject(object)) return "fields-differ"; - const skeleton = canonicalJson( - replaceAt(body, plan.pointer, null), - "Environment state", + const { skeleton, members } = mintedEnvelope( + body, + plan.pointer, + check.minted, ); if (envelope.skeleton === undefined) { context.retain(textBytes(skeleton.length)); envelope.skeleton = skeleton; + envelope.members = members; } if (skeleton !== envelope.skeleton) return "envelope-varies"; check.spellings.note(entity.fields, object); @@ -253,13 +266,14 @@ export const checkItemPlan = ( }); context.retain(union.bytes); const view = { tool: plan.tool.name, fields: union.fields }; - const envelope: { skeleton?: string } = {}; + const envelope: { skeleton?: string; members?: string[] } = {}; const spellings = new ClockSpellings(context.retain); + const minted = mintedFor(context.minted, plan.latest, true); for (const record of plan.latest) { const reason = itemMismatch( context, plan, - { view, envelope, spellings }, + { view, envelope, spellings, minted }, record, ); if (reason !== undefined) return recorded(plan, reason); @@ -272,106 +286,13 @@ export const checkItemPlan = ( fields: union.fields, required_fields: union.required, envelope_ordinal: plan.latest[0]!.ordinal, + ...declaredMembers(envelope.members, context.retain), checked_record_ordinals: plan.latest.map((record) => record.ordinal), ...replayedReads(plan), ...spellings.view, }; }; -/** The latest recordings that list their whole collection in state order, and the counters that equal the item count on each of them, or on every line when none does. */ -const listFacts = ( - context: StateGateContext, - plan: StatePlan, - union: FieldUnion, -): { readonly whole: ReadonlySet; readonly counters: string[] } => { - const field = context.idField(plan.type); - const whole = new Set(); - const counting = new Map(); - for (const record of plan.latest) - context.withBody(record.ordinal, (body) => { - const items = - body === undefined ? undefined : listItems(body, plan.pointer); - if (body === undefined || items === undefined) return; - items.forEach((item) => union.add(item)); - const parent = plan.pointer === "" || !isObject(body) ? {} : body; - const counted = Object.keys(parent).filter( - (name) => isItemTotal(name) && countOf(parent[name]) !== undefined, - ); - counting.set( - record.ordinal, - counted.filter((name) => parent[name] === items.length), - ); - // Only a line that pages at most can hold its whole collection; a total that differs from - // the number listed, or a next page, shows it is partial. - if ( - !startsAtBeginning(record.query) || - counted.some((name) => countOf(parent[name]) !== items.length) || - Object.keys(parent).some((name) => continues(name, parent[name])) - ) - return; - const ids = items.map((item) => scalarText(item[field]) ?? ""); - const expected = context - .inCollection(plan.type, collectionPathOf(record, false)) - .map((entity) => entity.id); - if (same(ids, expected)) whole.add(record.ordinal); - }); - // Counter presence is per envelope. Keep every observed page counter; - // renderStateList updates only one the selected base actually counted. - const counters = [...new Set([...counting.values()].flat())].sort(compare); - return { whole, counters }; -}; - -const nameTokens = (name: string): string[] => - name - .split(/[_\-\s]|(?<=[a-z0-9])(?=[A-Z])/u) - .map((token) => token.toLowerCase()); - -const LISTED_NOUNS = new Set(["elements", "entries", "items", "results"]); - -/** Item totals, including compact `totalcount`/`itemcount` and `numberOfElements`; page counts and account IDs are excluded. */ -const isItemTotal = (name: string): boolean => { - const tokens = nameTokens(name); - return ( - (tokens.some( - (token) => - token === "total" || - token === "count" || - token === "totalcount" || - token === "itemcount", - ) || - (tokens.includes("number") && - tokens.some((token) => LISTED_NOUNS.has(token)))) && - !tokens.some( - (token) => token === "page" || token === "pages" || token === "per", - ) - ); -}; - -/** A count recorded as a number or as a string of digits. */ -const countOf = (value: JsonValue | undefined): number | undefined => - typeof value === "number" - ? value - : typeof value === "string" && /^\d+$/u.test(value) - ? Number(value) - : undefined; - -const CONTINUATION_NAMES = new Set([ - "hasmore", - "next", - "nextcursor", - "nextpage", - "nextpagetoken", - "nexttoken", -]); - -/** A top-level `has_more`, `next` or next-page token member that says more items follow. */ -const continues = (name: string, value: JsonValue | undefined): boolean => - CONTINUATION_NAMES.has(nameTokens(name).join("")) && - value !== undefined && - value !== null && - value !== false && - value !== ""; - /** The query that lines which are not whole follow, with the item totals that count its matches before paging. */ const listQuery = ( context: StateGateContext, @@ -516,7 +437,7 @@ export const checkListPlan = ( plan: StatePlan, ): StateView => { const union = new FieldUnion(); - const { whole, counters } = listFacts(context, plan, union); + const { whole, counters, minted } = listFacts(context, plan, union); context.retain(union.bytes); const base = { tool: plan.tool.name, @@ -564,6 +485,7 @@ export const checkListPlan = ( }), counters, ...(query === undefined ? {} : { query }), + ...declaredMembers(minted, context.retain), checked_record_ordinals: plan.latest.map((record) => record.ordinal), ...replayedReads(plan), ...spellings.view, diff --git a/src/domain/analysisView/environmentStateListFacts.ts b/src/domain/analysisView/environmentStateListFacts.ts new file mode 100644 index 00000000000..84cd8a63184 --- /dev/null +++ b/src/domain/analysisView/environmentStateListFacts.ts @@ -0,0 +1,118 @@ +import type { JsonValue } from "../jsonValue.js"; +import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import type { StateGateContext, StatePlan } from "./environmentStateGate.js"; +import { startsAtBeginning } from "./environmentStatePaging.js"; +import { + envelopeMembers, + mintedFor, +} from "./environmentStateResponseMembers.js"; +import { + collectionPathOf, + isObject, + listItems, + same, + scalarText, + type JsonObject, +} from "./environmentStateRules.js"; + +/** The latest recordings that list their whole collection in state order, and the counters that equal the item count on each of them, or on every line when none does. */ +export const listFacts = ( + context: StateGateContext, + plan: StatePlan, + union: { add(object: JsonObject): void }, +): { + readonly whole: ReadonlySet; + readonly counters: string[]; + readonly minted: string[]; +} => { + const field = context.idField(plan.type); + const whole = new Set(); + const counting = new Map(); + const names = mintedFor(context.minted, plan.latest, false); + const minted = new Set(); + for (const record of plan.latest) + context.withBody(record.ordinal, (body) => { + const items = + body === undefined ? undefined : listItems(body, plan.pointer); + if (body === undefined || items === undefined) return; + for (const name of envelopeMembers(body, names, plan.pointer)) + minted.add(name); + items.forEach((item) => union.add(item)); + const parent = plan.pointer === "" || !isObject(body) ? {} : body; + const counted = Object.keys(parent).filter( + (name) => isItemTotal(name) && countOf(parent[name]) !== undefined, + ); + counting.set( + record.ordinal, + counted.filter((name) => parent[name] === items.length), + ); + // Only a line that pages at most can hold its whole collection; a total that differs from + // the number listed, or a next page, shows it is partial. + if ( + !startsAtBeginning(record.query) || + counted.some((name) => countOf(parent[name]) !== items.length) || + Object.keys(parent).some((name) => continues(name, parent[name])) + ) + return; + const ids = items.map((item) => scalarText(item[field]) ?? ""); + const expected = context + .inCollection(plan.type, collectionPathOf(record, false)) + .map((entity) => entity.id); + if (same(ids, expected)) whole.add(record.ordinal); + }); + // Counter presence is per envelope. Keep every observed page counter; + // renderStateList updates only one the selected base actually counted. + const counters = [...new Set([...counting.values()].flat())].sort(compare); + return { whole, counters, minted: [...minted].sort(compare) }; +}; + +export const nameTokens = (name: string): string[] => + name + .split(/[_\-\s]|(?<=[a-z0-9])(?=[A-Z])/u) + .map((token) => token.toLowerCase()); + +const LISTED_NOUNS = new Set(["elements", "entries", "items", "results"]); + +/** Item totals, including compact `totalcount`/`itemcount` and `numberOfElements`; page counts and account IDs are excluded. */ +export const isItemTotal = (name: string): boolean => { + const tokens = nameTokens(name); + return ( + (tokens.some( + (token) => + token === "total" || + token === "count" || + token === "totalcount" || + token === "itemcount", + ) || + (tokens.includes("number") && + tokens.some((token) => LISTED_NOUNS.has(token)))) && + !tokens.some( + (token) => token === "page" || token === "pages" || token === "per", + ) + ); +}; + +/** A count recorded as a number or as a string of digits. */ +const countOf = (value: JsonValue | undefined): number | undefined => + typeof value === "number" + ? value + : typeof value === "string" && /^\d+$/u.test(value) + ? Number(value) + : undefined; + +const CONTINUATION_NAMES = new Set([ + "hasmore", + "next", + "nextcursor", + "nextpage", + "nextpagetoken", + "nexttoken", +]); + +/** A top-level `has_more`, `next` or next-page token member that says more items follow. */ +const continues = (name: string, value: JsonValue | undefined): boolean => + CONTINUATION_NAMES.has(nameTokens(name).join("")) && + value !== undefined && + value !== null && + value !== false && + value !== ""; diff --git a/src/domain/analysisView/environmentStateResponseMembers.test.ts b/src/domain/analysisView/environmentStateResponseMembers.test.ts new file mode 100644 index 00000000000..d1a19a6cef6 --- /dev/null +++ b/src/domain/analysisView/environmentStateResponseMembers.test.ts @@ -0,0 +1,136 @@ +import { expect, it } from "vitest"; +import { + timedCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js"; +import type { JsonValue } from "../jsonValue.js"; + +const OPS = "0f8b2c1e-4d5a-4b6c-8d7e-9f0a1b2c3d4e"; +const AUDIT = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; +/** A distinct request id per response. */ +const rid = (n: number): string => + `9c0c1161-53cf-53e8-330a-${String(n).padStart(12, "0")}`; + +/** A reply in an envelope that mints a request id per response. */ +const reply = (n: number, data: JsonValue): JsonValue => ({ + request_id: rid(n), + lease_id: "", + data, +}); + +/** Repeated reads of `path` with nothing written between, each minting its request id. */ +const repeats = (path: string, from: number, count: number) => + Array.from({ length: count }, (_, index): TimedCaptureRow => [ + "GET", + path, + reply(from + index, { keys: [AUDIT, OPS] }), + ]); + +const entityRows = (listed: string): TimedCaptureRow[] => [ + ...repeats(listed, 1, 3), + ["GET", `/v1/entities/${OPS}`, reply(10, { id: OPS, name: "ops" })], + ["GET", `/v1/entities/${AUDIT}`, reply(11, { id: AUDIT, name: "audit" })], + ["DELETE", `/v1/entities/${OPS}`, null, 204], + ["GET", `/v1/entities/${OPS}`, { errors: [] }, 404], +]; + +const viewOf = (rows: readonly TimedCaptureRow[], tool: string) => + environmentStateViewOf(timedCaptureEvidence(rows)).views.find( + (view) => view.tool === tool, + ); + +it("leaves out of an item envelope a member its collection's repeated reads mint anew, and serves the write the item read then checks", () => { + const state = environmentStateViewOf( + timedCaptureEvidence(entityRows("/v1/entities")), + ); + expect( + state.views.find((view) => view.tool === "get_entities_by_uuid"), + ).toMatchObject({ + shape: "item", + pointer: "/data", + per_response_members: ["request_id"], + }); + expect( + state.views.find((view) => view.tool === "get_entities"), + ).toMatchObject({ shape: "document", per_response_members: ["request_id"] }); + expect( + state.writes.find((write) => write.tool === "delete_entities_by_uuid"), + ).toMatchObject({ served: true, reason: null }); +}); + +it("masks a minted member only on the paths whose reads minted it", () => { + // The request id is minted on /v1/policies, not on the entities' own paths. + expect(viewOf(entityRows("/v1/policies"), "get_entities_by_uuid")).toEqual({ + tool: "get_entities_by_uuid", + shape: "recorded", + reason: "envelope-varies", + }); +}); + +it("never takes a changing member for a minted one unless its value is a UUID or a clock", () => { + const rows: TimedCaptureRow[] = [ + ...["queued", "running", "done"].map((status): TimedCaptureRow => [ + "GET", + "/api/jobs/current", + { status }, + ]), + ["GET", "/api/notes/1", { status: "draft", note: { id: 1, text: "a" } }], + ["GET", "/api/notes/2", { status: "kept", note: { id: 2, text: "b" } }], + ]; + expect(viewOf(rows, "get_jobs_current")).not.toHaveProperty( + "per_response_members", + ); + expect(viewOf(rows, "get_notes_by_id")).toMatchObject({ + shape: "recorded", + reason: "envelope-varies", + }); +}); + +it("confirms a document write by a read whose minted member differs", () => { + const settings = (n: number, theme: string): TimedCaptureRow => [ + "GET", + "/v1/settings", + reply(n, { theme, density: "compact" }), + ]; + const rows: TimedCaptureRow[] = [ + settings(1, "light"), + settings(2, "light"), + settings(3, "light"), + ["PATCH", "/v1/settings", null, 204, { theme: "dark" }], + settings(4, "dark"), + ]; + const state = environmentStateViewOf(timedCaptureEvidence(rows)); + expect( + state.views.find((view) => view.tool === "get_settings"), + ).toMatchObject({ shape: "document", per_response_members: ["request_id"] }); + expect( + state.writes.find((write) => write.tool === "patch_settings"), + ).toMatchObject({ served: true, reason: null }); +}); + +it("confirms a create by a list read whose envelope clock differs on every response", () => { + const units = (at: string, names: readonly string[]): TimedCaptureRow => [ + "GET", + "/api/units", + { + timestamp: `2026-10-20T05:46:${at}.183616+00:00`, + results: names.map((name, index) => ({ id: index + 1, name })), + }, + ]; + const rows: TimedCaptureRow[] = [ + units("47", ["gram", "cup"]), + units("48", ["gram", "cup"]), + units("49", ["gram", "cup"]), + ["POST", "/api/units", { id: 3, name: "pinch" }, 201, { name: "pinch" }], + units("51", ["gram", "cup", "pinch"]), + ]; + const state = environmentStateViewOf(timedCaptureEvidence(rows)); + expect(state.views.find((view) => view.tool === "get_units")).toMatchObject({ + shape: "list", + per_response_members: ["timestamp"], + }); + expect( + state.writes.find((write) => write.tool === "post_units"), + ).toMatchObject({ served: true, reason: null }); +}); diff --git a/src/domain/analysisView/environmentStateResponseMembers.ts b/src/domain/analysisView/environmentStateResponseMembers.ts new file mode 100644 index 00000000000..3d5d115999a --- /dev/null +++ b/src/domain/analysisView/environmentStateResponseMembers.ts @@ -0,0 +1,206 @@ +import { canonicalJson } from "../comparisonSemantics.js"; +import type { JsonValue } from "../jsonValue.js"; +import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; +import { + collectionPathOf, + isObject, + normalizedPath, + replaceAt, + type JsonObject, + type StateRecordFacts, +} from "./environmentStateRules.js"; +import { readClock } from "./environmentStateWriteValues.js"; +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; + +/** Fewest repeats, across the capture, that show a member minted on every response rather than changed once. */ +const MINIMUM_REPEATS = 2; +const UUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu; + +/** The paths whose repeated reads showed each member minted anew, so only views of those paths leave it out. */ +export type MintedMembers = ReadonlyMap>; + +const succeeded = (record: StateRecordFacts): boolean => + record.status !== null && record.status >= 200 && record.status < 300; + +/** A body's top-level members whose value looks minted: a UUID or a clock reading. */ +const mintedValues = ( + body: JsonValue | undefined, +): Map | undefined => { + if (body === undefined || !isObject(body)) return undefined; + const values = new Map(); + for (const [name, value] of Object.entries(body)) + if ( + typeof value === "string" && + value.length <= 64 && + (UUID.test(value) || readClock(value) !== undefined) + ) + values.set(name, value); + return values; +}; + +interface Repeats { + differ: number; + same: number; +} + +const tally = ( + counts: Map, + key: string, + differ: boolean, + retain: (bytes: number) => void, +): void => { + let entry = counts.get(key); + if (entry === undefined) { + retain(ENTRY_BYTES * 2 + textBytes(key.length)); + entry = { differ: 0, same: 0 }; + counts.set(key, entry); + } + if (differ) entry.differ += 1; + else entry.same += 1; +}; + +/** + * Per path, the top-level members each response mints: a UUID or clock that differs on every repeat of that path's + * successful GET lines with no write between, where the member also differed on at least two repeats in the + * capture and never stayed the same. Each body is read once; only its minted-looking values are kept. + */ +export const perResponseMembers = (input: { + /** Records in timeline order. */ + readonly records: readonly StateRecordFacts[]; + readonly withBody: ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ) => T; + readonly writeWithin: ( + earlier: StateRecordFacts, + later: StateRecordFacts, + ) => boolean; + readonly retain: (bytes: number) => void; + /** Mark the retained bytes; the returned call releases the scan's line memory. */ + readonly checkpoint: () => () => void; +}): MintedMembers => { + const release = input.checkpoint(); + const latest = new Map< + string, + { record: StateRecordFacts; values: Map } + >(); + const byPath = new Map(); + const byName = new Map(); + for (const record of input.records) { + if (record.method !== "GET" || !succeeded(record)) continue; + const values = input.withBody(record.ordinal, mintedValues); + if (values === undefined) continue; + const line = `${record.path}?${record.query ?? ""}`; + const earlier = latest.get(line); + input.retain( + (earlier === undefined ? ENTRY_BYTES * 2 + textBytes(line.length) : 0) + + [...values].reduce( + (bytes, [name, value]) => + bytes + ENTRY_BYTES + textBytes(name.length + value.length), + 0, + ), + ); + latest.set(line, { record, values }); + if (earlier === undefined || input.writeWithin(earlier.record, record)) + continue; + const path = normalizedPath(record.path); + for (const name of new Set([...earlier.values.keys(), ...values.keys()])) { + // A member minted-looking on one side only is not minted on every response. + const before = earlier.values.get(name); + const after = values.get(name); + const differ = + before !== undefined && after !== undefined && before !== after; + tally(byPath, JSON.stringify([path, name]), differ, input.retain); + tally(byName, name, differ, input.retain); + } + } + const minted = new Map>(); + for (const [key, counts] of byPath) { + const [path, name] = JSON.parse(key) as [string, string]; + const overall = byName.get(name)!; + if (counts.same > 0 || counts.differ === 0) continue; + if (overall.same > 0 || overall.differ < MINIMUM_REPEATS) continue; + minted.set(path, (minted.get(path) ?? new Set()).add(name)); + } + release(); + for (const [path, names] of minted) + input.retain( + ENTRY_BYTES * 2 + + textBytes(path.length) + + [...names].reduce( + (bytes, name) => bytes + ENTRY_BYTES + textBytes(name.length), + 0, + ), + ); + return minted; +}; + +/** The members minted on the paths of these reads, and for item reads on their collection's path too. */ +export const mintedFor = ( + minted: MintedMembers, + records: readonly Pick[], + item: boolean, +): ReadonlySet => { + const names = new Set(); + for (const record of records) + for (const path of item + ? [record.path, collectionPathOf(record, true)] + : [record.path]) + for (const name of minted.get(normalizedPath(path)) ?? []) + names.add(name); + return names; +}; + +/** The first member a pointer names, which holds the entity rather than the envelope. */ +const pointerRoot = (pointer: string): string => + pointer.slice(1).split("/")[0]!.replaceAll("~1", "/").replaceAll("~0", "~"); + +/** Of these names, the top-level members a body carries outside the entity at `pointer`, or anywhere in a document (no pointer); none when the entity is the whole body. */ +export const envelopeMembers = ( + body: JsonValue | undefined, + names: ReadonlySet, + pointer?: string, +): string[] => { + if (body === undefined || !isObject(body) || pointer === "") return []; + const root = pointer === undefined ? undefined : pointerRoot(pointer); + return Object.keys(body) + .filter((name) => names.has(name) && name !== root) + .sort(compare); +}; + +/** The body with the named top-level members set to null, so values each response mints do not decide a comparison. */ +export const withoutMembers = ( + body: JsonValue, + names: readonly string[] | undefined, +): JsonValue => { + if (names === undefined || names.length === 0 || !isObject(body)) return body; + const copy: JsonObject = { ...body }; + for (const name of names) if (Object.hasOwn(copy, name)) copy[name] = null; + return copy; +}; + +/** An item recording's envelope without its entity and minted members, and those members. */ +export const mintedEnvelope = ( + body: JsonValue, + pointer: string, + names: ReadonlySet, +): { readonly skeleton: string; readonly members: string[] } => { + const members = envelopeMembers(body, names, pointer); + return { + skeleton: canonicalJson( + withoutMembers(replaceAt(body, pointer, null), members), + "Environment state", + ), + members, + }; +}; + +/** The view member naming the minted members it leaves out, charged as retained output; none when there are none. */ +export const declaredMembers = ( + members: readonly string[] | undefined, + retain: (bytes: number) => void, +): { readonly per_response_members?: string[] } => { + if (members === undefined || members.length === 0) return {}; + for (const name of members) retain(ENTRY_BYTES + textBytes(name.length)); + return { per_response_members: [...members] }; +}; diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index e5e32fd9d39..5c68157fb82 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -110,6 +110,8 @@ interface EntityViewPlan { readonly clock_formats?: Readonly> | undefined; /** Fields whose string arrays the view lists in code-point order, whatever order they were written in. */ readonly sorted_arrays?: string[] | undefined; + /** Envelope members each response there mints, which checks leave out and serving keeps as recorded. */ + readonly per_response_members?: string[] | undefined; } /** A query key that picks out replayed reads: a parameter, a parameter with one value, or a parameter left out. */ @@ -185,6 +187,7 @@ export type StateView = readonly tool: string; readonly shape: "document"; readonly checked_record_ordinals: number[]; + readonly per_response_members?: string[] | undefined; } | { readonly tool: string; diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 8b11017c071..a077c205afc 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -100,6 +100,12 @@ const clockFormatSchema = z.discriminatedUnion("kind", [ }), z.strictObject({ kind: z.literal("epoch"), unit: z.enum(["s", "ms"]) }), ]); +const perResponseSchema = z + .array(z.string()) + .optional() + .describe( + "Top-level members minted per response, such as a request id: a UUID or clock that differed on every repeat of the view's paths (or, for an item view, its collection's) with no write between. Checks leave them out; serving keeps the recorded value, so a served response repeats it.", + ); const entityViewFields = { tool: z.string(), type: z.string(), @@ -113,6 +119,7 @@ const entityViewFields = { .describe("Ordered fields the view shows of each entity."), required_fields: z.array(z.string()), checked_record_ordinals: checkedSchema, + per_response_members: perResponseSchema, clock_formats: z .record(z.string(), clockFormatSchema) .optional() @@ -187,6 +194,7 @@ const viewSchema = z.discriminatedUnion("shape", [ tool: z.string(), shape: z.literal("document"), checked_record_ordinals: checkedSchema, + per_response_members: perResponseSchema, }), z.strictObject({ tool: z.string(), diff --git a/src/domain/analysisView/environmentStateWriteChecks.ts b/src/domain/analysisView/environmentStateWriteChecks.ts index 6fd8eb9f444..dfaa860bc36 100644 --- a/src/domain/analysisView/environmentStateWriteChecks.ts +++ b/src/domain/analysisView/environmentStateWriteChecks.ts @@ -29,6 +29,7 @@ import { singleQueryValues } from "../recordedTransportUrl.js"; import type { ServedLine } from "./environmentStateCheckedLines.js"; import { insertIndex } from "./environmentStateWriteExplain.js"; import type { InsertRule } from "./environmentStateWriteRules.js"; +import { withoutMembers } from "./environmentStateResponseMembers.js"; export const entityTarget = (type: string, collection: string, id: string) => `e${compositeKey([type, collection, id])}`; @@ -595,16 +596,17 @@ export const checkListRead = ( /** A document read on its checked line must equal the held document. */ export const checkDocumentRead = ( state: SimulatedState, - tool: string, + view: Extract, record: StateRecordFacts, body: JsonValue | undefined, ): CheckOutcome | undefined => { if (!succeeded(record)) return undefined; - const value = state.document(tool); + const value = state.document(view.tool); if (body === undefined || value === undefined) return undefined; + const minted = view.per_response_members; return { - pass: same(value, body), - targets: [documentTarget(tool)], + pass: same(withoutMembers(value, minted), withoutMembers(body, minted)), + targets: [documentTarget(view.tool)], unheld: [], }; }; From 342933ea000f63b7748ba3f1cefa831ff9b6407c Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:24:32 -0700 Subject: [PATCH 32/68] fix(environment): count only reads finished before a linked create began as showing its id held A list still running when the call began may show what the call made, as the creation cut already decides, so it no longer refuses the link. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 14 ++++++------- .../agent-environments/state-writes/spec.md | 3 ++- .../environmentStateWriteLinks.ts | 17 ++++++++++------ .../environmentStateWrites.test.ts | 20 +++++++++++++++++++ tests/fixtures/analysisView.ts | 2 +- 5 files changed, 41 insertions(+), 15 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 849d6960294..a6564ec6999 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -29,13 +29,13 @@ its cause in the recordings and the code. The five largest shared causes: models or one redirected or unanswered, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names - an id its response returned, before any other tool's write, when the id is new: no earlier read of the id, its - type's lists or that collection showed it. Its observation is a read of an id its response returned, in an envelope - too. Serving creates in that read's collection, for the exemplar's path arguments only (segment by segment, in - either spelling), and fills path fields with its exemplar's path values decoded once. A successful POST that - returned an id a type's reads only show once it began ends that type's initial window: a read still running then may - show it, and a list read shows its listed entities' own ids (identity-named, or a suffix-named field such as - `projectId` distinct across two or more when no id-named field identifies them), not those they nest. + an id its response returned, before any other tool's write, when the id is new: no read finished before it began, of + the id, its type's lists or that collection, showed it. Its observation is a read of an id its response returned, in + an envelope too. Serving creates in that read's collection, for the exemplar's path arguments only (segment by + segment, in either spelling), and fills path fields with its exemplar's path values decoded once. A successful POST + that returned an id a type's reads only show once it began ends that type's initial window: a read still running + then may show it, and a list read shows its listed entities' own ids (identity-named, or a suffix-named field such + as `projectId` distinct across two or more when no id-named field identifies them), not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 463290691bc..804a308cf53 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -90,7 +90,8 @@ body or of an object member, or a scalar body or sole member of four characters or more), and the first later successful item read naming that id belongs to a state type. That read must come before any other tool's write, which may have made what it shows, as a publish call makes a note from a draft. The entity must -be new: neither the initial state nor any earlier read holds that id, whether an +be new: neither the initial state nor any read finished before the call began +holds that id (one still running may show what the call made), whether an item read of it, a list read of its type, or any read of the item read's collection, with or without a query, that lists it under an identity member of its own (a body with no list counts an identity member at any depth). An id shorter than four characters may be any type's, diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 7a04dc86aa9..77da45ca33d 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -234,8 +234,8 @@ export const creationLimit = ( /** * The state type and collection a POST whose path names none creates into: that of the first later * successful item read naming an id its first successful call returned, before any other tool's - * write, when neither the initial state nor any earlier read of that id, its type's lists or its - * collection showed that id. A short id may be any type's, so it links only to a type read before the call. + * write, when neither the initial state nor any read finished before the call of that id, its + * type's lists or its collection showed that id. A short id may be any type's, so it links only to a type read before the call. */ export const linkedCreate = (input: { readonly tool: StateToolFacts; @@ -252,9 +252,14 @@ export const linkedCreate = (input: { (record) => own.has(record.ordinal) && succeeded(record), ); if (first === -1) return undefined; - const ids = new Set(input.respondedIds(records[first]!.ordinal)); + const post = records[first]!; + const ids = new Set(input.respondedIds(post.ordinal)); if (ids.size === 0) return undefined; - for (const record of records.slice(0, first)) + // Only a read finished before the call began shows what was there before it, as `freshIds` decides. + const before = records + .slice(0, first) + .filter((record) => record.end <= post.start); + for (const record of before) if ( record.method === "GET" && succeeded(record) && @@ -278,7 +283,7 @@ export const linkedCreate = (input: { input.entities.some( (entity) => entity.type === view.type && entity.id === id, ) || - records.slice(0, first).some((earlier) => { + before.some((earlier) => { const read = input.viewOf(earlier.ordinal); return ( earlier.method === "GET" && @@ -290,7 +295,7 @@ export const linkedCreate = (input: { }); const unseen = id.length < MIN_ID_LENGTH && - !records.slice(0, first).some((earlier) => { + !before.some((earlier) => { const read = input.viewOf(earlier.ordinal); return ( earlier.method === "GET" && diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index af50d91f5c8..7342f9ad9d2 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1704,6 +1704,26 @@ describe("item lines first recorded after a write, against the lines left", () = }); }); +describe("reads overlapping a linked create", () => { + it("links a create whose id only a list still running when it began showed before", () => { + const state = stateOf([ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + // Begun before the publish and finished after it, so it may show what the publish made. + ["GET", "/api/notes", [A, B, C], 200, undefined, 2500], + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], + ]); + expect(planOf(state, "post_drafts_publish")).toMatchObject({ + effect: "create", + target: "/api/notes", + }); + expect(notesOf(state)).toEqual(["1001", "1002"]); + }); +}); + describe("what a linked create observes", () => { it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { const D = note(1004, "Delta"); diff --git a/tests/fixtures/analysisView.ts b/tests/fixtures/analysisView.ts index 37f3a7d973a..066672d1405 100644 --- a/tests/fixtures/analysisView.ts +++ b/tests/fixtures/analysisView.ts @@ -320,7 +320,7 @@ export type TimedCaptureRow = readonly [ path: string, body?: JsonValue, status?: number, - request?: JsonValue, + request?: JsonValue | undefined, time?: number, ]; From cfa8310708bcae401751c74ca548a4face284566 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:32:45 -0700 Subject: [PATCH 33/68] fix(environment): count a list total nested in a paging object An item total in a top-level object beside the list, such as pageInfo.totalRows, is a counter on the same evidence as a top-level one: it must equal the number listed, and one that differs marks the line partial. Serving and the gate render it from the state through its JSON pointer and leave the object's other members as recorded. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/list-queries/spec.md | 5 +- .../agent-environments/state-view/spec.md | 8 +- docs/web-network-captures.md | 12 +-- .../analysisView/environmentStateCounters.ts | 41 +++++++++ .../analysisView/environmentStateGate.ts | 17 ++-- .../environmentStateListCounters.test.ts | 85 +++++++++++++++++++ .../analysisView/environmentStateListFacts.ts | 31 ++++++- .../analysisView/environmentStateListQuery.ts | 21 +++-- .../analysisView/environmentStateRules.ts | 5 +- .../analysisView/environmentStateView.ts | 6 +- 10 files changed, 194 insertions(+), 37 deletions(-) create mode 100644 src/domain/analysisView/environmentStateCounters.ts create mode 100644 src/domain/analysisView/environmentStateListCounters.test.ts diff --git a/docs/specs/agent-environments/list-queries/spec.md b/docs/specs/agent-environments/list-queries/spec.md index e180f7a5b4e..ebd2e96b59a 100644 --- a/docs/specs/agent-environments/list-queries/spec.md +++ b/docs/specs/agent-environments/list-queries/spec.md @@ -51,8 +51,9 @@ merge: lines that disagree drop the parameter, inert values gather, search field named like its parameter (`shelf`, or `shelf_id`, for `shelf`) can match by coincidence, so it stands only when lines giving the parameter two different values agree on it; otherwise the parameter takes no role. The merged query keeps the lines it reproduces, envelope and fields included; any other line keeps its recorded members. The view's `query` names -the roles, those lines, and the envelope members that count every match before paging (`totals`); a `number`-of-items -member such as `numberOfElements` counts the page. +the roles, those lines, and the envelope members that count every match before paging (`totals`), top-level or one +level down in a paging object (`/pageInfo/totalRows`); a `number`-of-items member such as `numberOfElements` counts the +page. ## Serving and the write gate diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 0681d08a5c0..41fd4784f6a 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -120,8 +120,12 @@ later increments. parameter (`random`, `rand`, `shuffle`, `seed`); a collection without such a line keeps its entities' earliest sightings. - A list has `all` membership only when no item-total envelope member (`total`, - `count` and their compounds, not page counts) differs from the number of - entities it lists and no `has_more`, `next` or next-page token is set. + `count` and their compounds, not page counts), at the top level or in a + top-level object beside the list such as `pageInfo.totalRows`, differs from + the number of entities it lists and no `has_more`, `next` or next-page token + is set. Such a member that equals the number listed is a counter; a nested + one is named by its pointer (`/pageInfo/totalRows`), and members beside it + such as `isLastPage` stay as recorded. - Keep an item or list plan only when it reproduces each request line's latest initial recording from the state, comparing JSON values without regard to member order; otherwise record the tool with a reason. Parse bodies only when diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index afdb6df14d7..b5b4d5568a2 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -609,12 +609,12 @@ Every entity cites its `record_ordinals`. `views` lists one plan per read tool in tool order: -| Shape | Plan | -| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares, leaving out the `per_response_members` each response there mints: a top-level UUID or clock that differed on every repeat of its path's reads, or its collection's, with no write between, and never stayed the same on a repeat elsewhere; list views name theirs too | -| `list` | The array at `pointer`, its `fields`, `membership` (`all`: every entity of the collection in state order, when each recording listed exactly that, had no query or only paging parameters (`limit`, `offset`, `page`, `per_page`, `perpage`, `page_size`, `pagesize`, `size`, `start`, `_start`, `_end`), no item-total member (`total`, `count`, `totalCount`, `item_count`, `totalcount`, `itemcount`, `numberOfElements`, but not `total_pages` or `per_page`; a number or a string of digits) differing from the number listed, and no `has_more`, `next` or next-page token member set; `recorded`: the entities each recording listed, except on the lines `all_record_ordinals` names, which each meet those conditions on their own and list every entity), and `counters` that equal the number listed | -| `document` | The latest initial value of a list tool whose responses hold no identified list, when its initial reads share one request line; held in `documents` with that `path`, whether or not the capture writes it, unless its value changed across any recorded write between those reads (`fields-differ`); its `per_response_members` are the members of the value each response on that path mints | -| `recorded` | A `reason` the tool replays its recordings instead | +| Shape | Plan | +| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares, leaving out the `per_response_members` each response there mints: a top-level UUID or clock that differed on every repeat of its path's reads, or its collection's, with no write between, and never stayed the same on a repeat elsewhere; list views name theirs too | +| `list` | The array at `pointer`, its `fields`, `membership` (`all`: every entity of the collection in state order, when each recording listed exactly that, had no query or only paging parameters (`limit`, `offset`, `page`, `per_page`, `perpage`, `page_size`, `pagesize`, `size`, `start`, `_start`, `_end`), no item-total member (`total`, `count`, `totalCount`, `item_count`, `totalcount`, `itemcount`, `numberOfElements`, but not `total_pages` or `per_page`; a number or a string of digits; top-level, or in a top-level object beside the list such as `pageInfo.totalRows`) differing from the number listed, and no `has_more`, `next` or next-page token member set; `recorded`: the entities each recording listed, except on the lines `all_record_ordinals` names, which each meet those conditions on their own and list every entity), and `counters` that equal the number listed | +| `document` | The latest initial value of a list tool whose responses hold no identified list, when its initial reads share one request line; held in `documents` with that `path`, whether or not the capture writes it, unless its value changed across any recorded write between those reads (`fields-differ`); its `per_response_members` are the members of the value each response on that path mints | +| `recorded` | A `reason` the tool replays its recordings instead | An item or list plan is kept only when it reproduces the latest initial recording of each request line from the state, comparing JSON values without diff --git a/src/domain/analysisView/environmentStateCounters.ts b/src/domain/analysisView/environmentStateCounters.ts new file mode 100644 index 00000000000..16764672546 --- /dev/null +++ b/src/domain/analysisView/environmentStateCounters.ts @@ -0,0 +1,41 @@ +import type { JsonValue } from "../jsonValue.js"; + +type JsonObject = { [key: string]: JsonValue }; + +const isObject = (value: JsonValue | undefined): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** A list counter's member names: a top-level member, or a pointer to one in a top-level object (`/pageInfo/totalRows`). */ +export const counterPath = (counter: string): string[] => + counter.startsWith("/") + ? counter + .slice(1) + .split("/") + .map((token) => token.replaceAll("~1", "/").replaceAll("~0", "~")) + : [counter]; + +/** A list counter's recorded value, or undefined when the body lacks it. */ +export const counterAt = ( + body: JsonValue, + counter: string, +): JsonValue | undefined => + counterPath(counter).reduce( + (value, name) => + isObject(value) && Object.hasOwn(value, name) ? value[name] : undefined, + body, + ); + +/** The body with a counter it holds set to `value`. */ +export const withCounter = ( + body: JsonValue, + counter: string, + value: JsonValue, +): JsonValue => { + const set = (node: JsonValue, path: readonly string[]): JsonValue => { + const [name, ...rest] = path; + if (name === undefined) return value; + if (!isObject(node) || !Object.hasOwn(node, name)) return node; + return { ...node, [name]: set(node[name]!, rest) }; + }; + return set(body, counterPath(counter)); +}; diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index bc22e0c2fe4..1b0ccf46b34 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -19,6 +19,7 @@ import { type StateToolFacts, type StateView, } from "./environmentStateRules.js"; +import { counterPath } from "./environmentStateCounters.js"; import { evaluateQuery, learnQuery, @@ -37,7 +38,7 @@ import { type MintedMembers, } from "./environmentStateResponseMembers.js"; import { - isItemTotal, + itemTotals, listFacts, nameTokens, } from "./environmentStateListFacts.js"; @@ -336,12 +337,12 @@ const listQuery = ( const parent = plan.pointer === "" || !isObject(body) ? {} : body; counts.set( record.ordinal, - Object.keys(parent).flatMap((name): [string, number][] => { - const count = isItemTotal(name) - ? queryTotalCount(parent[name]) - : undefined; - return count === undefined ? [] : [[name, count]]; - }), + itemTotals(parent, plan.pointer).flatMap( + ([name, value]): [string, number][] => { + const count = queryTotalCount(value); + return count === undefined ? [] : [[name, count]]; + }, + ), ); }); } @@ -361,7 +362,7 @@ const listQuery = ( // Absence says nothing about another envelope's counter. Only a present // count that disagrees invalidates the shared total interpretation. for (const [name, count] of counts.get(line.ordinal) ?? []) { - if (nameTokens(name).includes("number")) continue; + if (nameTokens(counterPath(name).at(-1)!).includes("number")) continue; if (count === total) totals.add(name); else contradicted.add(name); } diff --git a/src/domain/analysisView/environmentStateListCounters.test.ts b/src/domain/analysisView/environmentStateListCounters.test.ts new file mode 100644 index 00000000000..0840ef3196e --- /dev/null +++ b/src/domain/analysisView/environmentStateListCounters.test.ts @@ -0,0 +1,85 @@ +import { expect, it } from "vitest"; +import { + timedCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { environmentStateViewOf } from "../../../tests/fixtures/environmentStateWrites.js"; +import { renderQueryList } from "./environmentStateListQuery.js"; +import { renderStateList, type JsonObject } from "./environmentStateRules.js"; + +const vessel = (id: number, status: string): JsonObject => ({ + Id: id, + name: `Vessel ${String(id)}`, + status, +}); +const SEEDED = [vessel(1, "Active"), vessel(2, "In Port"), vessel(3, "Active")]; + +/** A list in a paging envelope that counts its rows beside two page flags. */ +const page = (list: readonly JsonObject[], totalRows = list.length) => ({ + list: [...list], + pageInfo: { + totalRows, + page: 1, + pageSize: 25, + isFirstPage: true, + isLastPage: true, + }, +}); + +const rows: TimedCaptureRow[] = [ + ["GET", "/api/records?limit=25", page(SEEDED)], + ["GET", "/api/records/1", SEEDED[0]!], + ["GET", "/api/records/2", SEEDED[1]!], + ["GET", "/api/records/3", SEEDED[2]!], + [ + "GET", + "/api/records?where=(status,eq,Active)", + page([SEEDED[0]!, SEEDED[2]!]), + ], + [ + "POST", + "/api/records", + { Id: 4 }, + 200, + { name: "Vessel 4", status: "Laid Up" }, + ], + ["GET", "/api/records/4", vessel(4, "Laid Up")], + ["GET", "/api/records?limit=25", page([...SEEDED, vessel(4, "Laid Up")])], +]; + +it("counts a total nested in a paging object, and serves the create its list read-back counts", () => { + const state = environmentStateViewOf(timedCaptureEvidence(rows)); + expect(state.views.find((view) => view.tool === "get_records")).toMatchObject( + { shape: "list", counters: ["/pageInfo/totalRows"] }, + ); + expect( + state.writes.find((write) => write.tool === "post_records"), + ).toMatchObject({ served: true, reason: null }); +}); + +it("renders a nested counter and a nested query total from the state, leaving the page flags as recorded", () => { + const base = page(SEEDED); + const items = [...SEEDED, vessel(4, "Laid Up")]; + const view = { + pointer: "/list", + counters: ["/pageInfo/totalRows"], + query: { totals: ["/pageInfo/totalRows"] }, + }; + expect(renderStateList(view, base, items)).toEqual(page(items)); + expect(renderQueryList(view, page([SEEDED[0]!]), [SEEDED[0]!], 2)).toEqual( + page([SEEDED[0]!], 2), + ); +}); + +it("takes no nested member for a counter unless it equals the number listed", () => { + const offBy = rows.map((row): TimedCaptureRow => + row[1] === "/api/records?limit=25" && row[2] !== undefined + ? [row[0], row[1], { ...page(SEEDED), meta: { total: 99 } }] + : row, + ); + const state = environmentStateViewOf(timedCaptureEvidence(offBy)); + // A nested total that disagrees with the rows listed shows the line partial and counts nothing. + expect( + state.views.find((view) => view.tool === "get_records"), + ).not.toMatchObject({ counters: expect.arrayContaining(["/meta/total"]) }); +}); diff --git a/src/domain/analysisView/environmentStateListFacts.ts b/src/domain/analysisView/environmentStateListFacts.ts index 84cd8a63184..cee08a3f635 100644 --- a/src/domain/analysisView/environmentStateListFacts.ts +++ b/src/domain/analysisView/environmentStateListFacts.ts @@ -10,6 +10,8 @@ import { collectionPathOf, isObject, listItems, + pointerTo, + pointerTokens, same, scalarText, type JsonObject, @@ -39,18 +41,20 @@ export const listFacts = ( minted.add(name); items.forEach((item) => union.add(item)); const parent = plan.pointer === "" || !isObject(body) ? {} : body; - const counted = Object.keys(parent).filter( - (name) => isItemTotal(name) && countOf(parent[name]) !== undefined, + const counted = itemTotals(parent, plan.pointer).filter( + ([, value]) => countOf(value) !== undefined, ); counting.set( record.ordinal, - counted.filter((name) => parent[name] === items.length), + counted + .filter(([, value]) => value === items.length) + .map(([counter]) => counter), ); // Only a line that pages at most can hold its whole collection; a total that differs from // the number listed, or a next page, shows it is partial. if ( !startsAtBeginning(record.query) || - counted.some((name) => countOf(parent[name]) !== items.length) || + counted.some(([, value]) => countOf(value) !== items.length) || Object.keys(parent).some((name) => continues(name, parent[name])) ) return; @@ -66,6 +70,25 @@ export const listFacts = ( return { whole, counters, minted: [...minted].sort(compare) }; }; +/** + * A list envelope's item totals, each by its counter: a top-level member's name, or the pointer to one in a + * top-level object beside the list, such as `/pageInfo/totalRows`. + */ +export const itemTotals = ( + parent: JsonObject, + listPointer: string, +): [counter: string, value: JsonValue | undefined][] => { + const root = pointerTokens(listPointer)[0]; + const totals: [string, JsonValue | undefined][] = []; + for (const [name, value] of Object.entries(parent)) + if (isItemTotal(name)) totals.push([name, value]); + else if (isObject(value) && name !== root) + for (const [inner, count] of Object.entries(value)) + if (isItemTotal(inner)) + totals.push([`${pointerTo(name)}${pointerTo(inner)}`, count]); + return totals; +}; + export const nameTokens = (name: string): string[] => name .split(/[_\-\s]|(?<=[a-z0-9])(?=[A-Z])/u) diff --git a/src/domain/analysisView/environmentStateListQuery.ts b/src/domain/analysisView/environmentStateListQuery.ts index 599859911c1..bc1b37d47ae 100644 --- a/src/domain/analysisView/environmentStateListQuery.ts +++ b/src/domain/analysisView/environmentStateListQuery.ts @@ -4,14 +4,13 @@ import { literalSubstringPredicate } from "../analysisSearch.js"; import { directionOf, orderRole } from "./environmentStateOrderParameters.js"; import { isObject, - pointerTo, renderStateList, - replaceAt, scalarText, type JsonObject, type StateEntity, type StateListView, } from "./environmentStateRules.js"; +import { counterAt, withCounter } from "./environmentStateCounters.js"; /** What one list query parameter does to a list, learned from the recorded lines it explains. */ export type QueryParameter = @@ -599,15 +598,15 @@ export const renderQueryList = ( total: number, ): JsonValue => view.query.totals.reduce( - (body, name) => - isObject(base) && - Object.hasOwn(base, name) && - queryTotalCount(base[name]) !== undefined - ? replaceAt( + (body, name) => { + const recorded = counterAt(base, name); + return queryTotalCount(recorded) === undefined + ? body + : withCounter( body, - pointerTo(name), - typeof base[name] === "string" ? String(total) : total, - ) - : body, + name, + typeof recorded === "string" ? String(total) : total, + ); + }, renderStateList(view, base, items), ); diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index 5c68157fb82..e8bd3e3c7a9 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -8,6 +8,7 @@ import { type ClockFormat, } from "./environmentStateWriteValues.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; +import { counterAt, withCounter } from "./environmentStateCounters.js"; /** How records are ordered: by recorded start time, or by record order when any start time is missing. */ export type StateTimeline = "recorded-start-time" | "record-order"; @@ -690,8 +691,8 @@ export const renderStateList = ( const listed = listItems(base, view.pointer)?.length; return view.counters.reduce( (body, name) => - at(base, pointerTo(name)) === listed - ? replaceAt(body, pointerTo(name), items.length) + counterAt(base, name) === listed + ? withCounter(body, name, items.length) : body, replaceAt(base, view.pointer, [...items]), ); diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index a077c205afc..559e4b15432 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -83,7 +83,7 @@ const listQuerySchema = z.strictObject({ totals: z .array(z.string()) .describe( - "Observed envelope members with reproducible counts of every match before paging; absent or unknown representations stay recorded.", + "Observed envelope members with reproducible counts of every match before paging, named as counters are; absent or unknown representations stay recorded.", ), }); const checkedSchema = z @@ -182,7 +182,9 @@ const viewSchema = z.discriminatedUnion("shape", [ ), counters: z .array(z.string()) - .describe("Envelope members that count the listed entities."), + .describe( + "Envelope members that count the listed entities: a top-level member's name, or a JSON pointer to one in a top-level object beside the list (`/pageInfo/totalRows`).", + ), query: listQuerySchema .optional() .describe( From 65ba0354aff8d79e527ac2a42cefbba84d0ae2ae Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:42:16 -0700 Subject: [PATCH 34/68] fix(environment): take a created entity's nested clocks from its read-back After a create's generated values pass, its stored nested clocks take the instants the first later read of the entity shows, as an update's already do, so a create whose response and read spell the clock differently is confirmed. Co-Authored-By: Claude Opus 5.5 --- .../environmentStateWriteCreate.ts | 11 ++++++- .../environmentStateWriteEffects.ts | 2 +- .../environmentStateWrites.test.ts | 29 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index f1779fde0fa..7ecd3be8881 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -18,6 +18,7 @@ import { envelopeMember, envelopeOf, isOpaqueToken, + restampedFields, variedMembers, } from "./environmentStateWriteStamps.js"; import { @@ -33,6 +34,7 @@ import { built, callOf, fail, + itemReads, refuse, requestObject, retainFixed, @@ -476,7 +478,14 @@ export const applyCreate = ( return recorded(); } takeSequences(draft, { collection, fields: fields.value }); - const inserted = insertCreated(context, draft, entity(fields.value, id)); + // The call's own values follow the forms serving generates; the state holds a nested clock as the read-back restamped it, as an update's. + const stored = restampedFields( + searchFrom(context, step), + itemReads(context, { type, idField, collection, id }), + fields.value, + draft.plan.rules, + ); + const inserted = insertCreated(context, draft, entity(stored, id)); return { kind: "applied", targets: [inserted, collectionTarget(type, collection)], diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index b833fce1897..426d0ecaccb 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -246,7 +246,7 @@ export const searchFrom = (context: EffectContext, step: WriteStep) => ({ }); /** The later item reads of the entity a write resolved, as a forward search finds them. */ -const itemReads = ( +export const itemReads = ( context: EffectContext, entity: { readonly type: string; diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 2d61cfd82f9..d55aaee1d72 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1964,6 +1964,35 @@ describe("values an application stamps", () => { ]), }); }); + + it("serves creates whose read-backs store a nested clock at another instant than their responses spell", () => { + // Each response stamps the edit in milliseconds; its read-back stores microseconds a few milliseconds earlier. + const card = (id: number, seconds: number, at: string) => ({ + id, + name: `Card ${String(id)}`, + edit: { at, by: "rea" }, + }); + const answered = (seconds: number) => + new Date(Date.parse(bookClock(seconds)) + 30).toISOString(); + const stored = (seconds: number, micro: string) => + `${bookClock(seconds).slice(0, -1)}.${micro}Z`; + const state = stateOf([ + ["GET", "/api/cards", [FIRST_CARD, SECOND_CARD]], + ["GET", "/api/cards/1", FIRST_CARD], + ["GET", "/api/cards/2", SECOND_CARD], + ["POST", "/api/cards", card(3, 3, answered(3)), 201, { name: "Card 3" }], + ["GET", "/api/cards/3", card(3, 3, stored(3, "020123"))], + ["POST", "/api/cards", card(4, 5, answered(5)), 201, { name: "Card 4" }], + ["GET", "/api/cards/4", card(4, 5, stored(5, "021456"))], + ]); + expect(planOf(state, "post_cards")).toMatchObject({ + served: true, + checked_record_ordinals: [4, 6], + rules: expect.arrayContaining([ + expect.objectContaining({ field: "edit", rule: "nested-clock" }), + ]), + }); + }); }); /** A book with tags, as an application that keeps tags as a set lists them. */ From 9d0dc27c6e7a8bac5e63d12c5f0448d19725ed11 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:42:33 -0700 Subject: [PATCH 35/68] fix(environment): import the compare tool definition as a type Co-Authored-By: Claude Opus 5.5 --- src/application/environment/environmentCompare.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/application/environment/environmentCompare.ts b/src/application/environment/environmentCompare.ts index ccde948387b..b377c774013 100644 --- a/src/application/environment/environmentCompare.ts +++ b/src/application/environment/environmentCompare.ts @@ -54,7 +54,7 @@ import { environmentToolAnswer, type EnvironmentToolAnswer, } from "./environmentToolAnswer.js"; -import { type EnvironmentToolDefinition } from "./environmentTools.js"; +import type { EnvironmentToolDefinition } from "./environmentTools.js"; import { same } from "../../domain/analysisView/environmentStateRules.js"; /** One probe capture file: its label for the report and its parsed JSON. */ From c56728186b5e5cb045fa3b88047377317eff0cee Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:55:43 -0700 Subject: [PATCH 36/68] docs(environment): describe the new write rules and trim repeated parsing The environment and capture docs describe sorted arrays, per-response members, nested counters, item actions, bulk writes, the new write rules and refusals, and their known limits. `_order` is a direction only. Sorted-array retries and the per-response scan parse only the reads they need, and identifier words come from one helper. Co-Authored-By: Claude Opus 5.5 --- docs/agent-environments.md | 61 ++++++++++-- docs/web-network-captures.md | 39 +++++--- .../analysisView/environmentStateGate.ts | 10 +- .../analysisView/environmentStateListFacts.ts | 10 +- .../environmentStateOrderParameters.test.ts | 11 +++ .../environmentStateOrderParameters.ts | 10 +- .../environmentStateQueryCalls.ts | 10 +- .../environmentStateResponseMembers.ts | 99 ++++++++++++------- .../analysisView/environmentStateWords.ts | 6 ++ .../environmentStateWriteSorted.ts | 2 + 10 files changed, 172 insertions(+), 86 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWords.ts diff --git a/docs/agent-environments.md b/docs/agent-environments.md index a25eaef6f1c..398c546c3d9 100644 --- a/docs/agent-environments.md +++ b/docs/agent-environments.md @@ -446,6 +446,14 @@ An item or list view that always spells a clock field otherwise than the entity's stored value names that spelling in `clock_formats`, and a value it never recorded, such as a created entity's clock, is rendered in it: a list that writes `+00:00` where item reads write `Z` lists a new entity the same way. +A view that names a field in `sorted_arrays` lists that string array sorted, as +a read-back showed the application does, while the state keeps it in the order +it was written, so a write's own answer echoes it. Members a view names in +`per_response_members`, such as a request id each response mints, keep the +value its recording carried. A list's `counters` and `query.totals` are +top-level members or members one level down in a paging object +(`/pageInfo/totalRows`); either is set to the number listed or matched, and +members beside it such as `isLastPage` stay as recorded. A list or document call that names no checked line, including a line recorded after a write or with other query values, answers from the recording. Every @@ -475,20 +483,38 @@ tools are not served, so no call claims a change it does not make; each one's plan states why in its `reason`. A served write changes the live state, which every MCP session and `data/get` then see: -| Effect | Call | -| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `create` | Adds an entity to the collection the path names, built from the observed entity with each ruled field taken from the call or generated, at the plan's `insert` position. A plan tied to its exemplar's collection writes only there. | -| `update` | Sets the sent members on the entity the path names, constants for members accepted only with their recorded value, and the clock, nested clock, increment, slug, stamp, derived, unique and renewed changes the plan models. | -| `delete` | Removes the entity the path names. | -| `document` | Merges the body into the plan's document object, or replaces it for `PUT`. | +| Effect | Call | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `create` | Adds an entity to the collection the path names, built from the observed entity with each ruled field taken from the call or generated, at the plan's `insert` position. A plan tied to its exemplar's collection writes only there. | +| `update` | Sets the sent members on the entity the path names, constants for members accepted only with their recorded value, and the clock, nested clock, increment, slug, stamp, derived, unique and renewed changes the plan models. | +| `update` (action) | A `POST`, `PUT` or `PATCH` to an item path plus an action segment (`/{type}/{id}/archive`) sets, on the entity before the segment, each scalar the recorded calls showed the action set (`set`), with any sent members; it is served only when a recorded call found those fields already set, so a toggle never is. | +| `delete` | Removes the entity the path names. | +| bulk `update` or `delete` | A `DELETE`, `PUT` or `PATCH` at a collection, or a `POST` to it plus `delete`, `remove` or `destroy`, applies its effect to every entity the body names, as recorded: an array of ids or of objects carrying the id field, at the root or as the body's one array member (`{"IDs": […], "Read": true}`). | +| `document` | Merges the body into the plan's document object, or replaces it for `PUT`. | + +An update's unsent changes follow the plan's rules. A `held-clock` is a clock +the client sends back as it read it and the application stamps anew (Ghost's +`updated_at`): the call must send the entity's value and the field takes the +write's clock. A `nested-clock` sets the clocks inside an object the entity +holds, in that object's recorded format. A `stamp` writes the acting user +the entity already names under its `created…by` counterpart into a +`modified…by` or `updated…by` field. A `derived` field takes a value showing +the one sent member's text that the entity stores nowhere (a field Ghost +derives from `html`), only with that member's recorded value. An action's +`set` rule sets a scalar to the value the recorded calls left it at. Its answer has the status and content type of the plan's recorded response, with the written entity or its identity rendered in, no body, or the recorded body. A call whose body is not an object, sends a member the capture did not show stored, sends a fixed member with another value or a member of another JSON type, or lacks a required member is a tool error naming the accepted -members; so is a rendered answer missing a field the recorded response -carried, and an update or delete of an entity the state does not hold answers +members; so is a call sending query parameters other than the exemplar's (they +may change what the body does), a body not wrapped in the exemplar's envelope +(Ghost's `{"posts": [{…}]}`), a bulk call naming an id the state does not hold, +a `held-clock` member sent with another value than the entity holds, a call +sending a `derived` rule's member to an entity that does not hold the value the +recorded call found, a nested clock on an entity holding no such object, and a +rendered answer missing a field the recorded response carried, and an update or delete of an entity the state does not hold answers the recorded 400, 404 or 410 of the tool or of an item view of the type, if any. A refused call leaves the state unchanged. Values a write generates are deterministic: the clock starts at `write_clock` and advances one second per @@ -497,7 +523,8 @@ largest they generated, and UUIDs and tokens derive from the state Evidence id, tool, field and write count, skipping held values. `data/reset` and `data/add` restart the clock, counter and sequences, so the same calls after a reset give the same state. Answers carry `state: {"source": "state", "view": -"create" | "update" | "delete", …}` or `"document-write"`. +"create" | "update" | "delete", …}` or `"document-write"`; a bulk answer adds +`ids`, every entity it wrote in body order, with `id` naming the first. The data plane serves three JSON-RPC methods: @@ -652,6 +679,22 @@ after an update and referential rules on delete are not modelled. An exported bundle carries no state file: its server derives the state at startup, as the export does to predict what it serves. +Known limits of served writes: + +- A recorded view answers from its recordings after a served write: Mailpit's + `get_messages`, recorded as `list-differs`, still lists a message a served + delete removed. +- Served n8n workflow updates accept any `versionId`, while served Ghost post + updates require `updated_at` to match the entity (a `held-clock`). +- A slug derived from a title can repeat across served creates with the same + title, where the application would make it unique. +- A served create's sequence id is the state's next value, not the gaps an + application's own sequence would leave. +- Nested clocks are served in the spelling of the write's own response, which + can differ from what a later read of the application shows. +- A served write to an entity that a replayed (unserved) create made answers + as for a missing entity, since the state never held it. + ## Export a bundle `rea environment-export` writes the same pair as a bundle folder the agentenv diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index b5b4d5568a2..c9ac9cf3b2e 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -604,7 +604,11 @@ repeated reads of one full request line whose list membership changes across a write, including transitions to or from an empty list, or whose entity fields are added or removed. A type whose reads still disagree keeps every tool a recorded view with reason `fields-differ`. Different query strings remain distinct request lines. Sparse responses do not erase the last observation of a field supplied by another request line. Entities are ordered -by type, collection and first sighting; that order is a list's state order. +by type and collection, and within a collection as the first line that lists +every entity any initial read shows in it and names no sort, direction or +random parameter (`random`, `rand`, `shuffle`, `seed`) lists them; a collection +without such a line keeps its entities' earliest sightings. That order is a +list's state order. Every entity cites its `record_ordinals`. `views` lists one plan per read tool in tool order: @@ -644,22 +648,25 @@ collection, what each query parameter does, and names the result in `query`. Each such line is explained by the first combination of roles that lists exactly what it recorded from the collection's initial entities: -| Role | Parameter | Effect | -| ----------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `filter` | any, on a `field` every listed item holds the value in | entities whose field equals the value as text, or whose array field holds it directly or as an object's `id`, `slug` or `name` | -| `search` | `q`, `query`, `search`, `searchTerm`, `term`, `keyword`(s) | entities with one of `fields` containing the value, ignoring case; the fields are those it matched in the listed items, URLs only where nothing else matched | -| `sort` | `order`, `orderBy`, `ordering`, `sort`, `sortBy` (and `_by` spellings) | ordered by the field the value names (`name`, `-name`, `name:desc`, `name-ASC`): numbers by value, text ignoring case, null last ascending, ties in state order | -| `direction` | `dir`, `direction`, `order`, `orderDirection`, `sortDir`, `sortOrder` with `asc` or `desc` | the sort's direction | -| `limit` | `limit`, `per_page`, `perPage`, `page_size`, `size`, `count`, `take`, `itemsPerPage` | page size; zero or a negative value lists every match | -| `offset` | `offset`, `start`, `_start`, `skip` | matches skipped before the page | -| `page` | `page` | page number, counted from `first` (1 or 0, whichever explains the line) | -| `inert` | any | changes nothing for its recorded `values`; other values are not computed | - -Lines that disagree on a parameter's role drop it, inert values gather and -search fields unite. `query.record_ordinals` are the lines the merged roles +| Role | Parameter | Effect | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `filter` | any other, on a `field` every listed item holds the value in; one not named like the field (`shelf`, or `shelf_id`, for `shelf`) stands only when lines giving it two different values agree on it | entities whose field equals the value as text, or whose array field holds it directly or as an object's `id`, `slug` or `name` | +| `search` | `q`, `query`, `search`, `searchTerm`, `term`, `keyword`(s) | entities with one of `fields` containing the value, ignoring case; the fields are those it matched in the listed items, URLs only where nothing else matched; a term that matched no field leaves the parameter inert until another line's term does | +| `sort` | a name asking for an order in any common spelling: `sort`, `_sort`, `sort[]`, `sort[0][field]`, `sorters[...]`, `sortBy`, `sort-column`, `sortKey`, `order`, `orderBy`, `ordering` | ordered by the field the value names (`name`, `-name`, `name:desc`, `name-ASC`): numbers by value, text ignoring case, null last ascending, ties in state order | +| `direction` | a direction name (`dir`, `direction`, `sortDir`, `sortOrder`, `sortDirection`, `order_direction`, json-server's `_order`, and `order`) given `asc`, `desc`, `ascending` or `descending`; given anything else, `order` is a `sort` and the others are ordinary parameters | the sort's direction | +| `limit` | `limit`, `per_page`, `perPage`, `page_size`, `size`, `count`, `take`, `itemsPerPage` | page size; zero or a negative value lists every match | +| `offset` | `offset`, `start`, `_start`, `skip` | matches skipped before the page | +| `page` | `page` | page number, counted from `first` (1 or 0, whichever explains the line) | +| `inert` | any that names no order or direction; never a true `reverse`, or a paging value that is not a safe integer | changes nothing for its recorded `values`; other values are not computed | + +No two parameters of one call take the same `sort`, `direction` or paging role, +and a line with more than 12 query parameters is left unexplained. Lines that +disagree on a parameter's role drop it, inert values gather and search fields +unite. `query.record_ordinals` are the lines the merged roles reproduce, envelope and fields included, and `query.totals` the envelope -members that count every match before paging on each of them (a -`number`-of-items member counts the page). The roles are inferences from the +members that count every match before paging on each of them, top-level or one +level down in a paging object (`/pageInfo/totalRows`); a `number`-of-items +member counts the page. The roles are inferences from the recorded lines; a line they do not reproduce keeps its recorded members. `writes` lists one plan per tool whose request may change state, in tool diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index 1b0ccf46b34..c6510285ad3 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -1,3 +1,4 @@ +import { identifierWords } from "./environmentStateWords.js"; import type { JsonValue } from "../jsonValue.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { @@ -37,11 +38,7 @@ import { mintedFor, type MintedMembers, } from "./environmentStateResponseMembers.js"; -import { - itemTotals, - listFacts, - nameTokens, -} from "./environmentStateListFacts.js"; +import { itemTotals, listFacts } from "./environmentStateListFacts.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; /** A successful item read first recorded after the initial reads, with the members its object carries. */ @@ -362,7 +359,8 @@ const listQuery = ( // Absence says nothing about another envelope's counter. Only a present // count that disagrees invalidates the shared total interpretation. for (const [name, count] of counts.get(line.ordinal) ?? []) { - if (nameTokens(counterPath(name).at(-1)!).includes("number")) continue; + if (identifierWords(counterPath(name).at(-1)!).includes("number")) + continue; if (count === total) totals.add(name); else contradicted.add(name); } diff --git a/src/domain/analysisView/environmentStateListFacts.ts b/src/domain/analysisView/environmentStateListFacts.ts index cee08a3f635..885c7358387 100644 --- a/src/domain/analysisView/environmentStateListFacts.ts +++ b/src/domain/analysisView/environmentStateListFacts.ts @@ -1,3 +1,4 @@ +import { identifierWords } from "./environmentStateWords.js"; import type { JsonValue } from "../jsonValue.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import type { StateGateContext, StatePlan } from "./environmentStateGate.js"; @@ -89,16 +90,11 @@ export const itemTotals = ( return totals; }; -export const nameTokens = (name: string): string[] => - name - .split(/[_\-\s]|(?<=[a-z0-9])(?=[A-Z])/u) - .map((token) => token.toLowerCase()); - const LISTED_NOUNS = new Set(["elements", "entries", "items", "results"]); /** Item totals, including compact `totalcount`/`itemcount` and `numberOfElements`; page counts and account IDs are excluded. */ export const isItemTotal = (name: string): boolean => { - const tokens = nameTokens(name); + const tokens = identifierWords(name); return ( (tokens.some( (token) => @@ -134,7 +130,7 @@ const CONTINUATION_NAMES = new Set([ /** A top-level `has_more`, `next` or next-page token member that says more items follow. */ const continues = (name: string, value: JsonValue | undefined): boolean => - CONTINUATION_NAMES.has(nameTokens(name).join("")) && + CONTINUATION_NAMES.has(identifierWords(name).join("")) && value !== undefined && value !== null && value !== false && diff --git a/src/domain/analysisView/environmentStateOrderParameters.test.ts b/src/domain/analysisView/environmentStateOrderParameters.test.ts index 419dc2b0eeb..2c21588ed80 100644 --- a/src/domain/analysisView/environmentStateOrderParameters.test.ts +++ b/src/domain/analysisView/environmentStateOrderParameters.test.ts @@ -4,6 +4,7 @@ import { appliesOrder, directionOf, namesDirection, + orderRole, } from "./environmentStateOrderParameters.js"; describe("parameters that ask for an order", () => { @@ -43,6 +44,7 @@ describe("directions", () => { "order_direction", "sort_order", "reverse", + "_order", ])("reads %s as naming only a direction", (name) => { expect(namesDirection(name)).toBe(true); }); @@ -54,6 +56,15 @@ describe("directions", () => { }, ); + it("takes json-server's `_order` as a direction only, and `order` given a field as the sort", () => { + expect([ + orderRole("_order", "DESC"), + orderRole("_order", "title"), + orderRole("order", "title"), + orderRole("order", "asc"), + ]).toEqual(["direction", undefined, "sort", "direction"]); + }); + it("reads a direction in short or long spelling", () => { expect( ["ASC", "descending", "Ascending", "newest"].map(directionOf), diff --git a/src/domain/analysisView/environmentStateOrderParameters.ts b/src/domain/analysisView/environmentStateOrderParameters.ts index 612f3c7df82..8b85345efb4 100644 --- a/src/domain/analysisView/environmentStateOrderParameters.ts +++ b/src/domain/analysisView/environmentStateOrderParameters.ts @@ -1,3 +1,4 @@ +import { identifierWords } from "./environmentStateWords.js"; /** Parameter names a list query reads as the field it sorts by. */ export const SORT: ReadonlySet = new Set([ "order", @@ -61,11 +62,7 @@ const DIRECTION_ONLY = new Set( /** A parameter name's words, bracketed parts dropped: `sort[0][field]` is `sort`, `sortKey` is `sort`, `key`. */ const wordsOf = (name: string): string[] => - name - .replace(/\[[^\]]*\]/gu, "") - .split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/u) - .filter((word) => word.length > 0) - .map((word) => word.toLowerCase()); + identifierWords(name.replace(/\[[^\]]*\]/gu, "")); /** Whether a query parameter asks for an order, in any common spelling: `sort[0][field]`, `_sort`, `sort-direction`, `sortKey`, `orderBy`, `reverse`. */ export const appliesOrder = (name: string): boolean => { @@ -79,11 +76,12 @@ export const appliesOrder = (name: string): boolean => { ); }; -/** Whether a parameter names only the direction of an order, as `dir`, `sortDirection` or `reverse` do, not the field it sorts by. */ +/** Whether a parameter names only the direction of an order, as `dir`, `sortDirection`, `reverse` or json-server's `_order` beside `_sort` do, not the field it sorts by. */ export const namesDirection = (name: string): boolean => { const words = wordsOf(name); const last = words.at(-1); return ( + name === "_order" || DIRECTION_ONLY.has(words.join("")) || last === "dir" || last === "direction" || diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 93013590923..44da6e7b2be 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -1,3 +1,4 @@ +import { identifierWords } from "./environmentStateWords.js"; import type { JsonValue } from "../jsonValue.js"; import { changesState, @@ -13,13 +14,8 @@ import { import { isAbsence } from "./environmentStateWriteChecks.js"; import { prefixRelated } from "./environmentStateWriteRules.js"; -/** The words of a segment or operation name: split on `_`, `-`, `.` and camelCase, in lower case. */ -const words = (text: string): string[] => - text - .split(/[_\-.\s]+/u) - .flatMap((part) => part.split(/(?<=[a-z0-9])(?=[A-Z])/u)) - .map((word) => word.toLowerCase()) - .filter((word) => word.length > 0); +/** The words of a segment or operation name. */ +const words = identifierWords; /** Path words that name a lookup rather than a change. */ const QUERY_WORDS = new Set([ diff --git a/src/domain/analysisView/environmentStateResponseMembers.ts b/src/domain/analysisView/environmentStateResponseMembers.ts index 3d5d115999a..a6d1414198b 100644 --- a/src/domain/analysisView/environmentStateResponseMembers.ts +++ b/src/domain/analysisView/environmentStateResponseMembers.ts @@ -9,12 +9,11 @@ import { type JsonObject, type StateRecordFacts, } from "./environmentStateRules.js"; -import { readClock } from "./environmentStateWriteValues.js"; +import { isUuid, readClock } from "./environmentStateWriteValues.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; /** Fewest repeats, across the capture, that show a member minted on every response rather than changed once. */ const MINIMUM_REPEATS = 2; -const UUID = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu; /** The paths whose repeated reads showed each member minted anew, so only views of those paths leave it out. */ export type MintedMembers = ReadonlyMap>; @@ -32,7 +31,7 @@ const mintedValues = ( if ( typeof value === "string" && value.length <= 64 && - (UUID.test(value) || readClock(value) !== undefined) + (isUuid(value) || readClock(value) !== undefined) ) values.set(name, value); return values; @@ -59,6 +58,46 @@ const tally = ( else entry.same += 1; }; +/** The successful GET reads that repeat their line with no write between, as line, earlier and later read: only those can show a member minted, so only those are parsed. */ +const repeatPairs = ( + input: Pick< + Parameters[0], + "records" | "writeWithin" | "retain" + >, +): (readonly [string, StateRecordFacts, StateRecordFacts])[] => { + const previous = new Map(); + const pairs: (readonly [string, StateRecordFacts, StateRecordFacts])[] = []; + for (const record of input.records) { + if (record.method !== "GET" || !succeeded(record)) continue; + const line = `${record.path}?${record.query ?? ""}`; + const earlier = previous.get(line); + input.retain( + earlier === undefined ? ENTRY_BYTES * 2 + textBytes(line.length) : 0, + ); + previous.set(line, record); + if (earlier === undefined || input.writeWithin(earlier, record)) continue; + input.retain(ENTRY_BYTES * 3); + pairs.push([line, earlier, record]); + } + return pairs; +}; + +/** The members minted per path: differing on every repeat there, and across the capture on enough repeats and never the same. */ +const mintedOf = ( + byPath: ReadonlyMap, + byName: ReadonlyMap, +): Map> => { + const minted = new Map>(); + for (const [key, counts] of byPath) { + const [path, name] = JSON.parse(key) as [string, string]; + const overall = byName.get(name)!; + if (counts.same > 0 || counts.differ === 0) continue; + if (overall.same > 0 || overall.differ < MINIMUM_REPEATS) continue; + minted.set(path, (minted.get(path) ?? new Set()).add(name)); + } + return minted; +}; + /** * Per path, the top-level members each response mints: a UUID or clock that differs on every repeat of that path's * successful GET lines with no write between, where the member also differed on at least two repeats in the @@ -80,48 +119,38 @@ export const perResponseMembers = (input: { readonly checkpoint: () => () => void; }): MintedMembers => { const release = input.checkpoint(); - const latest = new Map< + const pairs = repeatPairs(input); + // Each read is parsed once: a line's later read is kept for the next pair of that line. + const parsed = new Map< string, - { record: StateRecordFacts; values: Map } + { ordinal: number; values: Map | undefined } >(); + const valuesOf = (line: string, record: StateRecordFacts) => { + const kept = parsed.get(line); + if (kept?.ordinal === record.ordinal) return kept.values; + const values = input.withBody(record.ordinal, mintedValues); + for (const [name, value] of values ?? []) + input.retain(ENTRY_BYTES + textBytes(name.length + value.length)); + return values; + }; const byPath = new Map(); const byName = new Map(); - for (const record of input.records) { - if (record.method !== "GET" || !succeeded(record)) continue; - const values = input.withBody(record.ordinal, mintedValues); - if (values === undefined) continue; - const line = `${record.path}?${record.query ?? ""}`; - const earlier = latest.get(line); - input.retain( - (earlier === undefined ? ENTRY_BYTES * 2 + textBytes(line.length) : 0) + - [...values].reduce( - (bytes, [name, value]) => - bytes + ENTRY_BYTES + textBytes(name.length + value.length), - 0, - ), - ); - latest.set(line, { record, values }); - if (earlier === undefined || input.writeWithin(earlier.record, record)) - continue; + for (const [line, earlier, record] of pairs) { + const before = valuesOf(line, earlier); + const after = valuesOf(line, record); + parsed.set(line, { ordinal: record.ordinal, values: after }); + if (before === undefined || after === undefined) continue; const path = normalizedPath(record.path); - for (const name of new Set([...earlier.values.keys(), ...values.keys()])) { + for (const name of new Set([...before.keys(), ...after.keys()])) { // A member minted-looking on one side only is not minted on every response. - const before = earlier.values.get(name); - const after = values.get(name); - const differ = - before !== undefined && after !== undefined && before !== after; + const was = before.get(name); + const now = after.get(name); + const differ = was !== undefined && now !== undefined && was !== now; tally(byPath, JSON.stringify([path, name]), differ, input.retain); tally(byName, name, differ, input.retain); } } - const minted = new Map>(); - for (const [key, counts] of byPath) { - const [path, name] = JSON.parse(key) as [string, string]; - const overall = byName.get(name)!; - if (counts.same > 0 || counts.differ === 0) continue; - if (overall.same > 0 || overall.differ < MINIMUM_REPEATS) continue; - minted.set(path, (minted.get(path) ?? new Set()).add(name)); - } + const minted = mintedOf(byPath, byName); release(); for (const [path, names] of minted) input.retain( diff --git a/src/domain/analysisView/environmentStateWords.ts b/src/domain/analysisView/environmentStateWords.ts new file mode 100644 index 00000000000..ad4cc11e40f --- /dev/null +++ b/src/domain/analysisView/environmentStateWords.ts @@ -0,0 +1,6 @@ +/** An identifier's words in lower case: split at every run of other characters and at each lower-to-upper case step (`sortKey`, `has_more`, `query-history`). */ +export const identifierWords = (text: string): string[] => + text + .split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])/u) + .filter((word) => word.length > 0) + .map((word) => word.toLowerCase()); diff --git a/src/domain/analysisView/environmentStateWriteSorted.ts b/src/domain/analysisView/environmentStateWriteSorted.ts index e10b340c543..8fffea31a38 100644 --- a/src/domain/analysisView/environmentStateWriteSorted.ts +++ b/src/domain/analysisView/environmentStateWriteSorted.ts @@ -145,6 +145,8 @@ export class SortedArrays { ): CheckOutcome { const failed = read.outcome; if (view.shape !== "item" && view.shape !== "list") return failed; + // A view with no candidate left has nothing to note or retry, so its read is never parsed. + if (!this.#candidates.has(view.tool)) return failed; const shown = this.#shown(view, read.record); this.#ruleOut(view.tool, shown); const candidates = this.#candidates.get(view.tool)?.fields; From 7ef08a3459ce038513fabb81fa1a4fa09a1e7332 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 10:59:40 -0700 Subject: [PATCH 37/68] fix(environment): confirm no update whose clocks or fields the evidence cannot show it writing An unsent clock an update left in the second it ran keeps the update unconfirmed until another call shows the clock stamped. A field the state lacks that the read and the update's response both show is the update's change, so without a rule for it the read confirms nothing. A modified-by name stamp brings its id sibling along, and created entities are indexed by id when a failed read is checked for embeds. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-writes/spec.md | 24 ++- .../EnvironmentStateWriteSimulation.ts | 3 +- .../environmentStateWriteBlame.test.ts | 18 ++ .../environmentStateWriteBlame.ts | 176 +++++++++++++----- .../environmentStateWriteCalls.ts | 11 +- .../environmentStateWriteChanges.ts | 136 ++++++++++++++ .../environmentStateWriteEffects.ts | 27 ++- .../environmentStateWriteExplain.test.ts | 3 +- .../environmentStateWriteExplain.ts | 127 ++----------- .../environmentStateWriteStamps.test.ts | 83 ++++++++- .../environmentStateWriteStamps.ts | 36 +++- .../environmentStateWriteVerdict.ts | 12 +- .../environmentStateWrites.test.ts | 59 ++++++ 13 files changed, 536 insertions(+), 179 deletions(-) create mode 100644 src/domain/analysisView/environmentStateWriteChanges.ts diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 907ab8ea167..8710e6122ad 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -270,8 +270,13 @@ least one. A sent clock the call left as it was, stored in whole seconds and naming the second the call ran in, is a `held-clock` the application stamps anew (Ghost's `updated_at`, which a client sends back as it read it), when it is the only such member the call sent: a call must send it as the entity holds it, -or it is refused, and it is served as the write's clock. A field the exemplar's -update changed without sending it is explained as one of: +or it is refused, and it is served as the write's clock. An unsent clock the +call left as it was, stored in whole seconds and naming the second the call ran +in, cannot show whether the update stamps it, unless it names when the entity +was made (`createdAt`, `row_created_timestamp`): the plan stays `unconfirmed` +until another call shows it stamped, and that call's clock rule then holds +without the first call contradicting it. A field the exemplar's update changed +without sending it is explained as one of: - clock; - a nested clock: an object the entity held whose only changes are clocks @@ -292,7 +297,10 @@ update changed without sending it is explained as one of: `edited…by` or `changed…by` (or `last…`), stored on every call, when the entity already held the value under its `created…by` counterpart (`modifiedByName` and `createdByName`), and the call sent no member naming - the same thing (`modifiedById`); + the same thing (`modifiedById`). The other `…by` field naming the same user + (`modifiedById` beside `modifiedByName`) is stamped with it when the call + showed it at its own `created…by` counterpart's value, even where the entity + lacked it before; - `derived`: when the call sent exactly one member the entity stores nowhere, a value showing that member's text, markup aside (at least 8 characters): a field Ghost derives from the `html` it was sent. The member is accepted only @@ -484,9 +492,13 @@ refuses to answer with. call's response shows every other field it and the read both show (but volatile ones and those other updates wrote) as the read does: serving answers an update from the copy, so a response that shows the entity - otherwise would be answered wrongly. When the read differs on a field the - copy holds that no exercised update wrote, any of the writes may have caused - it, and each is contradicted. + otherwise would be answered wrongly. A field the copy lacks that the read and + an exercised update's response both show, with the same value other than + null, is that update's change: an update whose effect does not hold it is + neither confirmed nor contradicted by the read, and when such changes are + the read's whole difference the entity's own writer is not contradicted. + When the read differs on a field the copy holds that no exercised update + wrote, any of the writes may have caused it, and each is contradicted. - A failed item read whose field newly embeds an entity a create made (an object in the field, or within it, naming it by its id and by another of its strings of 3 or more characters, 8 or more when the id is shorter than 8), diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 0c250d691d6..581853e7f17 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -215,6 +215,7 @@ export class EnvironmentStateWriteSimulation { updates: [], sequences: new Map(), steady: new Set(), + unstamped: new Set(), linked: link.collection, }); } @@ -662,7 +663,7 @@ export class EnvironmentStateWriteSimulation { if (failed.exercised.size === 0) for (const write of this.#log) if ( - write.index > blame.after && + write.index > since && prefixRelated(write.path, failed.record.path) ) this.#drafts.get(write.tool)!.sideEffect = true; diff --git a/src/domain/analysisView/environmentStateWriteBlame.test.ts b/src/domain/analysisView/environmentStateWriteBlame.test.ts index 045989dd047..2b875c01144 100644 --- a/src/domain/analysisView/environmentStateWriteBlame.test.ts +++ b/src/domain/analysisView/environmentStateWriteBlame.test.ts @@ -43,6 +43,24 @@ const createdThenRenamed = ( ]; describe("blame for a failed item read", () => { + it("confirms no update by a read showing a field its response showed and the state lacks, with no rule for it", () => { + const reviewed = (entry: Book): Book => ({ ...entry, reviewedBy: "rea" }); + const rows = createdThenRenamed( + reviewed(RENAMED_THIRD), + reviewed(shelved(RENAMED_THIRD)), + ); + // The shelves no write's answer shows stay the create's to answer for. + expect(planOf(rows, "post_books")).toMatchObject({ + reason: "contradicted", + contradicted_by: 5, + }); + expect(planOf(rows, "patch_books_by_id")).toMatchObject({ + served: false, + reason: "unconfirmed", + contradicted_by: null, + }); + }); + it("contradicts the create that left a field out and serves the update whose own fields the read shows", () => { const rows = createdThenRenamed(RENAMED_THIRD); expect(planOf(rows, "post_books")).toMatchObject({ diff --git a/src/domain/analysisView/environmentStateWriteBlame.ts b/src/domain/analysisView/environmentStateWriteBlame.ts index dfe8b22b171..1bbd2a10601 100644 --- a/src/domain/analysisView/environmentStateWriteBlame.ts +++ b/src/domain/analysisView/environmentStateWriteBlame.ts @@ -46,11 +46,10 @@ export interface BlameFacts { readonly volatileOf: (type: string) => ReadonlySet; } -/** A failed read's attribution: the writes it contradicts and confirms, and the timeline index after which related writes are its side effects. */ +/** A failed read's attribution: the writes it contradicts and those it confirms. */ export interface Blame { readonly contradicted: ReadonlySet; readonly confirmed: readonly string[]; - readonly after: number; } /** A failed item read: its view and target, the state's entity, and the object the read shows. */ @@ -107,11 +106,7 @@ export class FailedReadBlame { const blame = this.#fields(item, failed.exercised); for (const name of blame?.contradicted ?? failed.exercised) contradicted.add(name); - return { - contradicted, - confirmed: blame?.confirmed ?? [], - after: failed.since, - }; + return { contradicted, confirmed: blame?.confirmed ?? [] }; } const rebased = item === undefined ? -1 : (this.#rebased.get(item.target) ?? -1); @@ -122,7 +117,7 @@ export class FailedReadBlame { // A recorded outcome merges what its answer showed, so a required field it left out is still the create's. if (create !== undefined && this.#lacksFields(item!)) contradicted.add(create); - return { contradicted, confirmed: [], after: failed.since }; + return { contradicted, confirmed: [] }; } #item(view: StateView, record: StateRecordFacts): FailedItem | undefined { @@ -280,43 +275,99 @@ const fieldBlame = ( ) ); }; + const lacking = lackingFields(read, shown, writes); const confirmed = [...writes.partial.keys()].filter( - (name) => outcomes.get(name) === true && answered(name), + (name) => + outcomes.get(name) === true && + answered(name) && + !lacking.unruled.has(name), ); + // When updates' changes the state lacks are the read's whole difference, the entity's own writer is not blamed for them. + const owned = + lacking.fields > 0 && + !lacking.unowned && + [...writes.partial.keys()].every( + (name) => confirmed.includes(name) || lacking.unruled.has(name), + ); return { contradicted: [...writes.exercised].filter( - (name) => !confirmed.includes(name), + (name) => + !confirmed.includes(name) && + !lacking.unruled.has(name) && + !(owned && !writes.partial.has(name)), ), confirmed, }; }; -/** Whether a value is or holds an object naming the entity by its id and by one more of its strings, a long one when the id is short. */ -const embeds = ( - value: JsonValue | undefined, +/** + * Fields a failed read shows that the state's entity lacks: one an exercised update's response + * shows with the same value, not null, is that update's change, and an update whose effect does not + * hold it changed something no rule models, so the read confirms it no more than it contradicts it. + */ +const lackingFields = ( + read: { readonly object: JsonObject; readonly volatile: ReadonlySet }, + shown: JsonObject, + writes: { + readonly partial: ReadonlyMap; + readonly responses: ReadonlyMap; + }, +): { + readonly fields: number; + readonly unowned: boolean; + readonly unruled: Set; +} => { + const fields = Object.keys(read.object).filter( + (field) => !Object.hasOwn(shown, field) && !read.volatile.has(field), + ); + const unruled = new Set(); + let unowned = false; + for (const field of fields) { + const value = read.object[field] ?? null; + const owners = [...writes.partial.keys()].filter((name) => { + const response = writes.responses.get(name); + return ( + value !== null && response !== undefined && same(response[field], value) + ); + }); + if (owners.length === 0) unowned = true; + for (const name of owners) + if (!writes.partial.get(name)!.includes(field)) unruled.add(name); + } + return { fields: fields.length, unowned, unruled }; +}; + +/** Whether an object names the entity by its id and by one more of its strings, a long one when the id is short. */ +const names = ( + item: JsonObject, entity: JsonObject, idField: string, + id: string, ): boolean => { - const id = scalarText(entity[idField]); - if (id === undefined || value === undefined) return false; const length = id.length < EMBED_SHORT_ID_MATCH_LENGTH ? EMBED_SHORT_ID_MATCH_LENGTH : EMBED_MATCH_MIN_LENGTH; - const pending: JsonValue[] = [value]; - for (let item = pending.pop(); item !== undefined; item = pending.pop()) { - if ( - isObject(item) && - scalarText(item[idField]) === id && - Object.entries(item).some( - ([key, member]) => - key !== idField && - typeof member === "string" && - member.length >= length && - entity[key] === member, - ) + return ( + scalarText(item[idField]) === id && + Object.entries(item).some( + ([key, member]) => + key !== idField && + typeof member === "string" && + member.length >= length && + entity[key] === member, ) - return true; + ); +}; + +/** Visit every object a value holds at any depth, itself included. */ +const eachObject = ( + value: JsonValue | undefined, + visit: (item: JsonObject) => void, +): void => { + const pending: JsonValue[] = value === undefined ? [] : [value]; + for (let item = pending.pop(); item !== undefined; item = pending.pop()) { + if (isObject(item)) visit(item); const children = Array.isArray(item) ? item : isObject(item) @@ -324,13 +375,28 @@ const embeds = ( : []; for (const child of children) pending.push(child); } - return false; +}; + +/** Whether a value is or holds an object naming the entity by its id and by one more of its strings. */ +const embeds = ( + value: JsonValue | undefined, + entity: JsonObject, + idField: string, +): boolean => { + const id = scalarText(entity[idField]); + let found = false; + if (id !== undefined) + eachObject(value, (item) => { + found ||= names(item, entity, idField, id); + }); + return found; }; /** * The creates whose entity a failed item read newly embeds: a field the read shows otherwise than the * state holds it, with an object naming the created entity the state's value lacks, is a change the - * create made to another collection (a reverse embed) that serving would not show. + * create made to another collection (a reverse embed) that serving would not show. The created + * entities are found by id, so the read is walked once however many creates there were. */ const embeddingCreates = ( read: { @@ -343,23 +409,47 @@ const embeddingCreates = ( created: CreatedEntity, ) => { readonly fields: JsonObject; readonly idField: string } | undefined, ): string[] => { - const tools = new Set(); + const byId = new Map< + string, + { + readonly tool: string; + readonly fields: JsonObject; + readonly id: string; + }[] + >(); + const idFields = new Set(); for (const entity of created) { - if (tools.has(entity.tool)) continue; if (entity.type === read.type && entity.id === read.entity?.id) continue; const held = heldOf(entity); - if (held === undefined) continue; - for (const [field, value] of Object.entries(read.object)) { - const before = read.entity?.fields[field]; - if ( - !same(before, value) && - embeds(value, held.fields, held.idField) && - !embeds(before, held.fields, held.idField) - ) { - tools.add(entity.tool); - break; + const id = + held === undefined ? undefined : scalarText(held.fields[held.idField]); + if (held === undefined || id === undefined) continue; + idFields.add(held.idField); + const key = `${held.idField}\u0000${id}`; + byId.set(key, [ + ...(byId.get(key) ?? []), + { tool: entity.tool, fields: held.fields, id }, + ]); + } + const tools = new Set(); + if (byId.size === 0) return []; + for (const [field, value] of Object.entries(read.object)) { + const before = read.entity?.fields[field]; + if (same(before, value)) continue; + eachObject(value, (item) => { + for (const idField of idFields) { + const id = scalarText(item[idField]); + for (const entity of id === undefined + ? [] + : (byId.get(`${idField}\u0000${id}`) ?? [])) + if ( + !tools.has(entity.tool) && + names(item, entity.fields, idField, entity.id) && + !embeds(before, entity.fields, idField) + ) + tools.add(entity.tool); } - } + }); } return [...tools]; }; diff --git a/src/domain/analysisView/environmentStateWriteCalls.ts b/src/domain/analysisView/environmentStateWriteCalls.ts index ae7757d5ce6..080e6b382df 100644 --- a/src/domain/analysisView/environmentStateWriteCalls.ts +++ b/src/domain/analysisView/environmentStateWriteCalls.ts @@ -206,6 +206,7 @@ export const rememberCall = ( readonly plan: { readonly rules: readonly FieldRule[] }; readonly updates: UpdateCall[]; readonly steady: Set; + readonly unstamped: Set; }, call: { readonly before: JsonObject; @@ -213,9 +214,15 @@ export const rememberCall = ( readonly sent: JsonObject; readonly kept: readonly string[]; }, + /** Clocks the call left as they were in its own second, which show neither a stamp nor a kept value. */ + sameSecond: readonly string[], ): void => { - const { kept } = call; - const facts = { shown: scalars(call.after), sent: scalars(call.sent), kept }; + const unstamped = new Set(sameSecond); + for (const field of unstamped) draft.unstamped.add(field); + const kept = call.kept.filter((field) => !unstamped.has(field)); + const shown = scalars(call.after); + for (const field of unstamped) shown.delete(field); + const facts = { shown, sent: scalars(call.sent), kept }; retain(64 + jsonTextCodeUnits([...facts.shown, ...facts.sent, kept]) * 2); draft.updates.push(facts); for (const field of steadyFields(draft.plan.rules, call.before, call.after)) diff --git a/src/domain/analysisView/environmentStateWriteChanges.ts b/src/domain/analysisView/environmentStateWriteChanges.ts new file mode 100644 index 00000000000..fffddc528bd --- /dev/null +++ b/src/domain/analysisView/environmentStateWriteChanges.ts @@ -0,0 +1,136 @@ +import type { JsonValue } from "../jsonValue.js"; +import { isObject, same, type JsonObject } from "./environmentStateRules.js"; +import type { FieldRule, WriteCall } from "./environmentStateWriteRules.js"; +import { integerOf, readClock } from "./environmentStateWriteValues.js"; +import { freshUuid, renewedRule } from "./environmentStateWriteGenerated.js"; +import { + derivedRule, + freshToken, + isClockNear, + nestedClockRule, + stampRule, +} from "./environmentStateWriteStamps.js"; + +/** What explaining an update reads: the entity before and after, the call and its method. */ +export interface UpdateEvidence { + readonly before: JsonObject; + readonly after: JsonObject; + readonly call: WriteCall & { readonly body: JsonObject }; + readonly method: string; + readonly idField: string; + readonly id: string; + readonly startMs: number | undefined; + /** Fields covered by a later read view. Missing fields outside that coverage remain unknown. */ + readonly readFields?: readonly string[]; + /** The type's other entities, none of which may hold a value the update generated. */ + readonly others: readonly JsonObject[]; + /** The fields of the observing read's view when that view showed the entity before, so one the entity lacked was added. */ + readonly shown?: readonly string[]; + /** An item action, whose unsent changes take the values it showed. */ + readonly action?: boolean; +} + +/** The rule a field the update changed without sending follows, if any; `slugs` maps each echoed member's slug to the first such member. */ +export const changeRule = ( + evidence: UpdateEvidence, + field: string, + slugs: ReadonlyMap, +): FieldRule | undefined => { + const before = evidence.before[field]; + const after = evidence.after[field]!; + if (readClock(after) !== undefined && isClockNear(after, evidence.startMs)) + return { field, rule: "clock", format: readClock(after)!.format }; + if (freshUuid(evidence, field)) return { field, rule: "unique" }; + // A renamed slug is spelled like a token, so the slug comes first. + const member = typeof after === "string" ? slugs.get(after) : undefined; + if (member !== undefined) return { field, rule: "slug", from: member }; + if (freshToken(evidence, field)) return { field, rule: "unique" }; + const nested = nestedClockRule(field, { before, after }, evidence); + if (nested !== undefined) return nested; + // Child rows only: a single UUID that changed is a reference or a generated value, judged above. + const renewed = + Array.isArray(before) || isObject(before) + ? renewedRule(field, { before, after }, evidence.others) + : undefined; + if (renewed !== undefined) return renewed; + const was = integerOf(before); + if (was !== undefined && integerOf(after) === was + 1) + return { field, rule: "increment" }; + return ( + stampRule(evidence, field) ?? + derivedRule(evidence, field) ?? + actionRule(evidence, field) + ); +}; + +/** An item action sets a scalar it names; a changed object, list or instant is another write's doing or a regenerated value. */ +const actionRule = ( + evidence: UpdateEvidence, + field: string, +): FieldRule | undefined => { + const after = evidence.after[field]!; + return evidence.action === true && + (after === null || typeof after !== "object") && + readClock(after) === undefined + ? { field, rule: "set", value: after } + : undefined; +}; + +/** Whether a clock stored in whole seconds names the second a call started in, where a fresh stamp would read the same. */ +const inCallSecond = ( + value: JsonValue | undefined, + startMs: number | undefined, +): boolean => { + const clock = readClock(value); + return ( + clock !== undefined && + startMs !== undefined && + clock.ms % 1000 === 0 && + clock.subMillisecond === 0 && + Math.abs(clock.ms - startMs) < 1000 + ); +}; + +/** A sent clock the call left as it was, stored in whole seconds and naming the second the call ran in: the application stamps it anew, and the client sent back the one it read. */ +export const heldClock = ( + evidence: UpdateEvidence, + member: string, + sent: JsonValue, +): boolean => + inCallSecond(sent, evidence.startMs) && + same(evidence.before[member], sent) && + same(evidence.after[member], sent); + +/** A field naming when its entity was made (`createdAt`, `row_created_timestamp`), which no update stamps. */ +const CREATION_CLOCK = /creat(?:ed|ion)/iu; + +/** Unsent clocks an update left as they were in the second it ran, other than creation clocks: a fresh stamp would read the same, so the call cannot show whether it stamps them. */ +export const sameSecondClocks = (evidence: UpdateEvidence): string[] => + Object.keys(evidence.after).filter( + (field) => + !CREATION_CLOCK.test(field) && + !Object.hasOwn(evidence.call.body, field) && + Object.hasOwn(evidence.before, field) && + same(evidence.before[field], evidence.after[field]) && + inCallSecond(evidence.after[field], evidence.startMs), + ); + +/** How an update stored a sent member: stamped anew as the one held clock it sent back, echoed, renewed as a fresh UUID, or as a constant. */ +export const sentRule = ( + evidence: UpdateEvidence, + member: string, + held: readonly string[], +): FieldRule => { + const sent = evidence.call.body[member]!; + if (held.length === 1 && held[0] === member) + return { + field: member, + rule: "held-clock", + format: readClock(sent)!.format, + }; + if (same(evidence.after[member], sent)) + return { field: member, rule: "echo" }; + return freshUuid(evidence, member) + ? { field: member, rule: "unique" } + : { field: member, rule: "constant", value: evidence.after[member]! }; +}; diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 426d0ecaccb..62b08c8ca12 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -80,6 +80,8 @@ export interface WriteDraft { readonly linked?: string | undefined; /** Fields an item action's call found already at the value it sets them to. */ readonly steady: Set; + /** Unsent clocks a call left as they were in its own second, which it cannot show it stamps. */ + readonly unstamped: Set; } /** A write observation plus the fields its selected read view actually covers, if any. */ @@ -524,12 +526,12 @@ export const updateEntity = ( if (!written.ok || (disagrees && !unknown)) refuse(draft, step, "unexplained-change"); if (!written.ok || disagrees || unknown) return recorded(); - rememberCall(context.io.retain, draft, { - before: entity.fields, - after: after.object, - sent: body, - kept, - }); + rememberCall( + context.io.retain, + draft, + { before: entity.fields, after: after.object, sent: body, kept }, + explained.unstamped, + ); context.io.retain(64 + jsonTextCodeUnits(written.value) * 2); context.state.put(updatedEntity(entity, written.value)); return appliedUpdate(draft.plan, { targets, target }, entity.fields, { @@ -543,16 +545,21 @@ const contradictsGeneratedClock = ( before: JsonObject, after: JsonObject, rules: readonly FieldRule[], - explained: readonly FieldRule[], + explained: ReturnType, ): boolean => rules.some((rule) => { - if (rule.rule !== "clock" || !Object.hasOwn(after, rule.field)) + // A clock left in the call's own second cannot show whether it advanced. + if ( + rule.rule !== "clock" || + !Object.hasOwn(after, rule.field) || + explained.unstamped.includes(rule.field) + ) return false; const previous = readClock(before[rule.field]); if (previous === undefined) return false; const next = readClock(after[rule.field]); return ( - !explained.some( + !explained.rules.some( (candidate) => candidate.field === rule.field && candidate.rule === "clock", ) || @@ -569,5 +576,5 @@ const contradictsPlan = ( explained: ReturnType, ): boolean => contradictsEarlierCalls(draft, explained.rules) || - contradictsGeneratedClock(before, after, draft.plan.rules, explained.rules) || + contradictsGeneratedClock(before, after, draft.plan.rules, explained) || conflictsWithPlan(draft.plan, explained); diff --git a/src/domain/analysisView/environmentStateWriteExplain.test.ts b/src/domain/analysisView/environmentStateWriteExplain.test.ts index a5b145794a4..a7cb1bd8453 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.test.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.test.ts @@ -11,8 +11,8 @@ import { insertIndex, responseShapeOf, type CreateEvidence, - type UpdateEvidence, } from "./environmentStateWriteExplain.js"; +import type { UpdateEvidence } from "./environmentStateWriteChanges.js"; import { callRenewal, unexplainedRenewals, @@ -397,6 +397,7 @@ it("explains an update's sent members as echoes, constants or the identity", () kinds: [], }, unexplained: [], + unstamped: [], }); }); diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index feb396666eb..b50b821839e 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -34,20 +34,22 @@ import { } from "./environmentStateWriteCopies.js"; import { unexplainedRenewals, - freshUuid, GENERATED, - renewedRule, } from "./environmentStateWriteGenerated.js"; import { createdNestedClock, createdToken, - derivedRule, - freshToken, isClockNear, - nestedClockRule, + pairedStamps, pinnedEchoes, - stampRule, } from "./environmentStateWriteStamps.js"; +import { + changeRule, + heldClock, + sameSecondClocks, + sentRule, + type UpdateEvidence, +} from "./environmentStateWriteChanges.js"; /** What explaining a create reads: the observed entity, the call that wrote it and the entities it joined. */ export interface CreateEvidence { @@ -282,109 +284,6 @@ export const explainCreate = ( }; }; -/** What explaining an update reads: the entity before and after, the call and its method. */ -export interface UpdateEvidence { - readonly before: JsonObject; - readonly after: JsonObject; - readonly call: WriteCall & { readonly body: JsonObject }; - readonly method: string; - readonly idField: string; - readonly id: string; - readonly startMs: number | undefined; - /** Fields covered by a later read view. Missing fields outside that coverage remain unknown. */ - readonly readFields?: readonly string[]; - /** The type's other entities, none of which may hold a value the update generated. */ - readonly others: readonly JsonObject[]; - /** The fields of the observing read's view when that view showed the entity before, so one the entity lacked was added. */ - readonly shown?: readonly string[]; - /** An item action, whose unsent changes take the values it showed. */ - readonly action?: boolean; -} - -/** The rule a field the update changed without sending follows, if any; `slugs` maps each echoed member's slug to the first such member. */ -const changeRule = ( - evidence: UpdateEvidence, - field: string, - slugs: ReadonlyMap, -): FieldRule | undefined => { - const before = evidence.before[field]; - const after = evidence.after[field]!; - if (readClock(after) !== undefined && isClockNear(after, evidence.startMs)) - return { field, rule: "clock", format: readClock(after)!.format }; - if (freshUuid(evidence, field)) return { field, rule: "unique" }; - // A renamed slug is spelled like a token, so the slug comes first. - const member = typeof after === "string" ? slugs.get(after) : undefined; - if (member !== undefined) return { field, rule: "slug", from: member }; - if (freshToken(evidence, field)) return { field, rule: "unique" }; - const nested = nestedClockRule(field, { before, after }, evidence); - if (nested !== undefined) return nested; - // Child rows only: a single UUID that changed is a reference or a generated value, judged above. - const renewed = - Array.isArray(before) || isObject(before) - ? renewedRule(field, { before, after }, evidence.others) - : undefined; - if (renewed !== undefined) return renewed; - const was = integerOf(before); - if (was !== undefined && integerOf(after) === was + 1) - return { field, rule: "increment" }; - return ( - stampRule(evidence, field) ?? - derivedRule(evidence, field) ?? - actionRule(evidence, field) - ); -}; - -/** An item action sets a scalar it names; a changed object, list or instant is another write's doing or a regenerated value. */ -const actionRule = ( - evidence: UpdateEvidence, - field: string, -): FieldRule | undefined => { - const after = evidence.after[field]!; - return evidence.action === true && - (after === null || typeof after !== "object") && - readClock(after) === undefined - ? { field, rule: "set", value: after } - : undefined; -}; - -/** A sent clock the call left as it was, stored in whole seconds and naming the second the call ran in: the application stamps it anew, and the client sent back the one it read. */ -const heldClock = ( - evidence: UpdateEvidence, - member: string, - sent: JsonValue, -): boolean => { - const clock = readClock(sent); - return ( - clock !== undefined && - evidence.startMs !== undefined && - clock.ms % 1000 === 0 && - clock.subMillisecond === 0 && - Math.abs(clock.ms - evidence.startMs) < 1000 && - same(evidence.before[member], sent) && - same(evidence.after[member], sent) - ); -}; - -/** How an update stored a sent member: stamped anew as the one held clock it sent back, echoed, renewed as a fresh UUID, or as a constant. */ -const sentRule = ( - evidence: UpdateEvidence, - member: string, - held: readonly string[], -): FieldRule => { - const sent = evidence.call.body[member]!; - if (held.length === 1 && held[0] === member) - return { - field: member, - rule: "held-clock", - format: readClock(sent)!.format, - }; - if (same(evidence.after[member], sent)) - return { field: member, rule: "echo" }; - return freshUuid(evidence, member) - ? { field: member, rule: "unique" } - : { field: member, rule: "constant", value: evidence.after[member]! }; -}; - /** Each slug an echoed string member slugs to, from the first such member. */ const echoedSlugs = ( body: JsonObject, @@ -406,6 +305,8 @@ export const explainUpdate = ( readonly rules: FieldRule[]; readonly body: WriteBody; readonly unexplained: string[]; + /** Unsent clocks left as they were in the call's own second, which the call cannot show it stamps. */ + readonly unstamped: string[]; } => { const { body } = evidence.call; const rules: FieldRule[] = []; @@ -454,6 +355,7 @@ export const explainUpdate = ( if (rule === undefined) unexplained.push(field); else rules.push(rule); } + rules.push(...pairedStamps(evidence, rules)); // Serving renews one UUID alike in every field, so the call must have. unexplained.push(...unexplainedRenewals(rules, evidence)); const pinned = pinnedEchoes(evidence.after, body, { varied: new Set() }); @@ -466,7 +368,12 @@ export const explainUpdate = ( ? Object.keys(body).filter((member) => member !== identity) : [], ); - return { rules, body: { ...shaped, identity }, unexplained }; + return { + rules, + body: { ...shaped, identity }, + unexplained, + unstamped: sameSecondClocks(evidence), + }; }; /** diff --git a/src/domain/analysisView/environmentStateWriteStamps.test.ts b/src/domain/analysisView/environmentStateWriteStamps.test.ts index 3533561c49a..587c2fecef3 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.test.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.test.ts @@ -4,8 +4,8 @@ import { explainCreate, explainUpdate, type CreateEvidence, - type UpdateEvidence, } from "./environmentStateWriteExplain.js"; +import type { UpdateEvidence } from "./environmentStateWriteChanges.js"; import type { FieldRule } from "./environmentStateWriteRules.js"; import { envelopeOf, @@ -209,6 +209,87 @@ describe("values an update stamps without being sent them", () => { }); }); +describe("the acting user's paired fields and same-second clocks", () => { + it("stamps the id beside the name naming the acting user, as the recorded pair shows them", () => { + const result = explainUpdate( + updated( + { + id: "42", + name: "A", + createdById: "u1", + createdByName: "Rea Admin", + modifiedByName: null, + }, + { + id: "42", + name: "B", + createdById: "u1", + createdByName: "Rea Admin", + modifiedByName: "Rea Admin", + modifiedById: "u1", + }, + { name: "B" }, + ), + ); + expect(result.rules).toContainEqual({ + field: "modifiedById", + rule: "stamp", + value: "u1", + }); + expect(result.rules).toContainEqual({ + field: "modifiedByName", + rule: "stamp", + value: "Rea Admin", + }); + // An id the creator's counterpart does not hold names someone else, so it is not the acting user's. + const other = explainUpdate( + updated( + { + id: "42", + name: "A", + createdById: "u1", + createdByName: "Rea Admin", + modifiedByName: null, + }, + { + id: "42", + name: "B", + createdById: "u1", + createdByName: "Rea Admin", + modifiedByName: "Rea Admin", + modifiedById: "u2", + }, + { name: "B" }, + ), + ); + expect(other.rules.map((rule) => rule.field)).not.toContain("modifiedById"); + }); + + it("names the unsent whole-second clocks an update left in its own second, and no finer or creation one", () => { + const second = "2026-03-04T05:06:00Z"; + const result = explainUpdate( + updated( + { + id: "42", + name: "A", + modifiedAt: second, + seenAt: "2026-03-04T05:06:00.250Z", + createdAt: second, + }, + { + id: "42", + name: "B", + modifiedAt: second, + seenAt: "2026-03-04T05:06:00.250Z", + createdAt: second, + }, + { name: "B" }, + ), + ); + expect(result.unstamped).toEqual(["modifiedAt"]); + }); +}); + describe("clocks an update sends back unchanged", () => { it("stamps anew the one clock a call sent back in whole seconds within the call's second", () => { const second = "2026-03-04T05:06:00.000Z"; diff --git a/src/domain/analysisView/environmentStateWriteStamps.ts b/src/domain/analysisView/environmentStateWriteStamps.ts index 3fb87420fd6..e2aa693ecfd 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.ts @@ -309,7 +309,7 @@ const wordsOf = (name: string): string[] => .filter((word) => word.length > 0); /** A name without the trailing words that make it a reference: `assignedUserId` and `assignedUserName` share `assigned user`. */ -const stemOf = (name: string): string => { +const referentOf = (name: string): string => { const words = wordsOf(name); while (words.length > 1 && REFERENCE_WORDS.has(words.at(-1)!)) words.pop(); return words.join(" "); @@ -336,7 +336,7 @@ export const stampRule = ( // A field naming what the call sent refers to that, not to the acting user. if ( Object.keys(evidence.call.body).some( - (member) => stemOf(member) === stemOf(field), + (member) => referentOf(member) === referentOf(field), ) ) return undefined; @@ -347,6 +347,32 @@ export const stampRule = ( : undefined; }; +/** The other `…by` field naming the acting user (`modifiedById` beside `modifiedByName`), stamped with it when the recorded call shows it at its `created…by` counterpart's value. */ +export const pairedStamps = ( + evidence: ChangeEvidence, + rules: readonly FieldRule[], +): FieldRule[] => { + const ruled = new Set(rules.map((rule) => rule.field)); + return rules.flatMap((rule) => + rule.rule === "stamp" + ? Object.keys(evidence.after).flatMap((sibling): FieldRule[] => { + const value = evidence.after[sibling] ?? null; + const creator = creatorOf(sibling); + return !ruled.has(sibling) && + value !== null && + creator !== undefined && + referentOf(sibling) === referentOf(rule.field) && + Object.entries(evidence.before).some( + ([other, held]) => + same(held, value) && wordsOf(other).join(" ") === creator, + ) + ? [{ field: sibling, rule: "stamp", value }] + : []; + }) + : [], + ); +}; + /** A sent string's text, markup aside: what a value derived from it shows. */ const textOf = (value: JsonValue | undefined): string | undefined => typeof value === "string" @@ -433,7 +459,7 @@ const nestedIdentities = (entity: JsonObject): Map> => { return text === undefined ? [] : [text]; }); if (texts.length === 0) continue; - const stem = stemOf(field); + const stem = referentOf(field); index.set(stem, new Set([...(index.get(stem) ?? []), ...texts])); } return index; @@ -482,7 +508,9 @@ export const pinnedEchoes = ( // A member names the object nested under the field it refers to, as `collection_id` does `collection`. const namesNested = (member: string, value: JsonValue): boolean => { const text = scalarText(value); - return text !== undefined && nested.get(stemOf(member))?.has(text) === true; + return ( + text !== undefined && nested.get(referentOf(member))?.has(text) === true + ); }; return new Set( Object.entries(body).flatMap(([member, value]) => diff --git a/src/domain/analysisView/environmentStateWriteVerdict.ts b/src/domain/analysisView/environmentStateWriteVerdict.ts index 32f903ed388..16335a6bcfb 100644 --- a/src/domain/analysisView/environmentStateWriteVerdict.ts +++ b/src/domain/analysisView/environmentStateWriteVerdict.ts @@ -47,6 +47,12 @@ const steady = (plan: StateWritePlan, draft: WriteDraft): boolean => { return set.length > 0 && set.every((field) => draft.steady.has(field)); }; +/** Whether a clock a call left as it was in its own second has no rule another call showed, so no call showed whether the write stamps it. */ +const unstamped = (plan: StateWritePlan, draft: WriteDraft): boolean => + [...draft.unstamped].some( + (field) => !plan.rules.some((rule) => rule.field === field), + ); + /** A replayed write's plan, served only when it was called, nothing contradicted it, a read confirmed it and its answers can render. */ export const writeVerdict = ( draft: WriteDraft, @@ -59,7 +65,11 @@ export const writeVerdict = ( plan.reason = "contradicted"; plan.contradicted_by = draft.contradictedBy; } else if (draft.sideEffect) plan.reason = "side-effect"; - else if (draft.confirmed.length === 0 || !steady(plan, draft)) + else if ( + draft.confirmed.length === 0 || + !steady(plan, draft) || + unstamped(plan, draft) + ) plan.reason = "unconfirmed"; else if (!renders(plan, input)) plan.reason = "incomplete-entities"; } diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index d55aaee1d72..c8bc397ffc6 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -2194,3 +2194,62 @@ describe("insert rules the recorded order cannot settle", () => { expect(plan).toMatchObject({ served: true, insert: { rule: "last" } }); }); }); + +/** A task whose modified clock is stored in whole seconds. */ +const task = (id: number, name: string, modifiedAt: string) => ({ + id, + name, + modifiedAt, +}); +const OLD_CLOCK = "2026-10-01T09:00:00Z"; + +describe("clocks an update may stamp in its own second", () => { + const sameSecond: TimedCaptureRow[] = [ + [ + "GET", + "/api/tasks", + [task(1, "First", bookClock(3)), task(2, "Second", OLD_CLOCK)], + ], + ["GET", "/api/tasks/1", task(1, "First", bookClock(3))], + ["GET", "/api/tasks/2", task(2, "Second", OLD_CLOCK)], + [ + "PATCH", + "/api/tasks/1", + task(1, "Renamed", bookClock(3)), + 200, + { name: "Renamed" }, + ], + ["GET", "/api/tasks/1", task(1, "Renamed", bookClock(3))], + ]; + + it("confirms no update that left an unsent clock as it was in the second it ran", () => { + expect(planOf(stateOf(sameSecond), "patch_tasks_by_id")).toMatchObject({ + served: false, + reason: "unconfirmed", + }); + }); + + it("serves the update once another call shows it stamping the clock", () => { + const plan = planOf( + stateOf([ + ...sameSecond, + [ + "PATCH", + "/api/tasks/2", + task(2, "Second (renamed)", bookClock(5)), + 200, + { name: "Second (renamed)" }, + ], + ["GET", "/api/tasks/2", task(2, "Second (renamed)", bookClock(5))], + ]), + "patch_tasks_by_id", + ); + expect(plan).toMatchObject({ + served: true, + checked_record_ordinals: [4, 6], + }); + expect(plan.rules).toContainEqual( + expect.objectContaining({ field: "modifiedAt", rule: "clock" }), + ); + }); +}); From 434db0429adec27d600fc5f9e7f385103f4c3e22 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 11:07:44 -0700 Subject: [PATCH 38/68] fix(environment): show pinned query and body values in the served catalog and apply bulk writes atomically A pinned query parameter is required with its recorded value as the only choice, and a call that leaves it out takes that value. A fixed body member shows its recorded value, and an enveloped body its wrapping, in the schema, the description and the refusal. Bulk writes go through the same query pin and update or remove their entities at once. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-writes/spec.md | 26 +++- docs/web-network-captures.md | 3 +- .../environment/environmentState.ts | 11 +- .../environmentStateBulkAnswer.test.ts | 46 ++++++ .../environment/environmentStateBulkAnswer.ts | 54 ++----- .../environment/environmentStateStore.ts | 56 +++++-- .../environmentStateWriteAnswer.test.ts | 5 +- .../environmentStateWriteAnswer.ts | 21 +-- .../environmentStateWriteDescription.ts | 120 ++++++++++++--- .../environmentStateWriteDisclosure.test.ts | 143 ++++++++++++++++++ .../environment/environmentStateWriteQuery.ts | 35 +++++ .../environment/environmentToolAnswer.ts | 31 ++-- .../environment/environmentToolSchemas.ts | 26 ++++ .../environment/environmentTools.ts | 70 ++++++--- .../environmentStateCheckedLines.ts | 17 ++- .../environmentStateWriteAddress.test.ts | 16 ++ .../environmentStateWriteAddress.ts | 36 +++-- .../environmentStateWriteApply.test.ts | 2 +- .../environmentStateWriteApply.ts | 11 +- .../analysisView/environmentStateWriteBulk.ts | 15 +- .../environmentStateWriteEffects.ts | 4 +- .../environmentStateWriteStamps.test.ts | 19 ++- .../environmentStateWriteStamps.ts | 49 +++--- tests/boundary/mcp/toolSchemaValidity.test.ts | 61 ++++++-- 24 files changed, 666 insertions(+), 211 deletions(-) create mode 100644 src/application/environment/environmentStateWriteDisclosure.test.ts create mode 100644 src/application/environment/environmentStateWriteQuery.ts create mode 100644 src/application/environment/environmentToolSchemas.ts diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 8710e6122ad..c15c0075a7b 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -155,10 +155,12 @@ the exemplar. `body.envelope`: serving takes only a body wrapped that way. - **Query.** Serving takes only the query parameters the exemplar sent, with its values, since they may change what the body does (Ghost reads `html` - only with `?source=html`); a call with others is refused. The gate treats a - later recorded call sent with another query, or wrapped otherwise, as a - write its plan does not explain: it brings the entity to what the call - recorded, without attribution. + only with `?source=html`): a parameter a call leaves out takes the recorded + value, as the recording sent it, and a call with another value or parameter + is refused, a bulk call included. The gate treats a later recorded call sent + with another query, or wrapped otherwise, as a write its plan does not + explain: it brings the entity to what the call recorded, without + attribution, and a bulk call leaves the entities it names unmodelled. - **The written entity.** The entity is observed in the exemplar's response, located by its identity value at the root, in one member, or in a one-element array, as item views locate it. When the response does not carry @@ -551,7 +553,18 @@ served. Their descriptions say the tool: - applies its effect to the served state; - names its target type; - lists its required and accepted body members, quoted and sampled within the - description budget as response fields are. + description budget as response fields are, the members it accepts only with + their recorded value, with that value when its JSON text is 120 characters + or less, and the envelope a body wraps its object in; +- names the query its recording sent. + +The input schema says the same: each query parameter the recording sent is +required, with its value as the only `enum` member; a body that wraps its +object requires that member, an array of one object; and a member accepted +only with its recorded value carries that value as `const` when it is short +and no boolean (some clients reject boolean literals), else a description +saying it must equal the recorded value. A refused member's message names the +recorded value the same way. The discovery budget charges them. `--replay-only` and the replay fallback are unchanged. @@ -643,7 +656,8 @@ included, and `environment-compare` sends a probe's body to it; every id must name an entity the state holds, else the call is refused and the state is unchanged. A bulk update with a `unique` or `renewed` rule writes one entity per call, since one -call draws those values once. A served item action's path names its entity +call draws those values once. A bulk write changes or removes its entities in +one step, so a call the state cannot hold changes none of them. A served item action's path names its entity before the action segment. **Data plane and export.** diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index c9ac9cf3b2e..da1f6df2e31 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -698,7 +698,8 @@ stores nowhere, or for an item action a `set` of a scalar to the value it showed, or the plan is `unexplained-change`; an increment, slug, stamp, derived value or set must hold for every call of the tool, and an action is served only once a call found what it sets already set. A write is served only -with the query its first call sent. Every member the first call sent is required, except by `PATCH` and +with the query its first call sent, which serving applies to a call that +leaves a parameter out and the catalog advertises as required. Every member the first call sent is required, except by `PATCH` and `POST` updates. A read on a line `query` answers is checked against the query evaluated over diff --git a/src/application/environment/environmentState.ts b/src/application/environment/environmentState.ts index d54e54b2039..af5ed7d7821 100644 --- a/src/application/environment/environmentState.ts +++ b/src/application/environment/environmentState.ts @@ -28,6 +28,7 @@ import { initialStateBytes } from "./environmentStateStore.js"; import { describeWrite, writeBody, + writeQuery, } from "./environmentStateWriteDescription.js"; import { environmentToolDefinitions, @@ -105,8 +106,14 @@ export const servedCatalog = ( ...(state === undefined ? {} : { - describe: (tool) => describeWrite(state.writes.get(tool.name)), - body: (tool) => writeBody(state.writes.get(tool.name)), + describe: (tool) => + describeWrite( + state.writes.get(tool.name), + writeQuery(state.writes.get(tool.name), source), + ), + body: (tool, recorded) => + writeBody(state.writes.get(tool.name), recorded), + query: (tool) => writeQuery(state.writes.get(tool.name), source), }), }, ); diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 545cddb049e..db93a3d5aea 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -7,6 +7,7 @@ import { BOOK_NOT_FOUND, FIRST_BOOK, SECOND_BOOK, + renamedBook, type Book, } from "../../../tests/fixtures/environmentStateWrites.js"; import { servedCatalog } from "./environmentState.js"; @@ -18,6 +19,16 @@ const BULK_DELETE_ROWS: readonly TimedCaptureRow[] = [ ["GET", "/api/books", [FIRST_BOOK]], ]; +const RENAMED_AT_3 = renamedBook(FIRST_BOOK, "Renamed Book", 3); + +/** A bulk rename of the books an id array names, which the list after it confirms. */ +const BULK_RENAME_ROWS: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + ["PATCH", "/api/books", "", 204, { ids: [1], name: "Renamed Book" }], + ["GET", "/api/books/1", RENAMED_AT_3], + ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], +]; + /** A book with an `archived` flag, which an item action sets. */ const shelved = (entity: Book, archived: boolean) => ({ ...entity, archived }); @@ -64,6 +75,41 @@ describe("served bulk writes", () => { }); }); +describe("served bulk write queries and capacity", () => { + it("applies a bulk delete's recorded query when a call leaves it out, and refuses another", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books?force=true", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + const before = books.snapshot(); + expect( + books.refusal("delete_books", { force: "false", body: [{ id: 1 }] }) + .message, + ).toContain("takes only the query its recording sent (force=true)"); + expect(books.snapshot()).toBe(before); + expect(books.answer("delete_books", { body: [{ id: 1 }] })).toMatchObject({ + status: 200, + body: [{ id: 1 }], + }); + expect(books.store.ofType("/api/books").map((book) => book.id)).toEqual([ + "2", + ]); + }); + + it("refuses a bulk update the state cannot hold, leaving every entity as it was", () => { + const books = servedFrom(BULK_RENAME_ROWS); + const before = books.snapshot(); + // Each renamed book grows by twice the name, slug included; two of them pass the intake limit, one does not. + const name = "x".repeat(9 * 1024 * 1024); + expect( + books.refusal("patch_books", { body: { ids: [1, 2], name } }), + ).toMatchObject({ code: "resource_constraint" }); + expect(books.snapshot()).toBe(before); + }); +}); + describe("served item actions", () => { it("sets what the action changed on the entity the path names", () => { const books = servedFrom([ diff --git a/src/application/environment/environmentStateBulkAnswer.ts b/src/application/environment/environmentStateBulkAnswer.ts index 9a1d2358535..493dad1f70a 100644 --- a/src/application/environment/environmentStateBulkAnswer.ts +++ b/src/application/environment/environmentStateBulkAnswer.ts @@ -1,4 +1,7 @@ -import { namedEntities } from "../../domain/analysisView/environmentStateWriteAddress.js"; +import { + bulkCollectionOf, + namedEntities, +} from "../../domain/analysisView/environmentStateWriteAddress.js"; import { updatedEntity, updatedFields, @@ -8,12 +11,9 @@ import type { FieldRule, WriteResponse, } from "../../domain/analysisView/environmentStateWriteRules.js"; -import { - isParam, - segmentsOf, - type JsonObject, - type StateEntity, - type SuppliedSegment, +import type { + JsonObject, + StateEntity, } from "../../domain/analysisView/environmentStateRules.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import type { JsonValue } from "../../domain/jsonValue.js"; @@ -37,27 +37,11 @@ import { writeAnswer, type WriteRequest, } from "./environmentStateWriteAnswer.js"; -import { - environmentToolArguments, - hasRepeatedQueryArgument, -} from "./environmentTools.js"; +import { environmentToolArguments } from "./environmentTools.js"; /** Rules whose generated value is drawn once per call, which one call cannot give several entities. */ const DRAWN_ONCE = new Set(["unique", "renewed"]); -/** The collection a bulk call's path names, with the type's spelling of its last segment, and no delete segment after it. */ -const collectionSegments = ( - segments: readonly SuppliedSegment[], - target: string, -): SuppliedSegment[] => { - const typed = segmentsOf(target); - const collection = segments.slice(0, typed.length); - const last = typed.at(-1)!; - if (!isParam(last)) - collection[typed.length - 1] = { text: last, supplied: false }; - return collection; -}; - /** A bulk answer from the recorded one: one element per written entity, rendered as the first recorded element shows its entity. */ const bulkResponse = ( response: WriteResponse, @@ -110,7 +94,10 @@ const namedTargets = ( const segments = callSegments(tool, args); if (segments === undefined) return err(refused(tool, `Tool ${tool.name} needs every path argument.`)); - const collection = collectionSegments(segments, type); + const collection = bulkCollectionOf(type, segments, (text) => ({ + text, + supplied: false, + })); const targets = []; for (const { id, body: members } of named) { const entity = namedEntity(serving.store, type, { @@ -135,13 +122,6 @@ export const answerBulk = ( request: WriteRequest, ): Result => { const { tool, plan, args } = request; - if (hasRepeatedQueryArgument(tool, args)) - return err( - refused( - tool, - "The state write model cannot apply repeated query parameters; the state is unchanged.", - ), - ); const targets = namedTargets(serving, request); if (!targets.ok) return targets; const update = plan.effect === "update"; @@ -202,14 +182,10 @@ export const answerBulk = ( }, ); if (!answer.ok) return answer; - for (const entity of written) { - if (!update) { - serving.store.remove(entity); - continue; - } - const updated = serving.store.update(entity); + if (update) { + const updated = serving.store.updateAll(written); if (!updated.ok) return updated; - } + } else serving.store.removeAll(written); serving.store.commitWrite(values.taken); return answer; }; diff --git a/src/application/environment/environmentStateStore.ts b/src/application/environment/environmentStateStore.ts index 5f0a8479229..10662397363 100644 --- a/src/application/environment/environmentStateStore.ts +++ b/src/application/environment/environmentStateStore.ts @@ -299,16 +299,31 @@ export class EnvironmentStateStore { /** Replace a held entity's values in place, unless the state would outgrow what `data/add` loads. */ update(entity: StateEntity): Result { - const key = compositeKey([entity.type, entity.collection, entity.id]); - const held = this.#entities.get(key); - if (held === undefined) return ok(undefined); - const bytes = this.#grown(jsonByteLength(entity) - jsonByteLength(held)); + return this.updateAll([entity]); + } + + /** Replace held entities in one step, unless the state would outgrow what `data/add` loads; a refusal changes nothing. */ + updateAll( + entities: readonly StateEntity[], + ): Result { + const replaced = new Map(); + let delta = 0; + for (const entity of entities) { + const held = this.#entities.get( + compositeKey([entity.type, entity.collection, entity.id]), + ); + if (held === undefined) continue; + replaced.set(held, entity); + delta += jsonByteLength(entity) - jsonByteLength(held); + } + if (replaced.size === 0) return ok(undefined); + const bytes = this.#grown(delta); if (!bytes.ok) return bytes; this.#install( { ...this.#content, - entities: this.#content.entities.map((candidate) => - candidate === held ? entity : candidate, + entities: this.#content.entities.map( + (candidate) => replaced.get(candidate) ?? candidate, ), }, bytes.value, @@ -317,17 +332,28 @@ export class EnvironmentStateStore { } remove(entity: StateEntity): void { - const held = this.#entities.get( - compositeKey([entity.type, entity.collection, entity.id]), - ); - if (held === undefined) return; - const entities = this.#content.entities.filter( - (candidate) => candidate !== held, + this.removeAll([entity]); + } + + /** Remove held entities in one step. */ + removeAll(entities: readonly StateEntity[]): void { + const held = new Set( + entities.flatMap((entity) => { + const found = this.#entities.get( + compositeKey([entity.type, entity.collection, entity.id]), + ); + return found === undefined ? [] : [found]; + }), ); - this.#install( - { ...this.#content, entities }, - this.#bytes - jsonByteLength(held) - (entities.length > 0 ? 1 : 0), + if (held.size === 0) return; + const kept = this.#content.entities.filter( + (candidate) => !held.has(candidate), ); + let bytes = this.#bytes; + for (const entity of held) bytes -= jsonByteLength(entity); + // Each removed entity takes its separator, except the last one an emptied list had none for. + bytes -= held.size - (kept.length === 0 ? 1 : 0); + this.#install({ ...this.#content, entities: kept }, bytes); } /** Set a held document's value, unless the state would outgrow what `data/add` loads; a value that is not the Evidence's cites no record. */ diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index 07921f9a426..303b568876c 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -2001,7 +2001,10 @@ describe("served values an application stamps", () => { notes.refusal("patch_notes_by_id", edit("2", bookClock(3))).message, ).toContain("derives excerpt"); expect( - notes.refusal("patch_notes_by_id", edit("1", bookClock(3), {})).message, + notes.refusal( + "patch_notes_by_id", + edit("1", bookClock(3), { source: "markdown" }), + ).message, ).toContain("takes only the query its recording sent (source=html)"); expect( notes.refusal("patch_notes_by_id", edit("1", "2026-01-01T00:00:00Z")) diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index 80c08dcb944..11e39067ed3 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -16,7 +16,6 @@ import { import { callRenewal } from "../../domain/analysisView/environmentStateWriteGenerated.js"; import { nestedClockValue, - queryProblem, unenveloped, } from "../../domain/analysisView/environmentStateWriteStamps.js"; import { @@ -52,7 +51,7 @@ import { type ReplayArguments, } from "./environmentReplay.js"; import type { EnvironmentManifestTool } from "./environmentSource.js"; -import { callQuery, callSegments } from "./environmentStateCallLines.js"; +import { callSegments } from "./environmentStateCallLines.js"; import { itemCall, missingAnswer, @@ -70,10 +69,7 @@ import { unloadableMember, type HeldDocument, } from "./environmentStateDocument.js"; -import { - environmentToolArguments, - hasRepeatedQueryArgument, -} from "./environmentTools.js"; +import { environmentToolArguments } from "./environmentTools.js"; /** Attempts at a generated UUID or token before a collision with held values is refused. */ const GENERATION_ATTEMPTS = 64; @@ -649,19 +645,6 @@ export const answerWrite = ( serving: StateServing, request: WriteRequest, ): Result => { - if (hasRepeatedQueryArgument(request.tool, request.args)) - return err( - refused( - request.tool, - "The state write model cannot apply repeated query parameters; the state is unchanged.", - ), - ); - const query = queryProblem( - serving.source.exchanges.get(request.plan.exemplar_ordinal ?? -1)?.query, - callQuery(request.tool, request.args), - ); - if (query !== undefined) - return err(refused(request.tool, `Tool ${request.tool.name} ${query}`)); const body = callBody(request); if (!body.ok) return body; const call: WriteCall = { diff --git a/src/application/environment/environmentStateWriteDescription.ts b/src/application/environment/environmentStateWriteDescription.ts index d0ab2286a7d..113774d9a6e 100644 --- a/src/application/environment/environmentStateWriteDescription.ts +++ b/src/application/environment/environmentStateWriteDescription.ts @@ -2,16 +2,27 @@ import type { StateWritePlan, WriteBody, } from "../../domain/analysisView/environmentStateWriteRules.js"; +import { shownValue } from "../../domain/analysisView/environmentStateWriteApply.js"; +import type { JsonValue } from "../../domain/jsonValue.js"; +import { singleQueryValues } from "../../domain/recordedTransportUrl.js"; +import type { EnvironmentSource } from "./environmentSource.js"; import { describeList, quotedName, type EnvironmentToolProperty, } from "./environmentTools.js"; +import type { EnvironmentToolSchema } from "./environmentToolSchemas.js"; /** Captured member names, quoted and sampled as response fields are; the plan in the state Evidence holds every one. */ const members = (names: readonly string[]): string => describeList(names, names.length, quotedName, "state Evidence"); +/** A member a served write fixes, with the recorded value it takes when that is short. */ +const fixedMember = ({ member, sent }: WriteBody["fixed"][number]): string => { + const shown = shownValue(sent); + return `${quotedName(member)} ${shown === undefined ? "only as recorded" : `only as ${shown}`}`; +}; + /** The body members a served write accepts, as a description clause. */ const bodyClause = ( body: WriteBody, @@ -19,11 +30,18 @@ const bodyClause = ( action = false, ): string => { const parts: string[] = []; + if (body.envelope !== undefined) + parts.push(`one object wrapped as {${quotedName(body.envelope)}:[{…}]}`); if (body.accepted.length > 0) parts.push(`body members ${members(body.accepted)}`); if (body.fixed.length > 0) parts.push( - `${members(body.fixed.map(({ member }) => member))} only with the value the capture sent`, + describeList( + body.fixed, + body.fixed.length, + fixedMember, + "state Evidence", + ), ); if (body.required.length > 0) parts.push(`required: ${members(body.required)}`); @@ -31,19 +49,27 @@ const bodyClause = ( return parts.length === 0 ? "" : ` (${parts.join("; ")})`; }; +/** The query a served write takes, as a description clause. */ +const queryClause = (query: ReadonlyMap | undefined): string => + query === undefined || query.size === 0 + ? "" + : ` with the recorded query ${describeList(query, query.size, ([name, value]) => `${name}=${value}`, "state Evidence")}`; + /** What a served write tool does to the state, for its description; undefined for a tool the state does not serve. */ export const describeWrite = ( plan: StateWritePlan | undefined, + query?: ReadonlyMap, ): string | undefined => { if (plan?.served !== true) return undefined; const { address } = plan; const body = - plan.body === null + (plan.body === null ? "" - : bodyClause(plan.body, plan.effect, address?.by === "action"); + : bodyClause(plan.body, plan.effect, address?.by === "action")) + + queryClause(query); if (address !== undefined && address.by !== "action") return plan.effect === "delete" - ? "removes the entities its body names by id from the served environment state, modelled on the recorded calls" + ? `removes the entities its body names by id from the served environment state${queryClause(query)}, modelled on the recorded calls` : `changes the entities its body names by id in the served environment state${body}, modelled on the recorded calls`; if (address?.by === "action") return `applies ${quotedName(address.segment)} to the entity the path names in the served environment state${body}, modelled on the recorded calls`; @@ -53,7 +79,7 @@ export const describeWrite = ( case "update": return `changes the entity the path names in the served environment state${body}, modelled on the recorded calls`; case "delete": - return "removes the entity the path names from the served environment state, modelled on the recorded calls"; + return `removes the entity the path names from the served environment state${queryClause(query)}, modelled on the recorded calls`; case "document": return `changes a document of the served environment state${body}, modelled on the recorded calls`; case "none": @@ -61,27 +87,77 @@ export const describeWrite = ( } }; -/** The body a served bulk write takes: the recorded form naming its entities by id, an array or an object. */ +/** The query a served write's recording pins, by parameter; undefined when it sent none. */ +export const writeQuery = ( + plan: StateWritePlan | undefined, + source: Pick, +): ReadonlyMap | undefined => { + if (plan?.served !== true || plan.exemplar_ordinal === null) return undefined; + const query = singleQueryValues( + source.exchanges.get(plan.exemplar_ordinal)?.query ?? undefined, + ); + return query === undefined || query.size === 0 ? undefined : query; +}; + +/** A fixed member's schema: its recorded value as `const` when short and not a boolean, which some clients reject as a literal. */ +const fixedSchema = (sent: JsonValue): EnvironmentToolSchema => { + const shown = shownValue(sent); + if (shown !== undefined && typeof sent !== "boolean") + return { const: sent, description: "Only the recorded value is accepted." }; + return { + description: + shown === undefined + ? "Must equal the recorded value, which is too long to show here." + : `Must be ${shown}, the recorded value.`, + }; +}; + +/** The body a served write takes: a bulk write's ids, or the recorded object with the values it fixes, wrapped as recorded. */ export const writeBody = ( plan: StateWritePlan | undefined, + recorded: EnvironmentToolProperty, ): EnvironmentToolProperty | undefined => { - const address = plan?.served === true ? plan.address : undefined; - if (address === undefined || address.by === "action") return undefined; - const ids = - address.by === "ids" - ? "an array of entity ids" - : "an array of objects each carrying its entity's id field"; - const items = { - type: address.by === "ids" ? address.kind : "object", - } as const; - return address.member === null - ? { - type: "array", - items, - description: `Request body: ${ids}, as recorded.`, - } + if (plan?.served !== true) return undefined; + const { address, body } = plan; + if (address !== undefined && address.by !== "action") { + const ids = + address.by === "ids" + ? "an array of entity ids" + : "an array of objects each carrying its entity's id field"; + const items = { + type: address.by === "ids" ? address.kind : "object", + } as const; + return address.member === null + ? { + type: "array", + items, + description: `Request body: ${ids}, as recorded.`, + } + : { + type: "object", + description: `Request body: ${quotedName(address.member)} holds ${ids}, as recorded.`, + }; + } + if (body === null || (body.fixed.length === 0 && body.envelope === undefined)) + return undefined; + const object: EnvironmentToolSchema = { + type: "object", + properties: Object.fromEntries( + body.fixed.map(({ member, sent }) => [member, fixedSchema(sent)]), + ), + }; + return body.envelope === undefined + ? { ...recorded, ...object } : { type: "object", - description: `Request body: ${quotedName(address.member)} holds ${ids}, as recorded.`, + required: [body.envelope], + properties: { + [body.envelope]: { + type: "array", + items: object, + description: "One object, as the recording wrapped it.", + }, + }, + description: `Request body: one object wrapped as {${quotedName(body.envelope)}:[{…}]}, as recorded. ${recorded.description}`, }; }; diff --git a/src/application/environment/environmentStateWriteDisclosure.test.ts b/src/application/environment/environmentStateWriteDisclosure.test.ts new file mode 100644 index 00000000000..c67b7fe961f --- /dev/null +++ b/src/application/environment/environmentStateWriteDisclosure.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "vitest"; + +import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js"; +import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js"; +import { + BOOK_INIT_ROWS, + FIRST_BOOK, + SECOND_BOOK, + THIRD_BOOK, + renamedBook, + type Book, +} from "../../../tests/fixtures/environmentStateWrites.js"; +import { servedCatalog } from "./environmentState.js"; + +const RENAMED = renamedBook(FIRST_BOOK, "Renamed Book", 3); + +/** An update recorded with a query the served write pins. */ +const PINNED_ROWS: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + [ + "PATCH", + "/api/books/1?notify=quiet", + RENAMED, + 200, + { name: "Renamed Book" }, + ], + ["GET", "/api/books/1", RENAMED], +]; + +const LONG = "select * from shelves where ".padEnd(160, "x"); +/** A book as the application stores its edition details, which a create sends otherwise. */ +const edition = (book: Book) => ({ + ...book, + format: "HC", + query: "q1", + featured: 1, +}); +const STORED = edition(THIRD_BOOK); +/** A create wrapping its object, which stores `format`, `query` and `featured` otherwise than sent. */ +const FIXED_ROWS: readonly TimedCaptureRow[] = [ + ["GET", "/api/books", [edition(FIRST_BOOK), edition(SECOND_BOOK)]], + ["GET", "/api/books/1", edition(FIRST_BOOK)], + ["GET", "/api/books/2", edition(SECOND_BOOK)], + [ + "POST", + "/api/books", + STORED, + 201, + { + books: [ + { + name: "Third Book", + format: "hardcover", + query: LONG, + featured: true, + }, + ], + }, + ], + ["GET", "/api/books/3", STORED], +]; + +const toolOf = (rows: readonly TimedCaptureRow[], name: string) => { + const served = servedFrom(rows); + const catalog = servedCatalog(served.source, served.state, "books"); + if (!catalog.ok) throw catalog.error; + const tool = catalog.value.tools.find( + (definition) => definition.name === name, + ); + if (tool === undefined) throw new Error(`${name} is not served`); + return { served, tool }; +}; + +describe("served write queries", () => { + it("advertises the query a write's recording sent as required, and applies it when a call leaves it out", () => { + const { served, tool } = toolOf(PINNED_ROWS, "patch_books_by_id"); + expect(tool.inputSchema.properties["notify"]).toMatchObject({ + type: "string", + enum: ["quiet"], + }); + expect(tool.inputSchema.required).toContain("notify"); + expect(tool.description).toContain("with the recorded query notify=quiet"); + const before = served.snapshot(); + expect( + served.refusal("patch_books_by_id", { + id: "2", + notify: "loud", + body: { name: "Second Edition" }, + }).message, + ).toContain("takes only the query its recording sent (notify=quiet)"); + expect(served.snapshot()).toBe(before); + expect( + served.answer("patch_books_by_id", { + id: "2", + body: { name: "Second Edition" }, + }), + ).toMatchObject({ status: 200, body: { id: 2, name: "Second Edition" } }); + }); +}); + +describe("served write bodies", () => { + it("shows the values a create fixes and the object it wraps, in its schema, description and refusals", () => { + const { served, tool } = toolOf(FIXED_ROWS, "post_books"); + expect(tool.inputSchema.properties["body"]).toMatchObject({ + type: "object", + required: ["books"], + properties: { + books: { + type: "array", + items: { + type: "object", + properties: { + format: { const: "hardcover" }, + query: { + description: + "Must equal the recorded value, which is too long to show here.", + }, + featured: { description: "Must be true, the recorded value." }, + }, + }, + }, + }, + }); + expect(JSON.stringify(tool.inputSchema)).not.toContain(LONG); + expect(tool.description).toContain('one object wrapped as {"books":[{…}]}'); + expect(tool.description).toContain('"format" only as "hardcover"'); + expect(tool.description).toContain('"query" only as recorded'); + expect( + served.refusal("post_books", { + body: { + books: [ + { + name: "Fourth", + format: "paperback", + query: LONG, + featured: true, + }, + ], + }, + }).message, + ).toContain('accepted only with the value the capture sent, "hardcover"'); + }); +}); diff --git a/src/application/environment/environmentStateWriteQuery.ts b/src/application/environment/environmentStateWriteQuery.ts new file mode 100644 index 00000000000..23e1925d3b0 --- /dev/null +++ b/src/application/environment/environmentStateWriteQuery.ts @@ -0,0 +1,35 @@ +import { pinnedQuery } from "../../domain/analysisView/environmentStateWriteStamps.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { err, ok, type Result } from "../../domain/result.js"; +import { refused, type StateServing } from "./environmentStateAnswer.js"; +import { callQuery } from "./environmentStateCallLines.js"; +import type { WriteRequest } from "./environmentStateWriteAnswer.js"; +import { + environmentToolArguments, + hasRepeatedQueryArgument, +} from "./environmentTools.js"; + +/** A served write call with the query its recording pins: a parameter it leaves out takes the recorded value; another value or parameter, or a repeated one, is refused. */ +export const pinnedRequest = ( + serving: StateServing, + request: WriteRequest, +): Result => { + const { tool, plan, args } = request; + if (hasRepeatedQueryArgument(tool, args)) + return err( + refused( + tool, + "The state write model cannot apply repeated query parameters; the state is unchanged.", + ), + ); + const query = pinnedQuery( + serving.source.exchanges.get(plan.exemplar_ordinal ?? -1)?.query, + callQuery(tool, args), + ); + if (!query.ok) return err(refused(tool, `Tool ${tool.name} ${query.error}`)); + const names = environmentToolArguments(tool).query; + const filled = { ...args }; + for (const [name, value] of query.value) + filled[names.get(name) ?? name] ??= value; + return ok({ ...request, args: filled }); +}; diff --git a/src/application/environment/environmentToolAnswer.ts b/src/application/environment/environmentToolAnswer.ts index 2394949b030..5e70c1e4485 100644 --- a/src/application/environment/environmentToolAnswer.ts +++ b/src/application/environment/environmentToolAnswer.ts @@ -13,6 +13,7 @@ import { answerFromState } from "./environmentStateAnswer.js"; import { answerBulk } from "./environmentStateBulkAnswer.js"; import type { EnvironmentStateStore } from "./environmentStateStore.js"; import { answerWrite } from "./environmentStateWriteAnswer.js"; +import { pinnedRequest } from "./environmentStateWriteQuery.js"; /** How a served environment answers one tool call. */ export type EnvironmentToolAnswer = ( @@ -31,17 +32,21 @@ export const environmentToolAnswer = ( replayEnvironmentTool(source, tool, args, observedQuery) : (tool, args, observedQuery) => { const plan = store.state.writes.get(tool.name); - const bulk = - plan?.address !== undefined && plan.address.by !== "action"; - return plan?.served === true - ? (bulk ? answerBulk : answerWrite)( - { source, store }, - { - tool, - plan, - args, - ...(observedQuery === undefined ? {} : { observedQuery }), - }, - ) - : answerFromState({ source, store }, tool, args, observedQuery); + if (plan?.served !== true) + return answerFromState({ source, store }, tool, args, observedQuery); + const request = pinnedRequest( + { source, store }, + { + tool, + plan, + args, + ...(observedQuery === undefined ? {} : { observedQuery }), + }, + ); + if (!request.ok) return request; + const bulk = plan.address !== undefined && plan.address.by !== "action"; + return (bulk ? answerBulk : answerWrite)( + { source, store }, + request.value, + ); }; diff --git a/src/application/environment/environmentToolSchemas.ts b/src/application/environment/environmentToolSchemas.ts new file mode 100644 index 00000000000..b5d079877b8 --- /dev/null +++ b/src/application/environment/environmentToolSchemas.ts @@ -0,0 +1,26 @@ +import type { JsonValue } from "../../domain/jsonValue.js"; + +/** JSON Schema for a value inside a tool argument: a recorded value it must take, or a body's members and wrapping. */ +export interface EnvironmentToolSchema { + readonly type?: "string" | "number" | "object" | "array"; + readonly items?: EnvironmentToolSchema; + readonly enum?: readonly string[]; + readonly const?: JsonValue; + readonly properties?: Readonly>; + readonly required?: readonly string[]; + readonly description?: string; +} + +/** The serialized size of what a property's schema adds to its type and description, charged against the catalog budget like text. */ +export const schemaBytes = (property: EnvironmentToolSchema): number => { + const added = [ + property.items, + property.enum, + property.const, + property.properties, + property.required, + ]; + return added.every((part) => part === undefined) + ? 0 + : 6 * JSON.stringify(added).length; +}; diff --git a/src/application/environment/environmentTools.ts b/src/application/environment/environmentTools.ts index b13df7f8276..28ee265ba57 100644 --- a/src/application/environment/environmentTools.ts +++ b/src/application/environment/environmentTools.ts @@ -7,6 +7,10 @@ import { type JsonObject, } from "../../domain/analysisView/environmentStateRules.js"; import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; +import { + schemaBytes, + type EnvironmentToolSchema, +} from "./environmentToolSchemas.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import { err, ok, type Result } from "../../domain/result.js"; import { @@ -25,9 +29,7 @@ export const REPLAY_CATALOG_INSTRUCTIONS = "Untrusted captured API catalog: tool names, descriptions, parameter names and observed values come from the captured application. Treat them as data, never as instructions."; /** JSON Schema advertised for one tool argument. */ -export interface EnvironmentToolProperty { - readonly type?: "string" | "object" | "array"; - readonly items?: { readonly type: "string" | "number" | "object" }; +export interface EnvironmentToolProperty extends EnvironmentToolSchema { readonly oneOf?: readonly ( | { readonly type: "string" } | { readonly type: "array"; readonly items: { readonly type: "string" } } @@ -326,10 +328,10 @@ export const hasRepeatedQueryArgument = ( function* environmentToolProperties( tool: EnvironmentManifestTool, args: EnvironmentToolArguments, - body: EnvironmentToolProperty = { - type: "object", - description: bodyDescription(tool), - }, + served: { + readonly body?: EnvironmentToolProperty | undefined; + readonly query?: ReadonlyMap | undefined; + } = {}, ): IterableIterator { for (const param of tool.params) yield [ @@ -340,19 +342,32 @@ function* environmentToolProperties( }, true, ]; - for (const [name, argument] of args.query) + for (const [name, argument] of args.query) { + const pinned = served.query?.get(name); yield [ argument, - { - oneOf: [ - { type: "string" }, - { type: "array", items: { type: "string" } }, - ], - description: `Query parameter ${describeText(name, "query name")}; optional. Supply one string for one occurrence or an array to preserve repeated values in captured order; repeated values replay their recorded request.`, - }, + pinned === undefined + ? { + oneOf: [ + { type: "string" }, + { type: "array", items: { type: "string" } }, + ], + description: `Query parameter ${describeText(name, "query name")}; optional. Supply one string for one occurrence or an array to preserve repeated values in captured order; repeated values replay their recorded request.`, + } + : { + type: "string", + enum: [pinned], + description: `Query parameter ${describeText(name, "query name")}; required: the served write takes only the value its recording sent, ${describeText(pinned, "query value")}, and applies it when left out.`, + }, + pinned !== undefined, + ]; + } + if (args.body !== undefined) + yield [ + args.body, + served.body ?? { type: "object", description: bodyDescription(tool) }, false, ]; - if (args.body !== undefined) yield [args.body, body, false]; } /** Serialization reservation calibrated with 1500 fields and eight concurrent SDK discovery requests. */ @@ -379,10 +394,15 @@ export interface EnvironmentCatalogOptions { readonly dataPlane?: EnvironmentDataPlane; /** What a served tool does, in place of how it answers; undefined keeps the answering sentence. */ readonly describe?: (tool: EnvironmentManifestTool) => string | undefined; - /** The body a served tool takes in place of the method's, as a bulk write names its entities in it. */ + /** The body a served tool takes in place of the recorded one: a bulk write's ids, members it fixes, the object it wraps. */ readonly body?: ( tool: EnvironmentManifestTool, + recorded: EnvironmentToolProperty, ) => EnvironmentToolProperty | undefined; + /** The query a served write's recording pins, by parameter, which each call takes. */ + readonly query?: ( + tool: EnvironmentManifestTool, + ) => ReadonlyMap | undefined; } /** The body a tool takes in a catalog: a served plan's, else the method's. */ @@ -393,7 +413,10 @@ const catalogBody = ( readonly property: EnvironmentToolProperty | undefined; readonly withBody: boolean; } => { - const property = body?.(tool); + const property = body?.(tool, { + type: "object", + description: bodyDescription(tool), + }); return { property, withBody: WRITE_METHODS.has(tool.method) || property !== undefined, @@ -409,6 +432,7 @@ export const environmentToolDefinitions = ( dataPlane = "none", describe, body, + query, }: EnvironmentCatalogOptions = {}, ): Result< readonly EnvironmentToolDefinition[], @@ -421,6 +445,8 @@ export const environmentToolDefinitions = ( return true; }; const text = (value: string): boolean => reserve(2 + value.length * 6); + const fits = (property: EnvironmentToolProperty): boolean => + text(property.description) && reserve(schemaBytes(property)); const refused = () => err( new AnalysisResourceConstraintError( @@ -471,13 +497,9 @@ export const environmentToolDefinitions = ( for (const [argument, property, mandatory] of environmentToolProperties( tool, args, - taken, + { body: taken, query: query?.(tool) }, )) { - if ( - !text(argument) || - !text(property.description) || - (mandatory && !text(argument)) - ) + if (!text(argument) || !fits(property) || (mandatory && !text(argument))) return refused(); properties.set(argument, property); if (mandatory) required.push(argument); diff --git a/src/domain/analysisView/environmentStateCheckedLines.ts b/src/domain/analysisView/environmentStateCheckedLines.ts index a68626fbd1e..b9e976ae0b9 100644 --- a/src/domain/analysisView/environmentStateCheckedLines.ts +++ b/src/domain/analysisView/environmentStateCheckedLines.ts @@ -19,13 +19,16 @@ import { } from "./environmentStateRules.js"; import { pagesOnly } from "./environmentStatePaging.js"; -/** A query as replay compares a call's: decoded values by name, in any order; undefined when it repeats a name with another value, which no call's arguments can carry. */ -const queryKey = (query: string | undefined): string | undefined => { - const values = singleQueryValues(query); - if (values === undefined) return undefined; - return compositeKey( - [...values].sort(([left], [right]) => compare(left, right)), - ); +/** A query's decoded values by name, in any order, as replay compares a call's. */ +export const queryValuesKey = (values: ReadonlyMap): string => + compositeKey([...values].sort(([left], [right]) => compare(left, right))); + +/** A query as replay compares a call's; undefined when it repeats a name with another value, which no call's arguments can carry. */ +export const queryKey = ( + query: string | null | undefined, +): string | undefined => { + const values = singleQueryValues(query ?? undefined); + return values === undefined ? undefined : queryValuesKey(values); }; interface CheckedLine { diff --git a/src/domain/analysisView/environmentStateWriteAddress.test.ts b/src/domain/analysisView/environmentStateWriteAddress.test.ts index 674f3fbabb1..a3d873ded30 100644 --- a/src/domain/analysisView/environmentStateWriteAddress.test.ts +++ b/src/domain/analysisView/environmentStateWriteAddress.test.ts @@ -92,6 +92,22 @@ describe("bulk writes at a collection", () => { ), ).toMatchObject({ served: false, reason: "body-unusable" }); }); + it("models no bulk call sent with another query than the exemplar's, which may do something else", () => { + // A delete sent with force=false kept book 1, which a modelled delete would have removed. + expect( + planOf( + [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books?force=true", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["DELETE", "/api/books?force=false", [{ id: 1 }], 200, [{ id: 1 }]], + ["GET", "/api/books/1", FIRST_BOOK], + ], + "delete_books", + ), + ).toMatchObject({ served: true, checked_record_ordinals: [4] }); + }); + it("serves no bulk call whose recorded response counts the entities it wrote", () => { expect( planOf( diff --git a/src/domain/analysisView/environmentStateWriteAddress.ts b/src/domain/analysisView/environmentStateWriteAddress.ts index ed24687d64b..ab440c9d3f6 100644 --- a/src/domain/analysisView/environmentStateWriteAddress.ts +++ b/src/domain/analysisView/environmentStateWriteAddress.ts @@ -13,6 +13,7 @@ import { type StateView, } from "./environmentStateRules.js"; import { entityTarget, succeeded } from "./environmentStateWriteChecks.js"; +import type { WriteIo } from "./environmentStateWriteEffects.js"; import { pathValuesOf, type BodyAddress, @@ -25,7 +26,10 @@ import { const BULK_DELETE_SEGMENTS = new Set(["delete", "remove", "destroy"]); /** What classifying an addressed write reads: the state types, their id fields and item views, and the tool's recorded calls. */ -export interface AddressFacts { +export interface AddressFacts extends Pick< + WriteIo, + "withBody" | "requestBody" | "emptyResponse" +> { readonly types: ReadonlySet; readonly idField: (type: string) => string | undefined; /** Where item reads of a type show its entity, and the fields each always shows. */ @@ -35,12 +39,6 @@ export interface AddressFacts { }[]; /** The tool's successful calls. */ readonly calls: readonly StateRecordFacts[]; - readonly withBody: ( - ordinal: number, - use: (body: JsonValue | undefined) => T, - ) => T; - readonly requestBody: (ordinal: number) => JsonValue | undefined; - readonly emptyResponse: (ordinal: number) => boolean; } /** An addressed write's effect, the type it writes and how its calls name the entities. */ @@ -253,14 +251,17 @@ export const namedEntities = ( : undefined; }; -/** The collection path a bulk call writes in: its path, without a delete segment, with the type's spelling of the last segment. */ -export const bulkCollection = (target: string, path: string): string => { - const written = segmentsOf(path); - const depth = segmentsOf(target).length; - const collection = written.slice(0, depth); - const spelled = segmentsOf(target).at(-1)!; - if (!isParam(spelled)) collection[depth - 1] = spelled; - return `/${collection.join("/")}`; +/** The segments of the collection a bulk call writes in: its path's, without a delete segment, with the type's spelling of the last one. */ +export const bulkCollectionOf = ( + target: string, + segments: readonly T[], + spelled: (text: string) => T, +): T[] => { + const typed = segmentsOf(target); + const collection = segments.slice(0, typed.length); + const last = typed.at(-1)!; + if (!isParam(last)) collection[typed.length - 1] = spelled(last); + return collection; }; /** An item action call's path without its action segment: the item path its entity is read under. */ @@ -273,10 +274,7 @@ export const addressedWrite = ( input: Pick & { readonly views: Iterable; readonly records: readonly StateRecordFacts[]; - readonly io: Pick< - AddressFacts, - "withBody" | "requestBody" | "emptyResponse" - >; + readonly io: Pick; }, ): AddressedWrite | undefined => { const ordinals = new Set(tool.record_ordinals); diff --git a/src/domain/analysisView/environmentStateWriteApply.test.ts b/src/domain/analysisView/environmentStateWriteApply.test.ts index e21d3d7c569..f0f7b82f35d 100644 --- a/src/domain/analysisView/environmentStateWriteApply.test.ts +++ b/src/domain/analysisView/environmentStateWriteApply.test.ts @@ -98,7 +98,7 @@ it.each<[string, JsonObject | undefined, string]>([ [ "a fixed member with another value", { title: "B", priority: "LOW" }, - `Member priority is accepted only with the value the capture sent, because the application stored it differently or other recorded fields go with it (${LISTED}).`, + `Member priority is accepted only with the value the capture sent, "HIGH", because the application stored it differently or other recorded fields go with it (${LISTED}).`, ], [ "a number for a string", diff --git a/src/domain/analysisView/environmentStateWriteApply.ts b/src/domain/analysisView/environmentStateWriteApply.ts index aa53446bd56..4bb91c08bfc 100644 --- a/src/domain/analysisView/environmentStateWriteApply.ts +++ b/src/domain/analysisView/environmentStateWriteApply.ts @@ -111,6 +111,15 @@ const listed = (members: readonly string[]): string => { const bodyContract = (body: WriteBody): string => `accepted members: ${listed(body.accepted)}; members accepted only with their recorded value: ${listed(body.fixed.map(({ member }) => member))}; required: ${listed(body.required)}`; +/** Recorded values up to this many characters are shown where a served write names them; a longer one is only named. */ +const SHOWN_VALUE_CHARS = 120; + +/** A recorded value as JSON text, when short enough to show. */ +export const shownValue = (value: JsonValue): string | undefined => { + const text = JSON.stringify(value); + return text.length <= SHOWN_VALUE_CHARS ? text : undefined; +}; + /** Why a call's body does not fit the members the capture showed, if it does not; `shapes` gives each accepted member's JSON type, else the body's recorded kind. */ export const bodyProblem = ( body: WriteBody, @@ -128,7 +137,7 @@ export const bodyProblem = ( } if (fixed.has(member)) { if (!same(fixed.get(member), value)) - return `Member ${member} is accepted only with the value the capture sent, because the application stored it differently or other recorded fields go with it (${bodyContract(body)}).`; + return `Member ${member} is accepted only with the value the capture sent, ${shownValue(fixed.get(member)!) ?? "too long to show here"}, because the application stored it differently or other recorded fields go with it (${bodyContract(body)}).`; continue; } if (!body.accepted.includes(member)) diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 82ffe0c1ee7..cf0fd3f11a2 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -4,13 +4,15 @@ import { isObject, locateItem, scalarText, + segmentsOf, } from "./environmentStateRules.js"; import { - bulkCollection, + bulkCollectionOf, namedEntities, type NamedEntity, } from "./environmentStateWriteAddress.js"; import { itemTarget } from "./environmentStateWriteChecks.js"; +import { sameQuery } from "./environmentStateWriteStamps.js"; import { deleteEntity } from "./environmentStateWriteDelete.js"; import { built, @@ -83,11 +85,20 @@ export const applyBulk = ( address === undefined || address.by === "action" ? undefined : namedEntities(address, body, context.idField(type)); + // A call with another query than the exemplar's may do something else, as serving refuses it. + if ( + built(draft) && + !sameQuery( + context.io.queryOf(draft.plan.exemplar_ordinal ?? -1), + step.record.query, + ) + ) + return [UNKNOWN]; if (named === undefined) { fail(draft, step, "body-unusable"); return [UNKNOWN]; } - const collection = bulkCollection(type, step.record.path); + const collection = `/${bulkCollectionOf(type, segmentsOf(step.record.path), (text) => text).join("/")}`; const wasBuilt = built(draft); const results = named.map(({ id, body: members }) => { const target = itemTarget(context.state, type, { diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 62b08c8ca12..a722a4c2fd3 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -217,9 +217,7 @@ export const requestObject = ( draft && { built: built(draft), envelope: draft.plan.body?.envelope, - query: context.records.find( - (other) => other.ordinal === draft.plan.exemplar_ordinal, - )?.query, + query: context.io.queryOf(draft.plan.exemplar_ordinal ?? -1), }, ); diff --git a/src/domain/analysisView/environmentStateWriteStamps.test.ts b/src/domain/analysisView/environmentStateWriteStamps.test.ts index 587c2fecef3..044298a3119 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.test.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.test.ts @@ -10,7 +10,8 @@ import type { FieldRule } from "./environmentStateWriteRules.js"; import { envelopeOf, nestedClockValue, - queryKey, + pinnedQuery, + sameQuery, stampProblem, storedRestamp, } from "./environmentStateWriteStamps.js"; @@ -580,7 +581,19 @@ describe("call shapes", () => { envelopeOf({ posts: [{ title: "A" }, { title: "B" }] }), ).toBeUndefined(); expect(envelopeOf({ posts: [{ title: "A" }], meta: {} })).toBeUndefined(); - expect(queryKey("?source=html&b=2")).toBe(queryKey("b=2&source=html")); - expect(queryKey(null)).toBe(""); + expect(sameQuery("?source=html&b=2", "b=2&source=html")).toBe(true); + expect(sameQuery(null, "")).toBe(true); + expect(sameQuery("a=1&a=2", "a=1&a=2")).toBe(false); + // A call that leaves a pinned parameter out takes the recorded value; another value or parameter is refused. + const recorded = "?source=html"; + expect(pinnedQuery(recorded, new Map())).toEqual({ + ok: true, + value: new Map([["source", "html"]]), + }); + expect(pinnedQuery(recorded, new Map([["source", "markdown"]]))).toEqual({ + ok: false, + error: "takes only the query its recording sent (source=html).", + }); + expect(pinnedQuery(null, new Map([["page", "2"]])).ok).toBe(false); }); }); diff --git a/src/domain/analysisView/environmentStateWriteStamps.ts b/src/domain/analysisView/environmentStateWriteStamps.ts index e2aa693ecfd..e6dca7db5bc 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.ts @@ -1,6 +1,5 @@ import type { JsonValue } from "../jsonValue.js"; import { err, ok, type Result } from "../result.js"; -import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { IDENTITY_NAMES, isObject, @@ -12,6 +11,8 @@ import { laterObservation, type ObservationSearch, } from "./environmentStateWriteObserve.js"; +import { singleQueryValues } from "../recordedTransportUrl.js"; +import { queryKey, queryValuesKey } from "./environmentStateCheckedLines.js"; import type { FieldRule } from "./environmentStateWriteRules.js"; import { isUuid, readClock } from "./environmentStateWriteValues.js"; @@ -114,8 +115,8 @@ export const plannedObject = ( } | undefined, ): JsonObject | undefined => { - // Serving takes only the query the exemplar sent, which may change what the body does. - if (plan?.built === true && queryKey(plan.query) !== queryKey(call.query)) + // A recorded call with another query than the exemplar's may do something else with its body. + if (plan?.built === true && !sameQuery(plan.query, call.query)) return undefined; const envelope = plan === undefined @@ -127,25 +128,35 @@ export const plannedObject = ( return object !== undefined && isObject(object) ? object : undefined; }; -/** A query's parameters in one order, so two spellings of one query compare equal. */ -export const queryKey = ( - query: string | URLSearchParams | null | undefined, -): string => - new URLSearchParams( - [...new URLSearchParams(query ?? "")].sort( - ([a, x], [b, y]) => compare(a, b) || compare(x, y), - ), - ).toString(); +/** Whether two queries name the same values; a query repeating a name with another value matches none. */ +export const sameQuery = ( + left: string | null | undefined, + right: string | null | undefined, +): boolean => { + const key = queryKey(left); + return key !== undefined && key === queryKey(right); +}; -/** Why a write call's query is not the one its recording sent, which may change what the body does; undefined when it is. */ -export const queryProblem = ( +/** + * A write call's query as its recording pins it, which may change what the body does: each + * parameter the recording sent, at the call's value or else the recorded one; an error naming the + * recorded query when the call sends another value or parameter. + */ +export const pinnedQuery = ( recorded: string | null | undefined, call: ReadonlyMap, -): string | undefined => { - const want = queryKey(recorded); - return want === queryKey(new URLSearchParams([...call])) - ? undefined - : `takes only the query its recording sent (${want === "" ? "none" : want}).`; +): Result, string> => { + const values = singleQueryValues(recorded ?? undefined); + const pinned = new Map([...(values ?? []), ...call]); + const spelled = [...(values ?? [])] + .map(([name, value]) => `${name}=${value}`) + .join("&"); + return values !== undefined && + queryValuesKey(pinned) === queryValuesKey(values) + ? ok(pinned) + : err( + `takes only the query its recording sent (${spelled === "" ? "none" : spelled}).`, + ); }; /** Whether the type's other entities hold the field as objects agreeing with this one but in the members, which hold other clocks. */ diff --git a/tests/boundary/mcp/toolSchemaValidity.test.ts b/tests/boundary/mcp/toolSchemaValidity.test.ts index 2f1c052f97a..00e042385ba 100644 --- a/tests/boundary/mcp/toolSchemaValidity.test.ts +++ b/tests/boundary/mcp/toolSchemaValidity.test.ts @@ -16,10 +16,12 @@ import { import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js"; import { servedCatalog } from "../../../src/application/environment/environmentState.js"; import { servedFrom } from "../../fixtures/environmentStateServing.js"; +import type { TimedCaptureRow } from "../../fixtures/analysisView.js"; import { BOOK_INIT_ROWS, BOOK_NOT_FOUND, FIRST_BOOK, + THIRD_BOOK, } from "../../fixtures/environmentStateWrites.js"; interface ToolSchemas { @@ -439,29 +441,60 @@ const advertiseAndEnforceProcessEnvironmentKeyConstraint = } }; -describe("MCP JSON Schema validity", () => { - it("advertises served environment catalogs, bulk bodies included, in schemas clients accept", () => { - const served = servedFrom([ - ...BOOK_INIT_ROWS, - ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], - ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], - ["GET", "/api/books", [FIRST_BOOK]], - ]); - const catalog = servedCatalog(served.source, served.state, "books"); - if (!catalog.ok) throw catalog.error; - expect( - catalog.value.tools.some((tool) => tool.name === "delete_books"), - ).toBe(true); +describe("served environment catalogs", () => { + it("advertises served environment catalogs in schemas clients accept: bulk bodies, pinned queries and fixed members", () => { + const edition = { format: "HC", featured: 1 }; + const stored = { ...THIRD_BOOK, ...edition }; + const captures: readonly (readonly TimedCaptureRow[])[] = [ + [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ], + [ + ["GET", "/api/books", [{ ...FIRST_BOOK, ...edition }]], + ["GET", "/api/books/1", { ...FIRST_BOOK, ...edition }], + [ + "POST", + "/api/books?notify=quiet", + stored, + 201, + { + books: [ + { name: "Third Book", format: "hardcover", featured: true }, + ], + }, + ], + ["GET", "/api/books/3", stored], + ], + ]; + const tools = captures.flatMap((rows) => { + const served = servedFrom(rows); + const catalog = servedCatalog(served.source, served.state, "books"); + if (!catalog.ok) throw catalog.error; + return catalog.value.tools; + }); + const create = tools.find((tool) => tool.name === "post_books"); + expect(create?.inputSchema.properties["notify"]).toMatchObject({ + enum: ["quiet"], + }); + expect(JSON.stringify(create?.inputSchema)).toContain( + '"const":"hardcover"', + ); + expect(tools.some((tool) => tool.name === "delete_books")).toBe(true); expect( schemaErrors( - catalog.value.tools.map((tool) => ({ + tools.map((tool) => ({ name: tool.name, inputSchema: tool.inputSchema as unknown as Record, })), ), ).toEqual([]); }); +}); +describe("MCP JSON Schema validity", () => { it("preserves empty-array validation in the advertised representation", () => { const schema = z.toJSONSchema(emptyArraySchema); const ajv = new Ajv2020({ strict: false, validateFormats: false }); From 08c2532adc4277ac2a794597126a7f5628933392 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 11:10:20 -0700 Subject: [PATCH 39/68] docs(environment): specify and record the write-rule changes Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 11 --- .../agent-environments/write-rules/plan.md | 14 ++++ .../agent-environments/write-rules/spec.md | 71 +++++++++++++++++++ .../agent-environments/write-rules/tasks.md | 14 ++++ .../write-rules/verification.md | 57 +++++++++++++++ 5 files changed, 156 insertions(+), 11 deletions(-) create mode 100644 docs/specs/agent-environments/write-rules/plan.md create mode 100644 docs/specs/agent-environments/write-rules/spec.md create mode 100644 docs/specs/agent-environments/write-rules/tasks.md create mode 100644 docs/specs/agent-environments/write-rules/verification.md diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index 8ae9138a2eb..a6564ec6999 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -52,17 +52,6 @@ its cause in the recordings and the code. The five largest shared causes: new shaping parameter and its object carries or lacks members theirs do not, or selects some fields and leaves out members they always show, and an item only a replayed line showed, which the state never started with, answers with its own recording. -- **Item actions.** A write to an item path plus a literal segment that names no collection, whose calls answer nothing - or the entity (never a 201, and with every field its item read always shows), updates that entity; a scalar it - changes without sending is set on every call. It is served only once a call found every field it sets already at - that value, so a toggle is never served. An action never takes a read another write to the entity still needs. -- **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying - the id field, deletes or updates each one; serving takes the body as recorded, a `DELETE` included. -- **Per-response members.** A top-level member whose value is a UUID or a clock is minted per response on a path when - it differs on every repeat of that path's successful GET lines with no write between, and across the capture it - differed on at least two repeats and never stayed the same. Only views of that path, or item views whose collection - is that path, leave it out: item envelopes, and the write gate's item, list and document reads, compare without it. - The view names it in `per_response_members`, and serving keeps the recorded value. ## Acceptance diff --git a/docs/specs/agent-environments/write-rules/plan.md b/docs/specs/agent-environments/write-rules/plan.md new file mode 100644 index 00000000000..3912789f3e1 --- /dev/null +++ b/docs/specs/agent-environments/write-rules/plan.md @@ -0,0 +1,14 @@ +# Implementation plan + +1. **Blame and the constant guard.** A module attributes a failed item read to the writes whose fields it disagrees on, + and create explanation pins members a constant derives from. +2. **Update rules.** A module holds the stamp, derived, held-clock, nested-clock, token and envelope rules; write + plans record the recorded query and pinned members, and serving and the gate apply them alike. +3. **View order.** A module orders collections by whole order-free lines, another learns sorted string arrays from + read-backs, and the list query and the initial order share one order vocabulary. +4. **Bulk writes and item actions.** A module addresses writes at a collection or an action path; the gate applies + them per entity and serving answers them atomically. +5. **Per-response members.** A module finds members a path mints anew and leaves them out of that path's comparisons. +6. **Nested counters.** List facts and rendering read and write totals through JSON pointers. +7. **Tests and docs.** Each step's tests fail on the step before; the state-view, state-writes, list-queries and + state-coverage specs and the environment docs describe the new behaviour. diff --git a/docs/specs/agent-environments/write-rules/spec.md b/docs/specs/agent-environments/write-rules/spec.md new file mode 100644 index 00000000000..916a351af3c --- /dev/null +++ b/docs/specs/agent-environments/write-rules/spec.md @@ -0,0 +1,71 @@ +# Serve writes by what their recordings show + +Issue: https://github.com/morluto/rea/issues/4933 + +## Outcome + +After state targets, 30 write tools across the 50 published capture-built environments had a state target but were +refused (contradicted, an unexplained change, or a side effect), and 59 still had none. A diagnosis traced each +refused tool to the fields that differed between the gate's state and the recorded read, and named seven shared +causes. Seven of the 30 are refusals REA should keep (asynchronous jobs, rendered markup, reverse embeds, appended +relation rows), and six need only a better recording. This change addresses the causes REA can fix: + +- **Blame too broad.** A failed read contradicted every write it exercised, whatever fields differed. +- **Unsent update changes.** An update changing a field it did not send had no rule unless the change was a top-level + clock, unique value, slug, renewal or increment. +- **View order.** Collections took their initial order from the earliest sighting, and arrays a view lists sorted were + compared in written order. +- **Targets at a collection or an action path.** Bulk writes naming entities in the body, and actions at + `/{type}/{id}/{verb}`, had no target. +- **Per-response members.** A UUID or clock minted on every response made a view's envelope vary. +- **Nested counters.** A list total inside a paging object (`pageInfo.totalRows`) stayed at its recorded value. + +## Behaviour + +- **Blame.** A failed item read with no interfering unmodelled write contradicts the creates and deletes it exercised. + It contradicts an update only on a field that update wrote or its response showed, and a field the state lacks that + the read and the update's response both show is the update's change. A read that embeds a created entity elsewhere + and the state does not contradicts the create. +- **Constant guard.** A create member is accepted only with its recorded value when a constant derives from it: its + echoed text inside the constant, a referenced entity's string, or an instant beside a sent date, matched by related + field names. +- **Update rules.** An update's unsent change can be a modified-by stamp beside a created-by counterpart (with its id + sibling), a value derived from the one sent member stored nowhere (accepted only while the target holds the + recorded before-value), or a sent clock left in the call's own second. An unsent clock left in the call's own second + keeps the update unconfirmed until another call shows it stamped. Objects whose clocks moved with the request are + nested clocks, stored from the read-back on creates and updates; opaque tokens of a type's own length are + generated; an enveloped body is learned as its one object. A write takes only its recorded query, and an echoed + reference to a nested object or a state word paired with other fields stays at its recorded value. The served + catalog names these values. +- **View order.** A collection's initial order comes from the first list line that shows every entity its type's + sightings do and applies no order. A view renders a string array sorted only after a counted read-back shows an + order that neither the written order nor existing-values-first explains, and never once a read showed it unsorted. + Sort and direction parameters share one vocabulary and are never learned as inert. A create placed by disagreeing + sorts or a random id falls back to `last`. +- **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying + the id field, deletes or updates each one, all or none; serving refuses it unless every id is held. +- **Item actions.** A write to an item path plus a literal segment that names no collection, whose calls answer + nothing or the entity (never a 201, and with every field its item read always shows), updates that entity; a scalar + it changes without sending is set on every call. It is served only once a call found every field it sets already at + that value, so a toggle is never served. An action never takes a read another write to the entity still needs. +- **Per-response members.** A top-level member whose value is a UUID or a clock is minted per response on a path when + it differs on every repeat of that path's successful GET lines with no write between, and across the capture it + differed on at least two repeats and never stayed the same. Only views of that path, or item views whose collection + is that path, leave it out: item envelopes, and the write gate's item, list and document reads, compare without it. + The view names it in `per_response_members`, and serving keeps the recorded value. +- **Nested counters.** An item total in a top-level object beside the list is a counter on the same evidence as a + top-level one, rendered from the state through its pointer. + +## Acceptance + +- Over the 50 published captures, served write tools rise and none is lost except where the evidence cannot show the + write's own effect; write tools with no state target fall. +- Read calls that state serving answers keep matching their recordings, before the first write and across sessions. +- Every newly served write answers a call other than the recorded one correctly, or refuses it. + +## Not included + +- Soft deletes, appended relation rows, rendered markup and reverse embeds; creates completed from later reads. +- Templating literal ids by value (an opt-in rule served two deletes whose targets came from unserved writes wrongly). +- Identity aliases and resource names; per-response values that differ as instants. +- A replayed write leaves the state as it was, so a served write on an entity only a replayed write made refuses. diff --git a/docs/specs/agent-environments/write-rules/tasks.md b/docs/specs/agent-environments/write-rules/tasks.md new file mode 100644 index 00000000000..fb2a5a43b05 --- /dev/null +++ b/docs/specs/agent-environments/write-rules/tasks.md @@ -0,0 +1,14 @@ +# Tasks + +- [x] Blame a failed read on the writes whose fields it disagrees on, and pin members constants derive from. +- [x] Explain unsent update changes, nested clocks, tokens and envelopes by what the recording shows. +- [x] Order collections by whole lines and sort only arrays a read-back proves sorted. +- [x] Serve bulk writes at a collection and target item actions. +- [x] Set aside response members a path mints anew on every read. +- [x] Count a list total nested in a paging object. +- [x] Take a created entity's nested clocks from its read-back. +- [x] Confirm no update whose clocks or fields the evidence cannot show it writing. +- [x] Show pinned query and body values in the served catalog, and apply bulk writes atomically. +- [x] Add tests that fail on the step before each change. +- [x] Measure the 50 published captures, the served smoke and recorded-read serving after each step. +- [x] Run static, formatting, duplication, documentation and test gates. diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md new file mode 100644 index 00000000000..24f7c3fb181 --- /dev/null +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -0,0 +1,57 @@ +# Verification + +Executed on macOS with Node v22.23.1, one change at a time on the state-targets branch, over the 50 published +capture-built environments (each app's latest capture). The served smoke rebuilds each manifest with the tree under +test and applies every served write tool. The serving check answers every recorded read made before the capture's +first write through state serving and compares it with the recording; it reads no calls from the five +browser-scenario captures. The session replay answers every recorded call in order, writes included, through state +serving, reading records with REA's own capture parser, and compares the reads; it covers all 50 captures. + +## Gates + +- `npm run -s check:fast`, `npm run -s format:check`, `npx knip`, `npm run -s scan:todos`, `npm run -s docs:check`, + `npm run -s verify:test-discovery` and `npm run -s mcp-catalog:check`: passed. +- `npm run jscpd`: 3.57% duplicated lines over 4174 files (3.58% on the base). +- `npx vitest run --project domain --project services`: 9289 passed, 6 pre-existing skips. +- `npm run -s test:prepare`, then `npm run -s test:focused --` the environment serve and export CLI boundaries, the + serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary + and tool schema validity: 8 files, 91 passed. + +## Measurements + +| Step | Served | No state target | State-backed read views | Reads before first write | Session reads | +| ---------------------------- | ------ | --------------- | ----------------------- | ------------------------ | -------------- | +| state targets | 62 | 59 | 1,151 | 2,085 of 2,155 | 2,764 of 3,022 | +| blame and constant guard | 63 | 59 | 1,151 | 2,085 of 2,155 | 2,764 of 3,022 | +| update rules | 68 | 59 | 1,151 | 2,085 of 2,155 | 2,763 of 3,022 | +| view order | 69 | 59 | 1,151 | 2,085 of 2,155 | 2,763 of 3,022 | +| bulk writes and item actions | 71 | 48 | 1,151 | 2,085 of 2,155 | 2,763 of 3,022 | +| per-response members | 71 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| nested counters | 71 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| created nested clocks | 71 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| unshown writes refused | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| catalog values, atomic bulk | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | + +All 187 write tools are counted at every step, and the served smoke applies every served write tool. + +- **Newly served:** Ghost's post create and update, Metabase's card create and update, n8n's workflow update, + Navidrome's playlist create, and the NocoDB and Mailpit bulk deletes. +- **No longer served:** Gitea's issue update. Its create, update and read share one second, so the evidence cannot show + the update stamping `updated_at`, and serving it left the clock as it was. +- **Refused that were briefly served on this branch:** EspoCRM's task update, for the same reason, with `modifiedById` + absent from its create response. +- **Session reads:** one read is lost at Ghost #74, a 404 right after the served create whose delete the recording + lacks; Vault #80 answers 404 after an unserved create, as a served read on an entity only a replayed write made does. +- Ghost's create and update accept only the recorded html, and Metabase's create only the recorded collection, + display, type and query; the served catalog shows those values. + +Every change had an independent review that rebuilt it and tried to refute it; the corrections they found are part of +the change. A final review of the whole branch found one wrongly served update (EspoCRM) and the hidden pinned values, +both fixed. + +## Not included + +- Templating literal ids by value: an opt-in rule served Grafana's folder delete and Vault's policy delete, but both + targets came from unserved writes, so serving them answered their own recorded calls wrongly. +- Completing a created entity from a later read: it served Bookstack's page create wrongly. +- Soft deletes, appended relation rows, rendered markup, reverse embeds, identity aliases and resource names. From e08f003721d16e1d21eeb450f25ef4317cbd9502 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 13:31:24 -0700 Subject: [PATCH 40/68] fix(environment): keep served creates' items missing, check same-type earlier reads, and bound late lines and read-only stretches - An item only a replayed line showed replays only while no served create has added to its type, so a created and deleted item stays missing. - A linked create's earlier item-read veto checks only reads of the candidate's type or collection that show the item, so another type's id does not hide it. - An item read answered with JSON null shows no id to a creation cut. - Late lines' member names are charged before they are kept. - The read-only check precomputes nearest writes and passes once over each write-free stretch per path, skipping lines whose reads all agree. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 19 ++- .../agent-environments/state-view/spec.md | 4 +- .../agent-environments/state-writes/spec.md | 4 +- .../environment/environmentStateAnswer.ts | 4 +- .../environment/environmentStateStore.ts | 9 + .../environmentStateWriteAnswer.test.ts | 27 +++ .../EnvironmentStateExtraction.ts | 14 +- .../environmentStateQueryCalls.test.ts | 55 ++++++ .../environmentStateQueryCalls.ts | 156 ++++++++++++------ .../analysisView/environmentStateView.test.ts | 27 +++ .../environmentStateWriteLinks.test.ts | 35 ++++ .../environmentStateWriteLinks.ts | 38 +++-- .../environmentStateWrites.test.ts | 19 +++ 13 files changed, 338 insertions(+), 73 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index a6564ec6999..f34a655bf96 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -29,13 +29,14 @@ its cause in the recordings and the code. The five largest shared causes: models or one redirected or unanswered, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names - an id its response returned, before any other tool's write, when the id is new: no read finished before it began, of - the id, its type's lists or that collection, showed it. Its observation is a read of an id its response returned, in - an envelope too. Serving creates in that read's collection, for the exemplar's path arguments only (segment by - segment, in either spelling), and fills path fields with its exemplar's path values decoded once. A successful POST - that returned an id a type's reads only show once it began ends that type's initial window: a read still running - then may show it, and a list read shows its listed entities' own ids (identity-named, or a suffix-named field such - as `projectId` distinct across two or more when no id-named field identifies them), not those they nest. + an id its response returned, before any other tool's write, when the id is new: no read finished before it began + showed it, whether an item read of the id under that type or collection whose body shows the item, a list of the + type or a read of that collection. Its observation is a read of an id its response returned, in an envelope too. + Serving creates in that read's collection, for the exemplar's path arguments only (segment by segment, in either + spelling), and fills path fields with its exemplar's path values decoded once. A successful POST that returned an id + a type's reads only show once it began ends that type's initial window: a read still running then may show it, and a + list read shows its listed entities' own ids (identity-named, or a suffix-named field such as `projectId` distinct + across two or more when no id-named field identifies them), not those they nest. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. - **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's @@ -50,8 +51,8 @@ its cause in the recordings and the code. The five largest shared causes: than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. An item line first recorded after the initial window is a variant too, judged against the lines left once variants are dropped: when it names a new shaping parameter and its object carries or lacks members theirs do not, or selects some fields and leaves out - members they always show, and an item only a replayed line showed, which the state never started with, answers with - its own recording. + members they always show, and an item only a replayed line showed, which the state never started with and in whose + type no served create has added an entity since, answers with its own recording. ## Acceptance diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 94416f3465d..48a1b2d8eae 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -31,7 +31,9 @@ later increments. more) that the type's reads show only once it began: the `POST` made that entity, so it is not in the initial state. A read finished before the `POST` began shows what was there, and one still running may show its effect. A list - read shows the ids its listed entities carry as their own identity members, and + read shows the ids its listed entities carry as their own identity members, an + item read its path's id only when its body shows the item (a JSON `null` shows + none), and across two or more of them, when no id-named field (`id`, `uuid`, …; not `key`, `slug` or `name`) identifies them, the first suffix-named field (`projectId`) distinct on each, so a foreign key beside an `id` is none of theirs, nor are the diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index 804a308cf53..e9666d7da62 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -91,7 +91,9 @@ or more), and the first later successful item read naming that id belongs to a state type. That read must come before any other tool's write, which may have made what it shows, as a publish call makes a note from a draft. The entity must be new: neither the initial state nor any read finished before the call began -holds that id (one still running may show what the call made), whether an +holds that id (one still running may show what the call made): an item read of +it under the item read's type or collection whose body shows the item (a JSON +`null` is an absence), a list read of its type, or any read of that collection, whether an item read of it, a list read of its type, or any read of the item read's collection, with or without a query, that lists it under an identity member of its own (a body with no list counts an identity member at any depth). An id shorter than four characters may be any type's, diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 7c3c6f31412..3c8a126ae9f 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -325,9 +325,11 @@ const answerItem = ( // A projection or another representation of an entity the state holds replays as the capture's reads did. const replayed = replayedCall(source, view, callQuery(tool, args)); if (entity === undefined) { - // An item only a replayed line showed, which the state never started with, answers with its own recording. + // An item only a replayed line showed, which the state never held, answers with its own recording; a created + // item may since have been deleted, so a type a served create added to keeps the missing answer. if ( replayed !== undefined && + !store.createdInto(view.type) && !startedWithItem(store, view.type, call) && selectReplayExchange(tool, source.exchanges, args, observedQuery) ?.exact === true diff --git a/src/application/environment/environmentStateStore.ts b/src/application/environment/environmentStateStore.ts index 5f0a8479229..dcb2b233d6a 100644 --- a/src/application/environment/environmentStateStore.ts +++ b/src/application/environment/environmentStateStore.ts @@ -117,6 +117,8 @@ export class EnvironmentStateStore { readonly #sequences = new Map(); /** The entities the state held when it was last reset or loaded, whose values no sequence reuses either. */ #started: readonly StateEntity[] = []; + /** The types a served create has added an entity to since the last reset or load. */ + readonly #createdTypes = new Set(); /** Baseline and post-start spellings kept known after their entities are deleted. */ readonly #knownCollections = new Map>(); /** Logical UTF-8 key bytes plus a 64-byte allowance per collection and potential sequence-key record. */ @@ -210,6 +212,7 @@ export class EnvironmentStateStore { this.#writes = 0; this.#sequences.clear(); this.#started = this.#content.entities; + this.#createdTypes.clear(); this.#knownCollections.clear(); this.#collectionHistoryBytes = 0; for (const [type, collections] of this.#typeCollections) @@ -227,6 +230,11 @@ export class EnvironmentStateStore { } /** The entities of a type the state held when it was last reset or loaded. */ + /** Whether a served create has added an entity of the type since the last reset or load. */ + createdInto(type: string): boolean { + return this.#createdTypes.has(type); + } + startedWith(type: string): readonly StateEntity[] { return this.#started.filter((entity) => entity.type === type); } @@ -294,6 +302,7 @@ export class EnvironmentStateStore { this.#rememberCollection(entity.type, entity.collection); this.#collectionHistoryBytes += newCollectionBytes; } + this.#createdTypes.add(entity.type); return ok(undefined); } diff --git a/src/application/environment/environmentStateWriteAnswer.test.ts b/src/application/environment/environmentStateWriteAnswer.test.ts index f806060c9b5..cd3940540b7 100644 --- a/src/application/environment/environmentStateWriteAnswer.test.ts +++ b/src/application/environment/environmentStateWriteAnswer.test.ts @@ -482,6 +482,33 @@ describe("items only a replayed line showed", () => { }); }); +describe("items a served write made and removed", () => { + it("finds an item a served create made and a served delete removed missing, though a variant line recorded it", () => { + const created = book(3, "Third Book", bookClock(4)); + const books = servedFrom([ + ["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books/2", SECOND_BOOK], + ["GET", "/api/books/1?expand=shelf", expandedBook(FIRST_BOOK)], + ["POST", "/api/books", created, 201, { name: "Third Book" }], + ["GET", "/api/books/3", created], + ["GET", "/api/books/3?expand=shelf", expandedBook(created)], + ["DELETE", "/api/books/3", "", 204], + ["GET", "/api/books/3", BOOK_NOT_FOUND, 404], + ]); + expect(books.state.writes.get("post_books")).toMatchObject({ + served: true, + }); + expect(books.state.writes.get("delete_books_by_id")).toMatchObject({ + served: true, + }); + books.answer("post_books", { body: { name: "Third Book" } }); + books.answer("delete_books_by_id", { id: "3" }); + const read = books.call("get_books_by_id", { id: "3", expand: "shelf" }); + expect(read.ok && read.value.status === 200).toBe(false); + }); +}); + describe("field selections beside replayed reads", () => { it("replays a field selection no checked line gave, and answers a selection of every field from the state", () => { const books = servedFrom([ diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 95163329fa9..1d3f03a1865 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -88,9 +88,9 @@ const requestLine = (record: StateRecordFacts): string => record.path + (record.query ?? ""); /** The member names of the object at a pointer, none when it holds no object. */ -const membersAt = (body: JsonValue, pointer: string): Set => { +const memberNames = (body: JsonValue, pointer: string): string[] => { const object = at(body, pointer); - return new Set(isObject(object) ? Object.keys(object) : []); + return isObject(object) ? Object.keys(object) : []; }; /** Derive the init state and render plans from manifest tools and timeline-ordered records. */ @@ -452,9 +452,13 @@ export class EnvironmentStateExtraction { const located = locateItem(body, lastSegmentValue(record.path)); if (located === undefined) return projecting ? null : undefined; if (!selecting && !shaping) return undefined; - const members = membersAt(body, located.pointer); - this.#retain(ENTRY_BYTES * (2 + members.size)); - return { record, members, projecting: selecting }; + const names = memberNames(body, located.pointer); + // The kept set holds the names, which the body's own reservation no longer covers. + this.#retain( + ENTRY_BYTES * (2 + names.length) + + names.reduce((bytes, name) => bytes + textBytes(name.length), 0), + ); + return { record, members: new Set(names), projecting: selecting }; }); if (line === null) { this.#retain(ENTRY_BYTES); diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index ca3d4cd4d9a..f8d64ad160d 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -429,6 +429,61 @@ describe("the reads either side of a POST", () => { }); }); +describe("read-only decisions over many calls", () => { + it("visits each write-free stretch once for all of a lookup's calls in it", () => { + let visits = 0; + const calls = 2000; + const records: StateRecordFacts[] = Array.from( + { length: calls * 2 }, + (_, index) => { + const read = index % 2 === 0; + const record = { + ordinal: index, + path: read ? "/api/members" : "/api/members/ids", + query: undefined, + status: 200, + start: index, + end: index, + }; + const method = read ? "GET" : "POST"; + return Object.defineProperty(record, "method", { + enumerable: true, + get: () => { + visits += 1; + return method; + }, + }) as StateRecordFacts; + }, + ); + const ordinals = (read: boolean) => + records + .filter((record) => (record.ordinal % 2 === 0) === read) + .map((record) => record.ordinal); + const tools: StateToolFacts[] = [ + { + name: "get_members", + method: "GET", + path_template: "/api/members", + record_ordinals: ordinals(true), + }, + { + name: "post_ids", + method: "POST", + path_template: "/api/members/ids", + record_ordinals: ordinals(false), + }, + ]; + visits = 0; + expect([ + ...readOnlyTools(tools, records, { + response: () => [], + request: () => undefined, + }), + ]).toEqual(["post_ids"]); + expect(visits).toBeLessThan(50 * records.length); + }); +}); + describe("read-only decisions over many lines", () => { it("reads each related line's records once per call, however many lines the lookup's path relates to", () => { let reads = 0; diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 93013590923..05bf1c232e5 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -160,18 +160,29 @@ export const readOnlyTools = ( const position = new Map( records.map((record, index) => [record.ordinal, index]), ); - /** The timeline indexes of the nearest state writes either side of `at`, the skipped calls aside: -1 and the length when none. */ - const nearestWrites = - (skip: ReadonlySet) => - (at: number): { readonly before: number; readonly after: number } => { - const writes = (index: number): boolean => - !skip.has(records[index]!.ordinal) && isStateWrite(records[index]!); - let before = at - 1; - while (before >= 0 && !writes(before)) before -= 1; - let after = at + 1; - while (after < records.length && !writes(after)) after += 1; - return { before, after }; - }; + /** The timeline indexes of the nearest state writes either side of an index, the skipped calls aside: -1 and the length when none, found in one pass each way. */ + const nearestWrites = ( + skip: ReadonlySet, + ): ((at: number) => { readonly before: number; readonly after: number }) => { + const writes = records.map( + (record) => !skip.has(record.ordinal) && isStateWrite(record), + ); + const before: number[] = []; + const after: number[] = Array.from({ length: records.length }); + for (let index = 0, last = -1; index < records.length; index += 1) { + before.push(last); + if (writes[index]) last = index; + } + for ( + let index = records.length - 1, next = records.length; + index >= 0; + index -= 1 + ) { + after[index] = next; + if (writes[index]) next = index; + } + return (at) => ({ before: before[at]!, after: after[at]! }); + }; const candidates = new Map(); for (const tool of tools) { if ( @@ -289,48 +300,101 @@ const lastMeaningfulWord = (segment: string): string | undefined => * A GET line whose path a call's path relates to reads differently, or finds its entity present on one * side only, just before and just after it, with no other write between: the read that finished last * before it began and the first begun after it ended, since one overlapping it may show either state. - * One pass over the reads between the nearest other writes serves every line. + * Calls in one write-free stretch under one path share a pass over it, and only lines whose reads + * there disagree can change across a call. */ const changesReadsAcross = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], { position, writes, io }: Timeline, -): boolean => - calls.filter(succeeded).some((call) => { +): boolean => { + const stretches = new Map< + string, + { from: number; to: number; path: string; calls: StateRecordFacts[] } + >(); + for (const call of calls.filter(succeeded)) { + const { before, after } = writes(position.get(call.ordinal)!); + const key = JSON.stringify([before, after, call.path]); + const stretch = stretches.get(key); + if (stretch === undefined) + stretches.set(key, { + from: before, + to: after, + path: call.path, + calls: [call], + }); + else stretch.calls.push(call); + } + for (const stretch of stretches.values()) + if (changesInStretch(stretch, records, { position, io })) return true; + return false; +}; + +/** Whether a related line changes across one of these calls, all between the same two writes under one path. */ +const changesInStretch = ( + stretch: { + readonly from: number; + readonly to: number; + readonly path: string; + readonly calls: readonly StateRecordFacts[]; + }, + records: readonly StateRecordFacts[], + { position, io }: Pick, +): boolean => { + const shown = (record: StateRecordFacts): JsonValue | symbol => { + if (!succeeded(record)) return ABSENT; + const body = io.response(record.ordinal); + return body === undefined ? UNKNOWN : body; + }; + const lines = new Map(); + for (let index = stretch.from + 1; index < stretch.to; index += 1) { + const record = records[index]!; + if ( + record.method !== "GET" || + !(succeeded(record) || isAbsence(record.status)) || + !prefixRelated(stretch.path, record.path) + ) + continue; + const line = `${record.path}${record.query ?? ""}`; + const reads = lines.get(line); + if (reads === undefined) lines.set(line, [record]); + else reads.push(record); + } + // A line whose reads all show one thing cannot change across any call. + const changing = [...lines.values()].filter((reads) => { + const first = shown(reads[0]!); + return reads.some((read) => !sameShown(first, shown(read))); + }); + return stretch.calls.some((call) => { const at = position.get(call.ordinal)!; - const { before: lastWrite, after: nextWrite } = writes(at); - const before = new Map(); - const after = new Map(); - for (let index = lastWrite + 1; index < nextWrite; index += 1) { - const record = records[index]!; - if ( - index === at || - record.method !== "GET" || - !(succeeded(record) || isAbsence(record.status)) || - !prefixRelated(call.path, record.path) - ) - continue; - const line = `${record.path}${record.query ?? ""}`; - const latest = before.get(line); - if (index < at) { - if ( - record.end <= call.start && - (latest === undefined || record.end >= latest.end) - ) - before.set(line, record); - } else if (record.start >= call.end && !after.has(line)) - after.set(line, record); - } - return [...after].some(([line, later]) => { - const earlier = before.get(line); - if (earlier === undefined) return false; - if (succeeded(earlier) !== succeeded(later)) return true; - if (!succeeded(earlier)) return false; - const was = io.response(earlier.ordinal); - const now = io.response(later.ordinal); - return was !== undefined && now !== undefined && !same(was, now); + return changing.some((reads) => { + const earlier = lastFinishedBefore( + reads.filter((read) => position.get(read.ordinal)! < at), + call, + ); + const later = reads.find( + (read) => position.get(read.ordinal)! > at && read.start >= call.end, + ); + if (earlier === undefined || later === undefined) return false; + const [was, now] = [shown(earlier), shown(later)]; + // Presence on one side only is a change even when a body is unusable. + if ((was === ABSENT) !== (now === ABSENT)) return true; + return was !== UNKNOWN && now !== UNKNOWN && !sameShown(was, now); }); }); +}; + +/** A read that found its entity gone, and one whose body is unusable. */ +const ABSENT = Symbol("absent"); +const UNKNOWN = Symbol("unknown"); + +const sameShown = ( + left: JsonValue | symbol, + right: JsonValue | symbol, +): boolean => + typeof left === "symbol" || typeof right === "symbol" + ? left === right + : same(left, right); /** The timeline's state writes, less the calls of tools whose calls only read, and those tools. */ export const stateWritesOf = ( diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index 346de1db863..2a9250f32b4 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -928,6 +928,33 @@ const allowance = (parent: AnalysisViewParent): number => { return high * 1024; }; +it("counts the member names of later item lines against the budget before keeping them", () => { + const reads = 20; + // Each later read of an item names members its initial reads never did, `width` characters long. + const capture = (width: number) => + captureOf([ + ["GET", "/api/items/1", { id: 1, name: "One" }], + ["POST", "/api/items", { id: 2, name: "Two" }, 201, { name: "Two" }], + ...Array.from({ length: reads }, (_, read): TimedCaptureRow => [ + "GET", + `/api/items/1?expand=meta&view=${String(read)}`, + { + id: 1, + name: "One", + ...Object.fromEntries( + Array.from({ length: 5 }, (_, member) => [ + `${String(read)}_${String(member)}_`.padEnd(width, "m"), + 1, + ]), + ), + }, + ]), + ]); + expect( + allowance(capture(400)) - allowance(capture(10)), + ).toBeGreaterThanOrEqual((reads * 5 * 390 * 14) / 2); +}); + it("counts each change of a line's membership across a write against the budget", () => { const tags = 64; // Each tag's list is read three times across two writes; the third read shows the first book again or keeps the second. diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index 6dbdcc7aed1..031fbe9ef9b 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -140,6 +140,41 @@ describe("creation limits", () => { ).toBeUndefined(); }); + it("counts no id an item read answered with JSON null, the absence the gate accepts, as shown", () => { + const item = record(0, "GET", "/api/projects/proj-0002"); + const post = record(1, "POST", "/api/imports"); + const later = record(2, "GET", "/api/projects"); + const bodies = new Map([ + [0, null], + [2, [{ id: "proj-0001" }, { id: "proj-0002" }]], + ]); + const limit = creationLimit( + [{ record: post, ids: ["proj-0002"] }], + { + type: "/api/projects", + tools: [ + { + name: "get_projects_by_id", + method: "GET", + path_template: "/api/projects/{id}", + record_ordinals: [0], + }, + { + name: "get_projects", + method: "GET", + path_template: "/api/projects", + record_ordinals: [2], + }, + ], + records: new Map([item, post, later].map((at) => [at.ordinal, at])), + position: (at) => at.ordinal, + body: (ordinal) => bodies.get(ordinal), + }, + undefined, + ); + expect(limit).toBe(post); + }); + it("reads the ids a list shows from its listed entities, not the entities they nest", () => { const [list, post, later] = [ record(0, "GET", "/api/projects"), diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 77da45ca33d..54fa984a4f5 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -7,6 +7,7 @@ import { isParam, lastSegmentValue, listItems, + locateItem, locateList, normalizedPath, pathSegmentMatches, @@ -103,13 +104,20 @@ const listedIds = (body: JsonValue | undefined): Set => { ]); }; -/** The ids a read shows: its listed entities' for a list read, or its path's id for an item read. */ +/** Whether an item read's body shows the entity its path names, not an absence such as JSON null. */ +const showsItem = (body: JsonValue | undefined, id: string): boolean => + body !== undefined && body !== null && locateItem(body, id) !== undefined; + +/** The ids a read shows: its listed entities' for a list read, or its path's id for an item read that shows the item. */ const shownIds = ( record: StateRecordFacts, item: boolean, body: () => JsonValue | undefined, -): Set => - item ? new Set([lastSegmentValue(record.path)]) : listedIds(body()); +): Set => { + if (!item) return listedIds(body()); + const id = lastSegmentValue(record.path); + return showsItem(body(), id) ? new Set([id]) : new Set(); +}; /** One read of a type: where it ran, when it finished, whether it reads one item, and the ids it shows. */ interface ShownRead { @@ -245,6 +253,7 @@ export const linkedCreate = (input: { readonly entities: readonly StateEntity[]; readonly respondedIds: (ordinal: number) => readonly string[]; readonly shownIds: (ordinal: number) => ReadonlySet; + readonly showsItem: (ordinal: number, id: string) => boolean; }): { readonly type: string; readonly collection: string } | undefined => { const { tool, records } = input; const own = new Set(tool.record_ordinals); @@ -259,13 +268,6 @@ export const linkedCreate = (input: { const before = records .slice(0, first) .filter((record) => record.end <= post.start); - for (const record of before) - if ( - record.method === "GET" && - succeeded(record) && - ids.has(lastSegmentValue(record.path)) - ) - return undefined; for (const record of records.slice(first + 1)) { // Another write may have made what a later read shows, so the search ends there. if (!own.has(record.ordinal) && input.isWrite(record)) return undefined; @@ -279,7 +281,21 @@ export const linkedCreate = (input: { continue; const id = lastSegmentValue(record.path); const collection = collectionPathOf(record, true); + // An earlier read of the id under another type or collection names another entity. + const readBefore = before.some((earlier) => { + const read = input.viewOf(earlier.ordinal); + return ( + earlier.method === "GET" && + succeeded(earlier) && + lastSegmentValue(earlier.path) === id && + ((read?.shape === "item" && read.type === view.type) || + normalizedPath(collectionPathOf(earlier, true)) === + normalizedPath(collection)) && + input.showsItem(earlier.ordinal, id) + ); + }); const held = + readBefore || input.entities.some( (entity) => entity.type === view.type && entity.id === id, ) || @@ -395,6 +411,8 @@ export const linkedTarget = ( entities: input.entities, respondedIds: (ordinal) => input.io.withBody(ordinal, respondedIds), shownIds: (ordinal) => input.io.withBody(ordinal, listedIds), + showsItem: (ordinal, id) => + input.io.withBody(ordinal, (body) => showsItem(body, id)), }) : undefined; return link === undefined diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 7342f9ad9d2..467705655d1 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1724,6 +1724,25 @@ describe("reads overlapping a linked create", () => { }); }); +describe("earlier reads of the returned id under other types", () => { + it("links a create whose id an earlier read of another type named", () => { + const user = { id: 1003, login: "gamma" }; + const state = stateOf([ + ["GET", "/api/users/1003", user], + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], + ]); + expect(planOf(state, "post_drafts_publish")).toMatchObject({ + effect: "create", + target: "/api/notes", + }); + }); +}); + describe("what a linked create observes", () => { it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { const D = note(1004, "Delta"); From e4c4940879b870b396778e44481881764a94405a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 13:31:26 -0700 Subject: [PATCH 41/68] docs(environment): record the ninth review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index cc815f63170..32346456e62 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -66,6 +66,9 @@ write tool is lost. its only later read, `/wp-json/wp/v2/posts/22?context=edit`, shows the edit representation (`generated_slug`), so it is now replayed rather than checked. No served write, read view or recorded read changes. - **Eighth round** (on main `3e7e102a`): no verdict, read view or recorded read changes on the restored captures. +- **Ninth round** (on main `b7ebccf8`): no verdict, read view, recorded read or session replay changes on the restored + captures (187 write tools, 62 served, 1,151 views, 2,085 of 2,155 initial reads and 2,764 of 3,022 session reads + matching). Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 6ee9703eec32c29f16f577358bfe2e67a3179d0d Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 14:23:17 -0700 Subject: [PATCH 42/68] fix(environment): link creates past empty item reads, sweep repeated reads once and keep only returned ids for creation cuts - A linked create passes over a later item read naming its id whose body shows no item, such as JSON null, and links the next one. - Read-only repeated reads are found in one sweep: each path's reads wait by end time until a call's start passes them, and a write clears them. - A creation cut keeps, and charges, only the shown ids some creation returned. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-writes/spec.md | 4 +- .../EnvironmentStateExtraction.ts | 1 + .../environmentStateQueryCalls.test.ts | 55 +++++++ .../environmentStateQueryCalls.ts | 153 +++++++++++++++--- .../environmentStateWriteLinks.test.ts | 63 +++++++- .../environmentStateWriteLinks.ts | 30 +++- .../environmentStateWrites.test.ts | 28 ++++ 7 files changed, 297 insertions(+), 37 deletions(-) diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index e9666d7da62..5517aa6ee94 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -87,8 +87,8 @@ same root regenerates values on every read. A `POST` whose path gives it no target is a `create` into the type its returned id is read under: its exemplar's response names an id (an identity member of the body or of an object member, or a scalar body or sole member of four characters -or more), and the first later successful item read naming that id belongs to a -state type. That read must come before any other tool's write, which may have +or more), and the first later successful item read naming that id, whose body +shows the item (a JSON `null` read is passed over), belongs to a state type. That read must come before any other tool's write, which may have made what it shows, as a publish call makes a note from a draft. The entity must be new: neither the initial state nor any read finished before the call began holds that id (one still running may show what the call made): an item read of diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 1d3f03a1865..3a2c73bc1ff 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -329,6 +329,7 @@ export class EnvironmentStateExtraction { records: this.#byOrdinal, position: (record) => this.#position.get(record.ordinal)!, body: (ordinal) => this.#withBody(ordinal, (body) => body), + retain: (bytes) => this.#retain(bytes), }, first, ) ?? first; diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index f8d64ad160d..3fb1c48809b 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -484,6 +484,61 @@ describe("read-only decisions over many calls", () => { }); }); +describe("read-only decisions over a long run of calls", () => { + it("finds each call's repeated read without rescanning the run before it", () => { + let visits = 0; + const calls = 2000; + const records: StateRecordFacts[] = Array.from( + { length: calls * 2 }, + (_, index) => { + const read = index % 2 === 0; + const record = { + ordinal: index, + path: "/v1/jobs/statuses", + query: undefined, + status: 200, + start: index, + end: index, + }; + const method = read ? "GET" : "POST"; + return Object.defineProperty(record, "method", { + enumerable: true, + get: () => { + visits += 1; + return method; + }, + }) as StateRecordFacts; + }, + ); + const ordinals = (read: boolean) => + records + .filter((record) => (record.ordinal % 2 === 0) === read) + .map((record) => record.ordinal); + const tools: StateToolFacts[] = [ + { + name: "get_statuses", + method: "GET", + path_template: "/v1/jobs/statuses", + record_ordinals: ordinals(true), + }, + { + name: "post_statuses", + method: "POST", + path_template: "/v1/jobs/statuses", + record_ordinals: ordinals(false), + }, + ]; + visits = 0; + expect([ + ...readOnlyTools(tools, records, { + response: () => JOBS, + request: () => ({ jobs: ["night-watch"] }), + }), + ]).toEqual(["post_statuses"]); + expect(visits).toBeLessThan(50 * records.length); + }); +}); + describe("read-only decisions over many lines", () => { it("reads each related line's records once per call, however many lines the lookup's path relates to", () => { let reads = 0; diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index 05bf1c232e5..d934153c82e 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -163,7 +163,7 @@ export const readOnlyTools = ( /** The timeline indexes of the nearest state writes either side of an index, the skipped calls aside: -1 and the length when none, found in one pass each way. */ const nearestWrites = ( skip: ReadonlySet, - ): ((at: number) => { readonly before: number; readonly after: number }) => { + ): Pick => { const writes = records.map( (record) => !skip.has(record.ordinal) && isStateWrite(record), ); @@ -181,7 +181,10 @@ export const readOnlyTools = ( after[index] = next; if (writes[index]) next = index; } - return (at) => ({ before: before[at]!, after: after[at]! }); + return { + writes: (at) => ({ before: before[at]!, after: after[at]! }), + isWrite: (index) => writes[index]!, + }; }; const candidates = new Map(); for (const tool of tools) { @@ -194,9 +197,13 @@ export const readOnlyTools = ( .map((ordinal) => records[position.get(ordinal) ?? -1]) .filter((record): record is StateRecordFacts => record !== undefined); if (!calls.some(succeeded) || calls.some(unresolved)) continue; - const writes = nearestWrites(new Set(tool.record_ordinals)); + const timeline = { + position, + ...nearestWrites(new Set(tool.record_ordinals)), + io, + }; if ( - repeatsRead(calls, records, { position, writes, io }) || + repeatsRead(calls, records, timeline) || namesReadOperations(calls, io) || namesLookup(tool.path_template) ) @@ -204,12 +211,16 @@ export const readOnlyTools = ( } // No candidate's call explains a read change across another's, so drop vetoed candidates until none is. for (let vetoed = true; vetoed;) { - const writes = nearestWrites( - new Set([...candidates.values()].flat().map((call) => call.ordinal)), - ); + const timeline = { + position, + ...nearestWrites( + new Set([...candidates.values()].flat().map((call) => call.ordinal)), + ), + io, + }; vetoed = false; for (const [name, calls] of candidates) - if (changesReadsAcross(calls, records, { position, writes, io })) { + if (changesReadsAcross(calls, records, timeline)) { candidates.delete(name); vetoed = true; } @@ -224,6 +235,8 @@ interface Timeline { readonly before: number; readonly after: number; }; + /** Whether the record at a timeline index is another write. */ + readonly isWrite: (index: number) => boolean; readonly io: QueryCallIo; } @@ -242,30 +255,120 @@ const lastFinishedBefore = ( return latest; }; -/** Every successful call answers as the successful GET of its path that finished last before it began, of those with no write between, did. */ +/** Every successful call answers as the successful GET of its path that finished last before it began, of those since the last other write, did. */ const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], - { position, writes, io }: Timeline, -): boolean => - calls.filter(succeeded).every((call) => { - const at = position.get(call.ordinal)!; - // Only reads after the last other write show the state the call met. - const read = lastFinishedBefore( - records - .slice(writes(at).before + 1, at) - .filter( - (record) => - record.method === "GET" && - record.path === call.path && - succeeded(record), - ), - call, - ); + { position, isWrite, io }: Timeline, +): boolean => { + const answering = calls.filter(succeeded); + const reads = lastReads(answering, records, position, isWrite); + return answering.every((call) => { + const read = reads.get(call.ordinal); if (read === undefined) return false; const answered = io.response(call.ordinal); return answered !== undefined && same(answered, io.response(read.ordinal)); }); +}; + +/** + * Each call's successful GET of its path that finished last before it began, of those since the last + * other write, in one sweep: a path's reads wait by end time until a call's start passes them. + */ +const lastReads = ( + calls: readonly StateRecordFacts[], + records: readonly StateRecordFacts[], + position: ReadonlyMap, + isWrite: (index: number) => boolean, +): Map => { + const paths = new Set(calls.map((call) => call.path)); + const callAt = new Map( + calls.map((call) => [position.get(call.ordinal)!, call]), + ); + const lastCall = calls.reduce( + (latest, call) => Math.max(latest, position.get(call.ordinal)!), + -1, + ); + const waiting = new Map(); + const latest = new Map(); + const found = new Map(); + for (let index = 0; index <= lastCall; index += 1) { + const record = records[index]!; + const call = callAt.get(index); + if (call !== undefined) { + const ready = waiting.get(call.path); + for ( + let read = ready?.popEndedBy(call.start); + read !== undefined; + read = ready?.popEndedBy(call.start) + ) + latest.set(call.path, read); + const read = latest.get(call.path); + if (read !== undefined) found.set(call.ordinal, read); + } else if (isWrite(index)) { + waiting.clear(); + latest.clear(); + } else if ( + record.method === "GET" && + succeeded(record) && + paths.has(record.path) + ) { + const heap = waiting.get(record.path) ?? new ReadsByEnd(position); + heap.push(record); + waiting.set(record.path, heap); + } + } + return found; +}; + +/** Reads in a binary heap by end time, then timeline position, so the one that finished first comes out first. */ +class ReadsByEnd { + readonly #reads: StateRecordFacts[] = []; + + constructor(private readonly position: ReadonlyMap) {} + + #before(left: StateRecordFacts, right: StateRecordFacts): boolean { + return ( + left.end < right.end || + (left.end === right.end && + this.position.get(left.ordinal)! < this.position.get(right.ordinal)!) + ); + } + + push(read: StateRecordFacts): void { + const reads = this.#reads; + reads.push(read); + for (let at = reads.length - 1; at > 0;) { + const parent = (at - 1) >>> 1; + if (!this.#before(reads[at]!, reads[parent]!)) break; + [reads[at], reads[parent]] = [reads[parent]!, reads[at]!]; + at = parent; + } + } + + /** The read that finished first, when it finished by `time`. */ + popEndedBy(time: number): StateRecordFacts | undefined { + const reads = this.#reads; + const first = reads[0]; + if (first === undefined || first.end > time) return undefined; + const last = reads.pop()!; + if (reads.length > 0) { + reads[0] = last; + for (let at = 0; ;) { + const [left, right] = [at * 2 + 1, at * 2 + 2]; + let next = at; + if (left < reads.length && this.#before(reads[left]!, reads[next]!)) + next = left; + if (right < reads.length && this.#before(reads[right]!, reads[next]!)) + next = right; + if (next === at) break; + [reads[at], reads[next]] = [reads[next]!, reads[at]!]; + at = next; + } + } + return first; + } +} /** Every call names only read operations. */ const namesReadOperations = ( diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index 031fbe9ef9b..ed95a17b396 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -24,7 +24,13 @@ const projectsLimit = ( reads: readonly StateRecordFacts[], post: StateRecordFacts, bodies: ReadonlyMap, - created: readonly string[], + { + created, + retain = () => undefined, + }: { + readonly created: readonly string[]; + readonly retain?: (bytes: number) => void; + }, ) => creationLimit( [{ record: post, ids: created }], @@ -41,6 +47,7 @@ const projectsLimit = ( records: new Map([...reads, post].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, body: (ordinal) => bodies.get(ordinal), + retain, }, undefined, ); @@ -72,6 +79,7 @@ describe("creation limits", () => { records: new Map([list, post, later].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, body: (ordinal) => bodies.get(ordinal), + retain: () => undefined, }, undefined, ); @@ -88,11 +96,15 @@ describe("creation limits", () => { // The second list began before the POST but ended after it began, so it may show the import. const overlapping = record(1, "GET", "/api/projects", [10, 40]); expect( - projectsLimit([earlier, overlapping], post, bodies, ["proj-0002"]), + projectsLimit([earlier, overlapping], post, bodies, { + created: ["proj-0002"], + }), ).toBe(post); const finished = record(1, "GET", "/api/projects", [10, 15]); expect( - projectsLimit([earlier, finished], post, bodies, ["proj-0002"]), + projectsLimit([earlier, finished], post, bodies, { + created: ["proj-0002"], + }), ).toBeUndefined(); }); @@ -112,9 +124,9 @@ describe("creation limits", () => { ], ], ]); - expect(projectsLimit([list, later], post, bodies, ["proj-0002"])).toBe( - post, - ); + expect( + projectsLimit([list, later], post, bodies, { created: ["proj-0002"] }), + ).toBe(post); }); it("reads no suffix-named field as a list's ids when an id field already identifies its entities", () => { @@ -136,7 +148,7 @@ describe("creation limits", () => { ]); // The owner the user call returned is no project the call made. expect( - projectsLimit([list, later], post, bodies, ["user-0003"]), + projectsLimit([list, later], post, bodies, { created: ["user-0003"] }), ).toBeUndefined(); }); @@ -169,6 +181,7 @@ describe("creation limits", () => { records: new Map([item, post, later].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, body: (ordinal) => bodies.get(ordinal), + retain: () => undefined, }, undefined, ); @@ -190,7 +203,41 @@ describe("creation limits", () => { [2, { projects: [project("user-0009")] }], ]); expect( - projectsLimit([list, later], post, bodies, ["user-0009"]), + projectsLimit([list, later], post, bodies, { created: ["user-0009"] }), ).toBeUndefined(); }); }); + +describe("the ids creation limits keep", () => { + it("keeps and charges only the shown ids a creation returned", () => { + let retained = 0; + const lists = 50; + const reads = Array.from({ length: lists }, (_, index) => + record(index < lists / 2 ? index : index + 1, "GET", "/api/projects"), + ); + const post = record(lists / 2, "POST", "/api/imports"); + const rows = (extra: number) => + Array.from({ length: 1000 }, (_, row) => ({ + id: `proj-${String(row + extra).padStart(5, "0")}`, + })); + const bodies = new Map( + reads.map((read) => [ + read.ordinal, + read.ordinal > post.ordinal + ? [...rows(0), { id: "proj-made" }] + : rows(0), + ]), + ); + expect( + projectsLimit(reads, post, bodies, { + created: ["proj-made"], + retain: (bytes) => { + retained += bytes; + }, + }), + ).toBe(post); + // One kept id per later list, not a thousand per list. + expect(retained).toBeGreaterThan(0); + expect(retained).toBeLessThan(lists * 1000 * 16); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 54fa984a4f5..9332be54e74 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -18,6 +18,7 @@ import { type StateToolFacts, type StateView, } from "./environmentStateRules.js"; +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; import { pathValuesOf, type WriteEffect, @@ -119,6 +120,22 @@ const shownIds = ( return showsItem(body(), id) ? new Set([id]) : new Set(); }; +/** The shown ids a creation returned, each charged before it is kept. */ +const keptIds = ( + shown: ReadonlySet, + returned: ReadonlySet, + retain: (bytes: number) => void, +): Set => { + const kept = new Set(); + for (const id of shown) + if (returned.has(id)) { + retain(ENTRY_BYTES + textBytes(id.length)); + kept.add(id); + } + retain(ENTRY_BYTES); + return kept; +}; + /** One read of a type: where it ran, when it finished, whether it reads one item, and the ids it shows. */ interface ShownRead { readonly at: number; @@ -201,10 +218,13 @@ export const creationLimit = ( readonly records: ReadonlyMap; readonly position: (record: StateRecordFacts) => number; readonly body: (ordinal: number) => JsonValue | undefined; + readonly retain: (bytes: number) => void; }, until: StateRecordFacts | undefined, ): StateRecordFacts | undefined => { if (creations.length === 0) return undefined; + // Only the ids some creation returned can be fresh, so each read keeps those alone, charged. + const returned = new Set(creations.flatMap((creation) => creation.ids)); const end = until === undefined ? Infinity : reads.position(until); const readers = reads.tools.flatMap((tool) => { const read = readType(tool.path_template); @@ -222,7 +242,11 @@ export const creationLimit = ( at: reads.position(record), end: record.end, item, - ids: shownIds(record, item, () => reads.body(ordinal)), + ids: keptIds( + shownIds(record, item, () => reads.body(ordinal)), + returned, + reads.retain, + ), }, ]; }), @@ -272,11 +296,13 @@ export const linkedCreate = (input: { // Another write may have made what a later read shows, so the search ends there. if (!own.has(record.ordinal) && input.isWrite(record)) return undefined; const view = input.viewOf(record.ordinal); + // A read naming the id but showing no entity, such as JSON null, says nothing of where the call created. if ( record.method !== "GET" || !succeeded(record) || view?.shape !== "item" || - !ids.has(lastSegmentValue(record.path)) + !ids.has(lastSegmentValue(record.path)) || + !input.showsItem(record.ordinal, lastSegmentValue(record.path)) ) continue; const id = lastSegmentValue(record.path); diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 467705655d1..a01df2793f5 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -1743,6 +1743,34 @@ describe("earlier reads of the returned id under other types", () => { }); }); +describe("item reads that show no entity", () => { + it("links a create past a read of its id that answered JSON null under another type", () => { + const user = (id: number, login: string) => ({ id, login }); + const state = stateOf([ + ["GET", "/api/notes", [A, B]], + ["GET", "/api/notes/1001", A], + ["GET", "/api/notes/1002", B], + ["GET", "/api/users/1001", user(1001, "alpha")], + // Ends the users' initial reads, so the null read below plans nothing. + [ + "PATCH", + "/api/users/1001", + user(1001, "alpha2"), + 200, + { login: "alpha2" }, + ], + ["POST", "/api/drafts/publish", { id: 1003 }, 201, { title: "Gamma" }], + ["GET", "/api/users/1003", null], + ["GET", "/api/notes/1003", C], + ["GET", "/api/notes", [A, B, C]], + ]); + expect(planOf(state, "post_drafts_publish")).toMatchObject({ + effect: "create", + target: "/api/notes", + }); + }); +}); + describe("what a linked create observes", () => { it("observes a linked create only in a read of an id its response named, inside an envelope too", () => { const D = note(1004, "Delta"); From 88ee22e2d8f172e4685f960d525e795978416145 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 14:23:19 -0700 Subject: [PATCH 43/68] docs(environment): record the tenth review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 32346456e62..f0427acbc62 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -69,6 +69,8 @@ write tool is lost. - **Ninth round** (on main `b7ebccf8`): no verdict, read view, recorded read or session replay changes on the restored captures (187 write tools, 62 served, 1,151 views, 2,085 of 2,155 initial reads and 2,764 of 3,022 session reads matching). +- **Tenth round** (on main `a2235b09`): no verdict, read view, recorded read or session replay changes on the restored + captures. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From d3828d5871a196701157b74afd3209469b408b33 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 14:57:05 -0700 Subject: [PATCH 44/68] fix(environment): take bulk ids literally, check each recorded call's query once, and keep learned sorts open to contrary reads Bulk writes take body ids as written, refuse a call naming one entity twice, size updates from the replacements installed, generate each entity's values from that entity, and delete only with the members their exemplar sent besides the ids. Comparison translates bulk body ids with the target collection's mapping. Update rules echo a creation clock sent back unchanged, require every held clock, and refuse a nested clock once any recorded call kept its object. A recorded call sent with another query than its exemplar's, including item actions, documents and deletes, neither confirms nor teaches its plan, and only successful calls with that query relax a create's guards. A counted read listing a learned array unsorted drops the sort from its view, sort evidence comes only from the entities the read covers, and a top-level counter whose name starts with a slash is named by its escaped pointer. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/write-rules/spec.md | 29 ++- .../environment/environmentCompare.ts | 4 +- .../environmentCompareBulk.test.ts | 34 +++ .../environment/environmentCompareIds.ts | 71 +++++- .../environment/environmentCompareMatch.ts | 37 +++- .../environment/environmentStateAnswer.ts | 9 +- .../environmentStateBulkAnswer.test.ts | 199 +++++++++++++++++ .../environment/environmentStateBulkAnswer.ts | 104 +++++---- .../environment/environmentStateStore.ts | 9 +- .../environmentStateWriteAnswer.ts | 68 +++--- .../environmentStateWriteDescription.ts | 2 +- .../EnvironmentStateWriteSimulation.ts | 10 +- .../analysisView/environmentStateCounters.ts | 2 +- .../environmentStateListCounters.test.ts | 29 ++- .../analysisView/environmentStateListFacts.ts | 6 +- .../analysisView/environmentStateView.ts | 2 +- .../environmentStateWriteApply.test.ts | 22 ++ .../analysisView/environmentStateWriteBulk.ts | 64 +++++- .../environmentStateWriteCalls.ts | 9 +- .../environmentStateWriteChanges.ts | 4 +- .../environmentStateWriteCreate.ts | 14 +- .../environmentStateWriteDelete.ts | 16 +- .../environmentStateWriteDocument.ts | 2 +- .../environmentStateWriteEffects.ts | 26 ++- .../environmentStateWriteSorted.ts | 71 ++++-- .../environmentStateWriteStamps.test.ts | 17 +- .../environmentStateWriteStamps.ts | 20 +- .../environmentStateWrites.test.ts | 207 ++++++++++++++++++ 28 files changed, 903 insertions(+), 184 deletions(-) diff --git a/docs/specs/agent-environments/write-rules/spec.md b/docs/specs/agent-environments/write-rules/spec.md index 916a351af3c..2f906b00bfa 100644 --- a/docs/specs/agent-environments/write-rules/spec.md +++ b/docs/specs/agent-environments/write-rules/spec.md @@ -28,22 +28,28 @@ relation rows), and six need only a better recording. This change addresses the and the state does not contradicts the create. - **Constant guard.** A create member is accepted only with its recorded value when a constant derives from it: its echoed text inside the constant, a referenced entity's string, or an instant beside a sent date, matched by related - field names. + field names. Only successful calls sent with the exemplar's query show that a member may vary. - **Update rules.** An update's unsent change can be a modified-by stamp beside a created-by counterpart (with its id - sibling), a value derived from the one sent member stored nowhere (accepted only while the target holds the - recorded before-value), or a sent clock left in the call's own second. An unsent clock left in the call's own second - keeps the update unconfirmed until another call shows it stamped. Objects whose clocks moved with the request are - nested clocks, stored from the read-back on creates and updates; opaque tokens of a type's own length are - generated; an enveloped body is learned as its one object. A write takes only its recorded query, and an echoed - reference to a nested object or a state word paired with other fields stays at its recorded value. The served - catalog names these values. + sibling), a value derived from the one sent member stored nowhere (accepted only while the target holds the recorded + before-value), or a sent clock other than a creation clock left in the call's own second, which every call must then + send with the value the entity holds. An unsent clock left in the call's own second keeps the update unconfirmed until + another call shows it stamped. Objects whose clocks moved with the request are nested clocks, stored from the + read-back on creates and updates and refused once any call left the object as it was; opaque tokens of a type's own + length are generated; an enveloped body is learned as its one object. A write takes only its recorded query, and a + call sent with another neither confirms nor teaches its plan: a create or update only brings the state to what it + recorded, and a delete, document or bulk call leaves its target unknown. An echoed reference to a nested object or a + state word paired with other fields stays at its recorded value. The served catalog names these values. - **View order.** A collection's initial order comes from the first list line that shows every entity its type's sightings do and applies no order. A view renders a string array sorted only after a counted read-back shows an - order that neither the written order nor existing-values-first explains, and never once a read showed it unsorted. + order that neither the written order nor existing-values-first explains, among the entities that read covers in its + own collection, and never once a read showed it unsorted, which also drops a sort the view had learned. Sort and direction parameters share one vocabulary and are never learned as inert. A create placed by disagreeing sorts or a random id falls back to `last`. - **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying - the id field, deletes or updates each one, all or none; serving refuses it unless every id is held. + the id field, deletes or updates each one, all or none; serving refuses it unless every id is held. Body ids are + taken as written, and a call naming one entity twice is refused. Each entity's generated values come from that + entity, sharing the call's clock and counters. A delete requires the members its exemplar sent besides the ids, with + their recorded values. Comparison translates a bulk body's ids with the mapping of the collection the write targets. - **Item actions.** A write to an item path plus a literal segment that names no collection, whose calls answer nothing or the entity (never a 201, and with every field its item read always shows), updates that entity; a scalar it changes without sending is set on every call. It is served only once a call found every field it sets already at @@ -54,7 +60,8 @@ relation rows), and six need only a better recording. This change addresses the is that path, leave it out: item envelopes, and the write gate's item, list and document reads, compare without it. The view names it in `per_response_members`, and serving keeps the recorded value. - **Nested counters.** An item total in a top-level object beside the list is a counter on the same evidence as a - top-level one, rendered from the state through its pointer. + top-level one, rendered from the state through its pointer. A top-level member whose name starts with `/` is named by + its pointer (`/~1total`). ## Acceptance diff --git a/src/application/environment/environmentCompare.ts b/src/application/environment/environmentCompare.ts index e5dbdbc8f51..d983b8b6d6b 100644 --- a/src/application/environment/environmentCompare.ts +++ b/src/application/environment/environmentCompare.ts @@ -20,6 +20,7 @@ import { translatePath, } from "./environmentCompareIds.js"; import { + bulkIds, collectionScope, literalPositions, bodyTools, @@ -354,7 +355,8 @@ const compareStep = ( { category: "refused", pointer: "", env: message.slice(0, 200) }, ], }); - const args = environmentArguments(call, run.map); + const bulk = bulkIds(run, call, liveSegments); + const args = environmentArguments(call, run.map, bulk); const problem = check(args); if (problem !== undefined) return refusedWith(`Invalid arguments: ${problem}`); diff --git a/src/application/environment/environmentCompareBulk.test.ts b/src/application/environment/environmentCompareBulk.test.ts index 040904996a8..7d8b4a33207 100644 --- a/src/application/environment/environmentCompareBulk.test.ts +++ b/src/application/environment/environmentCompareBulk.test.ts @@ -12,6 +12,7 @@ import { BOOK_INIT_ROWS, BOOK_NOT_FOUND, FIRST_BOOK, + SECOND_BOOK, } from "../../../tests/fixtures/environmentStateWrites.js"; import { compareEnvironment } from "./environmentCompare.js"; @@ -47,4 +48,37 @@ describe("environment comparison of bulk writes", () => { expect(deleted).toMatchObject({ env_status: 200, equal: true }); expect(read).toMatchObject({ env_status: 404, equal: true }); }); + + it("translates the ids a bulk body names with its collection's own mapping", () => { + const project = { id: 7, name: "Project" }; + const fixture = environmentStateServeFixture( + timedCaptureEvidence([ + ["GET", "/api/projects", [project]], + ["GET", "/api/projects/7", project], + ...RECORDED, + ]), + ); + // The probe reuses id 100 for the project and for the first book. + const live = (id: number) => ({ ...FIRST_BOOK, id }); + const report = compareEnvironment({ + source: environmentServeSource(fixture), + captureValue: fixture.capture, + probes: [ + { + label: "shared-id", + value: timedCaptureEvidence([ + ["GET", "/api/projects", [{ ...project, id: 100 }]], + ["GET", "/api/books", [live(100), { ...SECOND_BOOK, id: 101 }]], + ["DELETE", "/api/books", [{ id: 100 }], 200, [{ id: 100 }]], + ["GET", "/api/books/100", BOOK_NOT_FOUND, 404], + ]), + }, + ], + operation: "environment-compare", + }); + if (!report.ok) throw report.error; + const [, , deleted, read] = report.value.probes[0]!.results; + expect(deleted).toMatchObject({ env_status: 200, equal: true }); + expect(read).toMatchObject({ env_status: 404, equal: true }); + }); }); diff --git a/src/application/environment/environmentCompareIds.ts b/src/application/environment/environmentCompareIds.ts index 8bc8c057dad..ecab1767ac5 100644 --- a/src/application/environment/environmentCompareIds.ts +++ b/src/application/environment/environmentCompareIds.ts @@ -1,4 +1,5 @@ import type { JsonObject } from "../../domain/analysisView/environmentStateRules.js"; +import type { BodyAddress } from "../../domain/analysisView/environmentStateWriteRules.js"; import { isUuid } from "../../domain/analysisView/environmentStateWriteValues.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import type { ProbeToolCall } from "./environmentCompareMatch.js"; @@ -404,6 +405,19 @@ export const learnIds = ( { at: "", own: false }, ); +/** A live identifier as the environment's value, in its own type; unchanged when unmapped. */ +const inEnvTerms = ( + value: string | number, + env: string | number | undefined, +): JsonValue => { + if (env === undefined) return value; + return typeof value === "string" + ? String(env) + : typeof env === "number" + ? env + : value; +}; + /** A value with every string or number equal to a mapped live identifier replaced by the environment's value, in its own type. */ export const translateValue = (value: JsonValue, map: IdMap): JsonValue => { if (Array.isArray(value)) @@ -415,27 +429,64 @@ export const translateValue = (value: JsonValue, map: IdMap): JsonValue => { translateValue(item, map), ]), ); - if (!isScalarId(value)) return value; - const env = map.env(value); - if (env === undefined) return value; - return typeof value === "string" - ? String(env) - : typeof env === "number" - ? env - : value; + return isScalarId(value) ? inEnvTerms(value, map.env(value)) : value; +}; + +/** A bulk write's body argument, how it names its entities, and the collection whose own mapping translates those ids. */ +export interface BulkIds { + readonly body: string; + readonly address: BodyAddress; + readonly idField: string; + readonly scope: string; +} + +/** A bulk write's body with each id it names translated by its collection's own mapping, and every other value as `translateValue` does. */ +const translateBulkBody = ( + body: JsonValue, + map: IdMap, + bulk: BulkIds, +): JsonValue => { + const { address, idField, scope } = bulk; + const id = (value: JsonValue): JsonValue => + isScalarId(value) ? inEnvTerms(value, map.env(value, scope)) : value; + const entries = (value: JsonValue): JsonValue => + Array.isArray(value) + ? value.map((entry) => + address.by === "ids" + ? id(entry) + : isObject(entry) && Object.hasOwn(entry, idField) + ? { + ...(translateValue(entry, map) as JsonObject), + [idField]: id(entry[idField]!), + } + : translateValue(entry, map), + ) + : translateValue(value, map); + if (address.member === null) return entries(body); + return isObject(body) + ? Object.fromEntries( + Object.entries(body).map(([key, value]) => [ + key, + key === address.member ? entries(value) : translateValue(value, map), + ]), + ) + : translateValue(body, map); }; -/** The arguments the environment is called with: path values as matched, already in its terms, paging values as sent, and every other value translated. */ +/** The arguments the environment is called with: path values as matched, already in its terms, paging values as sent, a bulk body's ids by their collection's mapping, and every other value translated. */ export const environmentArguments = ( call: ProbeToolCall, map: IdMap, + bulk?: BulkIds, ): Record => Object.fromEntries( Object.entries(call.args).map(([name, value]) => [ name, call.pathArguments.includes(name) || call.pagingArguments.includes(name) ? value - : translateValue(value, map), + : bulk !== undefined && name === bulk.body + ? translateBulkBody(value, map, bulk) + : translateValue(value, map), ]), ); diff --git a/src/application/environment/environmentCompareMatch.ts b/src/application/environment/environmentCompareMatch.ts index 1a06e7d1830..1d7704c76df 100644 --- a/src/application/environment/environmentCompareMatch.ts +++ b/src/application/environment/environmentCompareMatch.ts @@ -1,11 +1,17 @@ -import { decodedSegment } from "../../domain/analysisView/environmentStateRules.js"; +import { + decodedSegment, + segmentsOf, +} from "../../domain/analysisView/environmentStateRules.js"; +import { bulkCollectionOf } from "../../domain/analysisView/environmentStateWriteAddress.js"; import { isPagingParameter } from "../../domain/analysisView/environmentStatePaging.js"; import { segmentRule } from "../../domain/analysisView/webNetworkRouteTemplates.js"; import type { JsonValue } from "../../domain/jsonValue.js"; +import type { BulkIds } from "./environmentCompareIds.js"; import type { EnvironmentManifest, EnvironmentManifestTool, } from "./environmentSource.js"; +import type { EnvironmentStateStore } from "./environmentStateStore.js"; import { environmentToolArguments, type EnvironmentToolDefinition, @@ -82,6 +88,35 @@ export const collectionScope = ( ); }; +/** How a served bulk write's body names its entities, and the collection they belong to: the path up to its type's, spelled as the type ends, as reads of the type scope them. */ +export const bulkIds = ( + run: { + readonly store: EnvironmentStateStore | undefined; + readonly bodies: ReadonlySet; + }, + call: ProbeToolCall, + segments: readonly string[], +): BulkIds | undefined => { + const plan = run.store?.state.writes.get(call.tool.name); + const target = plan?.target ?? null; + const address = plan?.address; + const body = probeArguments(call.tool, run.bodies).body; + if ( + target === null || + address === undefined || + address.by === "action" || + body === undefined + ) + return undefined; + const scope = collectionAt(call.tool, segmentsOf(target).length, segments); + return { + body, + address, + idField: run.store?.type(target)?.id_field ?? "", + scope: `/${bulkCollectionOf(target, scope.slice(1).split("/"), (text) => text).join("/")}`, + }; +}; + /** The collection each path parameter names an entity of: the path before it, by the parameter's position. */ export const parameterScopes = ( tool: EnvironmentManifestTool, diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index 09f2b87bbfc..aa5b03dbee1 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -206,6 +206,8 @@ export const stateAnswer = ( export interface ItemCall { readonly segments: readonly SuppliedSegment[]; readonly id: string; + /** Set for an id a body names, which is taken as written rather than percent-decoded. */ + readonly literal?: boolean; } /** What an item call names, or undefined when a path argument is missing; an item action's id comes before its action segment. */ @@ -222,7 +224,7 @@ export const itemCall = ( : undefined; }; -/** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written. */ +/** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written, unless it is literal. */ /** Whether the state started with the item a call names, which a served delete may since have removed. */ const startedWithItem = ( store: EnvironmentStateStore, @@ -244,7 +246,10 @@ export const namedEntity = ( type: string, call: ItemCall, ): StateEntity | undefined => { - const ids = [...new Set([decodedSegment(call.id), call.id])]; + const ids = + call.literal === true + ? [call.id] + : [...new Set([decodedSegment(call.id), call.id])]; const candidates = store .collectionsOf(type) .flatMap((collection) => { diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index db93a3d5aea..12e59b53cb0 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -110,6 +110,205 @@ describe("served bulk write queries and capacity", () => { }); }); +describe("served bulk write targets", () => { + it("takes a body's ids as written, refusing one that only decodes to a held id", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["PATCH", "/api/books", "", 204, { ids: ["1"], name: "Renamed Book" }], + ["GET", "/api/books/1", RENAMED_AT_3], + ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], + ]); + const before = books.snapshot(); + expect( + books.refusal("patch_books", { body: { ids: ["1", "%31"], name: "B" } }), + ).toMatchObject({ + message: expect.stringContaining("holds no /api/books entity %31"), + }); + expect(books.snapshot()).toBe(before); + }); + + it("keeps the size data/get writes when one replacement names an entity twice", () => { + const { store } = servedFrom(BULK_RENAME_ROWS); + const held = store.ofType("/api/books")[0]!; + const renamed = (name: string) => ({ + ...held, + fields: { ...held.fields, name }, + }); + const updated = store.updateAll([renamed("A"), renamed("B")]); + expect(updated.ok).toBe(true); + expect(store.byteLength()).toBe( + Buffer.byteLength(JSON.stringify(store.snapshot()), "utf8"), + ); + }); +}); + +const uuid = (n: number): string => + `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; + +/** A book holding child rows, which an update gives fresh ids. */ +const withRows = (id: number, name: string, row: number) => ({ + id, + name, + rows: [{ id: uuid(row) }], +}); + +/** A card whose edit info an update restamps. */ +const card = (id: number, name: string, at: string | null) => ({ + id, + name, + edit: at === null ? null : { at, by: "rea" }, +}); +const EDITED_AT = "2026-10-01T09:00:00.000Z"; +const CARDS = [ + card(1, "One", EDITED_AT), + card(2, "Two", EDITED_AT), + card(3, "Three", null), +]; +/** The first card as the bulk update recorded at exchange 4 stored it. */ +const EDITED_CARD = card( + 1, + "Edited", + new Date(Date.parse("2026-10-17T18:00:04.000Z") + 53).toISOString(), +); + +describe("served bulk updates of what each entity holds", () => { + it("renews the child rows the written entity holds", () => { + const books = servedFrom([ + ["GET", "/api/books", [withRows(1, "One", 1), withRows(2, "Two", 2)]], + ["GET", "/api/books/1", withRows(1, "One", 1)], + ["GET", "/api/books/2", withRows(2, "Two", 2)], + ["PATCH", "/api/books", "", 204, { ids: [1], name: "After" }], + ["GET", "/api/books/1", withRows(1, "After", 3)], + ["GET", "/api/books", [withRows(1, "After", 3), withRows(2, "Two", 2)]], + ]); + expect(books.state.writes.get("patch_books")).toMatchObject({ + served: true, + rules: expect.arrayContaining([ + expect.objectContaining({ field: "rows", rule: "renewed" }), + ]), + }); + books.answer("patch_books", { body: { ids: [2], name: "Changed" } }); + const rows = ( + books.answer("get_books_by_id", { id: "2" }).body as { + rows: { id: string }[] | null; + } + ).rows; + expect(rows).toEqual([{ id: expect.any(String) }]); + expect(rows![0]!.id).not.toBe(uuid(2)); + }); + + it("restamps the nested clock each entity holds, refusing one holding no object", () => { + const cards = servedFrom([ + ["GET", "/api/cards", CARDS], + ...CARDS.map((entry): TimedCaptureRow => [ + "GET", + `/api/cards/${String(entry.id)}`, + entry, + ]), + ["PATCH", "/api/cards", "", 204, { ids: [1], name: "Edited" }], + ["GET", "/api/cards/1", EDITED_CARD], + ["GET", "/api/cards", [EDITED_CARD, ...CARDS.slice(1)]], + ]); + expect(cards.state.writes.get("patch_cards")).toMatchObject({ + served: true, + rules: expect.arrayContaining([ + expect.objectContaining({ field: "edit", rule: "nested-clock" }), + ]), + }); + // A loaded state can hold an edit object another editor wrote. + const loaded = cards.store.snapshot(); + expect( + cards.store.replace({ + rea_state: { + ...loaded.rea_state, + entities: loaded.rea_state.entities.map((entity) => + entity.id === "2" + ? { + ...entity, + fields: { + ...entity.fields, + edit: { at: EDITED_AT, by: "ops" }, + }, + } + : entity, + ), + }, + }).ok, + ).toBe(true); + cards.answer("patch_cards", { body: { ids: [2], name: "Edited" } }); + expect(cards.answer("get_cards_by_id", { id: "2" }).body).toMatchObject({ + edit: { by: "ops" }, + }); + const before = cards.snapshot(); + expect( + cards.refusal("patch_cards", { body: { ids: [3], name: "Edited" } }), + ).toMatchObject({ + message: expect.stringContaining("holds no edit object"), + }); + expect(cards.snapshot()).toBe(before); + }); +}); + +describe("served bulk delete options", () => { + it("deletes only with the members its recording sent besides the ids, as it sent them", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", "", 204, { ids: [2], dry_run: false }], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + const before = books.snapshot(); + for (const [body, message] of [ + [{ ids: [1], dry_run: true }, "Member dry_run is accepted only"], + [{ ids: [1], dry_run: false, force: true }, "Member force is not one"], + [{ ids: [1] }, "lacks required members"], + ] as const) + expect(books.refusal("delete_books", { body }).message).toContain( + message, + ); + expect(books.snapshot()).toBe(before); + expect( + books.answer("delete_books", { body: { ids: [1], dry_run: false } }), + ).toMatchObject({ status: 204 }); + expect(books.store.ofType("/api/books").map((book) => book.id)).toEqual([ + "2", + ]); + }); + + it("pins the members each recorded element sends besides its id", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", "", 204, [{ id: 2, cascade: true }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + const before = books.snapshot(); + expect( + books.refusal("delete_books", { body: [{ id: 1, cascade: false }] }) + .message, + ).toContain("Member cascade is accepted only"); + expect(books.snapshot()).toBe(before); + expect( + books.answer("delete_books", { body: [{ id: 1, cascade: true }] }), + ).toMatchObject({ status: 204 }); + }); + + it("models a recorded call with other members as unknown rather than as a delete", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", "", 204, { ids: [2], dry_run: false }], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["DELETE", "/api/books", "", 204, { ids: [1], dry_run: true }], + ["GET", "/api/books/1", FIRST_BOOK], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: true, + body: { fixed: [{ member: "dry_run", sent: false }] }, + }); + }); +}); + describe("served item actions", () => { it("sets what the action changed on the entity the path names", () => { const books = servedFrom([ diff --git a/src/application/environment/environmentStateBulkAnswer.ts b/src/application/environment/environmentStateBulkAnswer.ts index 493dad1f70a..22b1d600b97 100644 --- a/src/application/environment/environmentStateBulkAnswer.ts +++ b/src/application/environment/environmentStateBulkAnswer.ts @@ -3,6 +3,7 @@ import { namedEntities, } from "../../domain/analysisView/environmentStateWriteAddress.js"; import { + bodyProblem, updatedEntity, updatedFields, writtenResponse, @@ -34,6 +35,7 @@ import { observedEntity, pathValues, unloadable, + updateTarget, writeAnswer, type WriteRequest, } from "./environmentStateWriteAnswer.js"; @@ -42,6 +44,12 @@ import { environmentToolArguments } from "./environmentTools.js"; /** Rules whose generated value is drawn once per call, which one call cannot give several entities. */ const DRAWN_ONCE = new Set(["unique", "renewed"]); +/** One entity a bulk call names, held by the state, with the members it gets. */ +interface BulkTarget { + readonly entity: StateEntity; + readonly body: JsonObject | undefined; +} + /** A bulk answer from the recorded one: one element per written entity, rendered as the first recorded element shows its entity. */ const bulkResponse = ( response: WriteResponse, @@ -69,10 +77,7 @@ const bulkResponse = ( const namedTargets = ( serving: StateServing, request: WriteRequest, -): Result< - { readonly entity: StateEntity; readonly body: JsonObject | undefined }[], - AnalysisError -> => { +): Result => { const { tool, plan, args } = request; const { address } = plan; const type = plan.target ?? ""; @@ -98,11 +103,13 @@ const namedTargets = ( text, supplied: false, })); - const targets = []; + const targets: BulkTarget[] = []; for (const { id, body: members } of named) { + // A body's id is the entity's as written, never a percent-encoded spelling of another. const entity = namedEntity(serving.store, type, { segments: collection, id, + literal: true, }); if (entity === undefined) return err( @@ -111,17 +118,60 @@ const namedTargets = ( `The state holds no ${type} entity ${id}; the state is unchanged.`, ), ); + if (targets.some((target) => target.entity === entity)) + return err( + refused( + tool, + `The body names ${type} entity ${entity.id} more than once; the state is unchanged.`, + ), + ); targets.push({ entity, body: members }); } return ok(targets); }; +/** Each named entity as the call writes it, or a refusal: a delete takes only the members its recording sent, an update gets its fields with the call's shared values. */ +const writtenTargets = ( + serving: StateServing, + request: WriteRequest, + targets: readonly BulkTarget[], + values: ReturnType, +): Result => { + const { tool, plan, args } = request; + const observed = observedEntity(serving, plan) ?? {}; + const path = { path: tool.path_template, pathValues: pathValues(tool, args) }; + const written: StateEntity[] = []; + for (const { entity, body } of targets) { + const call = { ...path, body, id: entity.id }; + if (plan.effect !== "update") { + const problem = + plan.body === null + ? "The tool has no modelled body." + : bodyProblem(plan.body, call, { entity: {}, id: entity.id }); + if (problem !== undefined) return err(refused(tool, problem)); + written.push(entity); + continue; + } + const fields = updatedFields( + plan, + { before: entity.fields, observed }, + call, + values.forTarget(updateTarget(serving, entity, observed)), + ); + if (!fields.ok) return err(refused(tool, fields.error)); + const field = unloadableMember(fields.value); + if (field !== undefined) return err(unloadable(tool, `Field ${field}`)); + written.push(updatedEntity(entity, fields.value)); + } + return ok(written); +}; + /** Apply one served bulk call to every entity its body names and answer it; a refused call leaves the state unchanged. */ export const answerBulk = ( serving: StateServing, request: WriteRequest, ): Result => { - const { tool, plan, args } = request; + const { tool, plan } = request; const targets = namedTargets(serving, request); if (!targets.ok) return targets; const update = plan.effect === "update"; @@ -137,55 +187,27 @@ export const answerBulk = ( ), ); const [first] = targets.value; - const observed = observedEntity(serving, plan) ?? {}; - const values = generator(serving, request, { - name: first!.entity.collection, - collection: serving.store.inCollection( - first!.entity.type, - first!.entity.collection, - ), - observed, - }); - const written: StateEntity[] = []; - for (const { entity, body } of targets.value) { - if (!update) { - written.push(entity); - continue; - } - const fields = updatedFields( - plan, - { before: entity.fields, observed }, - { - path: tool.path_template, - pathValues: pathValues(tool, args), - body, - id: entity.id, - }, - values.generate, - ); - if (!fields.ok) return err(refused(tool, fields.error)); - const field = unloadableMember(fields.value); - if (field !== undefined) return err(unloadable(tool, `Field ${field}`)); - written.push(updatedEntity(entity, fields.value)); - } + const values = generator(serving, request); + const written = writtenTargets(serving, request, targets.value, values); + if (!written.ok) return written; const answer = writeAnswer( serving, request, - (recorded) => bulkResponse(plan.response!, recorded, written), + (recorded) => bulkResponse(plan.response!, recorded, written.value), { source: "state", view: update ? "update" : "delete", type: first!.entity.type, collection: first!.entity.collection, id: first!.entity.id, - ids: written.map((entity) => entity.id), + ids: written.value.map((entity) => entity.id), }, ); if (!answer.ok) return answer; if (update) { - const updated = serving.store.updateAll(written); + const updated = serving.store.updateAll(written.value); if (!updated.ok) return updated; - } else serving.store.removeAll(written); + } else serving.store.removeAll(written.value); serving.store.commitWrite(values.taken); return answer; }; diff --git a/src/application/environment/environmentStateStore.ts b/src/application/environment/environmentStateStore.ts index 8a1824f40be..7f8ad1bb5f2 100644 --- a/src/application/environment/environmentStateStore.ts +++ b/src/application/environment/environmentStateStore.ts @@ -316,16 +316,17 @@ export class EnvironmentStateStore { entities: readonly StateEntity[], ): Result { const replaced = new Map(); - let delta = 0; for (const entity of entities) { const held = this.#entities.get( compositeKey([entity.type, entity.collection, entity.id]), ); - if (held === undefined) continue; - replaced.set(held, entity); - delta += jsonByteLength(entity) - jsonByteLength(held); + if (held !== undefined) replaced.set(held, entity); } if (replaced.size === 0) return ok(undefined); + // Sized from the replacements installed, so an entity named twice counts once. + let delta = 0; + for (const [held, entity] of replaced) + delta += jsonByteLength(entity) - jsonByteLength(held); const bytes = this.#grown(delta); if (!bytes.ok) return bytes; this.#install( diff --git a/src/application/environment/environmentStateWriteAnswer.ts b/src/application/environment/environmentStateWriteAnswer.ts index a756c5d9362..eebf4b35c0a 100644 --- a/src/application/environment/environmentStateWriteAnswer.ts +++ b/src/application/environment/environmentStateWriteAnswer.ts @@ -161,23 +161,37 @@ const nextHeld = ( exemplar, ); +/** The entity a write generates values for: its collection, the observed entity and, for an update, the entity it writes. */ +export interface GeneratedTarget { + readonly name: string; + readonly collection: readonly StateEntity[]; + readonly observed: JsonObject; + /** The entity an update writes, whose values a renewed field keeps. */ + readonly current?: JsonObject; +} + +/** What an update generates values for: the entity it writes, in its collection. */ +export const updateTarget = ( + serving: StateServing, + entity: StateEntity, + observed: JsonObject, +): GeneratedTarget => ({ + name: entity.collection, + collection: serving.store.inCollection(entity.type, entity.collection), + observed, + current: entity.fields, +}); + /** * Values one served write generates: its clock instant, sequences one past the largest held * value, and UUIDs and tokens seeded by the state Evidence, tool, field and write count, - * skipping values the type already holds. + * skipping values the type already holds. Every entity the call writes shares them. */ export const generator = ( serving: StateServing, request: WriteRequest, - target: { - readonly name: string; - readonly collection: readonly StateEntity[]; - readonly observed: JsonObject; - /** The entity an update writes, whose values a renewed field keeps. */ - readonly current?: JsonObject; - }, ): { - readonly generate: GenerateValue; + readonly forTarget: (target: GeneratedTarget) => GenerateValue; readonly taken: Map; } => { const { store } = serving; @@ -191,7 +205,8 @@ export const generator = ( const ofType = store.ofType(request.plan.target ?? ""); // A sequence never reuses a value the state started with, even after its entity was deleted. const started = store.startedWith(request.plan.target ?? ""); - const startedIn = started.filter((held) => held.collection === target.name); + const startedIn = (collection: string) => + started.filter((held) => held.collection === collection); const renewed = callRenewal( `${store.state.evidenceId}:${request.tool.name}:renewed:${String(write.count)}`, ); @@ -210,7 +225,10 @@ export const generator = ( `Could not generate a unique value for ${field} after ${String(GENERATION_ATTEMPTS)} attempts without colliding with the held state.`, ); }; - const generate = (rule: GeneratedRule): Result => { + const generate = ( + target: GeneratedTarget, + rule: GeneratedRule, + ): Result => { const exemplar = target.observed[rule.field] ?? ""; const seed = (attempt: number) => `${store.state.evidenceId}:${request.tool.name}:${rule.field}:${String(write.count)}:${String(attempt)}`; @@ -239,7 +257,7 @@ export const generator = ( `${request.tool.name} ${rule.field} ${rule.scope === "collection" ? target.name : ""}`, nextHeld( rule.scope === "collection" - ? [...target.collection, ...startedIn] + ? [...target.collection, ...startedIn(target.name)] : [...ofType, ...started], rule.field, exemplar, @@ -267,7 +285,7 @@ export const generator = ( sequence( `${request.plan.target ?? ""} ${rule.field} ${target.name}`, nextHeld( - [...target.collection, ...startedIn], + [...target.collection, ...startedIn(target.name)], rule.field, exemplar, ), @@ -279,7 +297,7 @@ export const generator = ( ); } }; - return { generate, taken }; + return { forTarget: (target) => (rule) => generate(target, rule), taken }; }; /** A write's answer on its recorded response's status and content type: a rendered body, none, or the recorded one. */ @@ -424,16 +442,17 @@ const answerCreate = ( ), ); const members = serving.store.inCollection(type, collection); - const values = generator(serving, request, { - name: collection, - collection: members, - observed, - }); + const values = generator(serving, request); const created = { ...call, pathValues: createdPathValues(serving, request, call, collection), }; - const fields = createdFields(plan, observed, created, values.generate); + const fields = createdFields( + plan, + observed, + created, + values.forTarget({ name: collection, collection: members, observed }), + ); if (!fields.ok) return err(refused(tool, fields.error)); const field = unloadableMember(fields.value); if (field !== undefined) return err(unloadable(tool, `Field ${field}`)); @@ -515,17 +534,12 @@ const answerUpdate = ( if (!target.ok) return target.error; const entity = target.value; const observed = observedEntity(serving, plan) ?? {}; - const values = generator(serving, request, { - name: entity.collection, - collection: serving.store.inCollection(entity.type, entity.collection), - observed, - current: entity.fields, - }); + const values = generator(serving, request); const written = updatedFields( plan, { before: entity.fields, observed }, { ...call, id: entity.id }, - values.generate, + values.forTarget(updateTarget(serving, entity, observed)), ); if (!written.ok) return err(refused(tool, written.error)); // An increment can pass the exact integers. diff --git a/src/application/environment/environmentStateWriteDescription.ts b/src/application/environment/environmentStateWriteDescription.ts index 113774d9a6e..b20d30fba3b 100644 --- a/src/application/environment/environmentStateWriteDescription.ts +++ b/src/application/environment/environmentStateWriteDescription.ts @@ -69,7 +69,7 @@ export const describeWrite = ( queryClause(query); if (address !== undefined && address.by !== "action") return plan.effect === "delete" - ? `removes the entities its body names by id from the served environment state${queryClause(query)}, modelled on the recorded calls` + ? `removes the entities its body names by id from the served environment state${body}, modelled on the recorded calls` : `changes the entities its body names by id in the served environment state${body}, modelled on the recorded calls`; if (address?.by === "action") return `applies ${quotedName(address.segment)} to the entity the path names in the served environment state${body}, modelled on the recorded calls`; diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts index 581853e7f17..44496131653 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.ts @@ -21,6 +21,7 @@ import { updatedEntity } from "./environmentStateWriteApply.js"; import { projectedRead } from "./environmentStateWriteObserve.js"; import { OmittedFields } from "./environmentStateWriteOmitted.js"; import { SortedArrays } from "./environmentStateWriteSorted.js"; +import { sameQuery } from "./environmentStateWriteStamps.js"; import { checkDocumentRead, checkItemRead, @@ -294,7 +295,14 @@ export class EnvironmentStateWriteSimulation { } const observeOnly = draft.plan.reason !== null; if (!observeOnly) draft.calls += 1; - const step: WriteStep = { record, index, tool, observeOnly }; + // Serving pins the exemplar's query, so a call with another may do something else and confirms nothing. + const pinned = + !built(draft) || + sameQuery( + this.#input.io.queryOf(draft.plan.exemplar_ordinal ?? -1), + record.query, + ); + const step: WriteStep = { record, index, tool, observeOnly, pinned }; const context = this.#context(tool.name); const { address } = draft.plan; const results = diff --git a/src/domain/analysisView/environmentStateCounters.ts b/src/domain/analysisView/environmentStateCounters.ts index 16764672546..2a9fdef81ba 100644 --- a/src/domain/analysisView/environmentStateCounters.ts +++ b/src/domain/analysisView/environmentStateCounters.ts @@ -5,7 +5,7 @@ type JsonObject = { [key: string]: JsonValue }; const isObject = (value: JsonValue | undefined): value is JsonObject => typeof value === "object" && value !== null && !Array.isArray(value); -/** A list counter's member names: a top-level member, or a pointer to one in a top-level object (`/pageInfo/totalRows`). */ +/** A list counter's member names: a top-level member's name not starting with `/`, else a pointer (`/pageInfo/totalRows`, `/~1total`). */ export const counterPath = (counter: string): string[] => counter.startsWith("/") ? counter diff --git a/src/domain/analysisView/environmentStateListCounters.test.ts b/src/domain/analysisView/environmentStateListCounters.test.ts index 0840ef3196e..955e06f00ea 100644 --- a/src/domain/analysisView/environmentStateListCounters.test.ts +++ b/src/domain/analysisView/environmentStateListCounters.test.ts @@ -1,4 +1,5 @@ import { expect, it } from "vitest"; +import type { JsonValue } from "../jsonValue.js"; import { timedCaptureEvidence, type TimedCaptureRow, @@ -26,15 +27,24 @@ const page = (list: readonly JsonObject[], totalRows = list.length) => ({ }, }); -const rows: TimedCaptureRow[] = [ - ["GET", "/api/records?limit=25", page(SEEDED)], +/** A list beside a top-level total whose member name starts with a slash. */ +const slashed = (list: readonly JsonObject[]) => ({ + list: [...list], + "/total_count": list.length, +}); + +/** Seeded reads, a filtered line, then a create its list read-back counts, each list in `envelope`. */ +const rowsOf = ( + envelope: (list: readonly JsonObject[]) => JsonValue = page, +): TimedCaptureRow[] => [ + ["GET", "/api/records?limit=25", envelope(SEEDED)], ["GET", "/api/records/1", SEEDED[0]!], ["GET", "/api/records/2", SEEDED[1]!], ["GET", "/api/records/3", SEEDED[2]!], [ "GET", "/api/records?where=(status,eq,Active)", - page([SEEDED[0]!, SEEDED[2]!]), + envelope([SEEDED[0]!, SEEDED[2]!]), ], [ "POST", @@ -44,8 +54,9 @@ const rows: TimedCaptureRow[] = [ { name: "Vessel 4", status: "Laid Up" }, ], ["GET", "/api/records/4", vessel(4, "Laid Up")], - ["GET", "/api/records?limit=25", page([...SEEDED, vessel(4, "Laid Up")])], + ["GET", "/api/records?limit=25", envelope([...SEEDED, vessel(4, "Laid Up")])], ]; +const rows = rowsOf(); it("counts a total nested in a paging object, and serves the create its list read-back counts", () => { const state = environmentStateViewOf(timedCaptureEvidence(rows)); @@ -57,6 +68,16 @@ it("counts a total nested in a paging object, and serves the create its list rea ).toMatchObject({ served: true, reason: null }); }); +it("names a top-level total whose name starts with a slash by its pointer, and serves the create its list read-back counts", () => { + const state = environmentStateViewOf(timedCaptureEvidence(rowsOf(slashed))); + expect(state.views.find((view) => view.tool === "get_records")).toMatchObject( + { shape: "list", counters: ["/~1total_count"] }, + ); + expect( + state.writes.find((write) => write.tool === "post_records"), + ).toMatchObject({ served: true, reason: null }); +}); + it("renders a nested counter and a nested query total from the state, leaving the page flags as recorded", () => { const base = page(SEEDED); const items = [...SEEDED, vessel(4, "Laid Up")]; diff --git a/src/domain/analysisView/environmentStateListFacts.ts b/src/domain/analysisView/environmentStateListFacts.ts index 885c7358387..5848490897f 100644 --- a/src/domain/analysisView/environmentStateListFacts.ts +++ b/src/domain/analysisView/environmentStateListFacts.ts @@ -73,7 +73,8 @@ export const listFacts = ( /** * A list envelope's item totals, each by its counter: a top-level member's name, or the pointer to one in a - * top-level object beside the list, such as `/pageInfo/totalRows`. + * top-level object beside the list, such as `/pageInfo/totalRows`; a top-level name starting with `/` is named by + * its pointer, so a counter starting with `/` is always one. */ export const itemTotals = ( parent: JsonObject, @@ -82,7 +83,8 @@ export const itemTotals = ( const root = pointerTokens(listPointer)[0]; const totals: [string, JsonValue | undefined][] = []; for (const [name, value] of Object.entries(parent)) - if (isItemTotal(name)) totals.push([name, value]); + if (isItemTotal(name)) + totals.push([name.startsWith("/") ? pointerTo(name) : name, value]); else if (isObject(value) && name !== root) for (const [inner, count] of Object.entries(value)) if (isItemTotal(inner)) diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index 559e4b15432..eea61bc5a46 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -183,7 +183,7 @@ const viewSchema = z.discriminatedUnion("shape", [ counters: z .array(z.string()) .describe( - "Envelope members that count the listed entities: a top-level member's name, or a JSON pointer to one in a top-level object beside the list (`/pageInfo/totalRows`).", + "Envelope members that count the listed entities: a top-level member's name, or a JSON pointer to one in a top-level object beside the list (`/pageInfo/totalRows`); a top-level name starting with `/` is written as its pointer (`/~1total`).", ), query: listQuerySchema .optional() diff --git a/src/domain/analysisView/environmentStateWriteApply.test.ts b/src/domain/analysisView/environmentStateWriteApply.test.ts index f0f7b82f35d..306f9ade77c 100644 --- a/src/domain/analysisView/environmentStateWriteApply.test.ts +++ b/src/domain/analysisView/environmentStateWriteApply.test.ts @@ -376,6 +376,28 @@ it("takes an update's unique and renewed values from the generator, whether or n ]); }); +const HELD_PLAN: Plan = { + rules: [ + { field: "title", rule: "echo" }, + { field: "updatedAt", rule: "held-clock", format: SECONDS }, + ], + body: { ...UPDATE_PLAN.body!, accepted: ["title", "updatedAt"], fixed: [] }, +}; + +it("stamps a held clock only on a call that sends the value the entity holds", () => { + expect( + update({ title: "New Title", updatedAt: BEFORE.updatedAt! }, HELD_PLAN) + .result, + ).toEqual(ok({ ...BEFORE, title: "New Title", updatedAt: NOW })); + const { asked, result } = update({ title: "New Title" }, HELD_PLAN); + expect(result).toEqual( + err( + "Member updatedAt must be sent with the value the entity holds, as the recorded call did.", + ), + ); + expect(asked).toEqual([]); +}); + it("renews no child rows on an entity that holds none", () => { const { asked, result } = update({ title: "New Title" }, RENEWING_PLAN); expect(result.ok && result.value).not.toHaveProperty("steps"); diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index cf0fd3f11a2..904c0207d9e 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -3,8 +3,10 @@ import { at, isObject, locateItem, + same, scalarText, segmentsOf, + type JsonObject, } from "./environmentStateRules.js"; import { bulkCollectionOf, @@ -12,12 +14,12 @@ import { type NamedEntity, } from "./environmentStateWriteAddress.js"; import { itemTarget } from "./environmentStateWriteChecks.js"; -import { sameQuery } from "./environmentStateWriteStamps.js"; import { deleteEntity } from "./environmentStateWriteDelete.js"; import { built, fail, refuse, + retainFixed, updateEntity, UNKNOWN, type EffectContext, @@ -25,7 +27,7 @@ import { type WriteDraft, type WriteStep, } from "./environmentStateWriteEffects.js"; -import type { WriteResponse } from "./environmentStateWriteRules.js"; +import type { WriteBody, WriteResponse } from "./environmentStateWriteRules.js"; /** Whether any scalar in a body passes the test. */ const holds = ( @@ -72,6 +74,37 @@ export const bulkResponseFits = ( ); }; +/** The members a bulk delete sends besides the ids and each element's `identity` member, alike for every entity it names; undefined when they differ. */ +const deleteOptions = ( + named: readonly NamedEntity[], + identity: string | null, +): JsonObject | undefined => { + const [first, ...rest] = named.map(({ body }) => + Object.fromEntries( + Object.entries(body ?? {}).filter(([member]) => member !== identity), + ), + ); + return rest.every((options) => same(options, first)) ? first : undefined; +}; + +/** A bulk delete's body: every member its exemplar sent besides the ids, required and accepted only with the value sent. */ +const deleteBody = ( + options: JsonObject, + identity: string | null, +): WriteBody => ({ + accepted: [], + fixed: Object.entries(options).map(([member, sent]) => ({ member, sent })), + required: Object.keys(options), + identity, + kinds: [], +}); + +/** The members besides the ids a built bulk delete takes, as its body pins them. */ +const pinnedOptions = (body: WriteBody | null): JsonObject => + Object.fromEntries( + (body?.fixed ?? []).map(({ member, sent }) => [member, sent]), + ); + /** Apply a recorded bulk call to each entity its body names; one it names without holding leaves the call unmodelled there. */ export const applyBulk = ( context: EffectContext, @@ -86,28 +119,37 @@ export const applyBulk = ( ? undefined : namedEntities(address, body, context.idField(type)); // A call with another query than the exemplar's may do something else, as serving refuses it. - if ( - built(draft) && - !sameQuery( - context.io.queryOf(draft.plan.exemplar_ordinal ?? -1), - step.record.query, - ) - ) - return [UNKNOWN]; + if (!step.pinned) return [UNKNOWN]; if (named === undefined) { fail(draft, step, "body-unusable"); return [UNKNOWN]; } + const deleted = draft.plan.effect === "delete"; + const identity = address?.by === "elements" ? context.idField(type) : null; + const options = deleted ? deleteOptions(named, identity) : undefined; + // Serving deletes only with the members its exemplar sent besides the ids; a call sending others may do something else. + if ( + deleted && + (options === undefined || + (built(draft) && !same(options, pinnedOptions(draft.plan.body)))) + ) { + fail(draft, step, "body-unusable"); + return [UNKNOWN]; + } const collection = `/${bulkCollectionOf(type, segmentsOf(step.record.path), (text) => text).join("/")}`; const wasBuilt = built(draft); const results = named.map(({ id, body: members }) => { const target = itemTarget(context.state, type, { path: `${collection}/${encodeURIComponent(id)}`, }); - return draft.plan.effect === "delete" + return deleted ? deleteEntity(context, draft, step, target) : updateEntity(context, draft, step, { ...target, body: members }); }); + if (!wasBuilt && built(draft) && options !== undefined) { + draft.plan.body = deleteBody(options, identity); + retainFixed(context, draft.plan.body.fixed); + } // The plan's response is the exemplar's; serving answers any ids with it only in a shape it can render for them. const { response } = draft.plan; if ( diff --git a/src/domain/analysisView/environmentStateWriteCalls.ts b/src/domain/analysisView/environmentStateWriteCalls.ts index 080e6b382df..37587cfb075 100644 --- a/src/domain/analysisView/environmentStateWriteCalls.ts +++ b/src/domain/analysisView/environmentStateWriteCalls.ts @@ -20,7 +20,9 @@ export const unsentChange = (rule: FieldRule): boolean => /** Whether serving gives a rule's field a new value on every call, so no call may have kept it. */ export const regenerates = (rule: FieldRule): boolean => - rule.rule === "unique" || rule.rule === "renewed"; + rule.rule === "unique" || + rule.rule === "renewed" || + rule.rule === "nested-clock"; /** The fields a call showed as they were before it. */ export const keptFields = (before: JsonObject, after: JsonObject): string[] => @@ -86,10 +88,7 @@ export const contradictsEarlierCalls = ( const ruled = new Set(draft.plan.rules.map((rule) => rule.field)); return rules.some( (rule) => - (unsentChange(rule) || - regenerates(rule) || - rule.rule === "clock" || - rule.rule === "nested-clock") && + (unsentChange(rule) || regenerates(rule) || rule.rule === "clock") && !ruled.has(rule.field) && draft.updates.some(({ shown, sent, kept }) => { if (regenerates(rule)) return kept.includes(rule.field); diff --git a/src/domain/analysisView/environmentStateWriteChanges.ts b/src/domain/analysisView/environmentStateWriteChanges.ts index fffddc528bd..a13b2f9f527 100644 --- a/src/domain/analysisView/environmentStateWriteChanges.ts +++ b/src/domain/analysisView/environmentStateWriteChanges.ts @@ -115,14 +115,14 @@ export const sameSecondClocks = (evidence: UpdateEvidence): string[] => inCallSecond(evidence.after[field], evidence.startMs), ); -/** How an update stored a sent member: stamped anew as the one held clock it sent back, echoed, renewed as a fresh UUID, or as a constant. */ +/** How an update stored a sent member: stamped anew as the one held clock it sent back other than a creation clock, echoed, renewed as a fresh UUID, or as a constant. */ export const sentRule = ( evidence: UpdateEvidence, member: string, held: readonly string[], ): FieldRule => { const sent = evidence.call.body[member]!; - if (held.length === 1 && held[0] === member) + if (held.length === 1 && held[0] === member && !CREATION_CLOCK.test(member)) return { field: member, rule: "held-clock", diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 7ecd3be8881..f2793eb2c8f 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -19,6 +19,7 @@ import { envelopeOf, isOpaqueToken, restampedFields, + sameQuery, variedMembers, } from "./environmentStateWriteStamps.js"; import { @@ -29,6 +30,7 @@ import { import { collectionTarget, entityTarget, + succeeded, } from "./environmentStateWriteChecks.js"; import { built, @@ -147,6 +149,14 @@ const buildCreate = ( const type = draft.plan.target!; const idField = context.idField(type); const members = fieldsOf(context.state.members(type, evidence.collection)); + // Only calls serving would take, successful and with the exemplar's query, show that a member may vary. + const calls = new Set(step.tool.record_ordinals); + const taken = context.records.filter( + (record) => + calls.has(record.ordinal) && + succeeded(record) && + sameQuery(record.query, step.record.query), + ); const explained = explainCreate({ entity: evidence.observed.object, call: evidence.call, @@ -156,7 +166,7 @@ const buildCreate = ( type: fieldsOf(context.state.ofType(type)), named: (id) => context.state.named(id), varied: variedMembers( - step.tool.record_ordinals.map((ordinal) => { + taken.map(({ ordinal }) => { const body = context.io.requestBody(ordinal); return envelopeOf(body)?.object ?? body; }), @@ -414,7 +424,7 @@ export const applyCreate = ( (draft.linked !== undefined && !fromLinkedSource(context, draft, step))) ) return UNKNOWN; - const body = requestObject(context, step.record, draft); + const body = requestObject(context, step, draft); const observed = createdObservation(context, step, { type, collection, diff --git a/src/domain/analysisView/environmentStateWriteDelete.ts b/src/domain/analysisView/environmentStateWriteDelete.ts index 7db2a285dd3..495d6882e53 100644 --- a/src/domain/analysisView/environmentStateWriteDelete.ts +++ b/src/domain/analysisView/environmentStateWriteDelete.ts @@ -14,18 +14,20 @@ import { } from "./environmentStateWriteEffects.js"; import { responseShapeOf } from "./environmentStateWriteExplain.js"; -/** Apply a recorded delete: the held entity leaves its collection. */ +/** Apply a recorded delete: the held entity leaves its collection, unless the call sent another query than serving pins, which may delete nothing. */ export const applyDelete = ( context: EffectContext, draft: WriteDraft, step: WriteStep, ): EffectResult => - deleteEntity( - context, - draft, - step, - itemTarget(context.state, draft.plan.target!, step.record), - ); + step.pinned + ? deleteEntity( + context, + draft, + step, + itemTarget(context.state, draft.plan.target!, step.record), + ) + : UNKNOWN; /** Remove the held entity a call names. */ export const deleteEntity = ( diff --git a/src/domain/analysisView/environmentStateWriteDocument.ts b/src/domain/analysisView/environmentStateWriteDocument.ts index b15130a2529..9ff753070bb 100644 --- a/src/domain/analysisView/environmentStateWriteDocument.ts +++ b/src/domain/analysisView/environmentStateWriteDocument.ts @@ -105,7 +105,7 @@ export const applyDocument = ( if (initial !== undefined && !namesDocument(step.record.path, initial.path)) return UNKNOWN; const value = context.state.document(tool); - const body = requestObject(context, step.record); + const body = requestObject(context, step); const pointer = value === undefined || body === undefined ? undefined diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index a722a4c2fd3..ca712ad2dfb 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -145,6 +145,8 @@ export interface WriteStep { readonly tool: StateToolFacts; /** Set once the plan has a reason: the write only brings the state to its recorded outcome. */ readonly observeOnly: boolean; + /** Whether the call sent the query serving pins, its exemplar's, as every call before the plan is built does. */ + readonly pinned: boolean; } /** @@ -206,20 +208,18 @@ export const refuse = ( if (!step.observeOnly) draft.plan.reason = reason; }; -/** A call's body object; an entity write's is unwrapped from a one-element envelope, and once its plan is built only one sent with the exemplar's query and wrapping counts, as serving takes it. */ +/** A call's body object, none for a call serving refuses by its query; an entity write's is unwrapped from a one-element envelope, and once its plan is built only one sent with the exemplar's wrapping counts, as serving takes it. */ export const requestObject = ( context: EffectContext, - record: StateRecordFacts, + step: WriteStep, draft?: WriteDraft, ): JsonObject | undefined => - plannedObject( - { body: context.io.requestBody(record.ordinal), query: record.query }, - draft && { - built: built(draft), - envelope: draft.plan.body?.envelope, - query: context.io.queryOf(draft.plan.exemplar_ordinal ?? -1), - }, - ); + step.pinned + ? plannedObject( + context.io.requestBody(step.record.ordinal), + draft && { built: built(draft), envelope: draft.plan.body?.envelope }, + ) + : undefined; export const callOf = ( step: WriteStep, @@ -428,9 +428,11 @@ export const applyUpdate = ( }); // An item action names its change in its path, so it may send no body. const body = - action && context.io.requestBody(step.record.ordinal) === undefined + action && + step.pinned && + context.io.requestBody(step.record.ordinal) === undefined ? {} - : requestObject(context, step.record, draft); + : requestObject(context, step, draft); return updateEntity(context, draft, step, { ...named, body }); }; diff --git a/src/domain/analysisView/environmentStateWriteSorted.ts b/src/domain/analysisView/environmentStateWriteSorted.ts index 8fffea31a38..97c5a61a833 100644 --- a/src/domain/analysisView/environmentStateWriteSorted.ts +++ b/src/domain/analysisView/environmentStateWriteSorted.ts @@ -13,9 +13,10 @@ import { type StateRecordFacts, type StateView, } from "./environmentStateRules.js"; -import type { - CheckOutcome, - SimulatedState, +import { + entityTarget, + type CheckOutcome, + type SimulatedState, } from "./environmentStateWriteChecks.js"; import type { WriteIo } from "./environmentStateWriteEffects.js"; import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; @@ -30,6 +31,13 @@ const inOrder = (values: readonly string[]): boolean => const ordered = (value: JsonValue | undefined): value is string[] => value !== undefined && isStringArray(value) && new Set(value).size >= 2; +/** Whether no object a read shows lists the field as a string array out of order. */ +const listedSorted = (shown: readonly JsonObject[], field: string): boolean => + shown.every((object) => { + const value = object[field]; + return !ordered(value) || inOrder(value); + }); + /** An entity's value of a field as one view shows it: its own recorded value, else the stored one. */ const shownBy = ( entity: StateEntity, @@ -88,9 +96,9 @@ interface Candidates { * Array fields a view lists sorted however they were written, as APIs that keep tags as sets do. * A field is learned only from a read the gate counts that fails with the stored order and passes * with it sorted, where the order could not be the written one or the order the application first - * held the values in; one counted read listing it unsorted rules it out for that view. The stored - * value keeps the written order, so a write's response still echoes it; every view of the type that - * could sort the field sorts it once one does. + * held the values in; one counted read listing it unsorted rules it out for that view, learned or + * not. The stored value keeps the written order, so a write's response still echoes it; every view + * of the type that could sort the field sorts it once one does. */ export class SortedArrays { readonly #candidates = new Map(); @@ -135,7 +143,8 @@ export class SortedArrays { /** * Note what a read the gate counts shows, then retry it if it failed: the outcome with the fewest * candidate fields sorted that make it pass, which the type's views then keep; the outcome as it - * was when none does, the passing check is blocked or the read's order is ambiguous. + * was, without any learned field the read lists unsorted, when none does, the passing check is + * blocked or the read's order is ambiguous. */ retry( view: StateView, @@ -143,18 +152,24 @@ export class SortedArrays { check: (view: StateView) => CheckOutcome | undefined, blocked: (targets: readonly string[]) => boolean, ): CheckOutcome { - const failed = read.outcome; - if (view.shape !== "item" && view.shape !== "list") return failed; - // A view with no candidate left has nothing to note or retry, so its read is never parsed. - if (!this.#candidates.has(view.tool)) return failed; + if (view.shape !== "item" && view.shape !== "list") return read.outcome; + // A view with no candidate or learned field left has nothing to note or retry, so its read is never parsed. + if (!this.#candidates.has(view.tool) && !this.#adopted.has(view.tool)) + return read.outcome; const shown = this.#shown(view, read.record); this.#ruleOut(view.tool, shown); + // A read listing a learned field unsorted is checked again as the view now lists it. + const current = this.#unlearn(view.tool, shown) + ? { ...view, sorted_arrays: this.#adopted.get(view.tool) ?? [] } + : view; + const failed = + current === view ? read.outcome : (check(current) ?? read.outcome); const candidates = this.#candidates.get(view.tool)?.fields; if (failed.pass || candidates === undefined) return failed; const passing = (fields: readonly string[]) => { const outcome = check({ - ...view, - sorted_arrays: [...(view.sorted_arrays ?? []), ...fields], + ...current, + sorted_arrays: [...(current.sorted_arrays ?? []), ...fields], }); return outcome?.pass === true && !blocked([...outcome.targets, ...outcome.unheld]) @@ -169,7 +184,8 @@ export class SortedArrays { const retried = fewer.length === 0 ? undefined : passing(fewer); if (retried !== undefined) [needed, outcome] = [fewer, retried]; } - if (!needed.every((field) => this.#telling(view, shown, field))) + const targets = new Set(outcome.targets); + if (!needed.every((field) => this.#telling(view, shown, field, targets))) return failed; this.#adopt(view.type, needed); return outcome; @@ -190,22 +206,28 @@ export class SortedArrays { #ruleOut(tool: string, shown: readonly JsonObject[]): void { const entry = this.#candidates.get(tool); if (entry === undefined) return; - const left = entry.fields.filter((field) => - shown.every((object) => { - const value = object[field]; - return !ordered(value) || inOrder(value); - }), - ); + const left = entry.fields.filter((field) => listedSorted(shown, field)); if (left.length === 0) this.#candidates.delete(tool); else if (left.length < entry.fields.length) this.#candidates.set(tool, { ...entry, fields: left }); } - /** Whether a read shows a written array in an order neither the written one nor the order the values were first held in. */ + /** A read listing a learned field unsorted shows its view does not sort it after all; whether one was. */ + #unlearn(tool: string, shown: readonly JsonObject[]): boolean { + const adopted = this.#adopted.get(tool) ?? []; + const kept = adopted.filter((field) => listedSorted(shown, field)); + if (kept.length === adopted.length) return false; + if (kept.length === 0) this.#adopted.delete(tool); + else this.#adopted.set(tool, kept); + return true; + } + + /** Whether a read shows a written array of an entity it covers in an order neither the written one nor the order the values were first held in. */ #telling( view: StateItemView | StateListView, shown: readonly JsonObject[], field: string, + targets: ReadonlySet, ): boolean { const idField = this.facts.idField(view.type) ?? ""; const existing = this.#existing.get(`${view.type}\u0000${field}`)!; @@ -213,9 +235,12 @@ export class SortedArrays { const value = object[field]; const id = scalarText(object[idField]); if (!ordered(value) || id === undefined) return false; - return this.facts.state.ofType(view.type).some((entity) => { - const written = entity.id === id ? entity.fields[field] : undefined; + return this.facts.state.named(id).some((entity) => { + const written = entity.fields[field]; return ( + targets.has( + entityTarget(entity.type, entity.collection, entity.id), + ) && written !== undefined && isStringArray(written) && written.length === value.length && diff --git a/src/domain/analysisView/environmentStateWriteStamps.test.ts b/src/domain/analysisView/environmentStateWriteStamps.test.ts index 044298a3119..271136c39ad 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.test.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.test.ts @@ -204,7 +204,7 @@ describe("values an update stamps without being sent them", () => { stampProblem( rules, { ...before, excerpt: "Custom." }, - { title: "No html" }, + { title: "No html", updated_at: before.updated_at }, ), ).toBeUndefined(); }); @@ -338,6 +338,21 @@ describe("clocks an update sends back unchanged", () => { expect(ruleFor(whole.rules, "created_at")?.rule).toBe("echo"); expect(ruleFor(whole.rules, "updated_at")?.rule).toBe("echo"); }); + + it("echoes a creation clock a call sent back in the second the entity was made", () => { + const second = "2026-03-04T05:06:00.000Z"; + const result = explainUpdate( + updated( + { id: "42", title: "Post", created_at: second }, + { id: "42", title: "Post (edited)", created_at: second }, + { title: "Post (edited)", created_at: second }, + ), + ); + expect(ruleFor(result.rules, "created_at")).toEqual({ + field: "created_at", + rule: "echo", + }); + }); }); describe("objects whose clocks a write stamps", () => { diff --git a/src/domain/analysisView/environmentStateWriteStamps.ts b/src/domain/analysisView/environmentStateWriteStamps.ts index e6dca7db5bc..b153d975ba1 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.ts @@ -101,30 +101,23 @@ export const unenveloped = ( return wrapped?.member === envelope ? wrapped.object : undefined; }; -/** A call's body object as its plan takes it: an entity write's unwrapped from its envelope, and once the plan is built only one sent with the exemplar's query and wrapping. */ +/** A call's body object as its plan takes it: an entity write's unwrapped from its envelope, and once the plan is built only one sent with the exemplar's wrapping. */ export const plannedObject = ( - call: { - readonly body: JsonValue | undefined; - readonly query: string | null | undefined; - }, + body: JsonValue | undefined, plan: | { readonly built: boolean; readonly envelope: string | undefined; - readonly query: string | null | undefined; } | undefined, ): JsonObject | undefined => { - // A recorded call with another query than the exemplar's may do something else with its body. - if (plan?.built === true && !sameQuery(plan.query, call.query)) - return undefined; const envelope = plan === undefined ? undefined : plan.built ? plan.envelope - : envelopeOf(call.body)?.member; - const object = unenveloped(call.body, envelope); + : envelopeOf(body)?.member; + const object = unenveloped(body, envelope); return object !== undefined && isObject(object) ? object : undefined; }; @@ -421,7 +414,7 @@ export const derivedRule = ( : undefined; }; -/** Why a call cannot take an update's rules: a derived value for an entity holding another than the recorded one, or a held clock sent otherwise than the entity holds it. */ +/** Why a call cannot take an update's rules: a derived value for an entity holding another than the recorded one, or a held clock not sent or sent otherwise than the entity holds it. */ export const stampProblem = ( rules: readonly FieldRule[], before: JsonObject, @@ -434,9 +427,10 @@ export const stampProblem = ( !same(before[rule.field] ?? null, rule.from) ) return `Member ${rule.member} is accepted only on an entity whose ${rule.field} is as the recorded call found it, since the application derives ${rule.field} from it.`; + if (rule.rule === "held-clock" && !Object.hasOwn(sent, rule.field)) + return `Member ${rule.field} must be sent with the value the entity holds, as the recorded call did.`; if ( rule.rule === "held-clock" && - Object.hasOwn(sent, rule.field) && !same(sent[rule.field], before[rule.field]) ) return `Member ${rule.field} must repeat the value the entity holds, as the recorded call did.`; diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 0025c12d6ed..8499bf74b20 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -2042,6 +2042,45 @@ describe("values an application stamps", () => { }); }); +describe("nested clocks another recorded call kept", () => { + const CARD_INIT_ROWS: TimedCaptureRow[] = [ + ["GET", "/api/cards", [FIRST_CARD, SECOND_CARD]], + ["GET", "/api/cards/1", FIRST_CARD], + ["GET", "/api/cards/2", SECOND_CARD], + ]; + /** The first card renamed, with its edit stamped 64 ms into the given exchange's second, or kept as it was. */ + const card = (name: string, stampedAt?: number) => ({ + ...FIRST_CARD, + name, + edit: + stampedAt === undefined + ? FIRST_CARD.edit + : { + at: new Date(Date.parse(bookClock(stampedAt)) + 64).toISOString(), + by: "rea", + }, + }); + const put = (written: ReturnType): TimedCaptureRow[] => [ + ["PUT", "/api/cards/1", written, 200, { name: written.name }], + ["GET", "/api/cards/1", written], + ]; + const verdictOf = (rows: readonly TimedCaptureRow[]) => + planOf(stateOf([...CARD_INIT_ROWS, ...rows]), "put_cards_by_id"); + + it("serves no update whose nested clock another recorded call kept, before or after the call that stamped it", () => { + expect( + verdictOf([...put(card("Edited", 3)), ...put(card("Renamed", 5))]), + ).toMatchObject({ served: true }); + const stamped = card("Edited", 3); + expect( + verdictOf([...put(stamped), ...put({ ...stamped, name: "Renamed" })]), + ).toMatchObject({ served: false, reason: "unexplained-change" }); + expect( + verdictOf([...put(card("Edited")), ...put(card("Renamed", 5))]), + ).toMatchObject({ served: false, reason: "unexplained-change" }); + }); +}); + /** A book with tags, as an application that keeps tags as a set lists them. */ const tagged = (entry: Book, tags: string[]): Book => ({ ...entry, tags }); const TAGGED_INIT_ROWS: TimedCaptureRow[] = [ @@ -2136,6 +2175,59 @@ describe("array fields a view lists sorted", () => { }); }); +/** A book on a shelf, in a collection per shelf whose ids repeat across shelves. */ +const shelved = (tags: string[]) => ({ id: 1, name: "Shelved Book", tags }); + +describe("evidence a learned sort keeps answering to", () => { + it("drops a sort a view learned once a later counted read lists the field as written", () => { + const state = stateOf([ + ...TAGGED_INIT_ROWS, + ["GET", "/api/books/2", tagged(SECOND_BOOK, ["delta", "zeta"])], + [ + "GET", + "/api/books", + [ + tagged(FIRST_BOOK, ["alpha", "beta"]), + tagged(SECOND_BOOK, ["zeta", "delta"]), + ], + ], + ]); + expect(planOf(state, "patch_books_by_id")).toMatchObject({ + served: true, + checked_record_ordinals: [4, 5], + }); + expect( + state.views.find((view) => view.tool === "get_books_by_id"), + ).toMatchObject({ sorted_arrays: ["tags"] }); + expect( + state.views.find((view) => view.tool === "get_books"), + ).not.toHaveProperty("sorted_arrays"); + }); + + it("learns no sorting from another collection's entity under the read's id", () => { + // Shelf 1's read-back fits `alpha`, held before the update, then `zeta` as written; shelf 2's book shares its id. + const state = stateOf([ + ["GET", "/api/shelves/1/books", [shelved(["alpha", "beta"])]], + ["GET", "/api/shelves/1/books/1", shelved(["alpha", "beta"])], + ["GET", "/api/shelves/2/books", [shelved(["beta", "gamma"])]], + ["GET", "/api/shelves/2/books/1", shelved(["beta", "gamma"])], + [ + "PATCH", + "/api/shelves/1/books/1", + shelved(["zeta", "alpha"]), + 200, + { tags: ["zeta", "alpha"] }, + ], + ["GET", "/api/shelves/1/books/1", shelved(["alpha", "zeta"])], + ]); + expect(state.writes).toEqual([ + expect.objectContaining({ served: false, reason: "contradicted" }), + ]); + for (const view of state.views) + expect(view).not.toHaveProperty("sorted_arrays"); + }); +}); + describe("initial order", () => { it("orders a collection as a whole list line that applies no sort lists it, after an item read and filtered or sorted lines", () => { const alpha = book(1, "Alpha", "2026-10-01T09:00:00Z"); @@ -2300,3 +2392,118 @@ describe("clocks an update may stamp in its own second", () => { ); }); }); + +/** A book with an `archived` flag, which an item action sets. */ +const withArchived = (entity: Book, archived: boolean): Book => ({ + ...entity, + archived, +}); + +/** A post whose `status` goes with whether it has a publication clock. */ +const post = (id: number, status: string, publishedAt: string | null) => ({ + id, + title: `Post ${id}`, + status, + published_at: publishedAt, +}); + +describe("recorded calls serving would refuse", () => { + it("serves no action that only a call sent with another query showed setting its field", () => { + const archived = withArchived(FIRST_BOOK, true); + // Serving pins toggle=true, so the call sent with toggle=false shows nothing of what serving does. + const plan = planOf( + stateOf([ + [ + "GET", + "/api/books", + [withArchived(FIRST_BOOK, false), withArchived(SECOND_BOOK, false)], + ], + ["GET", "/api/books/1", withArchived(FIRST_BOOK, false)], + ["GET", "/api/books/2", withArchived(SECOND_BOOK, false)], + ["POST", "/api/books/1/archive?toggle=true", archived], + ["GET", "/api/books/1", archived], + ["POST", "/api/books/1/archive?toggle=false", archived], + ["GET", "/api/books/1", archived], + ]), + "post_books_archive_by_id", + ); + expect(plan).toMatchObject({ served: false, reason: "unconfirmed" }); + }); + + it("confirms no document write by a call sent with another query than serving pins", () => { + // The dry run changed nothing; the read after the real call shows only what that call did. + const plan = planOf( + stateOf([ + ["GET", "/api/settings", { theme: "light", lang: "en" }], + [ + "PATCH", + "/api/settings?dry_run=true", + { theme: "dark", lang: "en" }, + 200, + { theme: "dark" }, + ], + [ + "PATCH", + "/api/settings?dry_run=false", + { theme: "dark", lang: "en" }, + 200, + { theme: "dark" }, + ], + ["GET", "/api/settings", { theme: "dark", lang: "en" }], + ]), + "patch_settings", + ); + expect(plan).toMatchObject({ served: false, checked_record_ordinals: [] }); + }); + + it("confirms no delete by a call sent with another query than serving pins", () => { + const plan = planOf( + stateOf([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books/2?dry_run=true", "", 204], + ["DELETE", "/api/books/1?dry_run=false", "", 204], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ]), + "delete_books_by_id", + ); + expect(plan).toMatchObject({ served: false, checked_record_ordinals: [] }); + }); + + it("keeps a create's state at its recorded value, though a failed call or one with another query sent another", () => { + const draft = post(3, "draft", null); + const sent = { title: "Post 3", status: "draft" }; + const others: TimedCaptureRow[] = [ + ["POST", "/api/posts", { detail: "Invalid." }, 422, { status: "x" }], + [ + "POST", + "/api/posts?import=true", + post(4, "published", bookClock(6)), + 201, + { title: "Post 4", status: "published" }, + ], + ]; + for (const other of others) { + const plan = planOf( + stateOf([ + [ + "GET", + "/api/posts", + [ + post(1, "published", "2026-10-01T09:00:00Z"), + post(2, "published", "2026-10-01T10:00:00Z"), + ], + ], + ["GET", "/api/posts/1", post(1, "published", "2026-10-01T09:00:00Z")], + ["GET", "/api/posts/2", post(2, "published", "2026-10-01T10:00:00Z")], + ["POST", "/api/posts", draft, 201, sent], + ["GET", "/api/posts/3", draft], + other, + ]), + "post_posts", + ); + expect(plan.body?.fixed, other[1]).toEqual([ + { member: "status", sent: "draft" }, + ]); + } + }); +}); From 364891b4db62bdd1bfe2b9ee23cb50aeecb613f3 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 14:57:15 -0700 Subject: [PATCH 45/68] docs(environment): record the review fixes' checks Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/write-rules/verification.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md index 24f7c3fb181..714a148eb52 100644 --- a/docs/specs/agent-environments/write-rules/verification.md +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -11,8 +11,9 @@ serving, reading records with REA's own capture parser, and compares the reads; - `npm run -s check:fast`, `npm run -s format:check`, `npx knip`, `npm run -s scan:todos`, `npm run -s docs:check`, `npm run -s verify:test-discovery` and `npm run -s mcp-catalog:check`: passed. -- `npm run jscpd`: 3.57% duplicated lines over 4174 files (3.58% on the base). -- `npx vitest run --project domain --project services`: 9289 passed, 6 pre-existing skips. +- `npm run jscpd`: 3.57% duplicated lines over 4235 files. +- `npx vitest run --project domain --project services`: 9545 passed, 6 pre-existing skips. The 10 failures (JavaScript + Map endpoints, a returned invocation's alias graph, Frida cleanup) fail the same way on main. - `npm run -s test:prepare`, then `npm run -s test:focused --` the environment serve and export CLI boundaries, the serve and served-writes MCP boundaries, the analysis-view CLI and MCP boundaries, the compact input schema boundary and tool schema validity: 8 files, 91 passed. @@ -31,9 +32,16 @@ serving, reading records with REA's own capture parser, and compares the reads; | created nested clocks | 71 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | | unshown writes refused | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | | catalog values, atomic bulk | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| review fixes | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | All 187 write tools are counted at every step, and the served smoke applies every served write tool. +- **Review fixes:** literal bulk ids, per-entity bulk values, pinned bulk delete members, comparison ids per + collection, echoed creation clocks, required held clocks, nested clocks checked against every call, learned sorts + kept open to contrary reads and limited to the read's own entities, one query check per recorded call, guards + relaxed only by successful calls with the exemplar's query, and slash-named counters. No tool's verdict and no + session read changed; each fix has a test that fails without it. + - **Newly served:** Ghost's post create and update, Metabase's card create and update, n8n's workflow update, Navidrome's playlist create, and the NocoDB and Mailpit bulk deletes. - **No longer served:** Gitea's issue update. Its create, update and read share one second, so the evidence cannot show From 9614465f05561dd07acae294236d769cd63898ba Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 20:19:13 -0700 Subject: [PATCH 46/68] perf(environment): compare variant lines through shared entities and parse each compared body once The variant pass indexes a tool's lines by the entities they show and compares only lines that share one, charging the index to the budget while it is held; the pairwise work limit still decides when a tool keeps every line checked. Read-only decisions keep each response body's canonical digest, taken once while its parse is charged, across calls and veto passes. The creation cut no longer parses reads at or after the write that ends the initial reads, and reads the ids a body shows inside its lease. Adoption looks up a read's target only after an unplanned write before it. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 51 +++++----- .../EnvironmentStateExtraction.ts | 9 +- .../EnvironmentStateWriteSimulation.test.ts | 34 ++++++- .../environmentStateQueryCalls.test.ts | 98 +++++++++++++++++-- .../environmentStateQueryCalls.ts | 67 ++++++++----- .../analysisView/environmentStateVariants.ts | 76 ++++++++++---- .../analysisView/environmentStateView.test.ts | 65 ++++++++++++ .../environmentStateWriteAdoption.ts | 4 +- .../environmentStateWriteLinks.test.ts | 94 +++++++++++++++++- .../environmentStateWriteLinks.ts | 40 ++++---- 10 files changed, 436 insertions(+), 102 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index f34a655bf96..aef046da231 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -22,37 +22,40 @@ its cause in the recordings and the code. The five largest shared causes: - **Read-only calls.** A POST is not a state write when its response repeats the read of its path that finished last before it began, with no write between, it tunnels only read operations, its last literal segment names a lookup and - no write, or it renews a session; it is replayed. It stays a write when one of its calls was redirected or - unanswered, or when a related read line changes across one of its calls, or finds its entity there on one side only, - with no write but other read-only calls between; a read overlapping the call counts on neither side. + no write, or it renews a session; it is replayed. It stays a write when one of its calls was redirected or unanswered, + or when a related read line changes across one of its calls, or finds its entity there on one side only, with no write + but other read-only calls between; a read overlapping the call counts on neither side. Each response body compared is + parsed once and kept only as its canonical digest, charged to the view's budget until the decision ends. - **Adopted entities.** A successful item read of an entity the gate's copy never held, after a write no built plan models or one redirected or unanswered, puts the entity into the copy within the view's budget; an entity a modelled write touched is never taken back. - **Linked creates.** A POST whose path names no state type becomes a create into the type whose item read first names an id its response returned, before any other tool's write, when the id is new: no read finished before it began - showed it, whether an item read of the id under that type or collection whose body shows the item, a list of the - type or a read of that collection. Its observation is a read of an id its response returned, in an envelope too. - Serving creates in that read's collection, for the exemplar's path arguments only (segment by segment, in either - spelling), and fills path fields with its exemplar's path values decoded once. A successful POST that returned an id - a type's reads only show once it began ends that type's initial window: a read still running then may show it, and a - list read shows its listed entities' own ids (identity-named, or a suffix-named field such as `projectId` distinct - across two or more when no id-named field identifies them), not those they nest. + showed it, whether an item read of the id under that type or collection whose body shows the item, a list of the type + or a read of that collection. Its observation is a read of an id its response returned, in an envelope too. Serving + creates in that read's collection, for the exemplar's path arguments only (segment by segment, in either spelling), + and fills path fields with its exemplar's path values decoded once. A successful POST that returned an id a type's + reads only show once it began ends that type's initial window: a read still running then may show it, and a list read + shows its listed entities' own ids (identity-named, or a suffix-named field such as `projectId` distinct across two or + more when no id-named field identifies them), not those they nest. A read at or after the write that ends the initial + reads is not parsed for that cut, since it cannot show a new id. - **Rewrite cuts.** When a type's reads disagree across a write under another root, the type's initial window ends at the earliest write within the change and the state is extracted again. The earlier of this and the creation cut wins. -- **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's - checks, the entity observations (an entity's first sighting comes from the lines left) and the membership changes - that cut a type's initial window, and the view names it with the query keys that pick it out - (`projected_query_keys`, on item and list views). Beside a line showing whole entities, a list line asking for some - fields only (a projection value other than `*`) is set aside before the identity proof the same way. A call matching - those keys replays its recording, so it does not show served writes; a 400, 404 or 410 on such a line is still - evidence. A call asking for some fields only replays unless every value it gives is `*` or one a checked line gave, - and no replayed read gave it. The write gate skips exactly the successful reads serving replays, by the same - decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more - than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked. An item line first recorded - after the initial window is a variant too, judged against the lines left once variants are dropped: when it names a - new shaping parameter and its object carries or lacks members theirs do not, or selects some fields and leaves out - members they always show, and an item only a replayed line showed, which the state never started with and in whose - type no served create has added an entity since, answers with its own recording. +- **Variant lines.** A read line that shows the same entities in another form is a variant: it leaves the view's checks, + the entity observations (an entity's first sighting comes from the lines left) and the membership changes that cut a + type's initial window, and the view names it with the query keys that pick it out (`projected_query_keys`, on item and + list views). Beside a line showing whole entities, a list line asking for some fields only (a projection value other + than `*`) is set aside before the identity proof the same way. A call matching those keys replays its recording, so it + does not show served writes; a 400, 404 or 410 on such a line is still evidence. A call asking for some fields only + replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it. The write gate + skips exactly the successful reads serving replays, by the same decision. A filter role whose name matches no field + needs two agreeing values. A tool whose lines would take more than 2^24 line pairs and entity lookups to compare + pairwise keeps every line checked; otherwise lines are compared only with those showing one of the same entities, + through an index charged to the budget while it is held. An item line first recorded after the initial window is a + variant too, judged against the lines left once variants are dropped: when it names a new shaping parameter and its + object carries or lacks members theirs do not, or selects some fields and leaves out members they always show, and an + item only a replayed line showed, which the state never started with and in whose type no served create has added an + entity since, answers with its own recording. ## Acceptance diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 3a2c73bc1ff..8bbc223de57 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -148,14 +148,18 @@ export class EnvironmentStateExtraction { /** The timeline's state writes, less the calls of tools that only read. */ #findWrites(): void { + // The body digests the decision keeps are dropped with it, so what they were charged is released. + const release = this.#budget.checkpoint(); ({ readOnly: this.#readOnly, writes: this.#writes } = stateWritesOf( this.#tools, this.#records, { - response: (ordinal) => this.#withBody(ordinal, (body) => body), + withBody: (ordinal, use) => this.#withBody(ordinal, use), request: (ordinal) => this.#requestBody(ordinal), + retain: (bytes) => this.#retain(bytes), }, )); + release(); this.#writeWithin = writeSpanCheck(this.#writes); } @@ -223,6 +227,7 @@ export class EnvironmentStateExtraction { queryOf: (ordinal) => this.#byOrdinal.get(ordinal)?.query, position: (ordinal) => this.#position.get(ordinal)!, retain: (bytes) => this.#retain(bytes), + checkpoint: () => this.#budget.checkpoint(), }); if (split === undefined) continue; this.#retain(ENTRY_BYTES * (split.dropped.size + 2)); @@ -328,7 +333,7 @@ export class EnvironmentStateExtraction { tools: this.#tools, records: this.#byOrdinal, position: (record) => this.#position.get(record.ordinal)!, - body: (ordinal) => this.#withBody(ordinal, (body) => body), + withBody: (ordinal, use) => this.#withBody(ordinal, use), retain: (bytes) => this.#retain(bytes), }, first, diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index 587c7681605..7b1be9fa11e 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -1,6 +1,6 @@ import { OmittedFields } from "./environmentStateWriteOmitted.js"; import { checkedLines, servedLine } from "./environmentStateCheckedLines.js"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { timedCaptureEvidence, @@ -2298,6 +2298,38 @@ describe("entities an unmodelled write made", () => { expect(retained).toBeGreaterThan(20_000); }); + it("finds no read's target among the held entities until an unplanned write came before the read", () => { + const state = new SimulatedState([], []); + const targets = vi.spyOn(state, "ofType"); + const unseen = new UnseenEntities([], { + state, + io: { withBody: (_ordinal, use) => use(THIRD_BOOK), retain: () => 0 }, + lastCheck: new Map(), + idField: () => "id", + }); + const view = { shape: "item", type: "/api/books", pointer: "" }; + const read = (index: number) => ({ + record: { + ordinal: index, + method: "GET", + path: "/api/books/3", + query: undefined, + status: 200, + start: index, + end: index, + }, + index, + }); + const adopt = (index: number) => + unseen.adopt(view as unknown as StateItemView, read(index)); + expect(adopt(1)).toBeUndefined(); + // A write after the read cannot have made what it shows either. + unseen.unplanned(2); + expect(adopt(1)).toBeUndefined(); + expect(targets).not.toHaveBeenCalled(); + expect(adopt(3)).toMatchObject({ id: "3" }); + }); + it("takes back no book a modelled delete removed, so a list showing it again confirms no delete", () => { expect( gated(deletedAfterRead([RENAME, IMPORT]), "delete_books_by_id"), diff --git a/src/domain/analysisView/environmentStateQueryCalls.test.ts b/src/domain/analysisView/environmentStateQueryCalls.test.ts index 3fb1c48809b..f8ed3e0ef2f 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.test.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from "vitest"; import type { JsonValue } from "../jsonValue.js"; -import { readOnlyTools } from "./environmentStateQueryCalls.js"; +import { + readOnlyTools, + type QueryCallIo, +} from "./environmentStateQueryCalls.js"; import type { StateRecordFacts, StateToolFacts, @@ -20,8 +23,14 @@ interface Call { readonly end?: number; } +/** How the read-only pass parses response bodies and charges what it keeps of them, when a test watches either. */ +interface Bodies { + readonly withBody?: QueryCallIo["withBody"]; + readonly retain?: (bytes: number) => void; +} + /** The read-only tools of a timeline of calls, ordinals in order; a call spans its index unless it gives its times. */ -const readOnlyOf = (calls: readonly Call[]): string[] => { +const readOnlyOf = (calls: readonly Call[], bodies: Bodies = {}): string[] => { const records: StateRecordFacts[] = calls.map((call, index) => ({ ordinal: index, method: call.method, @@ -41,10 +50,13 @@ const readOnlyOf = (calls: readonly Call[]): string[] => { record_ordinals: [...(known?.record_ordinals ?? []), index], }); }); + const withBody: QueryCallIo["withBody"] = + bodies.withBody ?? ((ordinal, use) => use(calls[ordinal]?.response)); return [ ...readOnlyTools([...tools.values()], records, { - response: (ordinal) => calls[ordinal]?.response, + withBody, request: (ordinal) => calls[ordinal]?.request, + retain: bodies.retain ?? (() => undefined), }), ].sort(); }; @@ -476,8 +488,9 @@ describe("read-only decisions over many calls", () => { visits = 0; expect([ ...readOnlyTools(tools, records, { - response: () => [], + withBody: (_ordinal, use) => use([]), request: () => undefined, + retain: () => undefined, }), ]).toEqual(["post_ids"]); expect(visits).toBeLessThan(50 * records.length); @@ -531,8 +544,9 @@ describe("read-only decisions over a long run of calls", () => { visits = 0; expect([ ...readOnlyTools(tools, records, { - response: () => JOBS, + withBody: (_ordinal, use) => use(JOBS), request: () => ({ jobs: ["night-watch"] }), + retain: () => undefined, }), ]).toEqual(["post_statuses"]); expect(visits).toBeLessThan(50 * records.length); @@ -583,10 +597,82 @@ describe("read-only decisions over many lines", () => { ]; expect([ ...readOnlyTools(tools, records, { - response: () => [], + withBody: (_ordinal, use) => use([]), request: () => undefined, + retain: () => undefined, }), ]).toEqual(["post_ids"]); expect(reads).toBeLessThan(20 * records.length); }); }); + +describe("the bodies read-only decisions compare", () => { + const read = (members: string[]): Call => ({ + method: "GET", + path: "/api/members", + tool: "get_members", + response: members, + }); + const lookup: Call = { + method: "POST", + path: "/api/members/ids", + tool: "post_ids", + response: ["a"], + }; + const refresh: Call = { + method: "POST", + path: "/api/collections/_superusers/auth-refresh", + tool: "post_auth_refresh", + response: { token: "x" }, + }; + // The change across the lookup's calls drops it on the first pass, so the refresh is checked again. + const calls = [read(["a"]), lookup, lookup, refresh, read(["a", "b"])]; + + it("parses each read once across a tool's calls and the passes that drop vetoed tools", () => { + const parses = new Map(); + expect( + readOnlyOf(calls, { + withBody: (ordinal, use) => { + parses.set(ordinal, (parses.get(ordinal) ?? 0) + 1); + return use(calls[ordinal]?.response); + }, + }), + ).toEqual(["post_auth_refresh"]); + expect([...parses].filter(([, count]) => count > 1)).toEqual([]); + }); + + it("compares bodies only while their parse is charged, and charges what it keeps of each", () => { + const [parsed, outside] = [new Set(), new Set()]; + let parsing = false; + let retained = 0; + expect( + readOnlyOf(calls, { + withBody: (ordinal, use) => { + parsed.add(ordinal); + const body = calls[ordinal]?.response; + parsing = true; + try { + return use( + typeof body === "object" && body !== null + ? new Proxy(body, { + get: (target, key, receiver) => { + if (!parsing) outside.add(ordinal); + return Reflect.get(target, key, receiver) as unknown; + }, + }) + : body, + ); + } finally { + parsing = false; + } + }, + retain: (bytes) => { + retained += bytes; + }, + }), + ).toEqual(["post_auth_refresh"]); + expect([...outside]).toEqual([]); + // Each body is kept as its digest's hex text, charged before it is. + expect(retained).toBeGreaterThanOrEqual(parsed.size * 64); + }); +}); diff --git a/src/domain/analysisView/environmentStateQueryCalls.ts b/src/domain/analysisView/environmentStateQueryCalls.ts index d934153c82e..19c44e7d68e 100644 --- a/src/domain/analysisView/environmentStateQueryCalls.ts +++ b/src/domain/analysisView/environmentStateQueryCalls.ts @@ -1,3 +1,4 @@ +import { digestCanonicalValue } from "../canonicalDigest.js"; import type { JsonValue } from "../jsonValue.js"; import { changesState, @@ -5,13 +6,13 @@ import { isParam, isStateWrite, QUERY_SEGMENTS, - same, segmentsOf, type StateRecordFacts, type StateToolFacts, } from "./environmentStateRules.js"; import { isAbsence } from "./environmentStateWriteChecks.js"; import { prefixRelated } from "./environmentStateWriteRules.js"; +import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js"; /** The words of a segment or operation name: split on `_`, `-`, `.` and camelCase, in lower case. */ const words = (text: string): string[] => @@ -89,10 +90,33 @@ const OPERATION_PARAMETERS = ["operation", "op", "action"]; /** What deciding read-only calls reads besides the tools and the timeline. */ export interface QueryCallIo { - readonly response: (ordinal: number) => JsonValue | undefined; + /** Parse one response body and hand it to `use` while its parse is charged; unusable bodies arrive undefined. */ + readonly withBody: ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ) => T; readonly request: (ordinal: number) => JsonValue | undefined; + readonly retain: (bytes: number) => void; } +/** Each response body's canonical digest, taken once while its parse is charged and charged itself once kept; undefined when unusable. */ +const responseDigests = ( + io: QueryCallIo, +): ((ordinal: number) => string | undefined) => { + const digests = new Map(); + return (ordinal) => { + if (digests.has(ordinal)) return digests.get(ordinal); + const digest = io.withBody(ordinal, (body) => + body === undefined + ? undefined + : digestCanonicalValue(body, "Environment state"), + ); + io.retain(ENTRY_BYTES + textBytes(digest?.length ?? 0)); + digests.set(ordinal, digest); + return digest; + }; +}; + const succeeded = (record: StateRecordFacts): boolean => record.status !== null && record.status >= 200 && record.status < 300; @@ -160,6 +184,7 @@ export const readOnlyTools = ( const position = new Map( records.map((record, index) => [record.ordinal, index]), ); + const response = responseDigests(io); /** The timeline indexes of the nearest state writes either side of an index, the skipped calls aside: -1 and the length when none, found in one pass each way. */ const nearestWrites = ( skip: ReadonlySet, @@ -200,7 +225,7 @@ export const readOnlyTools = ( const timeline = { position, ...nearestWrites(new Set(tool.record_ordinals)), - io, + response, }; if ( repeatsRead(calls, records, timeline) || @@ -216,7 +241,7 @@ export const readOnlyTools = ( ...nearestWrites( new Set([...candidates.values()].flat().map((call) => call.ordinal)), ), - io, + response, }; vetoed = false; for (const [name, calls] of candidates) @@ -237,7 +262,8 @@ interface Timeline { }; /** Whether the record at a timeline index is another write. */ readonly isWrite: (index: number) => boolean; - readonly io: QueryCallIo; + /** A response body's canonical digest; undefined when unusable. */ + readonly response: (ordinal: number) => string | undefined; } /** Of these reads, the one that finished last before `call` began, a later one on a tie; records come in start order. */ @@ -259,15 +285,15 @@ const lastFinishedBefore = ( const repeatsRead = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], - { position, isWrite, io }: Timeline, + { position, isWrite, response }: Timeline, ): boolean => { const answering = calls.filter(succeeded); const reads = lastReads(answering, records, position, isWrite); return answering.every((call) => { const read = reads.get(call.ordinal); if (read === undefined) return false; - const answered = io.response(call.ordinal); - return answered !== undefined && same(answered, io.response(read.ordinal)); + const answered = response(call.ordinal); + return answered !== undefined && answered === response(read.ordinal); }); }; @@ -409,7 +435,7 @@ const lastMeaningfulWord = (segment: string): string | undefined => const changesReadsAcross = ( calls: readonly StateRecordFacts[], records: readonly StateRecordFacts[], - { position, writes, io }: Timeline, + { position, writes, response }: Timeline, ): boolean => { const stretches = new Map< string, @@ -429,7 +455,7 @@ const changesReadsAcross = ( else stretch.calls.push(call); } for (const stretch of stretches.values()) - if (changesInStretch(stretch, records, { position, io })) return true; + if (changesInStretch(stretch, records, { position, response })) return true; return false; }; @@ -442,13 +468,10 @@ const changesInStretch = ( readonly calls: readonly StateRecordFacts[]; }, records: readonly StateRecordFacts[], - { position, io }: Pick, + { position, response }: Pick, ): boolean => { - const shown = (record: StateRecordFacts): JsonValue | symbol => { - if (!succeeded(record)) return ABSENT; - const body = io.response(record.ordinal); - return body === undefined ? UNKNOWN : body; - }; + const shown = (record: StateRecordFacts): string | symbol => + succeeded(record) ? (response(record.ordinal) ?? UNKNOWN) : ABSENT; const lines = new Map(); for (let index = stretch.from + 1; index < stretch.to; index += 1) { const record = records[index]!; @@ -466,7 +489,7 @@ const changesInStretch = ( // A line whose reads all show one thing cannot change across any call. const changing = [...lines.values()].filter((reads) => { const first = shown(reads[0]!); - return reads.some((read) => !sameShown(first, shown(read))); + return reads.some((read) => shown(read) !== first); }); return stretch.calls.some((call) => { const at = position.get(call.ordinal)!; @@ -482,7 +505,7 @@ const changesInStretch = ( const [was, now] = [shown(earlier), shown(later)]; // Presence on one side only is a change even when a body is unusable. if ((was === ABSENT) !== (now === ABSENT)) return true; - return was !== UNKNOWN && now !== UNKNOWN && !sameShown(was, now); + return was !== UNKNOWN && now !== UNKNOWN && was !== now; }); }); }; @@ -491,14 +514,6 @@ const changesInStretch = ( const ABSENT = Symbol("absent"); const UNKNOWN = Symbol("unknown"); -const sameShown = ( - left: JsonValue | symbol, - right: JsonValue | symbol, -): boolean => - typeof left === "symbol" || typeof right === "symbol" - ? left === right - : same(left, right); - /** The timeline's state writes, less the calls of tools whose calls only read, and those tools. */ export const stateWritesOf = ( tools: readonly StateToolFacts[], diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index 5d4fd413fc3..da591893006 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -113,12 +113,42 @@ const EMPTY: LineShape = { /** Line pairs and entity lookups the variant pass may make; a plan whose lines need more keeps every line checked. */ const VARIANT_WORK_LIMIT = 1 << 24; -/** Whether two lines show a shared entity with different members. */ -const conflicts = (left: LineShape, right: LineShape): boolean => - [...left.entities].some( - ([key, members]) => - right.entities.has(key) && right.entities.get(key) !== members, - ); +/** For each entity some lines show, those lines by the members they show it with. */ +type LinesByEntity = ReadonlyMap< + string, + ReadonlyMap +>; + +/** The lines by the entities they show, an entry for each entity each line shows charged before it is kept. */ +const linesByEntity = ( + lines: readonly StateRecordFacts[], + shape: (record: StateRecordFacts) => LineShape, + retain: (bytes: number) => void, +): LinesByEntity => { + const shown = new Map>(); + for (const line of lines) + for (const [key, members] of shape(line).entities) { + retain(ENTRY_BYTES); + const showing = shown.get(key) ?? new Map(); + shown.set(key, showing); + const group = showing.get(members); + if (group === undefined) showing.set(members, [line]); + else group.push(line); + } + return shown; +}; + +/** The lines that show one of a line's entities with other members. */ +const conflictingLines = ( + mine: LineShape, + shown: LinesByEntity, +): Set => { + const conflicting = new Set(); + for (const [key, members] of mine.entities) + for (const [others, lines] of shown.get(key)!) + if (others !== members) for (const line of lines) conflicting.add(line); + return conflicting; +}; /** What lines compared later are compared with: the shaping parameter names they named, the members their objects carried, and those every one carried. */ interface LineTotals { @@ -172,7 +202,7 @@ const showsOtherMembers = ( /** The base lines so far, with their totals. */ interface BaseLines extends LineTotals { - readonly lines: StateRecordFacts[]; + readonly lines: Set; } /** @@ -182,6 +212,7 @@ interface BaseLines extends LineTotals { export const variantLines = ( latest: readonly StateRecordFacts[], shapeOf: (record: StateRecordFacts) => LineShape | undefined, + retain: (bytes: number) => void = () => undefined, ): StateRecordFacts[] => { if (latest.length < 2) return []; const shapes = new Map( @@ -191,16 +222,16 @@ export const variantLines = ( (sum, line) => sum + line.entities.size, 0, ); - // Each line is compared with every other, pair by pair and entity by entity. + // Comparing every pair of lines entity by entity bounds comparing only the lines that share an entity. if (latest.length * (latest.length + entities) > VARIANT_WORK_LIMIT) return []; const shape = (record: StateRecordFacts): LineShape => shapes.get(record)!; + const shown = linesByEntity(latest, shape, retain); const ranks = new Map( latest.map((record) => { const names = shapingNames(record.query).length; - const agreeing = latest.filter( - (other) => other !== record && !conflicts(shape(record), shape(other)), - ).length; + const agreeing = + latest.length - 1 - conflictingLines(shape(record), shown).size; return [ record, [ @@ -219,13 +250,13 @@ export const variantLines = ( const differs = a.findIndex((value, index) => value !== b[index]); return differs === -1 ? 0 : a[differs]! - b[differs]!; }); - const base: BaseLines = { ...noLines(), lines: [] }; + const base: BaseLines = { ...noLines(), lines: new Set() }; const variants: StateRecordFacts[] = []; for (const record of ordered) { - if (base.lines.length > 0 && isVariant(record, base, shape)) + if (base.lines.size > 0 && isVariant(record, base, shape(record), shown)) variants.push(record); else { - base.lines.push(record); + base.lines.add(record); addLine(base, record.query, shape(record)); } } @@ -236,12 +267,11 @@ export const variantLines = ( const isVariant = ( record: StateRecordFacts, base: BaseLines, - shape: (record: StateRecordFacts) => LineShape, -): boolean => { - const mine = shape(record); - if (base.lines.some((line) => conflicts(mine, shape(line)))) return true; - return namesNewParameter(record.query, base) && showsOtherMembers(mine, base); -}; + mine: LineShape, + shown: LinesByEntity, +): boolean => + [...conflictingLines(mine, shown)].some((line) => base.lines.has(line)) || + (namesNewParameter(record.query, base) && showsOtherMembers(mine, base)); /** The keys that tell replayed lines from base lines: a parameter or value only replayed lines give, or a parameter every base line names that one leaves out. */ export const replayKeys = ( @@ -369,11 +399,15 @@ export const withoutVariants = ( readonly queryOf: (ordinal: number) => string | null | undefined; readonly position: (ordinal: number) => number; readonly retain: (bytes: number) => void; + readonly checkpoint: () => () => void; }, ): | { readonly plan: StatePlan; readonly dropped: ReadonlySet } | undefined => { - const found = variantLines(plan.latest, facts.shapeOf); + // The lines indexed by entity are dropped once compared, so what they were charged is released. + const release = facts.checkpoint(); + const found = variantLines(plan.latest, facts.shapeOf, facts.retain); + release(); const unkeyed = plan.latest.filter((record) => !found.includes(record)); const variants = found.filter( (record) => diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index c602beec62d..c945f93896e 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -26,14 +26,17 @@ import { replaceAt, renderStateList, type JsonObject, + type StateRecordFacts, } from "./environmentStateRules.js"; import { environmentStateFields } from "./environmentStateView.js"; import { lineShapes, replayKeys, variantLines, + type LineShape, } from "./environmentStateVariants.js"; import { rewriteCuts } from "./environmentStateRewrites.js"; +import { ENTRY_BYTES } from "./webNetworkRouteTemplates.js"; type State = Extract; const ALL_RULES = [ @@ -931,6 +934,68 @@ it("leaves every line checked when comparing many mostly empty lines would excee expect(reads).toBeLessThan(10 * lines.length); }); +/** Item lines reading each of `items` items plainly, then each again with `?expand=shelf`; each shape's entities count the walks over them. */ +const expandedItemLines = (items: number) => { + let walks = 0; + const lines: StateRecordFacts[] = Array.from( + { length: items * 2 }, + (_, ordinal) => ({ + ordinal, + method: "GET", + path: `/api/items/${String(ordinal % items)}`, + query: ordinal < items ? undefined : "?expand=shelf", + status: 200, + start: ordinal, + end: ordinal, + }), + ); + const shapes = new Map( + lines.map((line): [StateRecordFacts, LineShape] => { + const members = + line.query === undefined ? ["id", "name"] : ["id", "name", "shelf"]; + const entities = new Map([ + [ + JSON.stringify([ + "/api/items", + "/api/items", + String(line.ordinal % items), + ]), + JSON.stringify(members), + ], + ]); + const walk = entities[Symbol.iterator].bind(entities); + entities[Symbol.iterator] = () => { + walks += 1; + return walk(); + }; + const carried = new Set(members); + return [line, { entities, carried, common: carried }]; + }), + ); + return { + lines, + shapeOf: (record: StateRecordFacts) => shapes.get(record), + walks: () => walks, + }; +}; + +it("compares lines through the entities they show, so items read plainly and expanded are not compared pair by pair", () => { + const { lines, shapeOf, walks } = expandedItemLines(1000); + expect(variantLines(lines, shapeOf)).toEqual(lines.slice(1000)); + // Comparing every pair would walk each line's entities thousands of times. + expect(walks()).toBeLessThan(10 * lines.length); +}); + +it("counts what it holds to compare lines by the entities they show against the budget", () => { + const { lines, shapeOf } = expandedItemLines(100); + let retained = 0; + variantLines(lines, shapeOf, (bytes) => { + retained += bytes; + }); + // An entry for each entity each line shows. + expect(retained).toBeGreaterThanOrEqual(lines.length * ENTRY_BYTES); +}); + /** The smallest allowance, to a KiB, a capture's state projects within. */ const allowance = (parent: AnalysisViewParent): number => { const fits = (bytes: number): boolean => diff --git a/src/domain/analysisView/environmentStateWriteAdoption.ts b/src/domain/analysisView/environmentStateWriteAdoption.ts index af5691a9406..93c52ac5d5c 100644 --- a/src/domain/analysisView/environmentStateWriteAdoption.ts +++ b/src/domain/analysisView/environmentStateWriteAdoption.ts @@ -68,7 +68,9 @@ export class UnseenEntities { ): StateEntity | undefined { const { record, index } = read; const { state, lastCheck } = this.facts; - if (!succeeded(record)) return undefined; + // Only an unplanned write before the read can have made what it shows, so its target is found only then. + if (!succeeded(record) || !this.#unplannedAt.some((write) => write < index)) + return undefined; const { collection, id } = itemTarget(state, view.type, record); const key = entityTarget(view.type, collection, id); if (this.#held.has(key) || state.entity(view.type, collection, id)) diff --git a/src/domain/analysisView/environmentStateWriteLinks.test.ts b/src/domain/analysisView/environmentStateWriteLinks.test.ts index ed95a17b396..85b40df3d43 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.test.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.test.ts @@ -46,7 +46,7 @@ const projectsLimit = ( ], records: new Map([...reads, post].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, - body: (ordinal) => bodies.get(ordinal), + withBody: (ordinal, use) => use(bodies.get(ordinal)), retain, }, undefined, @@ -78,7 +78,7 @@ describe("creation limits", () => { ], records: new Map([list, post, later].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, - body: (ordinal) => bodies.get(ordinal), + withBody: (ordinal, use) => use(bodies.get(ordinal)), retain: () => undefined, }, undefined, @@ -180,7 +180,7 @@ describe("creation limits", () => { ], records: new Map([item, post, later].map((at) => [at.ordinal, at])), position: (at) => at.ordinal, - body: (ordinal) => bodies.get(ordinal), + withBody: (ordinal, use) => use(bodies.get(ordinal)), retain: () => undefined, }, undefined, @@ -241,3 +241,91 @@ describe("the ids creation limits keep", () => { expect(retained).toBeLessThan(lists * 1000 * 16); }); }); + +describe("the reads creation limits parse", () => { + /** + * The creation limit of `/api/projects` over list reads, a POST returning `proj-0002` that later + * lists show, and the write that ends the initial reads; with the reads parsed, and those whose + * body was read after its parse ended. + */ + const parsedLimit = ( + reads: readonly StateRecordFacts[], + post: StateRecordFacts, + until: StateRecordFacts, + ) => { + const parsed: number[] = []; + const outside = new Set(); + let parsing = false; + const withBody = ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ): T => { + parsed.push(ordinal); + const body: JsonValue[] = + ordinal < post.ordinal + ? [{ id: "proj-0001" }] + : [{ id: "proj-0001" }, { id: "proj-0002" }]; + parsing = true; + try { + return use( + new Proxy(body, { + get: (target, key, receiver) => { + if (!parsing) outside.add(ordinal); + return Reflect.get(target, key, receiver) as unknown; + }, + }), + ); + } finally { + parsing = false; + } + }; + const limit = creationLimit( + [{ record: post, ids: ["proj-0002"] }], + { + type: "/api/projects", + tools: [ + { + name: "get_projects", + method: "GET", + path_template: "/api/projects", + record_ordinals: reads.map((read) => read.ordinal), + }, + ], + records: new Map([...reads, post, until].map((at) => [at.ordinal, at])), + position: (at) => at.ordinal, + withBody, + retain: () => undefined, + }, + until, + ); + return { limit, parsed, outside }; + }; + + it("parses no read at or after the write that ends the initial reads, since no id it shows can be fresh", () => { + const reads = [0, 2, 4, 5].map((ordinal) => + record(ordinal, "GET", "/api/projects"), + ); + const post = record(1, "POST", "/api/imports"); + const { limit, parsed } = parsedLimit( + reads, + post, + record(3, "PUT", "/api/projects/proj-0001"), + ); + expect(limit).toBe(post); + expect(parsed).toEqual([0, 2]); + }); + + it("reads the ids a body shows only while its parse is charged", () => { + const reads = [0, 2].map((ordinal) => + record(ordinal, "GET", "/api/projects"), + ); + const post = record(1, "POST", "/api/imports"); + const { limit, outside } = parsedLimit( + reads, + post, + record(3, "PUT", "/api/projects/proj-0001"), + ); + expect(limit).toBe(post); + expect([...outside]).toEqual([]); + }); +}); diff --git a/src/domain/analysisView/environmentStateWriteLinks.ts b/src/domain/analysisView/environmentStateWriteLinks.ts index 9332be54e74..ef4493fb5f8 100644 --- a/src/domain/analysisView/environmentStateWriteLinks.ts +++ b/src/domain/analysisView/environmentStateWriteLinks.ts @@ -113,11 +113,11 @@ const showsItem = (body: JsonValue | undefined, id: string): boolean => const shownIds = ( record: StateRecordFacts, item: boolean, - body: () => JsonValue | undefined, + body: JsonValue | undefined, ): Set => { - if (!item) return listedIds(body()); + if (!item) return listedIds(body); const id = lastSegmentValue(record.path); - return showsItem(body(), id) ? new Set([id]) : new Set(); + return showsItem(body, id) ? new Set([id]) : new Set(); }; /** The shown ids a creation returned, each charged before it is kept. */ @@ -217,7 +217,10 @@ export const creationLimit = ( readonly tools: readonly StateToolFacts[]; readonly records: ReadonlyMap; readonly position: (record: StateRecordFacts) => number; - readonly body: (ordinal: number) => JsonValue | undefined; + readonly withBody: ( + ordinal: number, + use: (body: JsonValue | undefined) => T, + ) => T; readonly retain: (bytes: number) => void; }, until: StateRecordFacts | undefined, @@ -232,23 +235,24 @@ export const creationLimit = ( ? [{ tool, item: read.item }] : []; }); + // A read at or after `end` is no counted creation's read before or after it, so it is not parsed. const shown: ShownRead[] = readers.flatMap(({ tool, item }) => tool.record_ordinals.flatMap((ordinal) => { const record = reads.records.get(ordinal); - return record === undefined || !succeeded(record) - ? [] - : [ - { - at: reads.position(record), - end: record.end, - item, - ids: keptIds( - shownIds(record, item, () => reads.body(ordinal)), - returned, - reads.retain, - ), - }, - ]; + if (record === undefined || !succeeded(record)) return []; + const at = reads.position(record); + if (at >= end) return []; + const ids = reads.withBody(ordinal, (body) => + shownIds(record, item, body), + ); + return [ + { + at, + end: record.end, + item, + ids: keptIds(ids, returned, reads.retain), + }, + ]; }), ); for (const creation of [...creations].sort( From 53b2966c52ed10705dd9909db2ccbf12254036e1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 20:19:14 -0700 Subject: [PATCH 47/68] docs(environment): record the eleventh review round's checks Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/state-targets/verification.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index f0427acbc62..1d1ba8686c4 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -71,6 +71,11 @@ write tool is lost. matching). - **Tenth round** (on main `a2235b09`): no verdict, read view, recorded read or session replay changes on the restored captures. +- **Eleventh round** (on main `2968d1e9`, performance review): variant lines compare only lines that share an entity, + read-only decisions parse each body once and keep its digest, and the creation cut skips reads that cannot count. + Every census, serving-check and session-replay row equals the previous head's. On a synthetic capture of a list and + 1,000 items read plainly and with `?expand=`, the variant pass falls from 401 ms to 2 ms and the state build from 659 + ms to 216 ms (Node v22.23.1). Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From 3dd85f21c7635590d936b94cde385b750c059256 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 22:55:04 -0700 Subject: [PATCH 48/68] perf(environment): list a type's collections only when the path's own holds no id, and parse variant base lines once The write gate's item target lists the type's held collections, and the removed targets', only when the path's own collection holds none of its ids, so a served item view's reads no longer walk every entity of the type. The variant pass parses the base lines' queries once for all the variants they key, and not at all when it found none. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/spec.md | 10 +-- .../EnvironmentStateWriteSimulation.test.ts | 26 +++++-- .../analysisView/environmentStateVariants.ts | 72 +++++++++++++------ .../analysisView/environmentStateView.test.ts | 38 ++++++++++ .../environmentStateWriteChecks.ts | 9 +-- 5 files changed, 120 insertions(+), 35 deletions(-) diff --git a/docs/specs/agent-environments/state-targets/spec.md b/docs/specs/agent-environments/state-targets/spec.md index aef046da231..f6736337782 100644 --- a/docs/specs/agent-environments/state-targets/spec.md +++ b/docs/specs/agent-environments/state-targets/spec.md @@ -51,11 +51,11 @@ its cause in the recordings and the code. The five largest shared causes: skips exactly the successful reads serving replays, by the same decision. A filter role whose name matches no field needs two agreeing values. A tool whose lines would take more than 2^24 line pairs and entity lookups to compare pairwise keeps every line checked; otherwise lines are compared only with those showing one of the same entities, - through an index charged to the budget while it is held. An item line first recorded after the initial window is a - variant too, judged against the lines left once variants are dropped: when it names a new shaping parameter and its - object carries or lacks members theirs do not, or selects some fields and leaves out members they always show, and an - item only a replayed line showed, which the state never started with and in whose type no served create has added an - entity since, answers with its own recording. + through an index charged to the budget while it is held. The base lines' queries are parsed once for every variant + they key. An item line first recorded after the initial window is a variant too, judged against the lines left once + variants are dropped: when it names a new shaping parameter and its object carries or lacks members theirs do not, or + selects some fields and leaves out members they always show, and an item only a replayed line showed, which the state + never started with and in whose type no served create has added an entity since, answers with its own recording. ## Acceptance diff --git a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts index 7b1be9fa11e..2ee9a0d8e70 100644 --- a/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts +++ b/src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts @@ -1246,10 +1246,11 @@ describe("reads named as serving names them", () => { }); describe("encoded parent spellings", () => { - it("names the plainly held entity from a path that encodes its parent", () => { - const type = "/api/orgs/uid/{uid}/books"; - const collection = "/api/orgs/uid/acme1/books"; - const state = new SimulatedState( + const type = "/api/orgs/uid/{uid}/books"; + const collection = "/api/orgs/uid/acme1/books"; + /** A state holding one book under its parent's plain spelling. */ + const plainlyHeld = () => + new SimulatedState( [ { type, @@ -1262,9 +1263,26 @@ describe("encoded parent spellings", () => { ], [], ); + + it("names the plainly held entity from a path that encodes its parent", () => { + expect( + itemTarget(plainlyHeld(), type, { + path: "/api/orgs/uid/%61cme1/books/1", + }), + ).toEqual({ collection, id: "1" }); + }); + + it("lists the type's entities only when the path's own collection holds no such id", () => { + const state = plainlyHeld(); + const listed = vi.spyOn(state, "ofType"); + expect( + itemTarget(state, type, { path: "/api/orgs/uid/acme1/books/1" }), + ).toEqual({ collection, id: "1" }); + expect(listed).not.toHaveBeenCalled(); expect( itemTarget(state, type, { path: "/api/orgs/uid/%61cme1/books/1" }), ).toEqual({ collection, id: "1" }); + expect(listed).toHaveBeenCalledTimes(1); }); it("answers an encoded read from the plain checked line", () => { diff --git a/src/domain/analysisView/environmentStateVariants.ts b/src/domain/analysisView/environmentStateVariants.ts index da591893006..c553b7d341b 100644 --- a/src/domain/analysisView/environmentStateVariants.ts +++ b/src/domain/analysisView/environmentStateVariants.ts @@ -273,19 +273,43 @@ const isVariant = ( [...conflictingLines(mine, shown)].some((line) => base.lines.has(line)) || (namesNewParameter(record.query, base) && showsOtherMembers(mine, base)); +/** What replay keys are found against: every value each base line gave a parameter, and the parameters every base line names. */ +interface KeyBase { + readonly values: ReadonlyMap>; + readonly everywhere: readonly string[]; +} + +/** Parse the base lines' queries once, for any number of replayed lines. */ +const keyBase = (base: readonly (string | null | undefined)[]): KeyBase => { + const baseValues = base.map(queryValues); + const values = new Map>(); + for (const line of baseValues) + for (const [name, given] of line) { + const seen = values.get(name) ?? new Set(); + values.set(name, seen); + for (const value of given) seen.add(value); + } + const everywhere = [...values.keys()].filter( + (name) => + !PAGING.has(name.toLowerCase()) && + baseValues.every((line) => line.has(name)), + ); + return { values, everywhere }; +}; + /** The keys that tell replayed lines from base lines: a parameter or value only replayed lines give, or a parameter every base line names that one leaves out. */ export const replayKeys = ( base: readonly (string | null | undefined)[], replayed: readonly (string | null | undefined)[], retain: (bytes: number) => void = () => undefined, +): ReplayKey[] => keysAgainst(keyBase(base), replayed, retain); + +/** The replay keys of replayed lines against base lines parsed once. */ +const keysAgainst = ( + { values: baseValues, everywhere }: KeyBase, + replayed: readonly (string | null | undefined)[], + retain: (bytes: number) => void, ): ReplayKey[] => { - const baseValues = base.map(queryValues); - const named = new Set(baseValues.flatMap((values) => [...values.keys()])); - const everywhere = [...named].filter( - (name) => - !PAGING.has(name.toLowerCase()) && - baseValues.every((values) => values.has(name)), - ); const keys = new Map(); const add = (key: ReplayKey): void => { const id = JSON.stringify([ @@ -302,13 +326,9 @@ export const replayKeys = ( const values = queryValues(query); for (const [name, given] of values) { if (PAGING.has(name.toLowerCase())) continue; - const unseen = given.filter( - (value) => - !baseValues.some( - (other) => other.get(name)?.includes(value) === true, - ), - ); - if (!named.has(name)) add({ name }); + const seen = baseValues.get(name); + const unseen = given.filter((value) => seen?.has(value) !== true); + if (seen === undefined) add({ name }); else for (const value of unseen) add({ name, value }); } for (const name of everywhere) @@ -391,6 +411,21 @@ export const replayReason = ( const requestLine = (record: StateRecordFacts): string => record.path + (record.query ?? ""); +/** The found lines a replay key tells from the other latest lines, which are parsed once for all of them. */ +const keyedVariants = ( + latest: readonly StateRecordFacts[], + found: readonly StateRecordFacts[], +): StateRecordFacts[] => { + if (found.length === 0) return []; + const variant = new Set(found); + const base = keyBase( + latest.filter((record) => !variant.has(record)).map((line) => line.query), + ); + return found.filter( + (record) => keysAgainst(base, [record.query], () => undefined).length > 0, + ); +}; + /** The plan with the variants a key picks out moved to its replayed reads and their recordings dropped, or undefined when it replays nothing. */ export const withoutVariants = ( plan: StatePlan, @@ -408,14 +443,7 @@ export const withoutVariants = ( const release = facts.checkpoint(); const found = variantLines(plan.latest, facts.shapeOf, facts.retain); release(); - const unkeyed = plan.latest.filter((record) => !found.includes(record)); - const variants = found.filter( - (record) => - replayKeys( - unkeyed.map((line) => line.query), - [record.query], - ).length > 0, - ); + const variants = keyedVariants(plan.latest, found); const lines = new Set(variants.map(requestLine)); const latest = plan.latest.filter( (record) => !lines.has(requestLine(record)), diff --git a/src/domain/analysisView/environmentStateView.test.ts b/src/domain/analysisView/environmentStateView.test.ts index c945f93896e..16a053af60f 100644 --- a/src/domain/analysisView/environmentStateView.test.ts +++ b/src/domain/analysisView/environmentStateView.test.ts @@ -33,6 +33,7 @@ import { lineShapes, replayKeys, variantLines, + withoutVariants, type LineShape, } from "./environmentStateVariants.js"; import { rewriteCuts } from "./environmentStateRewrites.js"; @@ -986,6 +987,43 @@ it("compares lines through the entities they show, so items read plainly and exp expect(walks()).toBeLessThan(10 * lines.length); }); +it("reads each base line's query a fixed number of times however many variants it keys", () => { + const items = 200; + const { lines, shapeOf } = expandedItemLines(items); + let reads = 0; + for (const line of lines.slice(0, items)) { + const { query } = line; + Object.defineProperty(line, "query", { + enumerable: true, + get: () => ((reads += 1), query), + }); + } + const tool = { + name: "get_items_by_id", + method: "GET", + path_template: "/api/items/{id}", + record_ordinals: lines.map((line) => line.ordinal), + }; + const plan = { + tool, + item: true, + type: "/api/items", + pointer: "", + recordings: lines, + latest: lines, + }; + const split = withoutVariants(plan, { + shapeOf, + queryOf: (ordinal) => lines[ordinal]?.query, + position: (ordinal) => ordinal, + retain: () => undefined, + checkpoint: () => () => undefined, + }); + expect(split?.plan.projected).toHaveLength(items); + // Keying each variant against the base lines anew reads every base line's query once per variant. + expect(reads).toBeLessThan(10 * items); +}); + it("counts what it holds to compare lines by the entities they show against the budget", () => { const { lines, shapeOf } = expandedItemLines(100); let retained = 0; diff --git a/src/domain/analysisView/environmentStateWriteChecks.ts b/src/domain/analysisView/environmentStateWriteChecks.ts index 7526160d67a..193619624f2 100644 --- a/src/domain/analysisView/environmentStateWriteChecks.ts +++ b/src/domain/analysisView/environmentStateWriteChecks.ts @@ -240,12 +240,13 @@ const matchingTarget = ( readonly ids: readonly string[]; readonly written: string; }, - collections: readonly string[], + /** Called only when the path's own collection holds none of its ids, since listing walks the type's entities. */ + collections: () => readonly string[], held: (collection: string, id: string) => boolean, ): { readonly collection: string; readonly id: string } | undefined => { for (const id of path.ids) if (held(path.written, id)) return { collection: path.written, id }; - const ranked = [...new Set(collections)] + const ranked = [...new Set(collections())] .flatMap((collection) => { const verbatim = segmentMatch(segmentsOf(collection), path.read); return verbatim === undefined ? [] : [{ collection, verbatim }]; @@ -278,12 +279,12 @@ export const itemTarget = ( return ( matchingTarget( path, - state.ofType(type).map((entity) => entity.collection), + () => state.ofType(type).map((entity) => entity.collection), (collection, id) => state.entity(type, collection, id) !== undefined, ) ?? matchingTarget( path, - removed.map((target) => target.collection), + () => removed.map((target) => target.collection), (collection, id) => removed.some( (target) => target.collection === collection && target.id === id, From dee4dd757a5a55f920f32c956f951ab4509c07f0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 23:02:02 -0700 Subject: [PATCH 49/68] docs(environment): record the twelfth review round's checks and the sweep's cost Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/state-targets/verification.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/specs/agent-environments/state-targets/verification.md b/docs/specs/agent-environments/state-targets/verification.md index 1d1ba8686c4..b218220552b 100644 --- a/docs/specs/agent-environments/state-targets/verification.md +++ b/docs/specs/agent-environments/state-targets/verification.md @@ -76,6 +76,14 @@ write tool is lost. Every census, serving-check and session-replay row equals the previous head's. On a synthetic capture of a list and 1,000 items read plainly and with `?expand=`, the variant pass falls from 401 ms to 2 ms and the state build from 659 ms to 216 ms (Node v22.23.1). +- **Twelfth round** (on main `d87e73f2`, second performance review): the write gate lists a type's collections only when + the path's own collection holds no id, and the variant pass parses base lines once. Every census, serving-check and + session-replay row equals the previous head's. The synthetic 1,000-item capture takes 259–264 ms against main's + 244–247 ms (378–397 ms before this round; Node v22.23.1, medians of seven warm runs). Over the 50 captures, the + environment-state and environment-manifest views together take 2.96 s wall and 3.82 s CPU with a 540 MiB peak RSS, + against main's 2.61 s, 3.41 s and 516 MiB (one Node v24.22.1 process per sweep, warm medians of three runs; the cold + first run is within 2% of them); the environment-state view alone takes 2,093 ms against 1,791 ms, and its results + grow from 3.69 MB to 3.84 MB. Agent tokens were not measured. Of the 40 views variant lines make state-backed, 146 of 151 recorded reads before the first write match; the other five (Sentry projects) are replayed, and replay returns the first of several differing recordings, as before. A paged From f01215d9347c882f7b5aecb7ed349568e4a066df Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 23 Oct 2026 23:02:30 -0700 Subject: [PATCH 50/68] docs(environment): record the 50-capture sweep's wall, CPU and peak memory Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/write-rules/verification.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md index 714a148eb52..ba13ae5f282 100644 --- a/docs/specs/agent-environments/write-rules/verification.md +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -57,6 +57,20 @@ Every change had an independent review that rebuilt it and tried to refute it; t the change. A final review of the whole branch found one wrongly served update (EspoCRM) and the hidden pinned values, both fixed. +## Cost + +Over the 50 captures, one Node v24.22.1 process per sweep builds the environment-state and environment-manifest views +of every capture (macOS arm64, warm medians of three runs; the cold first run is within 2% of them): + +| Tree | Wall | CPU | Peak RSS | Environment-state view | Its results | +| ----------------------- | ------ | ------ | -------- | ---------------------- | ----------- | +| main `d87e73f2` | 2.61 s | 3.41 s | 516 MiB | 1,791 ms | 3.69 MB | +| state targets (`#6385`) | 2.96 s | 3.82 s | 540 MiB | 2,093 ms | 3.84 MB | +| this branch | 3.06 s | 4.07 s | 601 MiB | 2,224 ms | 3.85 MB | + +The write rules add 0.10 s wall, 0.25 s CPU and 61 MiB of peak memory to the sweep while serving 7 more write tools. +Agent tokens were not measured; the views' results grow by 0.3%. + ## Not included - Templating literal ids by value: an opt-in rule served Grafana's folder delete and Vault's policy delete, but both From 3b66ee20b596ddb3e84dac4dc0daf9a5fc7e8dde Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:38:36 +0000 Subject: [PATCH 51/68] fix(environment): remove duplicate schema after main integration --- .../environment/environmentStateAnswer.ts | 2 +- .../analysisView/environmentStateView.ts | 20 ------------------- 2 files changed, 1 insertion(+), 21 deletions(-) diff --git a/src/application/environment/environmentStateAnswer.ts b/src/application/environment/environmentStateAnswer.ts index aa5b03dbee1..27155071cab 100644 --- a/src/application/environment/environmentStateAnswer.ts +++ b/src/application/environment/environmentStateAnswer.ts @@ -224,7 +224,6 @@ export const itemCall = ( : undefined; }; -/** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written, unless it is literal. */ /** Whether the state started with the item a call names, which a served delete may since have removed. */ const startedWithItem = ( store: EnvironmentStateStore, @@ -241,6 +240,7 @@ const startedWithItem = ( ); }; +/** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written, unless it is literal. */ export const namedEntity = ( store: EnvironmentStateStore, type: string, diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index da30b86c4e6..eea61bc5a46 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -153,26 +153,6 @@ const replayedReadFields = { "Query keys that pick calls of the replayed reads out: a parameter only they name, a value only they give a parameter, or (absent) a parameter every checked line names and they leave out. A call matching any key replays; a projection parameter's value is tested on its own: a call replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it.", ), }; -const replayedReadFields = { - projected_record_ordinals: z - .array(z.number().int().nonnegative()) - .optional() - .describe( - "Recorded reads left to replay: they asked for some fields only (`fields`, `select`), or show the entities in another representation than the checked lines (an augmenting or reducing query). Replayed calls do not show served writes.", - ), - projected_query_keys: z - .array( - z.strictObject({ - name: z.string(), - value: z.string().optional(), - absent: z.literal(true).optional(), - }), - ) - .optional() - .describe( - "Query keys that pick calls of the replayed reads out: a parameter only they name, a value only they give a parameter, or (absent) a parameter every checked line names and they leave out. A call matching any key replays; a projection parameter's value is tested on its own: a call replays unless every value it gives is `*` or one a checked line gave, and no replayed read gave it.", - ), -}; const viewSchema = z.discriminatedUnion("shape", [ z.strictObject({ ...entityViewFields, From f501e23cde822c697094b62b4879d449916ccf8d Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 08:45:38 +0000 Subject: [PATCH 52/68] fix(environment): honor recorded bulk identity kinds --- .../environmentStateBulkAnswer.test.ts | 33 +++++++++++++++++++ .../environmentStateWriteAddress.ts | 3 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 12e59b53cb0..4a3e00040fc 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -111,6 +111,39 @@ describe("served bulk write queries and capacity", () => { }); describe("served bulk write targets", () => { + it.each(["number", "string"] as const)( + "refuses ids whose JSON kind differs from the recorded %s array, without changing state", + (kind) => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "PATCH", + "/api/books", + "", + 204, + { ids: [kind === "number" ? 1 : "1"], name: "Renamed Book" }, + ], + ["GET", "/api/books/1", RENAMED_AT_3], + ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], + ]); + const before = books.snapshot(); + expect( + books.call("patch_books", { + body: { ids: [kind === "number" ? "1" : 1], name: "Changed" }, + }).ok, + ).toBe(false); + expect(books.snapshot()).toBe(before); + expect( + books.call("patch_books", { + body: { ids: [kind === "number" ? 1 : "1"], name: "Changed" }, + }).ok, + ).toBe(true); + expect(books.answer("get_books_by_id", { id: "1" }).body).toMatchObject({ + name: "Changed", + }); + }, + ); + it("takes a body's ids as written, refusing one that only decodes to a held id", () => { const books = servedFrom([ ...BOOK_INIT_ROWS, diff --git a/src/domain/analysisView/environmentStateWriteAddress.ts b/src/domain/analysisView/environmentStateWriteAddress.ts index ab440c9d3f6..232f3d8c6c6 100644 --- a/src/domain/analysisView/environmentStateWriteAddress.ts +++ b/src/domain/analysisView/environmentStateWriteAddress.ts @@ -229,7 +229,8 @@ export const namedEntities = ( if ( found === undefined || found.by !== address.by || - found.member !== address.member + found.member !== address.member || + (found.by === "ids" && address.by === "ids" && found.kind !== address.kind) ) return undefined; const entries = ( From 2c62bb9bd2cdb1ac58ee979555c1eb6ed3511480 Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:12:32 +0000 Subject: [PATCH 53/68] fix(environment): retain scoped evidence and honor write defaults --- .../agent-environments/state-view/spec.md | 10 +- .../agent-environments/state-writes/spec.md | 6 +- docs/web-network-captures.md | 2 +- .../environmentStateWriteDescription.ts | 3 +- .../environmentStateWriteDisclosure.test.ts | 74 ++++++++- .../environment/environmentTools.ts | 6 +- .../EnvironmentStateExtraction.ts | 2 +- .../analysisView/environmentStateGate.ts | 2 +- .../analysisView/environmentStateListFacts.ts | 2 +- .../environmentStateResponseMembers.test.ts | 45 +++++- .../environmentStateResponseMembers.ts | 23 +-- .../analysisView/environmentStateView.ts | 2 +- .../environmentStateWriteCalls.ts | 83 +++++++--- .../environmentStateWrites.test.ts | 48 ++++++ .../mcp/environmentServeWritesMcp.test.ts | 142 ++++++++++++++++++ 15 files changed, 396 insertions(+), 54 deletions(-) diff --git a/docs/specs/agent-environments/state-view/spec.md b/docs/specs/agent-environments/state-view/spec.md index 24a2b83142f..c7a602e6da6 100644 --- a/docs/specs/agent-environments/state-view/spec.md +++ b/docs/specs/agent-environments/state-view/spec.md @@ -84,10 +84,12 @@ later increments. - A top-level UUID or clock member that differs on every repeat of a path's successful GET lines with no write between, and across the capture differed on at least two repeats and never stayed the same, is minted per response - there (a request id). Views of that path, and item views whose collection is - that path, name it in `per_response_members`; an item plan's shared envelope - compares without it, and serving keeps the recorded value. A member minted on - one path is never left out of another path's views. + there (a request id). A view names it in `per_response_members` only when + every concrete path the view answers independently proves it minted. A + collection's proof does not establish that its item paths mint the same + member. The shared envelope compares without these common members, and + serving keeps their recorded values; an unproved envelope difference stays + recorded rather than borrowing another path's value. - Merge observations into one entity per collection and identity: item views' latest values win over list views', differing views keep their own values, and a value that changed between repeats of one request line with no recorded diff --git a/docs/specs/agent-environments/state-writes/spec.md b/docs/specs/agent-environments/state-writes/spec.md index c258feb1cea..f45e8eb4646 100644 --- a/docs/specs/agent-environments/state-writes/spec.md +++ b/docs/specs/agent-environments/state-writes/spec.md @@ -561,10 +561,12 @@ served. Their descriptions say the tool: - names the query its recording sent. The input schema says the same: each query parameter the recording sent is -required, with its value as the only `enum` member; a body that wraps its +optional, defaulting at execution to its recorded value, with a nonempty value +as the only `enum` member; an empty value is described and enforced at execution +because some clients reject empty literals. A body that wraps its object requires that member, an array of one object; and a member accepted only with its recorded value carries that value as `const` when it is short -and no boolean (some clients reject boolean literals), else a description +and neither a boolean nor an empty string (some clients reject these literals), else a description saying it must equal the recorded value. A refused member's message names the recorded value the same way. diff --git a/docs/web-network-captures.md b/docs/web-network-captures.md index 7248d9e297f..ef400725010 100644 --- a/docs/web-network-captures.md +++ b/docs/web-network-captures.md @@ -671,7 +671,7 @@ Every entity cites its `record_ordinals`. | Shape | Plan | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares, leaving out the `per_response_members` each response there mints: a top-level UUID or clock that differed on every repeat of its path's reads, or its collection's, with no write between, and never stayed the same on a repeat elsewhere; list views name theirs too | +| `item` | The entity object at `pointer` (the root, one member, or `/0` or `//0`), the ordered `fields` the view shows and the `required_fields` every recording had, and `envelope_ordinal`: the recording whose response, with the entity replaced, every item response shares, leaving out the `per_response_members` each response there mints: a top-level UUID or clock that differed on every repeat of every concrete path the view answers, with no write between, and never stayed the same on a repeat elsewhere; list views name theirs too | | `list` | The array at `pointer`, its `fields`, `membership` (`all`: every entity of the collection in state order, when each recording listed exactly that, had no query or only paging parameters (`limit`, `offset`, `page`, `per_page`, `perpage`, `page_size`, `pagesize`, `size`, `start`, `_start`, `_end`), no item-total member (`total`, `count`, `totalCount`, `item_count`, `totalcount`, `itemcount`, `numberOfElements`, but not `total_pages` or `per_page`; a number or a string of digits; top-level, or in a top-level object beside the list such as `pageInfo.totalRows`) differing from the number listed, and no `has_more`, `next` or next-page token member set; `recorded`: the entities each recording listed, except on the lines `all_record_ordinals` names, which each meet those conditions on their own and list every entity), and `counters` that equal the number listed | | `document` | The latest initial value of a list tool whose responses hold no identified list, when its initial reads share one request line; held in `documents` with that `path`, whether or not the capture writes it, unless its value changed across any recorded write between those reads (`fields-differ`); its `per_response_members` are the members of the value each response on that path mints | | `recorded` | A `reason` the tool replays its recordings instead | diff --git a/src/application/environment/environmentStateWriteDescription.ts b/src/application/environment/environmentStateWriteDescription.ts index b20d30fba3b..baf1c95cdde 100644 --- a/src/application/environment/environmentStateWriteDescription.ts +++ b/src/application/environment/environmentStateWriteDescription.ts @@ -102,9 +102,10 @@ export const writeQuery = ( /** A fixed member's schema: its recorded value as `const` when short and not a boolean, which some clients reject as a literal. */ const fixedSchema = (sent: JsonValue): EnvironmentToolSchema => { const shown = shownValue(sent); - if (shown !== undefined && typeof sent !== "boolean") + if (shown !== undefined && typeof sent !== "boolean" && sent !== "") return { const: sent, description: "Only the recorded value is accepted." }; return { + ...(typeof sent === "string" ? { type: "string" as const } : {}), description: shown === undefined ? "Must equal the recorded value, which is too long to show here." diff --git a/src/application/environment/environmentStateWriteDisclosure.test.ts b/src/application/environment/environmentStateWriteDisclosure.test.ts index c67b7fe961f..dce366bb68e 100644 --- a/src/application/environment/environmentStateWriteDisclosure.test.ts +++ b/src/application/environment/environmentStateWriteDisclosure.test.ts @@ -72,13 +72,13 @@ const toolOf = (rows: readonly TimedCaptureRow[], name: string) => { }; describe("served write queries", () => { - it("advertises the query a write's recording sent as required, and applies it when a call leaves it out", () => { + it("advertises the recorded query as optional so omission reaches its default", () => { const { served, tool } = toolOf(PINNED_ROWS, "patch_books_by_id"); expect(tool.inputSchema.properties["notify"]).toMatchObject({ type: "string", enum: ["quiet"], }); - expect(tool.inputSchema.required).toContain("notify"); + expect(tool.inputSchema.required).not.toContain("notify"); expect(tool.description).toContain("with the recorded query notify=quiet"); const before = served.snapshot(); expect( @@ -96,9 +96,79 @@ describe("served write queries", () => { }), ).toMatchObject({ status: 200, body: { id: 2, name: "Second Edition" } }); }); + + it.each(["notify", "notify="])( + "widens an empty pinned query literal in %s while enforcing it at runtime", + (query) => { + const rows: TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + [ + "PATCH", + `/api/books/1?${query}`, + RENAMED, + 200, + { name: "Renamed Book" }, + ], + ["GET", "/api/books/1", RENAMED], + ]; + const { served, tool } = toolOf(rows, "patch_books_by_id"); + expect(tool.inputSchema.properties["notify"]).not.toHaveProperty("enum"); + const before = served.snapshot(); + expect( + served.call("patch_books_by_id", { + id: "2", + notify: "yes", + body: { name: "Changed" }, + }).ok, + ).toBe(false); + expect(served.snapshot()).toBe(before); + expect( + served.call("patch_books_by_id", { id: "2", body: { name: "Changed" } }) + .ok, + ).toBe(true); + }, + ); }); describe("served write bodies", () => { + it("advertises an empty fixed body member without an empty literal, retaining its runtime guard", () => { + const rows: TimedCaptureRow[] = [ + ...FIXED_ROWS.slice(0, 3), + [ + "POST", + "/api/books", + STORED, + 201, + { + books: [ + { name: "Third Book", format: "", query: LONG, featured: true }, + ], + }, + ], + ...FIXED_ROWS.slice(4), + ]; + const { served, tool } = toolOf(rows, "post_books"); + expect(JSON.stringify(tool.inputSchema)).not.toContain('"const":""'); + const before = served.snapshot(); + expect( + served.call("post_books", { + body: { + books: [ + { name: "Fourth", format: "other", query: LONG, featured: true }, + ], + }, + }).ok, + ).toBe(false); + expect(served.snapshot()).toBe(before); + expect( + served.call("post_books", { + body: { + books: [{ name: "Fourth", format: "", query: LONG, featured: true }], + }, + }).ok, + ).toBe(true); + }); + it("shows the values a create fixes and the object it wraps, in its schema, description and refusals", () => { const { served, tool } = toolOf(FIXED_ROWS, "post_books"); expect(tool.inputSchema.properties["body"]).toMatchObject({ diff --git a/src/application/environment/environmentTools.ts b/src/application/environment/environmentTools.ts index 28ee265ba57..1cda2c6e890 100644 --- a/src/application/environment/environmentTools.ts +++ b/src/application/environment/environmentTools.ts @@ -356,10 +356,10 @@ function* environmentToolProperties( } : { type: "string", - enum: [pinned], - description: `Query parameter ${describeText(name, "query name")}; required: the served write takes only the value its recording sent, ${describeText(pinned, "query value")}, and applies it when left out.`, + ...(pinned === "" ? {} : { enum: [pinned] }), + description: `Query parameter ${describeText(name, "query name")}; optional: the served write takes only the value its recording sent, ${describeText(pinned, "query value")}, and applies it when left out.`, }, - pinned !== undefined, + false, ]; } if (args.body !== undefined) diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 28b9efc8230..1bcd3d46d7e 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -845,7 +845,7 @@ export class EnvironmentStateExtraction { value, record_ordinal: record.ordinal, }); - const minted = mintedFor(this.#minted ?? new Map(), [record], false); + const minted = mintedFor(this.#minted ?? new Map(), [record]); this.#views.set(tool.name, { tool: tool.name, shape: "document", diff --git a/src/domain/analysisView/environmentStateGate.ts b/src/domain/analysisView/environmentStateGate.ts index c6510285ad3..29ceceeebd6 100644 --- a/src/domain/analysisView/environmentStateGate.ts +++ b/src/domain/analysisView/environmentStateGate.ts @@ -276,7 +276,7 @@ export const checkItemPlan = ( const view = { tool: plan.tool.name, fields: union.fields }; const envelope: { skeleton?: string; members?: string[] } = {}; const spellings = new ClockSpellings(context.retain); - const minted = mintedFor(context.minted, plan.latest, true); + const minted = mintedFor(context.minted, plan.latest); for (const record of plan.latest) { const reason = itemMismatch( context, diff --git a/src/domain/analysisView/environmentStateListFacts.ts b/src/domain/analysisView/environmentStateListFacts.ts index d558e8dcc02..efbaf968243 100644 --- a/src/domain/analysisView/environmentStateListFacts.ts +++ b/src/domain/analysisView/environmentStateListFacts.ts @@ -32,7 +32,7 @@ export const listFacts = ( const field = context.idField(plan.type); const whole = new Set(); const counting = new Map(); - const names = mintedFor(context.minted, plan.latest, false); + const names = mintedFor(context.minted, plan.latest); const minted = new Set(); for (const record of plan.latest) context.withBody(record.ordinal, (body) => { diff --git a/src/domain/analysisView/environmentStateResponseMembers.test.ts b/src/domain/analysisView/environmentStateResponseMembers.test.ts index d1a19a6cef6..d41f2280cbb 100644 --- a/src/domain/analysisView/environmentStateResponseMembers.test.ts +++ b/src/domain/analysisView/environmentStateResponseMembers.test.ts @@ -40,9 +40,26 @@ const viewOf = (rows: readonly TimedCaptureRow[], tool: string) => (view) => view.tool === tool, ); -it("leaves out of an item envelope a member its collection's repeated reads mint anew, and serves the write the item read then checks", () => { +it("masks an item envelope member proved minted on every item path, and serves the write the item read checks", () => { + const rows = entityRows("/v1/entities"); + const itemRepeats: TimedCaptureRow[] = [ + ...Array.from({ length: 3 }, (_, n): TimedCaptureRow => [ + "GET", + `/v1/entities/${OPS}`, + reply(10 + n, { id: OPS, name: "ops" }), + ]), + ...Array.from({ length: 3 }, (_, n): TimedCaptureRow => [ + "GET", + `/v1/entities/${AUDIT}`, + reply(20 + n, { id: AUDIT, name: "audit" }), + ]), + ]; const state = environmentStateViewOf( - timedCaptureEvidence(entityRows("/v1/entities")), + timedCaptureEvidence([ + ...rows.slice(0, 3), + ...itemRepeats, + ...rows.slice(5), + ]), ); expect( state.views.find((view) => view.tool === "get_entities_by_uuid"), @@ -59,6 +76,15 @@ it("leaves out of an item envelope a member its collection's repeated reads mint ).toMatchObject({ served: true, reason: null }); }); +it("does not transfer a collection envelope's minted-member proof to its item paths", () => { + expect( + viewOf(entityRows("/v1/entities"), "get_entities_by_uuid"), + ).toMatchObject({ + shape: "recorded", + reason: "envelope-varies", + }); +}); + it("masks a minted member only on the paths whose reads minted it", () => { // The request id is minted on /v1/policies, not on the entities' own paths. expect(viewOf(entityRows("/v1/policies"), "get_entities_by_uuid")).toEqual({ @@ -68,6 +94,21 @@ it("masks a minted member only on the paths whose reads minted it", () => { }); }); +it("keeps a distinct item path's envelope unless its own repeats prove the member minted there", () => { + const first = { id: 1, name: "First" }; + const second = { id: 2, name: "Second" }; + const rows: TimedCaptureRow[] = [ + ["GET", "/api/items/1", reply(1, first)], + ["GET", "/api/items/1", reply(2, first)], + ["GET", "/api/items/1", reply(3, first)], + ["GET", "/api/items/2", reply(4, second)], + ]; + expect(viewOf(rows, "get_items_by_id")).toMatchObject({ + shape: "recorded", + reason: "envelope-varies", + }); +}); + it("never takes a changing member for a minted one unless its value is a UUID or a clock", () => { const rows: TimedCaptureRow[] = [ ...["queued", "running", "done"].map((status): TimedCaptureRow => [ diff --git a/src/domain/analysisView/environmentStateResponseMembers.ts b/src/domain/analysisView/environmentStateResponseMembers.ts index a6d1414198b..51d42ef8206 100644 --- a/src/domain/analysisView/environmentStateResponseMembers.ts +++ b/src/domain/analysisView/environmentStateResponseMembers.ts @@ -2,7 +2,6 @@ import { canonicalJson } from "../comparisonSemantics.js"; import type { JsonValue } from "../jsonValue.js"; import { compareUnicodeCodePoints as compare } from "../unicodeCodePointOrder.js"; import { - collectionPathOf, isObject, normalizedPath, replaceAt, @@ -164,20 +163,22 @@ export const perResponseMembers = (input: { return minted; }; -/** The members minted on the paths of these reads, and for item reads on their collection's path too. */ +/** Only members proved minted on every concrete path this shared view answers may be masked in its envelope. */ export const mintedFor = ( minted: MintedMembers, records: readonly Pick[], - item: boolean, ): ReadonlySet => { - const names = new Set(); - for (const record of records) - for (const path of item - ? [record.path, collectionPathOf(record, true)] - : [record.path]) - for (const name of minted.get(normalizedPath(path)) ?? []) - names.add(name); - return names; + let common: Set | undefined; + for (const path of new Set( + records.map((record) => normalizedPath(record.path)), + )) { + const names = minted.get(path); + if (names === undefined) return new Set(); + if (common === undefined) common = new Set(names); + else for (const name of common) if (!names.has(name)) common.delete(name); + if (common.size === 0) return common; + } + return common ?? new Set(); }; /** The first member a pointer names, which holds the entity rather than the envelope. */ diff --git a/src/domain/analysisView/environmentStateView.ts b/src/domain/analysisView/environmentStateView.ts index eea61bc5a46..1a7c998278f 100644 --- a/src/domain/analysisView/environmentStateView.ts +++ b/src/domain/analysisView/environmentStateView.ts @@ -104,7 +104,7 @@ const perResponseSchema = z .array(z.string()) .optional() .describe( - "Top-level members minted per response, such as a request id: a UUID or clock that differed on every repeat of the view's paths (or, for an item view, its collection's) with no write between. Checks leave them out; serving keeps the recorded value, so a served response repeats it.", + "Top-level members minted per response, such as a request id: a UUID or clock that differed on every repeat of every concrete path the view answers with no write between. Checks leave them out; serving keeps the recorded value, so a served response repeats it.", ); const entityViewFields = { tool: z.string(), diff --git a/src/domain/analysisView/environmentStateWriteCalls.ts b/src/domain/analysisView/environmentStateWriteCalls.ts index 37587cfb075..f8ad8ad29aa 100644 --- a/src/domain/analysisView/environmentStateWriteCalls.ts +++ b/src/domain/analysisView/environmentStateWriteCalls.ts @@ -1,4 +1,5 @@ import { jsonTextCodeUnits } from "../jsonSerialization.js"; +import { digestCanonicalValue } from "../canonicalDigest.js"; import type { JsonValue } from "../jsonValue.js"; import { same, type JsonObject } from "./environmentStateRules.js"; import { storedKinds } from "./environmentStateWriteApply.js"; @@ -63,16 +64,31 @@ export const steadyFields = ( ); /** A call's scalar members by name, as much of it as later rules are checked against. */ -export const scalars = (object: JsonObject): Map => +const scalars = (object: JsonObject): Map => new Map( Object.entries(object).filter( ([, value]) => value === null || typeof value !== "object", ), ); -/** The scalar values a modelled update call showed and sent, and the fields it kept, which later rules must reproduce. */ +type ObservedValue = + | { readonly kind: "scalar"; readonly value: JsonValue } + | { readonly kind: "structured"; readonly digest: string }; + +/** Keep structured equality facts without retaining another copy of each response body. */ +const observedValue = (value: JsonValue): ObservedValue => + value !== null && typeof value === "object" + ? { kind: "structured", digest: digestCanonicalValue(value) } + : { kind: "scalar", value }; + +const sameObserved = (left: ObservedValue, right: ObservedValue): boolean => + left.kind === "structured" + ? right.kind === "structured" && left.digest === right.digest + : right.kind === "scalar" && same(left.value, right.value); + +/** The equality facts a modelled update showed, scalar inputs it sent, and fields it kept, which later rules must reproduce. */ export interface UpdateCall { - readonly shown: ReadonlyMap; + readonly shown: ReadonlyMap; readonly sent: ReadonlyMap; readonly kept: readonly string[]; } @@ -86,26 +102,40 @@ export const contradictsEarlierCalls = ( rules: readonly FieldRule[], ): boolean => { const ruled = new Set(draft.plan.rules.map((rule) => rule.field)); - return rules.some( - (rule) => - (unsentChange(rule) || regenerates(rule) || rule.rule === "clock") && - !ruled.has(rule.field) && - draft.updates.some(({ shown, sent, kept }) => { - if (regenerates(rule)) return kept.includes(rule.field); - // An unruled field an earlier call showed is one it left as it was. - const value = shown.get(rule.field); - if (value === undefined) return false; - if (rule.rule === "increment") return integerOf(value) !== undefined; - if (rule.rule === "set") return !same(value, rule.value); - // Serving stamps a clock on every call, so a field an earlier call kept contradicts it. - if (rule.rule === "clock") return true; - if (rule.rule === "stamp") return !same(value, rule.value); - if (rule.rule === "derived") - return sent.has(rule.member) && !same(value, rule.value); - const from = rule.rule === "slug" ? sent.get(rule.from) : undefined; - return typeof from === "string" && slugOf(from) !== value; - }), - ); + return rules.some((rule) => { + if ( + !(unsentChange(rule) || regenerates(rule) || rule.rule === "clock") || + ruled.has(rule.field) + ) + return false; + // Compute a structured rule's digest once, rather than once per earlier call. + const expected = + rule.rule === "set" || rule.rule === "stamp" || rule.rule === "derived" + ? observedValue(rule.value) + : undefined; + return draft.updates.some(({ shown, sent, kept }) => { + if (regenerates(rule)) return kept.includes(rule.field); + // An unruled field an earlier call showed is one it left as it was. + const observation = shown.get(rule.field); + if (observation === undefined) return false; + if (rule.rule === "increment") + return ( + observation.kind === "structured" || + integerOf(observation.value) !== undefined + ); + if (rule.rule === "set") return !sameObserved(observation, expected!); + // Serving stamps a clock on every call, so a field an earlier call kept contradicts it. + if (rule.rule === "clock") return true; + if (rule.rule === "stamp") return !sameObserved(observation, expected!); + if (rule.rule === "derived") + return sent.has(rule.member) && !sameObserved(observation, expected!); + const from = rule.rule === "slug" ? sent.get(rule.from) : undefined; + return ( + typeof from === "string" && + !sameObserved(observation, observedValue(slugOf(from))) + ); + }); + }); }; /** A plan's body with the members and fixed values a later call's body adds, and the JSON types it stored those members as when the observation shows none. */ @@ -219,7 +249,12 @@ export const rememberCall = ( const unstamped = new Set(sameSecond); for (const field of unstamped) draft.unstamped.add(field); const kept = call.kept.filter((field) => !unstamped.has(field)); - const shown = scalars(call.after); + const shown = new Map( + Object.entries(call.after).map(([field, value]) => [ + field, + observedValue(value), + ]), + ); for (const field of unstamped) shown.delete(field); const facts = { shown, sent: scalars(call.sent), kept }; retain(64 + jsonTextCodeUnits([...facts.shown, ...facts.sent, kept]) * 2); diff --git a/src/domain/analysisView/environmentStateWrites.test.ts b/src/domain/analysisView/environmentStateWrites.test.ts index 8499bf74b20..dd8de02606b 100644 --- a/src/domain/analysisView/environmentStateWrites.test.ts +++ b/src/domain/analysisView/environmentStateWrites.test.ts @@ -50,6 +50,54 @@ const ISO_SECONDS = { const stateOf = (rows: readonly TimedCaptureRow[]): StateView => environmentStateViewOf(timedCaptureEvidence(rows)); +describe("structured values an earlier update kept", () => { + it.each([false, true])( + "refuses a later derived rule that changes an earlier kept value (array: %s)", + (array) => { + const content = (text: string): JsonValue => + array ? [{ text }] : { children: [{ text }] }; + const entry = (id: number, edited: boolean) => ({ + id, + title: edited ? "Edited" : "Original", + content: content(edited ? "Edited body text." : "Original body text."), + }); + const initial: TimedCaptureRow[] = [ + ["GET", "/api/posts", [entry(1, false), entry(2, false)]], + ["GET", "/api/posts/1", entry(1, false)], + ["GET", "/api/posts/2", entry(2, false)], + ]; + const edit = (id: number, changed: boolean): TimedCaptureRow[] => { + const after = { ...entry(id, changed), title: "Edited" }; + return [ + [ + "PATCH", + `/api/posts/${id}`, + after, + 200, + { title: "Edited", html: "

Edited body text.

" }, + ], + ["GET", `/api/posts/${id}`, after], + ]; + }; + const plan = (rows: TimedCaptureRow[]) => + stateOf([...initial, ...rows]).writes.find( + (write) => write.tool === "patch_posts_by_id", + ); + expect(plan([...edit(1, true), ...edit(2, true)])).toMatchObject({ + served: true, + }); + expect(plan([...edit(1, false), ...edit(2, true)])).toMatchObject({ + served: false, + reason: "unexplained-change", + }); + expect(plan([...edit(1, true), ...edit(2, false)])).toMatchObject({ + served: false, + reason: "unexplained-change", + }); + }, + ); +}); + const planOf = (state: StateView, tool: string) => { const plan = state.writes.find((candidate) => candidate.tool === tool); if (plan === undefined) throw new Error(`No write plan for ${tool}`); diff --git a/tests/boundary/mcp/environmentServeWritesMcp.test.ts b/tests/boundary/mcp/environmentServeWritesMcp.test.ts index 8ce3c750317..51d89683bb3 100644 --- a/tests/boundary/mcp/environmentServeWritesMcp.test.ts +++ b/tests/boundary/mcp/environmentServeWritesMcp.test.ts @@ -3,6 +3,7 @@ import { StreamableHTTPClientTransport, } from "@modelcontextprotocol/client"; import { describe, expect } from "vitest"; +import { Ajv2020 } from "ajv/dist/2020.js"; import { timedCaptureEvidence, @@ -17,7 +18,11 @@ import { BOOK_ROWS, book, bookClock, + FIRST_BOOK, + SECOND_BOOK, + renamedBook, } from "../../fixtures/environmentStateWrites.js"; +import { unsupportedInputLiteralSchemaError } from "../../fixtures/mcpClientSchemaConstraints.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { startListeningProcess } from "../../support/mcp/streamableHttpProcess.js"; import { processTest } from "../../support/process/processFixture.js"; @@ -28,6 +33,143 @@ const HTTP_BOUNDARY_TIMEOUT_MS = 90_000; const BOUNDARY_BOOK = book(3, "Boundary Book", bookClock(13)); describe("rea environment-serve write tools", () => { + processTest( + "discovers empty fixed values and applies omitted recorded queries through the SDK before enforcing writes", + async ({ processes }) => { + const edition = (entry: typeof FIRST_BOOK) => ({ + ...entry, + format: "HC", + }); + const renamed = edition(renamedBook(FIRST_BOOK, "Recorded edit", 3)); + const third = edition(book(3, "Recorded third", bookClock(5))); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books", [edition(FIRST_BOOK), edition(SECOND_BOOK)]], + ["GET", "/api/books/1", edition(FIRST_BOOK)], + ["GET", "/api/books/2", edition(SECOND_BOOK)], + [ + "PATCH", + "/api/books/1?notify=", + renamed, + 200, + { name: "Recorded edit" }, + ], + ["GET", "/api/books/1", renamed], + [ + "POST", + "/api/books?notify=quiet", + third, + 201, + { name: "Recorded third", format: "" }, + ], + ["GET", "/api/books/3", third], + ]; + const root = await createTestTempDirectory("rea-write-schema-defaults-"); + const files = await writeEnvironmentServeFiles( + root, + environmentStateServeFixture(timedCaptureEvidence(rows)), + ); + const started = await startListeningProcess(processes, [ + "environment-serve", + files.manifestPath, + "--evidence", + files.capturePath, + "--port", + "0", + ]); + const client = new Client({ + name: "write-schema-defaults", + version: "1", + }); + await client.connect(new StreamableHTTPClientTransport(started.url)); + try { + const { tools } = await client.listTools(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + for (const tool of tools) { + expect(ajv.validateSchema(tool.inputSchema)).toBe(true); + expect( + unsupportedInputLiteralSchemaError(tool.inputSchema, tool.name), + ).toBeUndefined(); + } + const update = tools.find((tool) => tool.name === "patch_books_by_id")!; + const create = tools.find((tool) => tool.name === "post_books")!; + expect(update.inputSchema.required).not.toContain("notify"); + expect(create.inputSchema.required).not.toContain("notify"); + expect(update.inputSchema.properties?.["notify"]).not.toHaveProperty( + "enum", + ); + expect(create.inputSchema.properties?.["notify"]).toMatchObject({ + enum: ["quiet"], + }); + const omitted = await client.callTool( + { + name: update.name, + arguments: { id: "2", body: { name: "Omitted query" } }, + }, + { toolDefinition: update }, + ); + expect(omitted.isError).toBeFalsy(); + expect(omitted.structuredContent).toMatchObject({ + body: { id: 2, name: "Omitted query" }, + state: { source: "state" }, + }); + const explicit = await client.callTool( + { + name: update.name, + arguments: { + id: "2", + notify: "", + body: { name: "Explicit empty" }, + }, + }, + { toolDefinition: update }, + ); + expect(explicit.isError).toBeFalsy(); + const refused = await client.callTool( + { + name: update.name, + arguments: { + id: "2", + notify: "yes", + body: { name: "Must not apply" }, + }, + }, + { toolDefinition: update }, + ); + expect(refused.isError).toBe(true); + const read = await client.callTool({ + name: "get_books_by_id", + arguments: { id: "2" }, + }); + expect(read.structuredContent).toMatchObject({ + body: { id: 2, name: "Explicit empty" }, + }); + const badCreate = await client.callTool( + { + name: create.name, + arguments: { body: { name: "Must not create", format: "other" } }, + }, + { toolDefinition: create }, + ); + expect(badCreate.isError).toBe(true); + const created = await client.callTool( + { + name: create.name, + arguments: { body: { name: "SDK created", format: "" } }, + }, + { toolDefinition: create }, + ); + expect(created.isError).toBeFalsy(); + expect(created.structuredContent).toMatchObject({ + body: { id: 3, name: "SDK created", format: "HC" }, + state: { source: "state" }, + }); + } finally { + await client.close(); + } + }, + HTTP_BOUNDARY_TIMEOUT_MS, + ); + processTest( "applies a served create to the state the next read answers from, until data/reset", async ({ processes }) => { From 352c0278d7fb109b412cefc9d2af749bfe38d731 Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:14:57 +0000 Subject: [PATCH 54/68] test(environment): keep SDK regressions independently scoped --- .../mcp/environmentServeWritesMcp.test.ts | 264 +++++++++--------- 1 file changed, 132 insertions(+), 132 deletions(-) diff --git a/tests/boundary/mcp/environmentServeWritesMcp.test.ts b/tests/boundary/mcp/environmentServeWritesMcp.test.ts index 51d89683bb3..a7ee2a06d0d 100644 --- a/tests/boundary/mcp/environmentServeWritesMcp.test.ts +++ b/tests/boundary/mcp/environmentServeWritesMcp.test.ts @@ -32,144 +32,144 @@ const HTTP_BOUNDARY_TIMEOUT_MS = 90_000; /** The book the first served create of "Boundary Book" makes: one second past the served clock's start. */ const BOUNDARY_BOOK = book(3, "Boundary Book", bookClock(13)); -describe("rea environment-serve write tools", () => { - processTest( - "discovers empty fixed values and applies omitted recorded queries through the SDK before enforcing writes", - async ({ processes }) => { - const edition = (entry: typeof FIRST_BOOK) => ({ - ...entry, - format: "HC", +processTest( + "discovers empty fixed values and applies omitted recorded queries through the SDK before enforcing writes", + async ({ processes }) => { + const edition = (entry: typeof FIRST_BOOK) => ({ + ...entry, + format: "HC", + }); + const renamed = edition(renamedBook(FIRST_BOOK, "Recorded edit", 3)); + const third = edition(book(3, "Recorded third", bookClock(5))); + const rows: TimedCaptureRow[] = [ + ["GET", "/api/books", [edition(FIRST_BOOK), edition(SECOND_BOOK)]], + ["GET", "/api/books/1", edition(FIRST_BOOK)], + ["GET", "/api/books/2", edition(SECOND_BOOK)], + [ + "PATCH", + "/api/books/1?notify=", + renamed, + 200, + { name: "Recorded edit" }, + ], + ["GET", "/api/books/1", renamed], + [ + "POST", + "/api/books?notify=quiet", + third, + 201, + { name: "Recorded third", format: "" }, + ], + ["GET", "/api/books/3", third], + ]; + const root = await createTestTempDirectory("rea-write-schema-defaults-"); + const files = await writeEnvironmentServeFiles( + root, + environmentStateServeFixture(timedCaptureEvidence(rows)), + ); + const started = await startListeningProcess(processes, [ + "environment-serve", + files.manifestPath, + "--evidence", + files.capturePath, + "--port", + "0", + ]); + const client = new Client({ + name: "write-schema-defaults", + version: "1", + }); + await client.connect(new StreamableHTTPClientTransport(started.url)); + try { + const { tools } = await client.listTools(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + for (const tool of tools) { + expect(ajv.validateSchema(tool.inputSchema)).toBe(true); + expect( + unsupportedInputLiteralSchemaError(tool.inputSchema, tool.name), + ).toBeUndefined(); + } + const update = tools.find((tool) => tool.name === "patch_books_by_id")!; + const create = tools.find((tool) => tool.name === "post_books")!; + expect(update.inputSchema.required).not.toContain("notify"); + expect(create.inputSchema.required).not.toContain("notify"); + expect(update.inputSchema.properties?.["notify"]).not.toHaveProperty( + "enum", + ); + expect(create.inputSchema.properties?.["notify"]).toMatchObject({ + enum: ["quiet"], }); - const renamed = edition(renamedBook(FIRST_BOOK, "Recorded edit", 3)); - const third = edition(book(3, "Recorded third", bookClock(5))); - const rows: TimedCaptureRow[] = [ - ["GET", "/api/books", [edition(FIRST_BOOK), edition(SECOND_BOOK)]], - ["GET", "/api/books/1", edition(FIRST_BOOK)], - ["GET", "/api/books/2", edition(SECOND_BOOK)], - [ - "PATCH", - "/api/books/1?notify=", - renamed, - 200, - { name: "Recorded edit" }, - ], - ["GET", "/api/books/1", renamed], - [ - "POST", - "/api/books?notify=quiet", - third, - 201, - { name: "Recorded third", format: "" }, - ], - ["GET", "/api/books/3", third], - ]; - const root = await createTestTempDirectory("rea-write-schema-defaults-"); - const files = await writeEnvironmentServeFiles( - root, - environmentStateServeFixture(timedCaptureEvidence(rows)), + const omitted = await client.callTool( + { + name: update.name, + arguments: { id: "2", body: { name: "Omitted query" } }, + }, + { toolDefinition: update }, ); - const started = await startListeningProcess(processes, [ - "environment-serve", - files.manifestPath, - "--evidence", - files.capturePath, - "--port", - "0", - ]); - const client = new Client({ - name: "write-schema-defaults", - version: "1", + expect(omitted.isError).toBeFalsy(); + expect(omitted.structuredContent).toMatchObject({ + body: { id: 2, name: "Omitted query" }, + state: { source: "state" }, }); - await client.connect(new StreamableHTTPClientTransport(started.url)); - try { - const { tools } = await client.listTools(); - const ajv = new Ajv2020({ strict: false, validateFormats: false }); - for (const tool of tools) { - expect(ajv.validateSchema(tool.inputSchema)).toBe(true); - expect( - unsupportedInputLiteralSchemaError(tool.inputSchema, tool.name), - ).toBeUndefined(); - } - const update = tools.find((tool) => tool.name === "patch_books_by_id")!; - const create = tools.find((tool) => tool.name === "post_books")!; - expect(update.inputSchema.required).not.toContain("notify"); - expect(create.inputSchema.required).not.toContain("notify"); - expect(update.inputSchema.properties?.["notify"]).not.toHaveProperty( - "enum", - ); - expect(create.inputSchema.properties?.["notify"]).toMatchObject({ - enum: ["quiet"], - }); - const omitted = await client.callTool( - { - name: update.name, - arguments: { id: "2", body: { name: "Omitted query" } }, - }, - { toolDefinition: update }, - ); - expect(omitted.isError).toBeFalsy(); - expect(omitted.structuredContent).toMatchObject({ - body: { id: 2, name: "Omitted query" }, - state: { source: "state" }, - }); - const explicit = await client.callTool( - { - name: update.name, - arguments: { - id: "2", - notify: "", - body: { name: "Explicit empty" }, - }, - }, - { toolDefinition: update }, - ); - expect(explicit.isError).toBeFalsy(); - const refused = await client.callTool( - { - name: update.name, - arguments: { - id: "2", - notify: "yes", - body: { name: "Must not apply" }, - }, - }, - { toolDefinition: update }, - ); - expect(refused.isError).toBe(true); - const read = await client.callTool({ - name: "get_books_by_id", - arguments: { id: "2" }, - }); - expect(read.structuredContent).toMatchObject({ - body: { id: 2, name: "Explicit empty" }, - }); - const badCreate = await client.callTool( - { - name: create.name, - arguments: { body: { name: "Must not create", format: "other" } }, + const explicit = await client.callTool( + { + name: update.name, + arguments: { + id: "2", + notify: "", + body: { name: "Explicit empty" }, }, - { toolDefinition: create }, - ); - expect(badCreate.isError).toBe(true); - const created = await client.callTool( - { - name: create.name, - arguments: { body: { name: "SDK created", format: "" } }, + }, + { toolDefinition: update }, + ); + expect(explicit.isError).toBeFalsy(); + const refused = await client.callTool( + { + name: update.name, + arguments: { + id: "2", + notify: "yes", + body: { name: "Must not apply" }, }, - { toolDefinition: create }, - ); - expect(created.isError).toBeFalsy(); - expect(created.structuredContent).toMatchObject({ - body: { id: 3, name: "SDK created", format: "HC" }, - state: { source: "state" }, - }); - } finally { - await client.close(); - } - }, - HTTP_BOUNDARY_TIMEOUT_MS, - ); + }, + { toolDefinition: update }, + ); + expect(refused.isError).toBe(true); + const read = await client.callTool({ + name: "get_books_by_id", + arguments: { id: "2" }, + }); + expect(read.structuredContent).toMatchObject({ + body: { id: 2, name: "Explicit empty" }, + }); + const badCreate = await client.callTool( + { + name: create.name, + arguments: { body: { name: "Must not create", format: "other" } }, + }, + { toolDefinition: create }, + ); + expect(badCreate.isError).toBe(true); + const created = await client.callTool( + { + name: create.name, + arguments: { body: { name: "SDK created", format: "" } }, + }, + { toolDefinition: create }, + ); + expect(created.isError).toBeFalsy(); + expect(created.structuredContent).toMatchObject({ + body: { id: 3, name: "SDK created", format: "HC" }, + state: { source: "state" }, + }); + } finally { + await client.close(); + } + }, + HTTP_BOUNDARY_TIMEOUT_MS, +); +describe("rea environment-serve write tools", () => { processTest( "applies a served create to the state the next read answers from, until data/reset", async ({ processes }) => { From de4035a7187b03e68198ac62b406b5020e7c92de Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:28:06 +0000 Subject: [PATCH 55/68] docs(environment): record scoped write verification and measured costs --- .../agent-environments/write-rules/spec.md | 5 +- .../write-rules/verification.md | 60 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/docs/specs/agent-environments/write-rules/spec.md b/docs/specs/agent-environments/write-rules/spec.md index 2f906b00bfa..45247fd8d0b 100644 --- a/docs/specs/agent-environments/write-rules/spec.md +++ b/docs/specs/agent-environments/write-rules/spec.md @@ -56,8 +56,9 @@ relation rows), and six need only a better recording. This change addresses the that value, so a toggle is never served. An action never takes a read another write to the entity still needs. - **Per-response members.** A top-level member whose value is a UUID or a clock is minted per response on a path when it differs on every repeat of that path's successful GET lines with no write between, and across the capture it - differed on at least two repeats and never stayed the same. Only views of that path, or item views whose collection - is that path, leave it out: item envelopes, and the write gate's item, list and document reads, compare without it. + differed on at least two repeats and never stayed the same. A shared view leaves it out only when every concrete + path it answers independently proves it minted; a collection's proof never transfers to its item paths. Item + envelopes and the write gate's item, list and document reads compare without these common proved members. The view names it in `per_response_members`, and serving keeps the recorded value. - **Nested counters.** An item total in a top-level object beside the list is a counter on the same evidence as a top-level one, rendered from the state through its pointer. A top-level member whose name starts with `/` is named by diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md index ba13ae5f282..4bf40299cb9 100644 --- a/docs/specs/agent-environments/write-rules/verification.md +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -77,3 +77,63 @@ Agent tokens were not measured; the views' results grow by 0.3%. targets came from unserved writes, so serving them answered their own recorded calls wrongly. - Completing a created entity from a later read: it served Bookstack's page create wrongly. - Soft deletes, appended relation rows, rendered markup, reverse embeds, identity aliases and resource names. + +## Linux integration and review corrections, 2026-10-24 + +The following is separate from the historical 50-capture measurements above. +Node 24.22.1, baseline `3ce311757`, reviewed implementation `352c0278d`: + +- 1,236 selected source tests passed. Typecheck, built lint/module boundaries, + format, knip, metadata, architecture guards and documentation checks passed. +- Seven review regression checks failed before correction and passed after it. + Earlier structured update values now retain canonical equality digests within + the history budget. A shared envelope masks only members independently proved + minted on every concrete path. Empty advertised literals are widened while + execution enforces their values, and pinned queries are optional so their + execution defaults can run. Numeric and string bulk id arrays stay distinct. +- Nineteen compiled SDK/schema checks passed, including real HTTP MCP discovery, + empty fixed values, omitted empty and nonempty queries, and unchanged state + after refused writes. Live Gemini API execution was not performed. +- Four public datasets were downloaded at immutable Hugging Face revisions: + NocoDB `d0f7e040`, Ghost `6d5b2d1c`, Metabase `fa2aa0fd`, and Mailpit + `416b29be`, under `earakely-scale/*Env-REA`. Capture hashes, full calls, + independent recorded JSON comparisons, runtime identities and resource + receipts were retained locally. These were recorded real applications; + the original applications were not re-recorded in this verification. + +| Capture | Eligible write tools before / after | Initial reads matching | Session reads matching | +| -------- | ----------------------------------- | ---------------------- | ---------------------- | +| NocoDB | 0 / 3 | 20 / 20 | 80 / 92 | +| Ghost | 1 / 1 | 19 / 20 | 72 / 88 | +| Metabase | 1 / 2 | 19 / 22 | 99 / 122 | +| Mailpit | 0 / 1 | 51 / 52 | 51 / 56 | + +Every previously matching read remains matching, record by record. Real CLI +listeners and the MCP SDK reproduce the shared application's outcomes. The +feature session applies six NocoDB mutations, one Ghost deletion and one +Metabase update; the baseline applies only the Ghost deletion. A `state` +answer with view `missing` is not counted as an applied write. Mailpit exchange +65 is refused because its target was introduced only by an unserved create. +Eligibility does not establish that every recorded write can run on the initial +state, and the remaining read mismatches are preserved coverage gaps. + +Three alternating fresh producer sweeps over all four captures had median +wall/CPU/cgroup peak of 5.360 s / 4.263 s / 327.3 MiB before and +4.960 s / 4.357 s / 323.1 MiB after. Ranges overlap. One complete SDK session +per app/revision, 403 versus 413 calls, took 20.905 s / 19.039 s / 508.7 MiB +before and 23.426 s / 19.396 s / 462.8 MiB after; these are single observations +with different write coverage, not a speed or memory improvement claim. + +Catalog estimates (`cl100k_base`) were 8,630 / 9,408 tokens for NocoDB, +11,355 / 11,355 for Ghost, 12,162 / 12,648 for Metabase and 2,955 / 3,138 +for Mailpit. Arguments, instructions and text replies were also counted in +retained receipts; actual model usage, prompts and client rendering were not +measured. No token saving is claimed. + +Processes were fresh, OS caches warm or uncontrolled, on a shared Linux host. +Each task used one CPU, a 3 GiB early stop / 4 GiB hard limit and zero swap. +All eight recorded-data task groups exited zero, verified payload cleanup, +and observed no OOM or limit events. Payload-exit counters were verified; +final whole-scope counters were unavailable. Downloads, builds and runtime +identity preparation are excluded from task measurements. The current +four-capture verification does not requalify the earlier 50-capture totals. From 41aff3d727221b1638c39f69837c0116c91eb34f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sat, 24 Oct 2026 03:12:40 -0700 Subject: [PATCH 56/68] fix(environment): serve bulk writes whose response lists each entity they wrote A bulk call answering an array with one element per entity its body names, in the body's order, is classified by its elements, so the existing renderer serves it from the entities each call writes. Responses listing entities out of order, with differing members or id spellings, wrapped elements or an envelope still refuse. Co-Authored-By: Claude Opus 5.5 --- .../agent-environments/write-rules/spec.md | 12 ++- .../environmentStateBulkAnswer.test.ts | 37 ++++++++ .../environmentStateWriteAddress.test.ts | 47 ++++++++++ .../analysisView/environmentStateWriteBulk.ts | 91 ++++++++++++++----- tests/fixtures/environmentStateWrites.ts | 32 +++++++ 5 files changed, 192 insertions(+), 27 deletions(-) diff --git a/docs/specs/agent-environments/write-rules/spec.md b/docs/specs/agent-environments/write-rules/spec.md index 45247fd8d0b..2e053e97127 100644 --- a/docs/specs/agent-environments/write-rules/spec.md +++ b/docs/specs/agent-environments/write-rules/spec.md @@ -46,10 +46,14 @@ relation rows), and six need only a better recording. This change addresses the Sort and direction parameters share one vocabulary and are never learned as inert. A create placed by disagreeing sorts or a random id falls back to `last`. - **Bulk writes.** A write at a type's collection whose body names entities by id, as an id array or objects carrying - the id field, deletes or updates each one, all or none; serving refuses it unless every id is held. Body ids are - taken as written, and a call naming one entity twice is refused. Each entity's generated values come from that - entity, sharing the call's clock and counters. A delete requires the members its exemplar sent besides the ids, with - their recorded values. Comparison translates a bulk body's ids with the mapping of the collection the write targets. + the id field, deletes or updates each one, all or none; serving refuses it unless every id is held. Body ids are taken + as written, and a call naming one entity twice is refused. Each entity's generated values come from that entity, + sharing the call's clock and counters. A delete requires the members its exemplar sent besides the ids, with their + recorded values. A recorded response is served when it names none of the ids and counts nothing, or is an array with + one element per entity the body names, in the body's order, each that entity with the first element's members or its + id spelled as the first spells its own; serving renders each element from the entity the call wrote, and any other + response naming the ids refuses the tool. Comparison translates a bulk body's ids with the mapping of the collection + the write targets. - **Item actions.** A write to an item path plus a literal segment that names no collection, whose calls answer nothing or the entity (never a 201, and with every field its item read always shows), updates that entity; a scalar it changes without sending is set on every call. It is served only once a call found every field it sets already at diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 4a3e00040fc..4f6ad33c065 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -5,8 +5,10 @@ import type { TimedCaptureRow } from "../../../tests/fixtures/analysisView.js"; import { BOOK_INIT_ROWS, BOOK_NOT_FOUND, + BOTH_BOOKS_RENAMED_ROWS, FIRST_BOOK, SECOND_BOOK, + bothBooksDeleted, renamedBook, type Book, } from "../../../tests/fixtures/environmentStateWrites.js"; @@ -175,6 +177,41 @@ describe("served bulk write targets", () => { }); }); +describe("served bulk writes whose recordings answered every entity", () => { + it("answers an update with each entity it wrote, in the call's order", () => { + const books = servedFrom(BOTH_BOOKS_RENAMED_ROWS); + const answer = books.answer("patch_books", { + body: { ids: [2, 1], name: "Other Book" }, + }); + expect(answer).toMatchObject({ + body: [ + { id: 2, name: "Other Book", slug: "other-book" }, + { id: 1, name: "Other Book", slug: "other-book" }, + ], + state: { source: "state", view: "update", ids: ["2", "1"] }, + }); + expect(answer.body).toEqual( + ["2", "1"].map((id) => books.answer("get_books_by_id", { id }).body), + ); + }); + + it("answers a delete with the rows or ids it names, never the recorded ones", () => { + const rows = servedFrom( + bothBooksDeleted([{ id: 1 }, { id: 2 }], [{ id: 1 }, { id: 2 }]), + ); + expect(rows.answer("delete_books", { body: [{ id: 2 }] }).body).toEqual([ + { id: 2 }, + ]); + expect(rows.store.ofType("/api/books").map((entry) => entry.id)).toEqual([ + "1", + ]); + const ids = servedFrom(bothBooksDeleted([1, 2], { ids: [1, 2] })); + expect(ids.answer("delete_books", { body: { ids: [2] } }).body).toEqual([ + 2, + ]); + }); +}); + const uuid = (n: number): string => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`; diff --git a/src/domain/analysisView/environmentStateWriteAddress.test.ts b/src/domain/analysisView/environmentStateWriteAddress.test.ts index a3d873ded30..17ba45e74af 100644 --- a/src/domain/analysisView/environmentStateWriteAddress.test.ts +++ b/src/domain/analysisView/environmentStateWriteAddress.test.ts @@ -7,8 +7,10 @@ import { import { BOOK_INIT_ROWS, BOOK_NOT_FOUND, + BOTH_BOOKS_RENAMED_ROWS, FIRST_BOOK, SECOND_BOOK, + bothBooksDeleted, environmentStateViewOf, renamedBook, type Book, @@ -122,6 +124,51 @@ describe("bulk writes at a collection", () => { }); }); +describe("bulk responses listing each written entity", () => { + it("serves a delete answering one element per row it names", () => { + expect( + planOf( + bothBooksDeleted([{ id: 1 }, { id: 2 }], [{ id: 1 }, { id: 2 }]), + "delete_books", + ), + ).toMatchObject({ + served: true, + response: { ordinal: 3, shape: "entity", pointer: "/0" }, + checked_record_ordinals: [4, 5, 6], + }); + }); + + it("serves a delete answering the ids it named", () => { + expect(planOf(bothBooksDeleted([1, 2]), "delete_books")).toMatchObject({ + served: true, + response: { ordinal: 3, shape: "identity", pointer: "/0" }, + }); + }); + + it("serves an update answering every entity it wrote", () => { + expect(planOf(BOTH_BOOKS_RENAMED_ROWS, "patch_books")).toMatchObject({ + served: true, + response: { ordinal: 3, shape: "entity", pointer: "/0" }, + }); + }); + + it("serves no bulk call whose response lists its entities in an order or form serving does not render", () => { + for (const response of [ + [{ id: 2 }, { id: 1 }], + [{ id: 1, name: "First Book" }, { id: 2 }], + [{ id: 1 }, { id: 2, deleted: true }], + [{ id: 1 }, { id: 3, parent: 2 }], + [1, "2"], + [{ book: { id: 1 } }, { book: { id: 2 } }], + { data: [{ id: 1 }, { id: 2 }] }, + ]) + expect(planOf(bothBooksDeleted(response), "delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }); +}); + describe("item actions", () => { const ARCHIVED = shelved(FIRST_BOOK, true); diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 904c0207d9e..62a9430a742 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -1,8 +1,6 @@ import type { JsonValue } from "../jsonValue.js"; import { - at, isObject, - locateItem, same, scalarText, segmentsOf, @@ -27,6 +25,7 @@ import { type WriteDraft, type WriteStep, } from "./environmentStateWriteEffects.js"; +import { responseShapeOf } from "./environmentStateWriteExplain.js"; import type { WriteBody, WriteResponse } from "./environmentStateWriteRules.js"; /** Whether any scalar in a body passes the test. */ @@ -44,15 +43,60 @@ const holds = ( return false; }; +/** + * A bulk response classified by its first element when it is an array with one element per named + * entity and that element is the first entity or its id; else as the exemplar entity's write classified it. + */ +const elementResponse = ( + response: WriteResponse, + body: JsonValue | undefined, + named: readonly NamedEntity[], + idField: string, +): WriteResponse => { + const [first] = named; + if ( + response.shape === "empty" || + first === undefined || + !Array.isArray(body) || + body.length !== named.length + ) + return response; + const element = responseShapeOf(response.ordinal, body[0], false, { + idField, + id: first.id, + }); + return element.shape !== "recorded" && element.pointer === "" + ? { ...element, pointer: "/0" } + : response; +}; + +/** Whether serving, rendering each element as the first shows its entity, renders this one as recorded. */ +const rendersLike = ( + element: JsonValue | undefined, + template: JsonValue | undefined, + shown: { + readonly shape: WriteResponse["shape"]; + readonly id: string; + readonly idField: string; + }, +): boolean => + shown.shape === "identity" + ? scalarText(element) === shown.id && typeof element === typeof template + : isObject(element) && + isObject(template) && + scalarText(element[shown.idField]) === shown.id && + same(Object.keys(element).toSorted(), Object.keys(template).toSorted()); + /** * Whether serving can answer a bulk call with this response for any ids: no body, one that names - * none of them and counts nothing it wrote, or an array with one element per named entity, each - * showing its id where the first does. + * none of them and counts nothing it wrote, or an array with one element per named entity, in + * order, each showing its entity or id as the first does. */ export const bulkResponseFits = ( response: WriteResponse, body: JsonValue | undefined, named: readonly NamedEntity[], + idField: string, ): boolean => { if (response.shape === "empty") return true; const ids = new Set(named.map(({ id }) => id)); @@ -61,16 +105,14 @@ export const bulkResponseFits = ( body, (scalar) => ids.has(scalarText(scalar) ?? "") || scalar === named.length, ); - if (response.pointer !== "/0" || !Array.isArray(body)) return false; - return ( - body.length === named.length && - named.every(({ id }, index) => { - const element = body[index]; - if (response.shape === "identity") return scalarText(element) === id; - const located = - element === undefined ? undefined : locateItem(element, id); - return located?.pointer === "" && isObject(at(element!, "")); - }) + if ( + response.pointer !== "/0" || + !Array.isArray(body) || + body.length !== named.length + ) + return false; + return named.every(({ id }, index) => + rendersLike(body[index], body[0], { shape: response.shape, id, idField }), ); }; @@ -150,15 +192,18 @@ export const applyBulk = ( draft.plan.body = deleteBody(options, identity); retainFixed(context, draft.plan.body.fixed); } - // The plan's response is the exemplar's; serving answers any ids with it only in a shape it can render for them. + // The plan's response is the exemplar's, read element by element; serving answers any ids with it only in a shape it can render for them. const { response } = draft.plan; - if ( - !wasBuilt && - response !== null && - !context.io.withBody(step.record.ordinal, (recorded) => - bulkResponseFits(response, recorded, named), - ) - ) - refuse(draft, step, "body-unusable"); + if (!wasBuilt && response !== null) { + const idField = context.idField(type); + const fitted = context.io.withBody(step.record.ordinal, (recorded) => { + const elements = elementResponse(response, recorded, named, idField); + return bulkResponseFits(elements, recorded, named, idField) + ? elements + : undefined; + }); + if (fitted === undefined) refuse(draft, step, "body-unusable"); + else draft.plan.response = fitted; + } return results; }; diff --git a/tests/fixtures/environmentStateWrites.ts b/tests/fixtures/environmentStateWrites.ts index 910f7c07d72..0838ae6d74d 100644 --- a/tests/fixtures/environmentStateWrites.ts +++ b/tests/fixtures/environmentStateWrites.ts @@ -94,6 +94,38 @@ export const BOOK_ROWS: readonly TimedCaptureRow[] = [ ["POST", "/api/exports", { queued: true }, 202, { format: "csv" }], ]; +/** A bulk delete of both books sending `body` and answering `response`, which the reads after it confirm. */ +export const bothBooksDeleted = ( + response: JsonValue, + body: JsonValue = { ids: [1, 2] }, +): TimedCaptureRow[] => [ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", response, 200, body], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], +]; + +/** Both books as a bulk rename recorded at exchange 3 left them. */ +const BOTH_RENAMED = [FIRST_BOOK, SECOND_BOOK].map((entity) => + renamedBook(entity, "Renamed Book", 3), +); + +/** A bulk rename of both books answering both, which the reads after it confirm. */ +export const BOTH_BOOKS_RENAMED_ROWS: readonly TimedCaptureRow[] = [ + ...BOOK_INIT_ROWS, + [ + "PATCH", + "/api/books", + BOTH_RENAMED, + 200, + { ids: [1, 2], name: "Renamed Book" }, + ], + ["GET", "/api/books/1", BOTH_RENAMED[0]!], + ["GET", "/api/books/2", BOTH_RENAMED[1]!], + ["GET", "/api/books", BOTH_RENAMED], +]; + /** A book whose item reads carry a `detail` member, which the application leaves out of books that have none. */ export const detailedBook = (entity: Book): Book => ({ ...entity, From a319ba1af6cae181a910909d80266236f000641f Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sat, 24 Oct 2026 03:17:44 -0700 Subject: [PATCH 57/68] docs(environment): measure the 50 captures at the scoped-envelope head Co-Authored-By: Claude Opus 5.5 --- docs/specs/agent-environments/write-rules/verification.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md index 4bf40299cb9..e71d1ea6ab1 100644 --- a/docs/specs/agent-environments/write-rules/verification.md +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -33,9 +33,14 @@ serving, reading records with REA's own capture parser, and compares the reads; | unshown writes refused | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | | catalog values, atomic bulk | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | | review fixes | 69 | 46 | 1,153 | 2,087 of 2,162 | 2,766 of 3,031 | +| scoped envelopes, bulk rows | 69 | 48 | 1,151 | 2,085 of 2,155 | 2,763 of 3,022 | All 187 write tools are counted at every step, and the served smoke applies every served write tool. +- **Scoped envelopes, bulk rows:** a shared envelope masks only members minted on every path, so Vault's identity entity + and group item views, which matched one of four and one of three recorded reads from the state, replay their + recordings, and Vault's entity update and delete lose their state target. Serving bulk responses that list each + written entity changes no capture's verdict. - **Review fixes:** literal bulk ids, per-entity bulk values, pinned bulk delete members, comparison ids per collection, echoed creation clocks, required held clocks, nested clocks checked against every call, learned sorts kept open to contrary reads and limited to the read's own entities, one query check per recorded call, guards From 3fe3b0ad185e4bdf8dfa2b5ef70fe59c60d099c1 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:18:34 +0800 Subject: [PATCH 58/68] fix(environment): classify bulk responses and release verifier transforms --- scripts/lib/owned-verifier-terminal.mjs | 9 ++-- scripts/lib/verifier-file-snapshots.mjs | 9 ++-- scripts/lib/verifier-source-loader.mjs | 17 ++++++ scripts/lib/verify-package-commands.mjs | 9 ++-- scripts/lib/windows-owned-command.mjs | 7 ++- .../environmentStateBulkAnswer.test.ts | 54 +++++++++++++++++++ .../analysisView/environmentStateWriteBulk.ts | 20 +++++++ .../packageVerifierCommandOwnership.test.ts | 40 ++++++++++++++ 8 files changed, 148 insertions(+), 17 deletions(-) create mode 100644 scripts/lib/verifier-source-loader.mjs diff --git a/scripts/lib/owned-verifier-terminal.mjs b/scripts/lib/owned-verifier-terminal.mjs index 8388cb89db6..7004c13e612 100644 --- a/scripts/lib/owned-verifier-terminal.mjs +++ b/scripts/lib/owned-verifier-terminal.mjs @@ -2,12 +2,11 @@ let implementation; /** Load the development terminal owner and canonical process helpers together. */ export async function runOwnedVerifierTerminal(options, dependencies) { - implementation ??= import("tsx/esm/api").then(({ tsImport }) => - tsImport( - new URL("./verifier-terminal-owner.mts", import.meta.url).href, - import.meta.url, - ), + implementation ??= importVerifierSource( + new URL("./verifier-terminal-owner.mts", import.meta.url).href, + import.meta.url, ); const module = await implementation; return module.runOwnedVerifierTerminal(options, dependencies); } +import { importVerifierSource } from "./verifier-source-loader.mjs"; diff --git a/scripts/lib/verifier-file-snapshots.mjs b/scripts/lib/verifier-file-snapshots.mjs index 115efdafbf8..169882df589 100644 --- a/scripts/lib/verifier-file-snapshots.mjs +++ b/scripts/lib/verifier-file-snapshots.mjs @@ -2,11 +2,9 @@ let implementation; /** Load the source file owner only when a verifier needs snapshot facts. */ const loadImplementation = () => { - implementation ??= import("tsx/esm/api").then(({ tsImport }) => - tsImport( - new URL("./verifier-file-snapshot-owner.mts", import.meta.url).href, - import.meta.url, - ), + implementation ??= importVerifierSource( + new URL("./verifier-file-snapshot-owner.mts", import.meta.url).href, + import.meta.url, ); return implementation; }; @@ -20,3 +18,4 @@ export async function assertVerifierFilesUnchanged(commands, snapshot, label) { const module = await loadImplementation(); return module.assertVerifierFilesUnchanged(commands, snapshot, label); } +import { importVerifierSource } from "./verifier-source-loader.mjs"; diff --git a/scripts/lib/verifier-source-loader.mjs b/scripts/lib/verifier-source-loader.mjs new file mode 100644 index 00000000000..5b3229faea1 --- /dev/null +++ b/scripts/lib/verifier-source-loader.mjs @@ -0,0 +1,17 @@ +import { createRequire } from "node:module"; + +const requireFromTsx = createRequire(import.meta.resolve("tsx/package.json")); +let imports = 0; + +/** Load a verifier's source graph, then release the transform service that loaded it. */ +export async function importVerifierSource(url, parent) { + const { tsImport } = await import("tsx/esm/api"); + imports++; + try { + return await tsImport(url, parent); + } finally { + // tsx's esbuild service otherwise outlives every owned command and appears + // as a surviving verifier descendant on a cold transform cache. + if (--imports === 0) requireFromTsx("esbuild").stop(); + } +} diff --git a/scripts/lib/verify-package-commands.mjs b/scripts/lib/verify-package-commands.mjs index ae8b753c49a..5c670b96ef0 100644 --- a/scripts/lib/verify-package-commands.mjs +++ b/scripts/lib/verify-package-commands.mjs @@ -2,12 +2,11 @@ let implementation; /** Load the development owner as one source graph, only when commands are needed. */ export async function createPackageVerifierCommands(options) { - implementation ??= import("tsx/esm/api").then(({ tsImport }) => - tsImport( - new URL("./package-command-owner.mts", import.meta.url).href, - import.meta.url, - ), + implementation ??= importVerifierSource( + new URL("./package-command-owner.mts", import.meta.url).href, + import.meta.url, ); const module = await implementation; return module.createPackageVerifierCommands(options); } +import { importVerifierSource } from "./verifier-source-loader.mjs"; diff --git a/scripts/lib/windows-owned-command.mjs b/scripts/lib/windows-owned-command.mjs index b52e8c586e0..6005f4148db 100644 --- a/scripts/lib/windows-owned-command.mjs +++ b/scripts/lib/windows-owned-command.mjs @@ -1,4 +1,5 @@ import { createRequire } from "node:module"; +import { importVerifierSource } from "./verifier-source-loader.mjs"; const require = createRequire(import.meta.url); const sourceWindowsProcess = new URL( @@ -8,8 +9,10 @@ const sourceWindowsProcess = new URL( /** Load the source owner without requiring a generated dist tree. */ export async function loadWindowsOwnedProcessClass() { - const { tsImport } = await import("tsx/esm/api"); - const source = await tsImport(sourceWindowsProcess, import.meta.url); + const source = await importVerifierSource( + sourceWindowsProcess, + import.meta.url, + ); return source.WindowsOwnedProcess; } diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 4a3e00040fc..2c223a063d5 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -33,6 +33,60 @@ const BULK_RENAME_ROWS: readonly TimedCaptureRow[] = [ const shelved = (entity: Book, archived: boolean) => ({ ...entity, archived }); describe("served bulk writes", () => { + it("learns a delete whose recording returned multiple entity objects", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "DELETE", + "/api/books", + [{ id: 1 }, { id: 2 }], + 200, + [{ id: 1 }, { id: 2 }], + ], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], + ]); + expect(books.answer("delete_books", { body: [{ id: 2 }] })).toMatchObject({ + status: 200, + body: [{ id: 2 }], + }); + expect(books.store.ofType("/api/books").map((book) => book.id)).toEqual([ + "1", + ]); + }); + + it("learns an update whose recording returned multiple entity objects", () => { + const renamed = [FIRST_BOOK, SECOND_BOOK].map((book) => + renamedBook(book, "Renamed Book", 3), + ); + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "PATCH", + "/api/books", + renamed, + 200, + { ids: [1, 2], name: "Renamed Book" }, + ], + ["GET", "/api/books/1", renamed[0]!], + ["GET", "/api/books/2", renamed[1]!], + ["GET", "/api/books", renamed], + ]); + expect( + books.answer("patch_books", { body: { ids: [2], name: "Changed" } }), + ).toMatchObject({ + status: 200, + body: [{ id: 2, name: "Changed", slug: "changed" }], + }); + expect(books.answer("get_books_by_id", { id: "1" }).body).toEqual( + FIRST_BOOK, + ); + expect(books.answer("get_books_by_id", { id: "2" }).body).toMatchObject({ + name: "Changed", + }); + }); + it("deletes every row a call names, answering one element per row", () => { const books = servedFrom(BULK_DELETE_ROWS); expect( diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 904c0207d9e..2690a1440fa 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -15,6 +15,7 @@ import { } from "./environmentStateWriteAddress.js"; import { itemTarget } from "./environmentStateWriteChecks.js"; import { deleteEntity } from "./environmentStateWriteDelete.js"; +import { responseShapeOf } from "./environmentStateWriteExplain.js"; import { built, fail, @@ -150,6 +151,25 @@ export const applyBulk = ( draft.plan.body = deleteBody(options, identity); retainFixed(context, draft.plan.body.fixed); } + // Bulk serving repeats the first element's shape for the addressed entities; + // classify that element rather than asking the single-entity classifier to + // find one entity in the whole multi-row response. + if (!wasBuilt && built(draft)) + draft.plan.response = context.io.withBody( + step.record.ordinal, + (recorded) => { + const array = Array.isArray(recorded); + const response = responseShapeOf( + step.record.ordinal, + array ? recorded[0] : recorded, + context.io.emptyResponse(step.record.ordinal), + { idField: context.idField(type), id: named[0]!.id }, + ); + return array && response.pointer === "" + ? { ...response, pointer: "/0" } + : response; + }, + ); // The plan's response is the exemplar's; serving answers any ids with it only in a shape it can render for them. const { response } = draft.plan; if ( diff --git a/tests/boundary/process/packageVerifierCommandOwnership.test.ts b/tests/boundary/process/packageVerifierCommandOwnership.test.ts index 533d400e86d..c4a3a64296c 100644 --- a/tests/boundary/process/packageVerifierCommandOwnership.test.ts +++ b/tests/boundary/process/packageVerifierCommandOwnership.test.ts @@ -10,6 +10,46 @@ import { systemProcessOwnershipHost } from "../../../src/process/ProcessOwnershi import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { processTest } from "../../support/process/processFixture.js"; +processTest.skipIf(process.platform === "win32")( + "releases a cold source loader before verifying command cleanup", + async ({ processes }) => { + const commandsModule = pathToFileURL( + resolve("scripts/lib/verify-package-commands.mjs"), + ).href; + const verifierModule = pathToFileURL( + resolve("scripts/lib/verifier-run.mjs"), + ).href; + const result = await processes.run( + process.execPath, + [ + "--input-type=module", + "-e", + ` + import { mkdtemp, rm } from "node:fs/promises"; + import { tmpdir } from "node:os"; + import { join } from "node:path"; + import { createPackageVerifierCommands } from ${JSON.stringify(commandsModule)}; + import { createVerifierRun, completeVerifierRun } from ${JSON.stringify(verifierModule)}; + const run = createVerifierRun(); + const path = await mkdtemp(join(tmpdir(), "rea-cold-verifier-")); + const commands = await createPackageVerifierCommands({ workspace: { path, close: () => rm(path, { recursive: true, force: true }) } }); + try { + await commands.exec(process.execPath, ["-e", "process.stdout.write('ok')"]); + } finally { + await commands.close(); + } + console.log(JSON.stringify(await completeVerifierRun(run))); + `, + ], + { env: { ...process.env, TSX_DISABLE_CACHE: "1" }, timeoutMs: 20_000 }, + ); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + process_lineage: { status: "verified", descendants: [] }, + }); + }, +); + const descendantSource = ` import { appendFileSync, existsSync, writeFileSync } from "node:fs"; const record = (entry) => appendFileSync(process.env.OWNER_EVENTS, JSON.stringify(entry) + "\\n"); From f4bc513dddfced1b00755b6e5ce6b54d173d156e Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:27:11 +0000 Subject: [PATCH 59/68] fix(environment): classify and verify complete bulk responses --- .../environmentStateBulkAnswer.test.ts | 153 ++++++++++++++++++ .../environment/environmentStateBulkAnswer.ts | 32 +--- .../EnvironmentStateAccumulator.ts | 7 +- .../EnvironmentStateExtraction.ts | 4 +- .../WebNetworkProjectionAccumulator.test.ts | 37 +++++ .../WebNetworkProjectionAccumulator.ts | 8 + .../environmentStateWriteApply.ts | 24 +++ .../analysisView/environmentStateWriteBulk.ts | 139 ++++++++++++---- .../environmentStateWriteChecks.ts | 24 ++- .../environmentStateWriteDelete.ts | 14 +- .../environmentStateWriteEffects.ts | 57 ++++--- 11 files changed, 408 insertions(+), 91 deletions(-) create mode 100644 src/domain/analysisView/WebNetworkProjectionAccumulator.test.ts diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 4a3e00040fc..81006d668df 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -29,6 +29,137 @@ const BULK_RENAME_ROWS: readonly TimedCaptureRow[] = [ ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], ]; +describe("bulk response records and rendering", () => { + const deletedReads: TimedCaptureRow[] = [ + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], + ]; + + it.each([1, 2])( + "serves a multi-entity delete recording for %s caller targets", + (count) => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "DELETE", + "/api/books", + [{ id: 1 }, { id: 2 }], + 200, + [{ id: 1 }, { id: 2 }], + ], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: true, + response: { shape: "entity", pointer: "/0" }, + }); + const body = count === 1 ? [{ id: 2 }] : [{ id: 1 }, { id: 2 }]; + expect(books.answer("delete_books", { body })).toMatchObject({ + body, + state: { view: "delete" }, + }); + expect( + books.store.ofType("/api/books").map((entity) => entity.id), + ).toEqual(count === 1 ? ["1"] : []); + }, + ); + + it("serves multiple returned identities with their recorded scalar kind", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [1, 2], 200, { ids: [1, 2] }], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: true, + response: { shape: "identity", pointer: "/0" }, + }); + expect(books.answer("delete_books", { body: { ids: [2] } }).body).toEqual([ + 2, + ]); + }); + + it("updates each returned entity without copying the first entity's fields to the others", () => { + const renamed = [ + renamedBook(FIRST_BOOK, "Recorded", 3), + renamedBook(SECOND_BOOK, "Recorded", 3), + ]; + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["PATCH", "/api/books", renamed, 200, { ids: [1, 2], name: "Recorded" }], + ["GET", "/api/books/1", renamed[0]!], + ["GET", "/api/books/2", renamed[1]!], + ["GET", "/api/books", renamed], + ]); + expect(books.state.writes.get("patch_books")).toMatchObject({ + served: true, + }); + expect( + books.answer("patch_books", { body: { ids: [1, 2], name: "Changed" } }) + .body, + ).toMatchObject([ + { id: 1, name: "Changed", created_at: FIRST_BOOK.created_at }, + { id: 2, name: "Changed", created_at: SECOND_BOOK.created_at }, + ]); + expect(books.answer("get_books_by_id", { id: "2" }).body).toMatchObject({ + id: 2, + name: "Changed", + }); + }); + + it("serves a recorded acknowledgement that names and counts no targets", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", { ok: true }, 200, { ids: [1, 2] }], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: true, + }); + expect(books.answer("delete_books", { body: { ids: [2] } }).body).toEqual({ + ok: true, + }); + expect(books.store.ofType("/api/books").map((entity) => entity.id)).toEqual( + ["1"], + ); + }); + + it.each([ + { response: [{ id: 2 }, { id: 1 }] }, + { response: [{ id: 1 }, { id: 2, name: "Second" }] }, + ])( + "withholds a response the shared first-element renderer cannot reproduce: %j", + ({ response }) => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", response, 200, [{ id: 1 }, { id: 2 }]], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }, + ); + + it("withholds a tool whose later response changes its modelled shape", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + ["DELETE", "/api/books", [{ id: 2 }], 200, [{ id: 2 }]], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", [FIRST_BOOK]], + ["DELETE", "/api/books", { ok: true }, 200, [{ id: 1 }]], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }); +}); + /** A book with an `archived` flag, which an item action sets. */ const shelved = (entity: Book, archived: boolean) => ({ ...entity, archived }); @@ -111,6 +242,28 @@ describe("served bulk write queries and capacity", () => { }); describe("served bulk write targets", () => { + it.each(["part/one", "%31", "A\uD800"])( + "resolves a literal JSON body identity without turning it into a URL: %j", + (id) => { + const unusual = { ...SECOND_BOOK, id }; + const books = servedFrom([ + ["GET", "/api/books", [FIRST_BOOK, unusual]], + ["GET", "/api/books/1", FIRST_BOOK], + ["DELETE", "/api/books", "", 204, { ids: [id] }], + ["GET", "/api/books", [FIRST_BOOK]], + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: true, + }); + expect( + books.answer("delete_books", { body: { ids: [id] } }), + ).toMatchObject({ state: { ids: [id] } }); + expect( + books.store.ofType("/api/books").map((entity) => entity.id), + ).toEqual(["1"]); + }, + ); + it.each(["number", "string"] as const)( "refuses ids whose JSON kind differs from the recorded %s array, without changing state", (kind) => { diff --git a/src/application/environment/environmentStateBulkAnswer.ts b/src/application/environment/environmentStateBulkAnswer.ts index 22b1d600b97..33b01e9bf4c 100644 --- a/src/application/environment/environmentStateBulkAnswer.ts +++ b/src/application/environment/environmentStateBulkAnswer.ts @@ -6,12 +6,9 @@ import { bodyProblem, updatedEntity, updatedFields, - writtenResponse, + writtenBulkResponse, } from "../../domain/analysisView/environmentStateWriteApply.js"; -import type { - FieldRule, - WriteResponse, -} from "../../domain/analysisView/environmentStateWriteRules.js"; +import type { FieldRule } from "../../domain/analysisView/environmentStateWriteRules.js"; import type { JsonObject, StateEntity, @@ -50,29 +47,6 @@ interface BulkTarget { readonly body: JsonObject | undefined; } -/** A bulk answer from the recorded one: one element per written entity, rendered as the first recorded element shows its entity. */ -const bulkResponse = ( - response: WriteResponse, - recorded: JsonValue | undefined, - written: readonly { readonly fields: JsonObject; readonly id: string }[], -): Result => { - if (response.shape === "empty") return ok(undefined); - const [template] = Array.isArray(recorded) ? recorded : []; - if (template === undefined) - return err("The recorded response shows no element to render."); - const elements: JsonValue[] = []; - for (const entity of written) { - const element = writtenResponse( - { ...response, pointer: "" }, - template, - entity, - ); - if (!element.ok) return element; - elements.push(element.value ?? null); - } - return ok(elements); -}; - /** The held entities a bulk call names, with the members each gets, or a refusal for an entity the state does not hold. */ const namedTargets = ( serving: StateServing, @@ -193,7 +167,7 @@ export const answerBulk = ( const answer = writeAnswer( serving, request, - (recorded) => bulkResponse(plan.response!, recorded, written.value), + (recorded) => writtenBulkResponse(plan.response!, recorded, written.value), { source: "state", view: update ? "update" : "delete", diff --git a/src/domain/analysisView/EnvironmentStateAccumulator.ts b/src/domain/analysisView/EnvironmentStateAccumulator.ts index bf389cc7b42..dd3e66fe64a 100644 --- a/src/domain/analysisView/EnvironmentStateAccumulator.ts +++ b/src/domain/analysisView/EnvironmentStateAccumulator.ts @@ -137,6 +137,7 @@ const UNKNOWNS: StateView["unknowns"] = [ /** The manifest's grouping plus the record facts and bodies the init state is extracted from. */ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator { readonly #entries = new Map(); + readonly #bodyReleases: (() => void)[] = []; constructor( maximumBytes = WEB_NETWORK_CAPTURE_LIMITS.outputBytes, @@ -282,6 +283,7 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator /** Parse one retained response body as state JSON, charging its decoding and tree as temporary work. */ #body(ordinal: number): ParsedBody | null { + this.#bodyReleases.push(this.temporaryCheckpoint()); const entry = this.#entries.get(ordinal); // A body that is not JSON-like is refused before its decoding is charged. if (entry === undefined || !isJsonLike(mediaTypeEssence(entry.contentType))) @@ -314,6 +316,7 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator const { mimeType, text } = request.data.request.postData; if (Buffer.byteLength(text, "utf8") > STATE_BODY_LIMIT_BYTES) return { kind: "unusable" }; + const release = this.temporaryCheckpoint(); if (!this.temporary(RECORD_SCRATCH_BYTES + textBytes(text.length) * 4)) return null; try { @@ -322,7 +325,7 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator ? { kind: "unusable" } : { kind: "json", value }; } finally { - this.releaseTemporary(); + release(); } } @@ -375,7 +378,7 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator emptyResponse: (ordinal) => this.#emptyResponse(ordinal), retain: (bytes) => this.retain(bytes), checkpoint: () => this.retainedCheckpoint(), - release: () => this.releaseTemporary(), + release: () => this.#bodyReleases.pop()?.(), }, }).run(); if (state === null) return this.overBudget(); diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index 1bcd3d46d7e..cefba34d76a 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -305,9 +305,9 @@ export class EnvironmentStateExtraction { /** Parse one body and hand it to `use` before its temporary work is dropped; unusable bodies arrive undefined. */ #withBody(ordinal: number, use: (body: JsonValue | undefined) => T): T { - const parsed = this.#budget.body(ordinal); - if (parsed === null) throw new StateBudgetExhausted(); try { + const parsed = this.#budget.body(ordinal); + if (parsed === null) throw new StateBudgetExhausted(); return use(parsed.kind === "json" ? parsed.value : undefined); } finally { this.#budget.release(); diff --git a/src/domain/analysisView/WebNetworkProjectionAccumulator.test.ts b/src/domain/analysisView/WebNetworkProjectionAccumulator.test.ts new file mode 100644 index 00000000000..72831f9e5df --- /dev/null +++ b/src/domain/analysisView/WebNetworkProjectionAccumulator.test.ts @@ -0,0 +1,37 @@ +import { expect, it } from "vitest"; +import { WebNetworkProjectionAccumulator } from "./WebNetworkProjectionAccumulator.js"; + +class Budget extends WebNetworkProjectionAccumulator { + constructor() { + super(100, "Network projection test"); + } + + reserve(bytes: number): boolean { + return this.temporary(bytes); + } + + keep(bytes: number): boolean { + return this.retain(bytes); + } + + lease(): () => void { + return this.temporaryCheckpoint(); + } +} + +it("keeps an enclosing body's scratch and learned facts charged when a nested lease ends", () => { + const budget = new Budget(); + const outer = budget.lease(); + expect(budget.reserve(60)).toBe(true); + const inner = budget.lease(); + expect(budget.reserve(20)).toBe(true); + expect(budget.keep(10)).toBe(true); + expect(budget.reserve(11)).toBe(false); + inner(); + // The outer body and ten retained bytes still occupy seventy bytes. + expect(budget.reserve(31)).toBe(false); + outer(); + // Ending the body lease releases scratch, while its learned facts survive. + expect(budget.reserve(91)).toBe(false); + expect(budget.reserve(90)).toBe(true); +}); diff --git a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts index 084eec71a38..81e64b70667 100644 --- a/src/domain/analysisView/WebNetworkProjectionAccumulator.ts +++ b/src/domain/analysisView/WebNetworkProjectionAccumulator.ts @@ -48,6 +48,14 @@ export abstract class WebNetworkProjectionAccumulator { return true; } + /** Restore the enclosing synchronous parse's scratch after a nested body lease. */ + protected temporaryCheckpoint(): () => void { + const held = this.#temporaryBytes; + return () => { + this.#temporaryBytes = held; + }; + } + /** Mark the retained bytes; the returned call releases what was retained since, once none of it is held. */ protected retainedCheckpoint(): () => void { const mark = this.#retainedBytes; diff --git a/src/domain/analysisView/environmentStateWriteApply.ts b/src/domain/analysisView/environmentStateWriteApply.ts index 4bb91c08bfc..2a7edf01564 100644 --- a/src/domain/analysisView/environmentStateWriteApply.ts +++ b/src/domain/analysisView/environmentStateWriteApply.ts @@ -446,6 +446,30 @@ export const writtenResponse = ( ); }; +/** The shared bulk renderer: fixed acknowledgements, or one first-template element per written entity. */ +export const writtenBulkResponse = ( + response: WriteResponse, + recorded: JsonValue | undefined, + written: readonly { readonly fields: JsonObject; readonly id: string }[], +): Applied => { + if (response.shape === "empty") return ok(undefined); + if (response.shape === "recorded") return ok(recorded); + const [template] = Array.isArray(recorded) ? recorded : []; + if (template === undefined) + return err("The recorded response shows no element to render."); + const elements: JsonValue[] = []; + for (const entity of written) { + const element = writtenResponse( + { ...response, pointer: "" }, + template, + entity, + ); + if (!element.ok) return element; + elements.push(element.value ?? null); + } + return ok(elements); +}; + /** An entity with updated fields: view-specific values of the fields that changed give way to the new values, and it cites no records. */ export const updatedEntity = ( entity: StateEntity, diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 904c0207d9e..23356ea27d4 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -13,7 +13,9 @@ import { namedEntities, type NamedEntity, } from "./environmentStateWriteAddress.js"; -import { itemTarget } from "./environmentStateWriteChecks.js"; +import { bodyTarget } from "./environmentStateWriteChecks.js"; +import { responseShapeOf } from "./environmentStateWriteExplain.js"; +import { writtenBulkResponse } from "./environmentStateWriteApply.js"; import { deleteEntity } from "./environmentStateWriteDelete.js"; import { built, @@ -57,9 +59,13 @@ export const bulkResponseFits = ( if (response.shape === "empty") return true; const ids = new Set(named.map(({ id }) => id)); if (response.shape === "recorded") - return !holds( - body, - (scalar) => ids.has(scalarText(scalar) ?? "") || scalar === named.length, + return ( + body !== undefined && + !holds( + body, + (scalar) => + ids.has(scalarText(scalar) ?? "") || scalar === named.length, + ) ); if (response.pointer !== "/0" || !Array.isArray(body)) return false; return ( @@ -74,6 +80,36 @@ export const bulkResponseFits = ( ); }; +/** Classify a complete bulk response by corresponding element, without changing its source pointers. */ +const bulkResponseShape = ( + ordinal: number, + body: JsonValue | undefined, + empty: boolean, + named: readonly NamedEntity[], + idField: string, +): WriteResponse => { + if (!empty && Array.isArray(body) && body.length === named.length) { + let shape: "entity" | "identity" | undefined; + for (const [index, target] of named.entries()) { + const element = responseShapeOf(ordinal, body[index], false, { + idField, + id: target.id, + }); + if ( + element.pointer !== "" || + (element.shape !== "entity" && element.shape !== "identity") || + (shape !== undefined && shape !== element.shape) + ) { + shape = undefined; + break; + } + shape = element.shape; + } + if (shape !== undefined) return { ordinal, shape, pointer: "/0" }; + } + return responseShapeOf(ordinal, body, empty, { idField, id: named[0]!.id }); +}; + /** The members a bulk delete sends besides the ids and each element's `identity` member, alike for every entity it names; undefined when they differ. */ const deleteOptions = ( named: readonly NamedEntity[], @@ -136,29 +172,78 @@ export const applyBulk = ( fail(draft, step, "body-unusable"); return [UNKNOWN]; } - const collection = `/${bulkCollectionOf(type, segmentsOf(step.record.path), (text) => text).join("/")}`; - const wasBuilt = built(draft); - const results = named.map(({ id, body: members }) => { - const target = itemTarget(context.state, type, { - path: `${collection}/${encodeURIComponent(id)}`, + const collection = bulkCollectionOf( + type, + segmentsOf(step.record.path), + (text) => text, + ); + const targets = named.map(({ id }) => + bodyTarget(context.state, type, collection, id), + ); + // Keep the response's one parsed lease while its rows are interpreted. Nested reads retain its scratch charge. + return context.io.withBody(step.record.ordinal, (recorded) => { + const empty = context.io.emptyResponse(step.record.ordinal); + const response = bulkResponseShape( + step.record.ordinal, + recorded, + empty, + named, + context.idField(type), + ); + const before = targets.map((target) => + context.state.entity(type, target.collection, target.id), + ); + const wasBuilt = built(draft); + const results = named.map(({ id, body: members }, index) => { + const target = targets[index]!; + const object = + response.shape === "entity" && + response.pointer === "/0" && + Array.isArray(recorded) + ? recorded[index] + : undefined; + const call = { + ...step, + response, + responseObservation: isObject(object) + ? { ordinal: step.record.ordinal, pointer: `/${index}`, id, object } + : null, + }; + return deleted + ? deleteEntity(context, draft, call, target) + : updateEntity(context, draft, call, { ...target, body: members }); }); - return deleted - ? deleteEntity(context, draft, step, target) - : updateEntity(context, draft, step, { ...target, body: members }); + if (!wasBuilt && built(draft) && options !== undefined) { + draft.plan.body = deleteBody(options, identity); + retainFixed(context, draft.plan.body.fixed); + } + const planned = draft.plan.response; + if (planned !== null) { + const written = targets.flatMap((target, index) => { + const entity = deleted + ? before[index] + : context.state.entity(type, target.collection, target.id); + return entity === undefined ? [] : [entity]; + }); + const fits = + planned.shape === response.shape && + planned.pointer === response.pointer && + bulkResponseFits(planned, recorded, named); + const render = (exemplar: JsonValue | undefined) => + writtenBulkResponse(planned, exemplar, written); + const rendered = + !fits || written.length !== named.length + ? undefined + : planned.ordinal === step.record.ordinal + ? render(recorded) + : context.io.withBody(planned.ordinal, render); + if ( + !fits || + (rendered !== undefined && + (!rendered.ok || !same(rendered.value, empty ? undefined : recorded))) + ) + refuse(draft, step, "body-unusable"); + } + return results; }); - if (!wasBuilt && built(draft) && options !== undefined) { - draft.plan.body = deleteBody(options, identity); - retainFixed(context, draft.plan.body.fixed); - } - // The plan's response is the exemplar's; serving answers any ids with it only in a shape it can render for them. - const { response } = draft.plan; - if ( - !wasBuilt && - response !== null && - !context.io.withBody(step.record.ordinal, (recorded) => - bulkResponseFits(response, recorded, named), - ) - ) - refuse(draft, step, "body-unusable"); - return results; }; diff --git a/src/domain/analysisView/environmentStateWriteChecks.ts b/src/domain/analysisView/environmentStateWriteChecks.ts index 75cd5441a82..4fd3a01aa86 100644 --- a/src/domain/analysisView/environmentStateWriteChecks.ts +++ b/src/domain/analysisView/environmentStateWriteChecks.ts @@ -285,11 +285,31 @@ export const itemTarget = ( ): { readonly collection: string; readonly id: string } => { const read = segmentsOf(record.path); const raw = read.pop() ?? ""; - const path = { + return targetFrom(state, type, { read, ids: [...new Set([decodedSegment(raw), raw])], written: `/${read.join("/")}`, - }; + }); +}; + +/** A JSON body's identity is literal, independent of URL escaping or path-segment syntax. */ +export const bodyTarget = ( + state: SimulatedState, + type: string, + read: readonly string[], + id: string, +): { readonly collection: string; readonly id: string } => + targetFrom(state, type, { read, ids: [id], written: `/${read.join("/")}` }); + +const targetFrom = ( + state: SimulatedState, + type: string, + path: { + readonly read: readonly string[]; + readonly ids: readonly string[]; + readonly written: string; + }, +): { readonly collection: string; readonly id: string } => { const removed = state.removedTargets(type); return ( matchingTarget( diff --git a/src/domain/analysisView/environmentStateWriteDelete.ts b/src/domain/analysisView/environmentStateWriteDelete.ts index 495d6882e53..88138d7e6ee 100644 --- a/src/domain/analysisView/environmentStateWriteDelete.ts +++ b/src/domain/analysisView/environmentStateWriteDelete.ts @@ -47,12 +47,14 @@ export const deleteEntity = ( if (!built(draft) && !step.observeOnly) Object.assign(draft.plan, { exemplar_ordinal: ordinal, - response: context.io.withBody(ordinal, (body) => - responseShapeOf(ordinal, body, context.io.emptyResponse(ordinal), { - idField: context.idField(type), - id, - }), - ), + response: + step.response ?? + context.io.withBody(ordinal, (body) => + responseShapeOf(ordinal, body, context.io.emptyResponse(ordinal), { + idField: context.idField(type), + id, + }), + ), }); context.state.remove(entity); const targets = [ diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index ca712ad2dfb..4121dfffa2f 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -58,6 +58,7 @@ import { type StateWritePlan, type WriteCall, type WriteReason, + type WriteResponse, } from "./environmentStateWriteRules.js"; type Mutable = { -readonly [K in keyof T]: T[K] }; @@ -147,6 +148,10 @@ export interface WriteStep { readonly observeOnly: boolean; /** Whether the call sent the query serving pins, its exemplar's, as every call before the plan is built does. */ readonly pinned: boolean; + /** A bulk response already classified by its owning body lease. */ + readonly response?: WriteResponse; + /** Its entity at the exact source pointer, or null when that response shows none. */ + readonly responseObservation?: Observed | null; } /** @@ -280,23 +285,27 @@ const updatedObservation = ( }, ): UpdateObservation | undefined => { const { required, borrow } = observing; - const own = context.io.withBody( - step.record.ordinal, - (body): Observed | undefined => { - const located = - body === undefined ? undefined : locateItem(body, entity.id); - const object = - located === undefined ? undefined : at(body!, located.pointer); - return located?.keys.includes(entity.idField) === true && isObject(object) - ? { - ordinal: step.record.ordinal, - pointer: located.pointer, - object, - id: entity.id, - } - : undefined; - }, - ); + const own = + step.responseObservation === undefined + ? context.io.withBody( + step.record.ordinal, + (body): Observed | undefined => { + const located = + body === undefined ? undefined : locateItem(body, entity.id); + const object = + located === undefined ? undefined : at(body!, located.pointer); + return located?.keys.includes(entity.idField) === true && + isObject(object) + ? { + ordinal: step.record.ordinal, + pointer: located.pointer, + object, + id: entity.id, + } + : undefined; + }, + ) + : (step.responseObservation ?? undefined); if ( own !== undefined && required.every((field) => Object.hasOwn(own.object, field)) @@ -396,12 +405,14 @@ const buildUpdate = ( ordinal: evidence.after.ordinal, pointer: evidence.after.pointer, }, - response: context.io.withBody(ordinal, (response) => - responseShapeOf(ordinal, response, context.io.emptyResponse(ordinal), { - idField: evidence.idField, - id: evidence.after.id, - }), - ), + response: + step.response ?? + context.io.withBody(ordinal, (response) => + responseShapeOf(ordinal, response, context.io.emptyResponse(ordinal), { + idField: evidence.idField, + id: evidence.after.id, + }), + ), body: { ...evidence.explained.body, ...envelopeMember(context.io.requestBody(ordinal)), From 390541e595e416478ca8121f75f8a4bf72d8774c Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:30:06 +0800 Subject: [PATCH 60/68] fix(javascript): retain capture context along covered mutation paths --- .../javascriptSemanticMemberMutations.ts | 77 +++++++++++++------ 1 file changed, 55 insertions(+), 22 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticMemberMutations.ts b/src/domain/javascript/javascriptSemanticMemberMutations.ts index e0a2b3ffad2..9030e8dd319 100644 --- a/src/domain/javascript/javascriptSemanticMemberMutations.ts +++ b/src/domain/javascript/javascriptSemanticMemberMutations.ts @@ -886,6 +886,52 @@ export function* collectSemanticMemberMutationsSteps( ]); const lifetime = lifetimeKey(captureKey, current.path); if (current.bindings.has(lifetime)) continue; + // Use the same binding/effect coverage for cycle escapes and ordinary + // propagation, so a previously escaped prefix stops recursive widening. + const coverageFor = ( + coverageEffect: ValueEffect, + coveragePath: PropertyPath, + ): SemanticPropertyPathCoverage => { + const pathState = `${JSON.stringify(binding.bindingId)}\u0001${ + coverageEffect + }\u0001${ + // Short writes stop at owned literal slots, whereas longer writes + // reach shared children. Only equal-depth writes cover one another. + coverageEffect === "write" ? coveragePath.length : -1 + }\u0001${mutation?.start ?? -1}\u0001${mutation?.end ?? -1}\u0001${ + current.originAt?.start ?? -1 + }\u0001${current.originAt?.end ?? -1}\u0001${ + current.ownerInitializer?.start ?? -1 + }\u0001${current.ownerInitializer?.end ?? -1}\u0001${widenedGetterResult}\u0001${current.definiteReceiver}\u0001${assignedSources?.[0]?.target?.start ?? -1}\u0001${current.memberReadAt?.start ?? -1}\u0001${current.memberReadAt?.end ?? -1}`; + let covering = coveringPaths.get(pathState); + if (covering === undefined) { + covering = new SemanticPropertyPathCoverage(); + coveringPaths.set(pathState, covering); + } + return covering; + }; + // Capture at depth d qualifies only the d-th selected member. Encoding + // it beside that member lets an escaped prefix cover deeper selections + // without conflating earlier and later captured references. + const coveredPath = (path: PropertyPath): PropertyPath => { + const captures = new Map( + (current.capturedSelections ?? []).map((capture) => [ + capture.depth, + capture, + ]), + ); + return path.flatMap((key, index) => { + const capture = captures.get(index + 1); + return [ + JSON.stringify( + capture === undefined + ? null + : [capture.at.start, capture.at.end, capture.ownEnumerable], + ), + key, + ]; + }); + }; // A self alias such as `node = node[key]` revisits its capture with the // same prefix added on every cycle, so exact paths never repeat. When // that prefix can never be pruned, escaping it once covers every longer @@ -907,6 +953,12 @@ export function* collectSemanticMemberMutationsSteps( repeatedPrefix !== undefined && observablePaths.repeatsUnpruned(binding.bindingId, repeatedPrefix) ) { + if ( + coverageFor("escape", repeatedPrefix).covers( + coveredPath(repeatedPrefix), + ) + ) + continue; markValue( current.node, repeatedPrefix, @@ -917,7 +969,7 @@ export function* collectSemanticMemberMutationsSteps( current.ownerInitializer, widenedGetterResult, undefined, - undefined, + current.definiteReceiver, current, ); continue; @@ -1014,27 +1066,8 @@ export function* collectSemanticMemberMutationsSteps( current, ); } - // Keep an antichain of exact paths. Widening distinct member keys would - // also invalidate unrelated siblings that never reach this effect. - // This map is local to the file scan. Escaping the binding id keeps a - // field separator injective while avoiding a fresh JSON array encode. - const pathState = `${JSON.stringify(binding.bindingId)}\u0001${ - effect - }\u0001${ - // Short writes stop at owned literal slots, whereas longer writes - // reach shared children. Only equal-depth writes cover one another. - effect === "write" ? path.length : -1 - }\u0001${mutation?.start ?? -1}\u0001${mutation?.end ?? -1}\u0001${ - current.originAt?.start ?? -1 - }\u0001${current.originAt?.end ?? -1}\u0001${ - current.ownerInitializer?.start ?? -1 - }\u0001${current.ownerInitializer?.end ?? -1}\u0001${widenedGetterResult}\u0001${current.definiteReceiver}\u0001${assignedSources?.[0]?.target?.start ?? -1}\u0001${captureSelectionIdentity}`; - let covering = coveringPaths.get(pathState); - if (covering === undefined) { - covering = new SemanticPropertyPathCoverage(); - coveringPaths.set(pathState, covering); - } - if (!covering.retain(path)) continue; + const covering = coverageFor(effect, path); + if (!covering.retain(coveredPath(path))) continue; // A recorded write invalidates the binding to a non-primitive value, so // only its first write can target a primitive. Re-evaluating it would // replay every earlier write and make repeated writes superlinear. From 5ae634f46ee123ad51571ff10e9ce4e40c06dbac Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:40:50 +0000 Subject: [PATCH 61/68] test(environment): verify bulk responses through the real MCP SDK --- .../write-rules/verification.md | 25 +++++ .../environmentStateBulkAnswer.test.ts | 42 +++++++++ .../mcp/environmentServeWritesMcp.test.ts | 93 +++++++++++++++++++ 3 files changed, 160 insertions(+) diff --git a/docs/specs/agent-environments/write-rules/verification.md b/docs/specs/agent-environments/write-rules/verification.md index e71d1ea6ab1..7446822a311 100644 --- a/docs/specs/agent-environments/write-rules/verification.md +++ b/docs/specs/agent-environments/write-rules/verification.md @@ -142,3 +142,28 @@ and observed no OOM or limit events. Payload-exit counters were verified; final whole-scope counters were unavailable. Downloads, builds and runtime identity preparation are excluded from task measurements. The current four-capture verification does not requalify the earlier 50-capture totals. + +### Bulk-response follow-up qualification + +The follow-up at `f4bc513dd` classifies every returned bulk element and checks +all recorded calls with the shared serving renderer. Nested parsed-body leases +retain their enclosing scratch charge. Literal JSON IDs never pass through a +synthetic URL. The author's subsequent bulk regressions and measurement note +were retained when integrating `a319ba1af`; their historical census does not +measure this follow-up. + +A fresh four-capture producer sweep and real CLI/MCP replay retained every +previously matching read (109/114 initial, 302/358 session). NocoDB, Ghost and +Metabase plans and complete SDK calls equal `9942863b2`. Mailpit's text/plain +`ok` deletion acknowledgement is not parsed by the state JSON owner, so its +contents remain unknown and its write tool is now withheld as `body-unusable`. +The prior session already refused this deletion for a missing target; no +previously applied mutation was lost. Plain-text acknowledgement support remains +unverified rather than treating unknown contents as empty. The three other +captures retain the same eight applied mutations. + +This qualification-only sweep took 5.857 s wall / 5.413 s CPU / 329.9 MiB peak; +the complete SDK replay took 23.264 s / 22.298 s / 474.0 MiB. These single +observations are not pooled with the earlier performance cohort. Payload cleanup +and payload-exit resource counters were verified, with no OOM/limit events; +final whole-scope counters and actual model token usage remain unmeasured. diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 99473163671..78185f90bc7 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -110,6 +110,48 @@ describe("bulk response records and rendering", () => { }); }); + it("withholds delete responses whose values differ from the held entities", () => { + const held = [FIRST_BOOK, SECOND_BOOK].map((entry) => ({ + ...entry, + deleted: false, + })); + const books = servedFrom([ + ["GET", "/api/books", held], + ["GET", "/api/books/1", held[0]!], + ["GET", "/api/books/2", held[1]!], + [ + "DELETE", + "/api/books", + held.map((entry) => ({ ...entry, deleted: true })), + 200, + { ids: [1, 2] }, + ], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }); + + it("withholds an unparsed acknowledgement instead of treating unknown contents as absent", () => { + const books = servedFrom([ + ...BOOK_INIT_ROWS, + [ + "DELETE", + "/api/books", + "unparsed acknowledgement", + 200, + { ids: [1, 2] }, + ], + ...deletedReads, + ]); + expect(books.state.writes.get("delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }); + it("serves a recorded acknowledgement that names and counts no targets", () => { const books = servedFrom([ ...BOOK_INIT_ROWS, diff --git a/tests/boundary/mcp/environmentServeWritesMcp.test.ts b/tests/boundary/mcp/environmentServeWritesMcp.test.ts index a7ee2a06d0d..ef053d67d2d 100644 --- a/tests/boundary/mcp/environmentServeWritesMcp.test.ts +++ b/tests/boundary/mcp/environmentServeWritesMcp.test.ts @@ -15,6 +15,7 @@ import { } from "../../fixtures/environmentServe.js"; import { BOOK_NOT_FOUND, + BOTH_BOOKS_RENAMED_ROWS, BOOK_ROWS, book, bookClock, @@ -316,3 +317,95 @@ describe("rea environment-serve write tools", () => { HTTP_BOUNDARY_TIMEOUT_MS, ); }); + +processTest( + "serves multi-row bulk responses and refuses absent targets atomically through the SDK", + async ({ processes }) => { + const rows: TimedCaptureRow[] = [ + ...BOTH_BOOKS_RENAMED_ROWS, + ["DELETE", "/api/books", [{ id: 1 }, { id: 2 }], 200, { ids: [1, 2] }], + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], + ]; + const root = await createTestTempDirectory("rea-write-bulk-sdk-"); + const files = await writeEnvironmentServeFiles( + root, + environmentStateServeFixture(timedCaptureEvidence(rows)), + ); + const started = await startListeningProcess(processes, [ + "environment-serve", + files.manifestPath, + "--evidence", + files.capturePath, + "--port", + "0", + ]); + const client = new Client({ + name: "bulk-response-verification", + version: "1", + }); + await client.connect(new StreamableHTTPClientTransport(started.url)); + try { + const { tools } = await client.listTools(); + const update = tools.find((tool) => tool.name === "patch_books")!; + const deletion = tools.find((tool) => tool.name === "delete_books")!; + const changed = await client.callTool( + { + name: update.name, + arguments: { body: { ids: [2], name: "Subset" } }, + }, + { toolDefinition: update }, + ); + expect(changed.isError).toBeFalsy(); + expect(changed.structuredContent).toMatchObject({ + body: [{ id: 2, name: "Subset", created_at: SECOND_BOOK.created_at }], + }); + const refused = await client.callTool( + { + name: update.name, + arguments: { body: { ids: [2, 999], name: "Refused" } }, + }, + { toolDefinition: update }, + ); + expect(refused.isError).toBe(true); + const unchanged = await client.callTool({ + name: "get_books_by_id", + arguments: { id: "2" }, + }); + expect(unchanged.structuredContent).toMatchObject({ + body: { id: 2, name: "Subset" }, + }); + const both = await client.callTool( + { + name: update.name, + arguments: { body: { ids: [1, 2], name: "Both" } }, + }, + { toolDefinition: update }, + ); + expect(both.isError).toBeFalsy(); + expect(both.structuredContent).toMatchObject({ + body: [ + { id: 1, name: "Both", created_at: FIRST_BOOK.created_at }, + { id: 2, name: "Both", created_at: SECOND_BOOK.created_at }, + ], + }); + const deleted = await client.callTool( + { + name: deletion.name, + arguments: { body: { ids: [2, 1] } }, + }, + { toolDefinition: deletion }, + ); + expect(deleted.isError).toBeFalsy(); + expect(deleted.structuredContent).toMatchObject({ + body: [{ id: 2 }, { id: 1 }], + }); + const empty = await client.callTool({ name: "get_books", arguments: {} }); + expect(empty.structuredContent).toMatchObject({ body: [] }); + } finally { + await client.close(); + } + }, + HTTP_BOUNDARY_TIMEOUT_MS, +); From 585d71cd617730ef5c9d2762ac732a69f0534587 Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:41:46 +0000 Subject: [PATCH 62/68] test(environment): separate bulk response proof regressions --- .../environmentStateBulkAnswer.test.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/application/environment/environmentStateBulkAnswer.test.ts b/src/application/environment/environmentStateBulkAnswer.test.ts index 78185f90bc7..dfe379a8b26 100644 --- a/src/application/environment/environmentStateBulkAnswer.test.ts +++ b/src/application/environment/environmentStateBulkAnswer.test.ts @@ -31,13 +31,13 @@ const BULK_RENAME_ROWS: readonly TimedCaptureRow[] = [ ["GET", "/api/books", [RENAMED_AT_3, SECOND_BOOK]], ]; -describe("bulk response records and rendering", () => { - const deletedReads: TimedCaptureRow[] = [ - ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], - ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], - ["GET", "/api/books", []], - ]; +const DELETED_READS: TimedCaptureRow[] = [ + ["GET", "/api/books/1", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/2", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], +]; +describe("bulk response records and rendering", () => { it.each([1, 2])( "serves a multi-entity delete recording for %s caller targets", (count) => { @@ -50,7 +50,7 @@ describe("bulk response records and rendering", () => { 200, [{ id: 1 }, { id: 2 }], ], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: true, @@ -71,7 +71,7 @@ describe("bulk response records and rendering", () => { const books = servedFrom([ ...BOOK_INIT_ROWS, ["DELETE", "/api/books", [1, 2], 200, { ids: [1, 2] }], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: true, @@ -109,7 +109,9 @@ describe("bulk response records and rendering", () => { name: "Changed", }); }); +}); +describe("bulk response proof and refusals", () => { it("withholds delete responses whose values differ from the held entities", () => { const held = [FIRST_BOOK, SECOND_BOOK].map((entry) => ({ ...entry, @@ -126,7 +128,7 @@ describe("bulk response records and rendering", () => { 200, { ids: [1, 2] }, ], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: false, @@ -144,7 +146,7 @@ describe("bulk response records and rendering", () => { 200, { ids: [1, 2] }, ], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: false, @@ -156,7 +158,7 @@ describe("bulk response records and rendering", () => { const books = servedFrom([ ...BOOK_INIT_ROWS, ["DELETE", "/api/books", { ok: true }, 200, { ids: [1, 2] }], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: true, @@ -178,7 +180,7 @@ describe("bulk response records and rendering", () => { const books = servedFrom([ ...BOOK_INIT_ROWS, ["DELETE", "/api/books", response, 200, [{ id: 1 }, { id: 2 }]], - ...deletedReads, + ...DELETED_READS, ]); expect(books.state.writes.get("delete_books")).toMatchObject({ served: false, From 3e1b023ea0c4c86361b4c5ba92eb085e047b2c4c Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:11:31 +0000 Subject: [PATCH 63/68] fix(environment): preserve request absence and generated value relationships --- .../environmentStateWriteReview.test.ts | 176 ++++++++++++++++++ .../EnvironmentStateAccumulator.ts | 33 +++- .../EnvironmentStateExtraction.ts | 12 +- .../analysisView/environmentStateRules.ts | 8 +- .../environmentStateWriteAddress.ts | 3 +- .../analysisView/environmentStateWriteBulk.ts | 7 +- .../environmentStateWriteCreate.ts | 59 +++++- .../environmentStateWriteDocument.ts | 7 +- .../environmentStateWriteEffects.ts | 65 ++++--- .../environmentStateWriteExplain.ts | 2 +- .../environmentStateWriteStamps.test.ts | 29 +++ .../environmentStateWriteStamps.ts | 80 ++++---- .../scenarioCaptureRecords.test.ts | 49 ++++- .../analysisView/scenarioCaptureRecords.ts | 1 + tests/fixtures/analysisView.ts | 2 + 15 files changed, 437 insertions(+), 96 deletions(-) create mode 100644 src/application/environment/environmentStateWriteReview.test.ts diff --git a/src/application/environment/environmentStateWriteReview.test.ts b/src/application/environment/environmentStateWriteReview.test.ts new file mode 100644 index 00000000000..d98c25b31c3 --- /dev/null +++ b/src/application/environment/environmentStateWriteReview.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, it } from "vitest"; + +import { + timedCaptureEvidence, + analysisViewCaptureEvidence, + type TimedCaptureRow, +} from "../../../tests/fixtures/analysisView.js"; +import { + environmentStateServeFixture, + environmentStateServeInputs, +} from "../../../tests/fixtures/environmentServe.js"; +import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js"; +import { + BOOK_NOT_FOUND, + FIRST_BOOK, + SECOND_BOOK, + book, + bookClock, +} from "../../../tests/fixtures/environmentStateWrites.js"; + +import { webNetworkCaptureSchema } from "../../domain/webNetworkCapture.js"; + +const archived = (value: boolean) => ({ ...FIRST_BOOK, archived: value }); + +describe("bodyless action evidence", () => { + it.each([ + { + name: "form", + postData: { + mimeType: "application/x-www-form-urlencoded", + text: "toggle=false", + }, + }, + { + name: "malformed JSON", + postData: { mimeType: "application/json", text: "{" }, + }, + { + name: "oversized JSON", + postData: { + mimeType: "application/json", + text: JSON.stringify({ note: "x".repeat(256 * 1024) }), + }, + }, + { name: "unretained body", postData: undefined }, + ])( + "does not use unreadable or unretained request bodies as a repeated bodyless action: $name", + ({ postData }) => { + const capture = timedCaptureEvidence([ + ["GET", "/api/books", [archived(false), SECOND_BOOK]], + ["GET", "/api/books/1", archived(false)], + ["GET", "/api/books/2", SECOND_BOOK], + ["POST", "/api/books/1/archive", archived(true)], + ["GET", "/api/books/1", archived(true)], + ["POST", "/api/books/1/archive", archived(true)], + ["GET", "/api/books/1", archived(true)], + ]); + const result = capture.normalized_result as { + records: { + reported: { request: { postData?: unknown; bodySize?: number } }; + }[]; + }; + const request = result.records[5]!.reported.request; + request.bodySize = 12; + if (postData === undefined) delete request.postData; + else request.postData = postData; + const { state } = environmentStateServeInputs( + environmentStateServeFixture( + analysisViewCaptureEvidence( + webNetworkCaptureSchema.parse(capture.normalized_result), + ), + ), + ); + expect(state.writes.get("post_books_archive_by_id")).toMatchObject({ + served: false, + }); + }, + ); +}); + +it("keeps a stored array-of-object field as an ordinary update body", () => { + const original = { ...FIRST_BOOK, tags: [{ id: 7, name: "Old" }] }; + const second = { ...SECOND_BOOK, tags: [{ id: 8, name: "Other" }] }; + const changed = { ...original, tags: [{ id: 9, name: "Recorded" }] }; + const books = servedFrom([ + ["GET", "/api/books", [original, second]], + ["GET", "/api/books/1", original], + ["GET", "/api/books/2", second], + ["PATCH", "/api/books/1", changed, 200, { tags: changed.tags }], + ["GET", "/api/books/1", changed], + ["GET", "/api/books", [changed, second]], + ]); + expect(books.state.writes.get("patch_books_by_id")).toMatchObject({ + served: true, + }); + expect(books.state.writes.get("patch_books_by_id")?.body).not.toHaveProperty( + "envelope", + ); + const tags = [ + { id: 10, name: "Caller" }, + { id: 11, name: "Second tag" }, + ]; + expect( + books.answer("patch_books_by_id", { id: "2", body: { tags } }).body, + ).toMatchObject({ id: 2, tags }); +}); + +const TOKENS = ["Abcdef0123456789A", "Abcdef0123456789B", "Abcdef0123456789C"]; + +it("withholds a generated create token copied into a nested constant", () => { + const first = { ...FIRST_BOOK, version: TOKENS[0]! }; + const second = { ...SECOND_BOOK, version: TOKENS[1]! }; + const third = { + ...book(3, "Created", bookClock(3)), + version: TOKENS[2]!, + metadata: { versions: [{ value: TOKENS[2]! }] }, + }; + const books = servedFrom([ + ["GET", "/api/books", [first, second]], + ["GET", "/api/books/1", first], + ["GET", "/api/books/2", second], + ["POST", "/api/books", third, 201, { name: "Created" }], + ["GET", "/api/books/3", third], + ]); + expect(books.state.writes.get("post_books")).toMatchObject({ + served: false, + reason: "unexplained-change", + }); +}); + +it("withholds an update token already present in a nested unchanged field", () => { + const first = { + ...FIRST_BOOK, + version: TOKENS[0]!, + metadata: { versions: [TOKENS[1]!] }, + }; + const second = { ...SECOND_BOOK, version: TOKENS[2]!, metadata: {} }; + const changed = { ...first, version: TOKENS[1]! }; + const books = servedFrom([ + ["GET", "/api/books", [first, second]], + ["GET", "/api/books/1", first], + ["GET", "/api/books/2", second], + ["PATCH", "/api/books/1", changed, 200, {}], + ["GET", "/api/books/1", changed], + ["GET", "/api/books", [changed, second]], + ]); + expect(books.state.writes.get("patch_books_by_id")).toMatchObject({ + served: false, + }); +}); + +it.each(["2", "02"])( + "withholds a bulk acknowledgement with string count %s", + (deleted) => { + const rows: TimedCaptureRow[] = [ + [ + "GET", + "/api/books", + [ + { ...FIRST_BOOK, id: 10 }, + { ...SECOND_BOOK, id: 20 }, + ], + ], + ["GET", "/api/books/10", { ...FIRST_BOOK, id: 10 }], + ["GET", "/api/books/20", { ...SECOND_BOOK, id: 20 }], + ["DELETE", "/api/books", { deleted }, 200, { ids: [10, 20] }], + ["GET", "/api/books/10", BOOK_NOT_FOUND, 404], + ["GET", "/api/books/20", BOOK_NOT_FOUND, 404], + ["GET", "/api/books", []], + ]; + expect(servedFrom(rows).state.writes.get("delete_books")).toMatchObject({ + served: false, + reason: "body-unusable", + }); + }, +); diff --git a/src/domain/analysisView/EnvironmentStateAccumulator.ts b/src/domain/analysisView/EnvironmentStateAccumulator.ts index dd3e66fe64a..94149b3c828 100644 --- a/src/domain/analysisView/EnvironmentStateAccumulator.ts +++ b/src/domain/analysisView/EnvironmentStateAccumulator.ts @@ -26,6 +26,7 @@ import { isStateWrite, STATE_BODY_LIMIT_BYTES, type ParsedBody, + type ParsedRequestBody, type StateRecordFacts, type StateTimeline, } from "./environmentStateRules.js"; @@ -102,10 +103,17 @@ const contentSchema = z.object({ }); const requestSchema = z.object({ request: z.object({ - postData: z.object({ mimeType: z.string(), text: z.string() }), + postData: z.unknown().optional(), + bodySize: z.number().optional(), }), }); +const requestContentSchema = z.object({ + mimeType: z.string(), + text: z.string(), + params: z.array(z.unknown()).optional(), +}); + interface RecordEntry { readonly facts: StateRecordFacts; /** Null for a write whose URL was redacted: its target is unknown, so it bounds every type. */ @@ -304,22 +312,27 @@ export class EnvironmentStateAccumulator extends EnvironmentManifestAccumulator } /** Parse one recorded request body as state JSON, as response bodies are admitted. */ - #requestBody(ordinal: number): ParsedBody | null { + #requestBody(ordinal: number): ParsedRequestBody | null { const entry = this.#entries.get(ordinal); const request = requestSchema.safeParse(entry?.record.reported); + if (entry === undefined || !request.success) return { kind: "unusable" }; + const { postData, bodySize } = request.data.request; + if (postData === undefined) + return { kind: bodySize === 0 ? "absent" : "unusable" }; + const parsed = requestContentSchema.safeParse(postData); + if (!parsed.success) return { kind: "unusable" }; + const { mimeType, text, params } = parsed.data; + if (bodySize === 0 && text === "" && (params?.length ?? 0) === 0) + return { kind: "absent" }; if ( - entry === undefined || - !request.success || - !isJsonLike(mediaTypeEssence(request.data.request.postData.mimeType)) + !isJsonLike(mediaTypeEssence(mimeType)) || + Buffer.byteLength(text, "utf8") > STATE_BODY_LIMIT_BYTES ) return { kind: "unusable" }; - const { mimeType, text } = request.data.request.postData; - if (Buffer.byteLength(text, "utf8") > STATE_BODY_LIMIT_BYTES) - return { kind: "unusable" }; const release = this.temporaryCheckpoint(); - if (!this.temporary(RECORD_SCRATCH_BYTES + textBytes(text.length) * 4)) - return null; try { + if (!this.temporary(RECORD_SCRATCH_BYTES + textBytes(text.length) * 4)) + return null; const value = stateBodyJson(mimeType, { bodyText: text }); return value === undefined ? { kind: "unusable" } diff --git a/src/domain/analysisView/EnvironmentStateExtraction.ts b/src/domain/analysisView/EnvironmentStateExtraction.ts index cefba34d76a..5e71b7f6b7b 100644 --- a/src/domain/analysisView/EnvironmentStateExtraction.ts +++ b/src/domain/analysisView/EnvironmentStateExtraction.ts @@ -30,6 +30,8 @@ import { type JsonObject, type RecordedViewReason, type StateBudget, + type ParsedRequestBody, + requestJson, type StateDocument, type StateEntity, type StateRecordFacts, @@ -284,7 +286,7 @@ export class EnvironmentStateExtraction { volatileOf: (type) => this.#volatileOf(type), io: { withBody: (ordinal, use) => this.#withBody(ordinal, use), - requestBody: (ordinal) => this.#requestBody(ordinal), + requestBody: (ordinal) => this.#parsedRequestBody(ordinal), emptyResponse: (ordinal) => this.#budget.emptyResponse(ordinal), retain: (bytes) => this.#retain(bytes), queryOf: (ordinal) => this.#byOrdinal.get(ordinal)?.query, @@ -293,10 +295,14 @@ export class EnvironmentStateExtraction { }; } - #requestBody(ordinal: number): JsonValue | undefined { + #parsedRequestBody(ordinal: number): ParsedRequestBody { const parsed = this.#budget.requestBody(ordinal); if (parsed === null) throw new StateBudgetExhausted(); - return parsed.kind === "json" ? parsed.value : undefined; + return parsed; + } + + #requestBody(ordinal: number): JsonValue | undefined { + return requestJson(this.#parsedRequestBody(ordinal)); } #retain(bytes: number): void { diff --git a/src/domain/analysisView/environmentStateRules.ts b/src/domain/analysisView/environmentStateRules.ts index d4ea4a0ff88..1db63d35e47 100644 --- a/src/domain/analysisView/environmentStateRules.ts +++ b/src/domain/analysisView/environmentStateRules.ts @@ -38,11 +38,17 @@ export type ParsedBody = | { readonly kind: "json"; readonly value: JsonValue } | { readonly kind: "unusable" }; +/** A request distinguishes confirmed absence from content the state cannot interpret. */ +export type ParsedRequestBody = ParsedBody | { readonly kind: "absent" }; + +export const requestJson = (body: ParsedRequestBody): JsonValue | undefined => + body.kind === "json" ? body.value : undefined; + /** Budgeted access the accumulator lends extraction; null and false mean the budget is exhausted. */ export interface StateBudget { readonly body: (ordinal: number) => ParsedBody | null; /** A record's request body, admitted as response bodies are. */ - readonly requestBody: (ordinal: number) => ParsedBody | null; + readonly requestBody: (ordinal: number) => ParsedRequestBody | null; /** Whether a record's response had no body. */ readonly emptyResponse: (ordinal: number) => boolean; readonly retain: (bytes: number) => boolean; diff --git a/src/domain/analysisView/environmentStateWriteAddress.ts b/src/domain/analysisView/environmentStateWriteAddress.ts index 232f3d8c6c6..ae5a98cff5e 100644 --- a/src/domain/analysisView/environmentStateWriteAddress.ts +++ b/src/domain/analysisView/environmentStateWriteAddress.ts @@ -1,6 +1,7 @@ import type { JsonValue } from "../jsonValue.js"; import { at, + requestJson, isObject, isParam, locateItem, @@ -199,7 +200,7 @@ export const bulkWrite = ( const idField = target === undefined ? undefined : facts.idField(target); if (target === undefined || idField === undefined) return undefined; const forms = facts.calls.map((record) => - addressOf(facts.requestBody(record.ordinal), idField), + addressOf(requestJson(facts.requestBody(record.ordinal)), idField), ); const [first] = forms; if ( diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 23356ea27d4..6873cd61b48 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -1,6 +1,7 @@ import type { JsonValue } from "../jsonValue.js"; import { at, + requestJson, isObject, locateItem, same, @@ -29,6 +30,7 @@ import { type WriteDraft, type WriteStep, } from "./environmentStateWriteEffects.js"; +import { integerOf } from "./environmentStateWriteValues.js"; import type { WriteBody, WriteResponse } from "./environmentStateWriteRules.js"; /** Whether any scalar in a body passes the test. */ @@ -64,7 +66,8 @@ export const bulkResponseFits = ( !holds( body, (scalar) => - ids.has(scalarText(scalar) ?? "") || scalar === named.length, + ids.has(scalarText(scalar) ?? "") || + integerOf(scalar) === named.length, ) ); if (response.pointer !== "/0" || !Array.isArray(body)) return false; @@ -149,7 +152,7 @@ export const applyBulk = ( ): EffectResult[] => { const type = draft.plan.target!; const { address } = draft.plan; - const body = context.io.requestBody(step.record.ordinal); + const body = requestJson(context.io.requestBody(step.record.ordinal)); const named = address === undefined || address.by === "action" ? undefined diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index f2793eb2c8f..2a29cdf1f4b 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -10,13 +10,14 @@ import { segmentsOf, selectedCollection, type JsonObject, + requestJson, type StateEntity, type SuppliedSegment, } from "./environmentStateRules.js"; import { createdFields } from "./environmentStateWriteApply.js"; import { - envelopeMember, - envelopeOf, + unenveloped, + createdToken, isOpaqueToken, restampedFields, sameQuery, @@ -38,7 +39,7 @@ import { fail, itemReads, refuse, - requestObject, + requestBodyPlan, retainFixed, searchFrom, startOf, @@ -145,10 +146,11 @@ const buildCreate = ( readonly call: WriteCall & { readonly body: JsonObject }; readonly collection: string; }, -): void => { +): boolean => { const type = draft.plan.target!; const idField = context.idField(type); const members = fieldsOf(context.state.members(type, evidence.collection)); + const held = fieldsOf(context.state.ofType(type)); // Only calls serving would take, successful and with the exemplar's query, show that a member may vary. const calls = new Set(step.tool.record_ordinals); const taken = context.records.filter( @@ -157,21 +159,38 @@ const buildCreate = ( succeeded(record) && sameQuery(record.query, step.record.query), ); + const request = requestBodyPlan( + context, + step, + draft, + evidence.observed.object, + )!; const explained = explainCreate({ entity: evidence.observed.object, call: evidence.call, idField, startMs: startOf(context, step), collection: members, - type: fieldsOf(context.state.ofType(type)), + type: held, named: (id) => context.state.named(id), varied: variedMembers( taken.map(({ ordinal }) => { - const body = context.io.requestBody(ordinal); - return envelopeOf(body)?.object ?? body; + const body = requestJson(context.io.requestBody(ordinal)); + return unenveloped(body, request.envelope); }), ), }); + const explainedFields = new Set(explained.rules.map((rule) => rule.field)); + if ( + Object.keys(evidence.observed.object).some( + (field) => + !explainedFields.has(field) && + createdToken(field, evidence.observed.object, held) === "linked", + ) + ) { + refuse(draft, step, "unexplained-change"); + return false; + } const clocks = explained.rules.flatMap((rule) => rule.rule === "clock" ? [rule.field] : [], ); @@ -214,7 +233,7 @@ const buildCreate = ( ), body: { ...explained.body, - ...envelopeMember(context.io.requestBody(step.record.ordinal)), + ...(request.envelope === undefined ? {} : { envelope: request.envelope }), }, rules: explained.rules, collection: @@ -222,6 +241,7 @@ const buildCreate = ( insert: draft.candidates[0]!, }); draft.observed = evidence.observed.object; + return true; }; type SequenceRule = Extract; @@ -424,13 +444,13 @@ export const applyCreate = ( (draft.linked !== undefined && !fromLinkedSource(context, draft, step))) ) return UNKNOWN; - const body = requestObject(context, step, draft); const observed = createdObservation(context, step, { type, collection, idField, linked: draft.linked !== undefined, }); + const body = requestBodyPlan(context, step, draft, observed?.object)?.object; if (observed === undefined) { fail(draft, step, body === undefined ? "body-unusable" : "no-observation"); return UNKNOWN; @@ -462,7 +482,26 @@ export const applyCreate = ( const call = { ...callOf(step, body), body }; // The exemplar defines the plan's sequences; each later call must follow them. const later = built(draft); - if (!later) buildCreate(context, draft, step, { observed, call, collection }); + if ( + later && + draft.plan.rules.some( + (rule) => + rule.rule === "unique" && + createdToken( + rule.field, + observed.object, + fieldsOf(context.state.ofType(type)), + ) === "linked", + ) + ) { + refuse(draft, step, "unexplained-change"); + return recorded(); + } + if ( + !later && + !buildCreate(context, draft, step, { observed, call, collection }) + ) + return recorded(); // Rules learn from the recorded path; serving fills path fields from the collection it selects. const created = { ...call, diff --git a/src/domain/analysisView/environmentStateWriteDocument.ts b/src/domain/analysisView/environmentStateWriteDocument.ts index 9ff753070bb..06e6d90b1cb 100644 --- a/src/domain/analysisView/environmentStateWriteDocument.ts +++ b/src/domain/analysisView/environmentStateWriteDocument.ts @@ -3,6 +3,7 @@ import type { JsonValue } from "../jsonValue.js"; import { at as valueAt, isObject, + requestJson, pathSegmentMatches, pointerTo, same, @@ -19,7 +20,6 @@ import { callOf, fail, refuse, - requestObject, UNKNOWN, type EffectContext, type EffectResult, @@ -105,7 +105,10 @@ export const applyDocument = ( if (initial !== undefined && !namesDocument(step.record.path, initial.path)) return UNKNOWN; const value = context.state.document(tool); - const body = requestObject(context, step); + const parsed = step.pinned + ? requestJson(context.io.requestBody(step.record.ordinal)) + : undefined; + const body = isObject(parsed) ? parsed : undefined; const pointer = value === undefined || body === undefined ? undefined diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 4121dfffa2f..e4eb60f1e2c 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -6,6 +6,8 @@ import { locateItem, at, type JsonObject, + type ParsedRequestBody, + requestJson, type StateDocument, type StateEntity, type StateRecordFacts, @@ -41,11 +43,7 @@ import { viewFields, type Observed, } from "./environmentStateWriteObserve.js"; -import { - envelopeMember, - plannedObject, - restampedFields, -} from "./environmentStateWriteStamps.js"; +import { plannedBody, restampedFields } from "./environmentStateWriteStamps.js"; import { readClock } from "./environmentStateWriteValues.js"; import { actionItemPath, @@ -96,7 +94,7 @@ export interface WriteIo { ordinal: number, use: (body: JsonValue | undefined) => T, ) => T; - readonly requestBody: (ordinal: number) => JsonValue | undefined; + readonly requestBody: (ordinal: number) => ParsedRequestBody; readonly emptyResponse: (ordinal: number) => boolean; readonly retain: (bytes: number) => void; readonly queryOf: (ordinal: number) => string | null | undefined; @@ -213,16 +211,18 @@ export const refuse = ( if (!step.observeOnly) draft.plan.reason = reason; }; -/** A call's body object, none for a call serving refuses by its query; an entity write's is unwrapped from a one-element envelope, and once its plan is built only one sent with the exemplar's wrapping counts, as serving takes it. */ -export const requestObject = ( +/** Shared request interpretation: the object's own fields take precedence over a one-element envelope. */ +export const requestBodyPlan = ( context: EffectContext, step: WriteStep, - draft?: WriteDraft, -): JsonObject | undefined => + draft: WriteDraft, + observed?: JsonObject, +) => step.pinned - ? plannedObject( - context.io.requestBody(step.record.ordinal), - draft && { built: built(draft), envelope: draft.plan.body?.envelope }, + ? plannedBody( + requestJson(context.io.requestBody(step.record.ordinal)), + { built: built(draft), envelope: draft.plan.body?.envelope }, + (member) => observed !== undefined && Object.hasOwn(observed, member), ) : undefined; @@ -399,6 +399,12 @@ const buildUpdate = ( } retainFixed(context, evidence.explained.body.fixed); const { ordinal } = step.record; + const envelope = requestBodyPlan( + context, + step, + draft, + evidence.after.object, + )?.envelope; Object.assign(draft.plan, { exemplar_ordinal: ordinal, observation: { @@ -415,7 +421,7 @@ const buildUpdate = ( ), body: { ...evidence.explained.body, - ...envelopeMember(context.io.requestBody(ordinal)), + ...(envelope === undefined ? {} : { envelope }), }, rules: evidence.explained.rules, }); @@ -437,14 +443,7 @@ export const applyUpdate = ( const named = itemTarget(context.state, draft.plan.target!, { path: action ? actionItemPath(step.record.path) : step.record.path, }); - // An item action names its change in its path, so it may send no body. - const body = - action && - step.pinned && - context.io.requestBody(step.record.ordinal) === undefined - ? {} - : requestObject(context, step, draft); - return updateEntity(context, draft, step, { ...named, body }); + return updateEntity(context, draft, step, { ...named, request: true }); }; /** Apply a recorded update to the held entity a call names, with the members it wrote to that entity. */ @@ -455,15 +454,20 @@ export const updateEntity = ( named: { readonly collection: string; readonly id: string; - readonly body: JsonObject | undefined; - }, + } & ({ readonly request: true } | { readonly body: JsonObject | undefined }), ): EffectResult => { const type = draft.plan.target!; const idField = context.idField(type); - const { collection, id, body } = named; + const { collection, id } = named; const needs = observationNeeds( draft.plan, - { ...named, type, idField }, + { + collection, + id, + type, + idField, + body: "body" in named ? named.body : undefined, + }, context.pending, ); const entity = context.state.entity(type, collection, id); @@ -481,6 +485,15 @@ export const updateEntity = ( return UNKNOWN; } const { targets, target, recorded } = outcomes(context, entity, after.object); + // Only confirmed absence makes a bodyless action; malformed or unretained content stays unknown. + const body = + "body" in named + ? named.body + : draft.plan.address?.by === "action" && + step.pinned && + context.io.requestBody(step.record.ordinal).kind === "absent" + ? {} + : requestBodyPlan(context, step, draft, after.object)?.object; if (step.observeOnly || body === undefined) { fail(draft, step, "body-unusable"); return recorded(); diff --git a/src/domain/analysisView/environmentStateWriteExplain.ts b/src/domain/analysisView/environmentStateWriteExplain.ts index b50b821839e..3c96ddb3907 100644 --- a/src/domain/analysisView/environmentStateWriteExplain.ts +++ b/src/domain/analysisView/environmentStateWriteExplain.ts @@ -182,7 +182,7 @@ const generatedRule = ( evidence.type.every((member) => member[field] !== value) ) return { field, rule: "unique" }; - if (createdToken(field, evidence.entity, evidence.type)) + if (createdToken(field, evidence.entity, evidence.type) === "independent") return { field, rule: "unique" }; return createdNestedClock(field, value, evidence); }; diff --git a/src/domain/analysisView/environmentStateWriteStamps.test.ts b/src/domain/analysisView/environmentStateWriteStamps.test.ts index 271136c39ad..ff3698895d0 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.test.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.test.ts @@ -612,3 +612,32 @@ describe("call shapes", () => { expect(pinnedQuery(null, new Map([["page", "2"]])).ok).toBe(false); }); }); + +it("does not explain nested opaque-token references as independent generation", () => { + const before = "Abcdef0123456789A"; + const after = "Abcdef0123456789B"; + const other = "Abcdef0123456789C"; + for (const metadata of [ + { version: after }, + [after], + { text: `token:${after}` }, + ]) { + const creation = explainCreate( + created( + { id: "42", title: "New", version: after, metadata }, + { title: "New" }, + [{ id: "41", version: before }], + ), + ); + expect(ruleFor(creation.rules, "version")?.rule).not.toBe("unique"); + const update = explainUpdate( + updated( + { id: "42", version: before, metadata }, + { id: "42", version: after, metadata }, + {}, + [{ id: "41", version: other }], + ), + ); + expect(update.unexplained).toContain("version"); + } +}); diff --git a/src/domain/analysisView/environmentStateWriteStamps.ts b/src/domain/analysisView/environmentStateWriteStamps.ts index b153d975ba1..adb10c35c8f 100644 --- a/src/domain/analysisView/environmentStateWriteStamps.ts +++ b/src/domain/analysisView/environmentStateWriteStamps.ts @@ -14,7 +14,11 @@ import { import { singleQueryValues } from "../recordedTransportUrl.js"; import { queryKey, queryValuesKey } from "./environmentStateCheckedLines.js"; import type { FieldRule } from "./environmentStateWriteRules.js"; -import { isUuid, readClock } from "./environmentStateWriteValues.js"; +import { + containsDelimited, + isUuid, + readClock, +} from "./environmentStateWriteValues.js"; /** A clock value counts as written by the request when it lies this close to the request's start. */ const CLOCK_WINDOW_MS = 10 * 60_000; @@ -83,14 +87,6 @@ export const envelopeOf = ( : undefined; }; -/** The envelope a body wraps its object in, as a write plan's body records it. */ -export const envelopeMember = ( - body: JsonValue | undefined, -): { readonly envelope?: string } => { - const wrapped = envelopeOf(body); - return wrapped === undefined ? {} : { envelope: wrapped.member }; -}; - /** A call's body as a plan with this envelope takes it: the object it wraps, the body itself without one, or undefined when the envelope is missing. */ export const unenveloped = ( body: JsonValue | undefined, @@ -101,24 +97,22 @@ export const unenveloped = ( return wrapped?.member === envelope ? wrapped.object : undefined; }; -/** A call's body object as its plan takes it: an entity write's unwrapped from its envelope, and once the plan is built only one sent with the exemplar's wrapping. */ -export const plannedObject = ( +/** The request object and its wrapping, decided once from known entity fields and retained by the plan. */ +export const plannedBody = ( body: JsonValue | undefined, - plan: - | { - readonly built: boolean; - readonly envelope: string | undefined; - } - | undefined, -): JsonObject | undefined => { - const envelope = - plan === undefined - ? undefined - : plan.built - ? plan.envelope - : envelopeOf(body)?.member; + plan: { readonly built: boolean; readonly envelope: string | undefined }, + knownField: (member: string) => boolean, +): { readonly object: JsonObject; readonly envelope?: string } | undefined => { + const wrapped = plan.built ? undefined : envelopeOf(body); + const envelope = plan.built + ? plan.envelope + : wrapped !== undefined && !knownField(wrapped.member) + ? wrapped.member + : undefined; const object = unenveloped(body, envelope); - return object !== undefined && isObject(object) ? object : undefined; + return object !== undefined && isObject(object) + ? { object, ...(envelope === undefined ? {} : { envelope }) } + : undefined; }; /** Whether two queries name the same values; a query repeating a name with another value matches none. */ @@ -257,24 +251,34 @@ export const nestedClockValue = ( }) : err(`The entity holds no ${rule.field} object for the write to stamp.`); -/** A created token no other entity holds and no other field repeats, where every other entity holds one of its length. */ +/** A created opaque token's proof: independent generation, an unsupported nested link, or insufficient evidence. */ export const createdToken = ( field: string, entity: JsonObject, type: readonly JsonObject[], -): boolean => { +): "independent" | "linked" | undefined => { const value = entity[field]; - return ( - isOpaqueToken(value) && - type.length > 0 && - !Object.entries(entity).some( - ([other, held]) => other !== field && held === value, - ) && - type.every( + if ( + !isOpaqueToken(value) || + type.length === 0 || + !type.every( (member) => member[field] !== value && isOpaqueToken(member[field], value), ) - ); + ) + return undefined; + if ( + Object.entries(entity).some( + ([other, held]) => + other !== field && + (held === value || + (typeof held === "object" && + held !== null && + containsDelimited(held, value))), + ) + ) + return "linked"; + return "independent"; }; /** What judging an unsent change reads: the entity before and after, the call's body and the type's other entities. */ @@ -296,11 +300,11 @@ export const freshToken = ( isOpaqueToken(after, before) && isOpaqueToken(before) && before !== after && - !Object.values(evidence.call.body).includes(after) && + !containsDelimited(evidence.call.body, after) && !Object.entries(evidence.after).some( - ([name, value]) => name !== field && value === after, + ([name, value]) => name !== field && containsDelimited(value, after), ) && - !evidence.others.some((other) => other[field] === after) + !evidence.others.some((other) => containsDelimited(other, after)) ); }; diff --git a/src/domain/analysisView/scenarioCaptureRecords.test.ts b/src/domain/analysisView/scenarioCaptureRecords.test.ts index be105decda4..f63645f6ad6 100644 --- a/src/domain/analysisView/scenarioCaptureRecords.test.ts +++ b/src/domain/analysisView/scenarioCaptureRecords.test.ts @@ -40,7 +40,11 @@ describe("scenarioCaptureRecords", () => { ]); const user = projected.records[1]; expect(user?.reported).toEqual({ - request: { method: "GET", url: "http://127.0.0.1:3101/api/users/2" }, + request: { + method: "GET", + url: "http://127.0.0.1:3101/api/users/2", + bodySize: -1, + }, response: { status: 200, content: { @@ -71,7 +75,11 @@ describe("scenarioCaptureRecords", () => { request: { url: null }, }); expect(projected.records[7]?.reported).toEqual({ - request: { method: "GET", url: "http://127.0.0.1:3101/api/slow" }, + request: { + method: "GET", + url: "http://127.0.0.1:3101/api/slow", + bodySize: -1, + }, }); expect(manifestLimitations(projected)).toContain( "1 of 7 scenario transactions with a usable request line retained no response body; tools citing them replay only the recorded status and content type, either of which may be absent.", @@ -252,3 +260,40 @@ it("does not decode request text when projecting replay records", () => { decoder.mockRestore(); } }); + +it("distinguishes a retained empty request from missing or redacted request bytes", () => { + const captured = scenarioCaptureFixture([ + { + method: "POST", + url: "/api/items/1/archive", + status: 204, + requestBody: "", + requestMediaType: "application/json", + }, + ]); + expect( + scenarioCaptureRecords(captured, "manifest").records[0]?.reported, + ).toMatchObject({ request: { bodySize: 0 } }); + const redacted = { + ...captured, + events: { + ...captured.events, + items: captured.events.items.map((event) => + event.kind === "network-content" && + event.phase === "request" && + event.body.state === "captured" + ? { ...event, body: { ...event.body, redacted: true } } + : event, + ), + }, + }; + expect( + scenarioCaptureRecords(redacted, "manifest").records[0]?.reported, + ).toMatchObject({ request: { bodySize: -1 } }); + const missing = scenarioCaptureFixture([ + { method: "POST", url: "/api/items/1/archive", status: 204 }, + ]); + expect( + scenarioCaptureRecords(missing, "manifest").records[0]?.reported, + ).toMatchObject({ request: { bodySize: -1 } }); +}); diff --git a/src/domain/analysisView/scenarioCaptureRecords.ts b/src/domain/analysisView/scenarioCaptureRecords.ts index 814888100c2..f8bc23277ab 100644 --- a/src/domain/analysisView/scenarioCaptureRecords.ts +++ b/src/domain/analysisView/scenarioCaptureRecords.ts @@ -96,6 +96,7 @@ const reportedRequest = ( const mimeType = mediaType(content); return { method: request.method, + bodySize: body !== undefined && !body.redacted ? body.bytes : -1, url: request.url.redacted ? null : request.url.url, ...(text === undefined || mimeType === undefined ? {} diff --git a/tests/fixtures/analysisView.ts b/tests/fixtures/analysisView.ts index 066672d1405..454526c1cee 100644 --- a/tests/fixtures/analysisView.ts +++ b/tests/fixtures/analysisView.ts @@ -339,6 +339,8 @@ export const timedCaptureEvidence = ( request: { method, url: `http://app.example${path}`, + bodySize: + sent === undefined ? 0 : Buffer.byteLength(JSON.stringify(sent)), ...(sent === undefined ? {} : { From 75817ba5f2712cd646fb6f7f584731381dfec51e Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:31:35 +0000 Subject: [PATCH 64/68] fix(environment): verify complete nested clocks on creates --- .../environmentStateWriteReview.test.ts | 75 +++++++++++++++++++ .../environmentStateWriteCreate.ts | 35 ++++++--- 2 files changed, 101 insertions(+), 9 deletions(-) diff --git a/src/application/environment/environmentStateWriteReview.test.ts b/src/application/environment/environmentStateWriteReview.test.ts index d98c25b31c3..dce95ca1dc1 100644 --- a/src/application/environment/environmentStateWriteReview.test.ts +++ b/src/application/environment/environmentStateWriteReview.test.ts @@ -174,3 +174,78 @@ it.each(["2", "02"])( }); }, ); + +const nestedClockRows = (edit: { + [key: string]: string; +}): TimedCaptureRow[] => { + const first = { + ...FIRST_BOOK, + edit: { + at: FIRST_BOOK.created_at!, + seen_at: FIRST_BOOK.created_at!, + by: "alice", + }, + }; + const second = { + ...SECOND_BOOK, + edit: { + at: SECOND_BOOK.created_at!, + seen_at: SECOND_BOOK.created_at!, + by: "alice", + }, + }; + const third = { + ...book(3, "Third", bookClock(3)), + edit: { at: bookClock(3), seen_at: bookClock(3), by: "alice" }, + }; + const fourth = { ...book(4, "Fourth", bookClock(5)), edit }; + return [ + ["GET", "/api/books", [first, second]], + ["GET", "/api/books/1", first], + ["GET", "/api/books/2", second], + ["POST", "/api/books", third, 201, { name: "Third" }], + ["GET", "/api/books/3", third], + ["POST", "/api/books", fourth, 201, { name: "Fourth" }], + ["GET", "/api/books/4", fourth], + ["GET", "/api/books", [first, second, third, fourth]], + ]; +}; + +it.each<{ name: string; edit: { [key: string]: string } }>([ + { + name: "changed editor", + edit: { at: bookClock(5), seen_at: bookClock(5), by: "bob" }, + }, + { + name: "added member", + edit: { + at: bookClock(5), + seen_at: bookClock(5), + by: "alice", + role: "admin", + }, + }, + { name: "omitted member", edit: { at: bookClock(5), seen_at: bookClock(5) } }, + { + name: "different clock values", + edit: { at: bookClock(5), seen_at: bookClock(6), by: "alice" }, + }, +])( + "withholds creates whose nested-clock renderer cannot reproduce a later $name", + ({ edit }) => { + expect( + servedFrom(nestedClockRows(edit)).state.writes.get("post_books"), + ).toMatchObject({ served: false, reason: "unexplained-change" }); + }, +); + +it("serves successive creates whose complete nested-clock objects are reproducible", () => { + const books = servedFrom( + nestedClockRows({ at: bookClock(5), seen_at: bookClock(5), by: "alice" }), + ); + expect(books.state.writes.get("post_books")).toMatchObject({ served: true }); + const result = books.answer("post_books", { body: { name: "Caller" } }); + expect(result.body).toMatchObject({ name: "Caller", edit: { by: "alice" } }); + const edit = (result.body as { edit: { at: string; seen_at: string } }).edit; + expect(edit.at).toBe(edit.seen_at); +}); diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 2a29cdf1f4b..52cf20b7652 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -1,12 +1,13 @@ import { jsonTextCodeUnits } from "../jsonSerialization.js"; import type { JsonValue } from "../jsonValue.js"; -import { ok } from "../result.js"; +import { err, ok, type Result } from "../result.js"; import { collectionPathOf, isObject, isParam, normalizedPath, scalarText, + same, segmentsOf, selectedCollection, type JsonObject, @@ -19,6 +20,7 @@ import { unenveloped, createdToken, isOpaqueToken, + nestedClockValue, restampedFields, sameQuery, variedMembers, @@ -301,13 +303,6 @@ const followsGenerated = ( return ( JSON.stringify(readClock(value)?.format) === JSON.stringify(rule.format) ); - if (rule.rule === "nested-clock") - return rule.members.every( - (member) => - isObject(value ?? null) && - JSON.stringify(readClock((value as JsonObject)[member])?.format) === - JSON.stringify(rule.format), - ); if (rule.rule === "unique") return ( (isUuid(value) || isOpaqueToken(value, draft.observed?.[rule.field])) && @@ -425,6 +420,28 @@ const insertCreated = ( return entityTarget(entity.type, entity.collection, entity.id); }; +/** A recorded generated value, checking a nested clock against the same complete-object renderer serving uses. */ +const recordedGeneration = ( + rule: FieldRule, + exemplar: JsonObject, + recorded: JsonObject, +): Result => { + const value = recorded[rule.field] ?? null; + if (rule.rule !== "nested-clock") return ok(value); + const clock = isObject(value) ? value[rule.members[0]!] : undefined; + if ( + clock === undefined || + JSON.stringify(readClock(clock)?.format) !== JSON.stringify(rule.format) + ) + return err(`The recorded ${rule.field} has no clock in the plan's format.`); + const rebuilt = nestedClockValue(exemplar[rule.field], rule, clock); + return rebuilt.ok && same(rebuilt.value, value) + ? rebuilt + : err( + `The recorded ${rule.field} differs from its nested-clock rendering.`, + ); +}; + /** Apply a recorded create, with the values it recorded for generated fields; an unexplained create adds what it recorded. */ export const applyCreate = ( context: EffectContext, @@ -509,7 +526,7 @@ export const applyCreate = ( pathValuesOf(step.tool.path_template, collection) ?? call.pathValues, }; const fields = createdFields(draft.plan, draft.observed!, created, (rule) => - ok(observed.object[rule.field] ?? null), + recordedGeneration(rule, draft.observed!, observed.object), ); const id = fields.ok ? scalarText(fields.value[idField]) : undefined; if ( From 5b91c99b90aa371a9f455669bc46f7a0ae226c1c Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:04:29 +0800 Subject: [PATCH 65/68] fix(javascript): erase inline type imports before binding values --- ...riptSemanticAnalysis.require_links.test.ts | 5 +++++ .../javascript/javascriptSemanticAnalysis.ts | 10 ++++------ .../javascriptWorkerUrlCli.test.ts | 19 +++++++++---------- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts index eafb40255bd..ddb63052204 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.require_links.test.ts @@ -160,6 +160,11 @@ describe("TypeScript type-only module links", () => { export type { hiddenFunction }; `); + expect( + ir.bindings.filter(({ name }) => + ["Whole", "Inline", "Erased"].includes(name), + ), + ).toEqual([]); const externalLinks = ir.moduleLinks .filter(({ specifier }) => specifier !== null) .map( diff --git a/src/domain/javascript/javascriptSemanticAnalysis.ts b/src/domain/javascript/javascriptSemanticAnalysis.ts index 56f72c8122a..8da15e25127 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.ts @@ -80,6 +80,7 @@ import { } from "./javascriptSemanticAmbientWrites.js"; import { hasUncertainTypeOnlyModuleSideEffect, + isTypeOnlyImportSpecifier, semanticImportEqualsSpecifier, } from "./javascriptModuleDeclaration.js"; import { @@ -2039,6 +2040,8 @@ const bindImports = ( state: JavaScriptSemanticAnalysisState, ): void => { for (const specifier of node.specifiers) { + if (t.isImportSpecifier(specifier) && isTypeOnlyImportSpecifier(specifier)) + continue; const importedPath = t.isImportDefaultSpecifier(specifier) ? ["default"] : t.isImportNamespaceSpecifier(specifier) @@ -2053,12 +2056,7 @@ const bindImports = ( definitionNode: specifier.local, initializer: null, directOrigin: { specifier: node.source.value, importedPath }, - runtimeImport: - node.importKind !== "type" && - node.importKind !== "typeof" && - (!t.isImportSpecifier(specifier) || - (specifier.importKind !== "type" && - specifier.importKind !== "typeof")), + runtimeImport: true, }); } }; diff --git a/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts b/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts index 1039f5d3a1c..0a1f4b19a3c 100644 --- a/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts +++ b/tests/acceptance/applications/javascriptWorkerUrlCli.test.ts @@ -84,6 +84,15 @@ cliTest( suffix: "", resolves: true, }, + ...[ + 'import type { Worker } from "node:worker_threads";', + 'import { type Worker } from "node:worker_threads";', + ].map((prefix) => ({ + prefix, + constructor: "new Worker", + suffix: "", + resolves: true, + })), ...[ ["class Worker {}", "new Worker", ""], ["globalThis.Worker = Fake;", "new Worker", ""], @@ -94,16 +103,6 @@ cliTest( ["const custom = { Worker: class {} };", "new custom.Worker", ""], ["function start(window) {", "new window.Worker", "}"], ["function start(globalThis) {", "new globalThis.Worker", "}"], - [ - 'import type { Worker } from "node:worker_threads";', - "new Worker", - "", - ], - [ - 'import { type Worker } from "node:worker_threads";', - "new Worker", - "", - ], [ 'import type * as threads from "node:worker_threads";', "new threads.Worker", From 130121f74282700b1e236685808d23b26efccab6 Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:54:21 +0000 Subject: [PATCH 66/68] fix(environment): share complete generated value verification --- .../environmentStateWriteReview.test.ts | 40 +++++++++++++++++++ .../environmentStateWriteApply.ts | 27 ++++++++++++- .../environmentStateWriteCreate.ts | 36 +++++------------ .../environmentStateWriteEffects.ts | 14 +++++-- 4 files changed, 86 insertions(+), 31 deletions(-) diff --git a/src/application/environment/environmentStateWriteReview.test.ts b/src/application/environment/environmentStateWriteReview.test.ts index dce95ca1dc1..a7a7a46e7b6 100644 --- a/src/application/environment/environmentStateWriteReview.test.ts +++ b/src/application/environment/environmentStateWriteReview.test.ts @@ -16,6 +16,7 @@ import { SECOND_BOOK, book, bookClock, + renamedBook, } from "../../../tests/fixtures/environmentStateWrites.js"; import { webNetworkCaptureSchema } from "../../domain/webNetworkCapture.js"; @@ -249,3 +250,42 @@ it("serves successive creates whose complete nested-clock objects are reproducib const edit = (result.body as { edit: { at: string; seen_at: string } }).edit; expect(edit.at).toBe(edit.seen_at); }); + +it.each([0, 1])( + "checks the complete nested-clock update for a %s-second member difference", + (seconds) => { + const first = { + ...FIRST_BOOK, + edit: { at: bookClock(-8), seen_at: bookClock(-8), by: "alice" }, + }; + const second = { + ...SECOND_BOOK, + edit: { at: bookClock(-7), seen_at: bookClock(-7), by: "alice" }, + }; + const changed = { + ...renamedBook(first, "Renamed", 3), + edit: { at: bookClock(3), seen_at: bookClock(3 + seconds), by: "alice" }, + }; + const books = servedFrom([ + ["GET", "/api/books", [first, second]], + ["GET", "/api/books/1", first], + ["GET", "/api/books/2", second], + ["PATCH", "/api/books/1", changed, 200, { name: "Renamed" }], + ["GET", "/api/books/1", changed], + ["GET", "/api/books", [changed, second]], + ]); + expect(books.state.writes.get("patch_books_by_id")).toMatchObject({ + served: seconds === 0, + }); + if (seconds === 0) { + const result = books.answer("patch_books_by_id", { + id: "2", + body: { name: "Caller" }, + }); + expect(result.body).toMatchObject({ edit: { by: "alice" } }); + const edit = (result.body as { edit: { at: string; seen_at: string } }) + .edit; + expect(edit.at).toBe(edit.seen_at); + } + }, +); diff --git a/src/domain/analysisView/environmentStateWriteApply.ts b/src/domain/analysisView/environmentStateWriteApply.ts index 2a7edf01564..7a57b41d305 100644 --- a/src/domain/analysisView/environmentStateWriteApply.ts +++ b/src/domain/analysisView/environmentStateWriteApply.ts @@ -20,9 +20,13 @@ import type { WriteCall, WriteResponse, } from "./environmentStateWriteRules.js"; -import { stampProblem } from "./environmentStateWriteStamps.js"; +import { + stampProblem, + nestedClockValue, +} from "./environmentStateWriteStamps.js"; import { integerOf, + readClock, isUuid, replaceDelimited, slugOf, @@ -179,6 +183,27 @@ const pathValue = (observed: JsonValue | undefined, text: string): JsonValue => ? Number(text) : text; +/** A generated field from a recorded call, reproduced with the same nested-clock renderer serving uses. */ +export const recordedGeneratedValue = ( + rule: GeneratedRule, + base: JsonValue | undefined, + value: JsonValue | undefined, +): Applied => { + if (rule.rule !== "nested-clock") return ok(value); + const clock = isObject(value) ? value[rule.members[0]!] : undefined; + if ( + clock === undefined || + JSON.stringify(readClock(clock)?.format) !== JSON.stringify(rule.format) + ) + return err(`The recorded ${rule.field} has no clock in the plan's format.`); + const rebuilt = nestedClockValue(base, rule, clock); + return rebuilt.ok && same(rebuilt.value, value) + ? rebuilt + : err( + `The recorded ${rule.field} differs from its nested-clock rendering.`, + ); +}; + /** One field's value under a rule that reads the call or generates. */ const ruledValue = ( rule: FieldRule, diff --git a/src/domain/analysisView/environmentStateWriteCreate.ts b/src/domain/analysisView/environmentStateWriteCreate.ts index 52cf20b7652..c97b1c243b5 100644 --- a/src/domain/analysisView/environmentStateWriteCreate.ts +++ b/src/domain/analysisView/environmentStateWriteCreate.ts @@ -1,13 +1,11 @@ import { jsonTextCodeUnits } from "../jsonSerialization.js"; import type { JsonValue } from "../jsonValue.js"; -import { err, ok, type Result } from "../result.js"; import { collectionPathOf, isObject, isParam, normalizedPath, scalarText, - same, segmentsOf, selectedCollection, type JsonObject, @@ -15,12 +13,14 @@ import { type StateEntity, type SuppliedSegment, } from "./environmentStateRules.js"; -import { createdFields } from "./environmentStateWriteApply.js"; +import { + createdFields, + recordedGeneratedValue, +} from "./environmentStateWriteApply.js"; import { unenveloped, createdToken, isOpaqueToken, - nestedClockValue, restampedFields, sameQuery, variedMembers, @@ -420,28 +420,6 @@ const insertCreated = ( return entityTarget(entity.type, entity.collection, entity.id); }; -/** A recorded generated value, checking a nested clock against the same complete-object renderer serving uses. */ -const recordedGeneration = ( - rule: FieldRule, - exemplar: JsonObject, - recorded: JsonObject, -): Result => { - const value = recorded[rule.field] ?? null; - if (rule.rule !== "nested-clock") return ok(value); - const clock = isObject(value) ? value[rule.members[0]!] : undefined; - if ( - clock === undefined || - JSON.stringify(readClock(clock)?.format) !== JSON.stringify(rule.format) - ) - return err(`The recorded ${rule.field} has no clock in the plan's format.`); - const rebuilt = nestedClockValue(exemplar[rule.field], rule, clock); - return rebuilt.ok && same(rebuilt.value, value) - ? rebuilt - : err( - `The recorded ${rule.field} differs from its nested-clock rendering.`, - ); -}; - /** Apply a recorded create, with the values it recorded for generated fields; an unexplained create adds what it recorded. */ export const applyCreate = ( context: EffectContext, @@ -526,7 +504,11 @@ export const applyCreate = ( pathValuesOf(step.tool.path_template, collection) ?? call.pathValues, }; const fields = createdFields(draft.plan, draft.observed!, created, (rule) => - recordedGeneration(rule, draft.observed!, observed.object), + recordedGeneratedValue( + rule, + draft.observed![rule.field], + observed.object[rule.field] ?? null, + ), ); const id = fields.ok ? scalarText(fields.value[idField]) : undefined; if ( diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index e4eb60f1e2c..153d802a489 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -1,6 +1,5 @@ import { jsonTextCodeUnits } from "../jsonSerialization.js"; import type { JsonValue } from "../jsonValue.js"; -import { ok } from "../result.js"; import { isObject, locateItem, @@ -15,7 +14,11 @@ import { type StateType, type StateView, } from "./environmentStateRules.js"; -import { updatedEntity, updatedFields } from "./environmentStateWriteApply.js"; +import { + updatedEntity, + updatedFields, + recordedGeneratedValue, +} from "./environmentStateWriteApply.js"; import { collectionTarget, entityTarget, @@ -537,7 +540,12 @@ export const updateEntity = ( draft.plan, { before: entity.fields, observed: draft.observed! }, { ...call, id }, - (rule) => ok(stored[rule.field]), + (rule) => + recordedGeneratedValue( + rule, + entity.fields[rule.field], + stored[rule.field], + ), ); const kept = keptFields(entity.fields, after.object); const disagrees = From 7f01865c272f03a9484558ee767051cb51b8ce6d Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:04:45 +0000 Subject: [PATCH 67/68] fix(verifiers): load the Windows source graph only when needed --- scripts/lib/windows-owned-command.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/lib/windows-owned-command.mjs b/scripts/lib/windows-owned-command.mjs index 6005f4148db..85bacba91fe 100644 --- a/scripts/lib/windows-owned-command.mjs +++ b/scripts/lib/windows-owned-command.mjs @@ -1,5 +1,4 @@ import { createRequire } from "node:module"; -import { importVerifierSource } from "./verifier-source-loader.mjs"; const require = createRequire(import.meta.url); const sourceWindowsProcess = new URL( @@ -9,6 +8,7 @@ const sourceWindowsProcess = new URL( /** Load the source owner without requiring a generated dist tree. */ export async function loadWindowsOwnedProcessClass() { + const { importVerifierSource } = await import("./verifier-source-loader.mjs"); const source = await importVerifierSource( sourceWindowsProcess, import.meta.url, From 7360127f258eda12da5c2428f17d17045f04f52e Mon Sep 17 00:00:00 2001 From: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:35:57 +0000 Subject: [PATCH 68/68] fix(environment): validate write responses before stored clock restamps --- .../environmentStateWriteReview.test.ts | 59 +++++++++++++++++++ .../analysisView/environmentStateWriteBulk.ts | 11 ++-- .../environmentStateWriteEffects.ts | 36 +++++++---- 3 files changed, 89 insertions(+), 17 deletions(-) diff --git a/src/application/environment/environmentStateWriteReview.test.ts b/src/application/environment/environmentStateWriteReview.test.ts index a7a7a46e7b6..5985745fdf4 100644 --- a/src/application/environment/environmentStateWriteReview.test.ts +++ b/src/application/environment/environmentStateWriteReview.test.ts @@ -289,3 +289,62 @@ it.each([0, 1])( } }, ); + +it.each([ + { bulk: false, unequal: false }, + { bulk: true, unequal: false }, + { bulk: false, unequal: true }, + { bulk: true, unequal: true }, +])( + "validates the write response before its stored clock spelling (bulk=$bulk, unequal=$unequal)", + ({ bulk, unequal }) => { + const edit = (seconds: number, fraction: string) => ({ + at: new Date(bookClock(seconds)).toISOString().replace(".000Z", fraction), + seen_at: new Date(bookClock(seconds)) + .toISOString() + .replace(".000Z", fraction), + by: "alice", + }); + const first = { ...FIRST_BOOK, edit: edit(-8, ".000123Z") }; + const second = { ...SECOND_BOOK, edit: edit(-7, ".000123Z") }; + const changed = { + ...renamedBook(first, "Renamed", 3), + edit: { + ...edit(3, ".000Z"), + seen_at: new Date(bookClock(unequal ? 4 : 3)).toISOString(), + }, + }; + const read = { ...changed, edit: edit(3, ".000123Z") }; + const books = servedFrom([ + ["GET", "/api/books", [first, second]], + ["GET", "/api/books/1", first], + ["GET", "/api/books/2", second], + [ + "PATCH", + bulk ? "/api/books" : "/api/books/1", + bulk ? [changed] : changed, + 200, + bulk ? [{ id: 1, name: "Renamed" }] : { name: "Renamed" }, + ], + ["GET", "/api/books/1", read], + ["GET", "/api/books", [read, second]], + ]); + const name = bulk ? "patch_books" : "patch_books_by_id"; + expect(books.state.writes.get(name)).toMatchObject({ served: !unequal }); + if (!unequal) { + const result = books.answer( + name, + bulk + ? { body: [{ id: 2, name: "Caller" }] } + : { id: "2", body: { name: "Caller" } }, + ); + const entity = (bulk ? (result.body as unknown[])[0] : result.body) as { + name: string; + edit: { at: string; seen_at: string; by: string }; + }; + expect(entity).toMatchObject({ name: "Caller", edit: { by: "alice" } }); + expect(entity.edit.at).toBe(entity.edit.seen_at); + expect(entity.edit.at).toMatch(/\.\d{3}Z$/u); + } + }, +); diff --git a/src/domain/analysisView/environmentStateWriteBulk.ts b/src/domain/analysisView/environmentStateWriteBulk.ts index 6873cd61b48..be2f04024c1 100644 --- a/src/domain/analysisView/environmentStateWriteBulk.ts +++ b/src/domain/analysisView/environmentStateWriteBulk.ts @@ -223,10 +223,13 @@ export const applyBulk = ( const planned = draft.plan.response; if (planned !== null) { const written = targets.flatMap((target, index) => { - const entity = deleted - ? before[index] - : context.state.entity(type, target.collection, target.id); - return entity === undefined ? [] : [entity]; + const result = results[index]; + const fields = deleted + ? before[index]?.fields + : result?.kind === "applied" + ? result.responseFields + : undefined; + return fields === undefined ? [] : [{ id: target.id, fields }]; }); const fits = planned.shape === response.shape && diff --git a/src/domain/analysisView/environmentStateWriteEffects.ts b/src/domain/analysisView/environmentStateWriteEffects.ts index 153d802a489..cdd4d0a6edb 100644 --- a/src/domain/analysisView/environmentStateWriteEffects.ts +++ b/src/domain/analysisView/environmentStateWriteEffects.ts @@ -176,6 +176,8 @@ export type EffectResult = readonly accumulated: readonly string[]; }; readonly inserted?: string; + /** Validated update-response fields, before a later read restamps stored clocks. */ + readonly responseFields?: JsonObject; } | { readonly kind: "observed"; @@ -529,12 +531,6 @@ export const updateEntity = ( return recorded(); } buildUpdate(context, draft, step, { after, explained, idField }); - const stored = restampedFields( - searchFrom(context, step), - itemReads(context, { type, idField, collection, id }), - after.object, - draft.plan.rules, - ); // Serving reads the plan's observation, so the gate does too; generated values are this call's. const written = updatedFields( draft.plan, @@ -544,7 +540,7 @@ export const updateEntity = ( recordedGeneratedValue( rule, entity.fields[rule.field], - stored[rule.field], + after.object[rule.field], ), ); const kept = keptFields(entity.fields, after.object); @@ -564,12 +560,26 @@ export const updateEntity = ( { before: entity.fields, after: after.object, sent: body, kept }, explained.unstamped, ); - context.io.retain(64 + jsonTextCodeUnits(written.value) * 2); - context.state.put(updatedEntity(entity, written.value)); - return appliedUpdate(draft.plan, { targets, target }, entity.fields, { - written: written.value, - body, - }); + // Response reproducibility is established before the read owner adopts a stored clock spelling. + const stored = restampedFields( + searchFrom(context, step), + itemReads(context, { type, idField, collection, id }), + written.value, + draft.plan.rules, + ); + context.io.retain( + 64 + + jsonTextCodeUnits(stored) * 2 + + (stored === written.value ? 0 : jsonTextCodeUnits(written.value) * 2), + ); + context.state.put(updatedEntity(entity, stored)); + return { + ...appliedUpdate(draft.plan, { targets, target }, entity.fields, { + written: stored, + body, + }), + responseFields: written.value, + }; }; /** Serving regenerates a learned clock on every update, so recorded calls must advance it. */