Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6c8f4f7
feat(environment): render more read tools from the state and describe…
cursoragent Oct 21, 2026
378a109
fix(environment): keep rendered documents and quoted samples inside t…
cursoragent Oct 21, 2026
cfb42dd
feat(environment): apply evidence-gated write effects to the served s…
cursoragent Oct 21, 2026
5d0e096
fix(environment): bound and validate write state history
morluto Oct 21, 2026
5b42469
feat(environment): render more read tools from the state and describe…
cursoragent Oct 21, 2026
54c8934
fix(environment): keep rendered documents and quoted samples inside t…
cursoragent Oct 21, 2026
19b50ea
feat(environment): apply evidence-gated write effects to the served s…
cursoragent Oct 21, 2026
a057ea9
fix(environment): bound and validate write state history
morluto Oct 21, 2026
f79f1e1
fix(environment): bound additional collection history
morluto Oct 21, 2026
4a678f1
Merge remote-tracking branch 'live-5600/feat/environment-state-writes…
morluto Oct 21, 2026
7de20bc
fix(environment): credit sent fields, negative sequences, and encoded…
cursoragent Oct 21, 2026
a1076ca
Merge live environment write verification fixes
morluto Oct 21, 2026
d3015d2
test(environment): cover resolved encoded update identities
morluto Oct 21, 2026
cddd3e6
fix: validate timed update observations
morluto Oct 21, 2026
fb6785d
fix(environment): share write overlap and check clocks on earlier calls
cursoragent Oct 21, 2026
d7c5c62
merge: restack environment state writes onto main after #5352
cursoragent Oct 21, 2026
3b34bbd
fix: preserve partial update evidence
morluto Oct 21, 2026
5d00ff3
Merge remote-tracking branch 'live-5600/feat/environment-state-writes…
morluto Oct 21, 2026
717ac2c
chore: merge main (8413ec08) into environment state writes
earakely-scale Oct 21, 2026
e923fc7
fix(environment): let an unmodelled write explain only the list membe…
earakely-scale Oct 21, 2026
75d7bb0
fix(environment): explain added fields, tie creates to serving's coll…
earakely-scale Oct 21, 2026
cd26a76
docs(environment): state how list reads weigh unmodelled writes, adde…
earakely-scale Oct 22, 2026
2a125b7
chore: merge main (4a4bbab3) into environment state writes
earakely-scale Oct 22, 2026
11e3f01
refactor(environment): keep the observing view helpers with the obser…
earakely-scale Oct 22, 2026
53a7866
fix(environment): resolve unmodelled writes onto the held collection
cursoragent Oct 22, 2026
329aeed
fix(environment): confirm no write through volatile fields or overwri…
earakely-scale Oct 22, 2026
ccdf091
fix(environment): leave unknown entities unchecked by failed reads, v…
earakely-scale Oct 22, 2026
1c97933
fix(environment): fill a create's path fields from the collection ser…
earakely-scale Oct 22, 2026
90d9022
fix(environment): name unmodelled writes as modelled ones, count fiel…
earakely-scale Oct 22, 2026
756c631
fix(environment): let a document replacement overwrite everything und…
earakely-scale Oct 22, 2026
3f1f825
chore: merge the published environment state writes (756c6312)
earakely-scale Oct 22, 2026
4bc6002
fix(environment): start the served clock from the records whose times…
earakely-scale Oct 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(environment): bound and validate write state history
  • Loading branch information
morluto authored and cursoragent committed Oct 21, 2026
commit a057ea978497a87c67ab22eb4d35971c780062ca
52 changes: 51 additions & 1 deletion src/application/environment/environmentState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ import {
prepareServedState,
} from "./environmentState.js";
import { STATE_INTAKE_LIMIT_BYTES } from "./environmentStateDocument.js";
import { EnvironmentStateStore } from "./environmentStateStore.js";
import {
EnvironmentStateStore,
ENVIRONMENT_COLLECTION_HISTORY_LIMIT_BYTES,
} from "./environmentStateStore.js";

