Repository navigation
feat(memory): Store one vector per embedding model and backfill in the heartbeat - #2542
Merged
Merged
Conversation
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
|
5 screenshot changes — 5 changed · 0 added · 0 removed Review screenshots in Frameshift |
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]>
thomasjiangcy
marked this pull request as ready for review
November 2, 2026 13:34
Recall and search already exclude expired memories, so embedding them spent the heartbeat budget on rows that vector search never returns.
thomasjiangcy
approved these changes
Nov 2, 2026
… 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]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ 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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Lets memory move from
openai/text-embedding-3-small(1536d) to a Voyage model such asvoyage/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_MODELto 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_idwas the primary key andstoreEmbedding()skipped any memory that already had a row.Schema (
0013_memory_embedding_models.sql)junior_memory_embeddingsis keyed on(memory_id, provider, model), so one memory can have a vector from the old model and one from the new model.embeddingis an untypedvector. Supported sizes are[1024, 1536]. The check constraint now requiresvector_dims(embedding) = dimensions.((embedding::vector(1024)) vector_cosine_ops) WHERE dimensions = 1024. Reads cast to the query's size and filterdimensionswith a literal, so Postgres can match it.EXPLAINon pgvector pg17 showsIndex Scan using junior_memory_embeddings_embedding_1024_hnsw_idx.vector(1536)tovectoronly 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 sameACCESS EXCLUSIVElock: about 90s on 20k rows, with reads and writes blocked.CREATE INDEX CONCURRENTLYprebuild (the 0062 pattern): Postgres rebuilds every partial or expression index on a column when the column type changes. A 1536 index prebuilt on the oldvector(1536)column loses its cast (the cast is a no-op on that type), and the rebuild then fails withcolumn does not have dimensions. I tested both on pg17. So the 1536 index can only be built after this migration.CONCURRENTLY(possible once the column is untyped), then have the migration check that it is valid and ready.Input type
PluginEmbedder.embedTextstakes an optionalinputType: "document" | "query". Memory writes and the backfill senddocument. Recall and search queries sendquery.embedTexts()maps it toproviderOptions.voyage.inputTypeforvoyage/*models only. I checked through AI Gateway that Voyage returns different vectors for the two types, and that it accepts only the camelCase key.voyage-4,voyage-4-lite, andvoyage-4-large.Backfill in the memory heartbeat
PluginEmbeddernow names itsproviderandmodelbefore any call, andHeartbeatHookContextgets the host embedder (createPluginEmbedder, bound toAI_EMBEDDING_MODEL).heartbeathook (Vercel cron, every minute) runsreembedMemories()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 EXISTSon the primary key, plussha256of the content in SQL, which matcheshashEmbeddedContent()). It pages by id so each run ends. Each batch is oneembedManycall 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.content_hashwent 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
EXISTSinstead of a join, so extra model rows don't inflate the counts.Cutover plan (junior-prod)
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.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.openai/text-embedding-3-smallrows. Until then, rollback means reverting Enable docs tools in the default tool catalog #590.Known limits
plugin.heartbeat.failedeach minute, so it is visible. I did not add skip logic for this.RECALL_MAX_VECTOR_DISTANCEstays 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-memorytests: 97 passed. The scenariomoves memory vectors to a new embedding model in the heartbeatruns the heartbeat hook with a 1024d model. It covers mixed sizes,documentinput type, vector search on the new model, a heartbeat rerun that embeds nothing, and the repair of a stalecontent_hash.drizzle-kit generatereports no schema drift.via @thomasjiangcy.
--
View Session [Sentry]