Skip to content

perf(sessions): avoid rescanning branches after message appends - #159309

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-sessions-branches-list-slow-20260919
Sep 27, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-sessions-branches-list-slow-20260919

Conversation

@steipete

@steipete steipete commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Opening or refreshing the session branch menu after a new message rescans the entire transcript, even when the new message only extends the active branch.

User Impact

Branch refreshes after ordinary message appends are much faster for long conversations. Branch ordering, counts, headlines, timestamps, and navigation behavior remain unchanged. First uncached reads and structural changes still require the complete scan; this does not meet a sub-20 ms cold-read target.

Why This Change Was Made

Extend the existing compact summary cache in the transcript read worker. The initial scan certifies identity coverage, unique IDs, and backward ancestry. A later read in the same physical database and rewrite generation reads only the indexed sequence suffix and extends the active count/headline when every new row is an identity-owned message continuing that branch. Rewrites, leaf/reset controls, side branches, and irregular imported graphs use the existing scanner. No new cache owner, configuration, schema, or retained transcript graph; net production growth is 80 lines.

Evidence

A synthetic stored session with 50,000 messages and five branches, exercised through listSessionBranches on blacksmith-testbox lease tbx_01m3g3zwptw7p6243mm4jcxs3t (run):

Call Before After
Refresh after one append, five samples 142.50–212.32 ms; mean 182.42 ms 2.04–6.21 ms; mean 3.15 ms
Unchanged cached call, five samples 0.20–0.58 ms 0.09–0.43 ms
First uncached call 449.43 ms 467.45 ms
Main-thread synchronous work before the append call yielded 0.23–0.74 ms 0.13–0.45 ms

The append refresh is approximately 58× faster (98.3% lower mean latency). Persisted cache misses already ran in the transcript worker before this change. The synchronous column measures entry-to-first-yield, not all main-thread work after worker completion. The synthetic fixture is not a live deployment measurement.

Focused validation used node scripts/run-vitest.mjs <files> --maxWorkers=1:

  • session-accessor.sqlite-branches.test.ts, session-accessor.sqlite-message-cut.test.ts, sessions-rewind.test.ts, and sessions-rewind.storage.test.ts: 97 passed, lease tbx_01m3g54pjfqx4p29g0qbvr8nzx (run). This includes the registered Gateway methods and the deterministic bounded-row assertion.
  • session-accessor.sqlite-branch-summaries.test.ts: 11 passed, lease tbx_01m3g5y0r96bh58gbs0prp3yf7 (run). Covers selected ancestors with inactive descendants, headline inheritance, forward references, duplicate IDs, cycles, and snapshot consistency.
  • Negative control on that same lease: the new bounded-row assertion fails against the original reader with 8 navigation rows read after one append, versus the allowed bound of 2. The candidate passes. Baseline copies were removed after the probe.
  • Single-worker test costs: branch suite 22.22 s test time (19 tests; earlier standalone candidate run 30.61 s wall), summary suite 5.41 s test time / 27.76 s wall including cold worker compilation (11 tests). The row bound extends an existing test; the two added compatibility cases took 0.43 s and 1.14 s. The 50k-event benchmark is task-only and does not add recurring CI cost.
  • Final independent Codex autoreview: no actionable P0–P2 findings. git diff --check passed.

Changed-file gate: passed on tbx_01m3g5y0r96bh58gbs0prp3yf7 with node scripts/check-changed.mjs --base 5fd7c3d95e03c1acbbfe180991309fe99d6a9fa3 -- <five changed paths> (22m17s command time). Production typechecking, all 25 test graphs, lint, formatting, dead-export checks, and repository guards passed. All task-owned leases are stopped.

Validation recovery: native Testbox sync hit its two-minute checksum deadline on reused leases; those leases were retired and replaced, never used concurrently. Fresh snapshots needed pnpm install --frozen-lockfile. Two new fixture cases initially attempted an empty bulk insert and then used the raw event writer for messages; both fixture errors were corrected before the passing run. The initial default changed-file check compared against a moving Testbox origin/main and encountered unrelated Slack/UI line limits; the final check pins the lane base 5fd7c3d95e03c1acbbfe180991309fe99d6a9fa3 and the five changed paths.

No live Gateway was modified or restarted. Cold/structural reads and process-local incognito appends retain full-scan behavior.

CI failure investigation

CI run 36286345135 on head 3df6a1dde9ef55f320a6fff435989aea25e02121 finished cancelled after checks-node-changed-compact-small-19 failed; 131 other jobs succeeded. The failure starts in server.private-completion.test.ts, case “settles private execution without confusing cancellation and failure: provider failed”: a 120-second test timeout followed by a 180-second queue-drain hook timeout. Later cases report the same session's competing work, and the five-minute no-output watchdog eventually terminates the shard. The failing job ran for 2,749 seconds. This is an unresolved failure, not a claimed infrastructure transient.

The failed-only path persists a lifecycle error and appends its transcript report through foreground/worker write admission. Source review found no forgotten fixture release and did not establish a safe product repair. The later cleanup errors are consistent with that first producer remaining unsettled. No change to this path is included in this PR.

Bounded reproduction on blacksmith-testbox lease tbx_01m3gcmv85t7k2tt5n6b27c80m:

  • Original 26-file group and ordering, using the captured CI group JSON and scripts/ci-run-node-test-shard.mts on the PR head: 92 passed, 125.43 seconds wrapper wall time.
  • Exact failing merge commit f6a0680aab74a0ca2acaa52404895c97f083756b, isolated server.private-completion.test.ts: 21 passed, 56.98 seconds wrapper wall time.
  • That exact merge commit with the original 26-file group and ordering: 92 passed, 143.17 seconds wrapper wall time.

These probes used bail-after-first-failure without changing test/hook budgets or assertions. They do not prove the hang fixed. Exact-merge scratch worktrees and the lease were cleaned up. CI was not rerun merely to obtain green, and the branch was not refreshed to hide the failure. CI remains red; the next useful evidence is a reproducing private-completion write/cleanup wait trace. Per-file CI timings for this PR's changed tests were not captured; their measured Testbox costs are above.

@clawsweeper

clawsweeper Bot commented Sep 27, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M labels Sep 27, 2026
@steipete
steipete marked this pull request as ready for review September 27, 2026 01:42
@steipete
steipete enabled auto-merge (squash) September 27, 2026 01:44
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 11:56 PM ET / September 27, 2026, 03:56 UTC (Revision 2).

ClawSweeper review

What this changes

The PR extends cached session branch counts and headlines from newly appended messages, with fallback tests and database-worker documentation.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still rescans the transcript after an append, and the focused patch has credible performance evidence with no confirmed introduced defect.

Priority: P2
Reviewed head: 031761512e2bb2026ac7fd2a099fa87257d5f725

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) The focused cache change has measured production-path performance evidence, a baseline negative control, and relevant compatibility coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.
Evidence reviewed 7 items Current main still rescans: On current main, a cache miss reads all transcript navigation rows in sequence before computing branch summaries.
Introduced append path: The new path reads only rows after the cached sequence and extends the active summary only for identity-owned messages continuing that branch; other rows fall back to scanning.
Cache and snapshot boundary: The read worker checks database identity, rewrite generation, session lifecycle, and the transcript watermark within its snapshot before caching results.
Findings None None.
Security None None.

How this fits together

The Gateway's branch-list API reads an agent's SQLite transcript through a read worker. It returns compact branch summaries for the chat branch menu.

flowchart LR
  A[Saved session messages] --> B[Branch list request]
  B --> C[Transcript read worker]
  C --> D{Valid cache and linear append?}
  D -->|Yes| E[Read new rows]
  D -->|No| F[Scan transcript]
  E --> G[Branch menu summaries]
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +80, Tests +90, Docs +9. Total +179 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 107 27 +80
Tests 2 90 0 +90
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 206 27 +179

Review metrics

Metric Value Why it matters
Append-refresh latency 182.42 ms to 3.15 ms mean on 50,000 messages The PR's synthetic Testbox benchmark exercises the intended branch-list hot path.
Code growth production +80 lines, tests +90 lines The production growth is tied to the bounded-read guard and full-scan fallback.

Technical review

Best possible solution:

Keep one worker-owned branch-summary cache that updates from verified append suffixes and uses the complete scanner for rewrites or irregular history.

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

Yes. Current main visibly scans all navigation rows on an append cache miss, and the PR records a repeatable 50,000-message branch-list benchmark; I did not rerun it in this read-only checkout.

Is this the best way to solve the issue?

Yes. Extending the existing worker cache with a verified append suffix keeps the optimization at its current owner and preserves full scans for structural changes.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a bounded performance improvement for long session branch lists, with limited user impact outside that path.
  • add proof: sufficient: Contributor real behavior proof is sufficient. A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.

Label justifications:

  • P2: This is a bounded performance improvement for long session branch lists, with limited user impact outside that path.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. A recorded Testbox run exercises the production listSessionBranches path against a real SQLite database with 50,000 synthetic messages and reports faster after-fix append refreshes; focused tests cover fallback behavior. The run logs were inaccessible to this reviewer, so the numeric results are attributed to the captured PR body. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (1 earlier review cycle)
  • reviewed 2026-09-27T01:47:01.337Z sha 3df6a1d :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 27, 2026
@steipete
steipete merged commit d492fca into main Sep 27, 2026
209 checks passed
@steipete
steipete deleted the steipete/perf-micro-sessions-branches-list-slow-20260919 branch September 27, 2026 04:01
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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