Skip to content

Commit a73910d

Browse files
authored
fix(agents): resolve authoritative session keys for delegated compaction (#120047)
* fix(agents): resolve authoritative session keys for delegated compaction * refactor(agents): keep session-target resolution error class module-local
1 parent d9ffbb3 commit a73910d

25 files changed

Lines changed: 385 additions & 104 deletions

‎src/agents/command/attempt-execution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,7 @@ export async function persistCliTurnTranscript(params: {
486486
const sessionTarget = await resolveAgentRunSessionTarget({
487487
agentId: params.sessionAgentId,
488488
config: params.config,
489+
missingSessionKey: "resolve-existing",
489490
sessionFile: params.sessionFile,
490491
sessionId: params.sessionId,
491492
sessionKey: params.sessionKey,

‎src/agents/command/cli-compaction.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,10 +324,10 @@ async function compactCliTranscript(params: {
324324
params.contextEngine,
325325
{
326326
sessionId: params.sessionId,
327-
sessionKey: params.sessionKey || params.sessionId,
327+
sessionKey: params.sessionKey,
328328
sessionTarget: {
329329
sessionId: params.sessionId,
330-
sessionKey: params.sessionKey || params.sessionId,
330+
sessionKey: params.sessionKey,
331331
...(params.storePath ? { storePath: params.storePath } : {}),
332332
},
333333
tokenBudget: params.contextTokenBudget,

‎src/agents/embedded-agent-runner.e2e.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,7 @@ const resolveTestSessionTarget = async (params: {
240240
}) =>
241241
await resolveAgentRunSessionTarget({
242242
config: params.config,
243+
missingSessionKey: "create",
243244
sessionId: params.sessionId,
244245
sessionKey: params.sessionKey,
245246
});

‎src/agents/embedded-agent-runner/compact-reasons.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,14 @@ describe("classifyCompactionReason", () => {
6161
).toBe("guard_blocked");
6262
});
6363

64+
it("classifies transcript persistence failures without losing them as unknown", () => {
65+
expect(
66+
classifyCompactionReason(
67+
"Session transcript entry was not persisted: compaction-1: session-rebound",
68+
),
69+
).toBe("transcript_persistence_failed");
70+
});
71+
6472
it("keeps unclassified provider errors in the stable unknown bucket", () => {
6573
expect(classifyCompactionReason("No API provider registered for api: ollama")).toBe("unknown");
6674
});

‎src/agents/embedded-agent-runner/compact-reasons.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ export function classifyCompactionReason(reason?: string): string {
4848
if (text.includes("still exceeds target")) {
4949
return "live_context_still_exceeds_target";
5050
}
51+
if (text.includes("session transcript") && text.includes("not persisted")) {
52+
return "transcript_persistence_failed";
53+
}
5154
if (text.includes("guard")) {
5255
return "guard_blocked";
5356
}

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

Lines changed: 41 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ const sessionHook = (action: string): SessionHookEvent | undefined =>
278278
return event?.type === "session" && event.action === action;
279279
})?.[0] as SessionHookEvent | undefined;
280280

281-
async function runCompactionHooks(params: { sessionKey?: string; messageProvider?: string }) {
281+
async function runCompactionHooks(params: { sessionKey: string; messageProvider?: string }) {
282282
// Build metrics through the production helper so hook payload assertions stay
283283
// aligned with compaction token accounting.
284284
const originalMessages = sessionMessages.slice(1) as AgentMessage[];
@@ -1903,26 +1903,6 @@ describe("compactEmbeddedAgentSessionDirect hooks", () => {
19031903
);
19041904
});
19051905

1906-
it("uses sessionId as hook session key fallback when sessionKey is missing", async () => {
1907-
hookRunner.hasHooks.mockReturnValue(true);
1908-
await runCompactionHooks({});
1909-
1910-
expect(sessionHook("compact:before")?.sessionKey).toBe("session-1");
1911-
expect(sessionHook("compact:after")?.sessionKey).toBe("session-1");
1912-
expect(hookRunner.runBeforeCompaction).toHaveBeenCalledWith(
1913-
mockCallArg(hookRunner.runBeforeCompaction),
1914-
expectRecordFields(mockCallArg(hookRunner.runBeforeCompaction, 0, 1), {
1915-
sessionKey: "session-1",
1916-
}),
1917-
);
1918-
expect(hookRunner.runAfterCompaction).toHaveBeenCalledWith(
1919-
mockCallArg(hookRunner.runAfterCompaction),
1920-
expectRecordFields(mockCallArg(hookRunner.runAfterCompaction, 0, 1), {
1921-
sessionKey: "session-1",
1922-
}),
1923-
);
1924-
});
1925-
19261906
it("applies validated transcript before hooks even when it becomes empty", async () => {
19271907
hookRunner.hasHooks.mockReturnValue(true);
19281908
const beforeMetrics = compactTesting.buildBeforeCompactionHookMetrics({
@@ -2454,6 +2434,46 @@ describe("compactEmbeddedAgentSession hooks (ownsCompaction engine)", () => {
24542434
mockQueuedRouteAwareModel();
24552435
});
24562436

2437+
it("resolves the durable session key before invoking an owning context engine", async () => {
2438+
const dir = await mkdtemp(join(tmpdir(), "openclaw-compaction-session-key-"));
2439+
const storePath = join(dir, "sessions.json");
2440+
const sessionId = "9d6c8436-7cb2-4bd5-a302-e33305bfc8c4";
2441+
const sessionKey = "agent:main:telegram:direct:reporter";
2442+
try {
2443+
await upsertSessionEntry(
2444+
{ agentId: "main", sessionKey, storePath },
2445+
{ sessionId, updatedAt: 1 },
2446+
);
2447+
hookRunner.hasHooks.mockReturnValue(true);
2448+
2449+
const result = await compactEmbeddedAgentSession(
2450+
wrappedCompactionArgs({
2451+
agentId: "main",
2452+
config: { session: { store: storePath } },
2453+
sessionFile: "",
2454+
sessionId,
2455+
sessionKey: undefined,
2456+
sessionTarget: undefined,
2457+
}),
2458+
);
2459+
2460+
expect(result.ok).toBe(true);
2461+
expectRecordFields(mockCallArg(contextEngineCompactMock), {
2462+
sessionId,
2463+
sessionKey,
2464+
});
2465+
expectRecordFields(
2466+
(mockCallArg(contextEngineCompactMock) as { sessionTarget?: unknown }).sessionTarget,
2467+
{ agentId: "main", sessionId, sessionKey, storePath },
2468+
);
2469+
expectRecordFields(mockCallArg(hookRunner.runBeforeCompaction, 0, 1), { sessionKey });
2470+
expectRecordFields(mockCallArg(hookRunner.runAfterCompaction, 0, 1), { sessionKey });
2471+
} finally {
2472+
closeOpenClawAgentDatabasesForTest();
2473+
await rm(dir, { force: true, recursive: true });
2474+
}
2475+
});
2476+
24572477
it("uses the acquired gateway runtime generation for queued model resolution", async () => {
24582478
await compactEmbeddedAgentSession(
24592479
wrappedCompactionArgs({

‎src/agents/embedded-agent-runner/compact.queued.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ function buildContextEngineCompactionSessionTarget(
129129
params: CompactEmbeddedAgentSessionParams,
130130
): ContextEngineSessionTarget {
131131
const agentId = params.sessionTarget?.agentId ?? params.agentId;
132-
const sessionKey = params.sessionTarget?.sessionKey ?? params.sessionKey ?? params.sessionId;
132+
const sessionKey = params.sessionTarget?.sessionKey ?? params.sessionKey;
133133
const storePath = params.sessionTarget?.storePath;
134134
return {
135135
...(agentId ? { agentId } : {}),
@@ -239,7 +239,10 @@ function mergeSecondaryNativeHarnessCompactionDetails(params: {
239239
export async function compactEmbeddedAgentSession(
240240
params: CompactEmbeddedAgentSessionParams,
241241
): Promise<EmbeddedAgentCompactResult> {
242-
const runtimeTarget = await resolveAgentRunSessionTarget(params);
242+
const runtimeTarget = await resolveAgentRunSessionTarget({
243+
...params,
244+
missingSessionKey: "resolve-existing",
245+
});
243246
const resolvedParams = {
244247
...params,
245248
agentId: runtimeTarget.agentId,
@@ -302,7 +305,10 @@ async function compactEmbeddedAgentSessionImpl(
302305
if (inputParams.abortSignal?.aborted) {
303306
return createCompactionAbortedResult();
304307
}
305-
const runtimeTarget = await resolveAgentRunSessionTarget(inputParams);
308+
const runtimeTarget = await resolveAgentRunSessionTarget({
309+
...inputParams,
310+
missingSessionKey: "resolve-existing",
311+
});
306312
const agentIds = resolveSessionAgentIds({
307313
sessionKey: runtimeTarget.sessionKey,
308314
config: inputParams.config,
@@ -387,7 +393,10 @@ async function compactResolvedContextEngine(
387393
preparedModelRuntime: PreparedModelRuntimeSnapshot,
388394
releaseContextEngineOwnership: () => void,
389395
): Promise<EmbeddedAgentCompactResult> {
390-
const runtimeTarget = await resolveAgentRunSessionTarget(params);
396+
const runtimeTarget = await resolveAgentRunSessionTarget({
397+
...params,
398+
missingSessionKey: "resolve-existing",
399+
});
391400
const lockedHarnessRuntime =
392401
params.modelSelectionLocked === true
393402
? normalizeOptionalAgentRuntimeId(params.agentHarnessId)
@@ -613,7 +622,7 @@ async function compactResolvedContextEngine(
613622
const hookRunner = engineOwnsCompaction
614623
? asCompactionHookRunner(getGlobalHookRunner())
615624
: null;
616-
const hookSessionKey = params.sessionKey?.trim() || params.sessionId;
625+
const hookSessionKey = runtimeTarget.sessionKey;
617626
const { sessionAgentId } = resolveSessionAgentIds({
618627
sessionKey: params.sessionKey,
619628
config: params.config,

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,10 @@ export async function compactEmbeddedAgentSessionDirect(
130130
failure: { reason: "model_selection_locked" },
131131
};
132132
}
133-
const runSessionTarget = await resolveAgentRunSessionTarget(paramsBase);
133+
const runSessionTarget = await resolveAgentRunSessionTarget({
134+
...paramsBase,
135+
missingSessionKey: "resolve-existing",
136+
});
134137
const requestedParams: CompactEmbeddedAgentSessionParamsWithSessionFile = {
135138
...paramsBase,
136139
agentId: runSessionTarget.agentId,

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ export function buildBeforeCompactionHookMetrics(params: {
209209
export async function runBeforeCompactionHooks(params: {
210210
hookRunner?: CompactionHookRunner | null;
211211
sessionId: string;
212-
sessionKey?: string;
212+
sessionKey: string;
213213
sessionAgentId: string;
214214
workspaceDir: string;
215215
messageProvider?: string;
@@ -221,8 +221,8 @@ export async function runBeforeCompactionHooks(params: {
221221
sessionKey: string;
222222
}) => void | Promise<void>;
223223
}) {
224-
const missingSessionKey = !params.sessionKey || !params.sessionKey.trim();
225-
const hookSessionKey = params.sessionKey?.trim() || params.sessionId;
224+
const missingSessionKey = false;
225+
const hookSessionKey = params.sessionKey;
226226
try {
227227
const hookEvent = createInternalHookEvent("session", "compact:before", hookSessionKey, {
228228
sessionId: params.sessionId,

‎src/agents/embedded-agent-runner/compaction-runtime-context.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,7 @@ describe("buildContextEngineCompactionSessionTarget", () => {
779779
});
780780
});
781781

782-
it("uses the marker session id when its store has no mapped key yet", () => {
782+
it("leaves the key absent when a marker store has no mapped row", () => {
783783
const storePath = path.join(compactionTempDirs.make("compaction-marker-"), "sessions.json");
784784
const sessionId = "legacy-unmapped-session";
785785

@@ -788,6 +788,6 @@ describe("buildContextEngineCompactionSessionTarget", () => {
788788
sessionFile: formatSqliteSessionFileMarker({ agentId: "main", sessionId, storePath }),
789789
sessionId,
790790
}),
791-
).toMatchObject({ agentId: "main", sessionId, sessionKey: sessionId, storePath });
791+
).toEqual({ agentId: "main", sessionId, storePath });
792792
});
793793
});

0 commit comments

Comments
 (0)