openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(memory): serialize memory_tree schema init across worker pool

Open oxoxDev opened this issue 6 months ago • 1 comments

Summary

  • Four tree_jobs_worker tasks were racing into memory::tree::store::with_connection on cold start, triggering ~19k Sentry events/day across three SQLite WAL/SHM bootstrap codes.
  • Gate apply_schema behind a process-wide Mutex<HashSet<PathBuf>> so only the first caller per DB path runs WAL setup + SCHEMA + ALTER TABLE migrations; subsequent callers skip.
  • Retry the open+init flow up to 3x on the three transient cold-start codes (14 / 1546 / 4874) with 50→150→500ms backoff as belt-and-suspenders.
  • Add a regression test spawning 8 threads against a cold tempdir DB; asserts all Ok and apply_schema runs exactly once per path.

Problem

Three Sentry issues, all tagged domain=memory, operation=tree_jobs_worker, worker_idx=0..3, sharing the same root cause:

Sentry ID Events Error message
OPENHUMAN-TAURI-HH 14168 Failed to initialize memory_tree schema: disk I/O error: Error code 1546: Error attempting to truncate file
OPENHUMAN-TAURI-ZM 3013 Failed to initialize memory_tree schema: disk I/O error: Error code 4874: I/O error within the xShmMap method (trying to resize an existing shared-memory segment)
OPENHUMAN-TAURI-MB 2177 Failed to initialize memory_tree schema: unable to open database file: Error code 14: Unable to open the database file

ZM + MB share a trace_id — two SQLite errors in the same event chain. Cross-platform (Windows + macOS) → race, not OS-specific. All three codes are flavors of the same race window on WAL+SHM cold start:

  • code 14 (SQLITE_CANTOPEN) — lockfile race, WAL not yet ready
  • code 1546 (SQLITE_IOERR_TRUNCATE) — WAL truncation contention
  • code 4874 (SQLITE_IOERR_SHMMAP) — shared-memory segment resize race

The 4 worker tasks (WORKER_COUNT = 4 in memory::tree::jobs::worker) all enter with_connection via claim_next immediately after the pool boots. Each connection re-ran PRAGMA journal_mode=WAL + execute_batch(SCHEMA) + ALTER TABLE migrations — fine for a warm DB, racy on cold start when WAL + SHM files don't yet exist.

Solution

Centralised the init in store.rs:

  • SCHEMA_INITIALIZED: OnceLock<Mutex<HashSet<PathBuf>>> records DB paths whose schema has been applied this process.
  • with_connection calls open_and_init_with_retry(&db_path):
    • Fast path: path already in set → just open conn + set busy_timeout + return.
    • Cold path: open conn, acquire mutex, double-check, run apply_schema (WAL + SCHEMA + ALTERs + index) once, insert path, drop mutex.
  • The whole flow is wrapped in a 3-attempt retry with 50/150/500ms backoff on the three transient codes; classifier walks the anyhow cause chain so codes buried under .context() layers still match.
  • Keyed on PathBuf (not "process-wide once") so per-test tempdir() configs each initialise independently — guards against the stale-handle pattern in feedback_oncelock_sqlite_test_isolation.md.

The busy_timeout = 15s and journal_mode = WAL from the existing code are unchanged.

Test: with_connection_serialises_concurrent_schema_init spawns 8 threads racing into with_connection on a fresh tempdir. Asserts (a) no errors surface and (b) apply_schema runs exactly once for the shared path. Per-path counter avoids false positives from parallel tests in the same binary against their own tempdirs.

Micro-commits (in order):

  1. fix(memory): serialize memory_tree schema init across workers — the mutex-gated guard + retry in store.rs
  2. test(memory): cover concurrent memory_tree schema init regression — 8-thread regression test in store_tests.rs

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] N/A: behaviour-change is a serialization guard around an existing init path; covered by the new 8-thread regression test plus the existing store test suite (13 tests pass locally). Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via diff-cover) meet the gate enforced by .github/workflows/coverage.yml.
  • [x] N/A: behaviour-only change to existing memory_tree init path, no new feature row. Coverage matrix updated — added/removed/renamed feature rows in docs/TEST-COVERAGE-MATRIX.md reflect this change.
  • [x] N/A: bug fix tracked via Sentry IDs, not GH-issue feature flow. All affected feature IDs from the matrix are listed in the PR description under ## Related.
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy)
  • [x] N/A: change is in the Rust core's SQLite init path; not a release-cut surface. Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md).
  • [x] Linked issue closed via Closes #NNN in the ## Related section

Impact

  • Runtime/platform: desktop (Windows + macOS observed in Sentry). Eliminates ~19k events/day of Failed to initialize memory_tree schema errors from the worker pool's cold-start path.
  • Performance: hot path (every with_connection call after first) now does Mutex<HashSet>::lock().contains() instead of running PRAGMA journal_mode=WAL, the full SCHEMA execute_batch, and 12+ ALTER TABLE probes. Net speedup per call on warm DBs — small but free, especially under contention.
  • Security/migration/compatibility: none. Schema is unchanged; the guard only changes when the existing migrations are run (once per process per path instead of once per with_connection call).

