Skip to content

Commit af2957a

Browse files
committed
perf(memory): defer session backfill runtime
Punchcard-Session: coral-workshop-workshop-3f
1 parent fb81d03 commit af2957a

8 files changed

Lines changed: 149 additions & 60 deletions

‎extensions/memory-core/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
21
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
32
// Memory Core plugin entrypoint registers its OpenClaw integration.
43
import {
54
jsonResult,
5+
listAgentIds,
66
resolveMemorySearchConfig,
77
resolveSessionAgentIds,
88
type MemoryPluginRuntime,
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import type { GatewayRequestHandlerOptions } from "openclaw/plugin-sdk/gateway-runtime";
2+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
3+
import { expect, it, vi } from "vitest";
4+
import { registerSessionBackfillGatewayMethods } from "./session-backfill-gateway.js";
5+
6+
const backfillModule = vi.hoisted(() => ({
7+
loadCount: 0,
8+
executeSessionBackfill: vi.fn(),
9+
executeSessionBackfillBatch: vi.fn(),
10+
}));
11+
12+
vi.mock("./session-backfill.js", () => {
13+
backfillModule.loadCount += 1;
14+
return {
15+
executeSessionBackfill: backfillModule.executeSessionBackfill,
16+
executeSessionBackfillBatch: backfillModule.executeSessionBackfillBatch,
17+
};
18+
});
19+
20+
it("loads session backfill execution only for the first valid request", async () => {
21+
const methods = new Map<string, (options: GatewayRequestHandlerOptions) => Promise<void>>();
22+
const api = {
23+
runtime: {
24+
config: {
25+
current: () => ({
26+
agents: {
27+
entries: { main: { default: true, workspace: "/tmp/main-workspace" } },
28+
},
29+
}),
30+
},
31+
agent: {
32+
resolveAgentWorkspaceDir: () => "/tmp/main-workspace",
33+
},
34+
},
35+
registerGatewayMethod(
36+
method: string,
37+
handler: (options: GatewayRequestHandlerOptions) => Promise<void>,
38+
) {
39+
methods.set(method, handler);
40+
},
41+
} as unknown as OpenClawPluginApi;
42+
43+
registerSessionBackfillGatewayMethods(api);
44+
expect(backfillModule.loadCount).toBe(0);
45+
46+
const preview = methods.get("memory.sessionBackfill.preview");
47+
expect(preview).toBeDefined();
48+
const invalidRespond = vi.fn();
49+
await preview!({
50+
params: { agentId: "main", from: "invalid" },
51+
respond: invalidRespond,
52+
} as unknown as GatewayRequestHandlerOptions);
53+
expect(backfillModule.loadCount).toBe(0);
54+
expect(invalidRespond.mock.calls[0]?.[2]).toMatchObject({ code: "INVALID_REQUEST" });
55+
56+
backfillModule.executeSessionBackfillBatch.mockResolvedValue({
57+
result: {
58+
agentId: "main",
59+
workspaceDir: "/tmp/main-workspace",
60+
applied: false,
61+
rem: false,
62+
days: [],
63+
candidateCount: 0,
64+
stagedEntries: 0,
65+
writtenDiaryEntries: 0,
66+
replacedDiaryEntries: 0,
67+
},
68+
continuation: { advanced: false, hasMore: false },
69+
});
70+
await preview!({
71+
params: { agentId: "main" },
72+
respond: vi.fn(),
73+
} as unknown as GatewayRequestHandlerOptions);
74+
await preview!({
75+
params: { agentId: "main" },
76+
respond: vi.fn(),
77+
} as unknown as GatewayRequestHandlerOptions);
78+
79+
expect(backfillModule.loadCount).toBe(1);
80+
expect(backfillModule.executeSessionBackfillBatch).toHaveBeenCalledTimes(2);
81+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
// Keep the gateway's dynamic boundary separate from the CLI runtime, which
2+
// also owns a static session-backfill import for command execution.
3+
export { executeSessionBackfill, executeSessionBackfillBatch } from "./session-backfill.js";

‎extensions/memory-core/src/session-backfill-gateway.ts‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,31 @@
1-
import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
21
import { readPositiveIntegerParam, readStringParam } from "openclaw/plugin-sdk/channel-actions";
32
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
43
import {
54
ErrorCodes,
65
errorShape,
76
type GatewayRequestHandlerOptions,
87
} from "openclaw/plugin-sdk/gateway-runtime";
8+
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
9+
import { listAgentIds } from "openclaw/plugin-sdk/memory-core-host-runtime-core";
910
import { resolveMemoryRemDreamingConfig } from "openclaw/plugin-sdk/memory-core-host-status";
1011
import { resolvePluginConfigObject } from "openclaw/plugin-sdk/plugin-config-runtime";
1112
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
1213
import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
13-
import {
14-
executeSessionBackfill,
15-
executeSessionBackfillBatch,
16-
normalizeSessionBackfillSelection,
17-
type RunSessionBackfillParams,
18-
type SessionBackfillResult,
19-
} from "./session-backfill.js";
14+
import type { SessionBackfillResult } from "./session-backfill-contract.js";
15+
import { normalizeSessionBackfillSelection } from "./session-backfill-selection.js";
2016

2117
const SESSION_BACKFILL_GATEWAY_METHODS = {
2218
preview: "memory.sessionBackfill.preview",
2319
apply: "memory.sessionBackfill.apply",
2420
rollback: "memory.sessionBackfill.rollback",
2521
} as const;
2622

27-
type SessionBackfillGatewayParams = Pick<
28-
RunSessionBackfillParams,
29-
"agentId" | "from" | "to" | "limitDays"
30-
>;
23+
type SessionBackfillGatewayParams = {
24+
agentId: string;
25+
from?: string;
26+
to?: string;
27+
limitDays: number;
28+
};
3129

3230
type SessionBackfillGatewayResult = {
3331
days: number;
@@ -44,6 +42,10 @@ type SessionBackfillGatewayResult = {
4442

4543
class InvalidSessionBackfillRequestError extends Error {}
4644

45+
const loadSessionBackfillGatewayRuntime = createLazyRuntimeModule(
46+
() => import("./session-backfill-gateway.runtime.js"),
47+
);
48+
4749
function paramsRecord(value: unknown): Record<string, unknown> {
4850
if (!value || typeof value !== "object" || Array.isArray(value)) {
4951
throw new Error("params must be an object.");
@@ -165,6 +167,7 @@ export function registerSessionBackfillGatewayMethods(api: OpenClawPluginApi): v
165167
}
166168
try {
167169
const context = resolveExecutionContext(api, request.agentId);
170+
const { executeSessionBackfillBatch } = await loadSessionBackfillGatewayRuntime();
168171
const execution = await executeSessionBackfillBatch({
169172
...request,
170173
...context,
@@ -203,6 +206,7 @@ export function registerSessionBackfillGatewayMethods(api: OpenClawPluginApi): v
203206
}
204207
try {
205208
const context = resolveExecutionContext(api, request.agentId);
209+
const { executeSessionBackfill } = await loadSessionBackfillGatewayRuntime();
206210
const result = await executeSessionBackfill({ ...request, ...context, rollback: true });
207211
respond(true, {
208212
removedDiaryEntries: result.rollback?.removedDiaryEntries ?? 0,

‎extensions/memory-core/src/session-backfill-lifecycle.ts‎

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@ import type {
1111
} from "./session-backfill-contract.js";
1212
import { readSessionIngestionState, writeSessionIngestionState } from "./session-ingestion.js";
1313

14-
const DEFAULT_SESSION_BACKFILL_LIMIT_DAYS = 92;
15-
const MEMORY_DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
1614
// Batch keys are SHA-256 hex digests, so this colon-delimited marker cannot collide.
1715
const SESSION_BACKFILL_BASELINE_KEY_PREFIX = "complete-baseline:";
1816

@@ -34,45 +32,6 @@ type SessionBackfillBaseline = {
3432
agentId: string;
3533
};
3634

37-
function normalizeMemoryDay(value: string | undefined, flag: string): string | undefined {
38-
if (value === undefined) {
39-
return undefined;
40-
}
41-
const day = value.trim();
42-
if (!MEMORY_DAY_RE.test(day)) {
43-
throw new Error(`${flag} must use YYYY-MM-DD.`);
44-
}
45-
const parsed = new Date(`${day}T00:00:00.000Z`);
46-
if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== day) {
47-
throw new Error(`${flag} must be a valid calendar day.`);
48-
}
49-
return day;
50-
}
51-
52-
export function normalizeSessionBackfillSelection(
53-
params: { from?: string; to?: string; limitDays?: number },
54-
labels: { from: string; to: string; limitDays: string } = {
55-
from: "--from",
56-
to: "--to",
57-
limitDays: "--limit-days",
58-
},
59-
): { from?: string; to?: string; limitDays: number } {
60-
const from = normalizeMemoryDay(params.from, labels.from);
61-
const to = normalizeMemoryDay(params.to, labels.to);
62-
if (from !== undefined && to !== undefined && from > to) {
63-
throw new Error(`${labels.from} must not be after ${labels.to}.`);
64-
}
65-
const limitDays = params.limitDays ?? DEFAULT_SESSION_BACKFILL_LIMIT_DAYS;
66-
if (!Number.isInteger(limitDays) || limitDays <= 0) {
67-
throw new Error(`${labels.limitDays} must be a positive integer.`);
68-
}
69-
return {
70-
...(from !== undefined ? { from } : {}),
71-
...(to !== undefined ? { to } : {}),
72-
limitDays,
73-
};
74-
}
75-
7635
export async function recordSessionBackfillRewindBatch(params: {
7736
workspaceDir: string;
7837
candidates: SessionBackfillRewindCandidate[];
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const DEFAULT_SESSION_BACKFILL_LIMIT_DAYS = 92;
2+
const MEMORY_DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
3+
4+
function normalizeMemoryDay(value: string | undefined, flag: string): string | undefined {
5+
if (value === undefined) {
6+
return undefined;
7+
}
8+
const day = value.trim();
9+
if (!MEMORY_DAY_RE.test(day)) {
10+
throw new Error(`${flag} must use YYYY-MM-DD.`);
11+
}
12+
const parsed = new Date(`${day}T00:00:00.000Z`);
13+
if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== day) {
14+
throw new Error(`${flag} must be a valid calendar day.`);
15+
}
16+
return day;
17+
}
18+
19+
export function normalizeSessionBackfillSelection(
20+
params: { from?: string; to?: string; limitDays?: number },
21+
labels: { from: string; to: string; limitDays: string } = {
22+
from: "--from",
23+
to: "--to",
24+
limitDays: "--limit-days",
25+
},
26+
): { from?: string; to?: string; limitDays: number } {
27+
const from = normalizeMemoryDay(params.from, labels.from);
28+
const to = normalizeMemoryDay(params.to, labels.to);
29+
if (from !== undefined && to !== undefined && from > to) {
30+
throw new Error(`${labels.from} must not be after ${labels.to}.`);
31+
}
32+
const limitDays = params.limitDays ?? DEFAULT_SESSION_BACKFILL_LIMIT_DAYS;
33+
if (!Number.isInteger(limitDays) || limitDays <= 0) {
34+
throw new Error(`${labels.limitDays} must be a positive integer.`);
35+
}
36+
return {
37+
...(from !== undefined ? { from } : {}),
38+
...(to !== undefined ? { to } : {}),
39+
limitDays,
40+
};
41+
}

‎extensions/memory-core/src/session-backfill.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ import type {
1414
import {
1515
drainSessionBackfill,
1616
markSessionBackfillRewindBaseline,
17-
normalizeSessionBackfillSelection,
1817
recordSessionBackfillRewindBatch,
1918
resetSessionBackfillIngestionState,
2019
rewindSessionBackfillIngestionState,
2120
} from "./session-backfill-lifecycle.js";
21+
import { normalizeSessionBackfillSelection } from "./session-backfill-selection.js";
2222
import {
2323
SESSION_INGESTION_MAX_MESSAGES_PER_FILE,
2424
SESSION_INGESTION_MAX_MESSAGES_PER_SWEEP,
@@ -46,9 +46,6 @@ const SESSION_BACKFILL_QUERY_PREFIX = "__dreaming_session_backfill__";
4646
const TOP_CANDIDATE_LIMIT = 5;
4747
const MAX_SESSION_BACKFILL_APPLY_BATCHES = 10_000;
4848

49-
export { normalizeSessionBackfillSelection } from "./session-backfill-lifecycle.js";
50-
export type { SessionBackfillResult } from "./session-backfill-contract.js";
51-
5249
export type MemorySessionBackfillOptions = {
5350
agent?: string;
5451
from?: string;
@@ -74,7 +71,7 @@ type SessionBackfillScan = {
7471
stateKey: string;
7572
};
7673

77-
export type RunSessionBackfillParams = {
74+
type RunSessionBackfillParams = {
7875
agentId: string;
7976
workspaceDir: string;
8077
from?: string;

‎src/plugin-sdk/memory-core-host-runtime-core.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ export {
1111
} from "../agents/tools/common.js";
1212
export type { AnyAgentTool } from "../agents/tools/common.js";
1313
export { resolveCronStyleNow } from "../agents/current-time.js";
14-
export { resolveDefaultAgentId, resolveSessionAgentIds } from "../agents/agent-scope.js";
14+
export {
15+
listAgentIds,
16+
resolveDefaultAgentId,
17+
resolveSessionAgentIds,
18+
} from "../agents/agent-scope.js";
1519
export { resolveMemorySearchConfig } from "../agents/memory-search.js";
1620
export { resolveMemoryDreamingPluginConfig } from "../memory-host-sdk/dreaming.js";
1721
export { parseNonNegativeByteSize } from "../config/byte-size.js";

0 commit comments

Comments
 (0)