Repository navigation
Description
Summary
The BB desktop app repeatedly stops responding for several seconds while loading the thread list. The latest-goal lookup rescans unrelated extension-state history even when there are no goals. Thread-list reads should not cause multi-second server stalls.
Versions and environment
- BB desktop 0.45.0, installed at
/Applications/bb.app. This is the latest published release,desktop-v0.45.0, when checked on 2026-10-08. - macOS 26.6.2, build 25G83.
- Local server and host daemon at the standard ports, data directory
~/.bb. - Production database approximately 4.05 GB, with 616 threads and 2,531 state events. All those state events were
thread/extensionState/updated; there were no matching Codex goals. - The largest observed state history contained 335
pi-subagents-provider/pi-subagents-viewevents, approximately 10.7 MB total. No agent turn is needed for the SQL reproduction below. - Inspected source commit:
fdd3de3b19b97e6cd1ef7300cbb54711431249d3. The function extracted from the installed server's source map contains the same query. The app itself was not rebuilt from this checkout. - Standalone diagnostic and reproduction reader: Python SQLite 3.53.2. BB uses synchronous
better-sqlite3; the standalone timings are not BB-driver benchmarks.
Steps to reproduce
- Run this self-contained command. It creates only an in-memory synthetic database and does not open a BB database.
- Compare the current query against the once-per-thread candidate. Both must return zero rows.
The current query's selected columns are reduced to rowid; its filtering and correlated subquery match the shipped lookup. The fixture contains five threads with 150 unrelated state updates each and 32 KiB payload text.
python3 - <<'PY'
import json, sqlite3, time
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE events (thread_id TEXT, sequence INTEGER, type TEXT, data TEXT)")
types = "('thread/goal/updated','thread/goal/cleared','thread/extensionState/updated')"
db.execute(f"CREATE INDEX events_thread_state_thread_sequence_idx ON events(thread_id,sequence) WHERE type IN {types}")
ids = [f"thread-{i}" for i in range(5)]
payload = json.dumps({"kind": "other-plugin/view", "payload": {"text": "x" * 32768}})
db.executemany("INSERT INTO events VALUES (?,?,?,?)",
[(thread, seq, "thread/extensionState/updated", payload)
for thread in ids for seq in range(1, 151)])
db.commit()
predicate = f"""candidate.type IN {types}
AND (candidate.type <> 'thread/extensionState/updated'
OR json_extract(candidate.data, '$.kind') = ?)"""
current = f"""
SELECT events.rowid FROM events WHERE events.rowid IN (
SELECT latest_state.rowid
FROM events AS latest_state INDEXED BY events_thread_state_thread_sequence_idx
WHERE latest_state.thread_id IN ({','.join('?' for _ in ids)})
AND latest_state.type IN {types}
AND latest_state.sequence = (
SELECT MAX(candidate.sequence)
FROM events AS candidate INDEXED BY events_thread_state_thread_sequence_idx
WHERE candidate.thread_id = latest_state.thread_id AND {predicate}
)
)"""
alternative = f"""
WITH requested(thread_id) AS (VALUES {','.join('(?)' for _ in ids)})
SELECT events.rowid FROM events WHERE events.rowid IN (
SELECT (
SELECT candidate.rowid
FROM events AS candidate INDEXED BY events_thread_state_thread_sequence_idx
WHERE candidate.thread_id = requested.thread_id AND {predicate}
ORDER BY candidate.sequence DESC LIMIT 1
) FROM requested
)"""
print("SQLite:", sqlite3.sqlite_version)
for name, sql in [("current", current), ("once-per-thread", alternative)]:
start = time.perf_counter()
rows = db.execute(sql, ids + ["provider-codex/goal"]).fetchall()
elapsed = time.perf_counter() - start
print(f"{name}: {elapsed:.3f}s, {len(rows)} rows")
assert rows == []
db.close()
PYOn a production installation with such histories, loading the thread list calls this lookup automatically. No active goal or running Codex thread is required.
Expected vs actual
Expected: check each requested thread's relevant history once, return no goal, and keep the server responsive.
Actual standalone synthetic output:
SQLite: 3.53.2
current: 0.393s, 0 rows
once-per-thread: 0.002s, 0 rows
Actual production server log excerpt:
{"level":30,"time":1791491161365,"component":"server","intervalMs":5000,"maxDelayMs":4028.6,"meanDelayMs":45.8,"p99DelayMs":54.8,"resolutionMs":20,"thresholdMs":500,"currentWork":"GET /api/v1/projects | GET /api/v1/threads","lastWork":"GET /api/v1/threads","lastWorkMs":0.2,"slowestWork":"timeline-build thr_qqmdpzvwke","slowestWorkMs":41.1,"msg":"Event loop stalled"}Evidence
This section is the investigation report. Originating BB investigation thread: thr_qpf2qi3emg. No private prompts, extension payloads, or database dump are included.
Observed
Parsed JSON records in ~/.bb/logs/server.17.log for the 15-minute window ending around 22:26 CEST on 2026-10-08:
- 103 slow-query records, totaling 178.7 seconds of logged query time.
- 51 server event-loop stalls, maximum approximately 8.72 seconds.
- The five longest query records all used the
latest_statelookup. The longest took 8,684.6 ms, including 6,040.1 ms CPU time.
A separate read-only connection to the live database measured the SQL with time.monotonic():
| Query | Threads | Returned rows | Elapsed |
|---|---|---|---|
| Current lookup | Five threads with the largest state payload totals | 0 | 6.218 s |
| Once-per-thread candidate | Same five threads | 0 | 17.74 ms |
| Once-per-thread candidate | All 616 threads | 0 | 28.57 ms |
The candidate uses the existing partial index. Production data was not changed.
For multiple requested threads, EXPLAIN QUERY PLAN showed:
SEARCH latest_state USING INDEX events_thread_state_thread_sequence_idx (thread_id=?)
CORRELATED SCALAR SUBQUERY 1
SEARCH candidate USING INDEX events_thread_state_thread_sequence_idx (thread_id=?)
Cause indicated by the query and reproduction
The outer lookup visits each state event and computes a correlated MAX(candidate.sequence) for its thread. The kind predicate requires JSON extraction from extension-state records. When all events have an unrelated kind, each inner search checks the same history again and finds no goal. This gives quadratic work in a thread's state-history length on the reproduced multi-thread query.
The existing query-plan test uses one thread and one event. It verifies index selection but does not detect repeated history scans.
Commit-pinned code references:
- Latest-thread-state query.
- Unconditional goal lookup for thread-list activity.
- Thread-list response activity assembly.
- Single-event query-plan test.
A possible bounded fix is to request the latest matching row once per requested thread, ordered by sequence descending, as in the SQL candidate above. This is a measured candidate, not an implemented or fully regression-tested fix. Any change must preserve legacy goal updates, cleared goals, unrelated extension kinds, and SQLite-variable batching.
What you ruled out
- Active goals are not required. Both the production lookup and synthetic reproduction return no goal rows.
- Lack of an index is not the immediate cause. The existing partial index is present and used by both queries.
- The SQL-only reproduction needs no network connection, provider call, plugin RPC, or disk database.
- Memory pressure looked healthy during inspection, with approximately 54% system-wide free memory. Simple local project requests took less than 1 ms between stalls.
- Searched open and closed issues for the function, index, thread state, and slow goal queries.
- Related to Prevent synchronous SQLite reads and retention sweeps from blocking the server #1131 and Fix the #1131 cold stall at its source: index the latest-goal lookup, drop the thread-list GROUP BY #1204, but this report reproduces the current extension-state query rather than assuming the earlier goal-query problem remains unfixed.
- Not the residual scattered thread-row read cost tracked by Thread-list reads still run synchronously on the event loop after #1204 #1207. This report isolates repeated JSON/state-history scanning and demonstrates a query-level reduction using the existing index.
- A full rebuilt application on current
main, cold-cache timings, and general semantic regression tests were not run.
Suggested priority and effort
High impact for installations with accumulated extension-state history: stalls affect unrelated routes as well as the thread list. No goal-check disable setting was found in the installed version. No data loss was observed. The proposed query change is small, but needs a multi-thread history regression test.
Checks
- Reproduced on the latest release; the current committed SQL was also reproduced in an isolated in-memory fixture.
- Searched open and closed issues.
- Included the investigation report and originating BB thread ID.
AGENT GENERATED
Activity
bb-slop-cop commentedon Oct 8, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotthreads,perf,no-repro.origin/mainatff94848832b22c3281ffc4b5b9069d2490ddea36; root-cause confidence high. Reproduction label:no-repro.MAXlookup repeatedly scanned unrelated extension history. Main already performs one descending latest-matching-row search per requested thread, fixed by fix(db): avoid repeated latest-state scans in thread batches #4931 (ef570298ef45b39d837da0fcab0fb94ea086783b), merged October 5, 2026.ymichael commentedon Oct 9, 2026
Fixed by #4931. this will go out in the next release