Skip to content

fix(sessions): channel message never answered after its first attempt fails - #193602

Merged
VACInc merged 2 commits into
openclaw:mainfrom
VACInc:fix/tg-pending-input-replay
Nov 5, 2026
Merged

VACInc merged 2 commits into
openclaw:mainfrom
VACInc:fix/tg-pending-input-replay

Conversation

@VACInc

@VACInc VACInc commented Nov 5, 2026

Copy link
Copy Markdown
Member

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:

  • the row is cancelled and unconsumed
  • it has no completion receipt
  • its request hash is byte-identical
  • it is not a replay fence: user Stop (pendingInputCancelledByUser) and dismissal (display: false) are both excluded

The stage write then rebinds run_id to 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 compares run_id and state as well as input_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):

  1. A Telegram group-topic message is spooled, and the first dispatch fails with UNIQUE constraint failed: transcript_events.session_id, transcript_events.seq. The pending-input row had already been staged, and the failure path finished it as cancelled.
  2. 1.5 s later ingress redelivers the same update. The retry fails with 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.
  3. The stored row (read-only query): state=cancelled, consumed_event_id=NULL, idempotency_key=channel-user:v1:<sha256>, run_id=<first attempt>. Recomputing sha256(stableStringify(message without timestamp)) from the stored message_json matches the stored request_hash. The bytes were stable; only the run id differed.
  4. Code path:
    • prepareReplySourceAdmission stages with runId: turn.runId, which is fresh for each dispatch.
    • stagePreparedPendingInput throws when existing.run_id !== options.runId.
    • Even with a matching run id, channel callers (no requestFingerprint, no trackCompletion) hit Pending input ownership ended.
  5. The ingress retry policy dead-letters only after both 8 attempts and 24 h of age (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 seq collision, 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

  • Incident before the fix (live logs, redacted): 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 showed status=pending attempts=69.
  • After the fix, the regression test reproduces the exact state machine on real SQLite (session-accessor.pending-inputs.test.ts):
    1. Stage under run 1, then finish("cancelled"). The stored row is run_id=attempt-1, state=cancelled, consumed_event_id=null.
    2. Without the opt-in, staging under run 2 still rejects with idempotency key conflicts, which is the old behavior.
    3. With the opt-in and different bytes, it still rejects.
    4. With the opt-in and identical bytes, it reopens the same input_id, and the row becomes run_id=attempt-2, state=queued.
    5. A concurrent run 3 is still rejected.
    6. Promotion appends the message to the transcript exactly once and clears custody.
  • Red on base, green with the fix. Base output: × lets a channel redelivery reopen its own cancelled attempt under a fresh run (Tests 1 failed | 32 passed). Patched: Tests 33 passed for that file.

What was not tested

  • No live end-to-end Telegram run. The reproduction needs a real model turn plus a forced first-attempt failure, and I did not run model inference or send test messages to real chats for this PR.
  • Media messages: the request hash covers the prepared message, so a redelivery that re-downloads media to a new path still conflicts as before. Fixing that needs a raw-input request fingerprint for channel turns, which is a follow-up.
  • interrupted rows (restart) are deliberately not reopened, because restart recovery owns them. Behavior there is unchanged.
  • The underlying transcript seq collision is not addressed here.

Evidence

Verification

  • Regression tests, each red on the base and green with the fix:
    • 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 rebinds run_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.
  • Consumer suites (all pending-input, actor kernel, memory continuations, withdrawal, dispatch-from-config.pending-restart, user-turn-transcript, get-reply-run.media-only): 19 files, 302 tests passed.
  • pnpm tsgo:core, plus the core.test.config-cli and core.test.messaging tsgo shards: clean. oxfmt clean. git diff --check clean. Pre-commit hooks passed, including the line-cap ratchet.
  • Local oxlint could not select files from this worktree location, so CI lint is the lint check.

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.
@clawsweeper

clawsweeper Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 5, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 5, 2026
@clawsweeper

clawsweeper Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: Redelivery under ingress-attempt-2 conflicts with the stored run ID and cannot proceed.
  • After: The retry reuses the input ID, binds it to ingress-attempt-2, and can promote the message once; Stop and dismissal remain fenced.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, narrowly scoped repair with meaningful storage regressions, limited by harness-only after-fix evidence and an implementation-coupled reply test.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its supplied after-fix SQLite evidence exercises staging and promotion, but does not establish recovery through the shipped Telegram ingress and reply path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A transient failure can leave a channel message unanswered and hold later messages behind repeated retry conflicts.
Reason: The concrete incident and current source justify the narrow retry repair, and the maintainer-authored PR supplies direction without another product approval.

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
Reviewed head: a14355e692a13393917e29f03913166f5d2aa75b

Before merge

None.

Findings

None.

Tests

  • Low-value test src/auto-reply/reply/get-reply-run.source-turn-reclaim.test.ts: These tests inspect recorder arguments rather than observing successful redelivery or refusal; replace the call-shape assertions with a reply-path regression that reaches pending-input staging.
  • Missing end-to-end proof: No after-fix shipped Telegram flow demonstrates first-attempt failure, successful redelivery, one answer, and subsequent lane progress.
Agent review details

How this fits together

Channel 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]
Loading

Technical review

Best 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

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current-main failure remains: Main still rejects an existing pending input when its run ID differs; the introduced diff narrowly relaxes that restriction for matching cancelled source turns. (src/config/sessions/session-accessor.pending-inputs.ts:365, 990fc1bd88b9)
  • Bounded reclaim and atomic rebinding: Reclaim requires cancelled, unconsumed, matching input without user retirement; both storage implementations compare input ID, run ID, and state before rebinding. (src/config/sessions/session-pending-input-operations.kernel.ts:159, a14355e692a1)
  • User impact matches ingress policy: Ingress caps ordinary retry backoff at three minutes, requires both the attempt floor and 24-hour age before dead-lettering, and blocks a lane behind its retry-delayed head. (src/channels/message/ingress-drain.ts:654, a14355e692a1)
  • Existing storage format remains compatible: Latest stable and the reviewed checkout have the same pending-input table contract; the patch updates existing run, state, and lifecycle columns while preserving input identity, message bytes, and acceptance time. (src/state/openclaw-agent-schema.sql:887, 4ffdd2047d19)
  • Supplied behavioral evidence: The full PR body reports a live affected-release incident and red-on-base, green-on-head SQLite regressions, while explicitly disclosing that no after-fix Telegram run was performed; discussion contains no additional behavior proof. (a14355e692a1)
  • Historical ownership and intent: The worker cutover retained exact pending-input custody and settlement; the later restart redesign intentionally left interrupted recovery separate. Those boundaries remain intact. Local content-history searches encountered unavailable older blobs, so no unsupported introduction attribution is made. (src/config/sessions/session-accessor.pending-inputs.ts:365, 990fc1bd88b9)

Likely related people:

  • Peter Steinberger: Raw commit d6c1b1f adds src/config/sessions/session-accessor.pending-inputs.ts:274 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d6c1b1f9e14a; files: src/config/sessions/session-accessor.pending-inputs.ts)

PR surface

Source +49, Tests +167, Other +2. Total +218 across 11 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 7 58 9 +49
Tests 3 167 0 +167
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 11 227 9 +218

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P1: The reported affected-release failure permanently rejects retries of an accepted channel message and blocks later messages in the same lane.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: The reported affected-release failure permanently rejects retries of an accepted channel message and blocks later messages in the same lane.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Capture the disclosed failure-and-redelivery scenario through an isolated Telegram Gateway, with one delivered answer and subsequent lane progress.
  • Replace recorder-argument assertions with observable reply-admission behavior.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 5, 2026, 11:59 AM ET / 16:59 UTC.

@VACInc
VACInc merged commit cb719fe into openclaw:main Nov 5, 2026
135 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 6, 2026
… 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]>
wangmiao0668000666 pushed a commit to wangmiao0668000666/openclaw that referenced this pull request Nov 6, 2026
… 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]>
obviyus added a commit that referenced this pull request Nov 18, 2026
… 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
… 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]>
obviyus added a commit that referenced this pull request Nov 26, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant