fix(embedding): guard provider responses against dimension mismatches#248
Conversation
Closes rohitg00#247. Embedding providers in src/providers/embedding/ trust that the API returns vectors matching their declared dimensions. None of them check result.length === this.dimensions. When that breaks, the failure is silent: src/state/vector-index.ts:10 returns 0 from cosineSimilarity on length mismatch, so a wrong-size vector gets stored, never matches anything, and the affected memory becomes invisible without a single error surfacing. Add a single dimension-check wrapper at the EmbeddingProvider boundary in createEmbeddingProvider() / createImageEmbeddingProvider(). Every provider inherits the guard for free; new providers added later are covered automatically. Throws a descriptive error naming the provider, the call site (embed / embedBatch[i] / embedImage), expected vs got dimensions. Tests cover the happy path and each method's mismatch path. Signed-off-by: ammarsaleh50 <ammar.alammar23@gmail.com>
|
@AmmarSaleh50 is attempting to deploy a commit to the rohitg00's projects Team on Vercel. A member of the Team first needs to authorize it. |
📝 WalkthroughWalkthroughAdds exported withDimensionGuard(provider) that enforces provider.dimensions on embed/embedBatch/(optional)embedImage outputs and wraps embedding factories; adds VectorIndex.validateDimensions(expected) and a restore-time check that compares persisted vectors to the active provider, optionally discarding or failing on mismatches; includes tests for the guard and index validation. ChangesEmbedding Dimension Validation & Index Safety
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/providers/embedding/index.ts (1)
52-55: ⚡ Quick winRemove the WHAT-style comment block and let naming carry intent
This block explains behavior in prose; repo guidelines for
src/**/*.tsask to avoid WHAT-comments.As per coding guidelines: “Avoid code comments explaining WHAT — use clear naming instead”.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/providers/embedding/index.ts` around lines 52 - 55, Delete the WHAT-style prose block that describes the silent failure and instead make the code self-describing: remove the comment and add/rename a boundary function in vector-index.ts to validate dimensions (e.g., ensureDimensionsMatchOrThrow) or rename cosineSimilarity to reflect its behavior (e.g., cosineSimilarityOrThrowOnDimensionMismatch), and call that validator/wrapper from the embedding entrypoint so mismatched-length vectors throw instead of silently returning 0; this keeps intent in names rather than a prose comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/providers/embedding/index.ts`:
- Around line 66-75: The wrapper currently constructs a plain object assigned to
wrapped which loses the provider's prototype and breaks instanceof checks (e.g.,
GeminiEmbeddingProvider, OpenAIEmbeddingProvider); instead create the wrapper
with the original prototype (use Object.create(provider)) so class identity is
preserved, then override/assign the name, dimensions, embed and embedBatch
properties while keeping embed/embedBatch calls wrapped with the existing
check(...) logic to validate outputs.
---
Nitpick comments:
In `@src/providers/embedding/index.ts`:
- Around line 52-55: Delete the WHAT-style prose block that describes the silent
failure and instead make the code self-describing: remove the comment and
add/rename a boundary function in vector-index.ts to validate dimensions (e.g.,
ensureDimensionsMatchOrThrow) or rename cosineSimilarity to reflect its behavior
(e.g., cosineSimilarityOrThrowOnDimensionMismatch), and call that
validator/wrapper from the embedding entrypoint so mismatched-length vectors
throw instead of silently returning 0; this keeps intent in names rather than a
prose comment.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 733047e6-120c-4fb4-8253-e272662741b7
📒 Files selected for processing (2)
src/providers/embedding/index.tstest/embedding-provider.test.ts
Address CodeRabbit review on rohitg00#248: the wrapper built a plain object instead of preserving the provider's prototype chain, which broke the existing toBeInstanceOf(GeminiEmbeddingProvider) / toBeInstanceOf(OpenAIEmbeddingProvider) checks against createEmbeddingProvider() in test/embedding-provider.test.ts. Switch the wrapper to Object.create(provider) so the prototype chain is preserved. `name` and `dimensions` fall through to the underlying provider; only `embed` / `embedBatch` / `embedImage` are overridden to insert the dimension check. Add a regression test asserting that `withDimensionGuard` preserves `instanceof`. Signed-off-by: ammarsaleh50 <ammar.alammar23@gmail.com>
|
This is a clean, well-thought fix. Reviewed end to end: Approach is right. Prototype-chain preservation is the detail that matters. Per-vector check on Test coverage is comprehensive. Good and bad paths for embed, embedBatch, and embedImage. The fake-provider helper is the right shape for this. Together with #246 (Gemini migration that explicitly passes No blockers. Approving — also in the land-soon bucket, holding for @rohitg00. Two things to consider after merge (not blocking):
|
|
Re-reviewed independently against the alternatives we'd consider, not just rubber-stamping. Conclusion: this is the right approach. Specifically: Why factory-boundary > the alternatives
The The per-vector index in Together with #246, your two PRs close the silent-corruption window front-to-back: #246 explicitly passes One real follow-up gap (not blocking this PR): The Worth a follow-up issue: validate dimensions against the active provider at Verdict: APPROVE. This was the highest-quality PR in the current backlog — issue + fix + tests in one well-scoped contribution. Strong work, @AmmarSaleh50. Holding for @rohitg00 to push the merge button. |
…atches active provider The factory-boundary dimension guard in this PR catches wrong-dim vectors on the live-API write path. The persistence restore path is the symmetric on-ramp: IndexPersistence.load() at src/state/index-persistence.ts:62-66 deserializes vectors directly from KV with no dimension check. If a user persists an index built against an N-dim provider and then swaps embedding configuration (EMBEDDING_PROVIDER, OPENAI_EMBEDDING_MODEL, local model upgrade, etc.), the restore brings old-dim vectors back into a freshly-instantiated VectorIndex while live observations write new-dim vectors alongside. cosineSimilarity returns 0 on every cross- dim pair — same silent recall degradation rohitg00#247 documents, just on a different on-ramp. This commit adds: 1. VectorIndex.firstDimensions() — exposes the dimension of any stored vector (or 0 if empty). All vectors in a single index are expected to share a dimension; the first entry is representative because the live-write path is now gated by the guard added earlier in this PR. 2. A startup check in src/index.ts after IndexPersistence.load(). When the persisted index has a different dimension than the active provider, the default behavior is to refuse to start with a clear error message: [agentmemory] Refusing to start: persisted vector index has dimension 384, but the active provider (openai) declares 1536. Loading would silently corrupt search (cross-dimension cosine returns 0). Choose one: - Re-embed the existing index against the new provider, then start. - Set AGENTMEMORY_DROP_STALE_INDEX=true to discard the persisted vectors and rebuild from live observations. - Switch the embedding provider back to the one that wrote the index. 3. Opt-in escape hatch: AGENTMEMORY_DROP_STALE_INDEX=true logs a warning, discards the persisted vectors, and lets the live path rebuild over time. Friendlier for users who deliberately swap providers. Test: VectorIndex.firstDimensions() returns 0 for empty and the correct size for populated indexes (small + 1536-dim). Closes rohitg00#256.
|
Pushed What the commit adds1. 2. Dimension validation at startup in
3. Test in Why it stays in scope
Tested locally:
If you'd rather have this as a separate PR for clean attribution / lighter review surface, say the word and I'll split it. But I think the bundle is more useful here. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/index.ts (1)
339-345: ⚡ Quick winTrim explanatory inline comments and rely on the guard logic + naming.
This block can stay clear without the added “what” comments.
As per coding guidelines, "Avoid code comments explaining WHAT — use clear naming instead".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/index.ts` around lines 339 - 345, Remove the verbose explanatory inline comments in the vector-dimension guard block and replace them with a concise comment that names the guard behavior; keep a short note like "Refuse to load vectors with mismatched dimension." and rely on the existing guard logic (the dimension check that refuses loading and the same defense used by the live-write path referenced in the code) and symbols such as cosineSimilarity to make intent clear; do not change the guard logic itself—only trim the explanatory text to a single-line summary.src/state/vector-index.ts (1)
69-72: ⚡ Quick winRemove inline “what” comments and keep this self-descriptive via naming.
These comments describe behavior directly and can be removed to align with the project convention.
♻️ Proposed cleanup
- // Dimension of any stored vector, or 0 if the index is empty. All vectors - // in a single index are expected to share the same dimension; the first - // entry is representative because the live-write path is gated by the - // dimension guard in src/providers/embedding/index.ts. firstDimensions(): number {As per coding guidelines, "Avoid code comments explaining WHAT — use clear naming instead".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/state/vector-index.ts` around lines 69 - 72, Remove the inline "what" comment block describing vector dimensions and make the code self-descriptive: delete the three-line comment and, if needed, rename the exposed identifier (e.g., dimension or vectorDimension/embeddingDimension) or add a clearer identifier so the comment's information is conveyed by the name of the variable/property in the vector index module (e.g., vectorDimension or embeddingDimension) and any brief docstring can be limited to why rather than what.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/index.ts`:
- Around line 346-348: The code currently uses loaded.vector.firstDimensions()
(persistedDim) to compare against embeddingProvider?.dimensions (activeDim),
which misses mixed-dimension entries; update the validation to iterate over all
persisted vectors in loaded.vector and verify each vector's dimension equals
activeDim (or fail/skip any that don't) instead of relying on firstDimensions();
apply the same fix to the other similar check around the second occurrence
(lines referenced in the review). Ensure you log or surface which vector(s) were
invalid and prevent restoring indexes containing mismatched-dimension vectors.
---
Nitpick comments:
In `@src/index.ts`:
- Around line 339-345: Remove the verbose explanatory inline comments in the
vector-dimension guard block and replace them with a concise comment that names
the guard behavior; keep a short note like "Refuse to load vectors with
mismatched dimension." and rely on the existing guard logic (the dimension check
that refuses loading and the same defense used by the live-write path referenced
in the code) and symbols such as cosineSimilarity to make intent clear; do not
change the guard logic itself—only trim the explanatory text to a single-line
summary.
In `@src/state/vector-index.ts`:
- Around line 69-72: Remove the inline "what" comment block describing vector
dimensions and make the code self-descriptive: delete the three-line comment
and, if needed, rename the exposed identifier (e.g., dimension or
vectorDimension/embeddingDimension) or add a clearer identifier so the comment's
information is conveyed by the name of the variable/property in the vector index
module (e.g., vectorDimension or embeddingDimension) and any brief docstring can
be limited to why rather than what.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 3ff42410-6f54-4f6f-af90-3e3af81c357d
📒 Files selected for processing (3)
src/index.tssrc/state/vector-index.tstest/vector-index-dimensions.test.ts
Review feedback on 57311c6: firstDimensions() only sampled the first stored vector. A legacy on-disk index that mixes dimensions inside one file (possible when a previous run swapped embedding model mid-session before the live-API guard in this PR existed) would slip past — the first vector might match while later ones don't, and the silent cross-dim cosine corruption returns through the back door. - Replace VectorIndex.firstDimensions() with validateDimensions(expected) that walks every entry, returns the obsIds whose dim doesn't match, and reports the set of distinct dims actually seen on disk. - src/index.ts now refuses to load whenever any single vector mismatches (not just the bulk dim). Error message reports how many of the total are bad, the distinct dims seen on disk, and the first 5 mismatched obsIds so the user can spot-check. - Test rewrite covers: empty index, all-match, partial mismatch (the case firstDimensions() missed), and entire-index mismatch. The reviewer also flagged "the other similar check around the second occurrence" — verified there is no second occurrence in the codebase. The only restoreFrom site is bm25Index.restoreFrom at src/index.ts:333 which restores a BM25 index that doesn't carry dimensions. Skipping.
|
Pushed Verification per finding
The only What changed
Validation
PR is now ready for merge from my side. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/state/vector-index.ts (1)
69-76: ⚡ Quick winRemove the explanatory WHAT block comment and rely on naming/types.
This comment narrates behavior rather than encoding intent in code, which conflicts with the repo rule for
src/**/*.ts.As per coding guidelines, "Avoid code comments explaining WHAT — use clear naming instead".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/state/vector-index.ts` around lines 69 - 76, Remove the multi-line explanatory WHAT comment above the vector-walking logic and rely on clear naming and types instead: delete that block and ensure the surrounding symbols (the function that walks stored vectors, and its return fields/variables named mismatches, seenDimensions, and expected) have descriptive names and proper TypeScript typings so the behavior is obvious without the long narrative comment.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/state/vector-index.ts`:
- Around line 69-76: Remove the multi-line explanatory WHAT comment above the
vector-walking logic and rely on clear naming and types instead: delete that
block and ensure the surrounding symbols (the function that walks stored
vectors, and its return fields/variables named mismatches, seenDimensions, and
expected) have descriptive names and proper TypeScript typings so the behavior
is obvious without the long narrative comment.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 25263d18-d616-414f-835a-3bb694367c83
📒 Files selected for processing (3)
src/index.tssrc/state/vector-index.tstest/vector-index-dimensions.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/index.ts
Bug-fix patch focused on search recall correctness and plugin compatibility. Pins iii-engine to v0.11.2 because v0.11.6 introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet — pin lifts once that refactor lands. Adds a hard guard against silent vector-index corruption, fixes BM25 indexing for memories saved via memory_save, and lands four Hermes plugin fixes. Per AGENTS.md release checklist: - package.json version 0.9.4 -> 0.9.5 - src/version.ts VERSION constant - src/types.ts ExportData version union - src/functions/export-import.ts supportedVersions Set - test/export-import.test.ts assertion - plugin/.claude-plugin/plugin.json version - CHANGELOG.md detailed entries with contributor shoutouts Headlines (full detail in CHANGELOG): Fixed: - BM25 search now indexes memories saved via memory_save (#258, #257) Thanks @Nizar-BenHamida for the precise repro. - Embedding providers no longer silently corrupt the vector index when an API returns wrong-dimension vectors (#248, #247, #256) Thanks @AmmarSaleh50 for issue + fix + tests. - Hermes handle_tool_call returns JSON strings, not raw dicts (#255, #254) Thanks @KyoMio for the Anthropic-protocol repro. - Hermes status reflects real service state on systemd installs (#253, #250) Thanks @OptionalCoin for tracing it to env-source divergence. - Hermes hooks accept passthrough kwargs (#252, #249) Thanks @OptionalCoin again for the log analysis. - agentmemory demo now seeds observations correctly (#251, #229) Thanks @seishonagon for root-cause analysis. - LLM compression / summarization timeouts increased (#213) Thanks @xuli500177. - Pi / OpenClaw / Hermes integration plugin fixes (#230) Thanks @deepmroot. Changed: - iii-engine pinned to v0.11.2 across every install path (#260). v0.11.6 introduces a new `iii worker add` sandbox model that agentmemory still pre-dates; pin lifts when we refactor agentmemory to register as a sandboxed worker. Override with AGENTMEMORY_III_VERSION=<version> for users who've migrated manually. - README documents iii worker add extension surface (#242). - README iii Console install/launch commands corrected (#243). Validated: 852/852 tests pass, npm run build clean.
Bug-fix patch focused on search recall correctness and plugin compatibility. Pins iii-engine to v0.11.2 because v0.11.6 introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet — pin lifts once that refactor lands. Adds a hard guard against silent vector-index corruption, fixes BM25 indexing for memories saved via memory_save, and lands four Hermes plugin fixes. Per AGENTS.md release checklist: - package.json version 0.9.4 -> 0.9.5 - src/version.ts VERSION constant - src/types.ts ExportData version union - src/functions/export-import.ts supportedVersions Set - test/export-import.test.ts assertion - plugin/.claude-plugin/plugin.json version - CHANGELOG.md detailed entries with contributor shoutouts Headlines (full detail in CHANGELOG): Fixed: - BM25 search now indexes memories saved via memory_save (#258, #257) Thanks @Nizar-BenHamida for the precise repro. - Embedding providers no longer silently corrupt the vector index when an API returns wrong-dimension vectors (#248, #247, #256) Thanks @AmmarSaleh50 for issue + fix + tests. - Hermes handle_tool_call returns JSON strings, not raw dicts (#255, #254) Thanks @KyoMio for the Anthropic-protocol repro. - Hermes status reflects real service state on systemd installs (#253, #250) Thanks @OptionalCoin for tracing it to env-source divergence. - Hermes hooks accept passthrough kwargs (#252, #249) Thanks @OptionalCoin again for the log analysis. - agentmemory demo now seeds observations correctly (#251, #229) Thanks @seishonagon for root-cause analysis. - LLM compression / summarization timeouts increased (#213) Thanks @xuli500177. - Pi / OpenClaw / Hermes integration plugin fixes (#230) Thanks @deepmroot. Changed: - iii-engine pinned to v0.11.2 across every install path (#260). v0.11.6 introduces a new `iii worker add` sandbox model that agentmemory still pre-dates; pin lifts when we refactor agentmemory to register as a sandboxed worker. Override with AGENTMEMORY_III_VERSION=<version> for users who've migrated manually. - README documents iii worker add extension surface (#242). - README iii Console install/launch commands corrected (#243). Validated: 852/852 tests pass, npm run build clean.
Bug-fix patch focused on search recall correctness and plugin compatibility. Pins iii-engine to v0.11.2 because v0.11.6 introduces a new sandbox-everything-via-`iii worker add` model that agentmemory hasn't been refactored for yet — pin lifts once that refactor lands. Adds a hard guard against silent vector-index corruption, fixes BM25 indexing for memories saved via memory_save, and lands four Hermes plugin fixes. Per AGENTS.md release checklist: - package.json version 0.9.4 -> 0.9.5 - src/version.ts VERSION constant - src/types.ts ExportData version union - src/functions/export-import.ts supportedVersions Set - test/export-import.test.ts assertion - plugin/.claude-plugin/plugin.json version - CHANGELOG.md detailed entries with contributor shoutouts Headlines (full detail in CHANGELOG): Fixed: - BM25 search now indexes memories saved via memory_save (#258, #257) Thanks @Nizar-BenHamida for the precise repro. - Embedding providers no longer silently corrupt the vector index when an API returns wrong-dimension vectors (#248, #247, #256) Thanks @AmmarSaleh50 for issue + fix + tests. - Hermes handle_tool_call returns JSON strings, not raw dicts (#255, #254) Thanks @KyoMio for the Anthropic-protocol repro. - Hermes status reflects real service state on systemd installs (#253, #250) Thanks @OptionalCoin for tracing it to env-source divergence. - Hermes hooks accept passthrough kwargs (#252, #249) Thanks @OptionalCoin again for the log analysis. - agentmemory demo now seeds observations correctly (#251, #229) Thanks @seishonagon for root-cause analysis. - LLM compression / summarization timeouts increased (#213) Thanks @xuli500177. - Pi / OpenClaw / Hermes integration plugin fixes (#230) Thanks @deepmroot. Changed: - iii-engine pinned to v0.11.2 across every install path (#260). v0.11.6 introduces a new `iii worker add` sandbox model that agentmemory still pre-dates; pin lifts when we refactor agentmemory to register as a sandboxed worker. Override with AGENTMEMORY_III_VERSION=<version> for users who've migrated manually. - README documents iii worker add extension surface (#242). - README iii Console install/launch commands corrected (#243). Validated: 852/852 tests pass, npm run build clean.
Closes #247.
What
Adds a dimension-check wrapper at the
EmbeddingProviderboundary insrc/providers/embedding/index.ts.createEmbeddingProvider()andcreateImageEmbeddingProvider()now wrap every provider so that any returnedFloat32Arraywhose length differs fromprovider.dimensionsthrows a descriptive error.Why
Embedding providers in
src/providers/embedding/(gemini, openai, voyage, cohere, openrouter, local, clip) trust that the API returns vectors matching their declared dimensions. None of them validateresult.length === this.dimensions. When the assumption breaks, the failure is silent:src/state/vector-index.ts:10returns0fromcosineSimilarityon length mismatch instead of throwing.This came up during review of #246 (gemini deprecation), where CodeRabbit flagged the gap on a single provider. Per-provider guards would be 7× duplication and easy to miss for new providers, so the fix lives at the factory boundary instead.
Changes
src/providers/embedding/index.tswithDimensionGuard(provider)that returns a wrapper checkingembed,embedBatch, and (when present)embedImageresults.createEmbeddingProvider()andcreateImageEmbeddingProvider()apply the wrapper to every constructed provider.embed/embedBatch[i]/embedImage), expected dimension, and actual dimension.test/embedding-provider.test.tsembedthrows.embedBatchthrows with the index.embedImageis guarded when present and absent when not.How to verify
npm install npm test -- test/embedding-provider.test.tsThe four new tests under
describe(\"withDimensionGuard\")should pass alongside the existing suite.Notes
new GeminiEmbeddingProvider(...), which is unwrapped, while only the factory entry points apply the guard.Summary by CodeRabbit
New Features
Tests