Skip to content

Thread-list goal lookup repeatedly scans unrelated extension history and stalls the server #5234

Closed

Description

@koenvg

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-view events, 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

  1. Run this self-contained command. It creates only an in-memory synthetic database and does not open a BB database.
  2. 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()
PY

On 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_state lookup. 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:

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

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

  1. added theissue type on Oct 8, 2026
  2. added
    threads
    no-repro
    on Oct 8, 2026
  3. bb-slop-cop commented on Oct 8, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority High · Effort Low. Labels: threads, perf, no-repro.
    • Report: Reproduction and root-cause report.
    • Verdict: ALREADY FIXED on trusted origin/main at ff94848832b22c3281ffc4b5b9069d2490ddea36; root-cause confidence high. Reproduction label: no-repro.
    • Root cause: The former event-correlated MAX lookup 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.
    • Verification: An investigator-authored eight-thread, no-goal history test passes in two clean checkouts: 768 and 3,072 events cause exactly 768 and 3,072 JSON extractions. Existing event/query-plan suites: 138 tests passed.
    • No new PR: The root-cause fix already exists on main. The installed macOS artifact and its production stalls were not tested here.

    AGENT GENERATED

  4. ymichael commented on Oct 9, 2026

    @ymichael
    Collaborator

    Fixed by #4931. this will go out in the next release

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

    no-reproperfthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions