Skip to content

fix: strip trailing orphaned user messages on retry to prevent duplicates - #46028

Closed
0xNatoshi wants to merge 2 commits into
openclaw:mainfrom
0xNatoshi:fix/webchat-duplicate-user-messages
Closed

0xNatoshi wants to merge 2 commits into
openclaw:mainfrom
0xNatoshi:fix/webchat-duplicate-user-messages

Conversation

@0xNatoshi

Copy link
Copy Markdown

Problem

When a chat.send RPC triggers an embedded agent run that fails (429 rate limit, model exhaustion, etc.) and the retry loop in run.ts calls runEmbeddedAttempt again, a new SessionManager is constructed from the existing JSONL file.

Since hasAssistant=true (the error entry has role: "assistant"), flushed=true immediately. When prompt() calls appendMessage(userMessage), the Pi agent's _persist() method calls appendFileSync immediately — writing a duplicate user message.

Each retry creates another duplicate. Result: N retries = N+1 copies of the same user message in the session JSONL.

Evidence

Single chat.send RPC produces 4 user message entries with unique IDs and timestamps 10-40s apart:

{"id":"8cfa68f8","timestamp":"2026-03-14T10:44:10.682Z"}
{"id":"a1b28ab6","timestamp":"2026-03-14T10:44:22.368Z"}
{"id":"a62bfc33","timestamp":"2026-03-14T10:44:47.593Z"}
{"id":"89ad76ee","timestamp":"2026-03-14T10:44:53.092Z"}

Root Cause

In prepareSessionManagerForRun(), the hadSessionFile && header && !hasAssistant branch resets the file. But on retry, hasAssistant=true (error entries have role: "assistant"), so no reset happens, flushed stays true, and the next prompt() call writes the user message again.

Fix

Added stripTrailingOrphanedUserMessages() to prepareSessionManagerForRun(). When the file exists and has assistant entries, it detects user messages after the last assistant entry (orphaned from a previous failed attempt) and removes them from both the in-memory entries and the JSONL file before the retry prompt.

This is a minimal, surgical fix that doesn't change the retry logic or the Pi agent runtime.

Fixes #46005

…ates

When an embedded agent run fails (429, rate limit, etc.) and retries,
a new SessionManager is created from the existing JSONL file. Since
hasAssistant=true (from the error entry), flushed=true, and prompt()
immediately writes a new user message via appendFileSync — creating
a duplicate.

This adds stripTrailingOrphanedUserMessages() to prepareSessionManagerForRun
which detects user messages after the last assistant entry and removes
them before the retry prompt, preventing N retries = N duplicate user
messages in the session transcript.

Fixes #46005
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Mar 14, 2026
@greptile-apps

greptile-apps Bot commented Mar 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real bug where duplicate user messages accumulate in a session JSONL file during retry loops (chat.send → embedded agent → 429/rate-limit failure → retry). When an attempt fails without writing an assistant entry, the next SessionManager constructed from the file (with hasAssistant=true from a prior turn) has flushed=true, so the subsequent prompt() immediately appends a fresh user message on top of the one written by the previous failed attempt. The new stripTrailingOrphanedUserMessages helper correctly detects and removes those orphaned trailing user messages from both the in-memory fileEntries array and the on-disk JSONL before the next retry begins.

Key findings:

  • The core logic is sound and addresses the described duplication scenario.
  • writeFileSync (synchronous blocking I/O) is introduced via a new import, inconsistent with the node:fs/promises-only pattern used elsewhere in this file — should be converted to async/await fs.writeFile.
  • The helper's sm parameter type omits labelsById, which the sibling reset branch (!hasAssistant path) explicitly clears; orphaned user-message label entries could be left behind in that map.

Confidence Score: 4/5

  • Safe to merge — the fix correctly removes duplicate user messages and is narrowly scoped to the retry path; two minor non-blocking style issues remain.
  • The fix targets a single well-understood root cause, the logic for detecting and stripping orphaned trailing user messages is correct, and it doesn't alter the retry flow itself. The two flagged issues (sync I/O and missing labelsById cleanup) are style/consistency concerns rather than correctness bugs, but the blocking writeFileSync is worth resolving before shipping to avoid event-loop stalls on large session files.
  • src/agents/pi-embedded-runner/session-manager-init.ts — the writeFileSync import and its usage in stripTrailingOrphanedUserMessages should be converted to async.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/session-manager-init.ts
