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

fix: Resolve reflection issue when running cognee a second time after… #373

Merged
merged 3 commits into from
Dec 16, 2024

Conversation

dexters1
Copy link
Collaborator

@dexters1 dexters1 commented Dec 16, 2024

… pruning data

When running cognee a second time after pruning data some metadata doesn't get pruned. This makes cognee believe some tables exist that have been deleted

Fix

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of database schema reflection and table access.
  • Refactor
    • Enhanced modularity by centralizing metadata management for dynamic table access.

… pruning data

When running cognee a second time after pruning data some metadata doesn't get pruned.
This makes cognee believe some tables exist that have been deleted

Fix
@dexters1 dexters1 self-assigned this Dec 16, 2024
Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

Walkthrough

The pull request modifies the PGVectorAdapter class in the PGVector database adapter, introducing changes to how database metadata is managed. The primary modification involves replacing Base.metadata with a new MetaData instance from SQLAlchemy. This change allows for more dynamic table access and schema reflection, potentially improving the adapter's flexibility in handling database collections and data points.

Changes

File Change Summary
cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py - Added MetaData import from SQLAlchemy
- Updated has_collection method to use metadata.tables
- Modified get_table method to return table from new metadata instance
- Adjusted create_collection and create_data_points methods to work with new metadata handling

Suggested Reviewers

  • hajdul88
  • Vasilije1990

Possibly related PRs

  • Fix pgvector search #360: Changes to the PGVectorAdapter class in the same file, suggesting a potential related modification to the vector database adapter

Poem

🐰 Metadata dancing, tables so light,
Reflecting schemas with SQLAlchemy might!
From Base to MetaData, a quantum leap,
Our vector adapter now dances so sweet!
Code modularity, oh what a delight! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request.


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.

Added fix when reflecting metadata to sqlite as well

Fix
@dexters1 dexters1 requested a review from hajdul88 December 16, 2024 10:28
hajdul88
hajdul88 previously approved these changes Dec 16, 2024
@dexters1 dexters1 requested a review from hajdul88 December 16, 2024 12:27
@dexters1 dexters1 marked this pull request as ready for review December 16, 2024 12:27
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: 2

🔭 Outside diff range comments (1)
cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py (1)

Potential issue with metadata cleanup during pruning operations

The implementation has a few concerns regarding proper cleanup during pruning:

  1. The prune() method in PGVectorAdapter only calls delete_database() which isn't implemented in the shown code
  2. There's no explicit cleanup of Base.metadata after table deletions
  3. The engine disposal is missing in the pruning operation

This could lead to stale metadata state after pruning operations. Specific changes needed:

  • Implement proper delete_database() method with table cleanup
  • Add Base.metadata.clear() after table deletions
  • Include engine.dispose() in cleanup
🔗 Analysis chain

Line range hint 51-155: Verify fix handles all pruning scenarios.

While the changes address the reflection issue, let's verify that it works correctly in all pruning scenarios.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the interaction between pruning and reflection

# Check for any remaining references to Base.metadata in the codebase
echo "Checking for remaining Base.metadata references..."
rg "Base\.metadata" --type py

# Check for proper cleanup in prune method
echo "Checking prune method implementation..."
rg "async def prune" -A 10 --type py

# Look for any TODO/FIXME comments related to pruning
echo "Checking for pruning-related TODOs..."
rg "TODO.*prun|FIXME.*prun" --type py

Length of output: 7480


Script:

#!/bin/bash
# Let's verify the PGVectorAdapter's delete_database implementation and its interaction with Base.metadata

# Check delete_database implementation
echo "Checking delete_database implementation in PGVectorAdapter..."
rg "async def delete_database" -A 15 --type py cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py

# Check if there's proper cleanup of Base.metadata after deletion
echo "Checking Base.metadata cleanup after deletion..."
rg "Base\.metadata\.clear|Base\.metadata\.remove" --type py

# Check for any drop table implementations
echo "Checking drop table implementations..."
rg "drop.*table|DROP.*TABLE" -A 5 --type py

Length of output: 4315


Script:

#!/bin/bash
# Let's check the complete implementation of PGVectorAdapter to understand table cleanup

echo "Checking PGVectorAdapter implementation..."
cat cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py

echo "Checking for any database cleanup utilities..."
rg "async def.*clean|async def.*delete" -A 10 cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py

echo "Checking for any database connection disposal..."
rg "dispose|close_all" --type py

Length of output: 12500

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2f2aa81 and 34b139a.

📒 Files selected for processing (1)
  • cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py (3 hunks)
🔇 Additional comments (1)
cognee/infrastructure/databases/vector/pgvector/PGVectorAdapter.py (1)

5-5: LGTM: Import addition is appropriate.

The addition of MetaData import is necessary for implementing the new reflection mechanism.

Comment on lines +51 to +56
# Create a MetaData instance to load table information
metadata = MetaData()
# Load table information from schema into MetaData
await connection.run_sync(metadata.reflect)

if collection_name in Base.metadata.tables:
if collection_name in metadata.tables:
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Good fix for reflection issue, but consider performance optimization.

The change correctly addresses the reflection issue by dynamically loading table information instead of relying on cached metadata. However, there are two concerns to address:

  1. Performance: Reflecting the entire schema on each collection check could be expensive.
  2. Error handling: Database reflection could fail and should be handled gracefully.

Consider implementing these improvements:

 async def has_collection(self, collection_name: str) -> bool:
     async with self.engine.begin() as connection:
         # Create a MetaData instance to load table information
         metadata = MetaData()
-        # Load table information from schema into MetaData
-        await connection.run_sync(metadata.reflect)
+        try:
+            # Only reflect the specific table we're interested in
+            await connection.run_sync(lambda conn: metadata.reflect(conn, only=[collection_name]))
+            return collection_name in metadata.tables
+        except Exception as e:
+            logger.error(f"Failed to reflect table {collection_name}: {str(e)}")
+            return False
-
-        if collection_name in metadata.tables:
-            return True
-        else:
-            return False
📝 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.

Suggested change
# Create a MetaData instance to load table information
metadata = MetaData()
# Load table information from schema into MetaData
await connection.run_sync(metadata.reflect)
if collection_name in Base.metadata.tables:
if collection_name in metadata.tables:
# Create a MetaData instance to load table information
metadata = MetaData()
try:
# Only reflect the specific table we're interested in
await connection.run_sync(lambda conn: metadata.reflect(conn, only=[collection_name]))
return collection_name in metadata.tables
except Exception as e:
logger.error(f"Failed to reflect table {collection_name}: {str(e)}")
return False

Comment on lines +150 to +155
# Create a MetaData instance to load table information
metadata = MetaData()
# Load table information from schema into MetaData
await connection.run_sync(metadata.reflect)
if collection_name in metadata.tables:
return metadata.tables[collection_name]
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to reduce code duplication and improve performance.

The table reflection logic is duplicated between has_collection and get_table. Consider extracting this into a shared private method for better maintainability and consistent error handling.

Here's a suggested refactor:

+    async def _reflect_table(self, connection, table_name: str) -> MetaData:
+        """
+        Reflect a specific table from the database.
+        
+        Args:
+            connection: The database connection
+            table_name: Name of the table to reflect
+            
+        Returns:
+            MetaData object containing the reflected table
+            
+        Raises:
+            EntityNotFoundError if table doesn't exist
+        """
+        metadata = MetaData()
+        try:
+            await connection.run_sync(lambda conn: metadata.reflect(conn, only=[table_name]))
+            if table_name not in metadata.tables:
+                raise EntityNotFoundError(f"Table '{table_name}' not found.")
+            return metadata
+        except Exception as e:
+            if isinstance(e, EntityNotFoundError):
+                raise
+            raise EntityNotFoundError(f"Failed to reflect table '{table_name}': {str(e)}")

     async def has_collection(self, collection_name: str) -> bool:
         async with self.engine.begin() as connection:
-            metadata = MetaData()
-            await connection.run_sync(metadata.reflect)
-            if collection_name in metadata.tables:
+            try:
+                await self._reflect_table(connection, collection_name)
                 return True
-            else:
+            except EntityNotFoundError:
                 return False

     async def get_table(self, collection_name: str) -> Table:
         async with self.engine.begin() as connection:
-            metadata = MetaData()
-            await connection.run_sync(metadata.reflect)
-            if collection_name in metadata.tables:
-                return metadata.tables[collection_name]
-            else:
-                raise EntityNotFoundError(message=f"Table '{collection_name}' not found.")
+            metadata = await self._reflect_table(connection, collection_name)
+            return metadata.tables[collection_name]

This refactor:

  1. Reduces code duplication
  2. Provides consistent error handling
  3. Improves performance by only reflecting the needed table
  4. Makes the code more maintainable
📝 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.

Suggested change
# Create a MetaData instance to load table information
metadata = MetaData()
# Load table information from schema into MetaData
await connection.run_sync(metadata.reflect)
if collection_name in metadata.tables:
return metadata.tables[collection_name]
async def _reflect_table(self, connection, table_name: str) -> MetaData:
"""
Reflect a specific table from the database.
Args:
connection: The database connection
table_name: Name of the table to reflect
Returns:
MetaData object containing the reflected table
Raises:
EntityNotFoundError if table doesn't exist
"""
metadata = MetaData()
try:
await connection.run_sync(lambda conn: metadata.reflect(conn, only=[table_name]))
if table_name not in metadata.tables:
raise EntityNotFoundError(f"Table '{table_name}' not found.")
return metadata
except Exception as e:
if isinstance(e, EntityNotFoundError):
raise
raise EntityNotFoundError(f"Failed to reflect table '{table_name}': {str(e)}")
async def has_collection(self, collection_name: str) -> bool:
async with self.engine.begin() as connection:
try:
await self._reflect_table(connection, collection_name)
return True
except EntityNotFoundError:
return False
async def get_table(self, collection_name: str) -> Table:
async with self.engine.begin() as connection:
metadata = await self._reflect_table(connection, collection_name)
return metadata.tables[collection_name]

@dexters1 dexters1 merged commit a312ce0 into dev Dec 16, 2024
24 checks passed
@dexters1 dexters1 deleted the fix-pgvector-reflection branch December 16, 2024 12:29
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.

2 participants