const fixture = environmentStateServeFixture();
const { source, state } = environmentStateServeInputs(fixture);
Expand Down Expand Up @@ -151,6 +154,53 @@ describe("loadEnvironmentState", () => {
});
});

describe("served collection history", () => {
it("refuses a new collection before retained collection and sequence history exceeds its budget", () => {
const store = new EnvironmentStateStore(state);
const original = state.entities[0];
if (original === undefined) throw new Error("Expected a seeded entity");
let refused: ReturnType<typeof store.insert> | undefined;
for (let index = 0; index < 2000; index += 1) {
const before = JSON.stringify(store.snapshot());
const result = store.insert(
{
...original,
collection: `/api/history/${String(index)}-${"x".repeat(900)}`,
id: `history-${String(index)}`,
},
0,
);
if (!result.ok) {
refused = result;
expect(JSON.stringify(store.snapshot())).toBe(before);
break;
}
const inserted = store.entity(
original.type,
`/api/history/${String(index)}-${"x".repeat(900)}`,
`history-${String(index)}`,
);
if (inserted === undefined) throw new Error("Expected inserted entity");
store.remove(inserted);
}
expect(refused?.ok).toBe(false);
if (refused?.ok !== false)
throw new Error("Expected a history budget refusal");
expect(refused.error).toMatchObject({
resource: "capacity",
retryable: false,
reportedLimits: {
collection_history_bytes: expect.any(Number),
max_collection_history_bytes:
ENVIRONMENT_COLLECTION_HISTORY_LIMIT_BYTES,
},
remediationAction: expect.stringContaining("Reset the served state"),
});
expect(refused.error.reason).toContain("retained metadata budget");
expect(store.knownCollectionsOf(original.type).length).toBeLessThan(2000);
});
});

