openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(memory_tree,scripts): IMMEDIATE-tx ingest + reembed skip-persistence + Windows dev-script PATH fixes

Open sanil-23 opened this issue 6 months ago • 2 comments

Summary

  • memory_tree::ingest::persist() uses an IMMEDIATE-tx for the read-then-write transaction. The previous DEFERRED tx bypassed the 15 s busy_timeout on lock upgrades (SQLite returns SQLITE_BUSY immediately for read→write upgrade conflicts, by design, to avoid deadlocks), so every Gmail per-message ingest failed under worker contention. Live evidence: 13/13 fails → 0/N on the verification run.
  • reembed_backfill runaway loop fixed: terminal-skip rows (body file missing on disk, embed wrong-dim, embed err) are now persistently tombstoned in two new *_reembed_skipped tables; the worklist/probe queries (handler batch + has_uncovered runtime + migration) exclude them via NOT EXISTS. Live verification on a dev workspace: 308 orphan chunks each attempted exactly once, chain complete reached in ~2 min — replaces a runaway that previously generated ~128 k body read failed; skipping warns across ~8 k batch defers for ~16 stuck chunks because the "skipping" was log-only with no persistent exit gate.
  • scripts/run-dev-win.sh — two Windows-contributor bugfixes for pnpm dev:app:win: (a) prepend dirname($PNPM_EXE) to PATH so Tauri's cmd /S /C "pnpm run dev" can resolve bare pnpm; (b) deduplicate PATH right before tauri dev so the MSYS→Windows env-conversion doesn't overflow the process-env block (without dedup, the spawned cmd inherits an EMPTY PATH).

Problem

Observed in production-mode use on Windows over a long debugging session:

  1. Gmail per-message ingest persists 0 messages under worker contention — every per-message ingest_email write fails with database is locked. The connection has busy_timeout(15s) configured, but the failures arrive in milliseconds, not seconds. Cause: a DEFERRED transaction takes a read lock then tries to upgrade to write on the first INSERT; under contention with the memory-tree worker pool, SQLite returns SQLITE_BUSY immediately for the lock upgrade and does NOT invoke the busy handler (documented deadlock-avoidance behaviour). The 15 s busy_timeout is bypassed; ingest fails fast every time; composio_sync never persists anything.
  2. reembed_backfill zombie loop — runaway re-selection of orphan chunks that can never embed (their body files are missing on disk, e.g. after a workspace path move). Generates ~128 k log warns / hour and burns one worker slot every 5 s indefinitely. Root cause: the *_embeddings tables only record successful embeddings; the worklist query WHERE NOT EXISTS embeddings keeps returning the same failing chunks because the "skipping" branch in the handler is log-only — no persistent state is written to exit the worklist.
  3. pnpm dev:app:win doesn't start cleanly on Windows — beforeDevCommand dies with 'pnpm' is not recognized. Two underlying causes: (a) pnpm's install directory was never added to PATH (the script otherwise only calls pnpm by absolute path); (b) the bash-side PATH stacks the system PATH ~5× over (vcvars rebuild + /etc/profile re-runs + pnpm .bin layering), and the MSYS→Windows env-block conversion drops the entire PATH variable when it exceeds the limit — so the spawned cmd inherits an empty PATH (not "pnpm missing" — every Windows PATH entry missing, including %SystemRoot%\System32, so even where returns "not recognized").

Solution

Concern File(s) What
Gmail "database is locked" memory_tree/ingest.rs:216 rusqlite::Transaction::new_unchecked(conn, TransactionBehavior::Immediate) instead of conn.unchecked_transaction() (deferred). Locks at BEGIN where the busy handler applies; writers serialize and wait instead of failing fast.
Reembed runaway loop memory_tree/store.rs, tree_source/store.rs, jobs/mod.rs, jobs/handlers/mod.rs Two new idempotent CREATE TABLE IF NOT EXISTS rows (mem_tree_chunk_reembed_skipped, mem_tree_summary_reembed_skipped), two helpers (mark_chunk_reembed_skipped, mark_summary_reembed_skipped), three worklist/probe SQL queries get an AND NOT EXISTS … reembed_skipped clause (handler batch in handlers/mod.rs, the has_uncovered runtime probe in jobs/mod.rs, the has_uncovered migration probe in store.rs). Handler skip branches now also write a sentinel via let _ = mark_*_reembed_skipped(...) (best-effort: if the sentinel write itself fails, the row simply gets retried on the next batch — desirable fallback).
Windows dev script scripts/run-dev-win.sh (a) After PNPM_EXE is resolved, export PATH="$(dirname "$PNPM_EXE"):$PATH". (b) Right before "$PNPM_EXE" tauri dev, an in-script first-seen-wins dedup loop collapses PATH (entries are clean /c/... POSIX so :-split is safe). Adds two [run-dev-win] info-level log lines so the next contributor can see at a glance what happened (pnpm dir prepended to PATH: ..., PATH de-duplicated: 317 → 71 entries).

Design choices worth flagging for reviewers:

  • Why a separate tombstone table rather than NULL-sidecar rows for reembed-skip: the existing *_embeddings table has vector BLOB NOT NULL and dim INTEGER NOT NULL, so a NULL sentinel doesn't fit the schema, and an empty-blob/zero-dim sentinel would pollute the embedding readers (they'd need a special-case for "not a real embedding"). A separate small table keeps the embedding semantics clean and the worklist query's NOT EXISTS predicate trivial.
  • Why three SQL sites get the same NOT EXISTS clause rather than refactoring into one helper: the three are different shapes (handler batch returns a list with LIMIT ?; the runtime + migration probes are SELECT EXISTS(... OR ...)); abstracting them would either lose query-shape clarity or require a builder. The duplication is small and the in-place comments cross-reference each other, so future drift would be obvious.

Submission Checklist

  • [x] N/A: tests deferred to a follow-up commit — see Validation Blocked below. The change is end-to-end verified on a live workspace (308 sentinel rows written + chain complete reached, 0 ingest lock failures observed in the new run) but unit-test additions for the new SQL paths are pending. The PR is opened as DRAFT for this reason. There IS an existing test reembed_backfill_repopulates_then_completes in handlers/mod.rs:1062 that already exercises the batch-defer-then-complete cycle — it should still pass with the new NOT EXISTS clause (the sentinel is only written on failure paths the test doesn't trigger), but I have not run it explicitly post-change.
  • [x] N/A: diff coverage gate will not pass on this commit alone — same reason as above. Will land tests in follow-up before un-drafting.
  • [x] N/A: no behaviour-only feature ID change — the IMMEDIATE-tx fix and the reembed-skip persistence are bugfixes on existing capabilities; no new top-level feature row required.
  • [x] N/A: no matrix-tracked feature IDs touched (changes are SQL paths / Windows dev script).
  • [x] No new external network dependencies — all changes are local SQLite or shell-script.
  • [x] N/A: no release-cut surface touched. The Windows dev-script change is for the dev workflow only; the runtime behaviour of pnpm dev:app:win is unaffected for contributors whose machines were already correctly configured (the two fixes are additive — they only matter when pnpm's dir isn't otherwise on PATH and when PATH is otherwise overflowing).
  • [x] N/A: no linked issue — the changes were derived from a long-running production-mode debugging session, not a tracked ticket. Happy to file follow-up issues if reviewers prefer.

Impact

Runtime / platform: desktop, all platforms for the Rust changes; the run-dev-win.sh change is Windows-only.

Performance: net positive. Gmail ingest no longer drops messages and serializes correctly; the reembed worker no longer wastes one slot every 5 s on the same orphan reads.

Migration / compatibility: two new SQLite tables added via the existing CREATE TABLE IF NOT EXISTS SCHEMA const path. No user_version bump; tables materialise lazily on next with_connection. Backward-compatible: older binaries opening the DB will simply ignore the new tables.

Security: no privilege changes.

Related

  • Closes:
  • Follow-up PR(s)/TODOs:
    • Unit tests for the IMMEDIATE-tx ingest path under simulated lock contention and for the reembed sentinel write/read cycle.
    • One-shot data cleanup or admin RPC for the ~308 sentinel rows now on the dev workspace (cosmetic — the rows are correct, just noisy in diagnostics).

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

Linear Issue

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

Commit & Branch

  • Branch: fix/memory-tree-and-win-dev
  • Commit SHA: 9b9f54ea

Validation Run

  • [x] N/A: pnpm --filter openhuman-app format:check not run — Windows working tree has the documented ~600-file CRLF/LF drift; format:check would rewrite unrelated files. Pre-push hook bypassed via --no-verify per the same documented pattern.
  • [x] N/A: pnpm typecheck not run — no TypeScript surface changed in this PR.
  • [x] Focused tests: the existing reembed_backfill_repopulates_then_completes integration-style test in jobs/handlers/mod.rs:1062 should still pass with the new NOT EXISTS clause (it triggers the success path the sentinel is not written on); I have not run it explicitly post-change.
  • [x] Rust fmt/check: cargo check ran implicitly via pnpm dev:app:win rebuild — 0 errors. cargo fmt not explicitly run; will run in the follow-up that adds tests.
  • [x] N/A: Tauri fmt/check — no app/src-tauri/ Rust changes in this PR.

Validation Blocked

  • command: cargo fmt and unit-test additions for the IMMEDIATE-tx and reembed-skip paths
  • error: n/a — not blocked technically; bundled with the test-coverage follow-up before un-drafting.
  • impact: PR is opened as DRAFT; reviewer feedback welcome on the schema + worklist-SQL approach before I invest in the test suite.

Behavior Changes

  • Intended behavior change:
    1. Gmail per-message ingest no longer drops messages under worker contention — the IMMEDIATE-tx makes the 15 s busy_timeout actually apply on the read-then-write block in persist().
    2. reembed_backfill chain terminates instead of looping forever on orphan chunks — terminal failures are persistently tombstoned and excluded from the worklist.
    3. pnpm dev:app:win actually starts on a fresh Windows checkout without manual workarounds.
  • User-visible effect:
    • Gmail sync writes actually persist; "Memory Sources" counts grow instead of staying at zero.
    • Logs are no longer flooded with [memory_tree::jobs] reembed_backfill: chunk … body read failed; skipping (was ~128 k warns / run before, now once per orphan per signature).
    • New contributors on Windows can run pnpm dev:app:win and have a Tauri shell open.

Parity Contract

  • Legacy behavior preserved:
    • mem_tree_chunk_reembed_skipped / mem_tree_summary_reembed_skipped are created idempotently — older code opening the DB pre-this-change works unchanged; rolling back this commit removes only the additive tables.
    • The NOT EXISTS … reembed_skipped clauses are pure subtraction from the worklist — every chunk that previously appeared still appears unless it has a terminal-failure sentinel, which only the new handler code can write.
    • mark_*_reembed_skipped is best-effort (let _ =): a transient write failure does not crash the batch; the row simply gets retried on the next batch (desired fallback).
    • IMMEDIATE-tx is strictly safer than DEFERRED: it never deadlocks (acquires write lock at BEGIN), and busy_timeout already governs the wait. Existing successful writers under no contention behave identically.
    • run-dev-win.sh changes are additive and only fire conditions that already produced errors (pnpm-not-on-PATH; PATH overflow). Contributors whose machines didn't hit those conditions see no behaviour change.
  • Guard/fallback/dispatch parity checks: the worklist SQL was updated in all 3 sites that reference the same predicate (handler batch + has_uncovered runtime probe + has_uncovered migration probe) to avoid drift between sites; each unconditionally adds AND NOT EXISTS … reembed_skipped so the three remain semantically aligned.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this one
  • Resolution: n/a

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Windows dev startup: improved PATH handling (derives package-manager dir, avoids redundant PATH entries) so the package manager is reliably found and startup logs the resulting PATH state.
    • Embedding backfill: unembeddable chunks/summaries are now permanently marked per model signature and excluded from reprocessing, preventing infinite retry loops and reducing redundant work.

Review Change Stack

sanil-23 avatar May 20 '26 12:05 sanil-23

[!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

Adds persistent tombstones and helpers for terminal re-embed failures, filters tombstoned rows from worklists and coverage probes, updates ingest transaction to Immediate, and fixes Windows dev script PATH/pnpm resolution.

Changes

Windows Dev Script & Persistence Configuration

Layer / File(s) Summary
Windows PATH resolution for pnpm
scripts/run-dev-win.sh
Prepends the resolved pnpm directory to PATH and de-duplicates PATH entries immediately before running tauri dev so Tauri's beforeDevCommand can resolve pnpm by bare name and avoid PATH overflow issues.
Ingest transaction concurrency mode
src/openhuman/memory/tree/ingest.rs
Replaces unchecked_transaction with rusqlite::TransactionBehavior::Immediate in persist to establish explicit locking semantics and document busy-timeout behavior during writes.

Re-embed Backfill Terminal Failure Handling

Layer / File(s) Summary
Tombstone schema tables for terminal failures
src/openhuman/memory/tree/store.rs
Adds mem_tree_chunk_reembed_skipped and mem_tree_summary_reembed_skipped schema entries to persist terminal skip records keyed by `(chunk_id
Coverage probe treats tombstones as covered
src/openhuman/memory/tree/jobs/mod.rs, src/openhuman/memory/tree/store.rs
Updates the migration/coverage probe SQL to treat rows present in the _reembed_skipped tables as covered (adds NOT EXISTS checks) so they do not trigger backfill enqueueing.
Skip marker helper functions
src/openhuman/memory/tree/store.rs, src/openhuman/memory/tree/tree_source/store.rs
Exports mark_chunk_reembed_skipped and mark_summary_reembed_skipped which upsert tombstone rows with reason and current UTC timestamp for idempotent terminal-failure recording.
Worklist filtering excludes tombstoned rows
src/openhuman/memory/tree/jobs/handlers/mod.rs
handle_reembed_backfill selection queries for chunks and summaries add NOT EXISTS predicates against the tombstone tables for the active model_signature, preventing re-selection of already-tombstoned rows.
Error handling records terminal failures
src/openhuman/memory/tree/jobs/handlers/mod.rs
Embed-phase error paths persistently tombstone chunks/summaries (body-read missing, embed errors, pack/dimension mismatches) by calling the new skip helpers with reason strings instead of only logging.
Regression test
src/openhuman/memory/tree/jobs/handlers/mod.rs
Adds a test that removes a staged chunk body, asserts a single tombstone write, verifies the next handler pass returns Done, and confirms the coverage probe marks the space covered.

Sync Status RPC

Layer / File(s) Summary
Module docs and imports
src/openhuman/memory/sync_status/rpc.rs
Clarifies resolved/pending semantics post-#1574 and adds rusqlite::Connection import for the new helper.
RPC refactor to query helper
src/openhuman/memory/sync_status/rpc.rs
Computes now_ms once and delegates aggregation to query_sync_statuses(conn, now_ms) instead of inline logic.
Query helper that uses embedding sidecar
src/openhuman/memory/sync_status/rpc.rs
Introduces query_sync_statuses which uses EXISTS on mem_tree_chunk_embeddings and treats dropped/reembed-skipped chunks as resolved for pending/processed calculations.
Tests for sidecar-driven counts and no active wave
src/openhuman/memory/sync_status/rpc.rs
Adds tests covering sidecar-driven pending/processed counts, no active wave when fully embedded, and dropped/reembed-skipped chunks counted as resolved.

Sequence Diagram(s)

(omitted — changes are schema, query, and helper updates; no new multi-component sequential control flow requiring diagram)

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • tinyhumansai/openhuman#2358: Proposes helpers to clear rows from the same *_reembed_skipped tables; directly related.

Possibly Related PRs

Suggested reviewers

  • graycyrus
  • senamakel

Poem

🐰 I hopped through logs and schema beds,
and planted tiny tombstone threads.
One mark to stop the looping chase,
neat PATH fixes, pnpm in place.
Cheers from a rabbit in the code-glade!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.
Title check ✅ Passed The title directly summarizes the three main coordinated bugfixes: IMMEDIATE-tx ingest, reembed skip-persistence, and Windows dev-script PATH fixes, matching the changeset's primary objectives.

✏️ 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 20 '26 12:05 coderabbitai[bot]

Thanks for the thorough review — all three points addressed in 09331d87.

[major] Tombstone exclusion path test coverage

Added reembed_backfill_tombstones_orphan_and_terminates in src/openhuman/memory/tree/jobs/handlers/mod.rs (right after the existing reembed_backfill_repopulates_then_completes scaffold you pointed at). It exercises the three invariants you called out, end-to-end:

  1. Seeds a chunk row + staged path, then fs::remove_file on the body to reproduce the in-wild orphan failure mode.
  2. Runs handle_reembed_backfill once → asserts JobOutcome::Defer and that mem_tree_chunk_reembed_skipped has exactly one row keyed by (chunk_id, sig).
  3. Runs the handler again → asserts JobOutcome::Done (the NOT EXISTS … reembed_skipped clause in the worklist excludes the tombstone).
  4. Runs the ensure_reembed_backfill migration probe inline → asserts has_uncovered = false, so the chain can't re-arm on the next config save.

That third assertion is the critical one — without it (3) the original 16-orphan → ~128 k warn → ~8 k defer runaway could silently regress and still pass the other two assertions.

[minor] summary_store alias

Added the use crate::openhuman::memory::tree::tree_source::store as summary_store; next to the existing chunk_store alias, and converted the three mark_summary_reembed_skipped calls in the reembed loop to use it. Kept the scope tight — the older fully-qualified tree_source::store:: calls at lines 465 / 486 / 531 / 745 in the same file are pre-existing (PR #2153) and out of this PR's diff, so I didn't sweep them up to keep the review-fix diff focused.

[minor] No path to un-tombstone

Filed #2358 to track. Scoped to a backend helper + optional admin RPC; explicitly noted the "sticky tombstone is intentional, manual operator action is the right interface" framing so we don't accidentally autocorrect them on the next PR.

CodeRabbit nit (SC2155)

While here, split export PATH="$(dirname "$PNPM_EXE"):$PATH" in scripts/run-dev-win.sh into a separate PNPM_DIR=$(…) + export PATH=… so a dirname failure surfaces with a real exit code instead of being eaten by the enclosing export. Single-line nit, fits the same review-fix commit.

Validation

  • cargo test --lib openhuman::memory::tree → 598 passed (including the new test)
  • cargo fmt --check → clean
  • cargo clippy -p openhuman --no-deps (matches the Rust Quality CI step) → no new warnings on touched files

sanil-23 avatar May 20 '26 15:05 sanil-23

@coderabbitai addressed in a45c5db6.

The "gate the wave anchor on unresolved chunks inside the window" finding is fixed: provider_pending.pending is now scoped to chunks within WAVE_WINDOW_MS of the provider's most recent chunk (joins provider_max, reuses the ?1 window param), so a stale out-of-window straggler can't resurrect an "active" wave. Lifetime chunks_pending is unchanged (still counts old stragglers).

Added the regression test you suggested — stale_out_of_window_pending_does_not_open_a_wave: old unresolved (30 min ago) + recent resolved ⇒ chunks_pending=1, batch_total=0. Module suite: 7 passed.

sanil-23 avatar May 21 '26 09:05 sanil-23

[!TIP] For best results, initiate chat on the files or code changes.

@sanil-23 Thanks for the update — the fix looks exactly right. Scoping provider_pending.pending to chunks within WAVE_WINDOW_MS of provider_max means a single stale out-of-window straggler can no longer anchor an active wave, while chunks_pending (lifetime count) still surfaces it to the operator so it isn't silently dropped. The regression test covers the precise edge case: a stale unresolved chunk produces batch_total=0 rather than reopening the wave — that's the invariant that would have been easiest to regress silently. 7/7 passing is a clean close on this thread.

coderabbitai[bot] avatar May 21 '26 09:05 coderabbitai[bot]