Skip to content

fix(agents): record background results at request boundaries - #188406

Merged
steipete merged 2 commits into
mainfrom
steipete/fix-background-result-placement-marker-20261030
Oct 30, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/fix-background-result-placement-marker-20261030

Conversation

@steipete

@steipete steipete commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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 fix 34a4e118dc1d, 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 four pnpm tsgo:test:root shards passed. Changed-file oxlint and oxfmt passed. No runtime performance improvement is claimed. Exact-head CI passed at f606d930c269a187dbd51e851fe731803d564213 (CI run), including all three PostgreSQL conformance jobs. The PR is ready and intentionally unmerged.

@clawsweeper

clawsweeper Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-30T14:57:07.166345Z f606d93 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 30, 2026

@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: 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".

Comment on lines +146 to +148
...(isSessionControllerWorkActive(storePath, identities, params.agentId)
? { excludeFromContext: true, openclawModelPlacement: "pending" as const }
: {}),

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 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 👍 / 👎.

Comment on lines +65 to +71
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);

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 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 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 30, 2026
@clawsweeper

clawsweeper Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This 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.

  • Before: Live execution and reopened history can place the result differently, changing an already submitted request prefix.
  • After: A persisted marker places the result after the completed lookup pair in both live execution and replay.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful request-level regressions support the design, but three context-selection defects and unverified persisted-contract compatibility prevent a pass.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied evidence exercises the real producer and Responses request builder with synthetic streams, without a provider request.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Reopening a conversation can reorder background completions relative to previously submitted assistant output, invalidating the request prefix.
Reason: The maintainer-authored direction restores the documented stable-history contract without delaying result visibility.

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
Reviewed head: 132c35cfe25f7dfee5ca6429952100b34ed93954

Before merge

  • Provide placement for results accepted during CLI turns (P2) - A background completion arriving during runWithCliTurn is marked pending because that runner also holds withSessionTurn custody. Only AgentSessionBase installs the placement hook, so CLI execution never places this result. Later canonical CLI context reads exclude it indefinitely unless an embedded run intervenes. Add CLI request-boundary placement or restrict pending admission to a runtime that can consume it. This confirms the existing discussion at fix(agents): record background results at request boundaries #188406 (comment).
  • Preserve retained placement markers during reset compaction hydration (P2) - For a branch containing a user message, pending result, assistant reply, placement marker, and preserve-tail reset, canonical replay retains the placed result. However, the actor reader selects reset-kept messages without their custom marker, and the SQLite reset window similarly retains message positions only. This fitter restores dependencies only for selected markers, leaving the retained payload excluded from compaction input. Preserve retained markers and their payloads in both reset-window owners. This confirms fix(agents): record background results at request boundaries #188406 (comment).
  • Retain placement semantics in manager-backed CLI history (P2) - When a supplied SessionManager contains an already placed result, the changed iterator yields its pending source entry with separate placement metadata. loadCliMemoryEntries keeps only entry identities and filters the original branch, dropping the marker. loadCliSessionContextEngineMessages and loadCliSessionPromptContext then call buildSessionContext on that filtered branch, which excludes the still-pending source. Thus even results already placed by an embedded run disappear from manager-backed CLI recovery. Preserve the marker dependencies or consume the canonical projected messages directly.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Provide placement for results accepted during CLI turns — src/sessions/background-session-result.ts:146-148
  • [P2] Preserve retained placement markers during reset compaction hydration — src/config/sessions/session-actor-bounded-history.ts:97-103
  • [P2] Retain placement semantics in manager-backed CLI history — src/agents/cli-runner/session-history.ts:233-237

Tests

  • Missing end-to-end proof: No supplied latest-stable upgrade run establishes that existing session data and context remain intact under the new persisted placement contract.
Agent review details

How this fits together

Background 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]
Loading

Technical review

