Skip to content

feat(memory): Store one vector per embedding model and backfill in the heartbeat - #2542

Merged
thomasjiangcy merged 4 commits into
mainfrom
feat/memory-embedding-model-migration
Nov 2, 2026
Merged

thomasjiangcy merged 4 commits into
mainfrom
feat/memory-embedding-model-migration

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Lets memory move from openai/text-embedding-3-small (1536d) to a Voyage model such as voyage/voyage-4-lite (1024d) without losing vector recall during the switch, and gives a rollback path. The backfill runs inside the deployment, so nobody needs production database credentials.

Before this change, setting AI_EMBEDDING_MODEL to a model with another vector size would fail validation. With a same-size model, vector recall would go empty right away and never recover: memory_id was the primary key and storeEmbedding() skipped any memory that already had a row.

Schema (0013_memory_embedding_models.sql)

  • junior_memory_embeddings is keyed on (memory_id, provider, model), so one memory can have a vector from the old model and one from the new model.
  • embedding is an untyped vector. Supported sizes are [1024, 1536]. The check constraint now requires vector_dims(embedding) = dimensions.
  • 1024 vectors get a partial HNSW index: ((embedding::vector(1024)) vector_cosine_ops) WHERE dimensions = 1024. Reads cast to the query's size and filter dimensions with a literal, so Postgres can match it. EXPLAIN on pgvector pg17 shows Index Scan using junior_memory_embeddings_embedding_1024_hnsw_idx.
  • No HNSW build over existing rows, so the lock is short. The type change from vector(1536) to vector only edits the catalog (no table rewrite), and the 1024 index is empty at upgrade time. On local pg17 with 20k 1536d rows, the whole migration took about 200ms. The earlier version rebuilt the 1536 HNSW index under the same ACCESS EXCLUSIVE lock: about 90s on 20k rows, with reads and writes blocked.
  • Why no CREATE INDEX CONCURRENTLY prebuild (the 0062 pattern): Postgres rebuilds every partial or expression index on a column when the column type changes. A 1536 index prebuilt on the old vector(1536) column loses its cast (the cast is a no-op on that type), and the rebuild then fails with column does not have dimensions. I tested both on pg17. So the 1536 index can only be built after this migration.
  • 1536 vectors have no ANN index for now. Vector search on them is an exact scan of the rows for that model: about 140ms on 20k rows locally. For prod this only matters until the switch to voyage-4-lite. If 1536 stays in use somewhere, a later migration can add the index with the 0062 pattern: prebuild it with CONCURRENTLY (possible once the column is untyped), then have the migration check that it is valid and ready.

Input type

  • PluginEmbedder.embedTexts takes an optional inputType: "document" | "query". Memory writes and the backfill send document. Recall and search queries send query.
  • Core embedTexts() maps it to providerOptions.voyage.inputType for voyage/* models only. I checked through AI Gateway that Voyage returns different vectors for the two types, and that it accepts only the camelCase key.
  • Added Gateway rates for voyage-4, voyage-4-lite, and voyage-4-large.

Backfill in the memory heartbeat

  • PluginEmbedder now names its provider and model before any call, and HeartbeatHookContext gets the host embedder (createPluginEmbedder, bound to AI_EMBEDDING_MODEL).
  • The memory plugin's heartbeat hook (Vercel cron, every minute) runs reembedMemories() in batches of 100 for up to 15s. The host stops waiting after 25s, so the budget leaves room for the batch in progress.
  • reembedMemories() selects live memories with no vector for the configured model and current content in one query (NOT EXISTS on the primary key, plus sha256 of the content in SQL, which matches hashEmbeddedContent()). It pages by id so each run ends. Each batch is one embedMany call plus an upsert, and commits on its own. When nothing is missing, a run is that one query: about 100ms with 50k memories on local pg17.
  • So a model change backfills itself after deploy. The heartbeat also repairs vectors that a failed or skipped write left out, and vectors whose content_hash went stale.
  • storeEmbedding() now checks for a vector of the current model instead of any model, so retries and duplicates during a switch get a new-model vector right away.

Other

  • The dashboard and the operational report count embedded memories with EXISTS instead of a join, so extra model rows don't inflate the counts.
  • Updated the memory plugin docs. They told readers to flush the table on a model change; they now describe the heartbeat backfill.

Cutover plan (junior-prod)

  1. Release, bump junior-prod, and deploy. The build runs junior upgrade (migration 0013, a short lock). From then on, OpenAI vectors are searched exactly without an ANN index, and the heartbeat fills any gaps for the current OpenAI model.
  2. Merge getsentry/junior-prod#590 (embeddingModelId: "voyage/voyage-4-lite") and deploy. The heartbeat embeds every memory with voyage-4-lite within a few minutes. Until then, vector search only finds memories that already have a Voyage vector, and full-text search finds all of them.
  3. Later: delete the old openai/text-embedding-3-small rows. Until then, rollback means reverting Enable docs tools in the default tool catalog #590.

Known limits

  • If one batch keeps failing (for example, the provider rejects a memory), each heartbeat retries the same first batch and the backfill stalls. The host logs plugin.heartbeat.failed each minute, so it is visible. I did not add skip logic for this.
  • RECALL_MAX_VECTOR_DISTANCE stays at 0.45. In a small spot check through the Gateway, related pairs scored about 0.39–0.57 distance on voyage-4-lite and 0.36–0.61 on 3-small, and unrelated pairs about 0.90 on both. So the cutoff seems to carry over, but the sample is too small to retune from.

Verification

  • pnpm typecheck (all packages), pnpm lint, pnpm file-length:check, Prettier.
  • @sentry/junior-memory tests: 97 passed. The scenario moves memory vectors to a new embedding model in the heartbeat runs the heartbeat hook with a 1024d model. It covers mixed sizes, document input type, vector search on the new model, a heartbeat rerun that embeds nothing, and the repair of a stale content_hash.
  • Core tests for the plugin model, memory plugin storage, heartbeat integration, client, and plugin CLI commands pass (real Postgres).
  • drizzle-kit generate reports no schema drift.
  • Ran migrations 0000–0013 on pgvector pg17 with 20k existing 1536 rows: 0013 took about 200ms in one transaction. Checked the 1024 index use and the exact-scan path for 1536.

via @thomasjiangcy.

--

View Session [Sentry]

…ckfill

Let memory move to a new embedding model without losing vector recall.

- Key junior_memory_embeddings on (memory_id, provider, model) and store
  untyped pgvector vectors, with one partial HNSW index per supported size
  (1024 and 1536). Reads only compare vectors of the query's model.
- Send inputType document/query on embedding calls. Core maps it to the
  Voyage provider option and ignores it for other models.
- Add 'junior memory reembed', an idempotent batched backfill for the
  configured embedding model. Plugin CLI actions get the host embedder.
- Count embedded memories with EXISTS so extra model rows do not inflate
  the dashboard and operational report.
@vercel

vercel Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Nov 2, 2026 2:17pm UTC

Request Review

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

5 screenshot changes — 5 changed · 0 added · 0 removed

Review screenshots in Frameshift

Conversation Attachment · Desktop
Conversation Attachment · Desktop
Changed
Conversation Attachment · Mobile
Conversation Attachment · Mobile
Changed
Conversation Attachment Modal · Desktop
Conversation Attachment Modal · Desktop
Changed
Conversation Child Agent Drawer · Desktop
Conversation Child Agent Drawer · Desktop
Changed
Conversation Child Agent Drawer · Mobile
Conversation Child Agent Drawer · Mobile
Changed

Production has no way to run the reembed CLI against its database, so
the memory plugin heartbeat now runs the backfill every minute with a
15s budget. A model change backfills itself after deploy, and vectors
that a failed or skipped write left out are repaired.

The host embedder now names its provider and model up front, so the
backfill selects missing vectors in one query instead of embedding a
probe batch, and memory writes check for a vector of the current model
instead of any model. The reembed CLI stays for manual runs.

Co-Authored-By: Thomas Jiang <[email protected]>
@sentry-junior sentry-junior Bot changed the title feat(memory): Store one vector per embedding model and add reembed backfill feat(memory): Store one vector per embedding model and backfill in the heartbeat Nov 2, 2026
@thomasjiangcy
thomasjiangcy marked this pull request as ready for review November 2, 2026 13:34
@github-actions github-actions Bot added the risk: high PR risk score: high label Nov 2, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread packages/junior-memory/src/reembed.ts Resolved
Recall and search already exclude expired memories, so embedding them
spent the heartbeat budget on rows that vector search never returns.
… CLI

The migration rebuilt the 1536 HNSW index over every existing vector
while it held an ACCESS EXCLUSIVE lock on junior_memory_embeddings.
On 20k vectors that build took about 90s, so recall and memory writes
would stall during junior upgrade.

A CONCURRENTLY prebuild cannot replace it. The type change to an
untyped vector rebuilds every partial or expression index on the
column, and an index on the old vector(1536) column cannot carry the
1536 cast. The migration now builds no HNSW graph over existing rows:
the type change only edits the catalog, and the 1024 index is empty.
1536 vectors have no ANN index and use exact search. A later migration
can add that index with a CONCURRENTLY prebuild.

The heartbeat now runs every backfill, so the reembed CLI command and
the CLI embedder are removed.

Co-Authored-By: Thomas Jiang <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b15558d. Configure here.

Comment thread packages/junior-memory/src/db/schema.ts Resolved
@thomasjiangcy
thomasjiangcy merged commit d8e1ce6 into main Nov 2, 2026
44 checks passed
@thomasjiangcy
thomasjiangcy deleted the feat/memory-embedding-model-migration branch November 2, 2026 14:27
thomasjiangcy pushed a commit that referenced this pull request Nov 2, 2026
Follow-up to #2542, which merged before this fix could be pushed. It
addresses [Cursor Bugbot's
finding](#2542 (comment))
on that PR.

Automatic recall puts the cosine distance cutoff in `WHERE`. That term
casts the stored vector to the query's size (`embedding::vector(N)`),
and the cast throws when a row holds a vector of another size.
`junior_memory_embeddings` now holds 1024 and 1536 vectors side by side,
and since #2542 the 1536 vectors have no HNSW index to narrow the scan.
Postgres does not promise to evaluate `dimensions = N` before the other
`WHERE` terms, so recall over mixed sizes could fail. For prod, that
would happen on a rollback to `text-embedding-3-small`.

**Change:** `embeddingWithinDistance()` wraps the cutoff in `CASE WHEN
dimensions = N THEN <distance> END <= max`. `CASE` is the documented way
to fix evaluation order. `ORDER BY` keeps the plain cast expression, so
1024 queries can still match the partial HNSW index.

**Notes**
- On pgvector pg17 with 3k rows of each size, I couldn't make the
unguarded query fail. With seq and index scans disabled, and with the
distance term written first, the planner still ran the cheaper
`dimensions` check first. So this makes an ordering guarantee explicit;
it doesn't fix a failure I reproduced.
- `EXPLAIN` gives the same plan shape with and without the `CASE` guard.
- I didn't add a test: the planner already orders these terms safely, so
a test couldn't show the difference.

**Checks:** `@sentry/junior-memory` typecheck, oxlint, and all 97 tests
pass.

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AC08SCGTC39P%3A1793597541.117479 -->

--

[View
Session](https://junior-prod.sentry.dev/conversations/slack%3AC08SCGTC39P%3A1793597541.117479)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC08SCGTC39P%3A1793597541.117479/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — b15558da Deployed Nov 2, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant