Skip to content

Commit 1b94810

Browse files
authored
fix(active-memory): share one recall per run across retries (#115627)
* fix(active-memory): share one recall per run across retries Register in-flight recalls per ctx.runId so overlapping or changed-prompt attempts join a single execution, and gate replacement recalls on settled timeout cleanup. Entries clear on agent_end. Fixes #106957. * fix(active-memory): evict rejected recall entries * test(active-memory): clarify run result retention * test(active-memory): complete recall result fixture
1 parent 82de022 commit 1b94810

5 files changed

Lines changed: 279 additions & 21 deletions

File tree

‎extensions/active-memory/index.test.ts‎

Lines changed: 175 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { appendSessionTranscriptMessageByIdentity } from "openclaw/plugin-sdk/se
1515
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
1616
import { applyCliRuntimeRecallTimeoutDefault } from "./config.js";
1717
import plugin, { testing } from "./index.js";
18+
import { resolveActiveRecallForRun } from "./recall-state.js";
1819
import { hasRememberAcrossConversationsAgent } from "./session-policy.js";
1920

2021
// Match only lone surrogates so valid supplementary-plane characters remain allowed.
@@ -715,12 +716,13 @@ describe("active-memory plugin", () => {
715716
stateDir = "";
716717
});
717718

718-
it("registers a before_prompt_build hook", () => {
719+
it("registers prompt-build and run-cleanup hooks", () => {
719720
const [hookName, handler, options] = firstHookRegistration();
720721
expect(hookName).toBe("before_prompt_build");
721722
expect(typeof handler).toBe("function");
722723
expect(options).toEqual({ timeoutMs: 153_000 });
723724
expect(hookOptions.before_prompt_build?.timeoutMs).toBe(153_000);
725+
expect(typeof hooks.agent_end).toBe("function");
724726
});
725727

726728
it("does not synthesize a main agent when every configured agent opts out", () => {
@@ -847,6 +849,178 @@ describe("active-memory plugin", () => {
847849
expect(secondSessionKey).not.toBe(firstSessionKey);
848850
});
849851

852+
it("shares recall results across changed-prompt retries in one run", async () => {
853+
const context = {
854+
runId: "run-changed-prompt-retry",
855+
sessionKey: "agent:main:changed-prompt-retry",
856+
};
857+
858+
const first = await runPromptBuild({ prompt: "what wings should i order?" }, context);
859+
const second = await runPromptBuild(
860+
{ prompt: "actually, what did I order last time?" },
861+
context,
862+
);
863+
864+
expectPrependContextContains(first, "lemon pepper wings");
865+
expectPrependContextContains(second, "lemon pepper wings");
866+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(1);
867+
});
868+
869+
it("joins concurrent recall attempts in one run", async () => {
870+
let releaseRecall: () => void = () => {
871+
throw new Error("recall gate was not initialized");
872+
};
873+
const recallGate = new Promise<void>((resolve) => {
874+
releaseRecall = resolve;
875+
});
876+
runEmbeddedAgent.mockImplementationOnce(async (params: { sessionFile: string }) => {
877+
await recallGate;
878+
await writeUsableMemoryTranscript(params.sessionFile, "lemon pepper wings");
879+
return { payloads: [{ text: "- lemon pepper wings" }] };
880+
});
881+
const context = {
882+
runId: "run-concurrent-attempts",
883+
sessionKey: "agent:main:concurrent-attempts",
884+
};
885+
886+
const first = runPromptBuild({ prompt: "what wings should i order?" }, context);
887+
await vi.waitFor(() => {
888+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(1);
889+
});
890+
const second = runPromptBuild({ prompt: "what wings did I order last time?" }, context);
891+
await new Promise<void>((resolve) => {
892+
setImmediate(resolve);
893+
});
894+
895+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(1);
896+
releaseRecall();
897+
const [firstResult, secondResult] = await Promise.all([first, second]);
898+
expectPrependContextContains(firstResult, "lemon pepper wings");
899+
expectPrependContextContains(secondResult, "lemon pepper wings");
900+
});
901+
902+
it("waits for timeout cleanup before replacing a recall in the same run", async () => {
903+
testing.setMinimumTimeoutMsForTests(1);
904+
testing.setSetupGraceTimeoutMsForTests(0);
905+
registerPluginConfig({ timeoutMs: 100, logging: true });
906+
let releaseCleanup: () => void = () => {
907+
throw new Error("cleanup gate was not initialized");
908+
};
909+
const cleanupGate = new Promise<void>((resolve) => {
910+
releaseCleanup = resolve;
911+
});
912+
hoisted.closeActiveMemorySearchManager.mockImplementationOnce(async () => {
913+
await cleanupGate;
914+
});
915+
runEmbeddedAgent.mockImplementationOnce(
916+
async (params: { abortSignal?: AbortSignal }) => await waitForAbort(params.abortSignal),
917+
);
918+
const context = {
919+
runId: "run-timeout-retry",
920+
sessionKey: "agent:main:timeout-retry",
921+
};
922+
923+
await expect(
924+
runPromptBuild({ prompt: "what wings should i order before timeout?" }, context),
925+
).resolves.toBeUndefined();
926+
await vi.waitFor(() => {
927+
expect(hoisted.closeActiveMemorySearchManager).toHaveBeenCalledTimes(1);
928+
});
929+
930+
const retry = runPromptBuild({ prompt: "what wings should i order after timeout?" }, context);
931+
await new Promise<void>((resolve) => {
932+
setImmediate(resolve);
933+
});
934+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(1);
935+
936+
releaseCleanup();
937+
await expect(retry).resolves.toEqual(
938+
expect.objectContaining({ prependContext: expect.stringContaining("lemon pepper wings") }),
939+
);
940+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(2);
941+
});
942+
943+
it("evicts a rejected replacement after timeout cleanup settles", async () => {
944+
let releaseCleanup: () => void = () => {
945+
throw new Error("cleanup gate was not initialized");
946+
};
947+
const cleanupGate = new Promise<void>((resolve) => {
948+
releaseCleanup = resolve;
949+
});
950+
const initialResult = { status: "timeout" as const, elapsedMs: 1, summary: null };
951+
await expect(
952+
resolveActiveRecallForRun("run-rejected-replacement", async (onTimeoutCleanup) => {
953+
onTimeoutCleanup(cleanupGate);
954+
return initialResult;
955+
}),
956+
).resolves.toEqual(initialResult);
957+
958+
let rejectedReplacementStarts = 0;
959+
const rejectedReplacement = resolveActiveRecallForRun("run-rejected-replacement", async () => {
960+
rejectedReplacementStarts++;
961+
throw new Error("retry deadline expired");
962+
});
963+
releaseCleanup();
964+
await expect(rejectedReplacement).rejects.toThrow("retry deadline expired");
965+
966+
const freshResult = {
967+
status: "ok" as const,
968+
elapsedMs: 2,
969+
rawReply: "recovered",
970+
summary: "recovered",
971+
};
972+
let freshStarts = 0;
973+
await expect(
974+
resolveActiveRecallForRun("run-rejected-replacement", async () => {
975+
freshStarts++;
976+
return freshResult;
977+
}),
978+
).resolves.toEqual(freshResult);
979+
expect({ freshStarts, rejectedReplacementStarts }).toEqual({
980+
freshStarts: 1,
981+
rejectedReplacementStarts: 1,
982+
});
983+
});
984+
985+
it("deduplicates cache-disabled private recall until the run ends", async () => {
986+
setMemorySlot("memory-core");
987+
configFile = {
988+
...configFile,
989+
agents: {
990+
defaults: {
991+
model: { primary: "github-copilot/gpt-5.4-mini" },
992+
},
993+
list: [
994+
{
995+
id: "main",
996+
memory: { search: { rememberAcrossConversations: true } },
997+
},
998+
],
999+
},
1000+
};
1001+
const context = {
1002+
runId: "run-private-recall",
1003+
sessionKey: "agent:main:telegram:direct:owner",
1004+
messageProvider: "telegram",
1005+
channelId: "owner",
1006+
};
1007+
seedSession(context.sessionKey, "s-private-recall", 0);
1008+
1009+
await runPromptBuild({ prompt: "what wings should i order?" }, context);
1010+
await runPromptBuild({ prompt: "what wings should i order?" }, context);
1011+
1012+
expect(lastEmbeddedRunParams().conversationRecall).toEqual({
1013+
anchorSessionKey: context.sessionKey,
1014+
scope: "same-agent-private",
1015+
corpus: "configured",
1016+
});
1017+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(1);
1018+
1019+
await requireHook("agent_end")({ runId: context.runId, messages: [], success: true }, context);
1020+
await runPromptBuild({ prompt: "what wings should i order?" }, context);
1021+
expect(runEmbeddedAgent).toHaveBeenCalledTimes(2);
1022+
});
1023+
8501024
it("retries transient SQLite recall cleanup failures", async () => {
8511025
hoisted.cleanupSessionLifecycleArtifacts.mockRejectedValueOnce(
8521026
new Error("session store is busy"),

‎extensions/active-memory/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { buildQuery, buildSearchQuery, extractRecentTurns, getModelRef } from ".
2323
import {
2424
buildCacheKey,
2525
buildCircuitBreakerKey,
26+
forgetActiveRecallRun,
2627
getCachedResult,
2728
getCircuitBreakerEntry,
2829
isCircuitBreakerOpen,
@@ -459,6 +460,7 @@ export default definePluginEntry({
459460
currentModelId: ctx.modelId,
460461
conversationRecall,
461462
abortSignal: deadlineController.signal,
463+
runId: ctx.runId,
462464
});
463465
deadlineController.signal.throwIfAborted();
464466
if (!result.summary) {
@@ -493,6 +495,9 @@ export default definePluginEntry({
493495
},
494496
{ timeoutMs: beforePromptBuildTimeoutMs },
495497
);
498+
api.on("agent_end", (event, ctx) => {
499+
forgetActiveRecallRun(event.runId ?? ctx.runId);
500+
});
496501
},
497502
});
498503

‎extensions/active-memory/recall-state.ts‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ import {
1818

1919
let lastActiveRecallCacheSweepAt = 0;
2020
const activeRecallCache = new Map<string, CachedActiveRecallResult>();
21+
type ActiveRecallRunEntry = {
22+
promise: Promise<ActiveRecallResult>;
23+
timeoutCleanup?: Promise<void>;
24+
};
25+
const activeRecallRuns = new Map<string, ActiveRecallRunEntry>();
2126
const timeoutCircuitBreaker = new Map<string, CircuitBreakerEntry>();
2227

2328
function buildCircuitBreakerKey(agentId: string, provider?: string, model?: string): string {
@@ -55,22 +60,74 @@ function scheduleMemorySearchCleanupAfterTimeout(
5560
api: OpenClawPluginApi,
5661
logPrefix: string,
5762
agentId: string,
58-
): void {
59-
const cfg = resolveActiveMemoryCleanupConfig(api);
60-
setTimeout(() => {
61-
void closeActiveMemorySearchManager({ cfg: cfg ?? api.config, agentId })
62-
.then(() => {
63-
api.logger.debug?.(`${logPrefix} released memory search managers after timeout`);
64-
})
65-
.catch((error: unknown) => {
66-
const message = toSingleLineLogValue(
67-
error instanceof Error ? error.message : String(error),
68-
);
69-
api.logger.warn?.(
70-
`${logPrefix} failed to release memory search managers after timeout: ${message}`,
71-
);
72-
});
73-
}, 0);
63+
): Promise<void> {
64+
return new Promise((resolve) => {
65+
const cfg = resolveActiveMemoryCleanupConfig(api);
66+
setTimeout(() => {
67+
void closeActiveMemorySearchManager({ cfg: cfg ?? api.config, agentId })
68+
.then(() => {
69+
api.logger.debug?.(`${logPrefix} released memory search managers after timeout`);
70+
})
71+
.catch((error: unknown) => {
72+
const message = toSingleLineLogValue(
73+
error instanceof Error ? error.message : String(error),
74+
);
75+
api.logger.warn?.(
76+
`${logPrefix} failed to release memory search managers after timeout: ${message}`,
77+
);
78+
})
79+
.finally(resolve);
80+
}, 0);
81+
});
82+
}
83+
84+
async function resolveActiveRecallForRun(
85+
runId: string,
86+
start: (onTimeoutCleanup: (cleanup: Promise<void>) => void) => Promise<ActiveRecallResult>,
87+
): Promise<ActiveRecallResult> {
88+
const existing = activeRecallRuns.get(runId);
89+
if (existing?.timeoutCleanup) {
90+
// A replacement must not reuse managers while the timed-out recall or its
91+
// cleanup is still settling; concurrent callers then join the replacement.
92+
await Promise.allSettled([existing.promise, existing.timeoutCleanup]);
93+
if (activeRecallRuns.get(runId) === existing) {
94+
activeRecallRuns.delete(runId);
95+
}
96+
return await resolveActiveRecallForRun(runId, start);
97+
}
98+
if (existing) {
99+
return await existing.promise;
100+
}
101+
102+
const entry: ActiveRecallRunEntry = {
103+
promise: Promise.resolve().then(() =>
104+
start((cleanup) => {
105+
entry.timeoutCleanup = cleanup;
106+
void Promise.allSettled([entry.promise, cleanup]).then(() => {
107+
if (activeRecallRuns.get(runId) === entry) {
108+
activeRecallRuns.delete(runId);
109+
}
110+
});
111+
}),
112+
),
113+
};
114+
activeRecallRuns.set(runId, entry);
115+
void entry.promise.catch(() => {
116+
// Failures before timeout cleanup starts must not poison this run;
117+
// timeout-backed entries stay registered until manager cleanup settles.
118+
if (!entry.timeoutCleanup && activeRecallRuns.get(runId) === entry) {
119+
activeRecallRuns.delete(runId);
120+
}
121+
});
122+
// Fulfilled results remain stable through agent_end, including `failed`;
123+
// rerunning them would recreate the redundant same-turn recalls this registry prevents.
124+
return await entry.promise;
125+
}
126+
127+
function forgetActiveRecallRun(runId: string | undefined): void {
128+
if (runId) {
129+
activeRecallRuns.delete(runId);
130+
}
74131
}
75132

76133
function buildCacheKey(params: {
@@ -172,6 +229,7 @@ function shouldCacheResult(result: ActiveRecallResult): boolean {
172229

173230
function resetActiveRecallStateForTests(): void {
174231
activeRecallCache.clear();
232+
activeRecallRuns.clear();
175233
timeoutCircuitBreaker.clear();
176234
lastActiveRecallCacheSweepAt = 0;
177235
}
@@ -186,9 +244,11 @@ export {
186244
getCachedResult,
187245
getCircuitBreakerEntry,
188246
isCircuitBreakerOpen,
247+
forgetActiveRecallRun,
189248
recordCircuitBreakerTimeout,
190249
resetActiveRecallStateForTests,
191250
resetCircuitBreaker,
251+
resolveActiveRecallForRun,
192252
scheduleMemorySearchCleanupAfterTimeout,
193253
setCachedResult,
194254
shouldCacheResult,

0 commit comments

Comments
 (0)