Skip to content

Commit 0b1ef90

Browse files
ekinneeErick Kinneesteipetegucasbrg
authored
fix(sessions): gateway becomes unusable when there are many sessions (#113959)
* fix(sessions): add SQLite session entry cache with current-schema support Rebase PR #113959 cache changes onto current origin/main: - Replace listSqliteSessionEntries with cached version using session_nodes table (was session_entries) - Add connection-identity token for data_version cross-connection safety - Add light listing variant with LIMIT/OFFSET pagination - Add file-stat + data_version coherence guards - Add cache invalidation on all mutation paths - Add SessionEntryListScope type with light/limit/offset fields - Restore store-cache.ts (deleted upstream, re-added with cache layer) * perf(sessions): project lightweight gateway lists Replace the request-time session cache and freshness probes with an explicit SQL-side list projection. Keep full entry reads as the default, preserve the post-await sharing authorization refresh, and carry the projection through Gateway, TUI, and embedded-tool list paths. Co-authored-by: Erick Kinnee <[email protected]> Co-authored-by: gucasbrg <[email protected]> * test(tui): expect lightweight session projection --------- Co-authored-by: Erick Kinnee <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: gucasbrg <[email protected]>
1 parent 0642072 commit 0b1ef90

11 files changed

Lines changed: 163 additions & 27 deletions

‎src/agents/tools/embedded-gateway-stub.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ describe("embedded gateway stub", () => {
8888

8989
expect(runtime.loadCombinedSessionStoreForGateway).toHaveBeenCalledWith(
9090
{ agents: { list: [{ id: "main", default: true }] } },
91-
{ agentId: "work" },
91+
{ agentId: "work", projection: "list" },
9292
);
9393
expect(runtime.listSessionsFromStoreAsync).toHaveBeenCalledWith({
9494
cfg: { agents: { list: [{ id: "main", default: true }] } },

‎src/agents/tools/embedded-gateway-stub.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ interface EmbeddedGatewayRuntime {
8181
}) => Promise<SessionsListResult>;
8282
loadCombinedSessionStoreForGateway: (
8383
cfg: OpenClawConfig,
84-
opts?: { agentId?: string },
84+
opts?: { agentId?: string; projection?: "full" | "list" },
8585
) => {
8686
storePath: string;
8787
store: unknown;
@@ -200,6 +200,7 @@ async function handleSessionsList(params: Record<string, unknown>) {
200200
const opts = params as SessionsListParams;
201201
const { storePath, store } = rt.loadCombinedSessionStoreForGateway(cfg, {
202202
agentId: opts.agentId,
203+
projection: "list",
203204
});
204205
return rt.listSessionsFromStoreAsync({
205206
cfg,

‎src/config/sessions/combined-store-gateway.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { listOpenIncognitoAgentDatabases } from "../../state/openclaw-agent-db.j
1717
import type { OpenClawConfig } from "../types.openclaw.js";
1818
import { resolveStorePath } from "./paths.js";
1919
import { listSessionEntries, listSessionEntriesReadOnly } from "./session-accessor.js";
20+
import type { SessionEntryListScope } from "./session-accessor.types.js";
2021
import {
2122
dedupeSessionStoreTargetsBySqliteTarget,
2223
listConfiguredSessionStoreAgentIds,
@@ -27,6 +28,8 @@ import {
2728
} from "./targets.js";
2829
import type { SessionEntry } from "./types.js";
2930

31+
type GatewaySessionEntryProjection = NonNullable<SessionEntryListScope["projection"]>;
32+
3033
// Template-backed stores need per-agent scans before they can be merged for Gateway views.
3134
function isStorePathTemplate(store?: string): boolean {
3235
return typeof store === "string" && store.includes("{agentId}");
@@ -42,25 +45,29 @@ function resolveCombinedStorePath(paths: string[], storeConfig?: string): string
4245

4346
function loadGatewayStoreEntries(params: {
4447
agentId: string;
48+
projection: GatewaySessionEntryProjection;
4549
storePath: string;
4650
}): Record<string, SessionEntry> {
4751
return Object.fromEntries(
4852
listSessionEntriesReadOnly({
4953
agentId: params.agentId,
5054
clone: false,
55+
projection: params.projection,
5156
storePath: params.storePath,
5257
}).map(({ sessionKey, entry }) => [sessionKey, entry]),
5358
);
5459
}
5560

5661
function loadIncognitoGatewayStoreEntries(params: {
5762
agentId: string;
63+
projection: GatewaySessionEntryProjection;
5864
storePath: string;
5965
}): Record<string, SessionEntry> {
6066
return Object.fromEntries(
6167
listSessionEntries({
6268
agentId: params.agentId,
6369
clone: false,
70+
projection: params.projection,
6471
storePath: params.storePath,
6572
}).map(({ sessionKey, entry }) => [sessionKey, entry]),
6673
);
@@ -112,6 +119,7 @@ function mergeOpenIncognitoStores(params: {
112119
cfg: OpenClawConfig;
113120
combined: Record<string, SessionEntry>;
114121
agentId?: string;
122+
projection: GatewaySessionEntryProjection;
115123
}): string[] {
116124
const storePaths: string[] = [];
117125
for (const target of listOpenIncognitoAgentDatabases()) {
@@ -123,6 +131,7 @@ function mergeOpenIncognitoStores(params: {
123131
}
124132
const store = loadIncognitoGatewayStoreEntries({
125133
agentId: target.agentId,
134+
projection: params.projection,
126135
storePath: target.storePath,
127136
});
128137
let merged = false;
@@ -149,14 +158,20 @@ function mergeOpenIncognitoStores(params: {
149158
/** Loads and canonicalizes session entries for gateway views across one or more agent stores. */
150159
export function loadCombinedSessionStoreForGateway(
151160
cfg: OpenClawConfig,
152-
opts: { agentId?: string; configuredAgentsOnly?: boolean; includeIncognito?: boolean } = {},
161+
opts: {
162+
agentId?: string;
163+
configuredAgentsOnly?: boolean;
164+
includeIncognito?: boolean;
165+
projection?: SessionEntryListScope["projection"];
166+
} = {},
153167
): {
154168
diagnostics?: string[];
155169
durableStorePath?: string;
156170
storePath: string;
157171
store: Record<string, SessionEntry>;
158172
} {
159173
const storeConfig = cfg.session?.store;
174+
const projection = opts.projection ?? "full";
160175
const diagnostics: string[] = [];
161176
// Exclusion happens before path aggregation; filtering rows afterward would
162177
// still leak a live incognito handle by changing the projected store path.
@@ -197,7 +212,7 @@ export function loadCombinedSessionStoreForGateway(
197212
},
198213
);
199214
for (const { agentId, storePath } of ownerTargets) {
200-
const store = loadGatewayStoreEntries({ agentId, storePath });
215+
const store = loadGatewayStoreEntries({ agentId, projection, storePath });
201216
for (const [key, entry] of Object.entries(store)) {
202217
const canonicalKey = resolveStoredSessionKeyForAgentStore({
203218
cfg,
@@ -229,6 +244,7 @@ export function loadCombinedSessionStoreForGateway(
229244
cfg,
230245
combined,
231246
...(requestedAgentId ? { agentId: requestedAgentId } : {}),
247+
projection,
232248
})
233249
: [];
234250
return {
@@ -247,7 +263,7 @@ export function loadCombinedSessionStoreForGateway(
247263
for (const target of targets) {
248264
const agentId = target.agentId;
249265
const storePath = target.storePath;
250-
const store = loadGatewayStoreEntries({ agentId, storePath });
266+
const store = loadGatewayStoreEntries({ agentId, projection, storePath });
251267
for (const [key, entry] of Object.entries(store)) {
252268
const canonicalKey = resolveStoredSessionKeyForAgentStore({
253269
cfg,
@@ -279,6 +295,7 @@ export function loadCombinedSessionStoreForGateway(
279295
cfg,
280296
combined,
281297
...(requestedAgentId ? { agentId: requestedAgentId } : {}),
298+
projection,
282299
})
283300
: [];
284301

‎src/config/sessions/session-accessor.sqlite-entry.ts‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ import {
6464
parseSqliteSessionEntryJson as parseSessionEntryRow,
6565
readSqliteSessionEntriesByStatus,
6666
} from "./session-accessor.sqlite-status.js";
67+
import type { SessionEntryListScope } from "./session-accessor.types.js";
6768
import { preserveSqliteSameKeySessionRolloverLineage } from "./session-entry-lineage.js";
6869
import { buildSessionCreationStamp } from "./session-entry-provenance.js";
6970
import { kickSessionHistoryDiskBudgetMaintenance } from "./session-history-eviction.js";
@@ -160,12 +161,10 @@ export function resolveSqliteSessionKeyBySessionId(
160161
}
161162

162163
/** Lists session entries from the additive SQLite session store. */
163-
export function listSqliteSessionEntries(
164-
scope: Partial<Omit<SessionAccessScope, "sessionKey">> = {},
165-
): SessionEntrySummary[] {
164+
export function listSqliteSessionEntries(scope: SessionEntryListScope = {}): SessionEntrySummary[] {
166165
const resolved = resolveSqliteScope({ ...scope, sessionKey: "" });
167166
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
168-
return listSqliteSessionEntriesFromDatabase(database);
167+
return listSqliteSessionEntriesFromDatabase(database, scope.projection);
169168
}
170169

171170
/**
@@ -174,25 +173,41 @@ export function listSqliteSessionEntries(
174173
* acceptable degradation (health snapshots) or hides real state (migration detection).
175174
*/
176175
export function listSqliteSessionEntriesReadOnly(
177-
scope: Partial<Omit<SessionAccessScope, "sessionKey">> = {},
176+
scope: SessionEntryListScope = {},
178177
): SessionEntrySummary[] {
179178
const resolved = resolveSqliteScope({ ...scope, sessionKey: "" });
180179
const result = withOpenClawAgentDatabaseReadOnly(
181-
(database) => listSqliteSessionEntriesFromDatabase(database),
180+
(database) => listSqliteSessionEntriesFromDatabase(database, scope.projection),
182181
toDatabaseOptions(resolved),
183182
);
184183
return result.found ? result.value : [];
185184
}
186185

187-
function listSqliteSessionEntriesFromDatabase(database: { db: DatabaseSync }) {
186+
function listSqliteSessionEntriesFromDatabase(
187+
database: { db: DatabaseSync },
188+
projection: SessionEntryListScope["projection"] = "full",
189+
) {
188190
const db = getSessionKysely(database.db);
189-
const rows = executeSqliteQuerySync(
190-
database.db,
191-
db
192-
.selectFrom("session_nodes")
193-
.select(["session_key", "entry_json", "current_session_id", "updated_at"])
194-
.orderBy("session_key", "asc"),
195-
).rows;
191+
const baseQuery = db.selectFrom("session_nodes").select("session_key");
192+
const query =
193+
projection === "list"
194+
? baseQuery.select((eb) =>
195+
eb
196+
.case()
197+
.when(eb.fn<number>("json_valid", [eb.ref("entry_json")]), "=", 1)
198+
.then(
199+
eb.fn<string>("json_remove", [
200+
eb.ref("entry_json"),
201+
eb.val("$.systemPromptReport"),
202+
eb.val("$.skillsSnapshot"),
203+
]),
204+
)
205+
.else(eb.ref("entry_json"))
206+
.end()
207+
.as("entry_json"),
208+
)
209+
: baseQuery.select("entry_json");
210+
const rows = executeSqliteQuerySync(database.db, query.orderBy("session_key", "asc")).rows;
196211
return rows
197212
.map((row) => {
198213
if (isInternalSessionEffectsKey(row.session_key)) {

‎src/config/sessions/session-accessor.types.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ export type LogicalSessionAccessScope = {
6161
sessionKey: string;
6262
};
6363

64-
export type SessionEntryListScope = Partial<Omit<SessionAccessScope, "sessionKey">>;
64+
export type SessionEntryListScope = Partial<Omit<SessionAccessScope, "sessionKey">> & {
65+
/** Listing views do not consume the large per-run prompt snapshots. */
66+
projection?: "full" | "list";
67+
};
6568
export type SessionEntryStatus = NonNullable<SessionEntry["status"]>;
6669

6770
export type ResolvedSessionEntryAccessTarget = {

‎src/gateway/server-methods/sessions-read.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,7 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
233233
() =>
234234
loadCombinedSessionStoreForGateway(cfg, {
235235
agentId: p.agentId,
236+
projection: "list",
236237
}),
237238
{
238239
config: cfg,
@@ -284,6 +285,7 @@ export const sessionReadHandlers: GatewayRequestHandlers = {
284285
const sharingTargets = result.sessions.map((session) =>
285286
resolveSessionSharingTarget({
286287
cfg,
288+
projection: "list",
287289
sessionKey: session.key,
288290
storeCache: sharingStoreCache,
289291
...(session.key === "global" && p.agentId ? { agentId: p.agentId } : {}),

‎src/gateway/server.sessions.list-store-materialization.test.ts‎

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
*/
66
import { expect, test, vi } from "vitest";
77
import * as sessionAccessor from "../config/sessions/session-accessor.js";
8-
import { writeSessionStore } from "./test-helpers.js";
8+
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
9+
import { openOpenClawAgentDatabase } from "../state/openclaw-agent-db.js";
10+
import { testState, writeSessionStore } from "./test-helpers.js";
911
import {
1012
directSessionReq,
1113
sessionStoreEntry,
@@ -64,7 +66,83 @@ test("sessions.list does not materialize the lookup store once per row", async (
6466
const small = await countMaterializedEntriesForRows(5);
6567
const large = await countMaterializedEntriesForRows(40);
6668

67-
// A load per row makes this quadratic: 40 rows would materialize roughly 64x
68-
// the entries of 5 rows. One cached load per request stays far below that.
69+
// The post-await sharing refresh intentionally rereads current ACL state,
70+
// but one request-scoped load per store keeps that refresh linear.
6971
expect(large).toBeLessThan(small * 12);
7072
});
73+
74+
test("sessions.list projects out prompt snapshots without changing full entry reads", async () => {
75+
await createSessionStoreDir();
76+
await writeSessionStore({
77+
entries: {
78+
main: sessionStoreEntry("sess-main"),
79+
},
80+
});
81+
const storePath = testState.sessionStorePath!;
82+
const target = resolveSqliteTargetFromSessionStorePath(storePath, { agentId: "main" });
83+
const database = openOpenClawAgentDatabase({
84+
agentId: target.agentId ?? "main",
85+
path: target.path,
86+
});
87+
const stored = database.db
88+
.prepare("SELECT session_key, entry_json FROM session_nodes LIMIT 1")
89+
.get() as { session_key: string; entry_json: string };
90+
database.db.prepare("UPDATE session_nodes SET entry_json = ? WHERE session_key = ?").run(
91+
JSON.stringify({
92+
...(JSON.parse(stored.entry_json) as Record<string, unknown>),
93+
skillsSnapshot: { prompt: "large skill prompt", skills: [{ name: "test" }] },
94+
systemPromptReport: {
95+
source: "run",
96+
generatedAt: Date.now(),
97+
systemPrompt: { chars: 100, projectContextChars: 40, nonProjectContextChars: 60 },
98+
injectedWorkspaceFiles: [],
99+
skills: { promptChars: 0, entries: [] },
100+
tools: { listChars: 0, schemaChars: 0, entries: [] },
101+
},
102+
}),
103+
stored.session_key,
104+
);
105+
database.db
106+
.prepare(
107+
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, updated_at) VALUES (?, ?, ?, ?)",
108+
)
109+
.run("zz-malformed", "malformed", "{", Date.now());
110+
111+
const fullEntries = sessionAccessor.listSessionEntriesReadOnly({ agentId: "main", storePath });
112+
expect(fullEntries).toHaveLength(1);
113+
expect(fullEntries[0]?.entry.skillsSnapshot).toBeDefined();
114+
expect(fullEntries[0]?.entry.systemPromptReport?.source).toBe("run");
115+
116+
const projections: Array<string | undefined> = [];
117+
const originalReadOnly = sessionAccessor.listSessionEntriesReadOnly;
118+
const originalWritable = sessionAccessor.listSessionEntries;
119+
const spies = [
120+
vi.spyOn(sessionAccessor, "listSessionEntriesReadOnly").mockImplementation((scope) => {
121+
projections.push(scope?.projection);
122+
return originalReadOnly(scope);
123+
}),
124+
vi.spyOn(sessionAccessor, "listSessionEntries").mockImplementation((scope) => {
125+
projections.push(scope?.projection);
126+
return originalWritable(scope);
127+
}),
128+
];
129+
try {
130+
const result = await directSessionReq("sessions.list", LIST_PARAMS);
131+
expect(result.ok).toBe(true);
132+
expect(projections.length).toBeGreaterThan(0);
133+
expect(projections).toEqual(projections.map(() => "list"));
134+
} finally {
135+
for (const spy of spies) {
136+
spy.mockRestore();
137+
}
138+
}
139+
140+
const listEntries = sessionAccessor.listSessionEntriesReadOnly({
141+
agentId: "main",
142+
projection: "list",
143+
storePath,
144+
});
145+
expect(listEntries).toHaveLength(1);
146+
expect(listEntries[0]?.entry.skillsSnapshot).toBeUndefined();
147+
expect(listEntries[0]?.entry.systemPromptReport).toBeUndefined();
148+
});

‎src/gateway/session-sharing.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,12 +101,14 @@ export function resolveSessionSharingTarget(params: {
101101
cfg: OpenClawConfig;
102102
sessionKey: string;
103103
agentId?: string;
104+
projection?: "full" | "list";
104105
storeCache?: GatewaySessionStoreCache;
105106
}): SessionSharingTarget | null {
106107
const target = resolveGatewaySessionStoreTargetWithStore({
107108
cfg: params.cfg,
108109
key: params.sessionKey,
109110
agentId: params.agentId,
111+
...(params.projection ? { projection: params.projection } : {}),
110112
...(params.storeCache ? { storeCache: params.storeCache } : {}),
111113
});
112114
const match = resolveFreshestSessionStoreMatchFromStoreKeys(target.store, target.storeKeys);

0 commit comments

Comments
 (0)