Skip to content

Keep server heartbeats responsive during expensive SQLite search - #5368

Closed
jonolee-kr wants to merge 1 commit into
get-bb:mainfrom
jonolee-kr:draft/sqlite-search-worker
Closed

jonolee-kr wants to merge 1 commit into
get-bb:mainfrom
jonolee-kr:draft/sqlite-search-worker

Conversation

@jonolee-kr

@jonolee-kr jonolee-kr commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Draft for review. This branch requires rebasing and validation on current main before merge.

The implementation was verified against the gorag checkout at 59a03819a, not current upstream main.
This draft contains the same 34 implementation files, with the unrelated Tasks Markdown commit excluded.
At publication, upstream main was 3aa5ef327093f2834f800370881ac0bed8f2d811, 1,581 commits ahead of this branch's base.
GitHub reports merge conflicts with main. The verified results below apply to the original checkout and require repetition after integration.

Human comments

What was wrong

Thread search invokes synchronous better-sqlite3 and Drizzle operations on the main Node event loop.
An observed four-token FTS query took 102,177 ms while daemon heartbeat acknowledgements stopped and Connect disconnected.
Common tokens expand grouped and ranked results before limits apply. The original segment ranking also carries full message text through temporary tables.
Memory reclaim and I/O pressure can amplify that latency. Their exact contribution to the observed query remains unknown.

Related: #4413 and #5192.
Those issues include additional work outside this draft's scope. This draft does not auto-close either issue.

Investigation, benchmarks, resource proposals, and remaining synchronous paths: report.

What changed

  • Add a dedicated worker with its own read-only SQLite connection and a typed async interface for existing search and outline routes.
  • Preserve cross-segment token matching, visibility and deletion filters, active/archived groups, ranking, totals, snippets, highlights, and limits.
  • Materialize shared match results and rank segment row identifiers before loading retained text. Remove a redundant DISTINCT count.
  • Allow one active read and eight queued reads. Apply ten-second queue and startup limits and a three-second execution deadline.
  • Propagate HTTP disconnect cancellation. Retire failed or canceled workers and reject pending requests during crashes and shutdown.
  • Add a connection-local native watchdog that calls sqlite3_interrupt. The installed SQLite build omits progress callbacks.
  • Gate native entries before worker termination to avoid a demonstrated better-sqlite3 process abort during native error creation.
  • Check the deadline before every native entry, including COMMIT after JavaScript processing. Readers avoid migrations and schema-changing setup.
  • Isolate completed-output retention in a separate maintenance worker with a 100 ms execution deadline and atomic output/cursor updates.
  • Separate queue, native SQL, processing, serialization, and delivery metrics. Correlate outcomes with event-loop samples and heartbeat acknowledgement age.

The existing search UI already calls the affected SDK route and supplies an AbortSignal. No frontend change is required.
No server/daemon payload changes or public configuration knobs are introduced. No daemon protocol bump is required.
Existing SDK declaration automation changes are excluded. The report proposes resource budgets without applying them.

Merge blockers and limitations

  • Rebase or port this implementation onto current main. Repeat correctness, lifecycle, build, and typecheck validation after integration.
  • Investigate the search p99 regression with a controlled comparison. The current benchmark cannot assign its cause.
  • Validate native-extension packaging for all supported platforms. This investigation verified Linux x64 only.
  • Prevent cross-platform cache reuse of bundled native artifacts. The native compile task itself is uncached.

General timeline reads, thread-list metadata, foreign-key cascades, session pruning, legacy cleanup, and vacuum paths still contain synchronous operations.
SQLite interruption cannot preempt an uninterruptible kernel I/O operation. Worker isolation does not remove host memory or disk pressure.
No production deployment, restart, agent termination, or production limit change occurred.

How you verified

Validation used the original gorag checkout and disposable migrated databases. These results do not validate current upstream main.

  • 162 focused tests passed: 103 server tests, 47 database tests, and 12 tunnel-client tests.
  • Focused server, database, and tunnel-client typechecks passed. The server bundle and native extension builds passed.
  • Existing search tests and a reference-query differential test cover common tokens, split segments, prefixes, archives, hidden/deleted threads, and large bodies.
  • Worker tests cover startup, crashes, shutdown, bounded queues, cancellation, replacement, real SQL deadlines, concurrent writes, snapshots, locks, and WAL release.
  • A real slow SQLite trigger verifies maintenance timeout, unchanged outputs/cursors after rollback, and successful retry.
  • Regression tests verify unrelated API and heartbeat timer responsiveness during native SQL, plus actual HTTP disconnect cancellation.
  • Ordinary route search returns HTTP 200. Statement wrappers preserve omitted raw/pluck/expand/safeIntegers arguments.
  • An independent child reproduces a native process abort when the cancellation barrier is removed. The restored cancellation probe passes.
  • Advisor found no actionable issue within the original Linux x64 scope.

Commands used, through Turbo with normal caching:

pnpm exec turbo run build typecheck \
  --filter=@bb/server --filter=@bb/db --filter=@bb/tunnel-client \
  --concurrency=2

pnpm exec turbo run test \
  --filter=@bb/server --filter=@bb/db --filter=@bb/tunnel-client \
  --concurrency=2 -- \
  test/system/database-read-service.test.ts \
  test/public/public-thread-search.test.ts \
  test/public/public-thread-data.test.ts \
  test/services/periodic-sweeps.test.ts \
  test/services/threads/conversation-outline-performance.test.ts \
  test/data/thread-search.test.ts test/query-plans.test.ts \
  test/data/sweeps.test.ts test/origin-request.test.ts test/reconnect.test.ts \
  --maxWorkers=2 --testTimeout=15000

Validation commands ran in temporary resource scopes outside the production service. No forced rebuild flag was used.

Benchmark

The disposable workload used four common tokens across separate segments, 300 threads, and 60,000 messages with 4,096 padding characters.
Each variant received 20 warmups followed by 1,000 serial searches. Each search ran beside an unrelated health request and a 10 ms heartbeat timer.
The OS cache was warm and was not purged. These are origin-only loopback measurements, not production p99 or Connect round-trip measurements.

Metric Original main-loop search Dedicated reader
Search p95 605.6 ms 516.4 ms
Search p99 692.2 ms 1227.9 ms
Unrelated API p95 605.6 ms 4.0 ms
Unrelated API p99 691.9 ms 8.9 ms
Event-loop p99 696.3 ms 13.2 ms
Heartbeat gap p99 695.8 ms 13.2 ms
Timeouts 0/1000 0/1000

Search p99 worsened by approximately 77%. The result demonstrates event-loop isolation while leaving search tail latency unresolved.
The baseline used a 256 MiB cache and 1 GiB mmap ceiling. The reader used a 32 MiB cache and no mmap.
Sequential runs shared a host with other workloads. Those differences prevent causal attribution of the tail regression.
The benchmark predates final wrapper, listener, and deadline-entry corrections. The optimized query and worker isolation strategy remained the same.
A single startup-plus-search measurement was 949.7 ms with a warm OS cache. No cold-storage distribution was measured.

AGENT GENERATED

@github-actions

Copy link
Copy Markdown
Contributor

This is an automated message. We have closed this pull request because it has been open for more than two weeks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant