Skip to content

fix(agents): wait for deferred transcript projection before reopening the session - #130930

Merged
VACInc merged 6 commits into
mainfrom
fix/compaction-retry-waits-for-projection
Aug 27, 2026
Merged

VACInc merged 6 commits into
mainfrom
fix/compaction-retry-waits-for-projection

Conversation

@VACInc

@VACInc VACInc commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

What problem this solves

Large-session auto-compaction can commit a transcript replacement, schedule its projection rebuild off-thread, and immediately retry. The retry then opens the durable session while its own projection is dirty and fails with Session transcript projection is rebuilding: <sessionId> instead of continuing the turn.

Live pre-fix evidence from a 5,063-event session showed compaction succeed at 01:35:57.491, followed 68 ms later by the projection-unavailable failure.

Root cause and owner

#129182 (233ac850f03) intentionally moved large projection rebuilds out of the write transaction. Ordinary readers must remain bounded and fail closed while maintenance is active (src/config/sessions/session-accessor.sqlite-active-projection.ts:120).

The first version of this PR waited in the shared durable-session open path. That was too broad: a fresh attempt could wait behind another run's rebuild, violating the reader contract.

The active run's prompt/session state is the architectural owner of whether a retry follows an in-run transcript mutation. It now records that fact for successful compaction, mid-turn truncation, in-attempt compaction retries, and successful append-only tool-result truncation.

Immediately before dispatching the next attempt, only that owned retry awaits the existing waitForSessionTranscriptProjection seam. The entitlement is consumed before the wait, so later dispatches do not inherit it. Fresh and no-op retries do not load the reconcile module or wait; their existing retryable fail-closed behavior is unchanged.

Invariant

A run's transcript-mutating retry must read its own committed transcript once, while fresh, no-op, and later attempts retain bounded projection-unavailable behavior.

The old unconditional session-open helper was removed. The reconcile module is dynamically loaded only on the owned recovery path, avoiding the CLI startup-memory regression caused by the original eager import.

User impact

Large-session recovery continues after compaction or truncation instead of failing in the deferred-projection window. No configuration, protocol, migration, schema, or persistent-store contract changes.

Evidence

  • Full public-runner integration proof: an actual SQLite projection is dirtied during successful timeout compaction; an ordinary durable read throws SessionTranscriptProjectionUnavailableError; the owned retry waits for the real worker; and the second dispatch reads the rebuilt projection successfully.
  • Mutation proof: removing the production pre-dispatch settlement call makes that integration test fail before the second attempt.
  • Full shared embedded-run integration suite: 77 tests passed.
  • Focused state, normalization, overflow, timeout, and recovery suites: 83 tests passed.
  • Unit negatives cover fresh attempts, no-op mid-turn retries, and one-shot ownership consumption.
  • node scripts/check-changed.mjs: passed, including formatting, lint, dead exports, import cycles, database-first guards, and core/core-test type checks.
  • pnpm tsgo:core and pnpm tsgo:core:test: passed.
  • Autoreview branch pass: no actionable findings.
  • Startup-memory root cause from the first CI run: the eager reconcile import pushed plugins list --json to the 401 MB ceiling. The eager import is removed; exact-head build-artifacts CI is the after-fix measurement.

No live Gateway deployment was performed as part of this PR repair. The reported incident remains the pre-fix real-behavior reproduction; the after-fix isolated proof exercises the public runner and real SQLite projection worker without a live provider.

Diff accounting

Relative to current base: production +28/-2 (net +26), tests +166/-3 (net +163). Production growth is the explicit one-shot owner fact, the mutation-producer mappings, and the single pre-dispatch settlement boundary; there is no second session-open path or compatibility fallback. The larger test delta is the isolated public-runner/SQLite regression scenario requested by review.

… the session

After #129182, compaction replace on transcripts past the sync-rebuild gate
(4,000 rows / 4 MiB) defers the projection rebuild to the reconcile worker.
The overflow-recovery retry reopens the session immediately and the bounded
open fails closed with "Session transcript projection is rebuilding", so
the turn dies right after a successful compaction.

The attempt session open now settles its own session's projection first.
@clawsweeper

clawsweeper Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@VACInc
VACInc marked this pull request as ready for review August 27, 2026 13:23
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 27, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 27, 2026, 12:28 PM ET / 16:28 UTC.

ClawSweeper review

What this changes

The PR waits for a deferred session-transcript projection only before an owned recovery retry, and lets that wait stop when the run is cancelled.

Regression provenance

Possible regression — probable (reviewed change; known regression link). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for normal maintainer review: the branch addresses the retry-after-compaction failure introduced by deferred projection rebuilding, and the focused cancellation and ordering coverage supports the approach. It is not already on the fetched main revision.

Priority: P1
Reviewed head: b87fcbb7a1a49cf7d47b448e757a227a11305dc0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch keeps the wait at the retry owner, preserves ordinary-reader behavior, and includes focused cancellation and ordering coverage.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored reliability PR includes focused SQLite worker and retry-ordering coverage; the external-contributor real-behavior gate does not apply.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored reliability PR includes focused SQLite worker and retry-ordering coverage; the external-contributor real-behavior gate does not apply.
Evidence reviewed 7 items Owned recovery wait: The pre-dispatch owner waits only through session prompt state and forwards the run cancellation signal.
One-shot retry ownership: The state is set only by transcript-mutating recovery paths and consumed before the projection wait, preserving fail-fast ordinary readers.
Cancellation contract: Projection polling accepts an AbortSignal and passes it to the Node timer promise.
Findings None None.
Security None None.

How this fits together

Embedded agent runs can compact or truncate a session transcript after context overflow, then retry the prompt. Large transcripts rebuild their search and active-event projection asynchronously, so the retry must wait for that projection before reopening the session.

flowchart LR
  A[Agent run] --> B[Overflow recovery]
  B --> C[Transcript compaction or truncation]
  C --> D[Deferred projection worker]
  D --> E[Owned retry wait]
  E --> F[Reopen session]
  F --> G[Retry prompt]
Loading

Before merge

  • Resolve merge risk (P1) - The recovery path now deliberately waits for projection completion; retain the cancellation path and verify exact-head checks before merge so a delayed worker cannot prolong a cancelled run.
  • Resolve merge risk (P1) - Production code grows by 26 net lines; the growth is scoped to carrying a retry-owned mutation fact to the pre-dispatch owner, rather than adding an unconditional wait to ordinary session reads.
  • Complete next step (P2) - This is an active maintainer PR with a coherent repair and focused coverage; complete routine exact-head validation rather than dispatching a replacement fix.
Agent review details

Security

None.

PR surface

Source +172, Tests +74. Total +246 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 175 3 +172
Tests 6 77 3 +74
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 252 6 +246

Review metrics

Metric Value Why it matters
Production versus test LOC production +28/-2 (net +26); tests and test support +224/-4 (net +220) The production growth is narrowly justified by retry ownership and cancellation propagation; most of the change is focused regression coverage.
Changed files 13 files affected The change spans the retry producer paths, pre-dispatch owner, projection waiter, and focused tests.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/run/session-prompt-state.ts, serialized state: src/config/sessions/session-transcript-reconcile.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: same_root_cause
Canonical: #129182
Summary: This PR handles the recovery interaction made visible when large transcript projection rebuilding became deferred.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Validate recovery cancellation (recommended)
    Confirm the exact head retains cancellation during the projection wait and that normal projection-reader behavior remains fail-fast before merging.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Verify the focused projection-retry and stalled-worker cancellation paths on the exact head.

Technical review

Best possible solution:

Merge only after exact-head validation confirms the owner-scoped wait remains cancellable and ordinary readers retain their bounded retryable behavior.

Do we have a high-confidence way to reproduce the issue?

No live reproduction was run in this read-only review, but current source and focused tests provide a high-confidence source reproduction of the deferred-projection retry ordering.

Is this the best way to solve the issue?

Yes: keeping the wait at the retry owner avoids changing the established fail-fast contract for ordinary session readers while covering transcript-mutating recovery retries.

AGENTS.md: found but not applied because it conflicted with ClawSweeper's review contract.