Best 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:

  • [P2] Provide placement for results accepted during CLI turns — src/sessions/background-session-result.ts:146-148
    A background completion arriving during runWithCliTurn is marked pending because that runner also holds withSessionTurn custody. Only AgentSessionBase installs the placement hook, so CLI execution never places this result. Later canonical CLI context reads exclude it indefinitely unless an embedded run intervenes. Add CLI request-boundary placement or restrict pending admission to a runtime that can consume it. This confirms the existing discussion at fix(agents): record background results at request boundaries #188406 (comment).
    Confidence: 0.98
  • [P2] Preserve retained placement markers during reset compaction hydration — src/config/sessions/session-actor-bounded-history.ts:97-103
    For a branch containing a user message, pending result, assistant reply, placement marker, and preserve-tail reset, canonical replay retains the placed result. However, the actor reader selects reset-kept messages without their custom marker, and the SQLite reset window similarly retains message positions only. This fitter restores dependencies only for selected markers, leaving the retained payload excluded from compaction input. Preserve retained markers and their payloads in both reset-window owners. This confirms fix(agents): record background results at request boundaries #188406 (comment).
    Confidence: 0.98
  • [P2] Retain placement semantics in manager-backed CLI history — src/agents/cli-runner/session-history.ts:233-237
    When a supplied SessionManager contains an already placed result, the changed iterator yields its pending source entry with separate placement metadata. loadCliMemoryEntries keeps only entry identities and filters the original branch, dropping the marker. loadCliSessionContextEngineMessages and loadCliSessionPromptContext then call buildSessionContext on that filtered branch, which excludes the still-pending source. Thus even results already placed by an embedded run disappear from manager-backed CLI recovery. Preserve the marker dependencies or consume the canonical projected messages directly.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d73a0d98757a.

Provenance checked

  • Immediate background-result persistence keeps the original intent (4261a4c: Allow results to commit during active turns without retaining mutation custody until turn settlement.)
  • Canonical replay selection changes intended behavior with a stated reason (4431033: Share canonical context selection while avoiding redundant history copies and preserving replay evidence.)
  • Reset and compaction hydration keeps the original intent (c902f9a: Hydrate complete current context and retained messages without obsolete archive history.)
  • Bounded model-context navigation keeps the original intent (9296818: Retain a selectable suffix and exact prefix facts instead of whole-history navigation objects.)
  • Suffix persistence keeps the original intent (fd578cb: Use existing worker admission and committed receipts while preserving durable ordering and current-owner checks.)
  • Fork selection and sizing keeps the original intent (4916019: Size and copy the same current selected context under guarded write admission.)
  • Manual transcript trimming keeps the original intent (6da98fb: Perform durable trimming in the existing worker while retaining normalized branch semantics.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/sessions/background-session-result.test.ts src/agents/cli-runner/session-history.test.ts src/agents/cli-runner/session-history.async.test.ts
  • pnpm test src/config/sessions/session-actor-bounded-history.test.ts src/config/sessions/session-accessor.sqlite-bounded-context.test.ts src/config/sessions/session-accessor.sqlite-model-context.test.ts
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts
  • pnpm tsgo:core
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4261a4c adds src/sessions/background-session-result.ts:85 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4261a4ccaad0; files: src/sessions/background-session-result.ts)
  • Josh Lehman: Raw commit 133d5ff adds src/sessions/background-session-result.ts:74 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 133d5fff6c94; files: src/sessions/background-session-result.ts)
  • Sukhdeep: Raw commit c902f9a adds src/config/sessions/session-actor-bounded-history.ts:83 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c902f9aa2f64; files: src/config/sessions/session-actor-bounded-history.ts)

PR surface

Source +693, Tests +685, Docs +10, Other +2. Total +1390 across 37 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 25 762 69 +693
Tests 10 715 30 +685
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 37 1489 99 +1390

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This fixes request-prefix consistency, with remaining defects limited to background-result context selection.
  • merge-risk: 🚨 session-state: CLI recovery and reset compaction can omit accepted background results from model context.
  • merge-risk: 🚨 compatibility: The persisted placement contract changes how new result rows are interpreted; older-reader omission is explicitly accepted, while upgrade compatibility remains unverified.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 30, 2026, 10:23 AM ET / 14:23 UTC.

@steipete
steipete force-pushed the steipete/fix-background-result-placement-marker-20261030 branch from 132c35c to f606d93 Compare October 30, 2026 14:52

@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: 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".

Comment on lines +146 to +148
...(isSessionControllerWorkActive(storePath, identities, params.agentId)
? { excludeFromContext: true, openclawModelPlacement: "pending" as const }
: {}),

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 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 👍 / 👎.

Comment on lines +31 to +35
...lines.slice(1, tailStart).filter((line) => {
const id = safeParseJsonRecord(line)?.id;
return typeof id === "string" && dependencyIds.has(id);
}),
...tailLines,

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 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 👍 / 👎.

@steipete
steipete merged commit 074b316 into main Oct 30, 2026
161 of 162 checks passed
@steipete
steipete deleted the steipete/fix-background-result-placement-marker-20261030 branch October 30, 2026 15:21
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 31, 2026
…enclaw#188406)

* fix(agents): record background results at request boundaries

* fix(agents): preserve bounded history during result placement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant