Skip to content

fix(channels/turn): clear pending history on error paths - #123193

Merged
obviyus merged 9 commits into
openclaw:mainfrom
SunnyShu0925:fix/clear-pending-history-error-path-bug-008
Aug 24, 2026
Merged

obviyus merged 9 commits into
openclaw:mainfrom
SunnyShu0925:fix/clear-pending-history-error-path-bug-008

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Failed group turns could replay stale context on the next turn.

Two current owners participate:

  • runPreparedChannelTurnCoreInTrace cleared caller-owned pending history only after successful dispatch. Record-key validation, transcript merge, session recording, and dispatch failures escaped cleanup.
  • Telegram now keeps a rolling group window instead of delegating destructive cleanup. Its normal context builder merged cached chat-window rows without first applying the existing “after latest self reply” selection used by topic recovery.

The result was a duplicated failed user turn in the next Telegram model request: once from the canonical transcript and once from stale Telegram chat-window context.

Fix

  • Finalize delegated pending history once in an outer finally after admission. Early drops keep their existing pre-callback cleanup.
  • Apply Telegram’s existing retain-then-merge flow to normal group context, while leaving DM chat windows unchanged.
  • Retain explicit is_reply_target rows even when older ambient chat-window rows are filtered.
  • Add owner-boundary regressions for invalid record keys, transcript-merge failure, record failure, dispatch failure, stale Telegram context, explicit reply targets, and DM preservation.

Production delta: net +9 judged lines (+5 channel terminal ownership, +7/-3 Telegram context ownership). Test delta: net +155 lines. The large raw channel diff is the existing record/dispatch body moving under one try/finally.

Evidence

Head: cd41e4e798c452635a4d8ca78d801e8fcd9cdec4

Regression proof before repair:

  • Channel dispatch-failure test failed with the pending entry still present.
  • Telegram context test failed with the failed turn and bot error still present in ChannelStructuredContext.

Local proof after repair:

  • Channel-turn grouped suite: 9 files, 93 tests passed.
  • Telegram bot/context/recovery suite: 19 files, 310 tests passed.
  • oxfmt --check on all changed files.
  • Type-aware Oxlint with core and extension configs.
  • pnpm tsgo, pnpm tsgo:extensions, and pnpm check:test-types.
  • Distill: one terminal finalizer for delegated maps; one existing retain/merge path for Telegram rolling history.
  • Greybeard: no new I/O or discovery; O(1) delegated clear plus a bounded historyLimit key/filter pass.
  • Exact-head local ClawSweeper (gpt-5.6-terra, high): PASS; correct patch, 0 findings, security clear, no maintainer decision, 0 Rank-up moves.

Hosted CI: exact-head run 32696855590 green; 0 pending, 10 obsolete checks superseded.

Real Telegram userbot evidence

Exact head, real QA user, Telegram group/topic, deterministic provider fixture:

  1. User sent failed-turn sentinel (50461). Provider returned intentional HTTP 503; SUT surfaced LLM request failed. (50462).
  2. QA user sent recovery sentinel as a native Telegram reply (50463) to SUT message 50462.
  3. Recovery provider request contained:
    • failed-turn sentinel strings: 1 — canonical transcript only; stale chat-window copy absent;
    • recovery sentinel strings: 1;
    • LLM request failed. strings: 1 — explicit reply target retained.
  4. SUT returned FAILED_TURN_HISTORY_COUNT_1.

Recorded artifacts include summary.json, events.ndjson, gateway.log, and mock-openai-requests.ndjson. The first-turn 503, Telegram-native reply relation, raw request counts, and recovery response agree.

Inspectable redacted exact-head artifact excerpts

summary.json / events.ndjson:

{
  "head": "cd41e4e798c452635a4d8ca78d801e8fcd9cdec4",
  "recordingComplete": true,
  "actions": [
    {"actionType":"send","status":"completed","botApiMessageId":50461},
    {"actionType":"reply","status":"completed","botApiMessageId":50463,"messageId":52914290688,"replyToMessageId":52913242112}
  ],
  "sutMessages": [
    {"botApiMessageId":50462,"messageId":52913242112,"text":"LLM request failed."},
    {"botApiMessageId":50464,"text":"FAILED_TURN_HISTORY_COUNT_1"}
  ],
  "observedRecoveryMessage": {"botApiMessageId":50463,"replyToMessageId":52913242112}
}

gateway.log:

{"status":503,"message":"503 INTENTIONAL_FIRST_TURN_FAILURE"}
{"event":"embedded_run_agent_end","isError":true,"error":"LLM request failed.","rawErrorPreview":"503 INTENTIONAL_FIRST_TURN_FAILURE"}

mock-openai-requests.ndjson, counts over every string field in each raw request:

[
  {"request":1,"failed":1,"recovery":0,"reply_error":0},
  {"request":2,"failed":1,"recovery":0,"reply_error":0},
  {"request":3,"failed":1,"recovery":0,"reply_error":0},
  {"request":4,"failed":1,"recovery":1,"reply_error":1}
]

Request 4 is the changed-path recovery request. failed: 1 proves the stale duplicate is absent; reply_error: 1 proves native reply ancestry remains present. Account, token, chat, session, trace, and filesystem fields are redacted.

Risk

  • Non-group and absent-history callers remain no-ops in the shared finalizer.
  • Telegram DMs bypass group retention; focused DM tests pass.
  • Explicit reply ancestry remains available even when stale ambient rows are removed.
  • No config, schema, protocol, dependency, or persistence change.

@clawsweeper

clawsweeper Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch 2 times, most recently from 04707cd to 722337d Compare August 13, 2026 13:25
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch from 722337d to 5c70037 Compare August 13, 2026 22:51
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Aug 14, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 24, 2026, 2:26 AM ET / 06:26 UTC.

ClawSweeper review

What this changes

The branch finalizes caller-owned group history on every channel-turn exit and preserves explicit Telegram reply targets while filtering stale cached group context.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 4 items remain

The cleanup boundary is sound and covers the previously missed terminal exits, but the current head also changes Telegram reply-context behavior without exact-head real Telegram proof; keep this PR open until that proof and its queued channel checks complete.

Priority: P2
Reviewed head: cd41e4e798c452635a4d8ca78d801e8fcd9cdec4

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch is a focused, source-supported repair, but exact-head real behavior proof is missing for the Telegram reply-context path.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The body provides focused test output and a claimed local script, but the current head’s Telegram reply-context change lacks an after-fix real Telegram trace or recording; add redacted evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The body provides focused test output and a claimed local script, but the current head’s Telegram reply-context change lacks an after-fix real Telegram trace or recording; add redacted evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Unified terminal cleanup: The post-admission finally encloses record-key validation, transcript merging, session recording, and dispatch, so every throw and successful return finalizes the supplied group-history map.
Pre-change gap: The local PR-base snapshot cleared pending history only after successful dispatch; record and dispatch exceptions rethrew before that call.
Sibling channel coverage: Signal and Discord construct routed turns with caller-owned group history maps, so the core finalizer protects those channel paths rather than a test-only surface.
Findings None None.
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs extensions/telegram/src/bot-message-context.prompt-context.test.ts

Result: FAIL (partial) — step 2 expect_output keeps an explicit reply target while omitting cached context before the latest bot reply: expected terminal output was not visible within 30 seconds: "keeps an explicit reply target while omitting cached context before the latest bot reply"

node scripts/run-vitest.mjs extensions/telegram/src/bot-message-context.prompt-context.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-123193-MfbmAJ/target$ node scripts/run-vitest.mjs extensions/telegram/src/bot-message-context.prompt-context.te
st.ts
node scripts/run-vitest.mjs extensions/telegram/src/bot-message-context.prompt-context.test.ts
[test] starting test/vitest/vitest.extension-telegram.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-123193-MfbmAJ/target

[vitest] still running with no output for 30000ms.
 ✓  extension-telegram  extensions/telegram/src/bot-message-context.prompt-context.test.ts (13 tests) 882ms
     ✓ omits Telegram chat-window context for existing unthreaded private DM sessions  486ms
     ✓ backfills Telegram group history when the ambient watermark belongs to a reset session  351ms

 Test Files  1 passed (1)
      Tests  13 passed (13)
   Start at  06:27:21
   Duration  30.28s (transform 24.60s, setup 1.26s, import 27.96s, tests 882ms, environment 0ms)

[test] passed 1 Vitest shard in 36.52s
runner@runnervm76f27:/tmp/clawsweeper-live-proof-123193-MfbmAJ/target$ node scripts/run-vitest.mjs extensions/telegram/src/bot-message-context.prompt-context.te
st.ts






























Assertions:

  • FAIL expect_output: keeps an explicit reply target while omitting cached context before the latest bot reply
  • FAIL expect_output: Test Files

How this fits together

Channel turns record an inbound message and dispatch an agent response while group-history maps feed later prompts. Telegram separately filters cached chat-window context before it is attached to the agent’s inbound context.

flowchart LR
  A[Incoming group message] --> B[Channel turn]
  B --> C[Session record]
  C --> D[Agent dispatch]
  D --> E[Finalize pending history]
  A --> F[Telegram cached context]
  F --> G[Reply-target filter]
  G --> B
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The body provides focused test output and a claimed local script, but the current head’s Telegram reply-context change lacks an after-fix real Telegram trace or recording; add redacted evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The exact head changes Telegram reply-context behavior, but the submitted evidence is synthetic and predates the latest Telegram commit; a real after-fix group-chat trace is still needed.
  • Resolve merge risk (P1) - The required exact-head channel checks are queued, so the final branch state has not yet been validated by CI.
  • Complete next step (P2) - The remaining gate is contributor-supplied real Telegram proof and exact-head CI, not a mechanical repair task.
Agent review details

Security

None.

PR surface

Source +9, Tests +155. Total +164 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 115 106 +9
Tests 2 168 13 +155
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 283 119 +164

Review metrics

Metric Value Why it matters
Production versus test delta production +9 raw (mostly relocated control flow), tests +155 The functional core change is a single finalization boundary plus Telegram context filtering; the larger addition is regression coverage.

Merge-risk options

Maintainer options:

  1. Prove the changed Telegram context path (recommended)
    Add a redacted after-fix Telegram group trace or recording with diagnostic context showing the reply target remains while stale history is excluded, then merge only after exact-head channel checks pass.

Technical review

Best possible solution:

Keep the single core finalizer, then add a redacted real Telegram group-turn proof showing an explicit reply target survives a failed prior turn without stale chat-window context before merging green exact-head checks.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes the prior failure path: the base implementation cleared history only after successful dispatch, while the focused regression cases exercise each earlier terminal escape.

Is this the best way to solve the issue?

Yes for the core defect: one post-admission finally is the narrow canonical owner boundary, and the Telegram filter preserves an explicit reply target while dropping unselected cached context.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f40cb158b1d8.

Labels

Label changes:

  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The body provides focused test output and a claimed local script, but the current head’s Telegram reply-context change lacks an after-fix real Telegram trace or recording; add redacted evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • add mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The Telegram change affects which reply target and chat-window context guide the next visible group reply and can be demonstrated in Telegram Desktop.
  • remove proof: sufficient: Current real behavior proof status is mock_only, not sufficient.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: 📣 needs proof.

Label justifications:

  • P2: This repairs bounded group-chat prompt state and reply context without evidence of broader runtime outage.
  • merge-risk: 🚨 session-state: Merging intentionally changes which caller-owned group history and cached Telegram context can reach the next agent prompt after terminal failures.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The body provides focused test output and a claimed local script, but the current head’s Telegram reply-context change lacks an after-fix real Telegram trace or recording; add redacted evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • mantis: telegram-visible-proof: Mantis should capture Telegram visible proof. The Telegram change affects which reply target and chat-window context guide the next visible group reply and can be demonstrated in Telegram Desktop.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: The current-head commit carrying the Telegram reply-target behavior is attributed locally to this author; shallow history prevents stronger ownership attribution. (role: recent area contributor; confidence: low; commits: cd41e4e798c4; files: extensions/telegram/src/group-history-window.ts, extensions/telegram/src/bot-message-context.session.ts)
  • obviyus: The PR’s recorded commit history attributes the preceding channel-history repair commits to this contributor. (role: recent repair contributor; confidence: medium; commits: 4939462ebd5f; files: src/channels/turn/execution.ts, src/channels/turn/run-channel-turn.finalize.test.ts)

Rank-up moves

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

  • Post a redacted Telegram group-chat trace or recording that exercises a failed prior turn and an explicit reply target.
  • Wait for the exact-head channel checks to complete successfully.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-14T09:46:10.848Z sha 1fd77ac50b9b0553c5b370a73fd47f8d0f79643a :: needs changes before merge. :: [P2] Begin finalization before record-key validation
  • reviewed 2026-08-14T09:52:07.719Z sha 1fd77ac50b9b0553c5b370a73fd47f8d0f79643a :: needs changes before merge. :: [P2] Start finalization before record-key validation
  • reviewed 2026-08-14T10:02:38.868Z sha 1fd77ac50b9b0553c5b370a73fd47f8d0f79643a :: needs changes before merge. :: [P2] Start finalization before record-key validation
  • reviewed 2026-08-14T10:19:42.852Z sha bfb35ec1089c97316ecd5716973780fb18edf4d4 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-18T07:34:12.335Z sha 60cf75ea29a9ac64ddc54fdb77ecb3d6e9ea44d5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-20T13:17:59.537Z sha 8be9210bf6c2b2dfd072b243c73d85e912277d9e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-20T17:09:20.830Z sha 35e934d :: needs changes before merge. :: [P3] Condense the finalizer invariant comment
  • reviewed 2026-08-24T06:10:42.009Z sha 4939462 :: needs maintainer review before merge. :: none

@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 14, 2026
@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch from a4df39c to 1fd77ac Compare August 14, 2026 09:40
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addresses the P2 finding "Finalize history around transcript-context failures".

Change: Replaced the per-catch and success-path clearPendingHistoryAfterTurn calls with a single post-drop try/finally that wraps transcript-context merge, session recording, and dispatch. The finally finalizes the caller-owned pending-history map on every terminal exit, including the pre-record transcript-context merge failure that previously threw before either catch ran.

Why this closes the finding: mergeSessionTranscriptContext runs before the record-stage try/catch; when it throws (unscoped owner, or readRecentUserAssistantTextForSession rejection), the old per-catch cleanup never executed, leaving the group history map populated. The outer finally covers that path now.

Regression test added: "clears pending group history when transcript-context merge fails before recording" — mocks readRecentUserAssistantTextForSession to reject and asserts the map is cleared.

Pre-fix / post-fix proof (local, exact head 1fd77ac):

Pre-fix (HEAD reverted to the prior per-catch implementation):

expect(historyMap.get(historyKey)).toStrictEqual([]);
// 1 failed | 16 skipped
// AssertionError: expected [ { sender: 'alice', body: 'earlier group msg', timestamp: 1 } ] to equal []

Post-fix (head 1fd77ac):

Test Files  1 passed (1)
     Tests  17 passed (17)

Early-drop returns (outbound-echo, bot-loop-protection) already call clearPendingHistoryAfterTurn and return before the try, so they are not affected by the new finally.

oxfmt --check, oxlint (-c .oxlintrc.json), and tsgo on execution.ts are clean.

@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch from 1fd77ac to bfb35ec Compare August 14, 2026 10:14
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Addresses the new P2 finding "Start finalization before record-key validation".

Change: Moved resolveRecordSessionKey(params) inside the post-drop try/finally boundary (it was previously called just before the try). Invalid explicit record.sessionKey values (blank or surrounding-whitespace) now throw through the same finally cleanup instead of escaping it, so the caller-owned group pending-history map is finalized on that terminal path too.

Why this closes the finding: resolveRecordSessionKey throws for blank keys ("Channel turn record.sessionKey must be non-empty.") and padded keys ("...must not include surrounding whitespace.") — both before the prior try began, leaving the history map populated for the next group turn. Moving the resolver inside the try covers that exit. The early-drop returns (outboundEcho, botLoop) still return before the try and remain unaffected.

Regression test added: "clears pending group history when the explicit record session key is invalid" — passes record: { sessionKey: " " } with a pre-seeded caller-owned historyMap and asserts the map is cleared after the turn re-throws.

Pre-fix / post-fix proof (local, exact head bfb35ec):

Pre-fix (HEAD reverted to the prior try placement via git stash):

$ node_modules/.bin/vitest run src/channels/turn/run-channel-turn.finalize.test.ts -t "clears pending group history when the explicit record session key is invalid"
 Test Files  1 failed (1)
      Tests  1 failed | 17 skipped (18)
AssertionError: expected [ { sender: 'alice', body: 'earlier group msg', timestamp: 1 } ] to strictly equal []

Post-fix (head bfb35ec):

$ node_modules/.bin/vitest run src/channels/turn/run-channel-turn.finalize.test.ts
 Test Files  1 passed (1)
      Tests  18 passed (18)

Behavior matrix now covered:

error path                  => pre-fix result                  => post-fix result
record-stage throw          => historyMap len=1 (leaked)        => historyMap len=0 (cleared)
dispatch-stage throw        => historyMap len=1 (leaked)        => historyMap len=0 (cleared)
transcript-merge throw      => historyMap len=1 (leaked)        => historyMap len=0 (cleared)
invalid record session key  => historyMap len=1 (leaked)        => historyMap len=0 (cleared)

oxfmt --check, oxlint (-c .oxlintrc.json), and tsgo on execution.ts are clean. Rebased onto latest origin/main (ahead 1, behind 0).

@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch from 60cf75e to 8be9210 Compare August 20, 2026 13:12
The caller-owned group pending-history map is retained across turns; a
turn must finalize it on every terminal exit so the next group turn does
not replay stale context. Wrap the transcript-context merge, session
recording, and dispatch in a single post-drop try/finally that calls
clearPendingHistoryAfterTurn once, replacing the per-catch and
success-path calls.

The previous per-catch cleanup left the map populated when the pre-record
transcript-context merge threw before either catch ran, so the next group
turn replayed stale context.

Adds regression tests for both the session-recording and
transcript-merge failure paths.

Closes openclaw#123193
@SunnyShu0925
SunnyShu0925 force-pushed the fix/clear-pending-history-error-path-bug-008 branch from 8be9210 to 35e934d Compare August 20, 2026 16:57
@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram size: S and removed size: M labels Aug 24, 2026
@clawsweeper clawsweeper Bot added mantis: telegram-visible-proof Mantis should capture Telegram visible proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Aug 24, 2026
@obviyus
obviyus merged commit 02b8ed7 into openclaw:main Aug 24, 2026
291 of 295 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 25, 2026
…3193)

Failed channel turns could leave caller-owned pending group history in the next prompt. Finalize it on every terminal path, and filter Telegram rolling context while preserving explicit reply ancestry.

Co-authored-by: SunnyShu0925 <[email protected]>
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

channel: telegram Channel integration: telegram mantis: telegram-visible-proof Mantis should capture Telegram visible proof. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants