Skip to content

Commit ec3077c

Browse files
authored
improve: reduce session import, compaction, and UI startup overhead (#133446)
* perf(sessions): hash staged import rows without stream objects * perf(agents): resolve compaction indexing without embedding discovery * perf(ui): avoid redundant duration formatting at startup
1 parent 6c93c1c commit ec3077c

6 files changed

Lines changed: 83 additions & 42 deletions

File tree

‎src/agents/embedded-agent-runner/compact.hooks.harness.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1019,7 +1019,7 @@ export async function loadCompactHooksHarness(): Promise<{
10191019
}));
10201020

10211021
vi.doMock("../memory-search.js", () => ({
1022-
resolveMemorySearchConfig: resolveMemorySearchConfigMock,
1022+
resolveMemorySearchIndexConfig: resolveMemorySearchConfigMock,
10231023
}));
10241024

10251025
vi.doMock("../runtime-plan/build.js", () => ({

‎src/agents/embedded-agent-runner/compaction-hooks.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
88
import { getActiveMemorySearchManagerCore } from "../../plugins/memory-runtime.js";
99
import { emitSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
1010
import { resolveSessionAgentId } from "../agent-scope.js";
11-
import { resolveMemorySearchConfig } from "../memory-search.js";
11+
import { resolveMemorySearchIndexConfig } from "../memory-search.js";
1212
import type { AgentMessage } from "../runtime/index.js";
1313
import { log } from "./logger.js";
1414

@@ -43,7 +43,9 @@ async function runPostCompactionSessionMemorySync(params: PostCompactionSession)
4343
config: params.config,
4444
agentId: params.agentId,
4545
});
46-
const resolvedMemory = resolveMemorySearchConfig(params.config, agentId);
46+
// The memory backend owns provider resolution; an unavailable backend must
47+
// not cold-load embedding plugins just to decide whether to sync.
48+
const resolvedMemory = resolveMemorySearchIndexConfig(params.config, agentId);
4749
if (!resolvedMemory || !resolvedMemory.sources.includes("sessions")) {
4850
return;
4951
}

‎src/agents/memory-search.ts‎

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -176,17 +176,49 @@ function getConfiguredMemoryEmbeddingProvider(
176176
return getMemoryEmbeddingProvider(providerId, cfg);
177177
}
178178

179-
function mergeConfig(
180-
cfg: OpenClawConfig,
181-
defaults: MemorySearchConfig | undefined,
182-
overrides: MemorySearchConfig | undefined,
183-
agentId: string,
184-
): ResolvedMemorySearchConfig {
179+
/** Resolves indexing eligibility without loading an embedding provider runtime. */
180+
export function resolveMemorySearchIndexConfig(cfg: OpenClawConfig, agentId: string) {
181+
const defaults = cfg.memory?.search;
182+
const overrides = resolveAgentConfig(cfg, agentId)?.memory?.search;
185183
const enabled = overrides?.enabled ?? defaults?.enabled ?? true;
184+
if (!enabled) {
185+
return null;
186+
}
187+
assertSecretOwnerAvailable("capability", runtimeMemorySecretOwnerId(agentId));
186188
const rememberAcrossConversations = resolveRememberAcrossConversations(cfg, agentId);
187189
const configuredSessionMemory =
188190
overrides?.experimental?.sessionMemory ?? defaults?.experimental?.sessionMemory ?? false;
189191
const sessionMemory = rememberAcrossConversations || configuredSessionMemory;
192+
const configuredSources = overrides?.sources ?? defaults?.sources;
193+
const searchSources = normalizeSources(
194+
configuredSources,
195+
configuredSessionMemory ||
196+
(rememberAcrossConversations && configuredSources?.includes("sessions") === true),
197+
);
198+
const sources = normalizeSources(
199+
rememberAcrossConversations ? [...searchSources, "sessions"] : configuredSources,
200+
sessionMemory,
201+
);
202+
return {
203+
enabled,
204+
rememberAcrossConversations,
205+
sources,
206+
searchSources,
207+
experimental: { sessionMemory },
208+
sync: resolveSyncConfig(),
209+
};
210+
}
211+
212+
function mergeConfig(
213+
cfg: OpenClawConfig,
214+
defaults: MemorySearchConfig | undefined,
215+
overrides: MemorySearchConfig | undefined,
216+
agentId: string,
217+
): ResolvedMemorySearchConfig | null {
218+
const indexConfig = resolveMemorySearchIndexConfig(cfg, agentId);
219+
if (!indexConfig) {
220+
return null;
221+
}
190222
const rawProvider = overrides?.provider ?? defaults?.provider;
191223
const provider =
192224
rawProvider?.trim() === "auto"
@@ -239,16 +271,6 @@ function mergeConfig(
239271
const local = {
240272
modelPath: overrides?.local?.modelPath ?? defaults?.local?.modelPath,
241273
};
242-
const configuredSources = overrides?.sources ?? defaults?.sources;
243-
const searchSources = normalizeSources(
244-
configuredSources,
245-
configuredSessionMemory ||
246-
(rememberAcrossConversations && configuredSources?.includes("sessions") === true),
247-
);
248-
const sources = normalizeSources(
249-
rememberAcrossConversations ? [...searchSources, "sessions"] : configuredSources,
250-
sessionMemory,
251-
);
252274
const extraPaths = normalizeConfiguredMemoryExtraPaths([
253275
...(defaults?.extraPaths ?? []),
254276
...(overrides?.extraPaths ?? []),
@@ -276,7 +298,6 @@ function mergeConfig(
276298
tokens: DEFAULT_CHUNK_TOKENS,
277299
overlap: DEFAULT_CHUNK_OVERLAP,
278300
};
279-
const sync = resolveSyncConfig();
280301
const query = {
281302
maxResults: overrides?.query?.maxResults ?? defaults?.query?.maxResults ?? DEFAULT_MAX_RESULTS,
282303
minScore: overrides?.query?.minScore ?? defaults?.query?.minScore ?? DEFAULT_MIN_SCORE,
@@ -302,17 +323,11 @@ function mergeConfig(
302323

303324
const minScore = clampNumber(query.minScore, 0, 1);
304325
return {
305-
enabled,
306-
rememberAcrossConversations,
307-
sources,
308-
searchSources,
326+
...indexConfig,
309327
extraPaths,
310328
multimodal,
311329
provider,
312330
remote,
313-
experimental: {
314-
sessionMemory,
315-
},
316331
fallback,
317332
model,
318333
inputType,
@@ -322,7 +337,6 @@ function mergeConfig(
322337
local,
323338
store,
324339
chunking,
325-
sync,
326340
query: {
327341
...query,
328342
minScore,
@@ -355,10 +369,9 @@ export function resolveMemorySearchConfig(
355369
const defaults = cfg.memory?.search;
356370
const overrides = resolveAgentConfig(cfg, agentId)?.memory?.search;
357371
const resolved = mergeConfig(cfg, defaults, overrides, agentId);
358-
if (!resolved.enabled) {
372+
if (!resolved) {
359373
return null;
360374
}
361-
assertSecretOwnerAvailable("capability", runtimeMemorySecretOwnerId(agentId));
362375
const isFtsOnly = normalizeProviderId(resolved.provider) === "none";
363376
const multimodalActive = isMemoryMultimodalEnabled(resolved.multimodal);
364377
const multimodalProvider = isFtsOnly

‎src/config/sessions/session-accessor.sqlite-import-stage.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Disposable migration spool: never registered, resumed, or read by the runtime.
2-
import { createHash } from "node:crypto";
2+
import { hash } from "node:crypto";
33
import fs from "node:fs";
44
import os from "node:os";
55
import path from "node:path";
@@ -72,7 +72,7 @@ export class SqliteSessionImportStage {
7272

7373
*iterateUnseenEvents(source: number): Generator<TranscriptEvent, void, boolean> {
7474
for (const row of this.rows(source)) {
75-
const eventHash = createHash("sha256").update(row.eventJson).digest();
75+
const eventHash = hash("sha256", row.eventJson, "buffer");
7676
// Hash narrows the lookup; exact bytes decide equality even under a hash collision.
7777
if (this.findSeen.get(eventHash, row.eventJson) !== undefined) {
7878
continue;
@@ -87,6 +87,6 @@ export class SqliteSessionImportStage {
8787
}
8888

8989
addSeen(eventJson: string): void {
90-
this.insertSeen.run(createHash("sha256").update(eventJson).digest(), eventJson);
90+
this.insertSeen.run(hash("sha256", eventJson, "buffer"), eventJson);
9191
}
9292
}

‎ui/src/lib/format.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,24 @@ describe("formatAgo", () => {
6565
});
6666

6767
describe("localized durations", () => {
68+
it.each([undefined, null, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, -1])(
69+
"preserves invalid duration fallbacks for %s",
70+
(durationMs) => {
71+
expect(formatDurationCompact(durationMs)).toBeUndefined();
72+
expect(formatDurationHuman(durationMs, "unavailable")).toBe("unavailable");
73+
},
74+
);
75+
76+
it("keeps zero distinct from a positive duration rounded to zero", () => {
77+
expect(formatDurationCompact(0)).toBeUndefined();
78+
expect(formatDurationCompact(0.1)).toBe("0ms");
79+
expect(formatDurationHuman(0)).toBe("0ms");
80+
});
81+
6882
it.each([
83+
{ durationMs: 999.5, expected: "1s" },
6984
{ durationMs: 59_000, expected: "59s" },
85+
{ durationMs: 59_500, expected: "1m" },
7086
{ durationMs: 92_000, expected: "1m 32s" },
7187
{ durationMs: 3_660_000, expected: "1h 1m" },
7288
{ durationMs: 49 * 60 * 60 * 1000, expected: "2d 1h" },
@@ -77,6 +93,22 @@ describe("localized durations", () => {
7793
it("switches human durations to days at 24 hours", () => {
7894
expect(formatDurationHuman(36 * 60 * 60 * 1000)).toBe("2d");
7995
});
96+
97+
it("uses the active locale for both duration formats", async () => {
98+
await i18n.setLocale("fr");
99+
try {
100+
const minute = new Intl.NumberFormat("fr", {
101+
style: "unit",
102+
unit: "minute",
103+
unitDisplay: "narrow",
104+
maximumFractionDigits: 0,
105+
}).format(1);
106+
expect(formatDurationCompact(60_000)).toBe(minute);
107+
expect(formatDurationHuman(60_000)).toBe(minute);
108+
} finally {
109+
await i18n.setLocale("en");
110+
}
111+
});
80112
});
81113

82114
describe("formatTimeAgo", () => {

‎ui/src/lib/format.ts‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,6 @@ import { bucketRelativeTimeMs, type RelativeTimeUnit } from "@openclaw/normaliza
22
// Control UI module implements format behavior.
33
import { asDateTimestampMs } from "@openclaw/normalization-core/number-coercion";
44
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
5-
import {
6-
formatDurationCompact as formatDurationCompactCore,
7-
formatDurationHuman as formatDurationHumanCore,
8-
} from "../../../src/infra/format-time/format-duration.ts";
95
import { i18n, t } from "../i18n/index.ts";
106
import { formatUiError } from "./format-error.ts";
117

@@ -99,9 +95,8 @@ export function formatRelativeTimestamp(
9995
}
10096

10197
export function formatDurationCompact(ms?: number | null): string | undefined {
102-
const coreValue = formatDurationCompactCore(ms, { spaced: true });
103-
if (!coreValue || ms == null || !Number.isFinite(ms) || ms <= 0) {
104-
return coreValue;
98+
if (ms == null || !Number.isFinite(ms) || ms <= 0) {
99+
return undefined;
105100
}
106101
const roundedMs = Math.round(ms);
107102
if (roundedMs < 1000) {
@@ -139,9 +134,8 @@ export function formatDurationCompact(ms?: number | null): string | undefined {
139134
}
140135

141136
export function formatDurationHuman(ms?: number | null, fallback = t("common.na")): string {
142-
const coreValue = formatDurationHumanCore(ms, fallback);
143137
if (ms == null || !Number.isFinite(ms) || ms < 0) {
144-
return coreValue;
138+
return fallback;
145139
}
146140
if (ms < 1000) {
147141
return formatUnit(Math.round(ms), "millisecond");

0 commit comments

Comments
 (0)