Repository navigation
feat(agents): add mid-turn compaction precheck - #73499
Conversation
|
Codex review: needs maintainer review before merge. What this changes: Keep open. Current main still lacks the PR's intended opt-in Maintainer follow-up before merge: Keep this PR open for maintainer and author iteration. A mergeable version should add the opt-in config/schema/help/docs surface, route post-tool-result pressure through the existing recovery path, document its relationship to Best possible solution: Keep this PR open for maintainer and author iteration. A mergeable version should add the opt-in config/schema/help/docs surface, route post-tool-result pressure through the existing recovery path, document its relationship to Acceptance criteria:
What I checked:
Likely related people:
Remaining risk / open question:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 1dac6ac4c601. |
|
seems valid — the opt-in flag + reuse of the existing precheck recovery path keeps the surface tight. one thing I'd want to understand: how does this compose with if the answer is "they're orthogonal and never compose because the byte-size guard already fired before the turn started," a one-line note in separate small thing: |
1830b18 to
562e679
Compare
Greptile SummaryThis PR adds an opt-in Confidence Score: 4/5Safe to merge; the feature is opt-in and the two P2 findings only affect observability and edge-case route accuracy, not correctness of the happy path. Both findings are P2: one is a silent failure mode that only manifests on session resume after a specific SDK internals mismatch, and the other is a minor estimation imprecision in route selection. No P0/P1 issues found in core logic, config schema, or test coverage. src/agents/pi-embedded-runner/run/attempt.ts — specifically removeTrailingMidTurnPrecheckAssistantError which relies on private SessionManager internals without any fallback diagnostic. Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/agents/pi-embedded-runner/run/attempt.ts
Line: 503-533
Comment:
**Silent failure when `SessionManager` internals are unavailable**
`removeTrailingMidTurnPrecheckAssistantError` accesses private `SessionManager` fields (`fileEntries`, `byId`, `leafId`, `_rewriteFile`) using optional chaining. If the `@mariozechner/pi-coding-agent` SDK changes these internal property names, the function silently exits after updating in-memory `agent.state.messages` (line 509) but without flushing the change to the JSONL file (`_rewriteFile?.()` is a no-op). On the next session resume the synthetic `"stopReason": "error"` message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.
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/tool-result-context-guard.ts
Line: 377-416
Comment:
**Mid-turn precheck runs on per-message-truncated messages, inflating `toolResultReducibleChars`**
The guard first applies per-message truncation (lines 365–376) to a clone of `sourceMessages`, producing `contextMessages`. The mid-turn precheck then calls `shouldPreemptivelyCompactBeforePrompt` with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the `toolResultReducibleChars` estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in `handleMidTurnPrecheckRequest` operates on the untouched `activeSessionManager` entries rather than on `contextMessages`.
In practice the downstream truncation-recovery code re-applies `maxCharsOverride` against the session manager, so the outcome should still be correct, but the route decision (`truncate_tool_results_only` vs. `compact_only`) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "test(agents): add live mid-turn loop ver..." | Re-trigger Greptile |
| function removeTrailingMidTurnPrecheckAssistantError(params: { | ||
| activeSession: { agent: { state: { messages: AgentMessage[] } } }; | ||
| sessionManager: ReturnType<typeof guardSessionManager>; | ||
| }): void { | ||
| const messages = params.activeSession.agent.state.messages; | ||
| if (isMidTurnPrecheckAssistantError(messages.at(-1))) { | ||
| params.activeSession.agent.state.messages = messages.slice(0, -1); | ||
| } | ||
|
|
||
| const mutableSessionManager = params.sessionManager as unknown as { | ||
| fileEntries?: Array<{ | ||
| type?: string; | ||
| id?: string; | ||
| parentId?: string | null; | ||
| message?: AgentMessage; | ||
| }>; | ||
| byId?: Map<string, unknown>; | ||
| leafId?: string | null; | ||
| _rewriteFile?: () => void; | ||
| }; | ||
| const lastEntry = mutableSessionManager.fileEntries?.at(-1); | ||
| if (lastEntry?.type !== "message" || !isMidTurnPrecheckAssistantError(lastEntry.message)) { | ||
| return; | ||
| } | ||
| mutableSessionManager.fileEntries?.pop(); | ||
| if (lastEntry.id) { | ||
| mutableSessionManager.byId?.delete(lastEntry.id); | ||
| } | ||
| mutableSessionManager.leafId = lastEntry.parentId ?? null; | ||
| mutableSessionManager._rewriteFile?.(); | ||
| } |
There was a problem hiding this comment.
Silent failure when
SessionManager internals are unavailable
removeTrailingMidTurnPrecheckAssistantError accesses private SessionManager fields (fileEntries, byId, leafId, _rewriteFile) using optional chaining. If the @mariozechner/pi-coding-agent SDK changes these internal property names, the function silently exits after updating in-memory agent.state.messages (line 509) but without flushing the change to the JSONL file (_rewriteFile?.() is a no-op). On the next session resume the synthetic "stopReason": "error" message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/run/attempt.ts
Line: 503-533
Comment:
**Silent failure when `SessionManager` internals are unavailable**
`removeTrailingMidTurnPrecheckAssistantError` accesses private `SessionManager` fields (`fileEntries`, `byId`, `leafId`, `_rewriteFile`) using optional chaining. If the `@mariozechner/pi-coding-agent` SDK changes these internal property names, the function silently exits after updating in-memory `agent.state.messages` (line 509) but without flushing the change to the JSONL file (`_rewriteFile?.()` is a no-op). On the next session resume the synthetic `"stopReason": "error"` message would still be present in the persisted transcript, which could confuse the model or cause a second unexpected error during session reload. There is no warning or metric emitted when this partial cleanup occurs.
How can I resolve this? If you propose a fix, please make it concise.| if (params.midTurnPrecheck?.enabled) { | ||
| const prePromptMessageCount = Math.max( | ||
| 0, | ||
| Math.min( | ||
| contextMessages.length, | ||
| lastSeenLength ?? | ||
| params.midTurnPrecheck.getPrePromptMessageCount?.() ?? | ||
| contextMessages.length, | ||
| ), | ||
| ); | ||
| lastSeenLength = prePromptMessageCount; | ||
| if ( | ||
| hasNewToolResultAfterFence({ | ||
| messages: contextMessages, | ||
| prePromptMessageCount, | ||
| }) | ||
| ) { | ||
| const precheck = shouldPreemptivelyCompactBeforePrompt({ | ||
| messages: contextMessages, | ||
| systemPrompt: params.midTurnPrecheck.getSystemPrompt?.(), | ||
| // During a tool loop, the active user prompt is already part of messages. | ||
| prompt: "", | ||
| contextTokenBudget: params.midTurnPrecheck.contextTokenBudget, | ||
| reserveTokens: params.midTurnPrecheck.reserveTokens(), | ||
| toolResultMaxChars: params.midTurnPrecheck.toolResultMaxChars, | ||
| }); | ||
| const request = toMidTurnPrecheckRequest(precheck); | ||
| log.debug( | ||
| `[context-overflow-midturn-precheck] tool-result-guard check route=${precheck.route} ` + | ||
| `messages=${contextMessages.length} prePromptMessageCount=${prePromptMessageCount} ` + | ||
| `estimatedPromptTokens=${precheck.estimatedPromptTokens} ` + | ||
| `promptBudgetBeforeReserve=${precheck.promptBudgetBeforeReserve} ` + | ||
| `overflowTokens=${precheck.overflowTokens}`, | ||
| ); | ||
| if (request) { | ||
| params.midTurnPrecheck.onMidTurnPrecheck?.(request); | ||
| throw new MidTurnPrecheckSignal(request); | ||
| } | ||
| } | ||
| lastSeenLength = contextMessages.length; |
There was a problem hiding this comment.
Mid-turn precheck runs on per-message-truncated messages, inflating
toolResultReducibleChars
The guard first applies per-message truncation (lines 365–376) to a clone of sourceMessages, producing contextMessages. The mid-turn precheck then calls shouldPreemptivelyCompactBeforePrompt with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the toolResultReducibleChars estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in handleMidTurnPrecheckRequest operates on the untouched activeSessionManager entries rather than on contextMessages.
In practice the downstream truncation-recovery code re-applies maxCharsOverride against the session manager, so the outcome should still be correct, but the route decision (truncate_tool_results_only vs. compact_only) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/tool-result-context-guard.ts
Line: 377-416
Comment:
**Mid-turn precheck runs on per-message-truncated messages, inflating `toolResultReducibleChars`**
The guard first applies per-message truncation (lines 365–376) to a clone of `sourceMessages`, producing `contextMessages`. The mid-turn precheck then calls `shouldPreemptivelyCompactBeforePrompt` with these already-truncated messages (line 394). If the per-message pass already brought individual results within the single-message cap, the `toolResultReducibleChars` estimate returned by the precheck may over-estimate the remaining reduction potential, because the recovery path in `handleMidTurnPrecheckRequest` operates on the untouched `activeSessionManager` entries rather than on `contextMessages`.
In practice the downstream truncation-recovery code re-applies `maxCharsOverride` against the session manager, so the outcome should still be correct, but the route decision (`truncate_tool_results_only` vs. `compact_only`) could be made on a lower-pressure estimate than reality. A comment explaining why the precheck intentionally uses the post-truncation view would improve maintainability.
How can I resolve this? If you propose a fix, please make it concise.
@stainlu stainluThanks, this is the intended split:
So they are complementary checkpoints rather than two competing triggers at the same point. If the byte guard already compacted before the turn, mid-turn precheck sees that resulting session state. If tool results later push the prompt over budget, mid-turn precheck can still fire later in the same user turn. It does not compact inside the Pi transform hook. I also added the doc note to make that distinction explicit. The recovery log already includes |
|
@stainlu maxActiveTranscriptBytes:
midTurnPrecheck:
所以它们不是同一个 checkpoint 上的两个 competing trigger。
|
Summary
agents.defaults.compaction.midTurnPrecheck.enabledsetting for embedded Pi runs.Validation
node scripts/test-projects.mjs src/agents/pi-embedded-runner/tool-result-context-guard.test.ts src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts src/config/config.compaction-settings.test.ts src/config/zod-schema.agent-defaults.test.ts src/config/schema.help.quality.test.ts