openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

fix(vault): sync writes to memory_tree, not legacy UnifiedMemory (#2705)

Open justinhsu1477 opened this issue 6 months ago • 8 comments

Closes #2705.

Root cause

vault::sync::sync_vault walked the directory, called doc_ingest → `MemoryClient::ingest_doc` → `UnifiedMemory::ingest_document` → `memory_docs` table. The UI's "synced" message was technically correct (UnifiedMemory accepted the writes), but every modern retrieval surface — `memory.search`, `tree.read_chunk`, `tree.browse`, the agent's recall path, the summary-tree builder — reads from the memory-tree backend (`mem_tree_chunks` + `mem_tree_ingested_sources`).

Vault data was invisible to all of them.

That explains the entire bug report:

Symptom Explanation
`mem_tree_chunks` = 0 vault sync never wrote there
`mem_tree_ingested_sources` = 0 same
"Memory wiped: 0 rows removed" wipe clears memory_tree, which was already empty
"Build summary trees" produces no jobs memory_tree has no chunks to summarise
UI "N file(s) · synced" vault state correctly reported the UnifiedMemory ingest succeeded — to the wrong table
Agent can't recall vault content agent retrieval reads memory_tree

Recent PRs (#2585, #2556, #2574) migrated RAG primitives to memory_tree as the canonical layer; the vault sync path was not migrated alongside.

Fix

`process_file` now calls `memory::ingest_pipeline::ingest_document` directly with a stable `source_id = vault:{vault_id}:{rel_path}`. The pipeline writes to `mem_tree_chunks` + `mem_tree_ingested_sources` — the tables the modern retrieval stack reads from.

Three design choices worth calling out:

  1. Content-update path — the pipeline's `already_ingested` gate is content-blind and the source_id is stable per file path. For real content updates the vault layer drops prior chunks via `memory_store::chunks::store::delete_chunks_by_source` before the re-ingest, otherwise new content gets short-circuited. The vault ledger's `content_hash` check still gates whether we run delete+reingest at all, so untouched files cost zero pipeline work.

  2. Deletion path (Phase 4) — `by_path` entries the walk didn't see now call `delete_chunks_by_source` instead of `doc_delete`. Migration-safe: ledger entries whose stored `document_id` doesn't start with `vault:` (rows persisted before this fix) fall back to a recomputed source_id.

  3. Vault ledger semantic — the `VaultFile.document_id` field now holds the memory-tree source_id. Schema column name unchanged for backward compatibility with persisted rows; only the semantic of what we store changed. Deletion uses the prefix-check above to handle the migration window cleanly.

Tests

Three new regression tests in `vault::sync::sync_tests`:

Test What it pins
`sync_writes_to_memory_tree` The #2705 regression. Creates a vault with two .md files, runs `sync_vault`, asserts `count_chunks` goes up + both source_ids appear in `mem_tree_ingested_sources` + ledger `document_id` starts with `vault:`
`second_sync_with_no_changes_is_idempotent` Re-sync with unchanged content does not duplicate chunks (vault-layer hash dedup guards the pipeline)
`vault_source_id_is_stable_and_namespaced` Unit test on the id format — defends against an accidental rename breaking cross-file isolation
  • [x] `cargo test --lib vault` — 28/28 pass.
  • [x] `cargo check --lib` — clean.
  • [x] `cargo fmt --check` — clean.
  • [x] `cargo test --tests --no-run` — clean (lesson from #2603 — integration-test target must compile).

Out of scope (separate audits / PRs)

  • Composio providers and `agent_experience` still call `doc_ingest` → UnifiedMemory. If they have the same gap, that's a separate audit; this PR is scoped to the vault path the user reported.
  • Removing `UnifiedMemory` entirely is the larger follow-up senamakel listed on #2585; out of scope here.

Refs #2705.

Summary by CodeRabbit

  • Improvements

    • Vault file synchronization now efficiently detects and skips redundant processing of unchanged content.
    • Improved cleanup of deleted vault files from the system.
  • Tests

    • Added regression tests for vault sync reliability and consistency.
    • Enhanced end-to-end test coverage for sync update, deletion, and addition workflows.

Review Change Stack

justinhsu1477 avatar May 27 '26 00:05 justinhsu1477

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ad689cff-1178-4a2a-94ca-0820e485138f

📥 Commits

Reviewing files that changed from the base of the PR and between f8b505437001bf01af8b4f8ba8ed9dbd6e90935a and 6f4324eab2a1d65d76f1f268d03bebdebfe1f5c2.

⛔ Files ignored due to path filters (1)
  • app/src-tauri/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • src/openhuman/vault/ops.rs
  • src/openhuman/vault/sync.rs
  • tests/vault_sync_e2e.rs
💤 Files with no reviewable changes (3)
  • tests/vault_sync_e2e.rs
  • src/openhuman/vault/ops.rs
  • src/openhuman/vault/sync.rs

📝 Walkthrough

Walkthrough

Vault sync has been rerouted to ingest per-file content through the memory-tree pipeline via stable per-file vault:{vault_id}:{rel_path} source IDs, with SHA-256-based change detection, pre-deletion of stale chunks, and migration support for legacy ledger entries. Regression tests and e2e assertions now validate memory-tree table population and idempotency.

Changes

Memory-tree migration and regression fix

Layer / File(s) Summary
Module setup and stable source ID helper
src/openhuman/vault/sync.rs (1–59)
Module documentation describes the memory-tree ingestion path and stable vault:{vault_id}:{rel_path} source-id semantics; vault_source_id(vault_id, rel_path) helper introduced.
Per-file data structures and process_file signature
src/openhuman/vault/sync.rs (132–139, 160–165)
FileToProcess struct reshaped to retain only memory-tree-specific fields (vault_id, prev_hash); process_file signature updated to accept Arc<Config> for routing through the memory-tree pipeline.
Per-file ingestion and change detection
src/openhuman/vault/sync.rs (179–296)
Compute SHA-256 content hash and return Unchanged when content matches prior hash; derive stable source_id and preemptively delete prior memory-tree chunks when content differs; build DocumentInput with vault/ext tags and call ingest_pipeline::ingest_document; map results to IngestFileResult with document_id set to the stable source_id.
Discovery wiring and concurrent ingestion
src/openhuman/vault/sync.rs (468–473, 491–498)
Discovery emits FileToProcess records with prev_hash and vault_id; concurrent ingestion shares a cloned Config via Arc so each worker calls process_file(Arc::clone(&config), file) for each candidate.
Memory-tree file deletion with legacy fallback
src/openhuman/vault/sync.rs (550–637)
Deletion driven by memory-tree delete_chunks_by_source; for pre-#2705 ledger rows with non-vault: prefixed document_id, recomputes stable vault_source_id for chunk deletion and performs best-effort doc_delete for UnifiedMemory migration cleanup.
Vault remove memory-tree purge wiring
src/openhuman/vault/ops.rs (118–190)
vault_remove purge_memory deletes chunks by vault:{id}: source-prefix in a blocking task, records memory_tree_chunks_deleted, returns error early when chunk deletion fails, and treats legacy clear_namespace as best-effort; RPC result includes memory_tree_chunks_deleted.
Regression and idempotency tests
src/openhuman/vault/sync.rs (699–1047), tests/vault_sync_e2e.rs (5–207)
New sync_tests module verifies mem_tree_chunks and mem_tree_ingested_sources population, validates ledger document_id encodes stable memory-tree source_ids, confirms unchanged re-sync is idempotent, adds `vault_remove(purge_memory=true

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • tinyhumansai/openhuman#1994: Both PRs modify the core vault ingestion/sync flow (notably src/openhuman/vault/sync.rs and src/openhuman/vault/ops.rs) and touch per-file ingestion semantics and memory-tree source-id usage.
  • tinyhumansai/openhuman#2243: Overlaps on vault sync refactoring and per-file deduplication/ingestion logic; related to sync status and content-hash handling.

Suggested labels

rust-core

Suggested reviewers

  • sanil-23
  • graycyrus

🐰 From memory's old attic to the tree so bright, Files synced with hashes, stable paths in sight, Chunks cleared and reingested with a tidy hum, Ledger rows now whisper vault: where they come, Hop—tests pass—now the memory tree can thrum! 🌿

🚥 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 pull request title 'fix(vault): sync writes to memory_tree, not legacy UnifiedMemory (#2705)' accurately and concisely describes the primary change: redirecting vault sync to write to the memory-tree backend instead of the legacy UnifiedMemory path.
Linked Issues check ✅ Passed The pull request fully addresses issue #2705 by implementing vault sync to write to mem_tree_chunks and mem_tree_ingested_sources, resolving the root cause of synced vault content remaining invisible to retrieval components.
Out of Scope Changes check ✅ Passed All changes are scoped to vault sync and removal logic, memory-tree ingestion integration, and comprehensive regression tests; the PR explicitly defers UnifiedMemory cleanup and composio/agent_experience audits as separate follow-ups.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

coderabbitai[bot] avatar May 27 '26 00:05 coderabbitai[bot]

justinhsu1477 could you please fix the tests and then push?

YellowSnnowmann avatar May 27 '26 08:05 YellowSnnowmann

@YellowSnnowmann thanks — pushed `f8b50543` about 5 min before your ping.

The failing test (`memory_ingestion_status_reflects_initialized_client_snapshot`) was asserting `queue_depth == 1` against the process-global `IngestionState`. Sibling tests in the same module call `spawn_manual_sync`, which detaches a `tokio::spawn(...)` that runs `composio::run_connection_sync` → `MemoryClient::store_skill_sync` → `IngestionQueue::submit` → `state.enqueue()`. That background task can still be draining when the snapshot test acquires `GLOBAL_MEMORY_TEST_LOCK`, so the global counter isn't 0.

Fix is to snapshot the baseline and assert the delta — pre-existing flake on `upstream/main`, the added vault sync tests just shifted the parallel-test ordering enough to expose it. Full reasoning in the commit body.

`cargo test --lib -- memory::ops::sync vault::sync` passes 9/9 locally; CI re-running now.

justinhsu1477 avatar May 27 '26 08:05 justinhsu1477

@sanil-23 thanks for the thorough pass — all four addressed in `e7c61b14` (rebased on `upstream/main` so the #2737 conflict is gone).

🛑 L378 conflict — Resolved by rebase: dropped my standalone `baseline_depth` commit since #2737 already landed the same de-flake with a cleaner `state.reset_for_test()` helper. Kept that, dropped mine.

L263 false-success — Added a `log::warn!` for the `already_ingested == true && chunks_written == 0` branch. The delete-first guard prevents this on the normal update path, so seeing it means ledger ↔ memory_tree desync — exactly the silent mode this PR exists to kill. Log line names the source_id + suggests a manual `delete_chunks_by_source` resync.

L474 per-file Config clone — Switched to `Arc`. `process_file` now takes `Arc`, the call site does one outer `Arc::new(config.clone())` then `Arc::clone(&...)` per candidate. A 5k-file backfill pays one deep clone + N ref-count bumps instead of N full clones.

L544 legacy fallback no-op — You're right, it was silently leaving legacy `memory_docs` rows behind. Migration-window fix: when `document_id` doesn't start with `vault:` (= pre-#2705 ledger row), the deletion path now runs `doc_delete(prev.document_id)` against UnifiedMemory in parallel with `delete_chunks_by_source` against the recomputed memory_tree source_id. `doc_delete` failures are best-effort (a 404 on the legacy path shouldn't block the canonical memory_tree cleanup).

`cargo test --lib -- memory::ops::sync vault::sync` → 9/9 pass. `cargo check --lib` + `cargo fmt --check` + `cargo test --tests --no-run` all clean.

Pushed as force-with-lease since the rebase was unavoidable.

justinhsu1477 avatar May 27 '26 11:05 justinhsu1477

I see @sanil-23 has requested changes — deferring to their feedback. Will review once those are addressed.

graycyrus avatar May 27 '26 15:05 graycyrus

@justinhsu1477 unresolved review feedback — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

Unresolved review feedback from sanil-23 — please address before we review.

graycyrus avatar May 27 '26 19:05 graycyrus

@graycyrus all four of @sanil-23's items were fully addressed in `e7c61b14` ~8 hours ago — the inline threads still show "unresolved" because I left a top-level summary instead of replying inline. Apologies for the noise; verifying-by-grep so you don't have to:

# sanil-23's point Fix in `e7c61b14`
🛑 L372 merge conflict Resolved by rebase onto current `main` (#2737's `state.reset_for_test()` is now upstream; my conflicting commit dropped) `git log --oneline upstream/main..HEAD`
L286 false-success edge `already_ingested && chunks_written == 0` now emits `log::warn!` naming the source_id + suggesting a manual `delete_chunks_by_source` resync `vault/sync.rs:L268-281`
Per-file `Config` clone `process_file` takes `Arc`; 5k-file backfill pays one deep clone + N atomic refs `vault/sync.rs:L165, L196, L496-498`
Legacy doc_id fallback no-op `is_legacy_ledger_row = !stored_id.starts_with("vault:")` triggers a parallel `doc_delete(prev.document_id)` against UnifiedMemory alongside the canonical `delete_chunks_by_source` `vault/sync.rs:L43, L574, L589-606`

Verification:

  • `cargo test --lib -- vault::sync memory::ops::sync` → 9/9 pass
  • `cargo check --lib` + `cargo fmt --check` + `cargo test --tests --no-run` clean
  • CI: 25 ok / 0 fail / 1 running at last snapshot (CodeRabbit re-APPROVED at 11:12)

Ready for re-review whenever you have cycles.

justinhsu1477 avatar May 27 '26 21:05 justinhsu1477

@justinhsu1477 followed up on the major item from sanil-23's top-level walkthrough (vault/ops.rs:116-136 — vault_remove(purge_memory=true) was still routing to the legacy backend) — fix pushed as 6f4324ea on top of e7c61b14.

What changed

  • vault_remove now runs delete_chunks_by_source_prefix(config, SourceKind::Document, "vault:{id}:") (mirrors the channels::clear_channel_memory pattern at channels/controllers/ops.rs:563) so vault content is purged from mem_tree_chunks + mem_tree_ingested_sources — the canonical retrieval surface — instead of being orphaned. The legacy clear_namespace call stays as best-effort cleanup for any pre-#2705 ledger rows still in memory_docs during the migration window. RPC response now surfaces memory_tree_chunks_deleted so the UI can show the real count.
  • Drive-by: hoisted Arc::new(config.clone()) out of sync.rs Phase 4's deletion loop — the per-iteration clone had quietly undone part of the Phase 2 worker-pool optimisation flagged earlier.

Tests

  • vault_remove_with_purge_clears_memory_tree — pins the regression: post-sync, vault_remove(purge_memory=true) drops the source from mem_tree_ingested_sources and shrinks count_chunks.
  • vault_remove_without_purge_leaves_memory_tree_intact — guards the boolean from silently flipping to always-purge.

Verification

  • cargo test --lib vault:: → 27/27 pass (including 2 new tests).
  • cargo test --test vault_sync_e2e → 1/1 pass.
  • cargo test --lib memory:: → 365/365 pass (smoke check).
  • cargo check --manifest-path Cargo.toml + cargo check --manifest-path app/src-tauri/Cargo.toml clean.
  • cargo fmt --check clean.

Re. the namespace question from the walkthrough ("is Vault.namespace still meaningful post-migration?") — left intact because it's still load-bearing for the best-effort legacy clear_namespace cleanup during the migration window. Removing it can ride the larger UnifiedMemory removal follow-up (#2585).

sanil-23 avatar May 28 '26 14:05 sanil-23

@coderabbitai review

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

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot] avatar May 28 '26 15:05 coderabbitai[bot]

Actionable comments posted: 0

coderabbitai[bot] avatar May 28 '26 15:05 coderabbitai[bot]