Skip to content

fix(sessions): branches.list stalls the event loop for ~12s on long-lived sessions - #123541

Merged
obviyus merged 2 commits into
openclaw:mainfrom
njuboy11:fix/branches-list-quadratic-summarize
Aug 30, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
njuboy11:fix/branches-list-quadratic-summarize

Conversation

@njuboy11

@njuboy11 njuboy11 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #123540

What Problem This Solves

Long-lived sessions can contain thousands of transcript events and more than one thousand branch tips. A cold sessions.branches.list request walked the shared transcript prefix once for every tip. This blocked the Gateway event loop for seconds and delayed unrelated work.

Why This Change Was Made

The SQLite session accessor owns branch-summary projection. It now memoizes the count and latest headline for each visited ancestor. Each shared prefix is summarized once, while the existing branch selector, active-first ordering, timestamps, missing-parent suffixes, and cycle behavior stay unchanged.

This repair was ported onto current main rather than rebasing the stale patch. It keeps newer session lifecycle, model-lock, incognito, commit-guard, and deferred-index behavior added since the original branch base.

User Impact

  • Branch listing no longer freezes the Gateway on a large shared session graph.
  • Branch order, headlines, message counts, timestamps, and active flags do not change.
  • No config, schema, storage, protocol, or migration surface changes.

Evidence

The same production sessions.branches.list handler read a disposable SQLite session with 13,917 events and 1,362 tips on current main 0a6c013be5f50981b12d021b387b4fd1ea7e491e and rebased repaired head 25776eec814d88160251eff06658c2a444624281.

Result Current main Repaired head
Cold RPC 4,824 ms 48 ms
Zero-delay timer drift 4,824 ms 49 ms
Branch count 1,362 1,362
Ordered result SHA-256 32c1950f…66aded 32c1950f…66aded

The 100x reduction removes the event-loop stall. The identical complete-result hash proves output equivalence. A warm-cache control remained 1 ms on both revisions.

Testing

  • Regression negative control on main: failed at 1,322 ms against the 1,000 ms bound.
  • Repaired focused suites: 30 tests passed; the rebased large-graph case completed in 476 ms.
  • Exact SQLite import negative control: without canonical tip resolution, duplicate IDs returned the first physical row's timestamp; the repaired head returns the canonical final row for both preserved tips.
  • pnpm check:changed: passed, including core and test type checks, type-aware lint, formatting, import cycles, schema guards, and repository ratchets.

Change Shape

  • Owner: SQLite session branch-summary projection.
  • Removed path: repeated full root-path summary work for every branch tip.
  • Production delta: +48/-21, net +27 lines. The cache is local to one cold summary build and is the minimum state needed to share ancestor results while preserving missing-parent, cycle, and exact-import semantics.
  • Tests: net +92 lines for the realistic 13,917-event regression, retained-suffix contract, and exact-import duplicate-ID compatibility.

@clawsweeper

clawsweeper Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. labels Aug 14, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 11:47 AM ET / 15:47 UTC.

ClawSweeper review

What this changes

The PR memoizes shared transcript ancestry when producing SQLite session branch summaries and adds large-graph and duplicate-ID regression coverage.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

No blocking correctness finding on the reviewed head: the prior duplicate-ID issue is addressed by canonicalizing each tip before traversal. Keep this PR open for normal exact-head validation; this checkout could not materialize the fetched current-main object for a final source comparison.

Priority: P1
Reviewed head: 25776eec814d88160251eff06658c2a444624281

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch addresses the prior canonical-tip finding and supplies meaningful production-path benchmark evidence plus focused regressions.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied PR body reports an after-fix run through the production branch-list handler against a disposable 13,917-event SQLite session, with lower cold-RPC and timer-drift times and an identical ordered-result hash; the local source test exercises the same accessor path, though it was not run in this read-only review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied PR body reports an after-fix run through the production branch-list handler against a disposable 13,917-event SQLite session, with lower cold-RPC and timer-drift times and an identical ordered-result hash; the local source test exercises the same accessor path, though it was not run in this read-only review.
Evidence reviewed 7 items Introduced owner-boundary repair: The branch-list accessor now supplies the canonical node from the transcript tree's ID map to the memoized path summarizer, so shared ancestors are accumulated once without changing the public summary shape.
Existing selector contract: The shared selector resolves nodes through the canonical ID map, retains reachable suffixes after missing ancestors, and returns an empty path for cycles; the new traversal has the same stopping behavior.
Prior finding covered: The imported-row regression now preserves two physical duplicate rows while asserting that both branch results use the final canonical row's headline and timestamp.
Findings None None.
Security None None.

How this fits together

SQLite transcript events are converted into branch summaries for the Gateway branch-list endpoint and Control UI branch menu. This projection must retain canonical tree semantics while avoiding synchronous work that delays other Gateway activity.

flowchart LR
  A[SQLite transcript events] --> B[Transcript tree scan]
  B --> C[Branch tip selection]
  C --> D[Shared ancestry summaries]
  D --> E[Branch-list response]
  E --> F[Gateway and Control UI]
Loading

Before merge

  • Resolve merge risk (P1) - The local partial clone could not load fetched current main, so the final merge result should be refreshed against current main after exact-head checks complete.
  • Complete next step (P2) - The prior mechanical finding is resolved; remaining work is ordinary exact-head CI and merge-result validation, not a separate repair dispatch.
Agent review details

Security

None.

PR surface

Source +27, Tests +92. Total +119 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 48 21 +27
Tests 2 94 2 +92
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 142 23 +119

Review metrics

Metric Value Why it matters
Production versus test delta production +27, tests +92 The local memo map adds bounded per-build state to remove repeated ancestry walks; the added tests cover realistic graph size and imported duplicate-ID behavior.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #123540
Summary: This PR is the candidate repair for the documented large-session branch-list event-loop stall.

Members:

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

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Land the local memoized projection only after the current-main merge result retains the tested canonical, missing-parent, and cycle semantics.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Land the local memoized projection only after the current-main merge result retains the tested canonical, missing-parent, and cycle semantics.

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

Yes. The pre-change implementation called the full path selector once per tip, and the supplied real-path benchmark plus large SQLite regression describe a high-confidence large-session reproduction; no target code was executed in this read-only review.

Is this the best way to solve the issue?

Yes. Memoizing at the SQLite branch-summary owner removes the repeated shared-prefix walks while retaining the canonical tree selector’s semantics; moving this into storage or a new global cache would broaden the state boundary unnecessarily.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied PR body reports an after-fix run through the production branch-list handler against a disposable 13,917-event SQLite session, with lower cold-RPC and timer-drift times and an identical ordered-result hash; the local source test exercises the same accessor path, though it was not run in this read-only review.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove merge-risk: 🚨 session-state: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Large branch-list requests can synchronously delay Gateway work for seconds on long-lived sessions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied PR body reports an after-fix run through the production branch-list handler against a disposable 13,917-event SQLite session, with lower cold-RPC and timer-drift times and an identical ordered-result hash; the local source test exercises the same accessor path, though it was not run in this read-only review.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied PR body reports an after-fix run through the production branch-list handler against a disposable 13,917-event SQLite session, with lower cold-RPC and timer-drift times and an identical ordered-result hash; the local source test exercises the same accessor path, though it was not run in this read-only review.

Evidence

What I checked:

Likely related people:

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

Rank-up moves

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

  • After the fresh exact-head checks finish, refresh the verified merge result against current main before landing.

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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-14T16:59:41.889Z sha 96b76a08c52d4f588bf8259ba8ea559231e152f8 :: needs changes before merge. :: [P2] Exercise the retained missing-parent suffix
  • reviewed 2026-08-14T17:56:56.286Z sha 8bc8f79e0a9b37901e8a7e8331c432303cf30904 :: needs changes before merge. :: [P2] Exercise a truly missing-parent suffix
  • reviewed 2026-08-15T01:23:05.526Z sha 91bb253442fbc2434af4e87282d6332173b94b18 :: needs changes before merge. :: [P2] Exercise a truly missing-parent suffix
  • reviewed 2026-08-15T14:44:32.803Z sha dabb8a16a4d14673333e86790762b705f8128050 :: needs maintainer review before merge. :: none
  • reviewed August 20, 2026, 1:49 AM ET / 05:49 UTC sha unknown :: needs maintainer review before merge. :: none
  • reviewed 2026-08-26T07:41:44.799Z sha dabb8a16a4d14673333e86790762b705f8128050 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T14:40:46.688Z sha 18f2625a07c5cc447dc5ef59b4307877df8d7876 :: needs changes before merge. :: [P2] Preserve canonical duplicate-ID timestamps
  • reviewed 2026-08-30T15:09:52.430Z sha 18f2625a07c5cc447dc5ef59b4307877df8d7876 :: needs changes before merge. :: [P2] Canonicalize duplicate-ID tips before summarizing

@njuboy11
njuboy11 force-pushed the fix/branches-list-quadratic-summarize branch from b1aa620 to 084b3a0 Compare August 14, 2026 07:56
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 14, 2026
@njuboy11

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review! The P1 finding is addressed in 96b76a08.

Fix

summarizeSessionBranches now seeds the traversal stack from both top-level roots and retained suffixes whose parent is absent from tree.byId:

if (node.parentId === null || !tree.byId.has(node.parentId)) {
  stack.push({ node, count: 0, headline: undefined });
}
  • selectSessionTranscriptTreePathNodes deliberately keeps a reachable suffix after a missing ancestor, and branch summaries now preserve that same behavior instead of degrading to an empty headline with zero count.
  • Cycles stay unseeded: every node in a cycle has its parent present in byId, so neither endpoint satisfies the seed condition.

Regression test

Added retains branch summaries for a reachable suffix after a missing ancestor through listSessionBranches: a message suffix hanging off an absent ancestor (orphan-user/orphan-assistant under missing-ancestor) is now listed with its own headline ("orphan answer") and the full root-to-suffix message count (4). Verified locally: 22/22 tests pass in session-accessor.sqlite-message-cut.test.ts, all pre-existing tests untouched.

CI status

All checks pass on the updated head except check-lint, which fails on src/auto-reply/reply/commands-compact.test.ts — a file outside this PR's diff, introduced by #123640 merged into main today (5 lint errors: curly×3, max-lines, no-map-spread). Every PR based on current main hits the same failure; happy to fix that file separately if maintainers prefer.

Requesting a re-review of the P1 item.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Aug 15, 2026
@njuboy11

Copy link
Copy Markdown
Contributor Author

P2 addressed (dabb8a16): the orphan suffix is now appended before any usable leaf exists — message rows carry their own leafId, so once a later row is scanned the scanner rebases an absent parent onto the current leaf and the suffix stops being orphaned. Keeping missing-ancestor unresolved preserves the exact shape branch summaries must retain, and the test now asserts the suffix's own two-message result (previously 4, counting the main path it was rebased onto).

Verified:

  • New test fails on the pre-seeding implementation (count 0, empty headline) and passes with the seeded traversal
  • Full file: 22/22 tests green
  • oxlint / oxfmt / git diff --check clean

Requesting a re-review of the P2 item.

@njuboy11

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 15, 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. clawsweeper-recovery-stuck 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. clawsweeper-recovery-stuck labels Aug 15, 2026
@obviyus
obviyus force-pushed the fix/branches-list-quadratic-summarize branch from dabb8a1 to 18f2625 Compare August 30, 2026 14:33
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed 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 30, 2026
@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Aug 30, 2026
@obviyus
obviyus force-pushed the fix/branches-list-quadratic-summarize branch from 18f2625 to 25776ee Compare August 30, 2026 15:40
@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. 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 30, 2026
@obviyus
obviyus merged commit 279a12c into openclaw:main Aug 30, 2026
269 checks passed
@obviyus

obviyus commented Aug 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks @njuboy11!

Proof: The production sessions.branches.list handler processed a disposable 13,917-event SQLite session with 1,362 branch tips. Cold latency and zero-delay timer drift fell from 4,824 ms on main to 48–49 ms on the merged head. The complete ordered branch-result SHA-256 stayed identical.

  • Bug: A cold branch list walked the same shared transcript prefix once per branch tip, blocking the Gateway event loop for seconds.
  • Fix: The SQLite session accessor now reuses canonical ancestor summaries while preserving ordering, counts, headlines, timestamps, missing-parent suffixes, cycles, and exact-import duplicate IDs.

Example

Before After
4,824 ms cold RPC and 4,824 ms timer drift 48 ms cold RPC and 49 ms timer drift

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
Memoize ancestor branch summaries during each cold SQLite transcript scan so long-lived sessions do not repeat the same root-path work for every branch tip.

Preserve active-first ordering, missing-parent and cycle behavior, and canonical duplicate-ID results from exact SQLite imports.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

sessions.branches.list stalls the event loop for ~12s on long-lived sessions (thousands of transcript branches)

2 participants