openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

Per-(row, model) embedding storage for memory_tree + event_log + segments

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

Summary

Replace the single embedding BLOB column on memory_tree chunks/summaries, episodic events, and conversation segments with a generic per-(row, model) join table. Each model gets its own row per entity, indexed by a model_signature string ("{provider}:{model_id}:{dim}"). Switching the embedder becomes a query-time lookup rather than a destructive re-embed; toggling between providers (e.g. cloud Voyage ↔ local bge-m3) is safe and reversible.

UnifiedMemory's vector_chunks and episodic_log are explicitly out of scope — vector_chunks is vestigial (the agent has moved to memory_tree for semantic memory) and episodic_log is FTS5-only with no embedding column.

Problem

The current schema attaches one embedding BLOB per entity with no provenance metadata. Provider switches produce three concrete failure modes — none of which are caught today:

Switch Failure mode
cloud Voyage 1024-d → all-minilm 384-d Cosine 0.0 on dim mismatch (unified/helpers.rs:64) — old vectors silently dropped from rerank. Loud but lossy.
cloud Voyage 1024-d → bge-m3 1024-d Silent. Same dim, different latent space. Cosine produces plausible scores between 0–1 that rank memories essentially at random. Retrieval is poisoned with no error, no Sentry event, no log line — only degraded answers.
Any switch back to a model used before Re-embed-on-switch does not exist anywhere; old vectors stay tagged with whatever produced them but the schema has no way to filter on that.

Affected tables:

Table File:line Used by
mem_tree_chunks memory/tree/store.rs:39+ memory_tree retrieval rerank
mem_tree_summaries memory/tree/store.rs:128+ memory_tree summary rerank
event_log memory/store/unified/events.rs:16-29 Episodic event semantic recall (Archivist)
conversation_segments memory/store/unified/segments.rs:15+ Segment-boundary cosine drift (Archivist)

This blocks the cloud-Voyage-in-memory_tree story safely shipping in the future, and means today's MemoryConfig.embedding_provider toggle is only safe if you never had embeddings before.

Solution

Pull the embedding column out of every affected table into a generic per-(row, model) join table. Identical schema everywhere:

CREATE TABLE IF NOT EXISTS <prefix>_embeddings (
  <parent_id>      TEXT    NOT NULL REFERENCES <parent>(<id>) ON DELETE CASCADE,
  model_signature  TEXT    NOT NULL,           -- "ollama:bge-m3:1024" | "cloud:embedding-v1:1024" | …
  vector           BLOB    NOT NULL,           -- packed f32
  dim              INTEGER NOT NULL,
  created_at       REAL    NOT NULL,
  PRIMARY KEY (<parent_id>, model_signature)
);
CREATE INDEX idx_<prefix>_embeddings_model ON <prefix>_embeddings(model_signature);

Four new tables: mem_tree_chunk_embeddings, mem_tree_summary_embeddings, event_embeddings, segment_embeddings.

At write time: one INSERT INTO <prefix>_embeddings per ingest, tagged with the active embedder's signature.

At query time: every cosine-rerank join filters on WHERE model_signature = ? for the active embedder. Rows without a matching-model vector are absent from semantic rerank but still surface via FTS5 / heuristic / graph recall — data is not lost, just outside vector reranking for that signature.

