Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: metrics in neo4j adapter [COG-1082] #487

Open
wants to merge 29 commits into
base: dev
Choose a base branch
from

Conversation

alekszievr
Copy link
Contributor

@alekszievr alekszievr commented Jan 30, 2025

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

Summary by CodeRabbit

  • New Features

    • Introduced enhanced graph management capabilities, allowing users to check for graph existence, project complete graphs, and remove graphs as needed.
    • Enabled the option to include detailed graph metrics—such as connectivity, diameter, and clustering—for more comprehensive insights.
  • Improvements

    • Updated various analytics operations to flexibly include optional metrics.
    • Enhanced timestamp consistency by shifting to database-managed timestamp values.

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Caution

Review failed

The head commit changed during the review from 81a4aa3 to f2ad1d4.

Walkthrough

This pull request updates various functions and methods across multiple modules to incorporate an include_optional parameter. The changes affect task instantiation in the API, the retrieval and computation of graph metrics in both GraphDB interfaces and adapter implementations, and the signature of the store_descriptive_metrics function. Additionally, database model columns for timestamps have been updated to use server-side defaults via SQLAlchemy’s func.now().

Changes

Files Change Summary
cognee/.../cognify_v2.py
cognee/.../store_descriptive_metrics.py
Updated to pass an include_optional parameter. In the API, the Task instantiation now includes include_optional=True and the store_descriptive_metrics function signature is updated accordingly.
cognee/.../graph_db_interface.py
cognee/.../networkx/adapter.py
Modified the get_graph_metrics method signature to accept an include_optional parameter. In the NetworkX adapter, the implementation now conditionally computes additional optional graph metrics using a new numpy import.
cognee/.../neo4j_driver/adapter.py Removed the old get_graph_metrics method and added three new methods: graph_exists, project_entire_graph, and drop_graph. A new implementation of get_graph_metrics computes detailed graph metrics via several asynchronous functions.
cognee/.../GraphMetrics.py Updated timestamp columns: replaced Python-side lambda defaults with SQLAlchemy’s func.now(), using server_default for created_at and onupdate for updated_at.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Store as store_descriptive_metrics
    participant GraphEngine as get_graph_metrics
    participant Neo4jAdapter

    Client->>Store: Call store_descriptive_metrics(data_points, include_optional)
    Store->>GraphEngine: get_graph_metrics(include_optional)
    GraphEngine->>Neo4jAdapter: Check graph_exists("myGraph")
    alt Graph does not exist
        Neo4jAdapter->>Neo4jAdapter: project_entire_graph("myGraph")
    end
    Neo4jAdapter->>Neo4jAdapter: Compute detailed graph metrics 
    Neo4jAdapter-->>GraphEngine: Return computed metrics
    GraphEngine-->>Store: Return metrics
    Store-->>Client: Return final result
Loading

Possibly related PRs

Suggested reviewers

  • borisarzentar
  • lxobr

Poem

In code I hop with joyful glee,
Adding options for you and me.
Metrics now dance, optional and bright,
Graphs reformed in a neo4j light.
I’m a rabbit in code, bouncing with might! 🐰✨
Keep on coding—hop to new heights!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @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.

@alekszievr alekszievr changed the base branch from dev to feat/cog-1082-metrics-in-networkx-adapter January 30, 2025 16:55
@alekszievr alekszievr requested a review from lxobr January 30, 2025 17:07
@alekszievr alekszievr self-assigned this Jan 30, 2025
@borisarzentar borisarzentar changed the title Feat: metrics in neo4j adapter [COG-1082] feat: metrics in neo4j adapter [COG-1082] Jan 31, 2025

async def _get_num_connected_components():
graph_name = "myGraph"
await self.drop_graph(graph_name)
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there reason we call drop_graph and project_entire_graph again here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We only need to do it once. I kept it in here to keep these methods interchangeable in case we want to remove one of them or change the order.
What do you think, should I remove one of them?

@alekszievr alekszievr force-pushed the feat/cog-1082-metrics-in-networkx-adapter branch from e89c9b9 to 27feae8 Compare February 3, 2025 14:37
@alekszievr alekszievr force-pushed the feat/cog-1082-metrics-in-networkx-adapter branch from 27feae8 to af8e798 Compare February 3, 2025 14:46
Base automatically changed from feat/cog-1082-metrics-in-networkx-adapter to dev February 3, 2025 17:05
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 2

🧹 Nitpick comments (8)
cognee/infrastructure/databases/graph/neo4j_driver/adapter.py (4)

573-577: Add logging after dropping the graph.
It might be helpful to log whether the graph was successfully dropped or was absent, for better traceability in production.

 async def drop_graph(self, graph_name="myGraph"):
     if await self.graph_exists(graph_name):
         drop_query = f"CALL gds.graph.drop('{graph_name}');"
         await self.query(drop_query)
+        logger.debug(f"Dropped graph '{{graph_name}}' successfully.")

633-636: Diameter not yet implemented.
If diameter is critical, consider GDS Shortest Path or BFS expansions. Let us know if you’d like assistance with a workable approach.


637-642: Average shortest path not yet implemented.
Likewise, GDS offers built-in algorithms for average path length. Let us know if you’d like to integrate it.


643-645: Average clustering not yet implemented.
For completeness, you may explore GDS or external libraries to compute clustering.

cognee/infrastructure/databases/graph/graph_db_interface.py (1)

59-59: Document the new parameter include_optional.
Adding a short docstring describing its usage will help future maintainers understand which metrics are impacted by this flag.

cognee/modules/data/methods/store_descriptive_metrics.py (1)

26-29: Add validation for the include_optional parameter.

Consider adding validation for the include_optional parameter to ensure it's a boolean value.

 async def store_descriptive_metrics(data_points: list[DataPoint], include_optional: bool):
+    if not isinstance(include_optional, bool):
+        raise ValueError("include_optional must be a boolean value")
     db_engine = get_relational_engine()
     graph_engine = await get_graph_engine()
     graph_metrics = await graph_engine.get_graph_metrics(include_optional)
cognee/api/v1/cognify/cognify_v2.py (1)

168-168: Consider making include_optional configurable.

The include_optional parameter is hardcoded to True. Consider making this configurable through the cognify config to allow flexibility in whether optional metrics are computed.

-            Task(store_descriptive_metrics, include_optional=True),
+            Task(store_descriptive_metrics, include_optional=cognee_config.include_optional_metrics),
cognee/infrastructure/databases/graph/networkx/adapter.py (1)

416-422: Improve error handling in clustering coefficient calculation.

The current implementation swallows exception details. Consider logging the full exception traceback for better debugging.

     def _get_avg_clustering(graph):
         try:
             return nx.average_clustering(nx.DiGraph(graph))
         except Exception as e:
-            logger.warning("Failed to calculate clustering coefficient: %s", e)
+            logger.warning("Failed to calculate clustering coefficient", exc_info=True)
             return None
🛑 Comments failed to post (2)
cognee/infrastructure/databases/graph/neo4j_driver/adapter.py (1)

647-649: ⚠️ Potential issue

Potential index/key error in node/edge data extraction.
nodes[0]["nodes"] or edges[0]["elements"] might raise an exception if the query returns an empty list or no matching keys. Consider validating non-empty results.

 num_nodes = len(nodes[0].get("nodes", [])) if nodes and "nodes" in nodes[0] else 0
 num_edges = len(edges[0].get("elements", [])) if edges and "elements" in edges[0] else 0
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        num_nodes = len(nodes[0].get("nodes", [])) if nodes and "nodes" in nodes[0] else 0
        num_edges = len(edges[0].get("elements", [])) if edges and "elements" in edges[0] else 0
cognee/infrastructure/databases/graph/networkx/adapter.py (1)

442-447: 🛠️ Refactor suggestion

Use None instead of -1 for missing optional metrics.

Using -1 as a sentinel value for missing optional metrics could be misleading as it might be interpreted as a valid metric value. Consider using None instead.

         optional_metrics = {
-            "num_selfloops": -1,
-            "diameter": -1,
-            "avg_shortest_path_length": -1,
-            "avg_clustering": -1,
+            "num_selfloops": None,
+            "diameter": None,
+            "avg_shortest_path_length": None,
+            "avg_clustering": None,
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            optional_metrics = {
                "num_selfloops": None,
                "diameter": None,
                "avg_shortest_path_length": None,
                "avg_clustering": None,
            }

@alekszievr alekszievr force-pushed the feat/cog-1082-metrics-in-neo4j-adapter branch from 81a4aa3 to f2ad1d4 Compare February 3, 2025 17:18
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.

3 participants