Repository navigation
Conversation
…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
Greptile SummaryThis PR fixes a real bug where duplicate user messages accumulate in a session JSONL file during retry loops ( Key findings:
Confidence Score: 4/5
Prompt To Fix All With AIThis 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"; | |||
There was a problem hiding this 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.
| 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.| function stripTrailingOrphanedUserMessages( | ||
| sm: { | ||
| flushed: boolean; | ||
| fileEntries: Array<SessionHeaderEntry | SessionMessageEntry | { type: string }>; | ||
| byId?: Map<string, unknown>; | ||
| leafId?: string | null; | ||
| }, | ||
| sessionFile: string, |
There was a problem hiding this 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:
| 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.There was a problem hiding this comment.
💡 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".
| if (removed && "id" in removed && typeof (removed as SessionMessageEntry).id === "string") { | ||
| sm.byId?.delete((removed as SessionMessageEntry).id!); | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
Problem
When a
chat.sendRPC triggers an embedded agent run that fails (429 rate limit, model exhaustion, etc.) and the retry loop inrun.tscallsrunEmbeddedAttemptagain, a new SessionManager is constructed from the existing JSONL file.Since
hasAssistant=true(the error entry hasrole: "assistant"),flushed=trueimmediately. Whenprompt()callsappendMessage(userMessage), the Pi agent's_persist()method callsappendFileSyncimmediately — 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.sendRPC produces 4 user message entries with unique IDs and timestamps 10-40s apart:Root Cause
In
prepareSessionManagerForRun(), thehadSessionFile && header && !hasAssistantbranch resets the file. But on retry,hasAssistant=true(error entries haverole: "assistant"), so no reset happens,flushedstaystrue, and the nextprompt()call writes the user message again.Fix
Added
stripTrailingOrphanedUserMessages()toprepareSessionManagerForRun(). 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