No vector is ever destroyed by a switch. Old (provider A) vectors stay on disk. Switch to B → only rows missing B's vector get embedded. Switch back to A → A's old vectors are still there, instant. Lazy backfill via scheduler_gate (#1073) keeps local-LLM load bounded.

Extend the EmbeddingProvider trait (embeddings/provider_trait.rs:7-13) with fn model_id(&self) -> &str; canonical signature is format!("{}:{}:{}", provider.name(), provider.model_id(), provider.dimensions()). Implementations in embeddings/{ollama,cloud,openai,noop}.rs — one-liner each.

Acceptance criteria

  • [ ] Per-model embedding tables exist — mem_tree_chunk_embeddings, mem_tree_summary_embeddings, event_embeddings, segment_embeddings defined and created via init SQL with the schema above.
  • [ ] EmbeddingProvider trait exposes model_id() + signature() — all four implementations (ollama, cloud, openai, noop) return stable strings; signature equality is the canonical "same vector space" check.
  • [ ] Write path uses the new tables — memory/tree/ingest.rs, memory/tree/tree_source/bucket_seal.rs, unified/events.rs (event insert), unified/segments.rs (segment-close embed) all write through the new tables tagged with the active embedder's signature.
  • [ ] Query path filters on model_signature — every cosine-rerank site in memory/tree/retrieval/{fetch,search,source,topic,drill_down,global}.rs, unified/events.rs recall, and unified/segments.rs boundary detection joins through the new tables WHERE model_signature = ?.
  • [ ] One-shot migration backfills legacy blobs — on init, if a row in mem_tree_chunks / mem_tree_summaries / event_log / conversation_segments has a non-null embedding blob and no corresponding row in the new table, copy the blob in tagged with the user's current active signature. Idempotent + re-runnable.
  • [ ] Lazy backfill worker exists — new module under memory/embeddings/backfill.rs finds rows in a parent table missing a matching-signature row in the embeddings table, enqueues them through scheduler_gate in bounded batches. Triggered on startup scan + on memory_tree.embedding_model / MemoryConfig.embedding_provider change.
  • [ ] Backfill progress surfaces in UI — reuse the memory_ingestion_status pill (#1126); no new UI surface.
  • [ ] Cross-signature isolation tested — writes tagged with signature A do not surface in queries asking for signature B. Property-style test seeds N entries under M signatures and queries each.
  • [ ] Provider-switch integration test — seed corpus under provider A, switch config to B, verify retrieval returns empty under B until backfill runs, then full results after backfill, then switch back to A and verify results are instant (no backfill needed).
  • [ ] Diff coverage ≥ 80% — the implementing PRs meet the changed-lines coverage gate (Vitest + cargo-llvm-cov, enforced by .github/workflows/coverage.yml).
  • [ ] Legacy embedding columns dropped — after migration soaks for one release, the embedding BLOB columns are removed from mem_tree_chunks, mem_tree_summaries, event_log, conversation_segments (Stage 3 PR).

Stage breakdown

This is too big for a single PR. Three stages, shipping independently.

Stage 1 — Schema + write path + dual-write/dual-read (flag-gated)

PR 1 — adds the four new tables and the per-table embedding-row read/write helpers; extends the EmbeddingProvider trait with model_id() + signature(); routes new writes through both the legacy embedding column AND the new table, and reads from new-table-first with legacy fallback. Behind a feature flag memory_per_model_embeddings = false by default. Default behavior unchanged for users; new code exercised in tests only.

Deliverables

  • New tables defined in memory/tree/store.rs, unified/events.rs, unified/segments.rs.
  • EmbeddingProvider::model_id() + signature() on all four impls.
  • Write path: dual-write into legacy column + new table.
  • Read path: prefer new table when flag is on, fall back to legacy column otherwise.
  • Unit tests for round-trip, cross-signature isolation, cascade delete.

Stage 2 — Migration + lazy backfill + flip default to true

PR 2 — one-shot migration that copies legacy embedding blobs into the new tables tagged with the user's current active signature. Lazy backfill worker that finds rows missing a vector for the active signature and embeds them through scheduler_gate with throttling + resumability. Flips memory_per_model_embeddings = true as the default. From here on, switching providers is safe.

Deliverables

  • Idempotent migration in init SQL block.
  • memory/embeddings/backfill.rs worker — generic over parent table + parent-id column.
  • Provider-switch trigger (config-change watcher).
  • UI progress via existing memory_ingestion_status pill.
  • Integration test: seed under provider A, switch to B, verify empty → backfill → full → switch back → instant.

Stage 3 — Drop the legacy columns (cleanup, 1 release later)

PR 3 — removes the embedding BLOB columns from mem_tree_chunks, mem_tree_summaries, event_log, conversation_segments. Removes the dual-write/dual-read fallback paths. Removes the feature flag.

Deliverables

  • ALTER TABLE drops in init SQL (idempotent — only drop if column exists).
  • All dual-path code removed; new tables are now the single source of truth.

Out of scope

  • vector_chunks (UnifiedMemory document chunks) — vestigial; not touched.
  • episodic_log — FTS5-only, no embedding column to migrate.
  • Pruner UI for old-model embeddings — disk-usage management is a follow-up.
  • Multi-model query-time blending (merging results from local + cloud simultaneously) — not asked for.
  • The actual nomic → bge-m3 default flip — independent change; ships before/after/in parallel.

Risks

Risk Mitigation
Disk growth — ~4 MB / 1000 rows / model. Power memory_tree users with deep summarisation history could see ~50–200 MB. Surface in settings. Optional follow-up pruner that drops vectors for "models not used in 30 days".
memory/tree/score/embed/mod.rs:46 defines EMBEDDING_DIM = 1024 as a compile-time constant; dim-validation code references it Becomes per-row metadata; ~5 test sites flip from "assert dim == EMBEDDING_DIM" to "assert dim == active embedder's dim".
Archivist code paths tightly coupled to segment + event lifecycle Existing agent/harness/archivist_tests.rs already exercises both — extend tests for signature isolation.
Backfill thrash if a user toggles often Worker only re-embeds missing rows, never re-embeds existing ones. scheduler_gate throttling.

Related

  • Sentry OPENHUMAN-TAURI-1X — 782 events on the legacy Ollama nomic-embed-text path; per-model storage is the structural fix that lets us safely move users to bge-m3 (or cloud) without destroying their existing vectors.
  • #1174 — memory_tree's switch to bge-m3 (1024-d, 8K context).
  • #1508 — MemoryConfig cloud-default (Voyage embedding-v1). The "silent same-dim" failure mode this issue addresses is most acute for users on this default who later opt into local AI.
  • #1252 / #1073 — scheduler_gate throttling that the backfill worker reuses.
  • #1126 — memory_ingestion_status pill the backfill progress reuses.

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

Posted a small Stage 1 PR for this so the slice is visible before the larger dogfood/full-suite pass:

  • #2010 adds per-model embedding tables for memory-tree chunks/summaries and unified-memory events/segments.
  • It intentionally keeps the legacy single-embedding columns untouched, so follow-up work can add dual-write/query-time model-signature filtering without a destructive migration.
  • Local focused verification before posting:
    • cargo fmt --all
    • cargo test embeddings_are_scoped_by_model_signature --lib → 4 passed
    • cargo check → completed successfully with existing warnings only after reusing the local OpenHuman target dir; the first worktree-local target attempt hit No space left on device.

This is only the schema/helper foundation for #1574, not the full read-path migration.

honor2030 avatar May 17 '26 15:05 honor2030