Line: 2

Comment:
**Use async `fs.writeFile` instead of `writeFileSync`**

`writeFileSync` is a synchronous blocking call imported specifically for this PR. The rest of this file consistently uses `await fs.writeFile(...)` (the existing `node:fs/promises` import). For large session files (long multi-turn conversations), `writeFileSync` will block the Node.js event loop while serialising potentially many KB or MB of JSONL.

`stripTrailingOrphanedUserMessages` should be made `async` and call `await fs.writeFile(...)` instead, consistent with the existing pattern in `prepareSessionManagerForRun`.

```suggestion
import fs from "node:fs/promises";
```

And update the function signature / call:

```ts
async function stripTrailingOrphanedUserMessages(
  sm: { ... },
  sessionFile: string,
): Promise<void> {
  // ...
  await fs.writeFile(sessionFile, lines, "utf-8");
}
```

Then `prepareSessionManagerForRun` should `await` the call:
```ts
await stripTrailingOrphanedUserMessages(sm, params.sessionFile);
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/session-manager-init.ts
Line: 65-72

Comment:
**`labelsById` not cleaned up when removing orphaned messages**

The `sm` parameter type for `stripTrailingOrphanedUserMessages` omits `labelsById`, whereas the broader `sm` type in `prepareSessionManagerForRun` (line 24–31) does include `labelsById?: Map<string, unknown>`. The parallel `hadSessionFile && !hasAssistant` branch explicitly calls `sm.labelsById?.clear?.()` when resetting state.

If any of the stripped user messages have an associated entry in `labelsById`, those stale references will be left behind. While user messages are less likely to have labels than assistant messages, the omission is inconsistent. Consider adding `labelsById` to the parameter type and deleting the relevant entries:

```suggestion
function stripTrailingOrphanedUserMessages(
  sm: {
    flushed: boolean;
    fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>;
    byId?: Map<string, unknown>;
    labelsById?: Map<string, unknown>;
    leafId?: string | null;
  },
  sessionFile: string,
): void {
```

And in the removal loop:
```ts
sm.byId?.delete((removed as SessionMessageEntry).id!);
sm.labelsById?.delete((removed as SessionMessageEntry).id!);
```

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 6ebacf4

@@ -1,7 +1,8 @@
import fs from "node:fs/promises";
import { writeFileSync } from "node:fs";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use async fs.writeFile instead of writeFileSync

writeFileSync is a synchronous blocking call imported specifically for this PR. The rest of this file consistently uses await fs.writeFile(...) (the existing node:fs/promises import). For large session files (long multi-turn conversations), writeFileSync will block the Node.js event loop while serialising potentially many KB or MB of JSONL.

stripTrailingOrphanedUserMessages should be made async and call await fs.writeFile(...) instead, consistent with the existing pattern in prepareSessionManagerForRun.

Suggested change
import { writeFileSync } from "node:fs";
import fs from "node:fs/promises";

And update the function signature / call:

async function stripTrailingOrphanedUserMessages(
  sm: { ... },
  sessionFile: string,
): Promise<void> {
  // ...
  await fs.writeFile(sessionFile, lines, "utf-8");
}

Then prepareSessionManagerForRun should await the call:

await stripTrailingOrphanedUserMessages(sm, params.sessionFile);
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/session-manager-init.ts
Line: 2

Comment:
**Use async `fs.writeFile` instead of `writeFileSync`**

`writeFileSync` is a synchronous blocking call imported specifically for this PR. The rest of this file consistently uses `await fs.writeFile(...)` (the existing `node:fs/promises` import). For large session files (long multi-turn conversations), `writeFileSync` will block the Node.js event loop while serialising potentially many KB or MB of JSONL.

`stripTrailingOrphanedUserMessages` should be made `async` and call `await fs.writeFile(...)` instead, consistent with the existing pattern in `prepareSessionManagerForRun`.

```suggestion
import fs from "node:fs/promises";
```

And update the function signature / call:

```ts
async function stripTrailingOrphanedUserMessages(
  sm: { ... },
  sessionFile: string,
): Promise<void> {
  // ...
  await fs.writeFile(sessionFile, lines, "utf-8");
}
```

Then `prepareSessionManagerForRun` should `await` the call:
```ts
await stripTrailingOrphanedUserMessages(sm, params.sessionFile);
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +65 to +72
function stripTrailingOrphanedUserMessages(
sm: {
flushed: boolean;
fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>;
byId?: Map<string, unknown>;
leafId?: string | null;
},
sessionFile: string,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

labelsById not cleaned up when removing orphaned messages

The sm parameter type for stripTrailingOrphanedUserMessages omits labelsById, whereas the broader sm type in prepareSessionManagerForRun (line 24–31) does include labelsById?: Map<string, unknown>. The parallel hadSessionFile && !hasAssistant branch explicitly calls sm.labelsById?.clear?.() when resetting state.

If any of the stripped user messages have an associated entry in labelsById, those stale references will be left behind. While user messages are less likely to have labels than assistant messages, the omission is inconsistent. Consider adding labelsById to the parameter type and deleting the relevant entries:

Suggested change
function stripTrailingOrphanedUserMessages(
sm: {
flushed: boolean;
fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>;
byId?: Map<string, unknown>;
leafId?: string | null;
},
sessionFile: string,
function stripTrailingOrphanedUserMessages(
sm: {
flushed: boolean;
fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>;
byId?: Map<string, unknown>;
labelsById?: Map<string, unknown>;
leafId?: string | null;
},
sessionFile: string,
): void {

And in the removal loop:

sm.byId?.delete((removed as SessionMessageEntry).id!);
sm.labelsById?.delete((removed as SessionMessageEntry).id!);
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/session-manager-init.ts
Line: 65-72

Comment:
**`labelsById` not cleaned up when removing orphaned messages**

The `sm` parameter type for `stripTrailingOrphanedUserMessages` omits `labelsById`, whereas the broader `sm` type in `prepareSessionManagerForRun` (line 24–31) does include `labelsById?: Map<string, unknown>`. The parallel `hadSessionFile && !hasAssistant` branch explicitly calls `sm.labelsById?.clear?.()` when resetting state.

If any of the stripped user messages have an associated entry in `labelsById`, those stale references will be left behind. While user messages are less likely to have labels than assistant messages, the omission is inconsistent. Consider adding `labelsById` to the parameter type and deleting the relevant entries:

```suggestion
function stripTrailingOrphanedUserMessages(
  sm: {
    flushed: boolean;
    fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>;
    byId?: Map<string, unknown>;
    labelsById?: Map<string, unknown>;
    leafId?: string | null;
  },
  sessionFile: string,
): void {
```

And in the removal loop:
```ts
sm.byId?.delete((removed as SessionMessageEntry).id!);
sm.labelsById?.delete((removed as SessionMessageEntry).id!);
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6ebacf456a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +98 to +100
if (removed && "id" in removed && typeof (removed as SessionMessageEntry).id === "string") {
sm.byId?.delete((removed as SessionMessageEntry).id!);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove label index entries when dropping orphaned users

stripTrailingOrphanedUserMessages deletes removed message IDs from byId but leaves labelsById untouched, which makes the SessionManager indexes diverge after this cleanup runs. This file’s reset path already treats byId and labelsById as coupled state, so removing only one side here can leave stale label pointers to non-existent entries and cause later session-manager operations (for example branch/label lookups on subsequent attempts) to resolve invalid IDs.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 26a2a34379

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +87 to +90
for (let i = lastAssistantIdx + 1; i < sm.fileEntries.length; i++) {
const e = sm.fileEntries[i];
if (e.type === "message" && (e as SessionMessageEntry).message?.role === "user") {
trailingUserIndices.push(i);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prune full trailing branch when removing orphaned users

This loop only marks role === "user" entries for deletion, so it can remove a parent node while leaving later non-user descendants behind, which corrupts the session tree. That case is reachable in the sessions-yield path, where a yield-aborted turn can persist a trailing custom message (persistSessionsYieldContextMessage in src/agents/pi-embedded-runner/run/attempt.ts:230-252 and its call at :2480-2482); after this change, the parent user entry is dropped but the custom entry remains with a dangling ancestry, which can break later SessionManager traversal/branch behavior. The cleanup should remove the entire trailing orphaned branch, not only user-role rows.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

webchat: single chat.send creates 3-4 duplicate user messages in session JSONL

1 participant