Skip to content

Conversation

borisarzentar
Copy link
Member

Description

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin.

@borisarzentar borisarzentar self-assigned this Apr 22, 2025
Copy link

pull-checklist bot commented Apr 22, 2025

Please make sure all the checkboxes are checked:

  • I have tested these changes locally.
  • I have reviewed the code changes.
  • I have added end-to-end and unit tests (if applicable).
  • I have updated the documentation and README.md file (if necessary).
  • I have removed unnecessary code and debug statements.
  • PR title is clear and follows the convention.
  • I have tagged reviewers or team members for feedback.

Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change refactors multiple vector database adapters and related modules to unify and modernize search and collection access logic. The deprecated get_distance_from_collection_elements method is removed across all adapters, replaced by a standardized search method with improved error handling, optional query parameters, and a default result limit of 15. Collection retrieval is centralized via new get_collection methods, which raise explicit errors for missing collections. All adapters now handle missing collections in a consistent way. Asynchronous patterns are enforced in adapters where appropriate, and related utility and graph modules are updated to use the new search interface.

Changes

File(s) Change Summary
cognee/infrastructure/databases/vector/chromadb/ChromaDBAdapter.py
cognee/infrastructure/databases/vector/lancedb/LanceDBAdapter.py
Refactored to introduce a centralized get_collection method for collection retrieval with explicit error handling; removed get_distance_from_collection_elements; updated all methods to use get_collection; increased default search limit to 15.
cognee/infrastructure/databases/vector/milvus/MilvusAdapter.py Added handling for CollectionNotExistException, wrapping it as CollectionNotFoundError; updated type hints for data point IDs to UUID; increased default search limit to 15.
cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py Renamed and refactored get_distance_from_collection_elements to search; added normalization of similarity scores; improved error handling and parameter flexibility; set default search limit to 15.
cognee/infrastructure/databases/vector/qdrant/QDrantAdapter.py Standardized error handling for missing collections; consolidated search logic into a single search method with improved parameters and exception management; set default search limit to 15.
cognee/infrastructure/databases/vector/weaviate_db/WeaviateAdapter.py Refactored for full async/await support; updated all methods to use async patterns; improved error handling; set default search limit to 15; removed duplicate search methods.
cognee/modules/graph/cognee_graph/CogneeGraph.py Updated to use vector_engine.search instead of the removed distance method, passing limit=0.
cognee/modules/retrieval/utils/brute_force_triplet_search.py Updated to use vector_engine.search with limit=0 in place of the removed distance method.
cognee/tests/unit/modules/retrieval/utils/brute_force_triplet_search_test.py Deleted unit tests for the removed get_distance_from_collection_elements method and related brute-force search error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Adapter
    participant DBClient

    Caller->>Adapter: search(collection_name, query_text, query_vector, limit)
    Adapter->>Adapter: get_collection(collection_name)
    Adapter->>DBClient: retrieve collection
    alt Collection exists
        Adapter->>DBClient: perform search (limit, query_text, query_vector)
        DBClient-->>Adapter: search results
        Adapter-->>Caller: normalized results
    else Collection missing
        Adapter-->>Caller: raise CollectionNotFoundError
    end
Loading

Possibly related PRs

  • topoteretes/cognee#436: Modifies the same method in CogneeGraph to update how vector engine search/distance is used, indicating a direct connection in control flow.
  • topoteretes/cognee#192: Refactors another vector adapter (LanceDBAdapter) in a similar way, introducing centralized collection retrieval and removing the deprecated distance method.

Suggested labels

run-checks

Poem

In the warren of code, where vectors align,
The rabbits refactor, making search so fine.
Old distance methods hop away,
Unified search now leads the way.
Errors are handled, async is king,
With every adapter, a sleeker spring!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@borisarzentar borisarzentar changed the base branch from main to dev April 22, 2025 12:21
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (7)
cognee/modules/graph/cognee_graph/CogneeGraph.py (1)

124-135: 🛠️ Refactor suggestion

⚠️ Potential issue

Unused embedding computation & wrong argument – avoid double work

An embedding is generated (query_vector) but never passed to search; instead, query_text is supplied, forcing the adapter to re‑embed the same string. This doubles compute cost and latency.

-            query_vector = await vector_engine.embed_data([query])
-            query_vector = query_vector[0]
-            if query_vector is None or len(query_vector) == 0:
-                raise ValueError("Failed to generate query embedding.")
-
-            edge_distances = await vector_engine.search(
-                collection_name="EdgeType_relationship_name",
-                query_text=query,
-                limit=0,
-            )
+            query_vector = (await vector_engine.embed_data([query]))[0]
+            if not query_vector:
+                raise ValueError("Failed to generate query embedding.")
+
+            edge_distances = await vector_engine.search(
+                collection_name="EdgeType_relationship_name",
+                query_vector=query_vector,   # reuse pre‑computed embedding
+                limit=0,
+            )

Side note: limit=0 is translated to None inside the adapter. Confirm that this yields the intended “unlimited results” behaviour with your backend.

cognee/infrastructure/databases/vector/milvus/MilvusAdapter.py (1)

148-165: ⚠️ Potential issue

retrieve() returns raw dicts, breaking the interface contract

VectorDBInterface.retrieve() is expected to return List[ScoredResult] (or equivalent), but this implementation returns Milvus‑specific dictionaries. Down‑stream code expecting ScoredResult will break.
Convert the results:

-            return results
+            return [
+                ScoredResult(id=parse_id(row["id"]), payload=row, score=0)
+                for row in results
+            ]
cognee/infrastructure/databases/vector/lancedb/LanceDBAdapter.py (1)

160-177: ⚠️ Potential issue

normalize_distances gets raw dataframe rows, missing _distance key

normalize_distances expects an iterable of dicts containing _distance; passing result_values as produced by to_dict() means the function cannot find distances and will raise or return nonsense.
Map the results first:

-result_values = list(results.to_dict("index").values())
+result_values = [
+    {
+        "id": row["id"],
+        "payload": row["payload"],
+        "_distance": row["distance"],
+    }
+    for row in results.to_dict("index").values()
+]
cognee/infrastructure/databases/vector/weaviate_db/WeaviateAdapter.py (1)

80-88: 🛠️ Refactor suggestion

O(N²) vector lookup in create_data_points

data_points.index(data_point) inside a loop gives quadratic complexity. Use enumerate to fetch the already‑computed vector in O(N).

-        def convert_to_weaviate_data_points(data_point: DataPoint):
-            vector = data_vectors[data_points.index(data_point)]
+        def convert_to_weaviate_data_points(idx: int, data_point: DataPoint):
+            vector = data_vectors[idx]
 ...
-data_points = [convert_to_weaviate_data_points(data_point) for data_point in data_points]
+data_points = [
+    convert_to_weaviate_data_points(idx, dp) for idx, dp in enumerate(data_points)
+]
cognee/infrastructure/databases/vector/chromadb/ChromaDBAdapter.py (3)

314-317: 🛠️ Refactor suggestion

get_collection_names should normalise to a list of strings

Returning the raw objects leaks implementation details and complicates every consumer (see previous bug).
Convert once here and keep the public contract simple.

-        return await client.list_collections()
+        # Chroma returns a list of Collection objects / dicts.
+        collections = await client.list_collections()
+        return [
+            c.name if hasattr(c, "name") else c["name"]
+            for c in collections
+        ]

After this change you can simplify has_collection to:

return collection_name in await self.get_collection_names()

184-201: ⚠️ Potential issue

Parameter normalized is unused & limit = 0 may DOS the service

  1. The normalized flag is accepted but ignored. Either honour it or drop the parameter.

  2. Converting limit == 0 into await collection.count() can explode to the full collection size, potentially overwhelming memory / network.
    Prefer a hard cap or require the caller to pass an explicit positive integer.

Example fix:

-        if limit == 0:
-            limit = await collection.count()
+        if limit == 0:
+            raise InvalidValueError(
+                message="Limit must be greater than 0; requesting the whole "
+                "collection is not supported."
+            )

and use normalized when post‑processing:

if normalized:
    normalized_values = normalize_distances(vector_list)
else:
    normalized_values = [1 - item["_distance"] for item in vector_list]  # or raw

239-242: 🛠️ Refactor suggestion

Catching bare Exception hides programming errors

Swallowing every exception and returning an empty list makes debugging impossible and may produce silent data loss.
Catch only anticipated runtime errors (CollectionNotFoundError, network time‑outs, etc.) and re‑raise the rest.

-        except Exception as e:
-            logger.error(f"Error in search: {str(e)}")
-            return []
+        except CollectionNotFoundError:
+            raise
+        except RuntimeError as e:  # adjust to concrete chromadb errors
+            logger.error(f"ChromaDB search failed: {e}")
+            return []
🧹 Nitpick comments (8)
cognee/modules/retrieval/utils/brute_force_triplet_search.py (1)

145-147: limit=0 fetches the entire collection – check scalability

The adapter interprets limit=0 as no limit, potentially returning every vector in large collections.
For most ranking scenarios only the top results are needed:

-                vector_engine.search(collection_name=collection_name, query_text=query, limit=0)
+                vector_engine.search(
+                    collection_name=collection_name,
+                    query_text=query,
+                    limit=top_k   # or another reasonable cap
+                )

Please verify the desired behaviour and adjust to prevent unnecessary load.

cognee/infrastructure/databases/vector/qdrant/QDrantAdapter.py (1)

183-204: Duplicate client.close() call – tidy up resource handling

await client.close() is executed inside the try and the finally block. Double closing is redundant and can raise errors in future client versions.

-            await client.close()
-            return [
+            return [
                 ScoredResult(
                     ...
                 )
             ]

Keep the single close in the finally block to centralise cleanup logic.

cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py (1)

210-210: with_vector parameter is ignored

The method declares with_vector but never includes the vector in the output when it is True. Either honour it (e.g. add a vector field to ScoredResult) or remove the parameter to avoid a misleading API.

cognee/infrastructure/databases/vector/milvus/MilvusAdapter.py (2)

153-155: Minor: shadowing the built‑in id inside f‑string comprehension

While harmless, using id as the loop variable shadows Python’s built‑in id() which can confuse readers.

", ".join(f'"{dp_id}"' for dp_id in data_point_ids)

193-210: Consider normalising Milvus distances for consistency

Other adapters map raw distances to a 0‑1 score via normalize_distances. Returning bare distances here makes score semantics adapter‑specific and complicates ranking across back‑ends.

cognee/infrastructure/databases/vector/lancedb/LanceDBAdapter.py (1)

165-167: limit == 0 semantics rely on an extra DB call

Calling await collection.count_rows() for every unlimited search adds latency. Consider treating limit <= 0 as None and letting LanceDB handle “no limit”, mirroring other adapters.

cognee/infrastructure/databases/vector/chromadb/ChromaDBAdapter.py (2)

121-127: Avoid double round‑trip in get_collection

has_collection() already hits the server. Immediately calling client.get_collection() makes a second request even when the collection is missing.
You can rely on the single get_collection call and catch the provider‑specific exception, mapping it to CollectionNotFoundError, e.g.:

-        if not await self.has_collection(collection_name):
-            raise CollectionNotFoundError(f"Collection '{collection_name}' not found!")
-
-        client = await self.get_connection()
-        return await client.get_collection(collection_name)
+        client = await self.get_connection()
+        try:
+            return await client.get_collection(collection_name)
+        except Exception:
+            # Map the provider error to the domain error
+            raise CollectionNotFoundError(
+                f"Collection '{collection_name}' not found!"
+            ) from None

This halves latency and network traffic for the common case.


253-261: Keep default limit consistent with search

search now defaults to limit=15 while batch_search still uses limit=5.
Recommend aligning both to avoid surprising behaviour.

-        limit: int = 5,
+        limit: int = 15,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1364fb and ae82c5a.

⛔ Files ignored due to path filters (3)
  • cognee-mcp/pyproject.toml is excluded by !**/*.toml
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (9)
  • cognee/infrastructure/databases/vector/chromadb/ChromaDBAdapter.py (8 hunks)
  • cognee/infrastructure/databases/vector/lancedb/LanceDBAdapter.py (7 hunks)
  • cognee/infrastructure/databases/vector/milvus/MilvusAdapter.py (9 hunks)
  • cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py (1 hunks)
  • cognee/infrastructure/databases/vector/qdrant/QDrantAdapter.py (6 hunks)
  • cognee/infrastructure/databases/vector/weaviate_db/WeaviateAdapter.py (10 hunks)
  • cognee/modules/graph/cognee_graph/CogneeGraph.py (1 hunks)
  • cognee/modules/retrieval/utils/brute_force_triplet_search.py (1 hunks)
  • cognee/tests/unit/modules/retrieval/utils/brute_force_triplet_search_test.py (0 hunks)
💤 Files with no reviewable changes (1)
  • cognee/tests/unit/modules/retrieval/utils/brute_force_triplet_search_test.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
cognee/infrastructure/databases/vector/qdrant/QDrantAdapter.py (5)
cognee/shared/logging_utils.py (2)
  • get_logger (137-158)
  • error (127-128)
cognee/infrastructure/engine/utils/parse_id.py (1)
  • parse_id (4-10)
cognee/exceptions/exceptions.py (1)
  • InvalidValueError (38-45)
cognee/infrastructure/engine/models/DataPoint.py (1)
  • DataPoint (16-96)
cognee/infrastructure/databases/vector/exceptions/exceptions.py (1)
  • CollectionNotFoundError (5-12)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: End-to-End Tests / Run Telemetry Pipeline Test
  • GitHub Check: End-to-End Tests / Server Start Test
  • GitHub Check: End-to-End Tests / S3 Bucket Test
  • GitHub Check: End-to-End Tests / Deletion Test
  • GitHub Check: End-to-End Tests / Deduplication Test
  • GitHub Check: Basic Tests / Run Unit Tests
  • GitHub Check: Basic Tests / Run Simple Examples
  • GitHub Check: Basic Tests / Run Basic Graph Tests
  • GitHub Check: Basic Tests / Run Integration Tests
🔇 Additional comments (1)
cognee/infrastructure/databases/vector/weaviate_db/WeaviateAdapter.py (1)

170-173: get_collection may need await with async client

If weaviate-python’s async variant makes collections.get() a coroutine, omitting await will return a coroutine object and break later calls. Please confirm the API version and add await if required.

@borisarzentar borisarzentar merged commit cd9c489 into dev Apr 30, 2025
50 checks passed
@borisarzentar borisarzentar deleted the feature/cog-1743-unify-get_distance_from_collection_names-and-search branch April 30, 2025 09:11
@coderabbitai coderabbitai bot mentioned this pull request May 13, 2025
@coderabbitai coderabbitai bot mentioned this pull request May 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant