From 6f9a1a526f3c03a7dbccac240cf38e15874b611b Mon Sep 17 00:00:00 2001 From: Harsh Bhati Date: Fri, 23 Oct 2026 13:04:38 -0400 Subject: [PATCH 1/9] docs(platform): link the BYOK page to the full model evaluation --- docs/platform/features/byok.mdx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx index 6a57c6cd8..022499a43 100644 --- a/docs/platform/features/byok.mdx +++ b/docs/platform/features/byok.mdx @@ -124,3 +124,7 @@ Accuracy against cost for every model we tested. The green line marks the best a Scatter chart of accuracy against cost per 1,000 add requests on a log scale, one ring per model, each labelled with its accuracy. Mistral Nemo sits at the far left at $0.68 and 84.1%; Claude Opus 5.5 at the far right at $158.55 and 93.5%. A dashed gray line marks Mem0's default model (free tier) at 92.5%. A green shaded region holds the models above it for under $10 per 1,000 add requests, a gold one the models under $2 per 1,000 add requests, and a dashed green line marks the best accuracy available at each price. Tags mark our picks: best value, DeepSeek V4.1 Flash; best under $1, Amazon Nova Micro; best quality, Claude Opus 5.5. + + + Every model's accuracy, cost and latency, and a calculator for your monthly volume. + From d7f6328206b7e116af7c7d2fdbfca57580a98ee4 Mon Sep 17 00:00:00 2001 From: Harsh Bhati Date: Fri, 23 Oct 2026 13:09:33 -0400 Subject: [PATCH 2/9] docs(platform): link the evaluation in a closing line instead of a card --- docs/platform/features/byok.mdx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx index 022499a43..7b26c46ea 100644 --- a/docs/platform/features/byok.mdx +++ b/docs/platform/features/byok.mdx @@ -125,6 +125,4 @@ Accuracy against cost for every model we tested. The green line marks the best a Scatter chart of accuracy against cost per 1,000 add requests on a log scale, one ring per model, each labelled with its accuracy. Mistral Nemo sits at the far left at $0.68 and 84.1%; Claude Opus 5.5 at the far right at $158.55 and 93.5%. A dashed gray line marks Mem0's default model (free tier) at 92.5%. A green shaded region holds the models above it for under $10 per 1,000 add requests, a gold one the models under $2 per 1,000 add requests, and a dashed green line marks the best accuracy available at each price. Tags mark our picks: best value, DeepSeek V4.1 Flash; best under $1, Amazon Nova Micro; best quality, Claude Opus 5.5. - - Every model's accuracy, cost and latency, and a calculator for your monthly volume. - +You can see every model's accuracy, cost and latency, and a calculator for your monthly volume, in the [full evaluation](https://mem0.ai/blog/bring-your-own-key-accuracy-cost-latency-by-model). From a34ebb0f69fe1f8687c9dc5bc92bc43b1183f449 Mon Sep 17 00:00:00 2001 From: Harsh Bhati Date: Fri, 23 Oct 2026 13:10:43 -0400 Subject: [PATCH 3/9] docs(platform): match the evaluation line to the page's wording --- docs/platform/features/byok.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx index 7b26c46ea..f2514c7bc 100644 --- a/docs/platform/features/byok.mdx +++ b/docs/platform/features/byok.mdx @@ -125,4 +125,4 @@ Accuracy against cost for every model we tested. The green line marks the best a Scatter chart of accuracy against cost per 1,000 add requests on a log scale, one ring per model, each labelled with its accuracy. Mistral Nemo sits at the far left at $0.68 and 84.1%; Claude Opus 5.5 at the far right at $158.55 and 93.5%. A dashed gray line marks Mem0's default model (free tier) at 92.5%. A green shaded region holds the models above it for under $10 per 1,000 add requests, a gold one the models under $2 per 1,000 add requests, and a dashed green line marks the best accuracy available at each price. Tags mark our picks: best value, DeepSeek V4.1 Flash; best under $1, Amazon Nova Micro; best quality, Claude Opus 5.5. -You can see every model's accuracy, cost and latency, and a calculator for your monthly volume, in the [full evaluation](https://mem0.ai/blog/bring-your-own-key-accuracy-cost-latency-by-model). +The [full evaluation](https://mem0.ai/blog/bring-your-own-key-accuracy-cost-latency-by-model) has the accuracy, cost and latency of every model we tested, and a calculator for your monthly volume. From 26cdefb46600c0fa5953c4b5ee5003c125539fc4 Mon Sep 17 00:00:00 2001 From: harsh-mem0 Date: Mon, 26 Oct 2026 10:51:39 -0400 Subject: [PATCH 4/9] docs(platform): add the pricing FAQ page (#7711) --- docs/docs.json | 3 +- docs/llms.txt | 1 + docs/platform/pricing.mdx | 96 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 docs/platform/pricing.mdx diff --git a/docs/docs.json b/docs/docs.json index c3ffd6d87..b694e288a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -116,7 +116,8 @@ "group": "Support", "icon": "life-buoy", "pages": [ - "platform/faqs" + "platform/faqs", + "platform/pricing" ] }, { diff --git a/docs/llms.txt b/docs/llms.txt index 7ceef9578..f13e2fc07 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -225,6 +225,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st ### Support & Migration - [FAQs](https://docs.mem0.ai/platform/faqs) [Platform]: Use when answering common Platform questions. +- [Pricing FAQ](https://docs.mem0.ai/platform/pricing) [Platform]: Use when a user asks how the October 26, 2026 pricing change affects their plan - existing Starter, Growth and Pro plans, free plan limits and the 30-day period, connecting their own LLM key, Vercel accounts and usage-based billing. - [Contribute to Platform](https://docs.mem0.ai/platform/contribute) [Platform]: Use when a user wants to contribute to Platform docs or code. - [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed. - [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions. diff --git a/docs/platform/pricing.mdx b/docs/platform/pricing.mdx new file mode 100644 index 000000000..5d27d8252 --- /dev/null +++ b/docs/platform/pricing.mdx @@ -0,0 +1,96 @@ +--- +title: "Pricing FAQ" +sidebarTitle: "Pricing" +description: "Frequently asked questions about Mem0's plans, limits and using your own LLM key." +icon: "credit-card" +--- + +## Existing paid plans + + + + Nothing. Your price, limits, extra usage and billing date stay the same, and you can still turn extra usage on or off from your dashboard. These plans are no longer sold to new accounts. + + + Plan changes now go through our team. If you need higher limits or more features, [talk to us](https://app.mem0.ai/enterprise?ref=docs) and we'll set up a custom plan. If you cancel, your account moves to the free plan, any extra usage up to then is billed on your last invoice, and the old plan can't be restarted. + + + +## Free plan + + + + For your first 30 days, Mem0 pays for the model calls, with limits of 10,000 adds and 1,000 retrievals a month. After that, connect your own LLM key to keep adding memories, and your limits go up to 50,000 adds and 10,000 retrievals a month at no charge from Mem0. You can connect a key at any time, including during your first 30 days. + + + If you signed up before October 26, 2026, you have until November 25, 2026. Otherwise, your 30 days start on the day you sign up. + + + Your memories stay, and searches keep working up to 1,000 a month. New adds return an error until you connect a key. + + + Calls past the limit return an error until your limits reset next month. + + + Yes. We email the organization owner at 50%, 80% and 100% of each monthly limit, and of your usage-based billing cap. + + + +## Your own LLM key + + + + Adding a memory runs language model calls that extract and organize it. With your key, those calls bill to your provider account. That is how we keep the free plan free at higher limits. + + + It depends on the model. Our recommended models cost about \$3.55 to \$5.34 per 1,000 adds: GPT-6 Luna on OpenAI, Claude Haiku 5.5 on Anthropic and DeepSeek V4.1 Flash on OpenRouter. The [BYOK guide](/platform/features/byok#choose-a-model) compares accuracy and cost across every model we tested. + + + OpenAI, Anthropic, Azure OpenAI and OpenRouter. + + + Yes. The text you add is sent to your provider under your account and its terms. Mem0 stores your key encrypted, never shows it again after you save it, and you can remove it at any time. + + + Organization owners, in **Settings → BYOK**. One key covers every project in the organization. + + + Adds fail with a reason you can see in the dashboard, and we email the organization owner, at most once a day. Mem0 doesn't switch to its own key, so send the failed adds again once the key works. Searches keep working. + + + Your limits go back to the ones without a key, and usage-based billing stops until you connect a key again. Anything you used before removing it is still billed on your next invoice. + + + +## Vercel + + + + Nothing changes. Your plan is billed through Vercel. Organizations created through the Vercel Marketplace are managed from Vercel and can't use BYOK. + + + +## Need more + + + + Once you've connected your own key, you can turn on usage-based billing from your dashboard and set a monthly spending cap. For SSO, an SLA or a contract, [talk to us](https://app.mem0.ai/enterprise?ref=docs). + + + You pay only for adds and retrievals above your free limits, billed once a month. The rate is shown when you turn it on, and those extra calls stop when you reach your monthly cap. + + + Yes, at any time from your dashboard. If you turn it off, you're still billed for what you used before. + + + +## Learn more + + + + Connect your provider key, pick a model and fix failed adds. + + + Accuracy, cost and latency for every model we tested. + + From d2b8432b772a5923ab5ba145cf1ae2a9f8b1c3f2 Mon Sep 17 00:00:00 2001 From: harsh-mem0 Date: Fri, 30 Oct 2026 17:35:20 -0400 Subject: [PATCH 5/9] fix(ts): never re-create a deleted memory when update races delete (#7788) --- mem0-ts/src/oss/src/memory/index.ts | 10 +- mem0-ts/src/oss/src/tests/chroma.test.ts | 35 +++- mem0-ts/src/oss/src/tests/mongodb.test.ts | 30 +++- mem0-ts/src/oss/src/tests/pinecone.test.ts | 32 +++- .../oss/src/vector_stores/azure_ai_search.ts | 8 +- .../src/oss/src/vector_stores/azure_mysql.ts | 8 +- mem0-ts/src/oss/src/vector_stores/base.ts | 3 +- mem0-ts/src/oss/src/vector_stores/chroma.ts | 13 +- .../src/oss/src/vector_stores/databricks.ts | 9 +- .../oss/src/vector_stores/elasticsearch.ts | 11 +- mem0-ts/src/oss/src/vector_stores/memory.ts | 5 +- mem0-ts/src/oss/src/vector_stores/mongodb.ts | 5 +- .../src/vector_stores/neptune_analytics.ts | 7 +- .../src/oss/src/vector_stores/opensearch.ts | 13 +- mem0-ts/src/oss/src/vector_stores/oracledb.ts | 6 +- mem0-ts/src/oss/src/vector_stores/pgvector.ts | 5 +- mem0-ts/src/oss/src/vector_stores/pinecone.ts | 7 +- mem0-ts/src/oss/src/vector_stores/qdrant.ts | 19 +- mem0-ts/src/oss/src/vector_stores/redis.ts | 43 ++++- .../oss/src/vector_stores/upstash_vector.ts | 12 +- mem0-ts/src/oss/src/vector_stores/valkey.ts | 47 ++++- mem0-ts/src/oss/src/vector_stores/weaviate.ts | 11 +- .../src/oss/tests/elasticsearch.unit.test.ts | 33 +++- mem0-ts/src/oss/tests/memory.crud.test.ts | 24 +++ mem0-ts/src/oss/tests/opensearch.unit.test.ts | 40 +++++ mem0-ts/src/oss/tests/oracledb.unit.test.ts | 38 ++++ mem0-ts/src/oss/tests/pgvector.unit.test.ts | 25 +++ .../oss/tests/qdrant-keyword-search.test.ts | 22 +++ mem0-ts/src/oss/tests/redis.unit.test.ts | 125 +++++++++++-- .../src/oss/tests/upstash_vector.unit.test.ts | 44 ++++- mem0-ts/src/oss/tests/valkey.test.ts | 136 ++++++++++++++ .../src/oss/tests/vector-store.unit.test.ts | 11 +- .../oss/tests/vector-stores-compat.test.ts | 169 +++++++++++++++++- 33 files changed, 934 insertions(+), 72 deletions(-) diff --git a/mem0-ts/src/oss/src/memory/index.ts b/mem0-ts/src/oss/src/memory/index.ts index 42f3ca22e..00fdc7d97 100644 --- a/mem0-ts/src/oss/src/memory/index.ts +++ b/mem0-ts/src/oss/src/memory/index.ts @@ -1990,7 +1990,15 @@ export class Memory { updatedAt: new Date().toISOString(), }; - await this.vectorStore.update(memoryId, embedding, newMetadata); + const updated = await this.vectorStore.update( + memoryId, + embedding, + newMetadata, + ); + // The memory was deleted between the get above and this write. + if (updated === false) { + throw new Error(`Memory with ID ${memoryId} not found`); + } await this.db.addHistory( memoryId, prevValue, diff --git a/mem0-ts/src/oss/src/tests/chroma.test.ts b/mem0-ts/src/oss/src/tests/chroma.test.ts index 3b51e7eef..6efb2df2f 100644 --- a/mem0-ts/src/oss/src/tests/chroma.test.ts +++ b/mem0-ts/src/oss/src/tests/chroma.test.ts @@ -271,14 +271,47 @@ describe("get", () => { describe("update", () => { it("updates a single record with embedding and metadata", async () => { + __mocks__.get.mockResolvedValue({ ids: ["vec-1"], metadatas: [{}] }); const db = await initDb(); - await db.update("vec-1", [1, 2, 3], { text: "updated" }); + expect(await db.update("vec-1", [1, 2, 3], { text: "updated" })).toBe(true); expect(__mocks__.update).toHaveBeenCalledWith({ ids: ["vec-1"], embeddings: [[1, 2, 3]], metadatas: [{ text: "updated" }], }); }); + + it("returns false and inserts nothing when the id does not exist", async () => { + const db = await initDb(); + expect(await db.update("missing", [1, 2, 3], { text: "x" })).toBe(false); + expect(__mocks__.get).toHaveBeenCalledWith({ + ids: ["missing"], + include: [], + }); + expect(__mocks__.add).not.toHaveBeenCalled(); + expect(__mocks__.upsert).not.toHaveBeenCalled(); + }); + + it("returns undefined, not an error, when the read-back after a landed update fails", async () => { + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const db = await initDb(); + __mocks__.get.mockRejectedValueOnce(new Error("chroma unavailable")); + expect(await db.update("vec-1", [1, 2, 3], { text: "x" })).toBeUndefined(); + expect(__mocks__.update).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + }); + + it("supports a payload-only update", async () => { + __mocks__.get.mockResolvedValue({ ids: ["vec-1"], metadatas: [{}] }); + const db = await initDb(); + expect(await db.update("vec-1", null as any, { text: "only" })).toBe(true); + expect(__mocks__.update).toHaveBeenCalledWith({ + ids: ["vec-1"], + embeddings: undefined, + metadatas: [{ text: "only" }], + }); + }); }); describe("delete", () => { diff --git a/mem0-ts/src/oss/src/tests/mongodb.test.ts b/mem0-ts/src/oss/src/tests/mongodb.test.ts index fe847b56c..d6600bf04 100644 --- a/mem0-ts/src/oss/src/tests/mongodb.test.ts +++ b/mem0-ts/src/oss/src/tests/mongodb.test.ts @@ -330,7 +330,9 @@ describe("MongoDB Vector Store", () => { it("should update document correctly", async () => { mockUpdateOne.mockResolvedValue({ matchedCount: 1 }); - await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" }); + expect( + await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" }), + ).toBe(true); expect(mockUpdateOne).toHaveBeenCalledWith( { _id: "id1" }, @@ -343,6 +345,32 @@ describe("MongoDB Vector Store", () => { ); }); + it("should return false and not insert when updating a missing id", async () => { + mockUpdateOne.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }); + await store.initialize(); + mockInsertOne.mockClear(); + + expect(await store.update("missing", [0.1, 0.2, 0.3, 0.4], {})).toBe(false); + expect(mockUpdateOne.mock.calls[0][2]?.upsert).toBeFalsy(); + expect(mockInsertOne).not.toHaveBeenCalled(); + expect(mockInsertMany).not.toHaveBeenCalled(); + }); + + it("should return undefined when the write is unacknowledged", async () => { + mockUpdateOne.mockResolvedValue({ acknowledged: false, matchedCount: 0 }); + expect(await store.update("id1", [0.1, 0.2, 0.3, 0.4], {})).toBeUndefined(); + }); + + it("should merge a payload-only update without touching the embedding", async () => { + mockUpdateOne.mockResolvedValue({ matchedCount: 1 }); + + expect(await store.update("id1", null as any, { name: "bob" })).toBe(true); + expect(mockUpdateOne).toHaveBeenCalledWith( + { _id: "id1" }, + { $set: { "payload.name": "bob" } }, + ); + }); + it("should delete document correctly", async () => { mockDeleteOne.mockResolvedValue({ deletedCount: 1 }); diff --git a/mem0-ts/src/oss/src/tests/pinecone.test.ts b/mem0-ts/src/oss/src/tests/pinecone.test.ts index 3c008538e..5342d7a49 100644 --- a/mem0-ts/src/oss/src/tests/pinecone.test.ts +++ b/mem0-ts/src/oss/src/tests/pinecone.test.ts @@ -9,12 +9,13 @@ // so `beforeEach` can reach them before the lazy import has fired; the factory, // which runs on first use, just returns a reference to the Pinecone class mock. const upsert = jest.fn().mockResolvedValue(undefined); +const update = jest.fn().mockResolvedValue(undefined); const query = jest.fn().mockResolvedValue({ matches: [] }); const fetch = jest.fn().mockResolvedValue({ records: {} }); const deleteOne = jest.fn().mockResolvedValue(undefined); const deleteAll = jest.fn().mockResolvedValue(undefined); -const nsHandle = { upsert, query, fetch, deleteOne, deleteAll }; +const nsHandle = { upsert, update, query, fetch, deleteOne, deleteAll }; const namespace = jest.fn().mockReturnValue(nsHandle); const describeIndexStats = jest @@ -26,6 +27,7 @@ const indexHandle = { describeIndexStats, // expose ops directly for the no-namespace path upsert, + update, query, fetch, deleteOne, @@ -45,6 +47,7 @@ const Pinecone = jest.fn().mockImplementation(() => ({ const __mocks__ = { upsert, + update, query, fetch, deleteOne, @@ -104,6 +107,7 @@ beforeEach(() => { const nsHandle = { upsert: __mocks__.upsert, + update: __mocks__.update, query: __mocks__.query, fetch: __mocks__.fetch, deleteOne: __mocks__.deleteOne, @@ -114,6 +118,7 @@ beforeEach(() => { namespace: __mocks__.namespace, describeIndexStats: __mocks__.describeIndexStats, upsert: __mocks__.upsert, + update: __mocks__.update, query: __mocks__.query, fetch: __mocks__.fetch, deleteOne: __mocks__.deleteOne, @@ -399,14 +404,27 @@ describe("get", () => { }); describe("update", () => { - it("upserts a single record", async () => { + it("updates by id and never upserts", async () => { const db = await initDb(); - await db.update("vec-1", [1, 2, 3, 4], { text: "updated" }); - expect(__mocks__.upsert).toHaveBeenCalledWith({ - records: [ - { id: "vec-1", values: [1, 2, 3, 4], metadata: { text: "updated" } }, - ], + await expect( + db.update("vec-1", [1, 2, 3, 4], { text: "updated" }), + ).resolves.toBeUndefined(); + expect(__mocks__.update).toHaveBeenCalledWith({ + id: "vec-1", + values: [1, 2, 3, 4], + metadata: { text: "updated" }, }); + expect(__mocks__.upsert).not.toHaveBeenCalled(); + }); + + it("payload-only update leaves the vector values alone", async () => { + const db = await initDb(); + await db.update("vec-1", null as any, { text: "renamed" }); + expect(__mocks__.update).toHaveBeenCalledWith({ + id: "vec-1", + metadata: { text: "renamed" }, + }); + expect(__mocks__.upsert).not.toHaveBeenCalled(); }); }); diff --git a/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts b/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts index 52576aca0..84117718b 100644 --- a/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts +++ b/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts @@ -474,7 +474,7 @@ export class AzureAISearch implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const document: Record = { id: vectorId }; @@ -493,15 +493,19 @@ export class AzureAISearch implements VectorStore { } } - const response = await this.searchClient.mergeOrUploadDocuments([document]); + const response = await this.searchClient.mergeDocuments([document]); for (const result of response.results) { + if (result.statusCode === 404) { + return false; + } if (!result.succeeded) { throw new Error( `Update failed for document ${vectorId}: ${result.errorMessage}`, ); } } + return true; } /** diff --git a/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts b/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts index 123767484..d525fcca7 100644 --- a/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts +++ b/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts @@ -1,4 +1,4 @@ -import type { Pool, RowDataPacket } from "mysql2/promise"; +import type { Pool, ResultSetHeader, RowDataPacket } from "mysql2/promise"; import { VectorStore } from "./base"; import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types"; import { loadPeer } from "../utils/load_peer"; @@ -275,16 +275,18 @@ export class AzureMySQLDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const conn = await this.pool!.getConnection(); try { await conn.beginTransaction(); - await conn.execute( + // mysql2 sets CLIENT_FOUND_ROWS by default, so affectedRows counts matched rows. + const [result] = await conn.execute( `UPDATE ${this.col()} SET vector = ?, payload = ? WHERE id = ?`, [JSON.stringify(vector), JSON.stringify(payload), vectorId], ); await conn.commit(); + return result.affectedRows > 0; } catch (err) { await conn.rollback(); throw err; diff --git a/mem0-ts/src/oss/src/vector_stores/base.ts b/mem0-ts/src/oss/src/vector_stores/base.ts index 975541cf8..970981274 100644 --- a/mem0-ts/src/oss/src/vector_stores/base.ts +++ b/mem0-ts/src/oss/src/vector_stores/base.ts @@ -17,11 +17,12 @@ export interface VectorStore { filters?: SearchFilters, ): Promise; get(vectorId: string): Promise; + /** Must not create a record. true: record changed; false: id does not exist; void: the store cannot tell. */ update( vectorId: string, vector: number[], payload: Record, - ): Promise; + ): Promise; delete(vectorId: string): Promise; deleteCol(): Promise; list( diff --git a/mem0-ts/src/oss/src/vector_stores/chroma.ts b/mem0-ts/src/oss/src/vector_stores/chroma.ts index bec0e961a..994b0a596 100644 --- a/mem0-ts/src/oss/src/vector_stores/chroma.ts +++ b/mem0-ts/src/oss/src/vector_stores/chroma.ts @@ -186,13 +186,24 @@ export class ChromaDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { const collection = await this.getCollection(); await collection.update({ ids: [vectorId], embeddings: vector ? [vector] : undefined, metadatas: payload ? [payload] : undefined, } as any); + // Chroma skips unknown ids on update without an error, so check existence after the write. + try { + const existing = await collection.get({ ids: [vectorId], include: [] }); + return existing.ids.length > 0; + } catch (error) { + // The write already ran; failing here would surface an error for a landed update. + console.warn( + `Chroma update of '${vectorId}' could not be confirmed:`, + error, + ); + } } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/databricks.ts b/mem0-ts/src/oss/src/vector_stores/databricks.ts index 627e522ee..f09e8f2b5 100644 --- a/mem0-ts/src/oss/src/vector_stores/databricks.ts +++ b/mem0-ts/src/oss/src/vector_stores/databricks.ts @@ -665,7 +665,7 @@ export class DatabricksVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); this.assertVectorDimension(vector, "Vector"); @@ -673,7 +673,8 @@ export class DatabricksVectorStore implements VectorStore { // are written once at insert(). Mirror Python's `excluded_keys`: update() must never rewrite // them from the payload -- a partial payload that omits these keys would otherwise SET them to // NULL and hide the row from every session-scoped search and list(). - await this.executeSql(` + // A Delta UPDATE returns one row with num_affected_rows; without it we cannot tell. + const rows = await this.executeSql(` UPDATE ${this.fullTableName} SET embedding = ${formatSqlValue(vector)}, payload = ${formatSqlValue(JSON.stringify(payload || {}))}, @@ -681,6 +682,10 @@ export class DatabricksVectorStore implements VectorStore { WHERE memory_id = ${formatSqlValue(vectorId)} `); this.requestIndexSync(); + const raw = extractRowValue(rows[0] ?? {}, ["num_affected_rows"]); + // Number(null) and Number("") are 0, which would read as "missing". + const affected = raw == null || raw === "" ? NaN : Number(raw); + if (Number.isFinite(affected)) return affected > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts b/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts index 27ec5dde6..c8a5d0e5b 100644 --- a/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts +++ b/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts @@ -236,17 +236,24 @@ export class ElasticsearchDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const doc: Record = {}; if (vector) doc.vector = vector; if (payload) doc.metadata = payload; - await this.client.update({ + const request = this.client.update({ index: this.collectionName, id: vectorId, doc, }); + try { + await request; + } catch (error: any) { + if (error?.meta?.statusCode === 404) return false; + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/memory.ts b/mem0-ts/src/oss/src/vector_stores/memory.ts index 7969194f0..bbbbabaf7 100644 --- a/mem0-ts/src/oss/src/vector_stores/memory.ts +++ b/mem0-ts/src/oss/src/vector_stores/memory.ts @@ -407,16 +407,17 @@ export class MemoryVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { if (vector.length !== this.dimension) { throw new Error( `Vector dimension mismatch. Expected ${this.dimension}, got ${vector.length}`, ); } const vectorBuffer = Buffer.from(new Float32Array(vector).buffer); - this.db + const result = this.db .prepare(`UPDATE vectors SET vector = ?, payload = ? WHERE id = ?`) .run(vectorBuffer, JSON.stringify(payload), vectorId); + return result.changes > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/mongodb.ts b/mem0-ts/src/oss/src/vector_stores/mongodb.ts index a3bcecf21..776bf7138 100644 --- a/mem0-ts/src/oss/src/vector_stores/mongodb.ts +++ b/mem0-ts/src/oss/src/vector_stores/mongodb.ts @@ -379,7 +379,7 @@ export class MongoDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const updateFields: any = {}; if (vector) { @@ -397,9 +397,12 @@ export class MongoDB implements VectorStore { { _id: vectorId as any }, { $set: updateFields }, ); + // An unacknowledged write reports no real matchedCount. + if (result.acknowledged === false) return; if (result.matchedCount === 0) { console.warn(`No document found with ID '${vectorId}' to update.`); } + return result.matchedCount > 0; } catch (error) { console.error("Error updating document:", error); throw error; diff --git a/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts b/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts index 79f6e5c9a..f569ed24e 100644 --- a/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts +++ b/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts @@ -173,7 +173,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { if (vector.length > 0) { this.assertVectorDimension(vector, "Vector"); } @@ -195,7 +195,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { if (hasPayload) { const properties = this.buildStoredPayload(payload); - await this.executeQuery( + const payloadResults = await this.executeQuery( ` MATCH (n:${this.collectionLabelExpr} {\`~id\`: $vectorId}) SET n = $properties @@ -206,6 +206,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { properties, }, ); + if (payloadResults.length === 0) return false; } if (hasVector) { @@ -224,6 +225,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { }, ); this.assertSuccessfulResults(updateResults, "Update"); + if (updateResults.length === 0) return false; } catch (error) { if (priorResult) { try { @@ -249,6 +251,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { throw error; } } + if (hasPayload || hasVector) return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/opensearch.ts b/mem0-ts/src/oss/src/vector_stores/opensearch.ts index 10f42e46a..b16717c6f 100644 --- a/mem0-ts/src/oss/src/vector_stores/opensearch.ts +++ b/mem0-ts/src/oss/src/vector_stores/opensearch.ts @@ -367,13 +367,13 @@ export class OpenSearchDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); if (vector) { this.validateVector(vector, 0); } - await this.client.update({ + const request = this.client.update({ index: this.collectionName, id: vectorId, body: { @@ -385,6 +385,15 @@ export class OpenSearchDB implements VectorStore { }, refresh: this.autoRefresh, }); + try { + await request; + } catch (error: any) { + if (error?.statusCode === 404 || error?.meta?.statusCode === 404) { + return false; + } + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/oracledb.ts b/mem0-ts/src/oss/src/vector_stores/oracledb.ts index 46cf016b8..08c2d12a3 100644 --- a/mem0-ts/src/oss/src/vector_stores/oracledb.ts +++ b/mem0-ts/src/oss/src/vector_stores/oracledb.ts @@ -654,7 +654,7 @@ export class OracleAIVectorSearch implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const assignments: string[] = []; @@ -670,7 +670,7 @@ export class OracleAIVectorSearch implements VectorStore { } if (assignments.length === 0) return; - await this.withConnection( + const result = await this.withConnection( (connection) => connection.execute( `UPDATE ${this.collectionName} SET ${assignments.join(", ")} WHERE id = :vector_id`, @@ -678,6 +678,8 @@ export class OracleAIVectorSearch implements VectorStore { ), true, ); + const affected = result.rowsAffected; + return typeof affected === "number" ? affected > 0 : undefined; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/pgvector.ts b/mem0-ts/src/oss/src/vector_stores/pgvector.ts index b7f2c2f69..1bd4d9a2c 100644 --- a/mem0-ts/src/oss/src/vector_stores/pgvector.ts +++ b/mem0-ts/src/oss/src/vector_stores/pgvector.ts @@ -464,10 +464,10 @@ export class PGVector implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const vectorStr = `[${vector.join(",")}]`; - await this.client.query( + const result = await this.client.query( ` UPDATE ${this.col()} SET vector = $1::vector, payload = $2::jsonb @@ -475,6 +475,7 @@ export class PGVector implements VectorStore { `, [vectorStr, payload, vectorId], ); + return (result.rowCount ?? 0) > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/pinecone.ts b/mem0-ts/src/oss/src/vector_stores/pinecone.ts index 3d8f4e851..ed6f9eb96 100644 --- a/mem0-ts/src/oss/src/vector_stores/pinecone.ts +++ b/mem0-ts/src/oss/src/vector_stores/pinecone.ts @@ -305,8 +305,11 @@ export class PineconeDB implements VectorStore { payload: Record, ): Promise { await this.initialize(); - await this.namespacedIndex().upsert({ - records: [{ id: vectorId, values: vector, metadata: payload }], + // update() never creates a missing id but does not report whether it existed. + await this.namespacedIndex().update({ + id: vectorId, + ...(vector ? { values: vector } : {}), + metadata: payload, }); } diff --git a/mem0-ts/src/oss/src/vector_stores/qdrant.ts b/mem0-ts/src/oss/src/vector_stores/qdrant.ts index e84a138f1..99f72b20c 100644 --- a/mem0-ts/src/oss/src/vector_stores/qdrant.ts +++ b/mem0-ts/src/oss/src/vector_stores/qdrant.ts @@ -319,9 +319,13 @@ export class Qdrant implements VectorStore { // named-vector and BM25-inference shapes are not typed. private async upsertPoints( points: { id: string | number; vector: any; payload?: any }[], + options: { update_mode?: "update_only" } = {}, ): Promise { try { - await this.client.upsert(this.collectionName, { points: points as any }); + await this.client.upsert(this.collectionName, { + points: points as any, + ...options, + }); } catch (error) { if (!this._hasBm25Slot) { throw error; @@ -338,6 +342,7 @@ export class Qdrant implements VectorStore { })); await this.client.upsert(this.collectionName, { points: denseOnly as any, + ...options, }); } } @@ -430,7 +435,7 @@ export class Qdrant implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const point = { id: vectorId, @@ -439,7 +444,15 @@ export class Qdrant implements VectorStore { payload, }; - await this.upsertPoints([point]); + // One write keeps the vector and payload of concurrent updates together. + // update_only (Qdrant 1.17+) never creates a point; older servers upsert as before. + await this.upsertPoints([point], { update_mode: "update_only" }); + const found = await this.client.retrieve(this.collectionName, { + ids: [vectorId], + with_payload: false, + with_vector: false, + }); + return found.length > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/redis.ts b/mem0-ts/src/oss/src/vector_stores/redis.ts index ecb326ac2..be016bada 100644 --- a/mem0-ts/src/oss/src/vector_stores/redis.ts +++ b/mem0-ts/src/oss/src/vector_stores/redis.ts @@ -122,6 +122,11 @@ const EXCLUDED_KEYS = new Set([ "updated_at", ]); +// HSET alone creates a missing hash; the script checks and writes atomically. +const HSET_IF_EXISTS = + "if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end " + + "redis.call('HSET', KEYS[1], unpack(ARGV)) return 1"; + // Utility function to convert object keys to snake_case function toSnakeCase(obj: Record): Record { if (typeof obj !== "object" || obj === null) return obj; @@ -574,7 +579,7 @@ export class RedisDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const snakePayload = toSnakeCase(payload); const createdAt = snakePayload.created_at @@ -589,8 +594,8 @@ export class RedisDB implements VectorStore { memory: snakePayload.data ?? "", created_at: createdAt, updated_at: updatedAt, - embedding: Buffer.from(new Float32Array(vector).buffer), }; + if (vector) entry.embedding = Buffer.from(new Float32Array(vector).buffer); // Add optional fields ["agent_id", "run_id", "user_id"].forEach((field) => { @@ -606,8 +611,40 @@ export class RedisDB implements VectorStore { ), ); + const key = `${this.indexPrefix}:${vectorId}`; try { - await this.client.hSet(`${this.indexPrefix}:${vectorId}`, entry); + const updated = await this.client + .sendCommand([ + "EVAL", + HSET_IF_EXISTS, + "1", + key, + ...Object.entries(entry).flatMap(([field, value]) => [ + field, + typeof value === "number" ? String(value) : value, + ]), + ]) + .catch(async (error: Error) => { + // ACL users without +@scripting: WATCH/MULTI is also atomic, but needs its own connection. + if (!String(error?.message).includes("NOPERM")) throw error; + const { WatchError } = await import("redis"); + return this.client.executeIsolated(async (conn) => { + for (;;) { + await conn.watch(key); + if (!(await conn.exists(key))) { + await conn.unwatch(); + return 0; + } + try { + await conn.multi().hSet(key, entry).exec(); + return 1; + } catch (e) { + if (!(e instanceof WatchError)) throw e; + } + } + }); + }); + return updated === 1; } catch (error) { console.error("Error during vector update:", error); throw error; diff --git a/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts b/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts index 2fa539dd6..bd627f409 100644 --- a/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts +++ b/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts @@ -141,19 +141,19 @@ export class UpstashVector implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); - // Upstash's `update` can't set the vector and metadata in one call (its - // payload is a discriminated union of vector | data | metadata), so a - // single `upsert` replaces both atomically, the same way insert() writes. - await this.client.upsert( + const { updated } = await this.client.update( { id: vectorId, - vector, + ...(vector ? { vector } : {}), metadata: payload, + metadataUpdateMode: "OVERWRITE", }, { namespace: this.collectionName }, ); + // 0 is not documented as "missing" and can come back for an existing id. + return typeof updated === "number" && updated > 0 ? true : undefined; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/valkey.ts b/mem0-ts/src/oss/src/vector_stores/valkey.ts index cd4f85920..61c557551 100644 --- a/mem0-ts/src/oss/src/vector_stores/valkey.ts +++ b/mem0-ts/src/oss/src/vector_stores/valkey.ts @@ -14,6 +14,16 @@ interface ValkeyClient { set: (key: string, value: string) => Promise<"OK">; quit: () => Promise<"OK">; on: (event: string, listener: (...args: any[]) => void) => void; + duplicate: () => ValkeyClient; + watch: (key: string) => Promise<"OK">; + unwatch: () => Promise<"OK">; + multi: () => { + hset: ( + key: string, + data: Record, + ) => { exec: () => Promise<[Error | null, unknown][] | null> }; + }; + disconnect: () => void; } /** @@ -36,6 +46,11 @@ const EXCLUDED_KEYS = new Set([ "updated_at", ]); +// HSET alone creates a missing hash; the script checks and writes atomically. +const HSET_IF_EXISTS = + "if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end " + + "redis.call('HSET', KEYS[1], unpack(ARGV)) return 1"; + function toSnakeCase(obj: Record): Record { if (typeof obj !== "object" || obj === null) return obj; return Object.fromEntries( @@ -503,7 +518,7 @@ export class ValkeyDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { const snakePayload = toSnakeCase(payload); const key = `${this.indexPrefix}:${vectorId}`; @@ -518,13 +533,15 @@ export class ValkeyDB implements VectorStore { created_at: String( Math.floor(new Date(snakePayload.created_at).getTime() / 1000), ), - embedding: Buffer.from(new Float32Array(vector).buffer), metadata: JSON.stringify( Object.fromEntries( Object.entries(snakePayload).filter(([k]) => !EXCLUDED_KEYS.has(k)), ), ), }; + if (vector) { + hashData.embedding = Buffer.from(new Float32Array(vector).buffer); + } if (snakePayload.updated_at) { hashData.updated_at = String( @@ -538,7 +555,31 @@ export class ValkeyDB implements VectorStore { } } - await this.client.hset(key, hashData); + const updated = await this.client + .call("EVAL", HSET_IF_EXISTS, 1, key, ...Object.entries(hashData).flat()) + .catch(async (error: Error) => { + // ACL users without +@scripting: WATCH/MULTI is also atomic, but needs its own connection. + if (!String(error?.message).includes("NOPERM")) throw error; + const conn = this.client.duplicate(); + try { + for (;;) { + await conn.watch(key); + if (!(await conn.exists(key))) { + await conn.unwatch(); + return 0; + } + // exec() resolves to null when a watched key changed: retry. + const replies = await conn.multi().hset(key, hashData).exec(); + if (!replies) continue; + const failed = replies.find(([err]) => err); + if (failed) throw failed[0]; + return 1; + } + } finally { + conn.disconnect(); + } + }); + return updated === 1; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/weaviate.ts b/mem0-ts/src/oss/src/vector_stores/weaviate.ts index 3c7d51246..ff0a6f95c 100644 --- a/mem0-ts/src/oss/src/vector_stores/weaviate.ts +++ b/mem0-ts/src/oss/src/vector_stores/weaviate.ts @@ -189,13 +189,20 @@ export class WeaviateDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); - await this._col.data.update({ + const request = this._col.data.update({ id: vectorId, properties: payload, vectors: vector, }); + try { + await request; + } catch (error: any) { + if (error?.code === 404) return false; + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts b/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts index 2793bf6a5..dbffc4c33 100644 --- a/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts +++ b/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts @@ -365,7 +365,9 @@ describe("ElasticsearchDB", () => { host: "localhost", }); - await store.update("id-1", [1, 2, 3, 4], { key: "val" }); + expect(await store.update("id-1", [1, 2, 3, 4], { key: "val" })).toBe( + true, + ); expect(mockUpdate).toHaveBeenCalledWith({ index: "mem0", @@ -373,6 +375,35 @@ describe("ElasticsearchDB", () => { doc: { vector: [1, 2, 3, 4], metadata: { key: "val" } }, }); }); + + it("returns false and inserts nothing when the document is missing", async () => { + mockUpdate.mockRejectedValue({ meta: { statusCode: 404 } }); + const store = new ElasticsearchDB({ + collectionName: "mem0", + embeddingModelDims: 4, + host: "localhost", + }); + + expect(await store.update("missing", [1, 2, 3, 4], { k: "v" })).toBe( + false, + ); + expect(mockUpdate.mock.calls[0][0]).not.toHaveProperty("doc_as_upsert"); + expect(mockUpdate.mock.calls[0][0]).not.toHaveProperty("upsert"); + expect(mockIndex_).not.toHaveBeenCalled(); + }); + + it("sends only metadata on a payload-only update", async () => { + const store = new ElasticsearchDB({ + collectionName: "mem0", + embeddingModelDims: 4, + host: "localhost", + }); + + expect(await store.update("id-1", null, { key: "new" })).toBe(true); + expect(mockUpdate.mock.calls[0][0].doc).toEqual({ + metadata: { key: "new" }, + }); + }); }); describe("delete", () => { diff --git a/mem0-ts/src/oss/tests/memory.crud.test.ts b/mem0-ts/src/oss/tests/memory.crud.test.ts index 6e45eaa01..35f3a54f2 100644 --- a/mem0-ts/src/oss/tests/memory.crud.test.ts +++ b/mem0-ts/src/oss/tests/memory.crud.test.ts @@ -165,6 +165,30 @@ describe("Memory - update()", () => { expect(result.message).toBe("Memory updated successfully!"); }); + test("a delete that lands between get and update is not undone", async () => { + const addResult: SearchResult = await memory.add("Race me", { + userId, + infer: false, + }); + const id = addResult.results[0].id; + const store = (memory as any).vectorStore; + const realUpdate = store.update.bind(store); + const updateSpy = jest + .spyOn(store, "update") + .mockImplementationOnce(async (...args: any[]) => { + await memory.delete(id); + return realUpdate(...args); + }); + + await expect(memory.update(id, { text: "Resurrected" })).rejects.toThrow( + `Memory with ID ${id} not found`, + ); + updateSpy.mockRestore(); + expect(await memory.get(id)).toBeNull(); + const actions = (await memory.history(id)).map((h) => h.action); + expect(actions).toEqual(["DELETE", "ADD"]); + }); + test("persists the updated text", async () => { const addResult: SearchResult = await memory.add("Before update", { userId, diff --git a/mem0-ts/src/oss/tests/opensearch.unit.test.ts b/mem0-ts/src/oss/tests/opensearch.unit.test.ts index e53a1dbc0..145f5cc8b 100644 --- a/mem0-ts/src/oss/tests/opensearch.unit.test.ts +++ b/mem0-ts/src/oss/tests/opensearch.unit.test.ts @@ -154,6 +154,46 @@ describe("OpenSearchDB", () => { await expect(store.get("missing")).resolves.toBeNull(); }); + it("update returns false and inserts nothing when the document is missing (404)", async () => { + const client = createClient({ + update: jest.fn().mockRejectedValue({ meta: { statusCode: 404 } }), + }); + const store = await createStore(client); + + await expect( + store.update("missing", [0.1, 0.2, 0.3], { data: "x" }), + ).resolves.toBe(false); + expect(client.update.mock.calls[0][0].body).not.toHaveProperty( + "doc_as_upsert", + ); + expect(client.index).not.toHaveBeenCalled(); + expect(client.bulk).not.toHaveBeenCalled(); + }); + + it("update returns true and sends the same partial doc for an existing document", async () => { + const client = createClient(); + const store = await createStore(client); + + await expect( + store.update("mem-1", [0.1, 0.2, 0.3], { data: "new" }), + ).resolves.toBe(true); + expect(client.update.mock.calls[0][0].body).toEqual({ + doc: { + vector_field: [0.1, 0.2, 0.3], + payload: { data: "new" }, + id: "mem-1", + }, + }); + + await expect( + store.update("mem-1", null as any, { data: "only" }), + ).resolves.toBe(true); + expect(client.update.mock.calls[1][0].body.doc).toEqual({ + payload: { data: "only" }, + id: "mem-1", + }); + }); + it("keywordSearch queries lemmatized payload fields", async () => { const client = createClient(); const store = await createStore(client); diff --git a/mem0-ts/src/oss/tests/oracledb.unit.test.ts b/mem0-ts/src/oss/tests/oracledb.unit.test.ts index 3afdbac6e..90e8fee5b 100644 --- a/mem0-ts/src/oss/tests/oracledb.unit.test.ts +++ b/mem0-ts/src/oss/tests/oracledb.unit.test.ts @@ -411,6 +411,44 @@ describe("OracleAIVectorSearch SQL", () => { expect(results).toEqual([]); expect(count).toBe(0); }); + + function storeWithRowsAffected(calls: Call[], rowsAffected: number) { + const connection: any = fakeConnection(calls, []); + const execute = connection.execute; + connection.execute = async (sql: string, binds: any = {}) => ({ + ...(await execute(sql, binds)), + rowsAffected, + }); + return makeStore(calls, [], { client: connection }); + } + + it("returns false from update and inserts nothing when the id is missing", async () => { + const calls: Call[] = []; + const store = storeWithRowsAffected(calls, 0); + expect(await store.update("missing", [1, 2, 3], { a: 1 })).toBe(false); + expect(calls.some((c) => /^(INSERT|MERGE)/.test(c.sql))).toBe(false); + }); + + it("returns undefined from update when the driver gives no rowsAffected", async () => { + const store = storeWithRowsAffected([], undefined as any); + expect(await store.update("id-1", [1, 2, 3], { a: 1 })).toBeUndefined(); + }); + + it("returns true from update and binds the same values for an existing id", async () => { + const calls: Call[] = []; + const store = storeWithRowsAffected(calls, 1); + expect(await store.update("id-1", [1, 2, 3], { a: 1 })).toBe(true); + expect(await store.update("id-1", null as any, { b: 2 })).toBe(true); + const updates = calls.filter((c) => c.sql.startsWith("UPDATE")); + expect(updates[0].sql).toBe( + 'UPDATE "mem0" SET vector = :vector, payload = :payload WHERE id = :vector_id', + ); + expect(updates[0].binds.vector.val).toEqual(new Float32Array([1, 2, 3])); + expect(updates[0].binds.payload.val).toEqual({ a: 1 }); + expect(updates[1].sql).toBe( + 'UPDATE "mem0" SET payload = :payload WHERE id = :vector_id', + ); + }); }); describe("OracleAIVectorSearch initialization failure", () => { diff --git a/mem0-ts/src/oss/tests/pgvector.unit.test.ts b/mem0-ts/src/oss/tests/pgvector.unit.test.ts index f6f75701f..eb3035aee 100644 --- a/mem0-ts/src/oss/tests/pgvector.unit.test.ts +++ b/mem0-ts/src/oss/tests/pgvector.unit.test.ts @@ -241,4 +241,29 @@ describe("PGVector", () => { ["[1,0,0]", 4], ); }); + + test("update returns rowCount > 0 and only ever issues an UPDATE", async () => { + const store = new PGVector({ + collectionName: "memories", + connectionString: "postgresql://postgres:postgres@localhost:5432/db", + embeddingModelDims: 3, + dimension: 3, + } as any); + await store.initialize(); + const client = require("pg").__mock.clients[0]; + client.query.mockClear(); + + client.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); + expect(await store.update("missing", [1, 0, 0], { data: "x" })).toBe(false); + client.query.mockResolvedValueOnce({ rows: [], rowCount: 1 }); + expect(await store.update("a", [0, 1, 0], { data: "y" })).toBe(true); + + const queries = getClientQueries(client); + expect(queries).toHaveLength(2); + expect(queries.every((sql) => sql.trim().startsWith("UPDATE"))).toBe(true); + expect(client.query).toHaveBeenLastCalledWith( + expect.stringContaining("SET vector = $1::vector, payload = $2::jsonb"), + ["[0,1,0]", { data: "y" }, "a"], + ); + }); }); diff --git a/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts b/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts index 2746238cc..a8d1ccd31 100644 --- a/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts +++ b/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts @@ -283,6 +283,27 @@ describe("Qdrant BM25 keyword search — insert / update", () => { expect(point.vector.bm25).toBeUndefined(); }); + it("update writes vector and payload in one update_only upsert", async () => { + const { store, client } = await freshStore(); + client.retrieve.mockResolvedValueOnce([{ id: "mem-1" }]); + const payload = { data: "new", user_id: "u" }; + + await expect(store.update("mem-1", [0.4], payload)).resolves.toBe(true); + expect(client.upsert).toHaveBeenCalledTimes(1); + const body = client.upsert.mock.calls[0][1]; + expect(body.update_mode).toBe("update_only"); + expect(body.points[0]).toMatchObject({ id: "mem-1", payload }); + }); + + it("update returns false when the point is gone after the write", async () => { + const { store, client } = await freshStore(); + client.retrieve.mockResolvedValueOnce([]); + + await expect(store.update("gone", [0.1], { data: "x" })).resolves.toBe( + false, + ); + }); + it("inserts a plain dense vector (no named/sparse) on legacy collections", async () => { const client = buildMockClient( { createCollection: jest.fn().mockRejectedValue({ status: 409 }) }, @@ -485,6 +506,7 @@ describe("Qdrant BM25 keyword search — reactive downgrade on upsert failure", expect(upsert).toHaveBeenCalledTimes(2); const retryPoint = upsert.mock.calls[1][1].points[0]; expect(retryPoint.vector).toEqual([0.4, 0.5]); + expect(upsert.mock.calls[1][1].update_mode).toBe("update_only"); expect(warnSpy).toHaveBeenCalledTimes(1); expect(await store.keywordSearch("updat")).toBeNull(); }); diff --git a/mem0-ts/src/oss/tests/redis.unit.test.ts b/mem0-ts/src/oss/tests/redis.unit.test.ts index 03343b501..c3a458860 100644 --- a/mem0-ts/src/oss/tests/redis.unit.test.ts +++ b/mem0-ts/src/oss/tests/redis.unit.test.ts @@ -1,6 +1,7 @@ import { RedisDB } from "../src/vector_stores/redis"; jest.mock("redis", () => ({ + WatchError: class WatchError extends Error {}, createClient: jest.fn(() => ({ connect: jest.fn(), on: jest.fn(), @@ -12,6 +13,8 @@ jest.mock("redis", () => ({ _list: jest.fn().mockResolvedValue([]), }, hSet: jest.fn(), + sendCommand: jest.fn().mockResolvedValue(1), + executeIsolated: jest.fn(), hGetAll: jest.fn(), del: jest.fn(), exists: jest.fn(), @@ -19,6 +22,13 @@ jest.mock("redis", () => ({ })), })); +// update() sends EVAL