Skip to content

Conversation

@gkorland
Copy link
Contributor

@gkorland gkorland commented Oct 3, 2025

Add support for with clause by adding close and aclose

fix #128

Summary by CodeRabbit

  • New Features
    • Added context manager support — use with “with” and “async with” for automatic cleanup.
    • Added close/aclose methods to explicitly release connections.
    • Improved shutdown resilience by safely handling connection errors during close without interrupting application flow.

@gkorland gkorland requested review from Copilot and swilly22 October 3, 2025 08:15
@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2025

Warning

Rate limit exceeded

@gkorland has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1faec44 and db56499.

📒 Files selected for processing (1)
  • tests/test_close.py (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds sync and async context-manager lifecycle to FalkorDB: new close()/aclose() methods with best-effort RedisError handling, plus __enter__/__exit__ and __aenter__/__aexit__ to support with and async with. Imports RedisError for error handling.

Changes

Cohort / File(s) Summary
Async context management
falkordb/asyncio/falkordb.py
Imported RedisError; added async def aclose(self), async def __aenter__(self), and async def __aexit__(self, exc_type, exc_val, exc_tb) to enable async with and perform best-effort async connection close.
Sync context management
falkordb/falkordb.py
Imported RedisError; added def close(self), def __enter__(self), and def __exit__(self, exc_type, exc_val, exc_tb) to enable with and perform best-effort connection close.
Tests
tests/test_close.py
Added tests validating sync close() and context-manager behavior, and async aclose() plus async with behavior, including cases where underlying client lacks close or raises RedisError.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant App as Application
  participant DB as FalkorDB (sync)
  participant RC as Redis Client

  User->>App: with FalkorDB(...) as db:
  App->>DB: __enter__()
  DB-->>App: self
  App->>RC: (operations)
  App->>DB: __exit__(exc_type, exc_val, exc_tb)
  DB->>DB: close()
  alt close succeeds
    DB->>RC: close()
    RC-->>DB: ok
  else RedisError
    note right of DB: catch RedisError (best-effort)
  end
  DB-->>App: exit complete
Loading
sequenceDiagram
  autonumber
  actor User
  participant App as Application
  participant ADB as FalkorDB (async)
  participant ARC as Redis Client (async)

  User->>App: async with FalkorDB(...) as adb:
  App->>ADB: __aenter__()
  ADB-->>App: self
  App->>ARC: (async operations)
  App->>ADB: __aexit__(exc_type, exc_val, exc_tb)
  ADB->>ADB: aclose()
  alt aclose succeeds
    ADB->>ARC: aclose()
    ARC-->>ADB: ok
  else RedisError
    note right of ADB: catch RedisError (best-effort)
  end
  ADB-->>App: exit complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I hop through code with tidy grace,
New with-blocks snug, a cozy place.
Sync or async, I twitch and close—
Best-effort hush if Redis throws.
Thump-thump—connections rest, I boast! 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately describes the primary change of adding synchronous and asynchronous close methods to FalkorDB connections, matching the main content of the pull request.
Linked Issues Check ✅ Passed The pull request implements the requested context-manager support for both synchronous and asynchronous FalkorDB connections by adding close, enter, exit, aclose, aenter, and aexit methods and accompanying tests, thereby satisfying issue #128.
Out of Scope Changes Check ✅ Passed All modifications in the pull request pertain to adding the context-manager methods and related tests for FalkorDB connections, with no unrelated or extraneous changes detected.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds connection management functionality to both sync and async FalkorDB classes by implementing close methods and context manager support. This allows proper cleanup of Redis connections when the client is no longer needed.

  • Adds close() method and context manager support (__enter__/__exit__) to the sync FalkorDB class
  • Adds aclose() method and async context manager support (__aenter__/__aexit__) to the async FalkorDB class
  • Implements best-effort error handling that suppresses Redis errors during connection cleanup

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
falkordb/falkordb.py Adds connection cleanup methods and context manager support for sync operations
falkordb/asyncio/falkordb.py Adds async connection cleanup methods and async context manager support

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@codecov
Copy link

codecov bot commented Oct 3, 2025

Codecov Report

❌ Patch coverage is 92.30769% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.70%. Comparing base (ddf10bd) to head (db56499).

Files with missing lines Patch % Lines
falkordb/asyncio/falkordb.py 80.00% 2 Missing ⚠️
falkordb/falkordb.py 80.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #127      +/-   ##
==========================================
+ Coverage   91.69%   91.70%   +0.01%     
==========================================
  Files          36       37       +1     
  Lines        2685     2737      +52     
==========================================
+ Hits         2462     2510      +48     
- Misses        223      227       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gkorland gkorland changed the title add close and aclose add close and aclose on FalkorDB connections Oct 3, 2025
Copy link

@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: 1

🧹 Nitpick comments (1)
tests/test_close.py (1)

37-53: Add fallback test for async close.

The test correctly validates that aclose() is awaited in both explicit calls and async context managers. However, similar to the sync version, consider adding a test for the fallback scenario when the connection lacks an aclose() method.

Add a test similar to test_sync_close_fallback_disconnect for the async case:

@pytest.mark.asyncio
async def test_async_aclose_fallback_disconnect():
    db = object.__new__(AsyncFalkorDB)
    
    # connection has no aclose(), only a connection_pool.disconnect()
    mock_conn = SimpleNamespace()
    mock_conn.connection_pool = SimpleNamespace(disconnect=AsyncMock())
    db.connection = mock_conn
    
    await db.aclose()
    
    mock_conn.connection_pool.disconnect.assert_awaited_once()

Note: This will also fail with the current implementation and requires the same fallback logic fix in falkordb/asyncio/falkordb.py.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94a6ac4 and 1faec44.

📒 Files selected for processing (1)
  • tests/test_close.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tests/test_close.py (2)
falkordb/falkordb.py (1)
  • close (242-251)
falkordb/asyncio/falkordb.py (1)
  • aclose (202-211)
🪛 GitHub Actions: Test
tests/test_close.py

[error] 32-32: Test failure in test_sync_close_fallback_disconnect: AttributeError raised when closing DB connection; indicates fallback disconnect path may be incorrect.

🔇 Additional comments (2)
tests/test_close.py (2)

1-7: LGTM!

Imports are appropriate for testing both synchronous and asynchronous close behavior with mocked connections.


10-21: LGTM!

The test correctly verifies that the context manager calls close() on the underlying connection. The use of object.__new__ to bypass initialization is appropriate for unit testing.

@gkorland gkorland requested a review from Copilot October 3, 2025 08:59
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +213 to +222

async def __aenter__(self) -> "FalkorDB":
"""Return self to support async with-statement usage."""

return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
"""Close the connection when exiting an async with-statement."""

await self.aclose()
Copy link

Copilot AI Oct 3, 2025

Choose a reason for hiding this comment

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

[nitpick] Remove the extra blank line between the aclose method and aenter method to maintain consistent spacing with the sync version.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for with clause on FalkorDB conenction

2 participants