Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
ad439bd
feat(environment): extract the initial state a capture's reads observed
earakely-scale Oct 20, 2026
7a668b7
Merge main into feat/environment-state-view
earakely-scale Oct 20, 2026
f2c9a2e
fix(environment): bound state at redacted writes; infer identity only…
earakely-scale Oct 20, 2026
2999128
fix(environment): keep first sightings, one list pointer and linear f…
earakely-scale Oct 20, 2026
a5c7b92
fix(environment): keep post-write values and partial lists out of the…
kaoru0822-kitauji Oct 20, 2026
4e93547
docs(environment): scope item-shaped and deleted written paths out of…
kaoru0822-kitauji Oct 20, 2026
aba9cb1
fix(environment): count writes in flight when a value changes between…
kaoru0822-kitauji Oct 20, 2026
856c8c0
Merge main into feat/environment-state-view
kaoru0822-kitauji Oct 20, 2026
55480bd
chore: merge main (5fa4defc) into environment state view
earakely-scale Oct 20, 2026
9fee36d
fix(environment): catch cross-tool changes across writes; read only i…
earakely-scale Oct 20, 2026
3c64cbe
chore: merge the branch's own main merge (856c8c0b), identical to 554…
earakely-scale Oct 20, 2026
47f8a27
chore: merge main (f93a0335, rich captures) into environment state view
earakely-scale Oct 20, 2026
32fbaa5
chore: merge main into environment state view
gensokyo-dev Oct 20, 2026
04e2c56
fix(environment): keep post-write observations out of initial state
gensokyo-dev Oct 20, 2026
3daeebb
chore: retain author main integration in environment state view
gensokyo-dev Oct 20, 2026
25923c3
chore: sync environment state view with latest main
gensokyo-dev Oct 20, 2026
6ad63bc
fix(environment): retain field provenance and bound state inference work
gensokyo-dev Oct 20, 2026
2bd0b3c
feat(environment): serve tool calls from the environment state
earakely-scale Oct 20, 2026
9f60e54
Merge the environment state view's review fixes into feat/environment…
earakely-scale Oct 20, 2026
cb04dcd
docs(environment): record verification after merging the state view's…
earakely-scale Oct 20, 2026
e96484b
Merge main (#5319 squashed, #5349) into feat/environment-state-serve
earakely-scale Oct 20, 2026
6676582
feat(environment)!: serve the environment state by default
earakely-scale Oct 20, 2026
83fcc73
fix(environment): bound data-plane replies, keep batch order, cancel …
earakely-scale Oct 20, 2026
d9c0357
fix(environment): keep bodies too deep for the state's nesting out of…
earakely-scale Oct 20, 2026
57b1168
fix(environment): measure data-plane replies before building them
earakely-scale Oct 20, 2026
5956e00
chore: merge main (d2a3269d) into environment state serve
earakely-scale Oct 20, 2026
5a61853
fix(environment): release batch replies as they are encoded; judge ex…
earakely-scale Oct 20, 2026
c00fde4
fix(environment): keep room for refusals and framing in the reply budget
earakely-scale Oct 20, 2026
25b6622
chore: merge main (335c042d) into environment state serve
earakely-scale Oct 21, 2026
6b8db19
fix(environment): refuse a loaded state that data/get would write pas…
earakely-scale Oct 21, 2026
31a618e
chore: merge main (d9767eb4) into environment state serve
cursoragent Oct 21, 2026
96ce6c6
fix(environment): keep merged export checks on the shared test graph
cursoragent Oct 21, 2026
bfe9d4b
chore: merge main into environment state serve
morluto Oct 21, 2026
0da8e23
fix(environment): keep a state file whose close failed owned until it…
earakely-scale Oct 21, 2026
98a7511
fix(environment): attempt all state cleanup on close
morluto Oct 21, 2026
d681bfd
fix(environment): bound wide state JSON traversal
morluto Oct 21, 2026
e4a0fc6
chore: merge current main into state server fixes
morluto Oct 21, 2026
467828e
fix(environment): scope cached state reply sizes to requests
morluto Oct 21, 2026
05deae3
fix(domain): preserve JSON depth diagnostic guidance
morluto Oct 21, 2026
7c3d0e9
chore: merge current main into state server fixes
morluto Oct 21, 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): keep a state file whose close failed owned until it…
… closes

A file:// data/add that could not close its descriptor dropped the handle,
and an admission failure whose cleanup close failed dropped its owner, so
nothing could retry the close or report it.

The read now runs through withOwnedRegularFile, and a failed close is
retained in a server-lifetime ArtifactResourceScope. The next file read
retries it first and answers -32000 while it is still open; inline and
https documents still load. Closing the served environment retries it again
and rejects with the unfinished close.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
earakely-scale and claude committed Oct 21, 2026
commit 0da8e2357a36023d3effe2fc08a57606c55d6f24
6 changes: 6 additions & 0 deletions docs/agent-environments.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,12 @@ are answered `-32000` with `error.data.reason` `cancelled` without running. A
cancelled call leaves the state unchanged, and shutdown never waits for a
download.

A `file://` state file whose close fails stays owned by the server, and
the `data/add` gets `-32000`. The next `file://` load retries that close first
and, while it still fails, answers `-32000` without reading another file;
inline and `https://` documents still load. Closing the server retries it once
more and fails with the unfinished close rather than dropping the descriptor.

One `/agentenv` response carries at most 64 MiB of replies, twice the 32 MiB
a loaded document may hold: room for a `data/get` of a loaded state, while a
batch of reads cannot multiply a large state into one body. Replies are
Expand Down
7 changes: 6 additions & 1 deletion docs/specs/agent-environments/state-serve/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ this increment: write tools are not served from the state.
download in progress ends with reason `cancelled`, queued calls are answered
`-32000` with reason `cancelled` without running, and a `data/add` whose
file read finished after the cancellation does not replace the state.
- A `file://` read whose descriptor close fails answers `-32000` and keeps the
descriptor in a server-lifetime owner. The next file read retries the close
first and, while it still fails, answers `-32000` without opening the file.
`close` retries it again and rejects while it is still open.
- Bound one `/agentenv` response to 64 MiB of replies (twice the intake
limit). Each reply is measured in bounded JSON parts as it is produced, in
message order, and assembled only when it fits, so a reply past the budget is
Expand Down Expand Up @@ -172,7 +176,8 @@ host or a UNC path, injected https downloads (status, declared and streamed
size, the timeout whether or not the fetcher honours its signal), the default
fetch's refused redirects, arrival-order application across requests, a batch
another request's reset cannot split, cancellation by the server's stop and by
a departed caller, a server that closes while a download is stalled, the
a departed caller, a server that closes while a download is stalled, a
retained state-file close that the next file read and `close` retry, the
response budget, batches and notifications, the card declaration, absent write
tools, a served query `POST`, the per-mode discovery reservation and a
`data/add` that changes the next tool answer over MCP. The mcp-boundary tests serve the state the
Expand Down
7 changes: 7 additions & 0 deletions docs/specs/agent-environments/state-serve/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ The review fixes are covered by these tests, all passing in the runs above:
unchanged. Over loopback HTTP, `close()` of a served state returned while a
download that never answers was in progress, and that download's signal was
aborted.
- File closes: with an injected close failure, `data/add` of a `file://` uri
answered `-32000` without echoing the uri. The descriptor stayed open, and
the next file load closed it before loading. While the close kept failing,
over loopback HTTP the next file load answered `-32000` ("still open") and
an inline `data` part still loaded. `close()` rejected with the unfinished
close, then resolved and closed the descriptor once the close succeeded.
Both tests fail on the previous head, which dropped the descriptor.
- File hosts: `file://remote.example.test/...` and
`file:////remote.example.test/...` are refused with the network-share
message and no failure category; a `file://localhost/...` uri loads.
Expand Down
14 changes: 9 additions & 5 deletions src/server/environment/environmentDataPlane.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { EnvironmentStateStore } from "../../application/environment/environmentStateStore.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import {
CANCELLED,
Expand Down Expand Up @@ -39,22 +40,23 @@ const documentError = (error: AnalysisInputError): RpcError => {
);
};

/** What one queued call runs with: the live state, how documents arrive and what cancels it. */
/** What one queued call runs with: the live state, how documents arrive, what cancels it and who owns file descriptors whose close failed. */
interface CallContext {
readonly store: EnvironmentStateStore;
readonly intake: StateIntake;
readonly cancel: AbortSignal;
readonly files: ArtifactResourceScope;
}

/** `data/add`: exactly one part, whose document replaces the whole state only when it is valid and the call was not cancelled. */
const addState = async (
{ store, intake, cancel }: CallContext,
{ store, intake, cancel, files }: CallContext,
params: unknown,
): Promise<RpcOutcome> => {
const parts = isRecord(params) ? params.parts : undefined;
if (!Array.isArray(parts) || parts.length !== 1)
return { error: invalidParams("data/add takes exactly one part") };
const document = await partDocument(parts[0], intake, cancel);
const document = await partDocument(parts[0], intake, cancel, files);
if (!document.ok) return { error: document.error };
// A file read is not interruptible, so a cancellation during it is honoured here, before the state changes.
if (cancel.aborted) return { error: CANCELLED };
Expand Down Expand Up @@ -91,12 +93,14 @@ const METHODS: ReadonlyMap<string, Method> = new Map<string, Method>([
* at a time in the order they are made, across requests, so a slow load never
* overwrites a later reset and at most one loaded document is parsed at once.
* Once `stopped` or a call's own signal aborts, its download ends and a call
* not yet run is answered as cancelled.
* not yet run is answered as cancelled. `files` keeps a state file whose close
* failed and retries it before the next file read; its owner closes it at shutdown.
*/
export const stateDataPlane = (
store: EnvironmentStateStore,
intake: StateIntake = DEFAULT_STATE_INTAKE,
stopped: AbortSignal = new AbortController().signal,
files: ArtifactResourceScope = new ArtifactResourceScope(),
): RpcMethods => {
let previous: Promise<unknown> = Promise.resolve();
return (method, params, signal) => {
Expand All @@ -107,7 +111,7 @@ export const stateDataPlane = (
const next = previous.then(() =>
cancel.aborted
? { error: CANCELLED }
: run({ store, intake, cancel }, params),
: run({ store, intake, cancel, files }, params),
);
previous = next.catch(() => undefined);
return next;
Expand Down
9 changes: 7 additions & 2 deletions src/server/environment/serveEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type EnvironmentToolAnswer,
} from "../../application/environment/environmentStateAnswer.js";
import { EnvironmentStateStore } from "../../application/environment/environmentStateStore.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
environmentCard,
REPLAY_CATALOG_INSTRUCTIONS,
Expand Down Expand Up @@ -376,6 +377,8 @@ export const serveEnvironment = async (
const stop = (): void => {
stopping.abort(new Error("The agent environment is stopping"));
};
// A state file whose close failed stays owned here: later file reads retry it, and close reports it if it is still open.
const stateFiles = new ArtifactResourceScope();
const served = await serveStreamableHttp({
host,
port,
Expand All @@ -394,6 +397,7 @@ export const serveEnvironment = async (
: { fetchState: options.fetchState }),
},
stopping.signal,
stateFiles,
),
),
...(logger === undefined ? {} : { logger }),
Expand All @@ -412,9 +416,10 @@ export const serveEnvironment = async (
stop();
return served.prepareShutdown();
},
close: () => {
close: async () => {
stop();
return served.close();
await served.close();
await stateFiles.close();
},
});
};
96 changes: 95 additions & 1 deletion src/server/environment/serveEnvironmentState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";

import { timedCaptureEvidence } from "../../../tests/fixtures/analysisView.js";
import {
Expand All @@ -14,6 +14,8 @@ import {
} from "../../../tests/fixtures/environmentServe.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { EnvironmentStateStore } from "../../application/environment/environmentStateStore.js";
import { ArtifactResourceRetryFailure } from "../../artifacts/ArtifactResourceScope.js";
import { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js";
import {
environmentCard,
STATE_INTAKE_EXTENSION,
Expand Down Expand Up @@ -92,6 +94,33 @@ const dataPlane = (
const loginOf = (store: EnvironmentStateStore) =>
store.entity("/api/users", "/api/users", "2")?.fields.login;

/** The `file://` uri of a fresh file holding the renamed document. */
const renamedStateUri = async (): Promise<string> => {
const root = await createTestTempDirectory("rea-environment-state-close-");
const path = join(root, "state.json");
await writeFile(path, JSON.stringify(renamedDocument()));
return pathToFileURL(path).href;
};

/** Fail every close of the first state file opened while `failing()` holds, recording its owner; restored when the test ends. */
const failFirstFileClose = (failing: () => boolean = () => true) => {
const owners: OwnedFileHandle[] = [];
const close = OwnedFileHandle.prototype.close;
const spy = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockImplementation(async function (this: OwnedFileHandle) {
if (owners.length === 0) owners.push(this);
if (this === owners[0] && failing())
throw new Error("injected state file close failure");
await close.call(this);
});
onTestFinished(async () => {
spy.mockRestore();
for (const owner of owners) if (owner.handle.fd >= 0) await owner.close();
});
return owners;
};

/** A `data/add` message loading the document an https uri names. */
const addByUri = (
id: number,
Expand Down Expand Up @@ -356,6 +385,31 @@ describe("state data plane intake", () => {
});
});

describe("state data plane file closes", () => {
it("keeps a state file whose close failed and closes it before the next file read", async () => {
const plane = dataPlane();
const uri = await renamedStateUri();
let failing = true;
const owners = failFirstFileClose(() => failing);
const failed = await plane.add({ kind: "file", file: { uri } });
expect(failed).toMatchObject({
error: {
code: -32000,
message: expect.stringContaining("could not be closed"),
},
});
expect(JSON.stringify(failed)).not.toContain(uri);
expect(loginOf(plane.store)).toBe("probe");
expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0);
failing = false;
await expect(
plane.add({ kind: "file", file: { uri } }),
).resolves.toMatchObject({ result: {} });
expect(owners[0]?.handle.fd).toBe(-1);
expect(loginOf(plane.store)).toBe("renamed");
});
});

describe("state data plane timing and order", () => {
it("ends a download that outlives its time limit, whether or not the fetcher honours the signal", async () => {
const uri = "https://state.example.test/slow.json?token=secret-token";
Expand Down Expand Up @@ -798,6 +852,46 @@ describe("serveEnvironment with a state", () => {
await answered;
});

it("refuses file reads while an earlier state file stays open, and reports it on close until it closes", async () => {
const environment = await serveState({ source, state });
const uri = await renamedStateUri();
let failing = true;
const owners = failFirstFileClose(() => failing);
const add = async (part: unknown) =>
(
await fetch(new URL(ENVIRONMENT_RPC_PATH, environment.url), {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
jsonrpc: "2.0",
id: 1,
method: "data/add",
params: { parts: [part] },
}),
})
).json();
await expect(add({ kind: "file", file: { uri } })).resolves.toMatchObject({
error: {
code: -32000,
message: expect.stringContaining("could not be closed"),
},
});
await expect(add({ kind: "file", file: { uri } })).resolves.toMatchObject({
error: { code: -32000, message: expect.stringContaining("still open") },
});
// Documents that need no file still load.
await expect(
add({ kind: "data", data: renamedDocument() }),
).resolves.toMatchObject({ result: {} });
await expect(environment.close()).rejects.toBeInstanceOf(
ArtifactResourceRetryFailure,
);
expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0);
failing = false;
await expect(environment.close()).resolves.toBeUndefined();
expect(owners[0]?.handle.fd).toBe(-1);
});

it("serves query POSTs from their recordings and leaves state-changing writes out", async () => {
const environment = await serveState(
environmentStateServeInputs(
Expand Down
Loading
Loading