Skip to content

perf(sessions): defer transcript index rebuilds to the reconcile worker - #129182

Merged
steipete merged 6 commits into
mainfrom
steipete/deferred-transcript-index-rebuild
Aug 25, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/deferred-transcript-index-rebuild

Conversation

@steipete

@steipete steipete commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Follow-up to #129135. The remaining whole-gateway stall source on busy hosts: transcript replacement/rewrite paths rebuilt the full FTS + active-event projection inside their synchronous SQLite write transactions on the gateway main thread (reconcileSessionTranscriptIndexInTransaction, src/config/sessions/session-transcript-index.ts). FTS5 deletion retokenizes every removed row, so compacting or repairing a large session blocked the event loop for O(transcript bytes) — the best match for the ~11s synchronized-stall windows observed live on the team host.

The chunked, claim-guarded off-thread rebuild machinery already existed (session-transcript-reconcile.worker.ts + session-transcript-projection-rebuild.ts, header: "request paths may only schedule it and return a bounded retryable response") — the write paths just never adopted it. Consumers are already lag-tolerant: history readers throw the retryable SessionTranscriptProjectionUnavailableError (#129114 contract) which gateway handlers map to retryable responses, FTS search schedules the worker for dirty sessions and reports indexing=true, and transcript mirror-facts fall back to raw rows.

Why This Change Was Made

Transcript replace (compaction), exact rewrite, text repair, and message-cut are now size-gated: transcripts within SYNC_REBUILD_MAX_ROWS = 4_000 / SYNC_REBUILD_MAX_BYTES = 4 MiB keep the original synchronous in-transaction rebuild (measured 60ms per 1k events/1MiB, so ≤250ms — no reader dirty window, semantics identical to today for the vast majority of sessions). Larger transcripts mark the projection dirty in-transaction (markSessionTranscriptIndexDirtyInTransaction, which also invalidates in-flight worker claims) and schedule the worker-owned reconcile after commit through the existing deferOpenClawAgentPostCommitPublication seam — discarded on rollback, with durable needs_rebuild making a missed kick recoverable by startup/search reconciliation. Old FTS rows are preserved on the deferred path (the dirty watermark hides them from search) instead of paying the synchronous O(bytes) FTS mass-delete. Doctor import and canonical repair intentionally stay synchronous (maintenance contexts that must finish with a complete projection; commented in place).

Accepted tradeoff on the deferred (large-transcript) path only: reads during the ~1–2s convergence window get the designed retryable/indexing=true responses, and the first appended turn publishes the cursor-invalidation fallback. Small sessions see no behavior change at all.

User Impact

Compaction and transcript repair of large sessions no longer freeze every session on the gateway. Small-session behavior is unchanged. No schema, worker-protocol, or config changes.

Evidence

A/B stall probe through the real accessor path (replaceTranscriptEvents with compaction-shaped replacement + event-loop lag sampler):

  • 60k events (~66MB), deferred path: max event-loop stall 3197ms → 639ms; immediately after, search returns indexing=true, and after off-thread convergence (~1.6s) FTS search returns the correct post-compaction rows.
  • 2k events, sync path: 95ms replace, search current immediately with indexing=false — no dirty window.

Tests: full src/config/sessions suite green (86 files, 947 tests), plus the gateway suites that exercise replace-then-read seeding: session-transcript-readers(.markers), server.chat-history-cursor, server.chat.gateway-server-chat, chat.directive-tags (312 tests) and ui/src/pages/chat/chat-pane-terminal.test.ts. New regressions: deferred path forced via an over-4MiB event proves search dirty-window exclusion + convergence; an oversized-rewind regression covers message-cut's deferred path; the deferred-FTS regression was confirmed failing on pre-fix code. pnpm check:changed green (import cycles, database-first, storage guards). Codex autoreview clean.

Production LOC +109 net vs main (tests +64): the growth is the size gate + post-commit scheduling seam, justified by the bounded-latency capability (stall budget enforced at the projection owner) while preserving small-session synchronous semantics.

Transcript replace, exact rewrite, text repair, and message-cut no longer
rebuild the full FTS/active-event projection inside their synchronous
write transactions. They mark the projection dirty and schedule the
existing chunked worker-owned reconcile after commit via the post-commit
publication seam; search already hides needs_rebuild sessions and
mirror-facts falls back to raw rows while the projection lags. Doctor
import and canonical repair keep synchronous reconciliation. A/B probe:
compaction replace of a 60k-event transcript blocked the event loop
3197ms before, 764ms after, with the projection converging off-thread.
Replace now defers the projection rebuild, so the ordered-turn setup must
wait for the reconcile worker before committed cursors are provable; the
invalidation fallback for unproven cursors keeps its own coverage.
@clawsweeper

clawsweeper Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: S maintainer Maintainer-authored PR labels Aug 25, 2026
@steipete
steipete marked this pull request as ready for review August 25, 2026 09:06
@clawsweeper clawsweeper Bot added 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: 🐚 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. labels Aug 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 25, 2026, 6:23 AM ET / 10:23 UTC.

ClawSweeper review

What this changes

This PR defers large transcript projection rebuilds to the reconciliation worker while keeping small-session rebuilds synchronous.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open: the large-transcript path still excludes the interactive fork action, leaving synchronous projection indexing inside its gateway write transaction.

Priority: P2
Reviewed head: 1af41676a910d7a09cd88742d8604b97b6e35af0

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has strong targeted intent and coverage, but one reachable oversized session mutation remains outside the deferred path.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from the contributor proof gate; its body nevertheless reports an after-fix real-accessor A/B probe.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the contributor proof gate; its body nevertheless reports an after-fix real-accessor A/B probe.
Evidence reviewed 5 items Fork path remains synchronous: The size gate explicitly excludes fork mode, so an oversized fork skips the dirty-marker path and appends/indexes every copied event during the write transaction.
User-facing caller: The Gateway session-rewind handler invokes forkSessionAtMessage when the requested action is fork, making the missed mode reachable from the interactive session flow.
Existing canonical deferred mechanism: The transcript store already schedules dirty projections after commit, and active-projection readers turn an unavailable projection into a bounded retryable response.
Findings 1 actionable finding [P2] Defer oversized fork projections too
Security None None.

Live Verification

Command: pnpm test src/config/sessions/session-accessor.sqlite-message-cut.test.ts

Result: PASS (completed)

pnpm test src/config/sessions/session-accessor.sqlite-message-cut.test.ts
runner@runnervm76f27:/tmp/clawsweeper-live-proof-129182-A884D2/target$ pnpm test src/config/sessions/session-accessor.sqlite-message-cut.test.ts
$ node --import tsx scripts/test-projects.mts src/config/sessions/session-accessor.sqlite-message-cut.test.ts
pnpm test src/config/sessions/session-accessor.sqlite-message-cut.test.ts
[test] starting test/vitest/vitest.runtime-config.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-129182-A884D2/target

 ✓  runtime-config  src/config/sessions/session-accessor.sqlite-message-cut.test.ts (22 tests) 7355ms
     ✓ fork invalidates the source cache and lists the resulting branch  428ms
     ✓ rejects rewind when the source lifecycle changes in the writer queue  943ms
     ✓ rejects fork when the source lifecycle changes in the writer queue  457ms
     ✓ keeps branch summaries isolated between sessions in the same store  387ms
     ✓ defers an oversized rewind projection until the reconcile worker finishes  1707ms

 Test Files  1 passed (1)
      Tests  22 passed (22)
   Start at  10:23:58
   Duration  13.16s (transform 4.35s, setup 44ms, import 5.27s, tests 7.35s, environment 0ms)
































Assertions:

  • PASS expect_output: Test Files

How this fits together

Session mutations store canonical transcript events and maintain derived search/history projections. Gateway handlers use those projections for session actions and readers either serve current data or return a retryable rebuilding state.

flowchart LR
  A[Gateway session action] --> B[Transcript mutation]
  B --> C{Transcript size gate}
  C -->|small| D[Rebuild projection in transaction]
  C -->|large| E[Mark projection dirty]
  E --> F[Post-commit reconcile worker]
  D --> G[History and search readers]
  F --> G
Loading

Before merge

  • Defer oversized fork projections too (P2) - forkSessionAtMessage reaches this mode through the Gateway action, but the mode !== "fork" guard leaves a large copied prefix to be forward-indexed event by event inside the synchronous write transaction. That preserves the gateway stall this size gate is meant to remove; mark an oversized fork dirty and schedule the existing reconcile worker, with a fork-specific regression.
  • Resolve merge risk (P1) - An oversized interactive fork can still monopolize the gateway write transaction while forward-indexing its copied prefix.
  • Complete next step (P2) - A concrete repair is available, but the protected maintainer item should remain in maintainer review rather than enter an automated repair lane.

Findings

  • [P2] Defer oversized fork projections too — src/config/sessions/session-accessor.sqlite-message-cut.ts:336-341
Agent review details

Security

None.

PR surface

Source +106, Tests +91. Total +197 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 8 148 42 +106
Tests 6 96 5 +91
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 244 47 +197

Review metrics

Metric Value Why it matters
Production versus test LOC production +106 net, tests +91 net The growth is mostly bounded reconciliation wiring and regression coverage; the remaining fork hole means the new production policy is not yet applied consistently.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/commands/doctor-session-transcript-headers.test.ts, migration/backfill/repair: src/commands/doctor-session-transcript-labels.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-archive.worker.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-message-cut.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-message-cut.ts, serialized state: src/config/sessions/session-accessor.sqlite-transcript-state.ts, and 8 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Cover oversized forks before merge (recommended)
    Extend the size gate to forked message cuts and add a regression proving that the gateway returns without synchronously rebuilding the copied projection.

Technical review

Best possible solution:

Apply the existing dirty-marker and post-commit reconciliation flow to oversized forks as well, then prove the temporary rebuilding state and eventual projection convergence.

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

Yes: a fork action whose active-path prefix exceeds the configured byte or row threshold reaches the explicit fork exclusion and still forward-indexes every copied event in its write transaction.

Is this the best way to solve the issue?

No: the current size gate is a plausible fix for rewinds and switches but not the best complete fix because it omits the sibling fork action that uses the same transcript-copy owner.

Full review comments:

  • [P2] Defer oversized fork projections too — src/config/sessions/session-accessor.sqlite-message-cut.ts:336-341
    forkSessionAtMessage reaches this mode through the Gateway action, but the mode !== "fork" guard leaves a large copied prefix to be forward-indexed event by event inside the synchronous write transaction. That preserves the gateway stall this size gate is meant to remove; mark an oversized fork dirty and schedule the existing reconcile worker, with a fork-specific regression.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.92

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 23382e77b5ee.

Labels

Label changes:

  • add merge-risk: 🚨 availability: Merging leaves a reachable large-session interaction performing unbounded synchronous projection work on the gateway thread.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The maintainer-authored PR is exempt from the contributor proof gate; its body nevertheless reports an after-fix real-accessor A/B probe.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review merge-risk labels are merge-risk: 🚨 availability.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: The missed fork path affects large-session gateway responsiveness but has a bounded, mechanical repair.
  • merge-risk: 🚨 availability: Merging leaves a reachable large-session interaction performing unbounded synchronous projection work on the gateway thread.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The maintainer-authored PR is exempt from the contributor proof gate; its body nevertheless reports an after-fix real-accessor A/B probe.

Evidence

What I checked:

Likely related people:

  • steipete: Recent history shows repeated ownership of the message-cut and transcript-session paths, including the current branch. (role: recent area contributor; confidence: high; commits: 1af41676a910, 0acece45912d; files: src/config/sessions/session-accessor.sqlite-message-cut.ts, src/config/sessions/session-transcript-index.ts)
  • shakkernerd: History identifies the stale transcript-projection repair as adjacent ownership for the worker and dirty-state invariant. (role: projection subsystem contributor; confidence: medium; commits: 0fc18f7447e7; files: src/config/sessions/session-transcript-index.ts)

Rank-up moves

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

  • Apply the deferred projection path to oversized forks.
  • Add a fork-specific oversized regression that observes rebuilding before worker convergence.
  • Rerun the focused message-cut and session-search suites on the repaired head.

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 (2 earlier review cycles)
  • reviewed 2026-08-25T09:15:33.972Z sha 28b3829 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-25T09:34:22.994Z sha 28b3829 :: needs maintainer review before merge. :: none

Small transcripts (<=4k events and <=4MiB) keep the original synchronous
in-transaction rebuild (~250ms bound, no reader dirty window); only large
transcripts defer to the reconcile worker where the FTS retokenization
cost would stall the event loop. Probe: 60k-event replace stalls 639ms
(deferred) vs 3197ms before; 2k-event replace is 95ms with search
current immediately.
… reads

Oversized chat.history fixtures take the deferred rebuild path, so the
shared transcript seeding helper awaits projection convergence, and the
archive-worker suite settles the reconcile worker before removing its
temp dir (Windows cannot unlink the still-open agent DB).
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Aug 25, 2026
The reconcile promise previously settled via fire-and-forget terminate,
letting waiters delete the database file while the worker thread still
held its SQLite handle open (Windows unlink fails with EBUSY). Settle
now finishes through worker.terminate()'s exit promise on every path.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 25, 2026
@steipete
steipete merged commit 233ac85 into main Aug 25, 2026
239 checks passed
@steipete
steipete deleted the steipete/deferred-transcript-index-rebuild branch August 25, 2026 10:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 26, 2026
…er (openclaw#129182)

* perf(sessions): defer transcript index rebuilds to the reconcile worker

Transcript replace, exact rewrite, text repair, and message-cut no longer
rebuild the full FTS/active-event projection inside their synchronous
write transactions. They mark the projection dirty and schedule the
existing chunked worker-owned reconcile after commit via the post-commit
publication seam; search already hides needs_rebuild sessions and
mirror-facts falls back to raw rows while the projection lags. Doctor
import and canonical repair keep synchronous reconciliation. A/B probe:
compaction replace of a 60k-event transcript blocked the event loop
3197ms before, 764ms after, with the projection converging off-thread.

* test(sessions): await projection convergence before proving turn cursors

Replace now defers the projection rebuild, so the ordered-turn setup must
wait for the reconcile worker before committed cursors are provable; the
invalidation fallback for unproven cursors keeps its own coverage.

* perf(sessions): size-gate synchronous transcript index rebuilds

Small transcripts (<=4k events and <=4MiB) keep the original synchronous
in-transaction rebuild (~250ms bound, no reader dirty window); only large
transcripts defer to the reconcile worker where the FTS retokenization
cost would stall the event loop. Probe: 60k-event replace stalls 639ms
(deferred) vs 3197ms before; 2k-event replace is 95ms with search
current immediately.

* test(sessions): settle deferred reconcile before teardown and history reads

Oversized chat.history fixtures take the deferred rebuild path, so the
shared transcript seeding helper awaits projection convergence, and the
archive-worker suite settles the reconcile worker before removing its
temp dir (Windows cannot unlink the still-open agent DB).

* fix(test): satisfy agent database options in archive-worker teardown

* fix(sessions): resolve reconcile only after the worker thread exits

The reconcile promise previously settled via fire-and-forget terminate,
letting waiters delete the database file while the worker thread still
held its SQLite handle open (Windows unlink fails with EBUSY). Settle
now finishes through worker.terminate()'s exit promise on every path.
VACInc added a commit that referenced this pull request Aug 27, 2026
… the session (#130930)

* fix(agents): wait for deferred transcript projection before reopening 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.

* 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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M 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