Skip to content

Commit 0dd1ca5

Browse files
authored
fix(sessions): isolate maintenance from channel plugin resolvers (#129490)
1 parent 3f6f679 commit 0dd1ca5

3 files changed

Lines changed: 129 additions & 3 deletions

File tree

‎src/config/sessions/session-accessor.conformance.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
writePersistedAuthProfileStateRaw,
88
} from "../../agents/auth-profiles/sqlite.js";
99
import { executeSqliteQueryTakeFirstSync, getNodeSqliteKysely } from "../../infra/kysely-sync.js";
10+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
1011
import { beginSessionWorkAdmission } from "../../sessions/session-lifecycle-admission.js";
1112
import { onSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
1213
import type { DB as OpenClawAgentKyselyDatabase } from "../../state/openclaw-agent-db.generated.js";
@@ -15,6 +16,7 @@ import {
1516
openOpenClawAgentDatabase,
1617
} from "../../state/openclaw-agent-db.js";
1718
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
19+
import { createTestRegistry } from "../../test-utils/channel-plugins.js";
1820
import { appendSqliteTrajectoryRuntimeEvents } from "../../trajectory/runtime-store.sqlite.js";
1921
import { normalizeSessionDeliveryState } from "../../utils/delivery-context.shared.js";
2022
import { readSessionArchiveContentSync } from "./archive-compression.js";
@@ -1660,6 +1662,65 @@ describe("sqlite session normalization", () => {
16601662
).toEqual(["agent:main:newer", "agent:main:newest"]);
16611663
});
16621664

1665+
it("commits unrelated channel sessions without invoking stored channel plugin resolvers", async () => {
1666+
vi.mocked(getRuntimeConfig).mockReturnValue({
1667+
session: { maintenance: { mode: "enforce", pruneAfter: "1d", maxEntries: 2 } },
1668+
});
1669+
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
1670+
const scopeFor = (sessionKey: string) => ({
1671+
agentId: "main",
1672+
env,
1673+
sessionKey,
1674+
storePath: paths.sqlitePath,
1675+
});
1676+
const storedKey = "agent:main:broken:group:room:thread:reply";
1677+
const storedEntry = {
1678+
sessionId: "stored-channel-session",
1679+
updatedAt: Date.now() - 2 * 24 * 60 * 60 * 1000,
1680+
};
1681+
await patchSessionEntryCore(scopeFor(storedKey), () => storedEntry, {
1682+
fallbackEntry: storedEntry,
1683+
replaceEntry: true,
1684+
skipMaintenance: true,
1685+
});
1686+
1687+
const resolveSessionConversation = vi.fn(() => {
1688+
throw new Error("channel resolver must not run inside a SQLite write");
1689+
});
1690+
setActivePluginRegistry(
1691+
createTestRegistry([
1692+
{
1693+
pluginId: "broken",
1694+
source: "test",
1695+
plugin: {
1696+
id: "broken",
1697+
meta: { label: "Broken" },
1698+
messaging: { resolveSessionConversation },
1699+
},
1700+
},
1701+
]),
1702+
);
1703+
1704+
try {
1705+
for (const channel of ["telegram", "discord"]) {
1706+
const sessionKey = `agent:main:${channel}:direct:user`;
1707+
const entry = { sessionId: `${channel}-session`, updatedAt: Date.now() };
1708+
await expect(
1709+
patchSessionEntryCore(scopeFor(sessionKey), () => entry, {
1710+
fallbackEntry: entry,
1711+
replaceEntry: true,
1712+
}),
1713+
).resolves.toMatchObject(entry);
1714+
expect(loadSessionEntry(scopeFor(sessionKey))).toMatchObject(entry);
1715+
}
1716+
1717+
expect(loadSessionEntry(scopeFor(storedKey))).toMatchObject(storedEntry);
1718+
expect(resolveSessionConversation).not.toHaveBeenCalled();
1719+
} finally {
1720+
resetPluginRuntimeStateForTest();
1721+
}
1722+
});
1723+
16631724
it("persists automatic dashboard archiving before stale-entry pruning", async () => {
16641725
vi.mocked(getRuntimeConfig).mockReturnValue({
16651726
session: {

‎src/config/sessions/store-maintenance-recent-preservation.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,83 @@
11
// Recent-session preservation tests cover the operator-configured retention shield.
22
import path from "node:path";
3-
import { describe, expect, it } from "vitest";
3+
import { describe, expect, it, vi } from "vitest";
4+
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../../plugins/runtime.js";
45
import { withTestDir } from "../../test-helpers/temp-dir.js";
6+
import { createTestRegistry } from "../../test-utils/channel-plugins.js";
57
import { enforceSessionDiskBudget } from "./disk-budget.js";
68
import {
79
capEntryCount,
810
pruneStaleEntries,
911
resolveMaintenanceConfigFromInput,
12+
shouldPreserveMaintenanceEntry,
1013
} from "./store-maintenance.js";
1114
import type { SessionEntry } from "./types.js";
1215

1316
const DAY_MS = 24 * 60 * 60 * 1000;
1417

1518
describe("recent session maintenance preservation", () => {
19+
it.each(["classification", "pruning", "capping"] as const)(
20+
"preserves external conversations during %s without invoking channel plugins",
21+
(boundary) => {
22+
const resolveSessionConversation = vi.fn(() => {
23+
throw new Error("channel resolver must not run during session maintenance");
24+
});
25+
setActivePluginRegistry(
26+
createTestRegistry([
27+
{
28+
pluginId: "broken",
29+
source: "test",
30+
plugin: {
31+
id: "broken",
32+
meta: { label: "Broken" },
33+
messaging: { resolveSessionConversation },
34+
},
35+
},
36+
]),
37+
);
38+
39+
const updatedAt = Date.now() - 31 * DAY_MS;
40+
const protectedKeys = [
41+
"agent:main:broken:group:room:thread:reply",
42+
"agent:main:broken:channel:room:with:colon",
43+
"agent:main:telegram:dm:user:topic:77",
44+
"agent:main:opaque:thread:reply",
45+
];
46+
const removableKeys = [
47+
"agent:main:old",
48+
"agent:main:subagent:worker",
49+
"agent:main:opaque:topic:unrelated",
50+
];
51+
const store: Record<string, SessionEntry> = Object.fromEntries(
52+
[...protectedKeys, ...removableKeys].map((key) => [key, { sessionId: key, updatedAt }]),
53+
);
54+
55+
try {
56+
if (boundary === "classification") {
57+
for (const key of protectedKeys) {
58+
expect(shouldPreserveMaintenanceEntry({ key, entry: store[key] })).toBe(true);
59+
}
60+
for (const key of removableKeys) {
61+
expect(shouldPreserveMaintenanceEntry({ key, entry: store[key] })).toBe(false);
62+
}
63+
} else if (boundary === "pruning") {
64+
expect(pruneStaleEntries(store, 30 * DAY_MS, { log: false })).toBe(removableKeys.length);
65+
} else {
66+
expect(capEntryCount(store, protectedKeys.length, { log: false })).toBe(
67+
removableKeys.length,
68+
);
69+
}
70+
71+
for (const key of protectedKeys) {
72+
expect(store).toHaveProperty(key);
73+
}
74+
expect(resolveSessionConversation).not.toHaveBeenCalled();
75+
} finally {
76+
resetPluginRuntimeStateForTest();
77+
}
78+
},
79+
);
80+
1681
it("is opt-in and keeps recent interactive sessions through prune and cap pressure", () => {
1782
const now = Date.now();
1883
const recentKey = "agent:main:dashboard:recent";

‎src/config/sessions/store-maintenance.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ import {
1111
isCronSessionKey,
1212
isSubagentSessionKey,
1313
parseAgentSessionKey,
14+
parseThreadSessionSuffix,
1415
} from "../../sessions/session-key-utils.js";
1516
import { sessionDeliveryOrigin } from "../../utils/delivery-context.shared.js";
1617
import type { SessionMaintenanceConfig, SessionMaintenanceMode } from "../types.base.js";
17-
import { parseSessionThreadInfoFast } from "./thread-info.js";
1818
import type { SessionEntry } from "./types.js";
1919

2020
const log = createSubsystemLogger("sessions/store");
@@ -533,7 +533,7 @@ function isProtectedSessionMaintenanceEntry(
533533
if (isPrimarySessionMaintenanceKey(sessionKey)) {
534534
return true;
535535
}
536-
if (parseSessionThreadInfoFast(sessionKey).threadId) {
536+
if (parseThreadSessionSuffix(sessionKey).threadId) {
537537
return true;
538538
}
539539
if (isTelegramTopicSessionKey(sessionKey)) {

0 commit comments

Comments
 (0)