describe("deriveEnvironmentState", () => {
it("derives the state inspect-analysis-view projects from the capture with the manifest's rules, under the same Evidence id", () => {
const derived = deriveEnvironmentState(source, fixture.capture);
Expand Down
3 changes: 2 additions & 1 deletion src/application/environment/environmentStateCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export const createdCollection = (
type: string,
): string | undefined => {
const segments = callSegments(tool, args);
if (segments === undefined) return undefined;
if (segments === undefined || segments.some(({ text }) => text.length === 0))
return undefined;
// The spelling the call supplies verbatim wins, as item calls choose their entity, then the first known: held ones lead.
let held: string | undefined;
let verbatim = -1;
Expand Down
64 changes: 63 additions & 1 deletion src/application/environment/environmentStateStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,34 @@ import {
type StateContent,
} from "./environmentStateDocument.js";

/** Bound estimated collection and sequence-key metadata retained after served creates are deleted. */
export const ENVIRONMENT_COLLECTION_HISTORY_LIMIT_BYTES = 1024 * 1024;

const collectionHistoryCost = (
state: EnvironmentState,
type: string,
collection: string,
): number => {
const sequenceKeys = new Set<string>();
for (const plan of state.writes.values()) {
if (!plan.served || plan.target !== type) continue;
for (const rule of plan.rules) {
if (rule.rule === "sequence" && rule.scope === "collection")
sequenceKeys.add(`${plan.tool} ${rule.field} ${collection}`);
else if (rule.rule === "identity" && rule.generator === "sequence")
sequenceKeys.add(`${type} ${rule.field} ${collection}`);
}
}
return (
64 +
Buffer.byteLength(collection, "utf8") +
[...sequenceKeys].reduce(
(bytes, key) => bytes + 64 + Buffer.byteLength(key, "utf8"),
0,
)
);
};

/** What `data/get` reports: the current state as a `rea-state/v1` document. */
export interface StateSnapshot {
readonly rea_state: {
Expand Down Expand Up @@ -91,6 +119,8 @@ export class EnvironmentStateStore {
#started: readonly StateEntity[] = [];
/** Every collection spelling a type's entities have been held under since the last reset or load, kept when a collection empties. */
readonly #knownCollections = new Map<string, string[]>();
/** Estimated retained collection and sequence-key metadata, reset with the serving history. */
#collectionHistoryBytes = 0;
/** The collections of the Evidence's own state, which stay known after any load. */
#evidenceCollections: ReadonlyMap<string, readonly string[]> = new Map();

Expand Down Expand Up @@ -176,6 +206,7 @@ export class EnvironmentStateStore {
this.#started = this.#content.entities;
// A reset or load knows the Evidence's spellings and its own, never those of a state it replaced.
this.#knownCollections.clear();
this.#collectionHistoryBytes = 0;
this.#remember(this.#evidenceCollections);
this.#remember(this.#typeCollections);
}
Expand All @@ -184,7 +215,14 @@ export class EnvironmentStateStore {
for (const [type, collections] of named) {
const known = this.#knownCollections.get(type) ?? [];
for (const collection of collections)
if (!known.includes(collection)) known.push(collection);
if (!known.includes(collection)) {
known.push(collection);
this.#collectionHistoryBytes += collectionHistoryCost(
this.state,
type,
collection,
);
}
this.#knownCollections.set(type, known);
}
}
Expand All @@ -209,6 +247,30 @@ export class EnvironmentStateStore {
jsonBytes(entity) + (entities.length > 0 ? 1 : 0),
);
if (!bytes.ok) return bytes;
const known = this.#knownCollections.get(entity.type) ?? [];
if (!known.includes(entity.collection)) {
const historyBytes =
this.#collectionHistoryBytes +
collectionHistoryCost(this.state, entity.type, entity.collection);
if (historyBytes > ENVIRONMENT_COLLECTION_HISTORY_LIMIT_BYTES)
return err(
new AnalysisResourceConstraintError(
ENVIRONMENT_SERVE_OPERATION,
"capacity",
"Served collection and sequence history would exceed its retained metadata budget",
{
max_collection_history_bytes:
ENVIRONMENT_COLLECTION_HISTORY_LIMIT_BYTES,
collection_history_bytes: historyBytes,
},
{
retryable: false,
remediationAction:
"Reset the served state to clear collection history, then use fewer distinct collection paths.",
},
),
);
}
const members = this.inCollection(entity.type, entity.collection);
const anchor =
index < members.length
Expand Down
19 changes: 19 additions & 0 deletions src/application/environment/environmentStateWriteAnswer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,6 +536,25 @@ describe("collections a create chooses", () => {
?.collection,
).toBe("/api/orgs/acme1/books");
});

it("refuses an empty parent segment before storing an unreadable collection", () => {
const books = servedFrom(ROWS);
const tool = books.source.manifest.tools.find(
(candidate) => candidate.method === "POST",
)!;
const [org] = environmentToolArguments(tool).path.values();
const before = books.snapshot();
expect(
books.refusal(tool.name, { [org!]: "", body: { name: "Invalid" } }),
).toMatchObject({
code: "invalid_request",
message: expect.stringContaining("path argument to be non-empty"),
});
expect(books.snapshot()).toBe(before);
expect(
books.store.knownCollectionsOf("/api/orgs/{org}/books"),
).not.toContain("/api/orgs//books");
});
});

describe("missing entities after a delete", () => {
Expand Down
7 changes: 6 additions & 1 deletion src/application/environment/environmentStateWriteAnswer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,12 @@ const answerCreate = (
);
const observed = observedEntity(serving, plan);
if (collection === undefined || observed === undefined)
return err(refused(tool, `Tool ${tool.name} needs every path argument.`));
return err(
refused(
tool,
`Tool ${tool.name} needs every path argument to be non-empty.`,
),
);
if (plan.collection !== null && plan.collection !== collection)
return err(
refused(
Expand Down
58 changes: 58 additions & 0 deletions src/domain/analysisView/EnvironmentStateWriteSimulation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,32 @@ describe("what a check leaves pending", () => {
});
});

it("checks only a partial update's fields that remain after a later overwrite", () => {
const patched = described(1, "Patched", "survives");
const replaced = described(1, "Replaced", "survives");
const changedByOtherAction = described(1, "Archived", "survives");
const rows: TimedCaptureRow[] = [
["GET", "/api/books", summary([FIRST_BOOK, SECOND_BOOK])],
["GET", "/api/books/1", described(1, "First Book", "original")],
["GET", "/api/books/2", described(2, "Second Book", "other")],
[
"PATCH",
"/api/books/1",
patched,
200,
{ name: "Patched", description: "survives" },
],
["PUT", "/api/books/1", replaced, 200, { name: "Replaced" }],
["POST", "/api/books/1/archive", changedByOtherAction, 204, {}],
["GET", "/api/books/1", changedByOtherAction],
];
expect(gated(rows, "patch_books_by_id")).toMatchObject({
served: true,
checked_record_ordinals: [6],
contradicted_by: null,
});
});

it("neither resynchronises nor checks an entity by a read begun while a write to it still ran", () => {
const rows: TimedCaptureRow[] = [
["GET", "/api/books", [FIRST_BOOK, SECOND_BOOK]],
Expand Down Expand Up @@ -880,6 +906,38 @@ describe("what a check leaves pending", () => {
});

describe("what a later call must follow", () => {
it("rejects a later create whose unique field repeats a value already held", () => {
const existing = {
id: "123e4567-e89b-42d3-a456-426614174000",
ref: "223e4567-e89b-42d3-a456-426614174000",
name: "Existing",
};
const first = {
id: "323e4567-e89b-42d3-a456-426614174000",
ref: "423e4567-e89b-42d3-a456-426614174000",
name: "First",
};
const duplicate = {
id: "523e4567-e89b-42d3-a456-426614174000",
ref: first.ref,
name: "Second",
};
const rows: TimedCaptureRow[] = [
["GET", "/api/items", [existing]],
["GET", `/api/items/${existing.id}`, existing],
["POST", "/api/items", first, 201, { name: "First" }],
["GET", `/api/items/${first.id}`, first],
["GET", "/api/items", [existing, first]],
["POST", "/api/items", duplicate, 201, { name: "Second" }],
["GET", `/api/items/${duplicate.id}`, duplicate],
["GET", "/api/items", [existing, first, duplicate]],
];
expect(gated(rows, "post_items")).toMatchObject({
served: false,
reason: "unexplained-change",
});
});

it("refuses a create whose later call does not follow the sequence it learned", () => {
const ranked = (at: Book, rank: number) => ({ ...at, rank });
const third = ranked(book(3, "Third Book", bookClock(3)), 3);
Expand Down
6 changes: 4 additions & 2 deletions src/domain/analysisView/environmentStateWriteAttribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,10 @@ export class WriteEffects {
const own = this.#changed.get(at.entity);
for (const [tool, claim] of own ?? []) {
const left = tool === at.writer ? claim : remaining(claim, write);
if (left !== undefined) own!.set(tool, left);
else {
if (left !== undefined) {
own!.set(tool, left);
if (tool !== at.writer) touched.get(at.entity)?.set(tool, left);
Comment thread
morluto marked this conversation as resolved.
Resolved
} else {
own!.delete(tool);
touched.get(at.entity)?.delete(tool);
Comment thread
morluto marked this conversation as resolved.
Resolved
}
Expand Down
11 changes: 8 additions & 3 deletions src/domain/analysisView/environmentStateWriteCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,10 +199,15 @@ const followsGenerated = (
return (
JSON.stringify(readClock(value)?.format) === JSON.stringify(rule.format)
);
if (rule.rule === "unique")
return (
isUuid(value) &&
!context.state
.ofType(created.type)
.some((held) => held.fields[rule.field] === value)
);
return (
(rule.rule !== "unique" &&
(rule.rule !== "identity" || rule.generator !== "uuid")) ||
isUuid(value)
rule.rule !== "identity" || rule.generator !== "uuid" || isUuid(value)
);
}) && followsSequences(context, draft, created);

Expand Down
Loading