Skip to content

Commit 7b48abc

Browse files
committed
fix(telegram): bind the visible-reply fact to the dispatching frame
ClawSweeper's P1 on 630973362846, reproduced: the delivery mark was read ambiently at settlement, so it was wrong on both sides. It missed its own target case. Settlement is reached from bot-message.ts:439-446, the retained onAbandoned callback invoked by the reply queue at src/auto-reply/reply/queue/types.ts:348, outside the update frame -- and that is the deferred-phase watchdog path this change exists to fix. The read returned false there and the guard still released. It could also drop a message, which the previous body wrongly ruled out. Because getStore() resolves at call time, update A's settlement running inside update B's frame reads B's mark; if B replied and A did not, A's guard commits and A is silently dropped. Reachable: the reply-queue drain never detaches its async context (drain.ts:1267-1272 swaps only the callback, self-reschedules from its own finally at :1535/:1538/:1548), so one starter's context spans drain cycles. captureTelegramVisibleReplyDelivered() is called during dispatch setup while the attempt's own frame is current and returns a closure over that frame object, so settlement performs no getStore() at all. Not ClawSweeper's suggested shape, deliberately. getTelegramSpooledReplayDeferredParticipant() (bot-processing-outcome.ts:216) is itself an AsyncLocalStorage read on a second store; both stores are entered around the same bot.handleUpdate region and have identical async lifetime, so moving the fact between them changes nothing about which attempt is read. Settlement lifetime was not the missing property. Neutralize cycle, re-derived independently: 10/10 pass -> 3 failed / 7 passed -> 10/10 pass, restored byte-identical. The three that go red: suppresses the redelivery of an attempt that replied before the queue abandoned it redelivers an abandoned attempt that never replied, even while another update's frame is current answers for its own update while another update's frame is current 298/298 across the changed files plus bot.test.ts and bot.create-telegram-bot.test.ts. Also fixes "behaviour" in shipped code and corrects the comment that asserted the refuted false-negatives-only safety property. Known gap, not closed here: bot/delivery.send.ts:115 confirms sends without recording the fact, so a reply through that funnel still leaves the guard blind. Production +9, tests +197.
1 parent ea55429 commit 7b48abc

5 files changed

Lines changed: 233 additions & 27 deletions

File tree

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
/** Verifies the ingress replay guard reads the visible-reply fact of its own attempt. */
2+
import type { Message } from "grammy/types";
3+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
5+
import { resetPluginStateStoreForTests } from "openclaw/plugin-sdk/plugin-state-test-runtime";
6+
import { getChildLogger } from "openclaw/plugin-sdk/runtime-env";
7+
import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env";
8+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9+
import { defaultTelegramBotDeps } from "./bot-deps.js";
10+
import {
11+
createTelegramMessagePipeline,
12+
type TelegramMessagePipeline,
13+
} from "./bot-handlers.message-pipeline.js";
14+
import type { RegisterTelegramHandlerParams } from "./bot-handlers.types.js";
15+
import {
16+
markTelegramVisibleReplyDelivered,
17+
runWithTelegramUpdateProcessingFrame,
18+
type TelegramMessageProcessingResult,
19+
} from "./bot-processing-outcome.js";
20+
import type { TelegramContext } from "./bot/types.js";
21+
22+
type SettleSpooledReplay = (
23+
result: TelegramMessageProcessingResult,
24+
) => Promise<TelegramMessageProcessingResult>;
25+
26+
const BOT_USER_ID = 99;
27+
const SPOOLED_MESSAGE = {
28+
message_id: 12949,
29+
date: 1736380800,
30+
chat: { id: 4242, type: "private" },
31+
from: { id: 77, is_bot: false, first_name: "Operator" },
32+
text: "does this answer twice?",
33+
} as Message;
34+
35+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
36+
let previousStateDir: string | undefined;
37+
38+
beforeEach(() => {
39+
previousStateDir = process.env.OPENCLAW_STATE_DIR;
40+
process.env.OPENCLAW_STATE_DIR = tempDirs.make("openclaw-telegram-replay-guard-");
41+
resetPluginStateStoreForTests({ closeDatabase: false });
42+
});
43+
44+
afterEach(() => {
45+
resetPluginStateStoreForTests();
46+
if (previousStateDir === undefined) {
47+
delete process.env.OPENCLAW_STATE_DIR;
48+
} else {
49+
process.env.OPENCLAW_STATE_DIR = previousStateDir;
50+
}
51+
});
52+
53+
/**
54+
* Builds the real pipeline over the real dispatch-dedupe guard. The stubbed
55+
* message processor hands back the retained `finalizeSpooledReplayResult` and
56+
* then stays pending, exactly as a deferred turn does while the reply queue owns
57+
* it, so the test can settle the attempt from a context the attempt never owned.
58+
*/
59+
function createPipelineUnderTest(): {
60+
pipeline: TelegramMessagePipeline;
61+
dispatched: Promise<SettleSpooledReplay>;
62+
replyDuringDispatch: { enabled: boolean };
63+
turnResult: ReturnType<typeof createDeferred<TelegramMessageProcessingResult>>;
64+
} {
65+
const dispatched = createDeferred<SettleSpooledReplay>();
66+
const turnResult = createDeferred<TelegramMessageProcessingResult>();
67+
const replyDuringDispatch = { enabled: false };
68+
const cfg = { channels: { telegram: { dmPolicy: "open", allowFrom: ["*"] } } } as OpenClawConfig;
69+
const processMessage = vi.fn(async (args: { turnContext?: Record<string, unknown> }) => {
70+
if (replyDuringDispatch.enabled) {
71+
markTelegramVisibleReplyDelivered();
72+
}
73+
dispatched.resolve(args.turnContext?.finalizeSpooledReplayResult as SettleSpooledReplay);
74+
return await turnResult.promise;
75+
});
76+
const params = {
77+
accountId: "default",
78+
ownerAgentId: "main",
79+
bot: { api: {} } as RegisterTelegramHandlerParams["bot"],
80+
cfg,
81+
mediaMaxBytes: 1,
82+
opts: { token: "tok" },
83+
telegramCfg: {},
84+
logger: getChildLogger({ module: "telegram/replay-guard-test" }),
85+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
86+
shouldSkipUpdate: () => false,
87+
resolveGroupPolicy: () => ({ allowlistEnabled: false, allowed: true }),
88+
resolveGroupActivation: () => undefined,
89+
resolveGroupRequireMention: () => false,
90+
resolveTelegramGroupConfig: () => ({ groupConfig: undefined, topicConfig: undefined }),
91+
processMessage: processMessage as unknown as RegisterTelegramHandlerParams["processMessage"],
92+
telegramDeps: {
93+
...defaultTelegramBotDeps,
94+
getRuntimeConfig: () => cfg,
95+
wasSentByBot: () => false,
96+
readChannelAllowFromStore: async () => [],
97+
},
98+
} as unknown as RegisterTelegramHandlerParams;
99+
return {
100+
pipeline: createTelegramMessagePipeline(params),
101+
dispatched: dispatched.promise,
102+
replyDuringDispatch,
103+
turnResult,
104+
};
105+
}
106+
107+
function dispatchSpooledAttempt(
108+
pipeline: TelegramMessagePipeline,
109+
claims: Awaited<ReturnType<TelegramMessagePipeline["claimMessageDispatchDedupe"]>>,
110+
) {
111+
return runWithTelegramUpdateProcessingFrame(
112+
async () =>
113+
await pipeline.processMessageWithReplyChain({
114+
ctx: { message: SPOOLED_MESSAGE, update: { update_id: 991 } } as unknown as TelegramContext,
115+
msg: SPOOLED_MESSAGE,
116+
allMedia: [],
117+
storeAllowFrom: [],
118+
options: { spooledReplay: true },
119+
dispatchDedupeClaims: claims.process ? claims.claims : [],
120+
}),
121+
);
122+
}
123+
124+
describe("Telegram spooled ingress replay guard", () => {
125+
it("suppresses the redelivery of an attempt that replied before the queue abandoned it", async () => {
126+
// The reviewer-requested sequence in one trace: confirmed send -> abandonment
127+
// settled on the queue's own chain (outside this update's frame) -> the spool
128+
// redelivery of the same logical message is refused as a duplicate.
129+
const trace: string[] = [];
130+
const { pipeline, dispatched, replyDuringDispatch, turnResult } = createPipelineUnderTest();
131+
const claimed = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID);
132+
trace.push(`claim attempt=1 process=${claimed.process}`);
133+
134+
replyDuringDispatch.enabled = true;
135+
const dispatch = dispatchSpooledAttempt(pipeline, claimed);
136+
const settleFromQueueChain = await dispatched;
137+
trace.push(`outbound send ok chatId=${SPOOLED_MESSAGE.chat.id} replyToMessageId=<redacted>`);
138+
139+
const settled = await settleFromQueueChain({
140+
kind: "failed-retryable",
141+
error: new Error("turn-abandoned"),
142+
});
143+
turnResult.resolve(settled);
144+
await dispatch;
145+
trace.push(`settled kind=${settled.kind}`);
146+
147+
const redelivered = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID);
148+
trace.push(`claim attempt=2 process=${redelivered.process}`);
149+
150+
expect(trace).toEqual([
151+
"claim attempt=1 process=true",
152+
"outbound send ok chatId=4242 replyToMessageId=<redacted>",
153+
"settled kind=failed-retryable",
154+
"claim attempt=2 process=false",
155+
]);
156+
});
157+
158+
it("redelivers an abandoned attempt that never replied, even while another update's frame is current", async () => {
159+
// Settlement runs on the followup drain chain, whose frame belongs to
160+
// whichever update rooted it. Committing on that update's reply would drop
161+
// this message without ever answering it.
162+
const trace: string[] = [];
163+
const { pipeline, dispatched, turnResult } = createPipelineUnderTest();
164+
const claimed = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID);
165+
trace.push(`claim attempt=1 process=${claimed.process}`);
166+
167+
const dispatch = dispatchSpooledAttempt(pipeline, claimed);
168+
const settleFromQueueChain = await dispatched;
169+
170+
const foreign = await runWithTelegramUpdateProcessingFrame(async () => {
171+
markTelegramVisibleReplyDelivered();
172+
trace.push("outbound send ok update=other-attempt");
173+
return await settleFromQueueChain({
174+
kind: "failed-retryable",
175+
error: new Error("turn-abandoned"),
176+
});
177+
});
178+
turnResult.resolve(foreign.value);
179+
await dispatch;
180+
trace.push(`settled kind=${foreign.value.kind}`);
181+
182+
const redelivered = await pipeline.claimMessageDispatchDedupe(SPOOLED_MESSAGE, BOT_USER_ID);
183+
trace.push(`claim attempt=2 process=${redelivered.process}`);
184+
185+
expect(trace).toEqual([
186+
"claim attempt=1 process=true",
187+
"outbound send ok update=other-attempt",
188+
"settled kind=failed-retryable",
189+
"claim attempt=2 process=true",
190+
]);
191+
});
192+
});

‎extensions/telegram/src/bot-handlers.message-pipeline.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ import type {
3333
TelegramMessageContextOptions,
3434
} from "./bot-message-context.types.js";
3535
import {
36+
captureTelegramVisibleReplyDelivered,
3637
createTelegramSpooledReplayDeferredParticipant,
3738
createTelegramSpooledReplayParticipant,
3839
getTelegramSpooledReplayDeferredParticipant,
3940
getTelegramSpooledReplayLifecycle,
40-
hasTelegramVisibleReplyDelivered,
4141
isTelegramSpooledReplayUpdate,
4242
recordTelegramMessageProcessingResult,
4343
type TelegramMessageProcessingResult,
@@ -393,6 +393,10 @@ export function createTelegramMessagePipeline({
393393
let dispatchDedupeCommitted = false;
394394
let spooledReplayFinalResult: TelegramMessageProcessingResult | undefined;
395395
let spooledReplayFinalization: Promise<TelegramMessageProcessingResult> | undefined;
396+
// Settlement below is also invoked from contexts this dispatch does not own
397+
// (the reply queue's retained onAbandoned runs on the followup drain chain),
398+
// so bind the visible-reply fact here while this attempt's frame is current.
399+
const hasDeliveredVisibleReply = captureTelegramVisibleReplyDelivered();
396400
// Callback-submit retries also set options.spooledReplay without durable ingress.
397401
// Media aborts retry only when the update frame or a buffered participant owns replay.
398402
const durableMediaReplay =
@@ -450,7 +454,7 @@ export function createTelegramMessagePipeline({
450454
// the replay is duplicate-suppressed. Only the guard is committed - the
451455
// spool row still follows its own retry/dead-letter policy.
452456
const repliedBeforeFailing =
453-
result.kind === "failed-retryable" && hasTelegramVisibleReplyDelivered();
457+
result.kind === "failed-retryable" && hasDeliveredVisibleReply();
454458
if (result.kind === "completed" || repliedBeforeFailing) {
455459
// Do not cache or settle a durable-adoption failure. Deferred queue
456460
// ownership retries this callback with the same spool participants.

‎extensions/telegram/src/bot-processing-outcome.test.ts‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/** Verifies Telegram update outcomes stay attached to their durable ingress owner. */
22
import { describe, expect, it } from "vitest";
33
import {
4+
captureTelegramVisibleReplyDelivered,
45
ensureTelegramMessageProcessingResult,
5-
hasTelegramVisibleReplyDelivered,
66
markTelegramVisibleReplyDelivered,
77
recordTelegramMessageProcessingResult,
88
runWithTelegramUpdateProcessingFrame,
@@ -50,42 +50,47 @@ describe("Telegram update processing outcomes", () => {
5050
describe("Telegram visible-reply delivery fact", () => {
5151
it("records delivery on the owning frame and reads it back", async () => {
5252
await runWithTelegramUpdateProcessingFrame(async () => {
53-
expect(hasTelegramVisibleReplyDelivered()).toBe(false);
53+
const hasDelivered = captureTelegramVisibleReplyDelivered();
54+
expect(hasDelivered()).toBe(false);
5455
markTelegramVisibleReplyDelivered();
55-
expect(hasTelegramVisibleReplyDelivered()).toBe(true);
56+
expect(hasDelivered()).toBe(true);
5657
return undefined;
5758
});
5859
});
5960

6061
it("shares the fact with nested middleware, which is the ingress owner's frame", async () => {
6162
await runWithTelegramUpdateProcessingFrame(async () => {
63+
const hasDelivered = captureTelegramVisibleReplyDelivered();
6264
await runWithTelegramUpdateProcessingFrame(async () => {
6365
markTelegramVisibleReplyDelivered();
6466
return undefined;
6567
});
6668
// The nested call reuses the outer frame, so a reply sent by inner
6769
// middleware must still fence the outer attempt's retry decision.
68-
expect(hasTelegramVisibleReplyDelivered()).toBe(true);
70+
expect(hasDelivered()).toBe(true);
6971
return undefined;
7072
});
7173
});
7274

73-
it("does not leak between updates", async () => {
75+
it("answers for its own update while another update's frame is current", async () => {
76+
// Settlement runs on the followup drain chain, whose ambient frame belongs to
77+
// whichever update rooted it. Reading there must not answer for this attempt.
78+
const captured = await runWithTelegramUpdateProcessingFrame(async () =>
79+
captureTelegramVisibleReplyDelivered(),
80+
);
7481
await runWithTelegramUpdateProcessingFrame(async () => {
7582
markTelegramVisibleReplyDelivered();
83+
expect(captured.value()).toBe(false);
7684
return undefined;
7785
});
78-
await runWithTelegramUpdateProcessingFrame(async () => {
79-
expect(hasTelegramVisibleReplyDelivered()).toBe(false);
80-
return undefined;
81-
});
86+
expect(captured.value()).toBe(false);
8287
});
8388

84-
it("defaults to false with no active frame so an unknown state still retries", () => {
85-
// False is the safe default: a false negative costs a duplicate reply, a
86-
// false positive would silently drop the user's message.
87-
expect(hasTelegramVisibleReplyDelivered()).toBe(false);
89+
it("stays false for a dispatch captured with no active frame", () => {
90+
// A false negative costs a duplicate reply; a false positive drops the
91+
// user's message, so an unknown owner keeps the pre-existing retry.
92+
const hasDelivered = captureTelegramVisibleReplyDelivered();
8893
markTelegramVisibleReplyDelivered();
89-
expect(hasTelegramVisibleReplyDelivered()).toBe(false);
94+
expect(hasDelivered()).toBe(false);
9095
});
9196
});

‎extensions/telegram/src/bot-processing-outcome.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,9 @@ export function ensureTelegramMessageProcessingResult(
8181
}
8282

8383
/**
84-
* Records that this attempt delivered a user-visible reply. Called from the one
85-
* chokepoint that knows a send actually succeeded; a no-op outside an update
86-
* frame, so bot-initiated sends (cron, alerts) never set it.
84+
* Records that this attempt delivered a user-visible reply, from the durable
85+
* send funnel's success log — the point that knows a send actually landed. A
86+
* no-op outside an update frame, so sends with no turn in flight never set it.
8787
*/
8888
export function markTelegramVisibleReplyDelivered(): void {
8989
const frame = telegramUpdateProcessingFrames.getStore();
@@ -93,12 +93,16 @@ export function markTelegramVisibleReplyDelivered(): void {
9393
}
9494

9595
/**
96-
* True when this attempt already replied. Defaults false when no frame is
97-
* active, which keeps the pre-existing retry behaviour: a false negative costs a
98-
* duplicate reply, a false positive would drop the user's message entirely.
96+
* Binds the fact to the frame owning the caller's dispatch, while that frame is
97+
* still the current async context. Settlement is also reached from contexts the
98+
* attempt does not own (the reply queue's retained `onAbandoned`, the ingress
99+
* drain chain); reading ambiently there resolves whichever update's frame is
100+
* current, so it both misses this attempt's own reply and can read another
101+
* attempt's reply and drop a message that was never answered.
99102
*/
100-
export function hasTelegramVisibleReplyDelivered(): boolean {
101-
return telegramUpdateProcessingFrames.getStore()?.visibleReplyDelivered === true;
103+
export function captureTelegramVisibleReplyDelivered(): () => boolean {
104+
const frame = telegramUpdateProcessingFrames.getStore();
105+
return () => frame?.visibleReplyDelivered === true;
102106
}
103107

104108
export function recordTelegramMessageProcessingResult(

‎extensions/telegram/src/send-context.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,10 @@ type TelegramOutboundSuccessLogParams = {
5959
};
6060

6161
export function logTelegramOutboundSendOk(params: TelegramOutboundSuccessLogParams): void {
62-
// Single chokepoint that knows a send actually landed, so it is where the
63-
// "this attempt already spoke to the user" fact is recorded. The ingress
64-
// settlement reads it to decide whether a retryable failure may replay.
62+
// The durable funnel's confirmation point, so it is where the "this attempt
63+
// already spoke to the user" fact is recorded. The ingress settlement reads it
64+
// to decide whether a retryable failure may replay. Note the streaming funnel
65+
// (`bot/delivery.send.ts`) confirms sends without recording it.
6566
markTelegramVisibleReplyDelivered();
6667
const parts = [
6768
"telegram outbound send ok",

0 commit comments

Comments
 (0)