Skip to content

Commit b49119b

Browse files
brettdamanobviyus
andauthored
fix(auto-reply): refresh stale session dispatches
## What Problem This Solves A durable inbound message can capture one session ID and reach reply admission after a concurrent reset or owner rotation commits a replacement session. The stale attempt fails before user-visible work with `Session changed while starting work. Retry.` and can keep the same ingress lane occupied across retries. Fixes #135149. ## Root Cause The dispatch pipeline reused its first session snapshot after the session owner changed. A repeated conflict then stayed under the generic retry rule, which requires both eight attempts and 24 hours before a terminal failure. The delayed head kept later updates in the same lane blocked. Telegram and grammY also wrap the original error twice, so top-level classification cannot identify the conflict. ## Fix - Visible pre-dispatch invalidation now carries a typed owner signal. - Dispatch rebuilds its complete state once from the durable session store. - Actual stale ownership conflicts use a dedicated code; generic storage invalidations keep their existing retry behavior. - The ingress retry owner follows nested error causes and terminates only the dedicated conflict at its configured attempt budget. - Archived, tombstoned, heartbeat, and queued-followup behavior does not change. - Generic transport failures retain the existing attempt-and-age rule. ## Evidence - Current-main red at `f1fb06eef9b46b55359f27451c10f0ba0996b534`: the final test bytes showed release at the attempt budget, missing conflict codes at each owner, generic deterministic diff-baseline conflicts, no Telegram dead letter, and a blocked same-lane follower. - Exact-head green at `1d0e517f412de0c6940ce6cbd03444285d5c6fb6`: all 328 focused tests passed with a disk-backed temporary directory. - The Telegram regression drives the durable queue, monitor, grammY middleware, shared drain, nested error graph, terminal failed row, and following same-lane update. - Generic diff-baseline read and persistence failures remain `SESSION_WORK_START_INVALIDATED` and do not take the attempt-only terminal path. - Exact-head continuous integration is the final platform gate. ## Live-proof limitation A public Telegram reset cancels the admitted turn, and message hooks run after admission, so neither can create this exact stale-start interleave. Direct database replacement would bypass the lifecycle owner under test. The deterministic Telegram E2E therefore drives the real durable queue, monitor, grammY wrapper graph, shared drain, terminal failed row, and same-lane follower without adding a production-only pause. A Test Server run confirmed this boundary with a source Gateway and public `sessions.reset`: three real DM inputs reached the provider, the reset completed, and no stale-start conflict was emitted because reset ran after admission and canceled the in-flight lifecycle instead. This negative trace is retained privately. The requested positive live trace is skipped because no supported external control exists before admission; adding a production pause or mutating the session database directly would invalidate the owner-boundary proof. ## ClawSweeper rank-up moves - Applied: stale ownership conflicts now have a dedicated code; storage failures retain the generic retry policy. - Applied: exact-head required checks completed successfully. - Skipped with proof: a positive Test Server stale-start trace is not safely reachable through public controls; the real attempt exercised the distinct reset-cancellation path described above. ## Worked on by - @brettdaman - @obviyus Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 397f298 commit b49119b

18 files changed

Lines changed: 419 additions & 101 deletions

‎extensions/telegram/src/telegram-ingress-coalescing.e2e.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import fs from "node:fs/promises";
66
import os from "node:os";
77
import path from "node:path";
8+
import { DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS } from "openclaw/plugin-sdk/channel-outbound";
89
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
910
import {
1011
closeOpenClawStateDatabaseForTest,
@@ -134,6 +135,19 @@ function forwardedTextUpdate(params: { updateId: number; messageId: number; text
134135
};
135136
}
136137

138+
function textUpdate(params: { updateId: number; messageId: number; text: string }) {
139+
return {
140+
update_id: params.updateId,
141+
message: {
142+
message_id: params.messageId,
143+
date: 1_736_380_800 + params.messageId,
144+
chat: { id: 111, type: "private" as const, first_name: "Ada" },
145+
from: { id: 111, is_bot: false, first_name: "Ada" },
146+
text: params.text,
147+
},
148+
};
149+
}
150+
137151
function createBotApiTransport() {
138152
let getFileCall = 0;
139153
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
@@ -470,4 +484,53 @@ describe("Telegram durable ingress coalescing", () => {
470484
await monitor.stop();
471485
await telegramTransport.close();
472486
});
487+
488+
it("bounds repeated session-start conflicts and drains the next Telegram update", async () => {
489+
const poison = textUpdate({ updateId: 801, messageId: 1, text: "poison" });
490+
const after = textUpdate({ updateId: 802, messageId: 2, text: "after" });
491+
const poisonId = telegramQueueEventId(poison.update_id);
492+
const sessionError = Object.assign(
493+
new Error('Session "agent:main:telegram:direct:111" changed while starting work. Retry.'),
494+
{ code: "SESSION_WORK_START_CHANGED" },
495+
);
496+
downstreamTurns.mockImplementation(async (turn) => {
497+
if ((turn.BodyForAgent ?? turn.Body ?? "").includes("poison")) {
498+
throw sessionError;
499+
}
500+
return { queuedFinal: false, counts: { block: 0, final: 0, tool: 0 } };
501+
});
502+
await writeTelegramSpooledUpdate({ spoolDir, update: poison });
503+
await writeTelegramSpooledUpdate({ spoolDir, update: after });
504+
const queue = openTelegramIngressQueue(spoolDir);
505+
for (let attempt = 1; attempt < DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS; attempt += 1) {
506+
const claim = await queue.claim(poisonId, { ownerId: `proof:${attempt}` });
507+
if (!claim) {
508+
throw new Error(`Expected setup claim ${attempt}`);
509+
}
510+
await queue.release(claim, {
511+
lastError: sessionError.message,
512+
releasedAt: Date.now() - 60 * 60 * 1_000,
513+
});
514+
}
515+
const runtimeError = vi.fn();
516+
const { monitor, telegramTransport } = await createMonitor({ onRuntimeError: runtimeError });
517+
518+
monitor.start();
519+
await vi.waitFor(async () => {
520+
expect(await queue.listFailed?.({ limit: "all" })).toEqual([
521+
expect.objectContaining({ id: poisonId, reason: "session-start-conflict-retry-limit" }),
522+
]);
523+
});
524+
await vi.waitFor(async () => {
525+
expect(await queue.listPending({ limit: "all" })).toEqual([]);
526+
});
527+
expect(
528+
downstreamTurns.mock.calls.some(([turn]) =>
529+
(turn.BodyForAgent ?? turn.Body ?? "").includes("after"),
530+
),
531+
).toBe(true);
532+
533+
await monitor.stop();
534+
await telegramTransport.close();
535+
});
473536
});

‎src/agents/agent-command-recovery-owner.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,7 @@ describe("agent command restart recovery ownership", () => {
510510
},
511511
run,
512512
}),
513-
).rejects.toThrow("changed while starting work");
513+
).rejects.toMatchObject({ code: "SESSION_WORK_START_CHANGED" });
514514
expect(run).not.toHaveBeenCalled();
515515
});
516516

‎src/agents/agent-command-recovery-owner.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import path from "node:path";
22
import type { InternalSessionEntry } from "../config/sessions.js";
3+
import { createSessionWorkStartChangedError } from "../config/sessions/lifecycle.js";
34
import { formatErrorMessage } from "../infra/errors.js";
45
import { createSubsystemLogger } from "../logging/subsystem.js";
56
import type { AgentCommandOpts } from "./command/types.js";
@@ -107,7 +108,7 @@ async function claimAgentCommandRecoveryOwner(params: {
107108
target: { sessionKey, storePath: params.prepared.storePath },
108109
});
109110
if (recoveryInspection.kind === "invalidated") {
110-
throw new Error(`Session "${sessionKey}" changed while starting work. Retry.`);
111+
throw createSessionWorkStartChangedError(sessionKey);
111112
}
112113
if (recoveryInspection.kind === "required") {
113114
throw new Error(
@@ -129,7 +130,7 @@ async function claimAgentCommandRecoveryOwner(params: {
129130
target: { sessionKey, storePath: params.prepared.storePath },
130131
});
131132
if (claim.kind === "invalidated") {
132-
throw new Error(`Session "${sessionKey}" changed while starting work. Retry.`);
133+
throw createSessionWorkStartChangedError(sessionKey);
133134
}
134135
if (claim.kind === "not_required") {
135136
return undefined;

‎src/agents/agent-command.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { normalizeOptionalString } from "@openclaw/normalization-core/string-coe
44
import type { VerboseLevel } from "../auto-reply/thinking.js";
55
import type { CliDeps } from "../cli/deps.types.js";
66
import {
7+
createSessionWorkStartChangedError,
78
isSessionWorkStartInvalidatedError,
89
resolveSessionWorkStartError,
910
} from "../config/sessions/lifecycle.js";
@@ -207,16 +208,12 @@ async function agentCommandInternal(
207208
})
208209
: sessionEntry;
209210
if (!currentEntry && preparedSessionId) {
210-
throw new Error(
211-
`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`,
212-
);
211+
throw createSessionWorkStartChangedError(sessionKey ?? sessionId);
213212
}
214213
const matchesIntentionalRollover =
215214
isNewSession && currentEntry?.sessionId === preparedSessionId;
216215
if (currentEntry && currentEntry.sessionId !== sessionId && !matchesIntentionalRollover) {
217-
throw new Error(
218-
`Session "${sessionKey ?? sessionId}" changed while starting work. Retry.`,
219-
);
216+
throw createSessionWorkStartChangedError(sessionKey ?? sessionId);
220217
}
221218
const archivedSessionError = resolveSessionWorkStartError(
222219
sessionKey ?? sessionId,
@@ -685,7 +682,6 @@ async function agentCommandFromIngressInternal(
685682
if (result && preparedAgentDir) {
686683
emitIngressModelUsageDiagnostic(result, opts, preparedAgentDir);
687684
}
688-
689685
return result;
690686
});
691687
return generation && runtimeContext

‎src/auto-reply/reply/dispatch-from-config.base.test-utils.ts‎

Lines changed: 85 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import type { GetReplyOptions, ReplyPayload } from "../types.js";
2525
import { markCommandSessionMetadataChanged } from "./command-session-metadata.js";
2626
import {
2727
createDispatcher,
28+
diagnosticMocks,
2829
emptyConfig,
2930
hookMocks,
3031
messageAuditMocks,
@@ -1734,7 +1735,7 @@ describe("dispatchReplyFromConfig", () => {
17341735
recoveryOperation?.complete();
17351736
});
17361737

1737-
it("rejects a stale turn without clearing the operation for the rotated session", async () => {
1738+
it("refreshes a stale visible turn after session rotation without clearing the new owner", async () => {
17381739
setNoAbort();
17391740
const sessionKey = "agent:main:telegram:group:-1003774691297";
17401741
// Terminal store snapshot still reports the failed lifecycle's session id.
@@ -1756,6 +1757,7 @@ describe("dispatchReplyFromConfig", () => {
17561757
// `terminalRecovery`, so only the session-id guard can stop the force-clear.
17571758
let freshOperation: ReturnType<typeof createReplyOperation> | undefined;
17581759
let signalFreshRegistered: () => void = () => {};
1760+
let fastAbortCalls = 0;
17591761
const freshRegistered = new Promise<void>((resolve) => {
17601762
signalFreshRegistered = resolve;
17611763
});
@@ -1771,9 +1773,17 @@ describe("dispatchReplyFromConfig", () => {
17711773
To: "telegram:-1003774691297",
17721774
BodyForAgent: "@openclaw recover",
17731775
}),
1774-
cfg: automaticGroupReplyConfig,
1776+
cfg: { ...automaticGroupReplyConfig, diagnostics: { enabled: true } },
17751777
dispatcher,
17761778
fastAbortResolver: async () => {
1779+
fastAbortCalls += 1;
1780+
if (fastAbortCalls > 1) {
1781+
return { handled: false, aborted: false };
1782+
}
1783+
sessionStoreMocks.currentEntry = {
1784+
sessionId: "fresh-rotated-session",
1785+
updatedAt: Date.now(),
1786+
};
17771787
freshOperation = createReplyOperation({
17781788
sessionKey,
17791789
sessionId: "fresh-rotated-session",
@@ -1786,6 +1796,7 @@ describe("dispatchReplyFromConfig", () => {
17861796
formatAbortReplyTextResolver: () => "aborted",
17871797
replyResolver,
17881798
});
1799+
void turn.catch(() => {});
17891800

17901801
// Let the visible turn run its admission/force-clear path. With the bug it
17911802
// would force-fail the rotated op here, mistaking a valid in-flight reply for
@@ -1795,16 +1806,84 @@ describe("dispatchReplyFromConfig", () => {
17951806
setTimeout(resolve, 100);
17961807
});
17971808

1798-
// The session-id guard keeps the rotated op untouched while the stale turn
1799-
// is invalidated instead of later crossing the reset boundary.
1809+
// The session-id guard keeps the rotated op untouched while this turn
1810+
// refreshes its snapshot instead of crossing the reset boundary with stale state.
18001811
expect(freshOperation).toBeDefined();
18011812
expect(freshOperation?.result).toBeNull();
18021813
expect(replyRunRegistry.get(sessionKey)).toBe(freshOperation);
18031814
expect(replyResolver).not.toHaveBeenCalled();
18041815

18051816
freshOperation?.complete();
1806-
await expect(turn).rejects.toThrow(/changed while starting work/i);
1807-
expect(replyResolver).not.toHaveBeenCalled();
1817+
await expect(turn).resolves.toMatchObject({
1818+
queuedFinal: true,
1819+
counts: { tool: 0, block: 0, final: 0 },
1820+
});
1821+
expect(replyResolver).toHaveBeenCalledOnce();
1822+
expect(fastAbortCalls).toBe(2);
1823+
expect(dispatcher.sendFinalReply).toHaveBeenCalledWith({ text: "visible recovery reply" });
1824+
expect(replyRunRegistry.isActive(sessionKey)).toBe(false);
1825+
expect(messageAuditEvents()).toEqual([
1826+
expect.objectContaining({ status: "succeeded", outcome: "completed" }),
1827+
]);
1828+
expect(diagnosticMocks.logMessageProcessed).toHaveBeenCalledOnce();
1829+
expect(diagnosticMocks.logMessageProcessed).toHaveBeenCalledWith(
1830+
expect.objectContaining({ outcome: "completed" }),
1831+
);
1832+
expect(diagnosticMocks.logMessageQueued).toHaveBeenCalledTimes(2);
1833+
expect(diagnosticMocks.logSessionStateChange.mock.calls).toEqual([
1834+
[
1835+
expect.objectContaining({
1836+
sessionId: "failed-session-rotated",
1837+
state: "processing",
1838+
}),
1839+
],
1840+
[
1841+
expect.objectContaining({
1842+
sessionId: "failed-session-rotated",
1843+
state: "idle",
1844+
reason: "session_refresh",
1845+
}),
1846+
],
1847+
[
1848+
expect.objectContaining({
1849+
sessionId: "fresh-rotated-session",
1850+
state: "processing",
1851+
}),
1852+
],
1853+
[
1854+
expect.objectContaining({
1855+
sessionId: "fresh-rotated-session",
1856+
state: "idle",
1857+
reason: "message_completed",
1858+
}),
1859+
],
1860+
]);
1861+
1862+
const followingDispatcher = createDispatcher();
1863+
await expect(
1864+
dispatchReplyFromConfig({
1865+
ctx: buildTestCtx({
1866+
Provider: "telegram",
1867+
Surface: "telegram",
1868+
OriginatingChannel: "telegram",
1869+
ChatType: "group",
1870+
SessionKey: sessionKey,
1871+
MessageSid: "following-visible-after-rotation",
1872+
To: "telegram:-1003774691297",
1873+
BodyForAgent: "@openclaw following message",
1874+
}),
1875+
cfg: automaticGroupReplyConfig,
1876+
dispatcher: followingDispatcher,
1877+
replyResolver,
1878+
}),
1879+
).resolves.toMatchObject({
1880+
queuedFinal: true,
1881+
counts: { tool: 0, block: 0, final: 0 },
1882+
});
1883+
expect(replyResolver).toHaveBeenCalledTimes(2);
1884+
expect(followingDispatcher.sendFinalReply).toHaveBeenCalledWith({
1885+
text: "visible recovery reply",
1886+
});
18081887
expect(replyRunRegistry.isActive(sessionKey)).toBe(false);
18091888
});
18101889

0 commit comments

Comments
 (0)