From ce929a824156b076462bd4803613dbb4dcdec8df Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sat, 6 Jun 2026 04:35:15 -0300 Subject: [PATCH 1/2] fix(backends): wrap bare-str OneOrMany inputs before embedding EmbeddingCollection did _embed_texts(list(documents)). For ChromaDB's OneOrMany shape, a bare str document splits into per-character 'docs' (list("abc") -> ['a','b','c']), embedding each character and breaking length alignment with ids/metadatas on explicit-vector backends (pgvector, sqlite_exact). Normalize str -> [str] via _as_list() at all four sites (add/upsert/update documents, query query_texts) and pass the normalized list to the inner backend too. Addresses PR #1706 review (Gemini + Copilot, HIGH). --- mempalace/backends/embedding_wrapper.py | 27 +++++-- tests/test_embedding_wrapper.py | 95 +++++++++++++++++++++++++ 2 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 tests/test_embedding_wrapper.py diff --git a/mempalace/backends/embedding_wrapper.py b/mempalace/backends/embedding_wrapper.py index f4a8ccd..220c92a 100644 --- a/mempalace/backends/embedding_wrapper.py +++ b/mempalace/backends/embedding_wrapper.py @@ -18,6 +18,19 @@ def _embed_texts(texts: list[str]) -> list[list[float]]: return [list(v) for v in vectors] +def _as_list(value): + """Normalize ChromaDB's ``OneOrMany`` shape (``str`` | sequence) to a list. + + A bare ``str`` must be *wrapped*, not iterated: ``list("abc")`` yields + ``['a', 'b', 'c']``, which would embed per character and break length + alignment with ``ids``/``metadatas`` on explicit-vector backends + (pgvector, sqlite_exact). See PR #1706 review. + """ + if isinstance(value, str): + return [value] + return list(value) + + class EmbeddingCollection(BaseCollection): """Wrap a collection that requires explicit vectors. @@ -33,8 +46,9 @@ class EmbeddingCollection(BaseCollection): return getattr(self._inner, name) def add(self, *, documents, ids, metadatas=None, embeddings=None): + documents = _as_list(documents) if embeddings is None: - embeddings = _embed_texts(list(documents)) + embeddings = _embed_texts(documents) return self._inner.add( documents=documents, ids=ids, @@ -43,8 +57,9 @@ class EmbeddingCollection(BaseCollection): ) def upsert(self, *, documents, ids, metadatas=None, embeddings=None): + documents = _as_list(documents) if embeddings is None: - embeddings = _embed_texts(list(documents)) + embeddings = _embed_texts(documents) return self._inner.upsert( documents=documents, ids=ids, @@ -63,7 +78,7 @@ class EmbeddingCollection(BaseCollection): include: Optional[list[str]] = None, ): if query_texts is not None and query_embeddings is None: - query_embeddings = _embed_texts(list(query_texts)) + query_embeddings = _embed_texts(_as_list(query_texts)) query_texts = None return self._inner.query( query_texts=query_texts, @@ -105,8 +120,10 @@ class EmbeddingCollection(BaseCollection): return self._inner.lexical_search(query=query, n_results=n_results, where=where) def update(self, *, ids, documents=None, metadatas=None, embeddings=None): - if documents is not None and embeddings is None: - embeddings = _embed_texts(list(documents)) + if documents is not None: + documents = _as_list(documents) + if embeddings is None: + embeddings = _embed_texts(documents) return self._inner.update( ids=ids, documents=documents, diff --git a/tests/test_embedding_wrapper.py b/tests/test_embedding_wrapper.py new file mode 100644 index 0000000..588876d --- /dev/null +++ b/tests/test_embedding_wrapper.py @@ -0,0 +1,95 @@ +"""EmbeddingCollection OneOrMany handling (PR #1706 review). + +A bare ``str`` passed as ``documents``/``query_texts`` (ChromaDB's OneOrMany +shape) must be wrapped, not iterated — otherwise ``list("abc")`` embeds per +character and breaks length alignment with ids/metadatas on explicit-vector +backends. +""" + +from mempalace.backends import embedding_wrapper as ew + + +class _FakeInner: + """Captures what the wrapper delegates to the backend.""" + + def __init__(self): + self.calls = {} + + def add(self, *, documents, ids, metadatas=None, embeddings=None): + self.calls["add"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + + def upsert(self, *, documents, ids, metadatas=None, embeddings=None): + self.calls["upsert"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + + def update(self, *, ids, documents=None, metadatas=None, embeddings=None): + self.calls["update"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + + def query(self, *, query_texts=None, query_embeddings=None, **_kw): + self.calls["query"] = {"query_texts": query_texts, "query_embeddings": query_embeddings} + from mempalace.backends.base import QueryResult + + return QueryResult.empty() + + +def _patch_embed(monkeypatch): + """Stub the embedder: one vector per input text, recording the inputs.""" + seen = {} + + def fake(texts): + seen["texts"] = texts + return [[0.0, 0.0] for _ in texts] + + monkeypatch.setattr(ew, "_embed_texts", fake) + return seen + + +def test_as_list_wraps_bare_string(): + assert ew._as_list("hello world") == ["hello world"] + assert ew._as_list(["a", "b"]) == ["a", "b"] + + +def test_add_wraps_bare_string_document(monkeypatch): + seen = _patch_embed(monkeypatch) + inner = _FakeInner() + ew.EmbeddingCollection(inner).add(documents="hello world", ids=["d1"]) + # embedded as one whole document, not per character + assert seen["texts"] == ["hello world"] + # and the backend receives a list, length-aligned with ids + assert inner.calls["add"]["documents"] == ["hello world"] + assert len(inner.calls["add"]["embeddings"]) == 1 + + +def test_upsert_wraps_bare_string_document(monkeypatch): + seen = _patch_embed(monkeypatch) + inner = _FakeInner() + ew.EmbeddingCollection(inner).upsert(documents="solo", ids=["d1"]) + assert seen["texts"] == ["solo"] + assert inner.calls["upsert"]["documents"] == ["solo"] + assert len(inner.calls["upsert"]["embeddings"]) == 1 + + +def test_update_wraps_bare_string_document(monkeypatch): + seen = _patch_embed(monkeypatch) + inner = _FakeInner() + ew.EmbeddingCollection(inner).update(ids=["d1"], documents="changed") + assert seen["texts"] == ["changed"] + assert inner.calls["update"]["documents"] == ["changed"] + assert len(inner.calls["update"]["embeddings"]) == 1 + + +def test_query_wraps_bare_string(monkeypatch): + seen = _patch_embed(monkeypatch) + inner = _FakeInner() + ew.EmbeddingCollection(inner).query(query_texts="find me") + assert seen["texts"] == ["find me"] + # query_texts is consumed into a single query embedding + assert len(inner.calls["query"]["query_embeddings"]) == 1 + assert inner.calls["query"]["query_texts"] is None + + +def test_list_inputs_unaffected(monkeypatch): + seen = _patch_embed(monkeypatch) + inner = _FakeInner() + ew.EmbeddingCollection(inner).add(documents=["one", "two"], ids=["a", "b"]) + assert seen["texts"] == ["one", "two"] + assert len(inner.calls["add"]["embeddings"]) == 2 From 051f0cc1ecb7075fcda2f9ce2429999cfbea3cab Mon Sep 17 00:00:00 2001 From: Igor Lins e Silva <4753812+igorls@users.noreply.github.com> Date: Sat, 6 Jun 2026 04:56:19 -0300 Subject: [PATCH 2/2] fix(backends): normalize all OneOrMany inputs in EmbeddingCollection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address #1707 review: - _as_list also wraps a bare dict (single metadata) — list({'k':1}) -> ['k'] would drop the values — and returns list inputs as-is (no copy, Copilot perf note); other iterables are materialized once. - Normalize ids and metadatas (not just documents) in add/upsert/update so a scalar id/metadata stays length-aligned with documents/embeddings. - Widen query_texts annotation to list[str] | str to match the behavior. - Tests: bare-str ids + dict metadatas, dict wrapping, list-returned-as-is. --- mempalace/backends/embedding_wrapper.py | 27 ++++++++++++----- tests/test_embedding_wrapper.py | 39 ++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/mempalace/backends/embedding_wrapper.py b/mempalace/backends/embedding_wrapper.py index 220c92a..1441deb 100644 --- a/mempalace/backends/embedding_wrapper.py +++ b/mempalace/backends/embedding_wrapper.py @@ -19,15 +19,19 @@ def _embed_texts(texts: list[str]) -> list[list[float]]: def _as_list(value): - """Normalize ChromaDB's ``OneOrMany`` shape (``str`` | sequence) to a list. + """Normalize ChromaDB's ``OneOrMany`` shape (``str`` | ``dict`` | sequence) to a list. - A bare ``str`` must be *wrapped*, not iterated: ``list("abc")`` yields - ``['a', 'b', 'c']``, which would embed per character and break length - alignment with ``ids``/``metadatas`` on explicit-vector backends - (pgvector, sqlite_exact). See PR #1706 review. + A bare ``str`` (a document/id) or ``dict`` (a single metadata) must be + *wrapped*, not iterated: ``list("abc")`` yields ``['a', 'b', 'c']`` and + ``list({"k": 1})`` yields ``['k']`` — either desyncs embeddings/metadatas + from ``ids`` on explicit-vector backends (pgvector, sqlite_exact). A list is + returned unchanged (no copy); any other iterable is materialized once. + See PR #1706/#1707 review. """ - if isinstance(value, str): + if isinstance(value, (str, dict)): return [value] + if isinstance(value, list): + return value return list(value) @@ -47,6 +51,9 @@ class EmbeddingCollection(BaseCollection): def add(self, *, documents, ids, metadatas=None, embeddings=None): documents = _as_list(documents) + ids = _as_list(ids) + if metadatas is not None: + metadatas = _as_list(metadatas) if embeddings is None: embeddings = _embed_texts(documents) return self._inner.add( @@ -58,6 +65,9 @@ class EmbeddingCollection(BaseCollection): def upsert(self, *, documents, ids, metadatas=None, embeddings=None): documents = _as_list(documents) + ids = _as_list(ids) + if metadatas is not None: + metadatas = _as_list(metadatas) if embeddings is None: embeddings = _embed_texts(documents) return self._inner.upsert( @@ -70,7 +80,7 @@ class EmbeddingCollection(BaseCollection): def query( self, *, - query_texts: Optional[list[str]] = None, + query_texts: Optional[list[str] | str] = None, query_embeddings: Optional[list[list[float]]] = None, n_results: int = 10, where: Optional[dict] = None, @@ -120,10 +130,13 @@ class EmbeddingCollection(BaseCollection): return self._inner.lexical_search(query=query, n_results=n_results, where=where) def update(self, *, ids, documents=None, metadatas=None, embeddings=None): + ids = _as_list(ids) if documents is not None: documents = _as_list(documents) if embeddings is None: embeddings = _embed_texts(documents) + if metadatas is not None: + metadatas = _as_list(metadatas) return self._inner.update( ids=ids, documents=documents, diff --git a/tests/test_embedding_wrapper.py b/tests/test_embedding_wrapper.py index 588876d..5d592d6 100644 --- a/tests/test_embedding_wrapper.py +++ b/tests/test_embedding_wrapper.py @@ -16,13 +16,28 @@ class _FakeInner: self.calls = {} def add(self, *, documents, ids, metadatas=None, embeddings=None): - self.calls["add"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + self.calls["add"] = { + "documents": documents, + "ids": ids, + "metadatas": metadatas, + "embeddings": embeddings, + } def upsert(self, *, documents, ids, metadatas=None, embeddings=None): - self.calls["upsert"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + self.calls["upsert"] = { + "documents": documents, + "ids": ids, + "metadatas": metadatas, + "embeddings": embeddings, + } def update(self, *, ids, documents=None, metadatas=None, embeddings=None): - self.calls["update"] = {"documents": documents, "ids": ids, "embeddings": embeddings} + self.calls["update"] = { + "documents": documents, + "ids": ids, + "metadatas": metadatas, + "embeddings": embeddings, + } def query(self, *, query_texts=None, query_embeddings=None, **_kw): self.calls["query"] = {"query_texts": query_texts, "query_embeddings": query_embeddings} @@ -45,7 +60,10 @@ def _patch_embed(monkeypatch): def test_as_list_wraps_bare_string(): assert ew._as_list("hello world") == ["hello world"] - assert ew._as_list(["a", "b"]) == ["a", "b"] + assert ew._as_list({"k": 1}) == [{"k": 1}] # bare dict wrapped, not -> ["k"] + src = ["a", "b"] + assert ew._as_list(src) is src # list returned as-is (no copy) + assert ew._as_list(("a", "b")) == ["a", "b"] # other iterables materialized def test_add_wraps_bare_string_document(monkeypatch): @@ -93,3 +111,16 @@ def test_list_inputs_unaffected(monkeypatch): ew.EmbeddingCollection(inner).add(documents=["one", "two"], ids=["a", "b"]) assert seen["texts"] == ["one", "two"] assert len(inner.calls["add"]["embeddings"]) == 2 + + +def test_add_wraps_bare_string_ids_and_dict_metadatas(monkeypatch): + _patch_embed(monkeypatch) + inner = _FakeInner() + # a single id (str) and a single metadata (dict) are OneOrMany shapes too + ew.EmbeddingCollection(inner).add(documents="solo", ids="d1", metadatas={"src": "web"}) + call = inner.calls["add"] + assert call["ids"] == ["d1"] # not ['d', '1'] + assert call["metadatas"] == [{"src": "web"}] # not ['src'] + # documents / embeddings / ids / metadatas all length-aligned at 1 + assert call["documents"] == ["solo"] + assert len(call["embeddings"]) == 1