Skip to content

Commit 1e6844b

Browse files
fix(discord): cache unavailable thread starters (#128653)
* fix(discord): cache unavailable thread starters * test(discord): prove thread starter cache over rest api * test(discord): satisfy proof lint guards * fix(discord): coalesce thread starter lookups * fix(discord): avoid coalescing incomplete metadata * test(discord): keep proof inside plugin boundary * test(discord): keep proof runner responsive * fix(discord): retry starters when parent type is unknown * fix(discord): preserve thread starter route ownership --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 6b6f196 commit 1e6844b

5 files changed

Lines changed: 301 additions & 25 deletions

File tree

‎extensions/discord/src/monitor/message-handler.context.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ export async function buildDiscordMessageProcessContext(params: {
269269
const starter = await resolveDiscordThreadStarter({
270270
channel: threadChannel,
271271
client,
272+
accountId,
272273
parentId: threadParentId,
273274
parentType: threadParentType,
274275
resolveTimestampMs,

‎extensions/discord/src/monitor/message-handler.process.room-events.test.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,8 @@ describe("processDiscordMessage session routing and room events", () => {
364364
});
365365

366366
it("omits thread starter context when the effective thread session already exists", async () => {
367-
const threadSessionKey = "agent:main:discord:channel:thread-1";
367+
const threadId = "thread-existing-session";
368+
const threadSessionKey = `agent:main:discord:channel:${threadId}`;
368369
readSessionUpdatedAt.mockImplementation((params?: unknown) => {
369370
const sessionKey = (params as { sessionKey?: string } | undefined)?.sessionKey;
370371
return sessionKey === threadSessionKey ? 1_700_000_000_000 : undefined;
@@ -383,17 +384,17 @@ describe("processDiscordMessage session routing and room events", () => {
383384
},
384385
baseSessionKey: threadSessionKey,
385386
route: BASE_CHANNEL_ROUTE,
386-
messageChannelId: "thread-1",
387+
messageChannelId: threadId,
387388
message: {
388389
id: "m1",
389-
channelId: "thread-1",
390+
channelId: threadId,
390391
content: "follow-up",
391392
timestamp: new Date().toISOString(),
392393
attachments: [],
393394
},
394395
messageText: "follow-up",
395396
baseText: "follow-up",
396-
threadChannel: { id: "thread-1", name: "child-thread" },
397+
threadChannel: { id: threadId, name: "child-thread" },
397398
threadParentId: "parent-1",
398399
client: { rest },
399400
channelConfig: { allowed: true, users: ["U2"] },
@@ -404,7 +405,7 @@ describe("processDiscordMessage session routing and room events", () => {
404405
expect(rest.get).toHaveBeenCalled();
405406
expectRecordFields(requireRecord(getLastDispatchCtx(), "dispatch context"), {
406407
SessionKey: threadSessionKey,
407-
MessageThreadId: "thread-1",
408+
MessageThreadId: threadId,
408409
ThreadLabel: "Discord thread #parent",
409410
});
410411
expect(getLastDispatchCtx()?.ThreadStarterBody).toBeUndefined();

‎extensions/discord/src/monitor/threading.cache.ts‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,33 @@ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
33
import type { DiscordThreadStarter } from "./threading.types.js";
44

55
type DiscordThreadStarterCacheEntry = {
6-
value: DiscordThreadStarter;
6+
value: DiscordThreadStarterCacheValue;
77
updatedAt: number;
88
};
99

10+
type DiscordThreadStarterCacheValue =
11+
| { kind: "hit"; starter: DiscordThreadStarter }
12+
| { kind: "miss" };
13+
1014
const DISCORD_THREAD_STARTER_CACHE_TTL_MS = 5 * 60 * 1000;
15+
const DISCORD_THREAD_STARTER_NEGATIVE_CACHE_TTL_MS = 30 * 1000;
1116
const DISCORD_THREAD_STARTER_CACHE_MAX = 500;
1217

1318
const DISCORD_THREAD_STARTER_CACHE = new Map<string, DiscordThreadStarterCacheEntry>();
1419

15-
export function getCachedThreadStarter(key: string, now: number): DiscordThreadStarter | undefined {
20+
export function getCachedThreadStarter(
21+
key: string,
22+
now: number,
23+
): DiscordThreadStarterCacheValue | undefined {
1624
const entry = DISCORD_THREAD_STARTER_CACHE.get(key);
1725
if (!entry) {
1826
return undefined;
1927
}
20-
if (now < entry.updatedAt || now - entry.updatedAt >= DISCORD_THREAD_STARTER_CACHE_TTL_MS) {
28+
const ttlMs =
29+
entry.value.kind === "miss"
30+
? DISCORD_THREAD_STARTER_NEGATIVE_CACHE_TTL_MS
31+
: DISCORD_THREAD_STARTER_CACHE_TTL_MS;
32+
if (now < entry.updatedAt || now - entry.updatedAt >= ttlMs) {
2133
DISCORD_THREAD_STARTER_CACHE.delete(key);
2234
return undefined;
2335
}
@@ -28,7 +40,7 @@ export function getCachedThreadStarter(key: string, now: number): DiscordThreadS
2840

2941
export function setCachedThreadStarter(
3042
key: string,
31-
value: DiscordThreadStarter,
43+
value: DiscordThreadStarterCacheValue,
3244
now: number,
3345
): void {
3446
DISCORD_THREAD_STARTER_CACHE.delete(key);

‎extensions/discord/src/monitor/threading.starter.test.ts‎

Lines changed: 235 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Discord tests cover threading.starter plugin behavior.
22
import { StickerFormatType } from "discord-api-types/v10";
33
import { describe, expect, it, vi } from "vitest";
4-
import { ChannelType, type Client } from "../internal/discord.js";
4+
import { ChannelType, DiscordError, type Client } from "../internal/discord.js";
55
import { getCachedThreadStarter, setCachedThreadStarter } from "./threading.cache.js";
66
import { resolveDiscordThreadStarter } from "./threading.js";
77

@@ -69,6 +69,10 @@ function createStarterMessage(overrides: ThreadStarterRestMessage = {}): ThreadS
6969
};
7070
}
7171

72+
function createDiscordError(status: number): DiscordError {
73+
return new DiscordError(new Response(null, { status }), {});
74+
}
75+
7276
function requireThreadStarter(
7377
result: Awaited<ReturnType<typeof resolveDiscordThreadStarter>>,
7478
): ResolvedThreadStarter {
@@ -78,6 +82,13 @@ function requireThreadStarter(
7882
return result;
7983
}
8084

85+
function requireCachedThreadStarter(value: ReturnType<typeof getCachedThreadStarter>) {
86+
if (!value || value.kind !== "hit") {
87+
throw new Error("expected cached Discord thread starter");
88+
}
89+
return value.starter;
90+
}
91+
8192
function firstRestGetPath(get: ReturnType<typeof vi.fn>): unknown {
8293
const [call] = get.mock.calls;
8394
if (!call) {
@@ -99,6 +110,7 @@ async function resolveStarter(params: {
99110
const result = await resolveDiscordThreadStarter({
100111
channel: { id: threadId },
101112
client,
113+
accountId: "test-account",
102114
parentId: params.parentId ?? "parent-1",
103115
parentType: params.parentType ?? ChannelType.GuildText,
104116
resolveTimestampMs: params.resolveTimestampMs ?? (() => undefined),
@@ -119,6 +131,7 @@ describe("resolveDiscordThreadStarter", () => {
119131
const params = {
120132
channel: { id: `active-thread-${++threadIdIndex}` },
121133
client,
134+
accountId: "test-account",
122135
parentId: "parent-1",
123136
parentType: ChannelType.GuildText,
124137
resolveTimestampMs: () => undefined,
@@ -148,7 +161,11 @@ describe("resolveDiscordThreadStarter", () => {
148161
{ name: "a clock rollback before the starter was fetched", now: 999_999 },
149162
])("invalidates cached thread starters at $name", ({ now }) => {
150163
const key = `expired-thread-${++threadIdIndex}`;
151-
setCachedThreadStarter(key, { text: "stale", author: "Alice" }, 1_000_000);
164+
setCachedThreadStarter(
165+
key,
166+
{ kind: "hit", starter: { text: "stale", author: "Alice" } },
167+
1_000_000,
168+
);
152169

153170
expect(getCachedThreadStarter(key, now)).toBeUndefined();
154171
});
@@ -158,17 +175,227 @@ describe("resolveDiscordThreadStarter", () => {
158175
for (let index = 0; index < 500; index += 1) {
159176
setCachedThreadStarter(
160177
`${prefix}${index}`,
161-
{ text: `starter-${index}`, author: "Alice" },
178+
{ kind: "hit", starter: { text: `starter-${index}`, author: "Alice" } },
162179
1_000_000,
163180
);
164181
}
165182

166-
expect(getCachedThreadStarter(`${prefix}0`, 1_000_001)?.text).toBe("starter-0");
167-
setCachedThreadStarter(`${prefix}500`, { text: "new starter", author: "Alice" }, 1_000_002);
168-
169-
expect(getCachedThreadStarter(`${prefix}0`, 1_000_003)?.text).toBe("starter-0");
183+
expect(requireCachedThreadStarter(getCachedThreadStarter(`${prefix}0`, 1_000_001)).text).toBe(
184+
"starter-0",
185+
);
186+
setCachedThreadStarter(
187+
`${prefix}500`,
188+
{ kind: "hit", starter: { text: "new starter", author: "Alice" } },
189+
1_000_002,
190+
);
191+
192+
expect(requireCachedThreadStarter(getCachedThreadStarter(`${prefix}0`, 1_000_003)).text).toBe(
193+
"starter-0",
194+
);
170195
expect(getCachedThreadStarter(`${prefix}1`, 1_000_003)).toBeUndefined();
171-
expect(getCachedThreadStarter(`${prefix}500`, 1_000_003)?.text).toBe("new starter");
196+
expect(requireCachedThreadStarter(getCachedThreadStarter(`${prefix}500`, 1_000_003)).text).toBe(
197+
"new starter",
198+
);
199+
});
200+
201+
it.each([
202+
{ name: "a missing starter", get: () => vi.fn().mockResolvedValue(null) },
203+
{
204+
name: "an inaccessible starter",
205+
get: () => vi.fn().mockRejectedValue(createDiscordError(403)),
206+
},
207+
])("negative-caches $name for 30 seconds", async ({ get: createGet }) => {
208+
vi.useFakeTimers();
209+
try {
210+
const now = new Date("2026-08-24T00:00:00.000Z");
211+
vi.setSystemTime(now);
212+
const get = createGet();
213+
const client = { rest: { get } } as unknown as Client;
214+
const params = {
215+
channel: { id: `missing-starter-${++threadIdIndex}` },
216+
client,
217+
accountId: "test-account",
218+
parentId: "parent-1",
219+
parentType: ChannelType.GuildText,
220+
resolveTimestampMs: () => undefined,
221+
};
222+
223+
await expect(resolveDiscordThreadStarter(params)).resolves.toBeNull();
224+
await expect(resolveDiscordThreadStarter(params)).resolves.toBeNull();
225+
expect(get).toHaveBeenCalledOnce();
226+
227+
vi.setSystemTime(now.getTime() + 30_000);
228+
await expect(resolveDiscordThreadStarter(params)).resolves.toBeNull();
229+
expect(get).toHaveBeenCalledTimes(2);
230+
} finally {
231+
vi.useRealTimers();
232+
}
233+
});
234+
235+
it("coalesces concurrent starter lookups for the same account and thread", async () => {
236+
let releaseGet!: (message: ThreadStarterRestMessage | null) => void;
237+
const response = new Promise<ThreadStarterRestMessage | null>((resolve) => {
238+
releaseGet = resolve;
239+
});
240+
const get = vi.fn(() => response);
241+
const client = { rest: { get } } as unknown as Client;
242+
const params = {
243+
channel: { id: `concurrent-starter-${++threadIdIndex}` },
244+
client,
245+
accountId: "test-account",
246+
parentId: "parent-1",
247+
parentType: ChannelType.GuildText,
248+
resolveTimestampMs: () => undefined,
249+
};
250+
251+
const first = resolveDiscordThreadStarter(params);
252+
const second = resolveDiscordThreadStarter(params);
253+
expect(get).toHaveBeenCalledOnce();
254+
255+
releaseGet(null);
256+
await expect(Promise.all([first, second])).resolves.toEqual([null, null]);
257+
expect(get).toHaveBeenCalledOnce();
258+
});
259+
260+
it("does not coalesce missing metadata with a lookup that has a parent id", async () => {
261+
const get = vi.fn().mockResolvedValue(createStarterMessage({ content: "resolved" }));
262+
const client = { rest: { get } } as unknown as Client;
263+
const params = {
264+
channel: { id: `metadata-single-flight-${++threadIdIndex}` },
265+
client,
266+
accountId: "test-account",
267+
parentType: ChannelType.GuildText,
268+
resolveTimestampMs: () => undefined,
269+
};
270+
271+
const missingMetadata = resolveDiscordThreadStarter(params);
272+
const completeMetadata = resolveDiscordThreadStarter({ ...params, parentId: "parent-1" });
273+
274+
await expect(missingMetadata).resolves.toBeNull();
275+
await expect(completeMetadata).resolves.toMatchObject({ text: "resolved" });
276+
expect(get).toHaveBeenCalledOnce();
277+
});
278+
279+
it("does not negative-cache transient REST failures", async () => {
280+
const get = vi
281+
.fn()
282+
.mockRejectedValueOnce(new Error("temporary network failure"))
283+
.mockResolvedValue(createStarterMessage({ content: "recovered starter" }));
284+
const client = { rest: { get } } as unknown as Client;
285+
const params = {
286+
channel: { id: `transient-starter-${++threadIdIndex}` },
287+
client,
288+
accountId: "test-account",
289+
parentId: "parent-1",
290+
parentType: ChannelType.GuildText,
291+
resolveTimestampMs: () => undefined,
292+
};
293+
294+
await expect(resolveDiscordThreadStarter(params)).resolves.toBeNull();
295+
await expect(resolveDiscordThreadStarter(params)).resolves.toMatchObject({
296+
text: "recovered starter",
297+
});
298+
expect(get).toHaveBeenCalledTimes(2);
299+
});
300+
301+
it("scopes negative cache entries to the Discord account", async () => {
302+
const deniedGet = vi.fn().mockRejectedValue(createDiscordError(403));
303+
const allowedGet = vi.fn().mockResolvedValue(createStarterMessage({ content: "visible" }));
304+
const threadId = `account-scoped-starter-${++threadIdIndex}`;
305+
const baseParams = {
306+
channel: { id: threadId },
307+
parentId: "parent-1",
308+
parentType: ChannelType.GuildText,
309+
resolveTimestampMs: () => undefined,
310+
};
311+
312+
await expect(
313+
resolveDiscordThreadStarter({
314+
...baseParams,
315+
client: { rest: { get: deniedGet } } as unknown as Client,
316+
accountId: "account-a",
317+
}),
318+
).resolves.toBeNull();
319+
await expect(
320+
resolveDiscordThreadStarter({
321+
...baseParams,
322+
client: { rest: { get: allowedGet } } as unknown as Client,
323+
accountId: "account-b",
324+
}),
325+
).resolves.toMatchObject({ text: "visible" });
326+
expect(deniedGet).toHaveBeenCalledOnce();
327+
expect(allowedGet).toHaveBeenCalledOnce();
328+
});
329+
330+
it("does not cache missing parent metadata", async () => {
331+
const get = vi.fn().mockResolvedValue(createStarterMessage({ content: "resolved" }));
332+
const client = { rest: { get } } as unknown as Client;
333+
const channel = { id: `metadata-starter-${++threadIdIndex}` };
334+
335+
await expect(
336+
resolveDiscordThreadStarter({
337+
channel,
338+
client,
339+
accountId: "test-account",
340+
parentType: ChannelType.GuildText,
341+
resolveTimestampMs: () => undefined,
342+
}),
343+
).resolves.toBeNull();
344+
await expect(
345+
resolveDiscordThreadStarter({
346+
channel,
347+
client,
348+
accountId: "test-account",
349+
parentId: "parent-1",
350+
parentType: ChannelType.GuildText,
351+
resolveTimestampMs: () => undefined,
352+
}),
353+
).resolves.toMatchObject({ text: "resolved" });
354+
expect(get).toHaveBeenCalledOnce();
355+
});
356+
357+
it("resolves thread starters when their parent type is unavailable", async () => {
358+
const threadId = `unknown-parent-type-starter-${++threadIdIndex}`;
359+
const get = vi.fn().mockResolvedValue(createStarterMessage({ content: "visible starter" }));
360+
361+
await expect(
362+
resolveDiscordThreadStarter({
363+
channel: { id: threadId },
364+
client: { rest: { get } } as unknown as Client,
365+
accountId: "test-account",
366+
parentId: "parent-1",
367+
resolveTimestampMs: () => undefined,
368+
}),
369+
).resolves.toMatchObject({ text: "visible starter" });
370+
expect(get).toHaveBeenCalledExactlyOnceWith(`/channels/parent-1/messages/${threadId}`);
371+
});
372+
373+
it("keeps parent-route misses separate when forum metadata recovers", async () => {
374+
const threadId = `recovering-forum-starter-${++threadIdIndex}`;
375+
const get = vi.fn(async (path: string) =>
376+
path === `/channels/${threadId}/messages/${threadId}`
377+
? createStarterMessage({ content: "recovered forum starter" })
378+
: null,
379+
);
380+
const client = { rest: { get } } as unknown as Client;
381+
const params = {
382+
channel: { id: threadId },
383+
client,
384+
accountId: "test-account",
385+
parentId: "parent-1",
386+
resolveTimestampMs: () => undefined,
387+
};
388+
389+
await expect(
390+
resolveDiscordThreadStarter({ ...params, parentType: undefined }),
391+
).resolves.toBeNull();
392+
expect(get).toHaveBeenCalledExactlyOnceWith(`/channels/parent-1/messages/${threadId}`);
393+
394+
await expect(
395+
resolveDiscordThreadStarter({ ...params, parentType: ChannelType.GuildForum }),
396+
).resolves.toMatchObject({ text: "recovered forum starter" });
397+
expect(get).toHaveBeenCalledTimes(2);
398+
expect(get).toHaveBeenNthCalledWith(2, `/channels/${threadId}/messages/${threadId}`);
172399
});
173400

174401
it("falls back to joined embed title and description when content is empty", async () => {

0 commit comments

Comments
 (0)