feat(environment): list every entity on a list's whole lines (#5787)
Derive whole-collection membership per checked list line while preserving recorded membership, counters, source Evidence and independent write claims. Integrate current main without losing its shared path decoder. Keep later or ambiguously positioned pages recorded rather than inventing earlier entities. Validation: 543 focused/adjacent tests, nine README checks, complete static/docs checks, repeated regression runs, and real retained GitHub-label CLI/MCP load/reset workflows. An actual Codex session returned the correct facts; its over-strict grader failure and same-trace semantic verification are recorded. Evidence and limitations: https://github.com/morluto/rea/pull/5787#issuecomment-6338446674 Tracking: #6262; feature scope: #4933. Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
1 parent
932fbb7d84
commit
4043e71f6c
18 files changed
+616
-113
No files matched your search
@@ -2,7 +2,9 @@ import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumul
|
||||
import {
|
||||
collectionPathOf,
|
||||
decodedSegment,
|
||||
allLines,
|
||||
listItems,
|
||||
listsAll,
|
||||
missingRequiredFields,
|
||||
renderStateEntity,
|
||||
renderStateList,
|
||||
@@ -427,27 +429,27 @@ const answerList = (
|
||||
return fromRecording(source, tool, args, "body-unusable");
|
||||
const collection = collectionPathOf(base, false);
|
||||
const type = store.type(view.type);
|
||||
const all = listsAll(view, base.ordinal);
|
||||
// A requested page the collection has outgrown is answered as recorded, never with more items than it asked for.
|
||||
const size = exact
|
||||
? pageBound(base.query ?? undefined, recorded.length)
|
||||
: undefined;
|
||||
if (
|
||||
view.membership === "all" &&
|
||||
all &&
|
||||
size !== undefined &&
|
||||
store.inCollection(view.type, collection).length > size
|
||||
)
|
||||
return fromRecording(source, tool, args, "page-exceeded");
|
||||
const members: readonly StateEntity[] =
|
||||
view.membership === "all"
|
||||
? store.inCollection(view.type, collection)
|
||||
: recorded.flatMap((item) => {
|
||||
const id = scalarText(item[type?.id_field ?? ""]);
|
||||
const entity =
|
||||
id === undefined
|
||||
? undefined
|
||||
: store.entity(view.type, collection, id);
|
||||
return entity === undefined ? [] : [entity];
|
||||
});
|
||||
const members: readonly StateEntity[] = all
|
||||
? store.inCollection(view.type, collection)
|
||||
: recorded.flatMap((item) => {
|
||||
const id = scalarText(item[type?.id_field ?? ""]);
|
||||
const entity =
|
||||
id === undefined
|
||||
? undefined
|
||||
: store.entity(view.type, collection, id);
|
||||
return entity === undefined ? [] : [entity];
|
||||
});
|
||||
const volatile = new Set(type?.volatile_fields);
|
||||
const items: JsonObject[] = [];
|
||||
for (const entity of members) {
|
||||
@@ -464,7 +466,7 @@ const answerList = (
|
||||
view: "list",
|
||||
type: view.type,
|
||||
collection,
|
||||
membership: view.membership,
|
||||
membership: all ? "all" : "recorded",
|
||||
listed: items.length,
|
||||
},
|
||||
);
|
||||
@@ -501,8 +503,8 @@ const answerCheckedLine = (
|
||||
);
|
||||
const base =
|
||||
named ??
|
||||
(view.shape === "list" && view.membership === "all"
|
||||
? unfilteredLine(serving.source, tool, view.checked_record_ordinals, args)
|
||||
(view.shape === "list"
|
||||
? unfilteredLine(serving.source, tool, allLines(view), args)
|
||||
: undefined);
|
||||
if (base === undefined)
|
||||
return fromRecording(serving.source, tool, args, "unrecorded-request");
|
||||
|
||||
@@ -10,10 +10,12 @@ import {
|
||||
BOOK_ROWS,
|
||||
DELETE_NOT_FOUND,
|
||||
FIRST_BOOK,
|
||||
LIST_LINE_ROWS,
|
||||
SECOND_BOOK,
|
||||
THIRD_BOOK,
|
||||
book,
|
||||
bookClock,
|
||||
bookPage,
|
||||
renamedBook,
|
||||
type Book,
|
||||
} from "../../../tests/fixtures/environmentStateWrites.js";
|
||||
@@ -539,6 +541,97 @@ describe("paged list lines", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("list lines", () => {
|
||||
it("keeps an empty later page recorded after data/add, while a first line lists the loaded entity", () => {
|
||||
for (const [query, whole] of [
|
||||
["offset=0", true],
|
||||
["start=0", true],
|
||||
["_start=0", true],
|
||||
["page=0", true],
|
||||
["offset=2", false],
|
||||
["start=2", false],
|
||||
["_start=2", false],
|
||||
["page=1", false],
|
||||
["offset=-1", false],
|
||||
["offset=unknown", false],
|
||||
] as const) {
|
||||
const alpha = { id: 1, name: "Alpha", org: "1" };
|
||||
const beta = { id: 2, name: "Beta", org: "2" };
|
||||
const books = servedFrom([
|
||||
["GET", "/api/orgs/1/books", [alpha]],
|
||||
["GET", "/api/orgs/1/books?name=Alpha", [alpha]],
|
||||
["GET", `/api/orgs/2/books?${query}&limit=50`, []],
|
||||
["GET", "/api/orgs/1/books/1", alpha],
|
||||
]);
|
||||
const held = books.store.snapshot().rea_state;
|
||||
const loaded = books.store.replace({
|
||||
rea_state: {
|
||||
...held,
|
||||
entities: [
|
||||
...held.entities,
|
||||
{
|
||||
type: held.entities[0]!.type,
|
||||
collection: "/api/orgs/2/books",
|
||||
id: "2",
|
||||
fields: beta,
|
||||
view_fields: [],
|
||||
record_ordinals: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
if (!loaded.ok) throw loaded.error;
|
||||
expect(
|
||||
books.answer("get_orgs_books_by_id", {
|
||||
id: "2",
|
||||
...Object.fromEntries(new URLSearchParams(query)),
|
||||
limit: "50",
|
||||
}),
|
||||
).toMatchObject({
|
||||
body: whole ? [beta] : [],
|
||||
state: {
|
||||
source: "state",
|
||||
membership: whole ? "all" : "recorded",
|
||||
listed: whole ? 1 : 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("lists a created book on the line that lists every book, while a filtered line keeps its recorded members", () => {
|
||||
const books = servedFrom(LIST_LINE_ROWS);
|
||||
const created = books.answer("post_books", CREATE_NEW_BOOK).body as Book;
|
||||
expect(books.answer("get_books")).toMatchObject({
|
||||
body: bookPage([FIRST_BOOK, SECOND_BOOK, created]),
|
||||
state: { source: "state", membership: "all", listed: 3 },
|
||||
});
|
||||
expect(books.answer("get_books", { name: "First Book" })).toMatchObject({
|
||||
body: bookPage([FIRST_BOOK]),
|
||||
state: { source: "state", membership: "recorded", listed: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates on each line only the counters its recording counted, so a partial page keeps its total", () => {
|
||||
const partial = {
|
||||
content: [FIRST_BOOK],
|
||||
totalElements: 2,
|
||||
numberOfElements: 1,
|
||||
};
|
||||
const books = servedFrom([
|
||||
["GET", "/api/books", bookPage([FIRST_BOOK, SECOND_BOOK])],
|
||||
["GET", "/api/books?page=1&size=1", partial],
|
||||
...LIST_LINE_ROWS.slice(2),
|
||||
]);
|
||||
const created = books.answer("post_books", CREATE_NEW_BOOK).body as Book;
|
||||
expect(books.answer("get_books")).toMatchObject({
|
||||
body: bookPage([FIRST_BOOK, SECOND_BOOK, created]),
|
||||
});
|
||||
expect(books.answer("get_books", { page: "1", size: "1" })).toMatchObject({
|
||||
body: partial,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("path values", () => {
|
||||
const orgBook = (id: number, org: string, name: string): Book => ({
|
||||
id,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
changesState,
|
||||
isObject,
|
||||
isStateWrite,
|
||||
listsAll,
|
||||
normalizedPath,
|
||||
type JsonObject,
|
||||
type StateEntity,
|
||||
@@ -24,7 +25,6 @@ import {
|
||||
servedLine,
|
||||
succeeded,
|
||||
withBodies,
|
||||
writtenFieldChecks,
|
||||
SimulatedState,
|
||||
type CheckOutcome,
|
||||
type CheckedLines,
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
WriteEffects,
|
||||
type PendingTargets,
|
||||
type TouchedTargets,
|
||||
writtenFieldChecks,
|
||||
} from "./environmentStateWriteAttribution.js";
|
||||
import { applyCreate } from "./environmentStateWriteCreate.js";
|
||||
import { applyDocument } from "./environmentStateWriteDocument.js";
|
||||
@@ -54,7 +55,6 @@ import {
|
||||
type WriteSimulationInput,
|
||||
type WriteStep,
|
||||
} from "./environmentStateWriteEffects.js";
|
||||
import { insertIndex } from "./environmentStateWriteExplain.js";
|
||||
import {
|
||||
classifyWrite,
|
||||
prefixRelated,
|
||||
@@ -270,7 +270,7 @@ export class EnvironmentStateWriteSimulation {
|
||||
this.#taint.known(entity.type, entity.collection, entity.id);
|
||||
this.#touched.delete(target);
|
||||
if (isAbsence(record.status)) {
|
||||
this.#state.remove(entity);
|
||||
this.#removeEntity(entity);
|
||||
return;
|
||||
}
|
||||
const object = this.#checkFields(view, record, entity, writes);
|
||||
@@ -336,7 +336,10 @@ export class EnvironmentStateWriteSimulation {
|
||||
};
|
||||
return item
|
||||
? checkItemRead(this.#state, view, record, check)
|
||||
: checkListRead(this.#state, view, record, check);
|
||||
: checkListRead(this.#state, view, record, {
|
||||
...check,
|
||||
all: listsAll(view, base),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -484,7 +487,13 @@ export class EnvironmentStateWriteSimulation {
|
||||
);
|
||||
if (isObject(object))
|
||||
this.#state.put(updatedEntity(entity, { ...entity.fields, ...object }));
|
||||
else this.#state.remove(entity);
|
||||
else this.#removeEntity(entity);
|
||||
}
|
||||
|
||||
/** A read showed the entity gone: the state drops it, and no write keeps a claim on its collection through it. */
|
||||
#removeEntity(entity: StateEntity): void {
|
||||
this.#state.remove(entity);
|
||||
this.#effects.removed(this.#touched, entity);
|
||||
}
|
||||
|
||||
/** Contradict the writes a failed check exercised, or, when none, the related writes since its targets were last checked; a failed list stops being checked. */
|
||||
@@ -521,9 +530,9 @@ export class EnvironmentStateWriteSimulation {
|
||||
record: StateRecordFacts,
|
||||
exercised: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const collection = this.#line(view, record)?.collection;
|
||||
if (view.membership !== "all" || collection === undefined) return false;
|
||||
const members = this.#state.members(view.type, collection);
|
||||
const line = this.#line(view, record);
|
||||
if (line === undefined || !listsAll(view, line.ordinal)) return false;
|
||||
const members = this.#state.members(view.type, line.collection);
|
||||
const key = (entity: StateEntity) =>
|
||||
entityTarget(entity.type, entity.collection, entity.id);
|
||||
const inserted = members.filter((entity) =>
|
||||
@@ -538,13 +547,7 @@ export class EnvironmentStateWriteSimulation {
|
||||
// An item read confirms the entity, not where a list places it.
|
||||
if (!exercised.has(name!) || this.#placed.has(name!)) return false;
|
||||
for (const candidate of draft.candidates.slice(1)) {
|
||||
for (const entity of inserted) this.#state.remove(entity);
|
||||
for (const entity of inserted) {
|
||||
const order = this.#state
|
||||
.members(view.type, collection)
|
||||
.map((member) => member.fields);
|
||||
this.#state.put(entity, insertIndex(candidate, order, entity.fields));
|
||||
}
|
||||
this.#state.reinsert(view.type, line.collection, inserted, candidate);
|
||||
if (this.#check(view, record)?.pass === true) {
|
||||
draft.plan.insert = candidate;
|
||||
return true;
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
type StateToolFacts,
|
||||
type StateView,
|
||||
} from "./environmentStateRules.js";
|
||||
import { pagesOnly } from "./environmentStatePaging.js";
|
||||
import { startsAtBeginning } from "./environmentStatePaging.js";
|
||||
import { ENTRY_BYTES, textBytes } from "./webNetworkRouteTemplates.js";
|
||||
|
||||
/** A read tool whose recordings locate entities of one type at one pointer. */
|
||||
@@ -159,44 +159,53 @@ export const checkItemPlan = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Whether every latest recording lists its whole collection in state order, and which counters equal the item count. */
|
||||
/** 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 all: boolean; readonly counters: string[] } => {
|
||||
): { readonly whole: ReadonlySet<number>; readonly counters: string[] } => {
|
||||
const field = context.idField(plan.type);
|
||||
let all = true;
|
||||
let counters: string[] | undefined;
|
||||
const whole = new Set<number>();
|
||||
const counting = new Map<number, string[]>();
|
||||
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));
|
||||
// Once a list cannot be the whole collection, its membership is not compared again; a line
|
||||
// that only pages its list can still hold all of it.
|
||||
if (all && pagesOnly(record.query)) {
|
||||
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)) all = false;
|
||||
} else all = false;
|
||||
const parent = plan.pointer === "" || !isObject(body) ? {} : body;
|
||||
const counted = Object.keys(parent).filter(
|
||||
(name) => isItemTotal(name) && countOf(parent[name]) !== undefined,
|
||||
);
|
||||
// A total that differs from the number listed, or a next page, shows the list is partial.
|
||||
counting.set(
|
||||
record.ordinal,
|
||||
counted.filter((name) => parent[name] === items.length),
|
||||
);
|
||||
// A later (or ambiguously positioned) page cannot establish whole membership,
|
||||
// even when its collection is empty. Totals and continuation also disprove it.
|
||||
if (
|
||||
!startsAtBeginning(record.query) ||
|
||||
counted.some((name) => countOf(parent[name]) !== items.length) ||
|
||||
Object.keys(parent).some((name) => continues(name, parent[name]))
|
||||
)
|
||||
all = false;
|
||||
const names = counted.filter((name) => parent[name] === items.length);
|
||||
counters = (counters ?? names).filter((name) => names.includes(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);
|
||||
});
|
||||
return { all, counters: (counters ?? []).sort(compare) };
|
||||
// A whole line's counters count the collection, which a partial page's total does not, so the whole lines decide.
|
||||
const lines = [...counting].filter(
|
||||
([ordinal]) => whole.size === 0 || whole.has(ordinal),
|
||||
);
|
||||
const counters = lines.reduce<string[] | undefined>(
|
||||
(kept, [, names]) =>
|
||||
kept === undefined ? names : kept.filter((name) => names.includes(name)),
|
||||
undefined,
|
||||
);
|
||||
return { whole, counters: (counters ?? []).sort(compare) };
|
||||
};
|
||||
|
||||
const nameTokens = (name: string): string[] =>
|
||||
@@ -204,17 +213,21 @@ const nameTokens = (name: string): string[] =>
|
||||
.split(/[_\-\s]|(?<=[a-z0-9])(?=[A-Z])/u)
|
||||
.map((token) => token.toLowerCase());
|
||||
|
||||
/** Item totals, including compact `totalcount`/`itemcount`; page counts and account IDs are excluded. */
|
||||
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(
|
||||
(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",
|
||||
)
|
||||
@@ -255,7 +268,7 @@ const listReproduces = (
|
||||
readonly fields: string[];
|
||||
readonly pointer: string;
|
||||
readonly counters: string[];
|
||||
readonly all: boolean;
|
||||
readonly whole: ReadonlySet<number>;
|
||||
},
|
||||
record: StateRecordFacts,
|
||||
): boolean => {
|
||||
@@ -267,7 +280,7 @@ const listReproduces = (
|
||||
const observed = new Map(
|
||||
items.map((item) => [scalarText(item[field]) ?? "", item]),
|
||||
);
|
||||
const members = view.all
|
||||
const members = view.whole.has(record.ordinal)
|
||||
? context.inCollection(plan.type, collectionPathOf(record, false))
|
||||
: items.flatMap((item) => {
|
||||
const entity = context.entity(
|
||||
@@ -295,15 +308,16 @@ export const checkListPlan = (
|
||||
plan: StatePlan,
|
||||
): StateView => {
|
||||
const union = new FieldUnion();
|
||||
const { all, counters } = listFacts(context, plan, union);
|
||||
const { whole, counters } = listFacts(context, plan, union);
|
||||
context.retain(union.bytes);
|
||||
const view = {
|
||||
tool: plan.tool.name,
|
||||
fields: union.fields,
|
||||
pointer: plan.pointer,
|
||||
counters,
|
||||
all,
|
||||
whole,
|
||||
};
|
||||
const all = plan.latest.every((record) => whole.has(record.ordinal));
|
||||
if (
|
||||
!plan.latest.every((record) => listReproduces(context, plan, view, record))
|
||||
)
|
||||
@@ -316,6 +330,13 @@ export const checkListPlan = (
|
||||
fields: union.fields,
|
||||
required_fields: union.required,
|
||||
membership: all ? "all" : "recorded",
|
||||
...(all || whole.size === 0
|
||||
? {}
|
||||
: {
|
||||
all_record_ordinals: plan.latest
|
||||
.map((record) => record.ordinal)
|
||||
.filter((ordinal) => whole.has(ordinal)),
|
||||
}),
|
||||
counters,
|
||||
checked_record_ordinals: plan.latest.map((record) => record.ordinal),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { startsAtBeginning } from "./environmentStatePaging.js";
|
||||
|
||||
it("requires every recorded position to establish the beginning, including repeated names", () => {
|
||||
expect(startsAtBeginning(undefined)).toBe(true);
|
||||
expect(startsAtBeginning("?offset=0&offset=0&limit=50")).toBe(true);
|
||||
for (const query of [
|
||||
"?offset=0&offset=2&limit=50",
|
||||
"?page=1&size=50",
|
||||
"?start=1&_end=50",
|
||||
"?_start=2&_end=50",
|
||||
"?offset=9007199254740992",
|
||||
"?offset=NaN",
|
||||
"?limit=unknown",
|
||||
"?name=Alpha",
|
||||
])
|
||||
expect(startsAtBeginning(query), query).toBe(false);
|
||||
});
|
||||
@@ -25,6 +25,20 @@ export const pagesOnly = (query: string | undefined): boolean =>
|
||||
PAGING_PARAMETERS.has(name.toLowerCase()),
|
||||
);
|
||||
|
||||
const PAGE_POSITION_PARAMETERS = new Set(["offset", "start", "_start", "page"]);
|
||||
|
||||
/** A paging-only line that can start at the collection's beginning. Positive page numbers are ambiguous (zero- or one-based); malformed or conflicting positions do not establish whole membership. */
|
||||
export const startsAtBeginning = (query: string | undefined): boolean => {
|
||||
if (!pagesOnly(query)) return false;
|
||||
for (const [name, value] of iterateUrlQueryParameters(query ?? "")) {
|
||||
const number = Number(value);
|
||||
if (!/^\d+$/u.test(value) || !Number.isSafeInteger(number)) return false;
|
||||
if (PAGE_POSITION_PARAMETERS.has(name.toLowerCase()) && number !== 0)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Paging parameters that bound how many items a page holds. */
|
||||
const PAGE_SIZE_PARAMETERS = new Set([
|
||||
"limit",
|
||||
|
||||
@@ -108,9 +108,22 @@ export type StateItemView = EntityViewPlan & {
|
||||
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[];
|
||||
};
|
||||
|
||||
/** Whether a list view answers on a checked line with every entity of the collection. */
|
||||
export const listsAll = (view: StateListView, ordinal: number): boolean =>
|
||||
view.membership === "all" ||
|
||||
(view.all_record_ordinals?.includes(ordinal) ?? false);
|
||||
|
||||
/** The checked lines a list view answers with every entity of the collection. */
|
||||
export const allLines = (view: StateListView): readonly number[] =>
|
||||
view.membership === "all"
|
||||
? view.checked_record_ordinals
|
||||
: (view.all_record_ordinals ?? []);
|
||||
|
||||
export type StateView =
|
||||
| StateItemView
|
||||
| StateListView
|
||||
@@ -530,13 +543,21 @@ export const missingRequiredFields = (
|
||||
return view.required_fields.filter((name) => !Object.hasOwn(shown, name));
|
||||
};
|
||||
|
||||
/** A list response rendered from `base`: its array replaced by `items` and its counters set to their number. */
|
||||
/**
|
||||
* A list response rendered from `base`: its array replaced by `items`, and set to their number each counter that
|
||||
* counted the items `base` listed; one that did not, such as a partial page's total, keeps its recorded value.
|
||||
*/
|
||||
export const renderStateList = (
|
||||
view: Pick<StateListView, "pointer" | "counters">,
|
||||
base: JsonValue,
|
||||
items: readonly JsonObject[],
|
||||
): JsonValue =>
|
||||
view.counters.reduce(
|
||||
(body, name) => replaceAt(body, pointerTo(name), items.length),
|
||||
): JsonValue => {
|
||||
const listed = listItems(base, view.pointer)?.length;
|
||||
return view.counters.reduce(
|
||||
(body, name) =>
|
||||
at(base, pointerTo(name)) === listed
|
||||
? replaceAt(body, pointerTo(name), items.length)
|
||||
: body,
|
||||
replaceAt(base, view.pointer, [...items]),
|
||||
);
|
||||
};
|
||||
@@ -58,7 +58,13 @@ const viewSchema = z.discriminatedUnion("shape", [
|
||||
membership: z
|
||||
.enum(["all", "recorded"])
|
||||
.describe(
|
||||
"all: every entity of the collection in state order; recorded: the entities each recorded response listed.",
|
||||
"all: every entity of the collection in state order; recorded: the entities each recorded response listed, except on the lines all_record_ordinals names.",
|
||||
),
|
||||
all_record_ordinals: z
|
||||
.array(z.number().int().nonnegative())
|
||||
.optional()
|
||||
.describe(
|
||||
"With recorded membership, the checked lines that each listed every entity of their collection in state order, with only paging parameters starting at zero; a call answered on one lists the whole collection. Absent when none does.",
|
||||
),
|
||||
counters: z
|
||||
.array(z.string())
|
||||
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { StateView } from "./environmentStateRules.js";
|
||||
import {
|
||||
renderStateEntity,
|
||||
same,
|
||||
type JsonObject,
|
||||
type StateEntity,
|
||||
type StateItemView,
|
||||
type StateView,
|
||||
} from "./environmentStateRules.js";
|
||||
import {
|
||||
collectionTarget,
|
||||
entityTarget,
|
||||
} from "./environmentStateWriteChecks.js";
|
||||
|
||||
/** The fields a read of a view shows of its entities, less volatile ones it does not compare; all of a document's. */
|
||||
export const shownFields = (
|
||||
@@ -178,6 +189,27 @@ export class WriteEffects {
|
||||
if (!unseen.has(tool)) byTool.get(key)!.delete(tool);
|
||||
}
|
||||
|
||||
/** A read showed the entity absent: no write's effect on it remains, so a write left with no entity drops from the collection. */
|
||||
removed(
|
||||
touched: TouchedTargets,
|
||||
gone: {
|
||||
readonly type: string;
|
||||
readonly collection: string;
|
||||
readonly id: string;
|
||||
},
|
||||
): void {
|
||||
const entity = entityTarget(gone.type, gone.collection, gone.id);
|
||||
const collection = collectionTarget(gone.type, gone.collection);
|
||||
this.#changed.delete(entity);
|
||||
const byTool = this.#members.get(collection);
|
||||
if (byTool === undefined) return;
|
||||
for (const [tool, entities] of byTool) {
|
||||
if (!entities.delete(entity) || entities.size > 0) continue;
|
||||
byTool.delete(tool);
|
||||
touched.get(collection)?.delete(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,
|
||||
@@ -348,3 +380,35 @@ export const forgetChecked = (
|
||||
}
|
||||
pending.effects.checked(key, unseen);
|
||||
};
|
||||
|
||||
/**
|
||||
* Check, field by field, the writes that changed an entity an unmodelled write also changed:
|
||||
* each write's own fields must show as the state holds them, but for volatile ones, which take
|
||||
* the read's value and so show nothing of a write. A create wrote every field, so it cannot be
|
||||
* told apart from the unmodelled change and is not checked.
|
||||
*/
|
||||
export const writtenFieldChecks = (
|
||||
entity: StateEntity,
|
||||
view: StateItemView,
|
||||
observed: JsonObject,
|
||||
check: {
|
||||
readonly volatile: ReadonlySet<string>;
|
||||
readonly writes: ReadonlyMap<string, readonly string[] | null>;
|
||||
},
|
||||
): Map<string, boolean> => {
|
||||
const shown = renderStateEntity(entity, view, check.volatile, observed);
|
||||
const outcomes = new Map<string, boolean>();
|
||||
for (const [tool, fields] of check.writes) {
|
||||
const compared = (fields ?? []).filter(
|
||||
(field) =>
|
||||
!check.volatile.has(field) &&
|
||||
(Object.hasOwn(observed, field) || Object.hasOwn(shown, field)),
|
||||
);
|
||||
if (fields === null || compared.length === 0) continue;
|
||||
outcomes.set(
|
||||
tool,
|
||||
compared.every((field) => same(shown[field], observed[field])),
|
||||
);
|
||||
}
|
||||
return outcomes;
|
||||
};
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
decodedSegment,
|
||||
isObject,
|
||||
isParam,
|
||||
listsAll,
|
||||
listItems,
|
||||
missingRequiredFields,
|
||||
renderStateEntity,
|
||||
@@ -27,6 +28,8 @@ import {
|
||||
type StateView,
|
||||
} from "./environmentStateRules.js";
|
||||
import { pageBound, pagesOnly } from "./environmentStatePaging.js";
|
||||
import { insertIndex } from "./environmentStateWriteExplain.js";
|
||||
import type { InsertRule } from "./environmentStateWriteRules.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 => {
|
||||
@@ -49,7 +52,7 @@ interface CheckedLine {
|
||||
export interface CheckedLines {
|
||||
readonly params: ReadonlySet<number>;
|
||||
readonly byQuery: ReadonlyMap<string, readonly CheckedLine[]>;
|
||||
/** A whole list's lines that only page it, which serving answers a call supplying no query from. */
|
||||
/** The lines listing their whole collection that only page it, which serving answers a call supplying no query from. */
|
||||
readonly unfiltered: readonly CheckedLine[];
|
||||
}
|
||||
|
||||
@@ -76,14 +79,18 @@ export const checkedLines = (input: {
|
||||
const checked = new Set(view.checked_record_ordinals);
|
||||
const byQuery = new Map<string, CheckedLine[]>();
|
||||
const unfiltered: CheckedLine[] = [];
|
||||
const whole = view.shape === "list" && view.membership === "all";
|
||||
for (const ordinal of tool.record_ordinals) {
|
||||
const record = byOrdinal.get(ordinal);
|
||||
const key = record === undefined ? undefined : queryKey(record.query);
|
||||
if (!checked.has(ordinal) || key === undefined) continue;
|
||||
const line = { ordinal, segments: segmentsOf(record!.path) };
|
||||
byQuery.set(key, [...(byQuery.get(key) ?? []), line]);
|
||||
if (whole && pagesOnly(record!.query)) unfiltered.push(line);
|
||||
if (
|
||||
view.shape === "list" &&
|
||||
listsAll(view, ordinal) &&
|
||||
pagesOnly(record!.query)
|
||||
)
|
||||
unfiltered.push(line);
|
||||
}
|
||||
const params = new Set(
|
||||
segmentsOf(tool.path_template).flatMap((segment, index) =>
|
||||
@@ -234,6 +241,22 @@ export class SimulatedState {
|
||||
);
|
||||
}
|
||||
|
||||
/** Place created entities again as a create under another insert rule would have. */
|
||||
reinsert(
|
||||
type: string,
|
||||
collection: string,
|
||||
entities: readonly StateEntity[],
|
||||
rule: InsertRule,
|
||||
): void {
|
||||
for (const entity of entities) this.remove(entity);
|
||||
for (const entity of entities) {
|
||||
const order = this.members(type, collection).map(
|
||||
(member) => member.fields,
|
||||
);
|
||||
this.put(entity, insertIndex(rule, order, entity.fields));
|
||||
}
|
||||
}
|
||||
|
||||
document(tool: string): JsonValue | undefined {
|
||||
return this.#documents.get(tool);
|
||||
}
|
||||
@@ -504,12 +527,17 @@ const checkRecordedList = (
|
||||
return { ...listCheck(view, check, members), targets, unheld };
|
||||
};
|
||||
|
||||
/** A list read on a checked line, compared with the answer the served environment renders on that line's base recording from the collection it names. */
|
||||
/** A list read on a checked line, compared with the answer the served environment renders on that line's base recording from the collection it names: every entity when that line lists them all. */
|
||||
export const checkListRead = (
|
||||
state: SimulatedState,
|
||||
view: StateListView,
|
||||
record: StateRecordFacts,
|
||||
check: ReadBodies & { readonly idField: string; readonly collection: string },
|
||||
check: ReadBodies & {
|
||||
readonly idField: string;
|
||||
readonly collection: string;
|
||||
/** Whether the base line lists every entity of its collection. */
|
||||
readonly all: boolean;
|
||||
},
|
||||
): CheckOutcome | undefined => {
|
||||
if (!succeeded(record)) return undefined;
|
||||
const { body, base } = check;
|
||||
@@ -520,7 +548,7 @@ export const checkListRead = (
|
||||
// Serving answers a page too small for the collection from its recording, so such a read checks nothing.
|
||||
const size = pageBound(record.query, baseItems.length);
|
||||
if (
|
||||
view.membership === "all" &&
|
||||
check.all &&
|
||||
size !== undefined &&
|
||||
state.members(view.type, check.collection).length > size
|
||||
)
|
||||
@@ -528,10 +556,9 @@ export const checkListRead = (
|
||||
// A usable body that no longer holds the list is not what serving answers on this line.
|
||||
const items = listItems(body, view.pointer);
|
||||
const bodies = { ...check, body, base, items: items ?? [], baseItems };
|
||||
const outcome =
|
||||
view.membership === "all"
|
||||
? checkAllList(state, view, bodies)
|
||||
: checkRecordedList(state, view, bodies);
|
||||
const outcome = check.all
|
||||
? checkAllList(state, view, bodies)
|
||||
: checkRecordedList(state, view, bodies);
|
||||
return items === undefined ? { ...outcome, pass: false } : outcome;
|
||||
};
|
||||
|
||||
@@ -551,35 +578,3 @@ export const checkDocumentRead = (
|
||||
unheld: [],
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Check, field by field, the writes that changed an entity an unmodelled write also changed:
|
||||
* each write's own fields must show as the state holds them, but for volatile ones, which take
|
||||
* the read's value and so show nothing of a write. A create wrote every field, so it cannot be
|
||||
* told apart from the unmodelled change and is not checked.
|
||||
*/
|
||||
export const writtenFieldChecks = (
|
||||
entity: StateEntity,
|
||||
view: StateItemView,
|
||||
observed: JsonObject,
|
||||
check: {
|
||||
readonly volatile: ReadonlySet<string>;
|
||||
readonly writes: ReadonlyMap<string, readonly string[] | null>;
|
||||
},
|
||||
): Map<string, boolean> => {
|
||||
const shown = renderStateEntity(entity, view, check.volatile, observed);
|
||||
const outcomes = new Map<string, boolean>();
|
||||
for (const [tool, fields] of check.writes) {
|
||||
const compared = (fields ?? []).filter(
|
||||
(field) =>
|
||||
!check.volatile.has(field) &&
|
||||
(Object.hasOwn(observed, field) || Object.hasOwn(shown, field)),
|
||||
);
|
||||
if (fields === null || compared.length === 0) continue;
|
||||
outcomes.set(
|
||||
tool,
|
||||
compared.every((field) => same(shown[field], observed[field])),
|
||||
);
|
||||
}
|
||||
return outcomes;
|
||||
};
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
BOOK_ROWS,
|
||||
BOOK_WRITE_CLOCK,
|
||||
FIRST_BOOK,
|
||||
LIST_LINE_ROWS,
|
||||
SECOND_BOOK,
|
||||
THIRD_BOOK,
|
||||
book,
|
||||
@@ -541,3 +542,65 @@ describe("observation from a later read", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("list lines", () => {
|
||||
it("lists every entity on a line that lists its whole collection, though another line of the tool is filtered", () => {
|
||||
const state = stateOf(LIST_LINE_ROWS);
|
||||
expect(state.views.find((view) => view.tool === "get_books")).toMatchObject(
|
||||
{
|
||||
shape: "list",
|
||||
pointer: "/content",
|
||||
membership: "recorded",
|
||||
all_record_ordinals: [0],
|
||||
counters: ["numberOfElements", "totalElements"],
|
||||
checked_record_ordinals: [0, 1],
|
||||
},
|
||||
);
|
||||
// The whole list after the create shows the created book, which confirms it.
|
||||
expect(planOf(state, "post_books")).toMatchObject({
|
||||
served: true,
|
||||
checked_record_ordinals: [5, 6],
|
||||
});
|
||||
});
|
||||
|
||||
it("confirms no create by a whole list taken after a read showed its entity gone", () => {
|
||||
const rows: TimedCaptureRow[] = [
|
||||
...BOOK_INIT_ROWS,
|
||||
["POST", "/api/books", THIRD_BOOK, 201, { name: "Third Book" }],
|
||||
// A redirected delete is not modelled; the read after it shows the book gone.
|
||||
["DELETE", "/api/books/3", "", 302],
|
||||
["GET", "/api/books/3", BOOK_NOT_FOUND, 404],
|
||||
["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]],
|
||||
];
|
||||
expect(planOf(stateOf(rows), "post_books")).toMatchObject({
|
||||
served: false,
|
||||
reason: "unconfirmed",
|
||||
});
|
||||
});
|
||||
|
||||
it("confirms no create by a whole list after an item read showed nothing of its entity", () => {
|
||||
const rows: TimedCaptureRow[] = [
|
||||
...BOOK_INIT_ROWS,
|
||||
["POST", "/api/books", THIRD_BOOK, 201, { name: "Third Book" }],
|
||||
// An unmodelled write elsewhere may explain the next read, which the state then takes.
|
||||
["POST", "/api/exports", { queued: true }, 202, { format: "csv" }],
|
||||
["GET", "/api/books/3", null],
|
||||
["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]],
|
||||
];
|
||||
expect(planOf(stateOf(rows), "post_books")).toMatchObject({
|
||||
served: false,
|
||||
checked_record_ordinals: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("names no line when every line lists its whole collection, or none does", () => {
|
||||
const listOf = (rows: readonly TimedCaptureRow[]) =>
|
||||
stateOf(rows).views.find((view) => view.tool === "get_books");
|
||||
const whole = listOf(LIST_LINE_ROWS.filter((_, index) => index !== 1));
|
||||
expect(whole).toMatchObject({ membership: "all" });
|
||||
expect(whole).not.toHaveProperty("all_record_ordinals");
|
||||
expect(listOf(LIST_LINE_ROWS.slice(1))).not.toHaveProperty(
|
||||
"all_record_ordinals",
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user