Skip to content

Commit 32adfe7

Browse files
authored
perf: reduce repeated work during turn preparation (#134921)
1 parent 868475a commit 32adfe7

5 files changed

Lines changed: 93 additions & 72 deletions

File tree

‎src/agents/tools/video-generate-tool.test.ts‎

Lines changed: 57 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { parseReplyDirectives } from "../../auto-reply/reply/reply-directives.js
66
import type { OpenClawConfig } from "../../config/config.js";
77
import * as mediaStore from "../../media/store.js";
88
import * as webMedia from "../../media/web-media.js";
9+
import * as pluginConfig from "../../plugins/config-state.js";
910
import { getCurrentPluginMetadataSnapshot } from "../../plugins/current-plugin-metadata-snapshot.js";
1011
import { setCurrentPluginMetadataSnapshot } from "../../plugins/current-plugin-metadata.test-support.js";
1112
import { resolveInstalledPluginIndexPolicyHash } from "../../plugins/installed-plugin-index-policy.js";
@@ -159,12 +160,13 @@ function createVideoProviderSnapshot(params: {
159160
id: string;
160161
origin: PluginManifestRecord["origin"];
161162
referenceAudioInputs?: boolean;
163+
unrelatedPluginCount?: number;
162164
workspaceDir?: string;
163165
}): PluginMetadataSnapshot {
164166
// Plugin-backed provider snapshots are synthesized here so tool behavior can
165167
// be tested without loading plugin manifests from disk.
166168
const policyHash = resolveInstalledPluginIndexPolicyHash(params.config);
167-
const plugin: PluginManifestRecord = {
169+
const providerPlugin: PluginManifestRecord = {
168170
id: params.id,
169171
origin: params.origin,
170172
rootDir: `/plugins/${params.id}`,
@@ -183,6 +185,17 @@ function createVideoProviderSnapshot(params: {
183185
[params.id]: { referenceAudioInputs: params.referenceAudioInputs },
184186
},
185187
};
188+
const plugins = [
189+
providerPlugin,
190+
...Array.from({ length: params.unrelatedPluginCount ?? 0 }, (_, index) => ({
191+
...providerPlugin,
192+
id: `unrelated-${index}`,
193+
rootDir: `/plugins/unrelated-${index}`,
194+
source: `/plugins/unrelated-${index}/index.js`,
195+
manifestPath: `/plugins/unrelated-${index}/openclaw.plugin.json`,
196+
contracts: index % 2 === 0 ? undefined : { videoGenerationProviders: [] },
197+
})),
198+
];
186199
const index: PluginMetadataSnapshot["index"] = {
187200
version: 1,
188201
hostContractVersion: "test",
@@ -191,23 +204,21 @@ function createVideoProviderSnapshot(params: {
191204
policyHash,
192205
generatedAtMs: 0,
193206
installRecords: {},
194-
plugins: [
195-
{
196-
pluginId: params.id,
197-
manifestPath: plugin.manifestPath,
198-
manifestHash: "test",
199-
source: plugin.source,
200-
rootDir: plugin.rootDir,
201-
origin: params.origin,
202-
enabled: true,
203-
startup: {
204-
sidecar: false,
205-
memory: false,
206-
agentHarnesses: [],
207-
},
208-
compat: [],
207+
plugins: plugins.map((plugin) => ({
208+
pluginId: plugin.id,
209+
manifestPath: plugin.manifestPath,
210+
manifestHash: "test",
211+
source: plugin.source,
212+
rootDir: plugin.rootDir,
213+
origin: params.origin,
214+
enabled: true,
215+
startup: {
216+
sidecar: false,
217+
memory: false,
218+
agentHarnesses: [],
209219
},
210-
],
220+
compat: [],
221+
})),
211222
diagnostics: [],
212223
};
213224
return {
@@ -216,10 +227,10 @@ function createVideoProviderSnapshot(params: {
216227
index,
217228
registryIndex: index,
218229
registryDiagnostics: [],
219-
manifestRegistry: { plugins: [plugin], diagnostics: [] },
220-
plugins: [plugin],
230+
manifestRegistry: { plugins, diagnostics: [] },
231+
plugins,
221232
diagnostics: [],
222-
byPluginId: new Map([[plugin.id, plugin]]),
233+
byPluginId: new Map(plugins.map((plugin) => [plugin.id, plugin])),
223234
normalizePluginId: (pluginId) => pluginId,
224235
owners: {
225236
channels: new Map(),
@@ -237,8 +248,8 @@ function createVideoProviderSnapshot(params: {
237248
manifestRegistryMs: 0,
238249
ownerMapsMs: 0,
239250
totalMs: 0,
240-
indexPluginCount: 1,
241-
manifestPluginCount: 1,
251+
indexPluginCount: plugins.length,
252+
manifestPluginCount: plugins.length,
242253
},
243254
};
244255
}
@@ -469,22 +480,30 @@ describe("createVideoGenerateTool", () => {
469480
},
470481
});
471482
const workspaceDir = "/workspace/external-video";
472-
setCurrentPluginMetadataSnapshot(
473-
createVideoProviderSnapshot({
474-
config,
475-
id: "external-video",
476-
origin: "workspace",
477-
workspaceDir,
478-
}),
479-
{ config, workspaceDir },
480-
);
481-
expect(getCurrentPluginMetadataSnapshot({ config, workspaceDir })).toBeDefined();
482-
483-
const properties = toolParameterProperties(createVideoGenerateTool({ config, workspaceDir }));
484-
485-
expect(properties.audioRef).toBeUndefined();
486-
expect(properties.audioRefs).toBeUndefined();
487-
expect(properties.audioRoles).toBeUndefined();
483+
const normalize = vi.spyOn(pluginConfig, "normalizePluginsConfig");
484+
const normalizationCounts: number[] = [];
485+
for (const unrelatedPluginCount of [0, 32]) {
486+
setCurrentPluginMetadataSnapshot(
487+
createVideoProviderSnapshot({
488+
config,
489+
id: "external-video",
490+
origin: "workspace",
491+
unrelatedPluginCount,
492+
workspaceDir,
493+
}),
494+
{ config, workspaceDir },
495+
);
496+
expect(getCurrentPluginMetadataSnapshot({ config, workspaceDir })).toBeDefined();
497+
createVideoGenerateTool({ config, workspaceDir });
498+
normalize.mockClear();
499+
const properties = toolParameterProperties(createVideoGenerateTool({ config, workspaceDir }));
500+
normalizationCounts.push(normalize.mock.calls.length);
501+
502+
expect(properties.audioRef).toBeUndefined();
503+
expect(properties.audioRefs).toBeUndefined();
504+
expect(properties.audioRoles).toBeUndefined();
505+
}
506+
expect(normalizationCounts[1]).toBeLessThanOrEqual(normalizationCounts[0]!);
488507
});
489508

490509
it("exposes reference-audio params for configured audio-capable model overrides", () => {

‎src/agents/tools/video-generate-tool.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ function shouldExposeVideoReferenceAudioParams(params: {
274274

275275
for (const plugin of snapshot.plugins) {
276276
if (
277+
!plugin.contracts?.videoGenerationProviders?.length ||
277278
!isManifestPluginAvailableForControlPlane({
278279
snapshot,
279280
plugin,
@@ -282,8 +283,7 @@ function shouldExposeVideoReferenceAudioParams(params: {
282283
) {
283284
continue;
284285
}
285-
const providerIds = plugin.contracts?.videoGenerationProviders ?? [];
286-
for (const providerId of providerIds) {
286+
for (const providerId of plugin.contracts.videoGenerationProviders) {
287287
knownProviderIds.add(providerId);
288288
const metadata = plugin.videoGenerationProviderMetadata?.[providerId];
289289
const providerCanUseReferenceAudio = metadata?.referenceAudioInputs === true;

‎src/config/sessions/session-accessor.sqlite-data-version.test.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,16 @@ describe("SQLite session entry cache", () => {
186186
},
187187
});
188188

189-
const fullEntry = listSessionEntriesCore({ ...scope, clone: false, projection: "full" })[0]
190-
?.entry;
191-
expect(fullEntry).toBeDefined();
192-
if (!fullEntry) {
193-
throw new Error("missing seeded lazy-list-projection entry");
194-
}
195189
const cloneSpy = vi.spyOn(globalThis, "structuredClone");
196190
try {
191+
const fullEntry = listSessionEntriesCore({
192+
agentId: scope.agentId,
193+
env: scope.env,
194+
})[0]?.entry;
195+
expect(fullEntry).toBeDefined();
196+
if (!fullEntry) {
197+
throw new Error("missing seeded lazy-list-projection entry");
198+
}
197199
parseSessionEntryCalls.mockClear();
198200
const first = listSessionEntriesCore({
199201
...scope,
@@ -221,11 +223,20 @@ describe("SQLite session entry cache", () => {
221223
expect(cached.entries.get(scope.sessionKey)?.skillsSnapshot).toBeUndefined();
222224
expect(cached.entries.get(scope.sessionKey)?.systemPromptReport).toBeUndefined();
223225

224-
const fullAgain = listSessionEntriesCore({ ...scope, clone: false, projection: "full" })[0]
225-
?.entry;
226-
expect(fullAgain).toEqual(fullEntry);
226+
fullEntry.worktree!.branch = "mutated full read";
227+
fullEntry.skillsSnapshot!.prompt = "mutated full prompt";
228+
const fullAgain = listSessionEntriesCore({ ...scope, projection: "full" })[0]?.entry;
229+
expect(fullAgain?.worktree?.branch).toBe("main");
227230
expect(fullAgain?.skillsSnapshot?.prompt).toBe(prompt);
228231
expect(fullAgain?.systemPromptReport?.source).toBe("run");
232+
expect(cloneSpy).not.toHaveBeenCalled();
233+
expect(first?.worktree?.branch).toBe("main");
234+
235+
const copiedListEntry = listSessionEntriesCore(scope)[0]?.entry;
236+
expect(copiedListEntry?.worktree?.branch).toBe("main");
237+
expect(copiedListEntry?.worktree).not.toBe(first?.worktree);
238+
copiedListEntry!.worktree!.branch = "mutated list copy";
239+
expect(first?.worktree?.branch).toBe("main");
229240
expect(listSessionEntriesCore({ ...scope, clone: false, projection: "list" })[0]?.entry).toBe(
230241
first,
231242
);

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

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,7 @@ import type {
2727
SessionEntryTargetPatchScope,
2828
SessionTranscriptReadScope,
2929
} from "./session-accessor.sqlite-contract.js";
30-
import {
31-
readSessionEntryCache,
32-
type SessionEntryCacheSnapshot,
33-
} from "./session-accessor.sqlite-entry-cache.js";
30+
import { readSessionEntryCache } from "./session-accessor.sqlite-entry-cache.js";
3431
import {
3532
assertLifecycleTargetSnapshotUnchanged,
3633
type SqliteLifecycleTargetSnapshot,
@@ -312,7 +309,16 @@ function listSqliteSessionEntriesFromDatabase(
312309
scope: SessionEntryListScope,
313310
): SessionEntrySummary[] {
314311
assertCanonicalSqliteSessionKeysCurrent(database);
315-
const snapshot = readSessionEntrySnapshot(database, resolved, scope);
312+
const projection = scope.projection ?? "full";
313+
const cache = !isIncognitoOpenClawAgentSqlitePath(database.path, {
314+
agentId: database.agentId,
315+
env: resolved.env,
316+
});
317+
const snapshot = readSessionEntryCache(database, {
318+
cache,
319+
latest: scope.readConsistency === "latest",
320+
projection,
321+
});
316322
return snapshot.keys.flatMap((sessionKey) => {
317323
if (isInternalSessionEffectsKey(sessionKey)) {
318324
return [];
@@ -327,31 +333,16 @@ function listSqliteSessionEntriesFromDatabase(
327333
`non-canonical persisted row resolves to session key ${deliveryCanonicalKey}`,
328334
);
329335
}
336+
// Full snapshots own their nested values; list snapshots may share cached entries.
330337
return [
331338
{
332339
sessionKey,
333-
entry: scope.clone === false ? entry : cloneSessionEntry(entry),
340+
entry: projection === "list" && scope.clone !== false ? cloneSessionEntry(entry) : entry,
334341
},
335342
];
336343
});
337344
}
338345

339-
function readSessionEntrySnapshot(
340-
database: Pick<OpenClawAgentDatabase, "agentId" | "db" | "path">,
341-
resolved: ResolvedSqliteScope,
342-
scope: SessionEntryListScope,
343-
): SessionEntryCacheSnapshot {
344-
const cache = !isIncognitoOpenClawAgentSqlitePath(database.path, {
345-
agentId: database.agentId,
346-
env: resolved.env,
347-
});
348-
return readSessionEntryCache(database, {
349-
cache,
350-
latest: scope.readConsistency === "latest",
351-
projection: scope.projection ?? "full",
352-
});
353-
}
354-
355346
/** Lists only entries whose normalized session row has one of the requested statuses. */
356347
export function listSessionEntriesByStatus(
357348
scope: Partial<Omit<SessionAccessScope, "sessionKey">>,

‎src/plugins/config-state.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ export function isTestDefaultMemorySlotDisabled(
197197
return true;
198198
}
199199

200-
export function resolvePluginActivationState(params: {
200+
function resolvePluginActivationState(params: {
201201
id: string;
202202
origin: PluginOrigin;
203203
config: NormalizedPluginsConfig;

0 commit comments

Comments
 (0)