Related

  • Closes OPENHUMAN-TAURI-HH
  • Closes OPENHUMAN-TAURI-ZM
  • Closes OPENHUMAN-TAURI-MB
  • Follow-up PR(s)/TODOs:

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/sentry-mt-init-worker-race
  • Commit SHA: see HEAD of branch

Validation Run

  • [x] N/A: Rust-only change. pnpm --filter openhuman-app format:check
  • [x] N/A: Rust-only change. pnpm typecheck
  • [x] Focused tests: cargo test --lib openhuman::memory::tree::store -- --test-threads=4 → 13/13 pass (includes new with_connection_serialises_concurrent_schema_init)
  • [x] Rust fmt/check (if changed): cargo fmt --check clean; cargo check clean
  • [x] N/A: no Tauri shell changes. Tauri fmt/check (if changed)

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: serialise schema init across concurrent with_connection callers; skip redundant WAL + SCHEMA + ALTER work after first per process.
  • User-visible effect: eliminates the three Sentry "Failed to initialize memory_tree schema" error classes on cold start. No UX-visible delta on success path.

Parity Contract

  • Legacy behavior preserved: every connection still gets busy_timeout = 15s set; WAL journal mode persists in the DB header from the first init; all ALTER TABLE migrations remain idempotent and are unchanged.
  • Guard/fallback/dispatch parity checks: retry classifier (is_transient_cold_start) only matches the three documented cold-start codes; non-transient errors still bubble up unchanged.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): N/A
  • Canonical PR: this PR
  • Resolution: N/A

Summary by CodeRabbit

  • Bug Fixes

    • DB schema initialization is now serialized per file and retries transient SQLite startup errors with backoff.
    • Foreign-key enforcement is consistently enabled on every connection.
  • New Features

    • Schema expanded with embedding and summary fields, importance/reason, backlinks, lifecycle status and index, content pointers, raw references, and an entity "is_user" flag.
  • Tests

    • Added regression tests for concurrent schema init and transient-error classification, a manual smoke/stress binary for concurrent init, and tightened a test with a global lock to prevent race flakes.

Review Change Stack

oxoxDev avatar May 18 '26 07:05 oxoxDev

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

SQLite initialization now uses per-DB-path guards and retries transient cold-starts with backoff; schema application is idempotent and extended with additive migrations. Tests and a smoke binary validate concurrent init correctness and that foreign key enforcement is enabled per connection.

Changes

Concurrent-Safe SQLite Initialization with Schema Extension

Layer / File(s) Summary
Concurrency guards and initialization tracking
src/openhuman/memory/tree/store.rs
Adds imports for path/keyed process-local bookkeeping, a per-path SCHEMA_INITIALIZED guard and SCHEMA_APPLY_COUNTS counter, and exposes a test-only accessor to read apply counts.
Connection opening with retry and FK per-connection
src/openhuman/memory/tree/store.rs
Refactors with_connection to open via open_and_init_with_retry, which checks the per-path guard and retries transient SQLite cold-start errors with bounded backoff before invoking schema application; moves foreign_keys enabling to per-connection setup and removes it from the base SCHEMA.
Schema migration column additions
src/openhuman/memory/tree/store.rs
apply_schema extended to idempotently add chunk embeddings, mem_tree_score LLM importance/reason fields, mem_tree_chunks.parent_summary_id, mem_tree_summaries.embedding, mem_tree_chunks.lifecycle_status and its index, content_path/content_sha256 for chunks and summaries, mem_tree_chunks.raw_refs_json, and mem_tree_entity_index.is_user.
Concurrent initialization regression test & smoke CLI
src/openhuman/memory/tree/store_tests.rs, Cargo.toml, src/bin/memory_tree_init_smoke.rs, src/openhuman/wallet/execution.rs
Adds with_connection_serialises_concurrent_schema_init and is_transient_cold_start_classifies_known_extended_codes tests asserting single-apply under concurrency and classification of transient extended codes; adds memory-tree-init-smoke binary and Cargo entry to stress-test concurrent initialization; synchronizes a wallet test with TEST_LOCK.

Sequence Diagram

sequenceDiagram
  participant WorkerThread
  participant with_connection
  participant open_and_init_with_retry
  participant InitializationGuard as Guard
  participant SQLiteDB as DB
  WorkerThread->>with_connection: request connection(path)
  with_connection->>open_and_init_with_retry: open/init path
  open_and_init_with_retry->>Guard: check/acquire per-path lock
  Guard->>open_and_init_with_retry: grant or block
  open_and_init_with_retry->>DB: open and run SCHEMA / migrations (if leader)
  open_and_init_with_retry->>with_connection: return Connection
  with_connection->>WorkerThread: provide Connection

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

working

Suggested reviewers

  • senamakel

Poem

🐰 I hopped to guard the DB door,
One schema run, not one run more.
Threads raced in flurry and light,
Backoff hummed through startup night.
Now counts whisper: "once" — alright.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: serializing SQLite schema initialization for memory_tree to prevent concurrent worker races.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 18 '26 07:05 coderabbitai[bot]

@oxoxDev bro conflicts

graycyrus avatar May 19 '26 15:05 graycyrus

@graycyrus resolved bro — merged upstream/main into branch, reconciled #2059 worker-race split with #1574 §7 legacy→sidecar migration. 600/600 memory_tree tests green. CI re-running.

oxoxDev avatar May 19 '26 15:05 oxoxDev