Repository navigation
fix(sessions): channel message never answered after its first attempt fails - #193602
Conversation
A channel message that fails after its pending input is staged leaves a cancelled custody row keyed by the stable channel source turn. Durable ingress then retries the same message under a fresh run ID, and staging rejects every retry with "Pending input idempotency key conflicts with the accepted input" until ingress dead-letters it 24 hours later. The message is never answered and its lane stays blocked. Let a channel source-turn redelivery reopen its own byte-identical, cancelled, unconsumed attempt and rebind the row to the new run. User Stop and dismissal stay replay fences, and the stage commit now compares run and state so two concurrent reopens cannot both win.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR lets a byte-identical channel redelivery reclaim its cancelled, unconsumed pending input under a fresh run ID. Example: Telegram message 4242 fails before transcript consumption under ingress-attempt-1.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it addresses a source-confirmed channel retry defect still present on main, and no definite introduced correctness bug was found. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherChannel ingress dispatches messages through reply admission into the session pending-input owner, which retains accepted input until authorized transcript consumption or cancellation. flowchart LR
A[Channel message] --> B[Durable ingress retry]
B --> C[Reply admission]
C --> D[Pending input owner]
D --> E[SQLite or memory actor]
E --> F[Transcript consumption]
F --> G[Agent reply]
Technical reviewBest possible solution: Use the existing pending-input owner to reclaim matching failed channel turns while preserving explicit cancellation, current admission, and restart ownership. Do we have a high-confidence way to reproduce the issue? The fresh dispatch run ID and main's exact-run restriction establish the failure path, supported by the reported live incident and supplied SQLite regression; this read-only review ran no target code. Is this the best way to solve the issue? The patch is a focused repair of retry admission: it reuses existing storage and custody owners, changes both backends together, and leaves the separate transcript sequence collision and media fingerprint limitation explicitly outside scope. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 990fc1bd88b9. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +49, Tests +167, Other +2. Total +218 across 11 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 5, 2026, 11:59 AM ET / 16:59 UTC. |
… fails (openclaw#193602) * fix(sessions): let channel redelivery reopen its own failed input A channel message that fails after its pending input is staged leaves a cancelled custody row keyed by the stable channel source turn. Durable ingress then retries the same message under a fresh run ID, and staging rejects every retry with "Pending input idempotency key conflicts with the accepted input" until ingress dead-letters it 24 hours later. The message is never answered and its lane stays blocked. Let a channel source-turn redelivery reopen its own byte-identical, cancelled, unconsumed attempt and rebind the row to the new run. User Stop and dismissal stay replay fences, and the stage commit now compares run and state so two concurrent reopens cannot both win. * test: allocate test lines for channel redelivery regression --------- Co-authored-by: VACInc <[email protected]>
… fails (openclaw#193602) * fix(sessions): let channel redelivery reopen its own failed input A channel message that fails after its pending input is staged leaves a cancelled custody row keyed by the stable channel source turn. Durable ingress then retries the same message under a fresh run ID, and staging rejects every retry with "Pending input idempotency key conflicts with the accepted input" until ingress dead-letters it 24 hours later. The message is never answered and its lane stays blocked. Let a channel source-turn redelivery reopen its own byte-identical, cancelled, unconsumed attempt and rebind the row to the new run. User Stop and dismissal stay replay fences, and the stage commit now compares run and state so two concurrent reopens cannot both win. * test: allocate test lines for channel redelivery regression --------- Co-authored-by: VACInc <[email protected]>
… crashes (#200533) ## Problem An accepted (acknowledged) queued chat message could disappear without a trace: - It could be cancelled with no stored reason. History showed nothing, and retrying the same message ID could return a cached success although the message never ran. - A Gateway crash (SIGKILL) lost it. Recovery depended on a graceful-shutdown marker, so a crash before the acknowledgment, or between claiming the message and the turn taking it over, left neither a queued row nor a running turn. On restart nothing answered and nothing explained why. This changes #185730's accepted SIGKILL loss for acknowledged queued input. ## Fix **Recorded end causes** - Store a closed `end_cause` (`user-stop`, `delete`, `reset`, `revoked`, `restart-unrecoverable`, `overflow`, `policy-refused`, `failed`) through the existing pending-input owner. One settlement owner classifies causes (an explicit Stop, delete, reset or revocation wins over a temporary outage), releases consumed custody and records terminal endings. - Temporary authority or dispatch outages: before the input is accepted (no acknowledgment sent; the caller gets the error), the row ends `failed`, as main cancels it today. After acceptance, the row stays queued and the failed attempt gives up its live ownership, so the existing owner (follow-up drain, mailbox, or startup replay) runs it once. - Read durable cancellation before cached success/abort responses; a queued retry reports in flight. - Chat shows one translated sentence per cause (for example "The Gateway restarted before this message ran. Send it again."). A message the user stopped shows no notice, as before (#186073). - Channel redelivery under a fresh run ID still reclaims an attempt that ended `failed`, `restart-unrecoverable`, or with no recorded cause (#193602). Explicit caller retries may reopen a cancelled row unless a final completion receipt exists or the user stopped it. One function (`isRetryableSessionPendingInputEndCause`) defines retryable endings for redelivery and Doctor repair; when Doctor merges two copies of one input, a deliberate ending in either copy wins. **Crash recovery** - Store the already captured, authenticated sender source on the pending row (`origin_source_json`). Startup replays queued, unconsumed rows in FIFO order after running-root resume admission and revalidates current authority when work starts. A missing source ends as `restart-unrecoverable`. The column is cleared when custody ends. It is not the retired, untrusted `recovery_intent_json` envelope; historical v24 interruption is unchanged. - The transaction that appends the user message and consumes the pending row also writes the turn's existing lifecycle start fields, so restart recovery always finds the input as either a queued row or a running turn. No new table, scheduler or reconstruction machinery. - If replay defers because authority or dispatch is temporarily unavailable, the session keeps its older rows ahead of new input: the shared admission point (`waitForAgentInputAdmission`) runs that session's deferred replay once before admitting fresh input, and refuses fresh input with the same retryable error while it still defers. Other sessions are unaffected. No timer or retry loop. - Legacy `queuedInputSources` move from shutdown markers to their pending rows through the startup/Doctor rewrite owner. #200394's `resumeAfterRestart.operatorSource` (the interrupted root requester) is kept; a crash writes no marker, so source-less root recovery keeps the existing session-principal policy. ## Agent schema 43 (one bump) The agent database schema advances from 42 to 43 on SQLite and PostgreSQL through the existing versioned migration owners. It adds nullable `end_cause` and `origin_source_json` to `session_pending_inputs` and, in the same transaction, sets `end_cause = 'user-stop'` for older cancelled rows whose message carries `__openclaw.pendingInputCancelledByUser: true` or `display: false` (message bytes unchanged; dismissed rows stay hidden). Runtime readers use only `end_cause`. Every pre-43 historical schema, including the schema-14 preflight, is derived without the two columns; PostgreSQL v42 predecessor DDL is unchanged. Older builds refuse schema 43; rollback needs the pre-upgrade backup and the matching binary. No schema-version bypass. Pre-migration backup: `session_pending_inputs` is the agent schema's only `AUTOINCREMENT` table, and the scoped migration snapshot does not cover `AUTOINCREMENT` tables (shared `sqlite_sequence`), so Doctor takes its existing full-database backup for 42 → 43 wherever that table exists. Upgrades from stable 2026.11.4 already take a full backup (schema 30 has no scoped entry). For stores already on 42 this is a one-time copy about the size of the agent database (3.0 GB on one measured long-lived store). The migration inserts no rows, and no backup code changes. ## User impact - A queued message survives a crash: it is answered once, or ends with a visible reason. Same-ID retries never start a second answer. - Cancelled messages explain why, in plain words, instead of looking successful. - During a startup access outage, new messages in an affected session get a "try again" error until its older messages have run; nothing runs out of order. Accepted edges: - Explicit `sessions.delete` removes input rows and message bodies; the delete confirmation is the visible result. - Stop on 2026.11.4 and earlier wrote no marker; such rows stay generically cancelled and reclaimable by a same-content channel redelivery, as on main. - An accepted input whose path has no in-process retrier (direct agent execution after acknowledgment) and that hits a temporary outage stays visibly queued until the next Gateway start replays it. - The upgrade from 42 to 43 takes a full-database backup where `session_pending_inputs` exists (see Agent schema 43). - No exactly-once guarantee for external tool effects or provider billing. ## Evidence - Head `ed2c3b46d558`, rebased on current main: format, lint and line caps pass; `pnpm tsgo:core`, all `pnpm tsgo:core:test` configurations and the script typecheck pass; all baseline ratchets and the import-cycle guard pass. Regression tests (each red on an earlier head) cover deferred replay ordering, the shared-store graceful-restart agent, pre-acceptance outages, an accepted follow-up that waits out an outage and then runs exactly once, a same-key attempt with a different run ID (refused), startup replay racing the follow-up drain (one run), a user Stop during an outage, and the original abort signal on cleanup. An internal stop is not recorded as `user-stop`; only a user-initiated Stop is. Only the recorder that confirmed a relinquish may re-attach its queued row; a fresh send, a redelivery or a row whose settlement failed cannot (the revoked-parent-after-stop test stays refused). Startup replay re-attaches only its exact durable row by input ID after a deferred outage. - Schema: reopening a main v42 PostgreSQL store failed before the migration (`PostgreSQL schema drift detected against generated DDL`) and now migrates to 43; 10 real PostgreSQL tests pass. The v14-to-v15 migration test failed with `column definitions differ for session_pending_inputs` before the historical-schema fix and passes now. Each review fix carries a regression test that failed before it. - Crash proof on head `ed2c3b46d558`: isolated source Gateway, Node inspector, real model, external SIGKILL at the exact breakpoint; `plugins.allow=["openai"]`, `plugins.slots.memory="none"`, `cron.enabled=false`. Baseline is main at `6747b1ec5ae3`. | Fault | Main answers / queued model calls | This PR answers / queued model calls | Stored outcome | | --- | --- | --- | --- | | Message row written, before acknowledgment | 0 / 0 | 1 / 1 | Answered; no pending row; session done | | Message claimed, before the turn took it over | 0 / 0 | 1 / 0 (one running-turn recovery call) | Answered; the message was already in the transcript and the row gone at the pause; session done | Each produced exactly one answer and no extra model calls after a same-ID retry. Earlier runs on pre-43 head `975900737b4f` covered a crash just after takeover (one answer, no duplicate) and mid-turn (one answer). - Upgrade from 2026.11.4 (schema 27), clean shutdown and SIGKILL: both reach schema 43 with both columns; a message still queued after the SIGKILL ends `cancelled / restart-unrecoverable`, shown in history and on same-ID retry, with zero model calls. Both this branch and pinned main fail their first start after that SIGKILL with a secrets/SQLite disk-I/O error and succeed on the second start; filed separately as #200617. Doctor's Control UI build during that upgrade is #200618. - Chat notice before/after screenshots are in the PR comments. No full release declaration proof or real PostgreSQL conformance suite is claimed beyond the tests above. Co-authored-by: Ayaan Zaidi <[email protected]>
… crashes (openclaw#200533) ## Problem An accepted (acknowledged) queued chat message could disappear without a trace: - It could be cancelled with no stored reason. History showed nothing, and retrying the same message ID could return a cached success although the message never ran. - A Gateway crash (SIGKILL) lost it. Recovery depended on a graceful-shutdown marker, so a crash before the acknowledgment, or between claiming the message and the turn taking it over, left neither a queued row nor a running turn. On restart nothing answered and nothing explained why. This changes openclaw#185730's accepted SIGKILL loss for acknowledged queued input. ## Fix **Recorded end causes** - Store a closed `end_cause` (`user-stop`, `delete`, `reset`, `revoked`, `restart-unrecoverable`, `overflow`, `policy-refused`, `failed`) through the existing pending-input owner. One settlement owner classifies causes (an explicit Stop, delete, reset or revocation wins over a temporary outage), releases consumed custody and records terminal endings. - Temporary authority or dispatch outages: before the input is accepted (no acknowledgment sent; the caller gets the error), the row ends `failed`, as main cancels it today. After acceptance, the row stays queued and the failed attempt gives up its live ownership, so the existing owner (follow-up drain, mailbox, or startup replay) runs it once. - Read durable cancellation before cached success/abort responses; a queued retry reports in flight. - Chat shows one translated sentence per cause (for example "The Gateway restarted before this message ran. Send it again."). A message the user stopped shows no notice, as before (openclaw#186073). - Channel redelivery under a fresh run ID still reclaims an attempt that ended `failed`, `restart-unrecoverable`, or with no recorded cause (openclaw#193602). Explicit caller retries may reopen a cancelled row unless a final completion receipt exists or the user stopped it. One function (`isRetryableSessionPendingInputEndCause`) defines retryable endings for redelivery and Doctor repair; when Doctor merges two copies of one input, a deliberate ending in either copy wins. **Crash recovery** - Store the already captured, authenticated sender source on the pending row (`origin_source_json`). Startup replays queued, unconsumed rows in FIFO order after running-root resume admission and revalidates current authority when work starts. A missing source ends as `restart-unrecoverable`. The column is cleared when custody ends. It is not the retired, untrusted `recovery_intent_json` envelope; historical v24 interruption is unchanged. - The transaction that appends the user message and consumes the pending row also writes the turn's existing lifecycle start fields, so restart recovery always finds the input as either a queued row or a running turn. No new table, scheduler or reconstruction machinery. - If replay defers because authority or dispatch is temporarily unavailable, the session keeps its older rows ahead of new input: the shared admission point (`waitForAgentInputAdmission`) runs that session's deferred replay once before admitting fresh input, and refuses fresh input with the same retryable error while it still defers. Other sessions are unaffected. No timer or retry loop. - Legacy `queuedInputSources` move from shutdown markers to their pending rows through the startup/Doctor rewrite owner. openclaw#200394's `resumeAfterRestart.operatorSource` (the interrupted root requester) is kept; a crash writes no marker, so source-less root recovery keeps the existing session-principal policy. ## Agent schema 43 (one bump) The agent database schema advances from 42 to 43 on SQLite and PostgreSQL through the existing versioned migration owners. It adds nullable `end_cause` and `origin_source_json` to `session_pending_inputs` and, in the same transaction, sets `end_cause = 'user-stop'` for older cancelled rows whose message carries `__openclaw.pendingInputCancelledByUser: true` or `display: false` (message bytes unchanged; dismissed rows stay hidden). Runtime readers use only `end_cause`. Every pre-43 historical schema, including the schema-14 preflight, is derived without the two columns; PostgreSQL v42 predecessor DDL is unchanged. Older builds refuse schema 43; rollback needs the pre-upgrade backup and the matching binary. No schema-version bypass. Pre-migration backup: `session_pending_inputs` is the agent schema's only `AUTOINCREMENT` table, and the scoped migration snapshot does not cover `AUTOINCREMENT` tables (shared `sqlite_sequence`), so Doctor takes its existing full-database backup for 42 → 43 wherever that table exists. Upgrades from stable 2026.11.4 already take a full backup (schema 30 has no scoped entry). For stores already on 42 this is a one-time copy about the size of the agent database (3.0 GB on one measured long-lived store). The migration inserts no rows, and no backup code changes. ## User impact - A queued message survives a crash: it is answered once, or ends with a visible reason. Same-ID retries never start a second answer. - Cancelled messages explain why, in plain words, instead of looking successful. - During a startup access outage, new messages in an affected session get a "try again" error until its older messages have run; nothing runs out of order. Accepted edges: - Explicit `sessions.delete` removes input rows and message bodies; the delete confirmation is the visible result. - Stop on 2026.11.4 and earlier wrote no marker; such rows stay generically cancelled and reclaimable by a same-content channel redelivery, as on main. - An accepted input whose path has no in-process retrier (direct agent execution after acknowledgment) and that hits a temporary outage stays visibly queued until the next Gateway start replays it. - The upgrade from 42 to 43 takes a full-database backup where `session_pending_inputs` exists (see Agent schema 43). - No exactly-once guarantee for external tool effects or provider billing. ## Evidence - Head `ed2c3b46d558`, rebased on current main: format, lint and line caps pass; `pnpm tsgo:core`, all `pnpm tsgo:core:test` configurations and the script typecheck pass; all baseline ratchets and the import-cycle guard pass. Regression tests (each red on an earlier head) cover deferred replay ordering, the shared-store graceful-restart agent, pre-acceptance outages, an accepted follow-up that waits out an outage and then runs exactly once, a same-key attempt with a different run ID (refused), startup replay racing the follow-up drain (one run), a user Stop during an outage, and the original abort signal on cleanup. An internal stop is not recorded as `user-stop`; only a user-initiated Stop is. Only the recorder that confirmed a relinquish may re-attach its queued row; a fresh send, a redelivery or a row whose settlement failed cannot (the revoked-parent-after-stop test stays refused). Startup replay re-attaches only its exact durable row by input ID after a deferred outage. - Schema: reopening a main v42 PostgreSQL store failed before the migration (`PostgreSQL schema drift detected against generated DDL`) and now migrates to 43; 10 real PostgreSQL tests pass. The v14-to-v15 migration test failed with `column definitions differ for session_pending_inputs` before the historical-schema fix and passes now. Each review fix carries a regression test that failed before it. - Crash proof on head `ed2c3b46d558`: isolated source Gateway, Node inspector, real model, external SIGKILL at the exact breakpoint; `plugins.allow=["openai"]`, `plugins.slots.memory="none"`, `cron.enabled=false`. Baseline is main at `c303d979c41b`. | Fault | Main answers / queued model calls | This PR answers / queued model calls | Stored outcome | | --- | --- | --- | --- | | Message row written, before acknowledgment | 0 / 0 | 1 / 1 | Answered; no pending row; session done | | Message claimed, before the turn took it over | 0 / 0 | 1 / 0 (one running-turn recovery call) | Answered; the message was already in the transcript and the row gone at the pause; session done | Each produced exactly one answer and no extra model calls after a same-ID retry. Earlier runs on pre-43 head `975900737b4f` covered a crash just after takeover (one answer, no duplicate) and mid-turn (one answer). - Upgrade from 2026.11.4 (schema 27), clean shutdown and SIGKILL: both reach schema 43 with both columns; a message still queued after the SIGKILL ends `cancelled / restart-unrecoverable`, shown in history and on same-ID retry, with zero model calls. Both this branch and pinned main fail their first start after that SIGKILL with a secrets/SQLite disk-I/O error and succeed on the second start; filed separately as openclaw#200617. Doctor's Control UI build during that upgrade is openclaw#200618. - Chat notice before/after screenshots are in the PR comments. No full release declaration proof or real PostgreSQL conformance suite is claimed beyond the tests above. Co-authored-by: Ayaan Zaidi <[email protected]>
…hority (#203464, #203463) (#205757) ## Problem Two issues reported possible admission gaps from static reads of `main`: - #203464: a queued channel message could be silently lost after a Gateway restart, because native channel staging saves no operator recovery source and startup replay cancels such a row as `restart-unrecoverable`. - #203463: a collected group batch could run with the last sender's owner rights when one message has no channel admission evidence (`resolveCollectedRun` in `src/auto-reply/reply/queue/drain.ts` returns the source run for unknown evidence). Neither has a regression test for the reported scenario. ## Change Test-only. Production code is unchanged (+0/−0). 1. `dispatch-from-config.pending-restart.test.ts`: a Discord message is staged by a native-shaped recorder (channel `observation` sender, channel source turn key, no operator source). The test runs Gateway shutdown preservation, then the real startup replay `continueSessionQueuedInputs`. The replay ends the row as `restart-unrecoverable` (as the issue says). Then the durable ingress redelivers the same message under a fresh run id: the recorder reclaims the cancelled row (`reclaimCancelledSourceTurn`, `isRetryableSessionPendingInputEndCause`), `dispatchReplyFromConfig` runs it through normal reply admission, and the transcript holds the message exactly once. 2. `queue.collect-sender-authority.test.ts` (new file; `queue.collect.test.ts` is at its line cap): in one group (collect mode, identity audit on), a guest message without admission evidence is queued, then an owner message with evidence. The guest text never runs in the owner's batch and never runs with `senderIsOwner: true`. ## Why no fix - #203464: Discord, Telegram and the other durable-ingress channels keep the message in ingress custody until turn adoption (`docs/concepts/queue.md`, "Channel messages retained by durable ingress remain retryable…"; `ingress-monitor.test.ts` "defers a claimed event across restart drain…"). The Gateway replay refusal is not the end of the message: the redelivery reclaims the row (since #193602 and #200533, both before the issue). No OA2 PR changed this; the issue's chain stopped at the Gateway replay and missed the ingress redelivery. - #203463: the collect storage key (`resolveFollowupAuthorizationKey`, `src/auto-reply/reply/queue/delivery-context.ts`) includes the requester principal, `senderId`, `senderE164` and `senderIsOwner` (since #122863 / #152460). An owner and a non-owner never share a collected claim, so the "return source" branch only sees items with the same sender and owner bit. Making that branch strip authority would remove owner tools from a single owner's batch when identity audit is off (no evidence is minted then), which is a UX regression with no security gain. ## Evidence - Both tests pass on `main` `e4517b0ef2f4`. - Red when the guarding code is removed (local mutation, reverted): - `resolveFollowupAuthorizationKey` returning a constant → #203463 test fails: `expected '[Queued messages while agent was busy…' not to contain 'owner message'`. - `isRetryableSessionPendingInputEndCause` without `restart-unrecoverable` → #203464 test fails: `Pending input idempotency key conflicts with the accepted input` (the redelivered message would be refused). - One-admission E2E on the exact head `aa63024ad82d`: Q, R, S pass (`verdict.json` + `results.jsonl`: https://gist.github.com/obviyus/9dfe6c3b490daebc5442b456a46e10d1). Closes #203463 Closes #203464 Co-authored-by: Ayaan Zaidi <[email protected]>
…hority (openclaw#203464, openclaw#203463) (openclaw#205757) ## Problem Two issues reported possible admission gaps from static reads of `main`: - openclaw#203464: a queued channel message could be silently lost after a Gateway restart, because native channel staging saves no operator recovery source and startup replay cancels such a row as `restart-unrecoverable`. - openclaw#203463: a collected group batch could run with the last sender's owner rights when one message has no channel admission evidence (`resolveCollectedRun` in `src/auto-reply/reply/queue/drain.ts` returns the source run for unknown evidence). Neither has a regression test for the reported scenario. ## Change Test-only. Production code is unchanged (+0/−0). 1. `dispatch-from-config.pending-restart.test.ts`: a Discord message is staged by a native-shaped recorder (channel `observation` sender, channel source turn key, no operator source). The test runs Gateway shutdown preservation, then the real startup replay `continueSessionQueuedInputs`. The replay ends the row as `restart-unrecoverable` (as the issue says). Then the durable ingress redelivers the same message under a fresh run id: the recorder reclaims the cancelled row (`reclaimCancelledSourceTurn`, `isRetryableSessionPendingInputEndCause`), `dispatchReplyFromConfig` runs it through normal reply admission, and the transcript holds the message exactly once. 2. `queue.collect-sender-authority.test.ts` (new file; `queue.collect.test.ts` is at its line cap): in one group (collect mode, identity audit on), a guest message without admission evidence is queued, then an owner message with evidence. The guest text never runs in the owner's batch and never runs with `senderIsOwner: true`. ## Why no fix - openclaw#203464: Discord, Telegram and the other durable-ingress channels keep the message in ingress custody until turn adoption (`docs/concepts/queue.md`, "Channel messages retained by durable ingress remain retryable…"; `ingress-monitor.test.ts` "defers a claimed event across restart drain…"). The Gateway replay refusal is not the end of the message: the redelivery reclaims the row (since openclaw#193602 and openclaw#200533, both before the issue). No OA2 PR changed this; the issue's chain stopped at the Gateway replay and missed the ingress redelivery. - openclaw#203463: the collect storage key (`resolveFollowupAuthorizationKey`, `src/auto-reply/reply/queue/delivery-context.ts`) includes the requester principal, `senderId`, `senderE164` and `senderIsOwner` (since openclaw#122863 / openclaw#152460). An owner and a non-owner never share a collected claim, so the "return source" branch only sees items with the same sender and owner bit. Making that branch strip authority would remove owner tools from a single owner's batch when identity audit is off (no evidence is minted then), which is a UX regression with no security gain. ## Evidence - Both tests pass on `main` `cb5ec7a5bab0`. - Red when the guarding code is removed (local mutation, reverted): - `resolveFollowupAuthorizationKey` returning a constant → openclaw#203463 test fails: `expected '[Queued messages while agent was busy…' not to contain 'owner message'`. - `isRetryableSessionPendingInputEndCause` without `restart-unrecoverable` → openclaw#203464 test fails: `Pending input idempotency key conflicts with the accepted input` (the redelivered message would be refused). - One-admission E2E on the exact head `aa63024ad82d`: Q, R, S pass (`verdict.json` + `results.jsonl`: https://gist.github.com/obviyus/9dfe6c3b490daebc5442b456a46e10d1). Closes openclaw#203463 Closes openclaw#203464 Co-authored-by: Ayaan Zaidi <[email protected]>
Summary
High Level TLDR
A Telegram message that fails once, after its input was saved but before the agent used it, could never be answered. Every retry was rejected with
Pending input idempotency key conflicts with the accepted input, so ingress retried it every 3 minutes for 24 hours and that topic's lane stayed blocked. This change lets the retry of the same channel message reopen its own failed attempt, so the retry actually runs.What Problem This Solves
Fixes: a channel message is never answered, and later messages in the same topic wait behind it, when its first attempt fails after the pending input was staged.
User Impact
User impact: a transient failure on the first attempt (here a transcript write error) now costs one retry instead of a silently dropped message and a 24-hour retry loop on that lane.
Why This Change Was Made
Channel turns key their pending input by the stable channel source turn id (
channel-user:v1:...), but each ingress redelivery dispatches under a fresh run id. Staging only reopens an existing row for the same run, so a redelivery can never match the cancelled row its own failed attempt left behind.The fix adds an opt-in for channel source turns only. A redelivery may reopen an existing row when all of these hold:
cancelledand unconsumedpendingInputCancelledByUser) and dismissal (display: false) are both excludedThe stage write then rebinds
run_idto the new run. Before this change, same-run restages were the only ones that reached that write, so for them it changes nothing. Because staging can now rebind the run, the stage commit comparesrun_idandstateas well asinput_id, so two concurrent reopens cannot both win.Root Cause
Observed on a live Gateway (2026.11.1 and the version before it; ids redacted):
UNIQUE constraint failed: transcript_events.session_id, transcript_events.seq. The pending-input row had already been staged, and the failure path finished it ascancelled.Error: Pending input idempotency key conflicts with the accepted input, and keeps failing at the capped 3-minute backoff: 69 attempts over 3 h 12 min, still pending, across a Gateway restart and upgrade.state=cancelled,consumed_event_id=NULL,idempotency_key=channel-user:v1:<sha256>,run_id=<first attempt>. Recomputingsha256(stableStringify(message without timestamp))from the storedmessage_jsonmatches the storedrequest_hash. The bytes were stable; only the run id differed.prepareReplySourceAdmissionstages withrunId: turn.runId, which is fresh for each dispatch.stagePreparedPendingInputthrows whenexisting.run_id !== options.runId.requestFingerprint, notrackCompletion) hitPending input ownership ended.shouldDeadLetterRetryableIngressEvent). The drain treats a retry-delayed head as blocking its lane (ingress-drain.ts: "A delayed head blocks its lane").The first failure, a transcript
seqcollision, came right after another process appended to the same session transcript. That is a separate bug and is out of scope here. This PR fixes the fact that any such pre-consumption failure becomes permanent for channel messages.Real behavior proof
message processed ... outcome=error error="Error: Pending input idempotency key conflicts with the accepted input"every ~3 minutes from 07:48 to 10:59+. The spool row showedstatus=pending attempts=69.session-accessor.pending-inputs.test.ts):finish("cancelled"). The stored row isrun_id=attempt-1, state=cancelled, consumed_event_id=null.idempotency key conflicts, which is the old behavior.input_id, and the row becomesrun_id=attempt-2, state=queued.× lets a channel redelivery reopen its own cancelled attempt under a fresh run(Tests 1 failed | 32 passed). Patched:Tests 33 passedfor that file.What was not tested
interruptedrows (restart) are deliberately not reopened, because restart recovery owns them. Behavior there is unchanged.seqcollision is not addressed here.Evidence
Verification
src/config/sessions/session-accessor.pending-inputs.test.ts: reopen under a new run; still rejects without the opt-in, with changed bytes, and on a concurrent redelivery; user Stop and dismissal stay fenced.src/config/sessions/session-actor-memory-pending.test.ts: the memory actor rebindsrun_id, and of two concurrent reopens only one wins.src/auto-reply/reply/get-reply-run.source-turn-reclaim.test.ts: channel turns with a provider message id opt in; turns without one do not.dispatch-from-config.pending-restart,user-turn-transcript,get-reply-run.media-only): 19 files, 302 tests passed.pnpm tsgo:core, plus thecore.test.config-cliandcore.test.messagingtsgo shards: clean. oxfmt clean.git diff --checkclean. Pre-commit hooks passed, including the line-cap ratchet.