perf: refuse a cursor of another read before the render (#1761)

## What

A read cursor now carries a short read tag. The tag is a digest of the
part of the scope that a read knows before it renders: the session, the
config folder, the protocol, the client capabilities, the adapter
version, the filters, and whether the read is a child read. A read
compares the tag first. A cursor of a status, root or child read, of
other filters, or of another session gets the same `-32602`
`invalid_cursor` error as before, but without a render of the history.

The working directory and a child's stream are still checked after the
render, as before. So another child's cursor in a child read is refused
only after the render, because the read must find the child's stream
first.

This is the first PR of a stack above #1754.

## Why

Finding 3 of the live probe in the #1754 review: a status cursor in a
full read took 6.1 s on a 131 MB session, because the adapter rendered
the history before it compared the cursor.

Synthetic session: a 100 MB root and 8 subagents of 5 MB, v1 with AIR
native subagent sessions, Node, median of 5.

| Poll | #1754 | this PR |
|---|---|---|
| Status cursor in a full read | 1471 ms | < 1 ms |
| Full cursor in a status read | 1029 ms | < 1 ms |

## Tests

- `npm run build` and `npm run check` pass.
- `npm run test:run`: 5086 passed. The same 34 tests fail on #1754 in
this environment (16 in `create-session-options`, 13 in `providers`, 5
provider tests in `v2/acp-v2`).
- `src/tests/session-read.test.ts`: a status cursor in a full read, a
full cursor in a status read, a full cursor in a child read, a child
cursor in a full read and a cursor of another session are refused as
`invalid_cursor`, with no replay and nothing sent. These 5 cases fail
without the change.

## Known issues

- The cursor has a new segment, so a cursor of an earlier adapter is
refused as `invalid_cursor`. The adapter version was already in the
scope, so cursors did not survive an upgrade before either.
This commit is contained in:
Slapoguzov Alexander
2026-12-04 21:38:37 +01:00
committed by GitHub
parent f597600e91
commit 173debc43d
3 changed files with 66 additions and 5 deletions

View File

@@ -26,7 +26,7 @@ By default each read renders the root and the whole transcript of every subagent
### Filters
The optional `filters` object of a read says what the read sends. Its only key is `subagents`: `"full"`, the default, or `"status"`. A read without `filters`, or with `filters.subagents: "full"`, is the default read and shares its cursor. The keys that an adapter supports are the keys of `_meta.sessionRead.filters` in its initialize response. A read with another key, or with another value of `subagents`, returns `-32602` with `data.reason: "unsupported_filter"` and the refused keys in `data.filters`, so that a client never gets more than it asked for. A cursor belongs to the filters of the read that returned it: a read with other filters refuses it as `invalid_cursor`.
The optional `filters` object of a read says what the read sends. Its only key is `subagents`: `"full"`, the default, or `"status"`. A read without `filters`, or with `filters.subagents: "full"`, is the default read and shares its cursor. The keys that an adapter supports are the keys of `_meta.sessionRead.filters` in its initialize response. A read with another key, or with another value of `subagents`, returns `-32602` with `data.reason: "unsupported_filter"` and the refused keys in `data.filters`, so that a client never gets more than it asked for. A cursor belongs to the filters of the read that returned it: a read with other filters refuses it as `invalid_cursor`. A read refuses a cursor of another session, of a read with other filters, or of a root read in a child read and the other way around, before it renders the history, so the refusal is fast also on a large session.
### Status read
@@ -118,7 +118,7 @@ Send the root session and one child session id that the client got:
The response and the updates are those of a root read, restricted to the child's stream: every update has the child's session id, including the `cursor_update` and, on v2, the `replay_complete`. They are the updates of that stream in a default read. A child read sends no title. The child id can be the agent id, the agent id with a `:generation:<n>` suffix of a live child, or AIR's `<root>:replay-subagent:<launch id>`. All ids of one child share its stream and cursor.
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child used a tool other than Bash, PowerShell, Read, Write, Edit, Glob, Grep or SubagentHandback.
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A root cursor is refused before the render, another child's only after it, because the read must find the child's stream first. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child used a tool other than Bash, PowerShell, Read, Write, Edit, Glob, Grep or SubagentHandback.
A child that was just launched and has no transcript yet has no records on its stream: its read returns no cursor until the first record is written. Poll it from the start until then. Cached cursors of child reads and of root reads share one limit of 32 per connection; the oldest is dropped first, and its next read renders again.

View File

@@ -507,14 +507,16 @@ function digest(value: string) {
// A cursor carries the number of delivered updates per session. Its digest binds
// those counts to the rendering options, exact history prefixes and post-replay metadata.
// Its read tag names the read that returned it (see `readTag`).
const lengths = z.record(z.string(), z.int().nonnegative());
const CURSOR = /^read:v1:[\w-]{43}\.([\w-]{16})\.([\w-]+)$/;
function decodeLengths(id: string): Map<string, number> {
const match = /^read:v1:[\w-]{43}\.([\w-]+)$/.exec(id);
const match = CURSOR.exec(id);
if (match) {
try {
return new Map(
Object.entries(
lengths.parse(JSON.parse(Buffer.from(match[1]!, "base64url").toString("utf8"))),
lengths.parse(JSON.parse(Buffer.from(match[2]!, "base64url").toString("utf8"))),
),
);
} catch {
@@ -524,11 +526,29 @@ function decodeLengths(id: string): Map<string, number> {
throw invalidCursor();
}
/**
* The tag of the cursors of a read: the part of its scope that is known
* before the render. Its session, the config folder, the protocol, the
* client capabilities, the adapter version, its filters and whether it reads
* a child. A cursor with another tag cannot continue the read, so it is
* refused without a render. The rest of the scope (the working directory and
* a child's stream) is checked after the render.
*/
function readTag(scope: unknown[]): string {
return digest(json(scope)).slice(0, 16);
}
/** The read tag of `cursorId`, undefined when it is no cursor of this adapter. */
function tagOf(cursorId: string): string | undefined {
return CURSOR.exec(cursorId)?.[1];
}
function snapshot(
frames: SessionReadFrame[],
root: string,
protocol: 1 | 2,
scope: string,
tag: string,
previous?: string,
historyEnd = frames.length,
/** `root` is a child's stream, whose entities name their launch. */
@@ -586,7 +606,8 @@ function snapshot(
hashes.set(id, prefix ? stream.prefix : stream.history.copy().digest("base64url"));
}
const encoded = Buffer.from(json(Object.fromEntries(counts))).toString("base64url");
return "read:v1:" + digest(json([scope, encoded, Object.fromEntries(hashes)])) + "." + encoded;
const hash = digest(json([scope, encoded, Object.fromEntries(hashes)]));
return `read:v1:${hash}.${tag}.${encoded}`;
}
if (previous && cursor(true) !== previous) throw invalidCursor();
@@ -722,6 +743,15 @@ export class SessionReads {
...(status ? [{ filters: { subagents: "status" } }] : []),
...(stream === undefined ? [] : [stream]),
]);
// Root, status and child reads, and reads with other filters, refuse each other's cursors.
const tag = readTag([
sessionId,
claudeConfigDir(),
options.protocol,
options.capabilities,
packageJson.version,
status ? "status" : subagent !== undefined ? "subagent" : "full",
]);
const replay = async () => {
try {
const view = await options.replay(sessionId, cwd, useCursor, readScope);
@@ -789,6 +819,8 @@ export class SessionReads {
return cursorId ? { cursorId } : {};
};
try {
// Before the render, which can take seconds on a large session.
if (cursor !== undefined && tagOf(cursor) !== tag) throw invalidCursor();
const cached = cursor ? this.checkpoints.get(key) : undefined;
if (
cached &&
@@ -815,6 +847,7 @@ export class SessionReads {
streamId,
options.protocol,
scope,
tag,
cursor,
historyEnd,
stream !== undefined,

View File

@@ -67,6 +67,34 @@ describe("session read cursors", () => {
expect(options.send).not.toHaveBeenCalled();
});
it.each([
["a status read in a full read", { filters: { subagents: "status" } }, {}],
["a full read in a status read", {}, { filters: { subagents: "status" } }],
["a full read in a child read", {}, { subagentSessionId: "child" }],
["a child read in a full read", { subagentSessionId: "child" }, {}],
["another session", {}, { sessionId: "other" }],
] as const)("refuses a cursor from %s before it renders", async (_name, first, other) => {
const options = {
...reader([message("1")]),
subagents: true,
replay: vi.fn(async (_id: string, cwd = "/project", _observe: boolean, scope: object) => ({
frames: [message("1")],
cwd,
...("subagentSessionId" in scope ? { stream: "root" } : {}),
})),
};
const reads = new SessionReads();
const { cursorId } = await reads.read({ ...start, ...first }, options);
expect(cursorId).toBeTruthy();
options.replay.mockClear();
options.send.mockClear();
await expect(reads.read({ ...poll(cursorId), ...other }, options)).rejects.toMatchObject(
invalid,
);
expect(options.replay).not.toHaveBeenCalled();
expect(options.send).not.toHaveBeenCalled();
});
it("keeps the previous cursor usable when the confirmation replay changes or a file cannot be read", async () => {
const options = reader([message("1")]);
const reads = new SessionReads();