Codex review notes: model internal, reasoning high; reviewed against 1c761b712e8c.

Labels

Label justifications:

  • P1: The repaired path can terminate an active agent turn immediately after successful large-session compaction.
  • merge-risk: 🚨 availability: The patch adds a recovery-time wait whose cancellation and projection-completion behavior determines whether a retry can finish.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored reliability PR includes focused SQLite worker and retry-ordering coverage; the external-contributor real-behavior gate does not apply.

Evidence

Acceptance criteria:

  • [P1] Run the focused projection retry ordering coverage.
  • [P1] Run the stalled-worker projection cancellation coverage.
  • [P1] Confirm required checks complete successfully on b87fcbb.

What I checked:

Likely related people:

  • steipete: Authored the merged deferred transcript-projection implementation and the most recent session-area maintenance commit found locally. (role: feature owner and recent area contributor; confidence: high; commits: 233ac850f03c, 2de73ebac9e6; files: src/config/sessions/session-transcript-reconcile.ts, src/agents/embedded-agent-runner/run/session-prompt-state.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete exact-head validation of the projection-retry and cancellation paths.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-27T13:30:29.422Z sha 1da86ba :: found issues before merge. :: [P1] Restrict the wait to the retry that owns the transcript write
  • reviewed 2026-08-27T14:47:12.116Z sha fc9c5da :: needs maintainer review before merge. :: none
  • reviewed 2026-08-27T15:10:37.102Z sha 6e3f656 :: found issues before merge. :: [P1] Honor run cancellation while waiting for the projection

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Updated head: 252d9247e7488da1de170c6756a30f39609db3ad

Scoped projection settlement to retries that own an in-run transcript mutation, removed the unconditional shared-open wait and 5,000-event worker test, and changed the reconcile dependency to a recovery-only dynamic import. Focused validation: 89 tests passed; check-changed, core/core-test typing, and branch autoreview passed. The fresh-path test has negative proof against the unguarded behavior.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Updated head: abc7ec7bafb

Addressed the exact-head ClawSweeper follow-up: continueFromCurrentTranscript no longer marks projection ownership. Only positive truncation and successful compaction outcomes do, and the handled truncatedCount: 0 branch now has an explicit negative assertion. Focused recovery tests, core/core-test typing, check-changed, and branch autoreview pass.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Updated head: fc9c5da5b32

Addressed the latest exact-head ClawSweeper finding: projection ownership is now a one-shot entitlement consumed before settlement. A second dispatch without a new compaction/truncation does not invoke the waiter. Focused recovery tests, core/core-test typing, check-changed, and branch autoreview pass.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Head 6e3f656616ed6555fb65b7f8da1be36d89346e25 adds the requested isolated recovery proof. It exercises the public runner with a real SQLite projection worker: the ordinary dirty read fails fast, the owned compacted retry settles once, and the next dispatch reads successfully. Removing the production settlement call makes the new test fail. Full shared integration: 77 passed; focused recovery suites: 83 passed; check-changed, core/core-test type checks, and branch autoreview are clean. ClawSweeper rank-up move: applied.

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Final exact head 6e3f656616ed6555fb65b7f8da1be36d89346e25 is green: CI run https://github.com/openclaw/openclaw/actions/runs/33085582831 completed successfully, including build-artifacts, all compact shards, all 65 extension/config shards, and openclaw/ci-gate. Startup-memory plugins list --json passed at 400.8 MB median against the 401 MB effective ceiling. Latest ClawSweeper review reports no findings; its isolated-proof rank-up move is applied by this head.

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Unrelated CI follow-up recorded from superseded run 33083512648: extensions/oc-path/.../perf-determinism.test.ts took 5.10s against an 0.8s budget while 5,836 sibling tests passed, and startup RSS missed its median ceiling by 0.8 MB. Neither surface is touched here; both passed on final exact-head run 33085582831. No PR change was made for those non-reproducing shard-load failures.

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Updated head: b87fcbb7a1a49cf7d47b448e757a227a11305dc0

Addressed the exact-head ClawSweeper P1: owned projection settlement now carries the admitted run abort signal into an abortable poll, so cancellation releases a retry even when the projection worker stalls. The new stalled-worker regression has mutation proof (the non-abortable poll stays blocked past 250 ms); the real SQLite/public-runner recovery scenario still passes. Validation: shared integration 77/77, session prompt 8/8, SQLite handle lifecycle 7/7, check-changed, and branch autoreview clean.

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Exact-head validation is complete for b87fcbb7a1a49cf7d47b448e757a227a11305dc0.

  • CI run 33092693011 passed, including check-sqlite-session-lifecycle and openclaw/ci-gate.
  • The first build-artifacts attempt missed the startup-memory ceiling by 0.5 MB; its targeted rerun passed on the same head.
  • The ClawSweeper exact-head review found no actionable findings and confirms the wait remains retry-owned, abortable, and fail-fast for ordinary readers.

@VACInc

VACInc commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Live Gateway proof on exact PR head b87fcbb7a1a49cf7d47b448e757a227a11305dc0 (2026-08-27 ET):

Deployment proof:

Fresh-session real-behavior probe:

  • Forked an inactive historical transcript through the public sessions.fork RPC into a new isolated dashboard session; the source session was not mutated. Source, probe, and run identifiers are omitted.
  • The fork began with 4,557 transcript events and a fully current projection (needs_rebuild=0, indexed_seq=4556).
  • Sent a bounded synthetic prompt through the live Gateway to the reachable ai-server-v4flash/deepseek-v4-flash model (198K context). The first attempt measured 257,433 prompt tokens against the 178,000 pre-reserve budget, and the provider confirmed context overflow at 198,001 total tokens.
  • A compaction event committed at 13:08:19.182 across 4,562 rows, above the 4,000-row deferred-projection gate. Auto-compaction reported success at 13:08:19.416; the owned retry was admitted at 13:08:19.771; an assistant event committed at 13:08:32.448.
  • Terminal outcome was status=ok; durable session state is done with compactionCount=1. Final projection state is clean and current (needs_rebuild=0, indexed_seq=4562, latest transcript seq 4562). The run contains no Session transcript projection is rebuilding / SessionTranscriptProjectionUnavailableError failure.

The intentionally near-limit retry had only one output token available and emitted PRO with stopReason=length; that is a successful provider terminal response, not a response-quality claim. The invariant under test is that the live run continued past successful large-session compaction and its deferred projection window instead of dying before the retry. The exact stalled-worker cancellation behavior remains covered by the focused SQLite lifecycle test and green exact-head CI.

@VACInc
VACInc merged commit 3366d2c into main Aug 27, 2026
344 of 346 checks passed
@VACInc
VACInc deleted the fix/compaction-retry-waits-for-projection branch August 27, 2026 17:39
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 28, 2026
… the session (openclaw#130930)

* fix(agents): wait for deferred transcript projection before reopening the session

After openclaw#129182, compaction replace on transcripts past the sync-rebuild gate
(4,000 rows / 4 MiB) defers the projection rebuild to the reconcile worker.
The overflow-recovery retry reopens the session immediately and the bounded
open fails closed with "Session transcript projection is rebuilding", so
the turn dies right after a successful compaction.

The attempt session open now settles its own session's projection first.

* fix(agents): scope projection waits to owned retries

* fix(agents): exclude no-op transcript retries

* fix(agents): consume projection retry ownership

* test(agents): prove owned projection retry ordering

* fix(agents): make projection retry wait abortable

---------

Co-authored-by: VACInc <[email protected]>
@VACInc

VACInc commented Sep 8, 2026

Copy link
Copy Markdown
Member Author

Complementary handoff coverage merged in #141718 (merge commit). This PR's owned in-run retry waiter remains intact. The new fix reuses waitForSessionTranscriptProjection at a different owner: sessions_yield cleanup waits for its durable rewrite before releasing the session to a new queued turn, which would not inherit the previous run's retry entitlement.

The new SQLite regression covers more than 4,000 retained history entries and immediate bounded reopening, with and without handoff context. Ordinary fresh readers remain bounded/fail-fast; no global wait or replay of completed tools was added.

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

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant