Skip to content

fix(sessions): agents with small transcript rebuild backlogs wait behind larger agents at startup - #165207

Merged
steipete merged 2 commits into
mainfrom
steipete/zen-jemison-73560d
Oct 5, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/zen-jemison-73560d

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Related: #165107

What Problem This Solves

Fixes: after a Gateway restart, an agent with only a few pending transcript-projection rebuilds stays unavailable until every earlier agent's whole rebuild backlog has finished, because all agents share one reconcile worker that runs each agent's backlog to completion in arrival order.

User Impact

User impact: agents with small rebuild backlogs become available after at most one in-flight session rebuild instead of waiting behind larger agents. Large agents still rebuild one at a time, never interleaved, so the first large agent is not delayed by the second. Total rebuild work and worker count are unchanged. No config, schema, or stored-data changes.

Why This Change Was Made

#165107 described the two large stores' rebuilds as interleaving inside the single-worker pool. Measured on main, they do not. Each reconcile pass is one whole-agent worker task, and the pool runs those tasks strictly FIFO. With backlogs large-a=4, large-b=4, small=1 submitted in that order, plan order is a:s0..s3, b:s0..s3, small:s0. So the cost #165107 observed is enqueue order. The real defect is head-of-line blocking: a one-session agent waits for every earlier large backlog.

The reconcile pool now owns admission for planning tasks:

  • Waiting passes are ordered by pending session backlog. The count comes from the existing preflight, which now returns a count instead of a boolean. Ties go to the older operation.
  • At a completed session boundary, a running planner yields only to a strictly smaller waiting backlog. It reserves its own place in the queue before releasing the worker, so an equal or larger agent that arrived later cannot overtake it. Its next pass refreshes the backlog in preflight.
  • Startup migration still awaits each agent's complete rebuild, because the pass loop repeats until no yield.

MAX_WORKERS stays 1. Raising it would not help here: on a CPU-bound host, two concurrent large rebuilds just delay both, and each extra worker costs up to 512 MB of heap on large fleets. Lease-release tasks bypass admission, so cleanup can never wait behind planners. No deadlines were added.

The lease-settlement tail moved unchanged from session-transcript-reconcile.ts into the pool module (which already owns lease release) to stay under the file-size lint limit.

Known tradeoff: shortest-backlog-first lets a continuous stream of smaller backlogs postpone a large store. Those small backlogs are real pending rebuilds, and the large store resumes as soon as they drain. No starvation deadline was added, by design.

Evidence

Regression test src/config/sessions/session-transcript-reconcile.backlog-order.test.ts (real reconcile worker, observed ports). It holds large-a's first plan-finish, queues large-b(3) and small(1), then asserts plan order a:s0, small:s0, a:s1, a:s2, a:s3, b:s0, b:s1, b:s2 and completion order small, large-a, large-b. It also checks that every store ends fully indexed and the pool ends idle. A second case checks that a revoked waiter leaves the queue without leaking the permit. On the unmodified code the first case fails as expected:

Expected: a:s0, small:s0, a:s1, a:s2, a:s3, b:s0, b:s1, b:s2
Received: a:s0, a:s1, a:s2, a:s3, b:s0, b:s1, b:s2, small:s0

pnpm test src/config/sessions/session-transcript-reconcile.backlog-order.test.ts --maxWorkers=1: 2 passed, 14.0 s in tests (160 s wall, including Vitest startup on a loaded Mac).

Neighbours: 19 files / 152 tests passed: reconcile pool, session-transcript-reconcile.*, transcript index, and startup session migration suites. Core and test typechecks, scoped oxlint, oxfmt, and git diff --check are clean. Codex autoreview (P2 threshold): scoped-clean.

Before/after measurement (Crabbox direct AWS c7a.4xlarge, lease cbx_b73c0ff6081c, run run_76e6a3496a913c645e83b0898a02d664). Both arms ran on the same box from a fresh checkout of this PR. The "before" arm swapped in the five base production files from a58fe52a98b5. The benchmark itself is proof-only and not committed. It used isolated temp state and the real reconcile worker, pinned to 2 cores with taskset -c 0,1. Each round has two stores with 48 sessions × 120 messages and one store with 2 sessions, all marked needs_rebuild. Both large reconciles start at t=0; the small one starts at t=250 ms. Values are completion times in ms from t=0 over 3 rounds. Testbox was queued with no runner for 15+ minutes, so I fell back to AWS.

Agent before (base) after (this PR) change
small (2 sessions) 2661 / 2658 / 2611 (avg 2643) 1504 / 1542 / 1445 (avg 1497) −1146 ms (−43%)
large-a (48) 2484 / 2469 / 2430 (avg 2461) 2745 / 2885 / 2793 (avg 2808) +347 ms
large-b (48), also total 4025 / 3917 / 3923 (avg 3955) 4015 / 4167 / 4068 (avg 4083) +128 ms (+3.2%)

On base, the small agent always waited for large-a's entire backlog. It slipped ahead of large-b only because large-b's preflight finished later. With this PR it runs after at most one in-flight large-a session; most of its remaining 1.5 s is its own preflight competing for the two pinned cores. The large stores still complete one after the other, never interleaved. The +128 ms total is the cost of one yield and resumed pass (re-open, lease, re-list) plus the count preflight. Each yield costs a similar fixed amount. On base, the small agent's wait grows with the large backlog; with this PR it is bounded by a single session rebuild. The synthetic stores here are small (about 2.4 s each), so production-sized stores like the 1.6 GB ones in #165107 should show a proportionally larger gain for small agents and the same fixed per-yield overhead.

The transcript reconcile pool runs one whole-agent task per pass on a single
worker in FIFO order, so an agent with one pending projection rebuild waited
for every earlier agent's full backlog before it could serve history.

Admission is now owned by the reconcile pool: planning tasks are ordered by
pending session backlog (operation order breaks ties), and a running planner
yields at a completed session boundary only to a strictly smaller waiting
backlog, reserving its own place before releasing the worker. Large stores
never interleave, total work is unchanged, MAX_WORKERS stays 1, and lease
release tasks bypass admission. Startup still awaits each agent's complete
rebuild.
@clawsweeper

clawsweeper Bot commented Oct 5, 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: L labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 4, 2026, 9:58 PM ET / October 5, 2026, 01:58 UTC (Revision 3).

ClawSweeper review

What this changes

Prioritize smaller transcript-index rebuild backlogs and let larger rebuilds yield between sessions while preserving startup completion and lease cleanup.

Merge readiness

⛔ Needs changes before merge - 2 items remain

This remains useful: current main and the latest release lack backlog-aware admission. The runtime measurements support the fix, but the prior P3 test finding remains unresolved.

Priority: P1
Reviewed head: a7d06801868c7b9dbc27e3531d58f2858d028f70

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, scoped implementation with convincing runtime measurements and one remaining deterministic-test repair.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured same-host before/after benchmark exercises the real reconcile worker against isolated pending SQLite rebuilds under CPU contention and observes faster small-store completion with both large stores completing. The latest commit changes only backlog counting, while the supplied regression and neighboring validation are supplemental. No stored-data contract changes were introduced.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured same-host before/after benchmark exercises the real reconcile worker against isolated pending SQLite rebuilds under CPU contention and observes faster small-store completion with both large stores completing. The latest commit changes only backlog counting, while the supplied regression and neighboring validation are supplemental. No stored-data contract changes were introduced.
Evidence reviewed 9 items Pinned patch ownership: Reviewed the merge-base-to-head production and test changes. The checkout is the exact original PR head; the supplied stale test merge was not used to infer removals or regressions.
Current-main necessity: Current main still dispatches whole-agent planning tasks directly into the single-worker pool, without backlog admission or session-boundary reservations.
Latest-release comparison: The v2026.9.8 pool likewise lacks the introduced backlog admission mechanism; this requested improvement is not already shipped there.
Findings 1 actionable finding [P3] Replace real snapshot polling with explicit admission gates
Security None None.

How this fits together

Transcript reconciliation rebuilds searchable history from each agent’s stored conversations. Gateway startup waits for these rebuilds before making the affected agents available.

flowchart TD
 A[Agent conversation stores] --> B[Count pending rebuilds]
 B --> C[Backlog admission queue]
 C --> D[Single rebuild worker]
 D --> E[Publish completed session index]
 E --> F{Smaller backlog waiting?}
 F -->|Yes| C
 F -->|No| D
 E --> G[Completed agent startup]
Loading

Before merge

  • Replace real snapshot polling with explicit admission gates (P3) - Both new cases wait for competing operations with vi.waitFor and a fixed ten-second deadline, here and at line 245. On a loaded host, preflight can exceed that window before the operations enter admission, failing otherwise-correct scheduling tests. This prior finding remains unchanged. Observe runSessionTranscriptReconcileOperation/startTask and resolve a deferred gate when both waiters enter, following the modified lifecycle test.
  • Complete next step (P2) - Replace both real-time admission polling waits with deferred admission gates and rerun the focused backlog-order regression.

Findings

  • [P3] Replace real snapshot polling with explicit admission gates — src/config/sessions/session-transcript-reconcile.backlog-order.test.ts:146-154
Agent review details

Security

None.

PR surface

Source +212, Tests +286, Docs +7. Total +505 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 334 122 +212
Tests 3 312 26 +286
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 653 148 +505

Review metrics

Metric Value Why it matters
Production versus test growth production +212 net lines; tests +286 net lines Production growth implements pool-owned admission and yielding; the body explains the lease-settlement move as file-size management.
Measured small-agent recovery 43% faster; total rebuild completion +3.2% Three same-host rounds demonstrate the responsiveness benefit and its measured scheduling overhead.

Technical review

Best possible solution:

Keep one pool owner for backlog scheduling, with complete rebuild settlement and deterministic admission-boundary regression coverage.

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

Yes: current main’s single-worker whole-agent queue establishes the blocking mechanism, and the supplied before/after run exercises competing real rebuild backlogs. This review did not execute a reproduction.

Is this the best way to solve the issue?

Yes: scheduling belongs in the existing pool, and yielding at completed-session boundaries preserves bounded publication and cleanup. The regression test still needs deterministic admission gates.

Full review comments:

  • [P3] Replace real snapshot polling with explicit admission gates — src/config/sessions/session-transcript-reconcile.backlog-order.test.ts:146-154
    Both new cases wait for competing operations with vi.waitFor and a fixed ten-second deadline, here and at line 245. On a loaded host, preflight can exceed that window before the operations enter admission, failing otherwise-correct scheduling tests. This prior finding remains unchanged. Observe runSessionTranscriptReconcileOperation/startTask and resolve a deferred gate when both waiters enter, following the modified lifecycle test.
    Confidence: 0.99

Overall correctness: patch is correct
Overall confidence: 0.91

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Startup rebuild queues can keep smaller agents unavailable behind large stores, affecting history and agent workflows.
  • merge-risk: 🚨 availability: Shortest-backlog scheduling can postpone larger agents under continuous smaller arrivals; the supplied maintainer context explicitly accepts this tradeoff.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured same-host before/after benchmark exercises the real reconcile worker against isolated pending SQLite rebuilds under CPU contention and observes faster small-store completion with both large stores completing. The latest commit changes only backlog counting, while the supplied regression and neighboring validation are supplemental. No stored-data contract changes were introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured same-host before/after benchmark exercises the real reconcile worker against isolated pending SQLite rebuilds under CPU contention and observes faster small-store completion with both large stores completing. The latest commit changes only backlog counting, while the supplied regression and neighboring validation are supplemental. No stored-data contract changes were introduced.

Evidence

Acceptance criteria:

  • [P1] pnpm test src/config/sessions/session-transcript-reconcile.backlog-order.test.ts --maxWorkers=1.
  • [P1] pnpm test src/config/sessions/session-transcript-reconcile.lifecycle.test.ts --maxWorkers=1.
  • [P1] git diff --check.

What I checked:

  • Pinned patch ownership: Reviewed the merge-base-to-head production and test changes. The checkout is the exact original PR head; the supplied stale test merge was not used to infer removals or regressions. (a7d06801868c)
  • Current-main necessity: Current main still dispatches whole-agent planning tasks directly into the single-worker pool, without backlog admission or session-boundary reservations. (src/config/sessions/session-transcript-reconcile-pool.ts, ff1c79a1f101)
  • Latest-release comparison: The v2026.9.8 pool likewise lacks the introduced backlog admission mechanism; this requested improvement is not already shipped there. (src/config/sessions/session-transcript-reconcile-pool.ts, fc23bc864e45)
  • Prior finding remains unchanged: Both admission waits still use vi.waitFor with ten-second real-time deadlines, at lines 146 and 245. The targeted earlier-head comparison is empty; GitHub’s earlier blob SHA and the current file hash both equal 84bc8a3d70e5961e03e867681e1ac1da016d6b9d. The previous finding and rank-up move therefore remain applicable. (src/config/sessions/session-transcript-reconcile.backlog-order.test.ts:146, a7d06801868c)
  • Deterministic testing contract: The testing cost budget requires owned completion signals instead of new real timers or polling. The modified lifecycle test already observes startTask and resolves an explicit admission gate, providing a concrete repair pattern. Public docs: docs/help/testing/writing-tests.md. (docs/help/testing/writing-tests.md, a7d06801868c)
  • Real production-worker measurement: The captured PR body reports a same-host AWS before/after run through the real reconcile worker with isolated SQLite stores and two pinned cores. Across three rounds, the two-session store averaged 2643 ms before and 1497 ms after; both large stores completed, with total completion averaging 3955 ms before and 4083 ms after. This exercises the changed scheduling boundary rather than an unrelated startup smoke. Tests and checks were reported by the author; none were executed during this read-only review. (8cdf84659aa7)

Likely related people:

  • steipete: 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.

  • Replace both real-timer admission waits with deferred gates and rerun the focused regression file.

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-10-05T00:17:08.358Z sha 8cdf846 :: needs changes before merge. :: [P3] Replace real snapshot polling with explicit admission gates
  • reviewed 2026-10-05T00:41:06.253Z sha 8cdf846 :: needs changes before merge. :: [P3] Replace real snapshot polling with explicit admission gates

@steipete
steipete marked this pull request as ready for review October 5, 2026 00:35
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 5, 2026
…site

The database-worker ratchet counts SQL call sites in non-worker modules. Reuse the pending-session listing inside the publication worker preflight instead of adding a COUNT helper to session-transcript-index.ts.
@steipete
steipete merged commit 52df080 into main Oct 5, 2026
118 checks passed
@steipete
steipete deleted the steipete/zen-jemison-73560d branch October 5, 2026 02:21
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…ind larger agents at startup (openclaw#165207)

* fix(sessions): admit smaller transcript rebuild backlogs first

The transcript reconcile pool runs one whole-agent task per pass on a single
worker in FIFO order, so an agent with one pending projection rebuild waited
for every earlier agent's full backlog before it could serve history.

Admission is now owned by the reconcile pool: planning tasks are ordered by
pending session backlog (operation order breaks ties), and a running planner
yields at a completed session boundary only to a strictly smaller waiting
backlog, reserving its own place before releasing the worker. Large stores
never interleave, total work is unchanged, MAX_WORKERS stays 1, and lease
release tasks bypass admission. Startup still awaits each agent's complete
rebuild.

* fix(sessions): count reconcile backlog without a new main-thread SQL site

The database-worker ratchet counts SQL call sites in non-worker modules. Reuse the pending-session listing inside the publication worker preflight instead of adding a COUNT helper to session-transcript-index.ts.
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 merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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: L 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