Skip to content

Commit 7330e2c

Browse files
committed
perf(memory): avoid eager provider init on empty search
1 parent db0f957 commit 7330e2c

4 files changed

Lines changed: 68 additions & 20 deletions

File tree

‎src/config/schema-base.ts‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ export type BaseConfigSchemaResponse = {
1919
generatedAt: string;
2020
};
2121

22+
type BaseConfigSchemaStablePayload = Omit<BaseConfigSchemaResponse, "generatedAt">;
23+
2224
function cloneSchema<T>(value: T): T {
2325
if (typeof structuredClone === "function") {
2426
return structuredClone(value);
@@ -54,19 +56,42 @@ function stripChannelSchema(schema: ConfigSchema): ConfigSchema {
5456
return next;
5557
}
5658

57-
export function computeBaseConfigSchemaResponse(params?: {
58-
generatedAt?: string;
59-
}): BaseConfigSchemaResponse {
59+
let baseConfigSchemaStablePayload: BaseConfigSchemaStablePayload | null = null;
60+
61+
function computeBaseConfigSchemaStablePayload(): BaseConfigSchemaStablePayload {
62+
if (baseConfigSchemaStablePayload) {
63+
return {
64+
schema: cloneSchema(baseConfigSchemaStablePayload.schema),
65+
uiHints: cloneSchema(baseConfigSchemaStablePayload.uiHints),
66+
version: baseConfigSchemaStablePayload.version,
67+
};
68+
}
6069
const schema = OpenClawSchema.toJSONSchema({
6170
target: "draft-07",
6271
unrepresentable: "any",
6372
});
6473
schema.title = "OpenClawConfig";
65-
const hints = applyDerivedTags(mapSensitivePaths(OpenClawSchema, "", buildBaseHints()));
66-
return {
74+
const stablePayload = {
6775
schema: stripChannelSchema(schema),
68-
uiHints: hints,
76+
uiHints: applyDerivedTags(mapSensitivePaths(OpenClawSchema, "", buildBaseHints())),
6977
version: VERSION,
78+
} satisfies BaseConfigSchemaStablePayload;
79+
baseConfigSchemaStablePayload = stablePayload;
80+
return {
81+
schema: cloneSchema(stablePayload.schema),
82+
uiHints: cloneSchema(stablePayload.uiHints),
83+
version: stablePayload.version,
84+
};
85+
}
86+
87+
export function computeBaseConfigSchemaResponse(params?: {
88+
generatedAt?: string;
89+
}): BaseConfigSchemaResponse {
90+
const stablePayload = computeBaseConfigSchemaStablePayload();
91+
return {
92+
schema: stablePayload.schema,
93+
uiHints: stablePayload.uiHints,
94+
version: stablePayload.version,
7095
generatedAt: params?.generatedAt ?? new Date().toISOString(),
7196
};
7297
}

‎src/memory/index.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -957,6 +957,7 @@ describe("memory index", () => {
957957

958958
const result = await getMemorySearchManager({ cfg, agentId: "main" });
959959
const manager = requireManager(result);
960+
await manager.probeEmbeddingAvailability();
960961

961962
expect(
962963
providerCalls.some(

‎src/memory/manager.get-concurrency.test.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,17 +93,15 @@ describe("memory manager cache hydration", () => {
9393

9494
expect(managers).toHaveLength(12);
9595
expect(new Set(managers).size).toBe(1);
96-
expect(hoisted.providerCreateCalls).toBe(1);
96+
expect(hoisted.providerCreateCalls).toBe(0);
9797

9898
await managers[0].close();
9999
});
100100

101-
it("drains in-flight manager creation during global teardown", async () => {
101+
it("evicts cached managers during global teardown", async () => {
102102
const indexPath = path.join(workspaceDir, "index.sqlite");
103103
const cfg = createMemoryConcurrencyConfig(indexPath);
104104

105-
hoisted.providerDelayMs = 100;
106-
107105
const pendingResult = RawMemoryIndexManager.get({ cfg, agentId: "main" });
108106
await closeAllMemoryIndexManagers();
109107
const firstManager = await pendingResult;
@@ -113,7 +111,7 @@ describe("memory manager cache hydration", () => {
113111
expect(firstManager).toBeTruthy();
114112
expect(secondManager).toBeTruthy();
115113
expect(Object.is(secondManager, firstManager)).toBe(false);
116-
expect(hoisted.providerCreateCalls).toBe(2);
114+
expect(hoisted.providerCreateCalls).toBe(0);
117115

118116
await secondManager?.close?.();
119117
});

‎src/memory/manager.ts‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,6 @@ export class MemoryIndexManager extends MemoryManagerEmbeddingOps implements Mem
193193
return pending;
194194
}
195195
const createPromise = (async () => {
196-
const providerResult = await MemoryIndexManager.loadProviderResult({
197-
cfg,
198-
agentId,
199-
settings,
200-
});
201196
const refreshed = INDEX_CACHE.get(key);
202197
if (refreshed) {
203198
return refreshed;
@@ -208,7 +203,6 @@ export class MemoryIndexManager extends MemoryManagerEmbeddingOps implements Mem
208203
agentId,
209204
workspaceDir,
210205
settings,
211-
providerResult,
212206
purpose: params.purpose,
213207
});
214208
INDEX_CACHE.set(key, manager);
@@ -334,17 +328,21 @@ export class MemoryIndexManager extends MemoryManagerEmbeddingOps implements Mem
334328
sessionKey?: string;
335329
},
336330
): Promise<MemorySearchResult[]> {
337-
await this.ensureProviderInitialized();
331+
const cleaned = query.trim();
332+
if (!cleaned) {
333+
return [];
334+
}
338335
void this.warmSession(opts?.sessionKey);
339336
if (this.settings.sync.onSearch && (this.dirty || this.sessionsDirty)) {
340337
void this.sync({ reason: "search" }).catch((err) => {
341338
log.warn(`memory sync failed (search): ${String(err)}`);
342339
});
343340
}
344-
const cleaned = query.trim();
345-
if (!cleaned) {
341+
const hasIndexedContent = this.hasIndexedContent();
342+
if (!hasIndexedContent) {
346343
return [];
347344
}
345+
await this.ensureProviderInitialized();
348346
const minScore = opts?.minScore ?? this.settings.query.minScore;
349347
const maxResults = opts?.maxResults ?? this.settings.query.maxResults;
350348
const hybrid = this.settings.query.hybrid;
@@ -437,6 +435,32 @@ export class MemoryIndexManager extends MemoryManagerEmbeddingOps implements Mem
437435
.slice(0, maxResults);
438436
}
439437

438+
private hasIndexedContent(): boolean {
439+
const chunks =
440+
(
441+
this.db.prepare(`SELECT COUNT(*) as c FROM chunks`).get() as
442+
| {
443+
c: number;
444+
}
445+
| undefined
446+
)?.c ?? 0;
447+
if (chunks > 0) {
448+
return true;
449+
}
450+
if (!this.fts.enabled || !this.fts.available) {
451+
return false;
452+
}
453+
const ftsRows =
454+
(
455+
this.db.prepare(`SELECT COUNT(*) as c FROM ${FTS_TABLE}`).get() as
456+
| {
457+
c: number;
458+
}
459+
| undefined
460+
)?.c ?? 0;
461+
return ftsRows > 0;
462+
}
463+
440464
private async searchVector(
441465
queryVec: number[],
442466
limit: number,

0 commit comments

Comments
 (0)