Skip to content

Commit 4534446

Browse files
authored
feat: bound transcript reads across replacements (#110374)
1 parent 1ca6b6f commit 4534446

32 files changed

Lines changed: 1855 additions & 37 deletions

‎config/knip.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ const rootEntries = [
106106
"scripts/repro/tool-surface-live-bench.ts!",
107107
// Workflow/package-script entrypoints are not imported from production modules.
108108
"scripts/openclaw-cross-os-release-checks.ts!",
109+
"scripts/bench-transcript-cursors.ts!",
109110
"scripts/bench-sqlite-reliability.ts!",
110111
// Docker/manual E2E executables and their nested assertion/probe entrypoints.
111112
"scripts/e2e/*.{js,mjs,ts}!",

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ e9c4398b04d04fead0e46ec618589d8f597a0b6087805ab132138e941b76e190 module/sandbox
276276
f07839f5b8929a179857a0b4b89f8448864078cd5972dd53f9a30e50bf55408d module/session-key-runtime
277277
f59099aa2d536246d4b1297f01bcea66796351a9259debdd45909afeb7a42d86 module/session-store-runtime
278278
b1d0a76337122cb9dbb0c89fbb8bfacc1a88ce689270d3d684019c9a03ce669a module/session-transcript-hit
279-
480e6b526b788bee458ef6e023a8bb53dd3b5a09c11278f8e3424629e43852f5 module/session-transcript-runtime
279+
04c19558a5f27380ea13cadee1e3238729788c18a919fb078b24d2d67d006ecf module/session-transcript-runtime
280280
a8fb87c7c39ec6e874926a311d2306b49843767ee5659e006024c59af822466e module/session-visibility
281281
695971d31b3e16f0bf9b643acc30df312fe94b3c0dfb27a2e6156c8a00b5e261 module/setup
282282
575fe05081bf9edd1c6d886143e4835c218fb8d0641ce148a4a69d3cefcea2ef module/setup-adapter-runtime

‎docs/plugins/sdk-runtime.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,11 @@ two-party event loops that do not go through the shared inbound reply runner.
200200

201201
`formatSqliteSessionFileMarker(...)`, `parseSqliteSessionFileMarker(...)`, and `sqliteSessionFileMarkerMatchesSession(...)` are transitional helpers for code that still receives a legacy field named `sessionFile`. A parsed SQLite marker identifies a live SQLite transcript target; it is not a filesystem path. New APIs should carry typed session identity instead of marker strings.
202202

203-
For transcript reads and writes, import `openclaw/plugin-sdk/session-transcript-runtime` and use `resolveSessionTranscriptIdentity(...)`, `resolveSessionTranscriptTarget(...)`, `readSessionTranscriptEvents(...)`, `readVisibleSessionTranscriptMessageEntries(...)`, `appendSessionTranscriptMessageByIdentity(...)`, `publishSessionTranscriptUpdateByIdentity(...)`, or `withSessionTranscriptWriteLock(...)` with `{ agentId, sessionKey, sessionId }`. These APIs let plugins identify a transcript, read raw events or visible branch-safe message entries, append messages, publish updates, and run related operations under the same transcript write lock without depending on active transcript file paths. `readVisibleSessionTranscriptMessageEntries(...)` returns ordered read metadata; its `seq` field is not a resumable cursor.
203+
For transcript reads and writes, import `openclaw/plugin-sdk/session-transcript-runtime` and use `resolveSessionTranscriptIdentity(...)`, `resolveSessionTranscriptTarget(...)`, `readSessionTranscriptEvents(...)`, `readSessionTranscriptRawDelta(...)`, `readSessionTranscriptVisibleMessageDelta(...)`, `readVisibleSessionTranscriptMessageEntries(...)`, `appendSessionTranscriptMessageByIdentity(...)`, `publishSessionTranscriptUpdateByIdentity(...)`, or `withSessionTranscriptWriteLock(...)` with `{ agentId, sessionKey, sessionId }`. These APIs let plugins identify a transcript, read raw events or visible branch-safe message entries, append messages, publish updates, and run related operations under the same transcript write lock without depending on active transcript file paths. `readVisibleSessionTranscriptMessageEntries(...)` returns ordered read metadata; its `seq` field is not a resumable cursor.
204+
205+
`readSessionTranscriptRawDelta(...)` returns a bounded `page`, `reset`, or `missing` result. Pass the opaque `page.cursor` into the next call. Pure appends preserve the cursor, while transcript replacement returns `reset` with a new bootstrap cursor. Pages default to 1,000 events and 1,000,000 serialized bytes; callers may request up to 10,000 events and 64 MiB. When the next event alone exceeds `maxBytes`, the page is empty and reports `requiredBytes`; retry with at least that byte limit when it is no greater than 64 MiB. Larger individual events require the complete-read API. A cursor identifies position only and never grants access to another session.
206+
207+
`readSessionTranscriptVisibleMessageDelta(...)` provides the same bounded bootstrap-and-resume shape over the host-owned active message projection. It returns messages from oldest to newest, so context engines can drain initial history and persist the opaque cursor as their watermark. Store and return the cursor unchanged; it is a continuation hint, not an authorization credential. Linear appends resume after the last returned message. Transcript replacement, a cursor whose anchor left or moved within the active branch, malformed cursors, and cross-session cursors return `reset` with a fresh bootstrap cursor. The count and byte defaults and caps match the raw delta API. While the active projection is rebuilding after a branch change, the result is `unavailable` with reason `projection_rebuilding`; retry later rather than falling back to an active transcript file.
204208

205209
The legacy whole-store and active transcript file helpers are no longer exported from the plugin SDK. Use the scoped entry helpers for session metadata and the transcript identity helpers for active transcript operations. Archive/support workflows that need file artifacts should use their dedicated archive surfaces instead of active session runtime APIs.
206210

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ usage endpoint failed or returned no usable usage data.
275275
| `plugin-sdk/reply-reference` | `createReplyReferencePlanner` |
276276
| `plugin-sdk/reply-chunking` | Narrow text/markdown chunking helpers |
277277
| `plugin-sdk/session-store-runtime` | Session workflow helpers (`getSessionEntry`, `listSessionEntries`, `patchSessionEntry`, `upsertSessionEntry`), repair/lifecycle helpers (`deleteSessionEntry`, `cleanupSessionLifecycleArtifacts`, `resolveSessionStoreBackupPaths`), marker helpers for transitional `sessionFile` values, bounded recent user/assistant transcript text reads by session identity, session store path/session-key helpers, and updated-at reads, without broad config writes/maintenance imports |
278-
| `plugin-sdk/session-transcript-runtime` | Transcript identity, scoped target/read/write helpers, visible message-entry projection, update publishing, write locks, and transcript memory hit keys |
278+
| `plugin-sdk/session-transcript-runtime` | Transcript identity, bounded raw and visible cursors, scoped target/read/write helpers, visible message-entry projection, update publishing, write locks, and transcript memory hit keys |
279279
| `plugin-sdk/sqlite-runtime` | Focused SQLite agent-schema, path, and transaction helpers for first-party runtime, without database lifecycle controls |
280280
| `plugin-sdk/cron-store-runtime` | Cron store path/load/save helpers |
281281
| `plugin-sdk/state-paths` | State/OAuth dir path helpers |

‎extensions/active-memory/index.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ const hoisted = vi.hoisted(() => {
5252
closeActiveMemorySearchManager: vi.fn(async () => {}),
5353
cleanupSessionLifecycleArtifacts: vi.fn(),
5454
patchSessionEntry: vi.fn(),
55+
rawDeltaReads: [] as Array<{ maxBytes?: number; maxEvents?: number; sessionId: string }>,
5556
runtimeTranscriptFiles: {} as Record<string, string>,
5657
sessionStore,
5758
updateSessionStore: vi.fn(
@@ -87,6 +88,52 @@ vi.mock("openclaw/plugin-sdk/session-transcript-runtime", async () => {
8788
>("openclaw/plugin-sdk/session-transcript-runtime");
8889
return {
8990
...actual,
91+
readSessionTranscriptRawDelta: async (
92+
params: Parameters<typeof actual.readSessionTranscriptRawDelta>[0],
93+
) => {
94+
hoisted.rawDeltaReads.push({
95+
maxBytes: params.maxBytes,
96+
maxEvents: params.maxEvents,
97+
sessionId: params.sessionId,
98+
});
99+
const testSessionFile = hoisted.runtimeTranscriptFiles[params.sessionId];
100+
if (!testSessionFile) {
101+
return await actual.readSessionTranscriptRawDelta(params);
102+
}
103+
try {
104+
const lines = (await fs.readFile(testSessionFile, "utf8"))
105+
.split("\n")
106+
.map((line) => line.trim())
107+
.filter(Boolean);
108+
const maxEvents = params.maxEvents ?? lines.length;
109+
const maxBytes = params.maxBytes ?? Number.MAX_SAFE_INTEGER;
110+
const events: Array<{ event: unknown; seq: number }> = [];
111+
let serializedBytes = 0;
112+
for (const [seq, line] of lines.entries()) {
113+
const nextBytes = Buffer.byteLength(`${line}\n`, "utf8");
114+
if (events.length >= maxEvents || serializedBytes + nextBytes > maxBytes) {
115+
break;
116+
}
117+
events.push({ event: JSON.parse(line) as unknown, seq });
118+
serializedBytes += nextBytes;
119+
}
120+
const requiredBytes =
121+
events.length === 0 && lines[0] ? Buffer.byteLength(`${lines[0]}\n`, "utf8") : undefined;
122+
return {
123+
kind: "page" as const,
124+
cursor: `test-runtime:${String(events.length)}`,
125+
events,
126+
hasMore: events.length < lines.length,
127+
...(requiredBytes !== undefined ? { requiredBytes } : {}),
128+
serializedBytes,
129+
};
130+
} catch (error) {
131+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
132+
throw error;
133+
}
134+
}
135+
return await actual.readSessionTranscriptRawDelta(params);
136+
},
90137
readSessionTranscriptEvents: async (
91138
target: Parameters<typeof actual.readSessionTranscriptEvents>[0],
92139
) => {
@@ -538,6 +585,7 @@ describe("active-memory plugin", () => {
538585
for (const key of Object.keys(hoisted.runtimeTranscriptFiles)) {
539586
delete hoisted.runtimeTranscriptFiles[key];
540587
}
588+
hoisted.rawDeltaReads.length = 0;
541589
hoisted.sessionStore["agent:main:main"] = {
542590
sessionId: "s-main",
543591
updatedAt: 0,
@@ -3783,6 +3831,12 @@ describe("active-memory plugin", () => {
37833831
);
37843832

37853833
expectPrependContextContains(result, "sqlite partial recall summary");
3834+
expect(hoisted.rawDeltaReads).toContainEqual(
3835+
expect.objectContaining({
3836+
maxBytes: 50 * 1024 * 1024,
3837+
maxEvents: 2_000,
3838+
}),
3839+
);
37863840
if (artifactSessionFile) {
37873841
await expectPathMissing(artifactSessionFile);
37883842
}

‎extensions/active-memory/transcript.ts‎

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import fs from "node:fs/promises";
33
import * as readline from "node:readline";
44
import { parseSqliteSessionFileMarker } from "openclaw/plugin-sdk/session-store-runtime";
55
import {
6-
readSessionTranscriptEvents,
6+
readSessionTranscriptRawDelta,
77
type SessionTranscriptTargetParams,
88
} from "openclaw/plugin-sdk/session-transcript-runtime";
99
import {
@@ -127,39 +127,26 @@ function transcriptSourceFromReturnedSessionFile(params: {
127127
};
128128
}
129129

130-
function estimateTranscriptEventsBytes(events: readonly unknown[]): number {
131-
let total = 0;
132-
for (const event of events) {
133-
try {
134-
total += Buffer.byteLength(`${JSON.stringify(event)}\n`, "utf8");
135-
} catch {
136-
total += 1;
137-
}
138-
}
139-
return total;
140-
}
141-
142130
async function streamRuntimeTranscriptEvents(params: {
143131
target: SessionTranscriptTargetParams;
144132
limits?: TranscriptReadLimits;
145133
onRecord: (record: unknown) => boolean | void;
146134
}): Promise<void> {
147135
const limits = resolveTranscriptReadLimits(params.limits);
148-
let events: readonly unknown[];
136+
let page: Awaited<ReturnType<typeof readSessionTranscriptRawDelta>>;
149137
try {
150-
events = await readSessionTranscriptEvents(params.target);
138+
page = await readSessionTranscriptRawDelta({
139+
...params.target,
140+
maxBytes: limits.maxBytes,
141+
maxEvents: limits.maxLines,
142+
});
151143
} catch {
152144
return;
153145
}
154-
if (estimateTranscriptEventsBytes(events) > limits.maxBytes) {
146+
if (page.kind !== "page") {
155147
return;
156148
}
157-
let seenLines = 0;
158-
for (const event of events) {
159-
seenLines += 1;
160-
if (seenLines > limits.maxLines) {
161-
break;
162-
}
149+
for (const { event } of page.events) {
163150
try {
164151
if (params.onRecord(event)) {
165152
break;

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"openclaw": {
55
"schemaVersions": {
66
"state": 4,
7-
"agent": 12
7+
"agent": 13
88
}
99
},
1010
"description": "Multi-channel AI gateway with extensible messaging integrations",
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
// Benchmarks generation-aware raw transcript reads against a 100k-event session.
2+
import fs from "node:fs";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import {
6+
loadTranscriptEventsSync,
7+
readTranscriptRawDelta,
8+
} from "../src/config/sessions/session-accessor.js";
9+
import {
10+
closeOpenClawAgentDatabasesForTest,
11+
openOpenClawAgentDatabase,
12+
} from "../src/state/openclaw-agent-db.js";
13+
import { closeOpenClawStateDatabaseForTest } from "../src/state/openclaw-state-db.js";
14+
15+
const EVENT_COUNT = 100_000;
16+
const DELTA_COUNT = 20;
17+
const RUNS = 12;
18+
19+
type Timing = {
20+
p50Ms: number;
21+
p95Ms: number;
22+
};
23+
24+
function percentile(values: readonly number[], fraction: number): number {
25+
const sorted = values.toSorted((left, right) => left - right);
26+
const index = Math.min(sorted.length - 1, Math.floor(sorted.length * fraction));
27+
return Number((sorted[index] ?? 0).toFixed(3));
28+
}
29+
30+
function measure(operation: () => void): Timing {
31+
const values: number[] = [];
32+
for (let index = 0; index < RUNS; index += 1) {
33+
const startedAt = performance.now();
34+
operation();
35+
values.push(performance.now() - startedAt);
36+
}
37+
return { p50Ms: percentile(values, 0.5), p95Ms: percentile(values, 0.95) };
38+
}
39+
40+
function seedTranscript(
41+
database: ReturnType<typeof openOpenClawAgentDatabase>,
42+
sessionId: string,
43+
sessionKey: string,
44+
): void {
45+
database.db.exec("BEGIN IMMEDIATE");
46+
try {
47+
const now = Date.now();
48+
database.db
49+
.prepare(
50+
`INSERT INTO sessions (session_id, session_key, session_scope, created_at, updated_at)
51+
VALUES (?, ?, 'conversation', ?, ?)`,
52+
)
53+
.run(sessionId, sessionKey, now, now);
54+
database.db
55+
.prepare(
56+
`INSERT INTO session_transcript_generations (session_id, generation, updated_at)
57+
VALUES (?, 'benchmark-generation', ?)`,
58+
)
59+
.run(sessionId, now);
60+
const insert = database.db.prepare(
61+
`INSERT INTO transcript_events (session_id, seq, event_json, created_at)
62+
VALUES (?, ?, ?, ?)`,
63+
);
64+
for (let seq = 0; seq < EVENT_COUNT; seq += 1) {
65+
insert.run(
66+
sessionId,
67+
seq,
68+
JSON.stringify({ id: `event-${seq}`, text: "x".repeat(64), type: "custom" }),
69+
now + seq,
70+
);
71+
}
72+
database.db.exec("COMMIT");
73+
} catch (error) {
74+
database.db.exec("ROLLBACK");
75+
throw error;
76+
}
77+
}
78+
79+
function appendDelta(
80+
database: ReturnType<typeof openOpenClawAgentDatabase>,
81+
sessionId: string,
82+
): void {
83+
const insert = database.db.prepare(
84+
`INSERT INTO transcript_events (session_id, seq, event_json, created_at)
85+
VALUES (?, ?, ?, ?)`,
86+
);
87+
database.db.exec("BEGIN IMMEDIATE");
88+
try {
89+
for (let offset = 0; offset < DELTA_COUNT; offset += 1) {
90+
const seq = EVENT_COUNT + offset;
91+
insert.run(
92+
sessionId,
93+
seq,
94+
JSON.stringify({ id: `delta-${offset}`, text: "delta", type: "custom" }),
95+
Date.now() + offset,
96+
);
97+
}
98+
database.db.exec("COMMIT");
99+
} catch (error) {
100+
database.db.exec("ROLLBACK");
101+
throw error;
102+
}
103+
}
104+
105+
function readFrontierCursor(scope: Parameters<typeof readTranscriptRawDelta>[0]): string {
106+
let cursor: string | undefined;
107+
for (;;) {
108+
const page = readTranscriptRawDelta(scope, {
109+
...(cursor ? { cursor } : {}),
110+
maxBytes: 64 * 1024 * 1024,
111+
maxEvents: 10_000,
112+
});
113+
if (page.kind !== "page") {
114+
throw new Error(`unexpected cursor bootstrap result: ${page.kind}`);
115+
}
116+
cursor = page.cursor;
117+
if (!page.hasMore) {
118+
return cursor;
119+
}
120+
}
121+
}
122+
123+
function main(): void {
124+
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-transcript-bench-"));
125+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
126+
const agentId = "benchmark";
127+
const sessionId = "cursor-benchmark";
128+
const sessionKey = `agent:${agentId}:cursor-benchmark`;
129+
try {
130+
const database = openOpenClawAgentDatabase({ agentId, env });
131+
seedTranscript(database, sessionId, sessionKey);
132+
const scope = { agentId, sessionId, sessionKey, storePath: database.path };
133+
134+
const bootstrap = measure(() => {
135+
const page = readTranscriptRawDelta(scope, { maxBytes: 1_000_000, maxEvents: 1_000 });
136+
if (page.kind !== "page" || page.events.length !== 1_000) {
137+
throw new Error("raw bootstrap did not return 1,000 events");
138+
}
139+
});
140+
const activeMemoryBounded = measure(() => {
141+
const page = readTranscriptRawDelta(scope, {
142+
maxBytes: 50 * 1024 * 1024,
143+
maxEvents: 2_000,
144+
});
145+
if (page.kind !== "page" || page.events.length !== 2_000) {
146+
throw new Error("active-memory bounds did not return 2,000 events");
147+
}
148+
});
149+
const frontierCursor = readFrontierCursor(scope);
150+
appendDelta(database, sessionId);
151+
const shortDelta = measure(() => {
152+
const page = readTranscriptRawDelta(scope, {
153+
cursor: frontierCursor,
154+
maxBytes: 1_000_000,
155+
maxEvents: 100,
156+
});
157+
if (page.kind !== "page" || page.events.length !== DELTA_COUNT || page.hasMore) {
158+
throw new Error("raw delta did not return the appended frontier");
159+
}
160+
});
161+
const fullRead = measure(() => {
162+
if (loadTranscriptEventsSync(scope).length !== EVENT_COUNT + DELTA_COUNT) {
163+
throw new Error("full transcript read returned the wrong row count");
164+
}
165+
});
166+
167+
console.log(
168+
JSON.stringify(
169+
{
170+
events: EVENT_COUNT,
171+
appendedEvents: DELTA_COUNT,
172+
runs: RUNS,
173+
timings: { activeMemoryBounded, bootstrap, fullRead, shortDelta },
174+
},
175+
null,
176+
2,
177+
),
178+
);
179+
} finally {
180+
closeOpenClawAgentDatabasesForTest();
181+
closeOpenClawStateDatabaseForTest();
182+
fs.rmSync(stateDir, { force: true, recursive: true });
183+
}
184+
}
185+
186+
main();

‎scripts/plugin-sdk-surface-report.mjs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,9 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
271271
// +4: gateway-backed harness question runner, claim/cancel helpers, and caller type.
272272
// Harvest: internal question runtime exports -2.
273273
// +1: ingress-effect-once factory.
274-
8158,
274+
// +3: bounded raw transcript cursor request, result, and reader.
275+
// +3: bounded visible transcript cursor request, result, and reader.
276+
8164,
275277
env,
276278
),
277279
publicFunctionExports: readPluginSdkSurfaceBudgetEnv(
@@ -312,7 +314,9 @@ export function readPluginSdkSurfaceBudgets(env = process.env) {
312314
// +3: gateway-backed harness question runner and claim/cancel helpers.
313315
// Harvest: internal question runtime callable -1.
314316
// +1: ingress-effect-once factory.
315-
4540,
317+
// +1: bounded raw transcript cursor reader.
318+
// +1: bounded visible transcript cursor reader.
319+
4542,
316320
env,
317321
),
318322
publicDeprecatedExports: readPluginSdkSurfaceBudgetEnv(

0 commit comments

Comments
 (0)