Skip to content

Event-loop stalls up to 62 s on a 15 GB bb.db (0.49.0): data for #6499, #7399, #7473, plus a planner-statistics finding #7753

Open

Description

@ahkohd

Summary

On a self-hosted bb 0.49.0 server with a 15 GB bb.db, the server's event loop stalls often: 4,972 stall records in 16.4 hours, p99 30.5 s, max 61.7 s. In the same hours, machines reconnect and some API calls fail with 502 Host is not connected. The figures come from bb's own server logs (2026-11-17 13:22 to 2026-11-18 05:43 UTC), short live samples (one inside the window, one just after it), and an offline copy of the database. IDs are pseudonymised.

This report keeps what was measured separate from what is suspected. It was put together with an AI agent and checked by a second, independent agent against the evidence; the methods are included so each number can be checked.

Related issues

We have not checked the top queries below against main. #7535 (merged 2026-11-14) also changes queries whose cost grows with history.

Environment

  • bb 0.49.0 (npm, native updater), Node 24.21.0, better-sqlite3 13.0.3, SQLite 3.53.4 (compiled with ENABLE_STAT4)
  • Ubuntu 24.04 in an unprivileged Proxmox LXC: 12 vCPU, 16 GiB limit (about 7.4 to 7.5 GiB in use), NODE_OPTIONS=--max-old-space-size=8192
  • Reached through a reverse proxy on a private network, not bb connect
  • Disk: LVM-thin on an NVMe shared with other busy guests (dev boxes running builds, tests and Postgres). One 5 s host sample: device 77% busy, about 49 MB/s written across the host (bb included). One 10 s sample: reads 1.7 ms and writes 2.4 ms on average
  • 58 machines (47 connected), heavy Account Pooler use
  • 51 plugins: 42 built in, 9 installed from git (aura, beside [disabled], canvas, genui, inline-comments, polish, shell-tasks, sticky-prompt, and bb-box); 10 disabled in total

Measurements

1. Event-loop stalls (bb's Event loop stalled records)

4,972 records. Max delay: p50 1.2 s, p90 7.5 s, p99 30.5 s, max 61.7 s. 735 records over 5 s, 127 over 20 s, 53 at 30 s or more. Stalls occur in every hour of the window.

The attributed part, summed over records (a piece of work seen in several 5 s intervals may be counted more than once):

Work Records CPU s Wall s
conversation-outline 1,768 1,357 4,762
timeline-build 882 107 2,804
conversation-rows 636 513 932
ws:daemon heartbeat 1,514 5 105

By thread (top 10). Highest sequence counts pruned events, so rows stored is lower. None of these threads are archived:

Work Thread Rows stored Highest sequence Turns Records CPU s Wall s Longest wall ms
conversation-outline thr_c7242c 108,755 212,024 6,233 988 876.6 2334.5 45,400
conversation-rows thr_c7242c 108,755 212,024 6,233 381 326.5 478.8 22,436
conversation-outline thr_7207e3 145,717 274,349 8,231 129 198.1 1032.7 52,125
conversation-outline thr_eb5d84 44,274 93,723 3,004 434 184.0 521.5 29,430
conversation-rows thr_7207e3 145,717 274,350 8,231 75 99.9 217.2 46,873
conversation-rows thr_eb5d84 44,274 93,723 3,004 116 57.1 129.7 20,119
conversation-outline thr_a6106f 144,986 261,670 5,682 33 34.6 51.5 10,626
timeline-build thr_7207e3 145,717 274,350 8,231 75 33.8 822.7 52,399
timeline-build thr_c7242c 108,755 212,024 6,233 289 28.2 704.2 24,514
conversation-outline thr_5557cc 47,708 82,392 599 97 27.4 326.7 20,722

Work in flight when stalls were observed (inFlightWorkAtObservation). Each record lists several items, so the counts add up to more than the number of records. Being in flight does not mean it caused the stall:

  • POST /api/v1/plugins/account-pool/http/v1/messages/count_tokens > plugin:account-pool http: 12,514
  • POST /api/v1/plugins/account-pool/http/v1/responses > plugin:account-pool http POST /v1/re: 8,450
  • plugin:<private-plugin> tool box_run: 5,808
  • POST /api/v1/plugins/account-pool/http/v1/messages > plugin:account-pool http POST /v1/mes: 5,772
  • plugin:<private-plugin> cli box: 3,108
  • plugin:<private-plugin> tool box_copy: 2,338
  • GET /api/v1/sidebar-bootstrap: 2,002
  • POST /api/v1/threads/<id>/send: 1,530

2. Slow queries (bb's Slow DB query records, threshold 100 ms)

20,678 records, 23,095 s wall, of which 3,517 s on CPU (cpuDurationMs). The TRANSACTION DEFERRED/IMMEDIATE records (6,801 s) appear to wrap statements that are also logged; for example, #2 and #5 share a 238 s maximum. Counting them, slow-query time is about 39% of the window; leaving them out, about 28%. Roughly 85% of it was not on CPU (presumably IO or lock waits; not measured directly).

# Count Wall s CPU s p50 ms p99 ms Max ms SQL (as logged; some cut short by the logger)
0 2,056 3,681 226 291.9 22039.8 83,213 TRANSACTION DEFERRED
1 2,192 3,588 332 157.8 23649.9 65,105 select "created_at", "data", "id", "item_id", "item_kind", "parent_tool_call_id", "provider_thread_id", "scope_kind", "sequence", "thread_id...
2 5,024 3,120 1,354 231.4 3106.3 238,041 TRANSACTION IMMEDIATE
3 461 2,174 43 1869 38156 71,007 select distinct "item_kind" from "events" where ("events"."thread_id" = ? and "events"."turn_id" = ? and "events"."type" = ? and "events"."p...
4 865 1,780 98 361.8 20580.4 48,179 WITH nested_history AS MATERIALIZED ( SELECT 1 FROM events INDEXED BY events_parent_tool_call_thread_parent_sequence_idx WHERE thread_id = ?...
5 37 1,296 1,285 17917.3 238014.4 238,014 select "sequence" from "events" "retry_chain_accepted" where ("retry_chain_accepted"."thread_id" = ? and "retry_chain_accepted"."type" = ? a...
6 251 844 30 483.7 42764.1 57,854 select "sequence", "turn_id", "type", "parent_tool_call_id", json_extract("data", '?'), json_extract("data", '?'), json_extract("data", '?')...
7 410 682 24 576.7 11096.3 52,286 select 1 from "events" INDEXED BY events_thread_type_sequence_idx where ("events"."thread_id" = ? and "events"."sequence" >= ? and "events"....
8 479 642 14 521.1 10273.9 13,624 select "events"."created_at", "events"."data", "events"."id", "events"."item_id", "events"."item_kind", "events"."parent_tool_call_id", "eve...
9 803 464 8 340.7 2638.2 7,144 SELECT requested.column1 AS threadId, ( SELECT candidate.sequence FROM "events" AS candidate INDEXED BY events_thread_state_thread_sequence_...
10 1,458 448 12 228.3 1764.4 5,337 WITH candidate_ids AS MATERIALIZED ( SELECT eventRowid, sequence FROM ( SELECT eventRowid, sequence FROM ( SELECT rowid AS eventRowid, seque...
11 1,238 418 1 218.8 1957.4 4,338 INSERT INTO events (id, thread_id, environment_id, scope_kind, turn_id, provider_thread_id, sequence, type, item_id, item_kind, parent_tool_...
Full SQL of #1, #3, #4 and #5, as logged

#1 (3,588 s wall, 332 s CPU, 2,192 calls)

select "created_at", "data", "id", "item_id", "item_kind", "parent_tool_call_id", "provider_thread_id", "scope_kind", "sequence", "thread_id", "turn_id", "type" from "events" where ("events"."thread_id" = ? and "events"."sequence" >= ? and "events"."type" in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)) union all select "created_at", "data", "id", "item_id", "item_kind", "parent_tool_call_id", "provider_thread_id", "scope_kind", "sequence", "thread_id", "turn_id", "type" from "events" where ("events"."thread_id" = ? and "events"."sequence" >= ? and "events"."type" = ? and "events"."item_kind" in (?, ?)) union all select "created_at", CASE "item_kind" WHEN '?' THEN json_remove( "data", '?', '?', '?', '?', '?' ) WHEN '?' THEN json_remove( "data", '?', '?', '?', '?', '?' ) ELSE "data" END, "id", "item_id", "item_kind", "parent_tool_call_id", "provider_thread_id", "scope_kind", "sequence", "thread_id", "turn_id", "type" from "events" where (("events"."thread_id" = ? and "events"."sequence" >= ? and "...

#3 (2,174 s wall, 43 s CPU, 461 calls)

select distinct "item_kind" from "events" where ("events"."thread_id" = ? and "events"."turn_id" = ? and "events"."type" = ? and "events"."parent_tool_call_id" is null)

#4 (1,780 s wall, 98 s CPU, 865 calls)

WITH nested_history AS MATERIALIZED ( SELECT 1 FROM events INDEXED BY events_parent_tool_call_thread_parent_sequence_idx WHERE thread_id = ? AND parent_tool_call_id IS NOT NULL LIMIT 1 ), parents AS MATERIALIZED ( SELECT item_id, turn_id, min(sequence) AS start FROM nested_history CROSS JOIN events INDEXED BY events_delegating_item_lookup_idx WHERE thread_id = ? AND item_kind IN ('?', '?') AND parent_tool_call_id IS NULL AND sequence >= ? AND sequence <= ? AND EXISTS ( SELECT 1 FROM events AS root_start INDEXED BY events_thread_turn_type_item_sequence_idx WHERE root_start.thread_id = events.thread_id AND root_start.turn_id = events.turn_id AND root_start.type = '?' AND root_start.parent_tool_call_id IS NULL AND root_start.sequence <= ? ) GROUP BY item_id, turn_id ), spans AS MATERIALIZED ( SELECT start, ( SELECT max(child.sequence) FROM events AS child INDEXED BY events_parent_tool_call_thread_parent_sequence_idx WHERE child.thread_id = ? AND child.parent_tool_call_id IS NOT NULL AN...

#5 (1,296 s wall, 1,285 s CPU, 37 calls)

select "sequence" from "events" "retry_chain_accepted" where ("retry_chain_accepted"."thread_id" = ? and "retry_chain_accepted"."type" = ? and exists (select "sequence" from "events" "retry_chain_request" where ("retry_chain_request"."thread_id" = ? and "retry_chain_request"."type" = ? and json_extract("retry_chain_request"."data", '?') = json_extract("retry_chain_accepted"."data", '?') and (json_extract("retry_chain_request"."data", '?') = ? or json_extract("retry_chain_request"."data", '?') = ?)))) limit ?

3. What the main thread is doing (live samples: one inside the log window, one just after)

Sampled from /proc/<pid>/task/<tid>/{stat,wchan,syscall} every 50 ms, without pausing or tracing. Neither sample is known to cover a long stall:

Sample Running or runnable (R) Idle (epoll_pwait) Disk wait (D) Disk waits seen in
30 s, about 04:20 UTC 30% 54% 12% page reads (folio_wait_bit_common), a little jbd2_log_wait_commit
60 s, about 05:45 UTC 46% 44% 6% pread64 on bb.db (about 4%), fsync/pwrite64 on bb.db-wal, fsync on a plugin's own SQLite WAL

R also includes time waiting for a CPU. Over 20 s the main thread used 7.5 s of CPU (38%); the four V8 worker threads (probably GC) used about 2.4 s each. These samples suggest a mix of CPU and disk waits, while the slow-query log suggests most query time is not CPU. We have not reconciled the two. Kernel delay accounting is off on this host.

4. CPU profile of the main thread (63.5 s, a calm minute)

Taken without a restart: SIGUSR1, then Profiler.start/stop at a 1 ms interval, then the inspector was closed. Profiler.stop took 473 ms. No stall of 1 s or more was logged between 05:48 and 05:56 UTC, so this is not a stall profile. Time blocked inside synchronous native calls, such as SQLite, counts as busy.

Self time Share
(idle) 75.5%
(program): native/VM, including SQLite 6.4%
bb server JavaScript 5.9%
other native frames 4.7%
garbage collector 4.3%
node internals 2.6%
frames under plugin paths (built-in and installed) about 0.3%

Largest inclusive bb-specific frames: runEventLoopWorkSync 5.9%, getThreadMessage 5.2%, buildThreadConversationRows 5.1%, runTimedStatementOperation 4.1%, parseStoredEvent 2.8%, sqliteTransaction 2.5%, zod parsing 1.6%, appendDaemonEventsInTransaction 1.4%, insertStoredEventRow 1.3%.

5. Errors in the window

  • 75 Server error response, status 502, "Host is not connected": thread-storage file lists, path checks, provider CLI install/status, file writes, thread send
  • 2 "Timed out waiting for command result"; 1 plugin "is not running" error
  • 3,221 daemon WebSocket closes and 3,225 opens; 876 of the closes fall in one hour
  • Pruning: 3,142 "Slow thread pruning advance" records, 1.24 M rows scanned, about 92,000 removed

6. Database shape (offline copy unless stated)

  • 15.0 GB, page size 4096, auto_vacuum=INCREMENTAL, WAL, freelist 952 pages
  • events: 6.46 M rows, 10.1 GB, including 759,000 overflow pages. In a 1% sample (64,385 rows), data averaged 1.07 KB, the largest was 1.2 MB, and 5% were over 4 KB
  • retained_event_outputs: 1.44 GB, almost all overflow pages
  • events indexes range from 4 MiB (partial indexes) to 600 MiB; all indexes total 2.5 GB
  • 6,632 threads, 6,538 archived and kept. In a 10% sample, archived threads hold 81% of stored event rows and 85% of data bytes
  • Events per thread: p50 204, p90 1,583, p99 13,298, max 145,223 stored rows
  • Locality (live database, read-only): the most recent 2,000 events of three large threads span 23 to 134 times as many rows. In 1,500-row random samples within those spans, 71 to 75% belonged to other non-archived threads and 20 to 28% to archived ones

Experiment: planner statistics on the offline copy (not applied live)

Method: an LVM snapshot of the container disk; bb.db and its WAL copied into a RAM disk on a separate box (quick_check ok), with the same better-sqlite3 and SQLite. Timings are in RAM, so they show relative cost, not production latency.

  • Baseline, Add sidebar row context menus #3: uses events_thread_type_item_kind_sequence_idx (thread_id=?, type=?). On a large thread that index matches 26,571 rows for item/started, while (thread_id, turn_id, type) matches 1 (live read-only count). Per call: 31 to 52 ms on the first, cold run and 15 to 38 ms warm.
  • ANALYZE with analysis_limit=1000 (0.76 s): no plan change for Add sidebar row context menus #3. PRAGMA optimize normally runs a bounded analysis, so it may not be enough on its own. We did not test it.
  • Full ANALYZE (stat1 and stat4; 4.1 s in RAM, reading 2.5 GB of index; cost on the live disk unknown): Add sidebar row context menus #3 switches to events_thread_turn_type_item_sequence_idx (thread_id=?, turn_id=?, type=?), 0.02 to 0.03 ms per call. We did not isolate whether stat1 or stat4 made the difference.
  • Another query, ... type = ? and turn_id in (?) and sequence <= ? order by sequence, changes plan for item/started (26 to 36 ms becomes 0.04 to 0.13 ms) and not for item/completed. Row counts were the same under both plans.
  • Other plans: plans were compared with NULL binds and logged '?' literals, so value-dependent stat4 plans may differ in production. Of the other 15 testable statements (2 INSERTs, 3 with INDEXED BY) none changed. 8 of the top 25 could not be prepared: 7 because the logger cuts long SQL short, and 1 because replaced literals left "no query solution".
  • Applying it: copying the statistics rows into the database took one 7 ms write transaction. A long-lived connection's existing prepared statement then ran on the new plan without a restart, and DROP TABLE sqlite_stat1; DROP TABLE sqlite_stat4; returned it to the old timing in 2.4 ms.
  • Scale: the two statements that changed account for about 10% of logged slow-query wall time. No experiment shows that stalls would fall.

Not established

  • How much the shared, busy disk contributes compared with bb's own access pattern
  • Whether the outside plugins contribute. Plugin calls show up often among in-flight work; one plugin fsyncs its own SQLite file on the main thread; shell-tasks retries reconciliation for about 8 stale tasks every 13 s or so
  • What the unattributed 86% of stall records were doing; no profile of a long stall exists yet
  • Whether the 502s come only from missed heartbeats during stalls (Host daemons all drop together when the server event loop stalls past the 30s heartbeat lease (502/504) #6499)

Possible causes, for maintainers to judge

  1. Synchronous better-sqlite3 calls on the main thread turn slow reads and lock waits into event-loop stalls, made worse by poor locality (events interleaved across threads) and overflow pages.
  2. Without planner statistics, some queries use a poor index, and the cost grows with thread size.
  3. Outline, rows and timeline builds for very large threads are synchronous (conversation-outline rebuilds 2-3 MB on almost every open of a long, busy thread (0.49.0): key includes outlineSequence and status, no incremental build #7399). Here outline builds spend about 28% of their wall time on CPU, timeline builds about 4% and row builds about 55%.
  4. Long stalls starve heartbeats, so machines disconnect and 502s follow (Host daemons all drop together when the server event loop stalls past the 30s heartbeat lease (502/504) #6499).

Happy to provide

Query plans before and after (JSON), the database-shape summary, the CPU profile with local paths stripped, a longer profile that keeps running until it catches a stall of 5 s or more, or test results on the database copy against a pre-release build.

Activity

  1. added theissue type on Nov 18, 2026
  2. added
    host
    threads
    partial-repro
    on Nov 18, 2026
  3. bb-slop-cop commented on Nov 18, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · High priority · Medium effort; host, threads, perf.
    • Report: Reproduction and root-cause investigation.
    • Verdict: PARTIALLY REPRODUCED · root-cause confidence medium · reproduction label partial-repro.
    • Finding: Real synchronous SQLite lock waits block JavaScript timers for approximately five seconds, and fresh migrated databases lack planner statistics. The closest current production turn-item lookup already pins the correct index; the reported 62-second stalls and disconnects remain unverified.
    • Verification: The same harness ran in two clean trusted-main checkouts; 72 relevant existing tests passed. Both bounded and full analysis improved the synthetic unhinted comparison—not a current production query.
    • No PR: No failing current-main regression isolates a safe simple fix; statistics persistence or I/O isolation exceeds this run’s constraints.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    hostpartial-reproperfthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions