Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions autobot-backend/knowledge/backends/_chroma_args.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""The argument shapes ChromaDB expects, shared by the sync and async adapters (#18557).

Pure functions only: each adapter still makes its own call, sync or awaited.
"""

from __future__ import annotations

from typing import Any, Sequence

from autobot_shared.time_utils import utc_timestamp


def optional_list(values: Sequence[Any] | None) -> list | None:
"""A list copy of *values*, keeping ``None`` as ``None``."""
return list(values) if values is not None else None


def write_args(
ids: Sequence[str],
documents: Sequence[str] | None,
metadatas: Sequence[Any] | None,
embeddings: Sequence[Any] | None,
) -> dict:
"""Arguments for ``add``, ``upsert`` and ``update``."""
return {
"ids": list(ids),
"documents": optional_list(documents),
"metadatas": optional_list(metadatas),
"embeddings": optional_list(embeddings),
}


def filter_args(ids: Any = None, where: Any = None, where_document: Any = None) -> dict:
"""The record filters a caller set; an unset one is left out."""
kwargs: dict = {}
if ids is not None:
kwargs["ids"] = list(ids)
if where is not None:
kwargs["where"] = where
if where_document is not None:
kwargs["where_document"] = where_document
return kwargs


def get_args(ids: Any, where: Any, where_document: Any, limit: Any, offset: Any, include: Any) -> dict:
"""Arguments for ``get``, passing only what the caller set."""
kwargs = filter_args(ids, where, where_document)
if limit is not None:
kwargs["limit"] = limit
if offset is not None:
kwargs["offset"] = offset
if include is not None:
kwargs["include"] = list(include)
return kwargs


def query_args(
query_embeddings: Any, query_texts: Any, n_results: int, where: Any, where_document: Any, include: Any
) -> dict:
"""Arguments for ``query``, passing only what the caller set."""
kwargs: dict = {"n_results": n_results}
if query_embeddings is not None:
kwargs["query_embeddings"] = [list(e) for e in query_embeddings]
if query_texts is not None:
kwargs["query_texts"] = list(query_texts)
kwargs.update(filter_args(where=where, where_document=where_document))
if include is not None:
kwargs["include"] = list(include)
return kwargs


def delete_args(ids: Any, where: Any, where_document: Any) -> dict:
"""Arguments for ``delete``, which refuses to run with no filter at all."""
kwargs = filter_args(ids, where, where_document)
if not kwargs:
raise ValueError("delete requires ids or where")
return kwargs


def collection_provenance(metadata: dict | None) -> dict:
"""A new collection's metadata: its creation time, then the caller's values."""
provenance: dict = {"created_at": utc_timestamp()}
if metadata:
provenance.update(metadata)
return provenance
79 changes: 17 additions & 62 deletions autobot-backend/knowledge/backends/async_chromadb_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@

from autobot_shared.logging_manager import get_logger
from autobot_shared.slug import sanitize_token
from autobot_shared.time_utils import utc_timestamp
from knowledge.backends._chroma_args import (
collection_provenance,
delete_args,
get_args,
optional_list,
query_args,
write_args,
)
from knowledge.backends.async_base import AsyncBaseClient, AsyncBaseCollection
from knowledge.backends.base import Embedding, Metadata, Where, WhereDocument

Expand Down Expand Up @@ -56,12 +63,7 @@ async def add(
metadatas: Sequence[Metadata] | None = None,
embeddings: Sequence[Embedding] | None = None,
) -> None:
await self._raw.add(
ids=list(ids),
documents=list(documents) if documents is not None else None,
metadatas=list(metadatas) if metadatas is not None else None,
embeddings=list(embeddings) if embeddings is not None else None,
)
await self._raw.add(**write_args(ids, documents, metadatas, embeddings))

async def upsert(
self,
Expand All @@ -71,12 +73,7 @@ async def upsert(
metadatas: Sequence[Metadata] | None = None,
embeddings: Sequence[Embedding] | None = None,
) -> None:
await self._raw.upsert(
ids=list(ids),
documents=list(documents) if documents is not None else None,
metadatas=list(metadatas) if metadatas is not None else None,
embeddings=list(embeddings) if embeddings is not None else None,
)
await self._raw.upsert(**write_args(ids, documents, metadatas, embeddings))

async def update(
self,
Expand All @@ -86,12 +83,7 @@ async def update(
metadatas: Sequence[Metadata] | None = None,
embeddings: Sequence[Embedding] | None = None,
) -> None:
await self._raw.update(
ids=list(ids),
documents=list(documents) if documents is not None else None,
metadatas=list(metadatas) if metadatas is not None else None,
embeddings=list(embeddings) if embeddings is not None else None,
)
await self._raw.update(**write_args(ids, documents, metadatas, embeddings))

async def get(
self,
Expand All @@ -106,20 +98,7 @@ async def get(
# AsyncChromaCollection.get has defaults for include — pass only the
# fields caller set, letting the wrapper apply its own default when
# include is None.
kwargs: dict = {}
if ids is not None:
kwargs["ids"] = list(ids)
if where is not None:
kwargs["where"] = where
if where_document is not None:
kwargs["where_document"] = where_document
if limit is not None:
kwargs["limit"] = limit
if offset is not None:
kwargs["offset"] = offset
if include is not None:
kwargs["include"] = list(include)
return await self._raw.get(**kwargs)
return await self._raw.get(**get_args(ids, where, where_document, limit, offset, include))

async def query(
self,
Expand All @@ -131,17 +110,7 @@ async def query(
where_document: WhereDocument | None = None,
include: Sequence[str] | None = None,
) -> dict:
kwargs: dict = {"n_results": n_results}
if query_embeddings is not None:
kwargs["query_embeddings"] = [list(e) for e in query_embeddings]
if query_texts is not None:
kwargs["query_texts"] = list(query_texts)
if where is not None:
kwargs["where"] = where
if where_document is not None:
kwargs["where_document"] = where_document
if include is not None:
kwargs["include"] = list(include)
kwargs = query_args(query_embeddings, query_texts, n_results, where, where_document, include)
return await self._raw.query(**kwargs)

async def query_batch(
Expand All @@ -163,7 +132,7 @@ async def query_batch(
n_results=n_results,
where=where,
where_document=where_document,
include=list(include) if include is not None else None,
include=optional_list(include),
)

async def delete(
Expand All @@ -173,16 +142,7 @@ async def delete(
where: Where | None = None,
where_document: WhereDocument | None = None,
) -> None:
kwargs: dict = {}
if ids is not None:
kwargs["ids"] = list(ids)
if where is not None:
kwargs["where"] = where
if where_document is not None:
kwargs["where_document"] = where_document
if not kwargs:
raise ValueError("delete requires ids or where")
await self._raw.delete(**kwargs)
await self._raw.delete(**delete_args(ids, where, where_document))

async def count(self) -> int:
return int(await self._raw.count())
Expand Down Expand Up @@ -210,12 +170,9 @@ async def get_or_create_collection(
metadata: Metadata | None = None,
embedding_function: Any | None = None,
) -> AsyncBaseCollection:
provenance: dict = {"created_at": utc_timestamp()}
if metadata:
provenance.update(metadata)
raw_col = await self._raw.get_or_create_collection(
name=_chroma_safe_name(name),
metadata=provenance,
metadata=collection_provenance(metadata),
embedding_function=embedding_function,
)
return AsyncChromaDBCollection(raw_col)
Expand All @@ -240,9 +197,7 @@ async def create_collection(
metadata: Metadata | None = None,
embedding_function: Any | None = None,
) -> AsyncBaseCollection:
provenance: dict = {"created_at": utc_timestamp()}
if metadata:
provenance.update(metadata)
provenance = collection_provenance(metadata)
try:
raw_col = await self._raw.create_collection(
name=_chroma_safe_name(name),
Expand Down
99 changes: 99 additions & 0 deletions autobot-backend/knowledge/backends/chroma_args_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""The shapes both ChromaDB adapters send (#18557), and that each adapter really sends them."""

from unittest.mock import AsyncMock, MagicMock

import pytest

from knowledge.backends._chroma_args import (
collection_provenance,
delete_args,
get_args,
optional_list,
query_args,
write_args,
)
from knowledge.backends.async_chromadb_adapter import AsyncChromaDBCollection
from knowledge.backends.chromadb_adapter import ChromaDBCollection


def test_write_args_copy_to_lists_and_keep_none():
assert write_args(("a",), ("d",), None, None) == {
"ids": ["a"],
"documents": ["d"],
"metadatas": None,
"embeddings": None,
}


def test_optional_list_keeps_none_and_an_empty_sequence_apart():
assert optional_list(None) is None
assert optional_list(()) == []


def test_get_args_leave_out_what_was_not_set_and_keep_a_zero():
assert get_args(None, None, None, None, None, None) == {}
assert get_args(("a",), {"w": 1}, {"d": 1}, 0, 0, ("documents",)) == {
"ids": ["a"],
"where": {"w": 1},
"where_document": {"d": 1},
"limit": 0,
"offset": 0,
"include": ["documents"],
}


def test_query_args_always_carry_n_results_and_listify_each_embedding():
assert query_args(None, None, 3, None, None, None) == {"n_results": 3}
assert query_args(((1.0, 2.0),), ("t",), 3, {"w": 1}, None, ("documents",)) == {
"n_results": 3,
"query_embeddings": [[1.0, 2.0]],
"query_texts": ["t"],
"where": {"w": 1},
"include": ["documents"],
}


def test_delete_refuses_no_filter_and_accepts_an_empty_where():
with pytest.raises(ValueError, match="delete requires ids or where"):
delete_args(None, None, None)
assert delete_args(None, {}, None) == {"where": {}}


def test_provenance_lets_the_caller_override_created_at():
assert "created_at" in collection_provenance(None)
assert collection_provenance({"created_at": "x", "k": 1}) == {"created_at": "x", "k": 1}


def test_the_sync_adapter_sends_the_shared_shapes():
raw = MagicMock()
col = ChromaDBCollection(raw)
col.upsert(ids=("a",), documents=("d",))
raw.upsert.assert_called_once_with(ids=["a"], documents=["d"], metadatas=None, embeddings=None)
col.get(ids=("a",))
raw.get.assert_called_once_with(ids=["a"])
col.query(query_texts=("t",), n_results=2)
raw.query.assert_called_once_with(n_results=2, query_texts=["t"])
col.delete(ids=("a",))
raw.delete.assert_called_once_with(ids=["a"])


@pytest.mark.asyncio
async def test_the_async_adapter_sends_the_shared_shapes():
raw = AsyncMock()
col = AsyncChromaDBCollection(raw)
await col.upsert(ids=("a",), documents=("d",))
raw.upsert.assert_awaited_once_with(ids=["a"], documents=["d"], metadatas=None, embeddings=None)
await col.get(ids=("a",))
raw.get.assert_awaited_once_with(ids=["a"])
await col.query(query_texts=("t",), n_results=2)
raw.query.assert_awaited_once_with(n_results=2, query_texts=["t"])
await col.query_batch(((1.0,),), include=("documents",))
raw.query_batch.assert_awaited_once_with(
query_embeddings=[[1.0]], n_results=10, where=None, where_document=None, include=["documents"]
)
await col.delete(ids=("a",))
raw.delete.assert_awaited_once_with(ids=["a"])
Loading
Loading