Repository navigation
fix(agents): record background results at request boundaries - #188406
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 132c35cfe2
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ...(isSessionControllerWorkActive(storePath, identities, params.agentId) | ||
| ? { excludeFromContext: true, openclawModelPlacement: "pending" as const } | ||
| : {}), |
There was a problem hiding this comment.
Place pending results for CLI-backed sessions too
When a background result arrives during a CLI-backed turn, runWithCliTurn() also holds withSessionTurn() custody, so this condition marks the result as pending. However, the only placement producer is installed by AgentSessionBase; runCliAgent() never invokes it. Subsequent CLI history reads use buildSessionContext() or iterateSessionContextEntries(), which now omit unplaced pending results. Consequently, completions previously included in CLI recovery/resume context remain excluded indefinitely unless the session later runs through the embedded agent. Either provide a request-boundary placement path for CLI runners or restrict pending admission to runtimes that can consume it.
Useful? React with 👍 / 👎.
| for (const id of placements.get(row.seq) ?? []) { | ||
| const source = sources.get(id); | ||
| if (!source) { | ||
| throw new Error(`Background result placement payload is unavailable: ${id}`); | ||
| } | ||
| if (!retained.has(source.seq)) { | ||
| additions.set(source.seq, source); |
There was a problem hiding this comment.
Retain placement markers in reset compaction windows
After a preserve-tail reset retains a placed background result, compaction hydration drops its placement marker before this dependency fitter runs. In readSessionActorBoundedHistory(), the reset-retained selection uses selectResetKeptEntries(), which selects messages but not custom markers; the SQLite reset-window reader likewise retains only message positions. This fitter restores dependencies only for selected markers, so the hydrated result remains an excluded pending message with no placement. A branch containing a user message, pending result, assistant reply, placement, and retaining reset therefore includes the result in canonical replay but omits it from compaction input. Preserve the retained placements and their payloads when constructing reset compaction windows.
Useful? React with 👍 / 👎.
|
Codex review: blocked before merge. What this changesThis PR records background-result placement at request boundaries so live requests and reopened conversations preserve the same message order. Example: An automation result arrives while lookup call call_lookup_1 is running.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep this PR open: it addresses a real prompt-prefix defect, but three consumer gaps can exclude background results from later context. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherBackground producers append results to the session transcript; the agent loop, replay readers, compaction, and forks consume that transcript to construct model context. flowchart LR
Producer[Background producer] --> Transcript[Session transcript]
Transcript --> Placement[Request boundary placement]
Placement --> Loop[Live agent request]
Transcript --> Replay[Replay and bounded readers]
Replay --> Lifecycle[Compaction and forks]
Replay --> Request[Reopened model request]
Technical reviewBest possible solution: Complete placement support in the existing CLI and reset-hydration owners while preserving immediate persistence and immutable accepted payloads. Do we have a high-confidence way to reproduce the issue? The producer, live loop, and replay selector establish the ordering mismatch, and supplied regressions report baseline failures for tool-time and streaming arrivals; no target code was executed during this review. Is this the best way to solve the issue? Persisting placement through existing transcript owners addresses the invariant directly, but the cutover must include CLI consumers and reset compaction hydration. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d73a0d98757a. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +693, Tests +685, Docs +10, Other +2. Total +1390 across 37 files. Added test files: 0. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 30, 2026, 10:23 AM ET / 14:23 UTC. |
132c35c to
f606d93
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f606d930c2
ℹ️ About Codex in GitHub
Your team has set up Codex to 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 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ...(isSessionControllerWorkActive(storePath, identities, params.agentId) | ||
| ? { excludeFromContext: true, openclawModelPlacement: "pending" as const } | ||
| : {}), |
There was a problem hiding this comment.
Include placed results in compaction summary preparation
When a live or fully loaded session is compacted after a background result has been placed, runCompactionWork() still passes the raw sessionManager.getBranch() to prepareCompaction(). Its cut-point and summarization paths use getMessageFromEntryForCompaction(), which excludes the pending artifact because of excludeFromContext and ignores the custom placement marker. Consequently, a result already seen by the foreground model never reaches the summary, and its information disappears once compaction advances past its placement. Project the logical placements for compaction planning and summarization as well as ordinary replay.
Useful? React with 👍 / 👎.
| ...lines.slice(1, tailStart).filter((line) => { | ||
| const id = safeParseJsonRecord(line)?.id; | ||
| return typeof id === "string" && dependencyIds.has(id); | ||
| }), | ||
| ...tailLines, |
There was a problem hiding this comment.
Keep retained trim dependencies on the active branch
When a referenced result predates the trimmed tail and intervening ancestors are removed, prepending its row does not keep it reachable from the placement. For example, trimming result -> old -> recent -> placement to the last two entries produces retained rows result, recent, and placement, but normalization assigns recent.parentId = null because old is absent. The active branch then contains only recent -> placement; canonical replay throws Background result placement payload is unavailable because the referenced result is outside that branch. Preserve or reconnect the dependency ancestry when normalizing the retained rows.
Useful? React with 👍 / 👎.
…enclaw#188406) * fix(agents): record background results at request boundaries * fix(agents): preserve bounded history during result placement
What Problem This Solves
Background task results accepted during an assistant run can appear at a different position when the conversation is reopened, breaking the previously sent prompt prefix. A result arriving during streaming can even move ahead of signed assistant output.
User Impact
Background completions remain immediately durable and visible. Subsequent model requests preserve their recorded order across live execution and replay, including recovery after an interrupted run. Existing transcripts keep their current interpretation.
Why This Change Was Made
The approved persisted-contract extension records placement with an immutable transcript marker at the next request boundary. It references the original result entries and the exact preceding entry. Live execution adopts those recorded results without importing foreign queued user input, rewriting accepted payloads, or waiting for the parent run to settle.
Bounded and model-context reads, compaction/reset, forks, and suffix cleanup preserve the marker's dependencies. Pending payloads remain recoverable before placement, including through cached reads. There is no database table migration or transcript version bump. Older readers omit newly pending results from model context; the results remain visible in transcript history.
This is one complete persisted-contract cutover: the producer, live loop, replay, and lifecycle consumers must agree before the new marker can be written. Production TypeScript is +789/−69 lines (net +720); tests are +724/−30 (net +694). The growth supports that contract across existing owners, rather than a parallel execution path. No test-line ceiling increase is needed.
Evidence
Both real-producer timing regressions fail on main
f9135d23491031bbc55bd265f5be07c246b6139b: tool-time arrival preserves only 4 of 6 prior Responses input items; streaming arrival inserts ahead of signed reasoning. The regression captures the real Responses request builder with synthetic messages, without sending a provider request. Candidate assertions check byte-exact prefix extension, live/replay equality, and unchanged accepted transcript bytes.Initial complete consumer run: 119 tests passed across 10 files, including both timing variants, interrupted-run recovery, bounded cleanup, forks/resets, rewrite references, all 14 prompt-prefix tests, and next-turn consumers.
Final agent-loop, Responses-continuation, and argument-preparation tests: 43 passed. The request-hook tests moved intact into the existing continuation file; the oversized loop delegates its unchanged synchronous argument-preparation block to the existing tool-execution owner. Line-cap ratchet passed without raising caps.
Existing live-input tests: 7 passed, including foreign-input isolation.
PR wrapper closure: both previously failing checks now pass after adding the new modules to its inventory; the other 36 tooling checks passed in the earlier run.
pnpm tsgo:test:root: all four shards passed.Review-fix validation: 47 tests passed across five files, including both original timing variants, all four original recovery modes, cached pending-payload hydration, byte limits, and zero acquisition of unrelated excluded navigation.
All five interrupted-run recovery modes passed; the final bounded tests also prove that the omitted middle history stays unhydrated.
pnpm tsgo:core, changed-file oxlint, and oxfmt checks passed.Exact-head CI test-line ratchet passed: 6,299,756 lines against a 6,311,720 ceiling, with 11,964 lines of headroom. The ceiling is unchanged.
Codex autoreview completed through P2. Both accepted findings were fixed. A final bounded-ancestry concern was rejected:
SessionManager.getEntry()already returns normalized parents; the added real-producer regression confirms recovery with only the pending result and newest input hydrated across omitted middle history. No accepted findings remain. Two subsequent Codex reviews of the CI repair batch were clean through P2, including the final fixture and assertion-baseline changes. Rebase retained the upstream replay-test repair unchanged; production changes are identical to the reviewed patch. Export-name collision guard passed.CI found and the follow-up repairs address a bounded-read regression: dependency selection now checks the stored classification before evaluating model navigation, so it does not parse omitted malformed history or legacy duplicate-key rows. The unchanged tests for both cases pass. Marker projection now uses the existing dialect-aware JSON helper; the dialect guard remains at 25 design and 4 mechanical constructs. The moved argument-preparation cast has its validation invariant documented, and its old unused assertion allowance was removed.
The replay-cohort rewrite failures reproduced on unchanged base
6c9614337c050e379a0d01cd469c3fd6db36b001(both cases failed). They were stale expectations after #187989 introduced a fresh read on the first conflict. The upstream repair in #188398 now requires empty fresh preparation without a replay callback, or rejection of the obsolete final projection, while still proving no stale input is consumed. We kept that upstream test unchanged when rebasing; this PR does not duplicate its repair. All close/revoke cases passed in the equivalent local repair run. The inherited PostgreSQL backup/config alias failure is resolved by rebasing over the upstream fix34a4e118dc1d, without copying it into this branch.The repair run passed 148 tests across seven files. The final fixture check, targeted source-test typechecks,
pnpm tsgo:core, and all fourpnpm tsgo:test:rootshards passed. Changed-file oxlint and oxfmt passed. No runtime performance improvement is claimed. Exact-head CI passed atf606d930c269a187dbd51e851fe731803d564213(CI run), including all three PostgreSQL conformance jobs. The PR is ready and intentionally unmerged.