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 bug where an edge case exception causes a query to not be removed… #88

Merged
merged 3 commits into from
Sep 27, 2024

Conversation

eriktaubeneck
Copy link
Member

@eriktaubeneck eriktaubeneck commented Sep 26, 2024

… from active running queries

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of query execution by ensuring proper cleanup of running queries, even in the event of an error.
    • Added tests to verify the behavior of the query manager when exceptions occur during query execution.

Copy link

vercel bot commented Sep 26, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
draft ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 27, 2024 0:32am

Copy link
Contributor

coderabbitai bot commented Sep 26, 2024

Walkthrough

The changes introduce a try block around the query.start() method call in the run_query function. This modification ensures that the cleanup operation, specifically the removal of the query from the running_queries dictionary, is executed in a finally block. Additionally, a new test function has been added to verify the behavior of the QueryManager when an exception occurs during query execution.

Changes

Files Change Summary
sidecar/app/query/base.py Added a try block around query.start() in run_query to ensure consistent cleanup in finally.
sidecar/tests/app/query/test_base.py Added test_query_manager_run_query_exception to test QueryManager behavior on exceptions during start.

Poem

In the code where queries run,
A little change, oh what fun!
With try and finally in place,
Cleanup now has a steady grace.
Hopping through, we fix and play,
Ensuring all is clear each day! 🐰✨


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 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.

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: 0

🧹 Outside diff range and nitpick comments (1)
sidecar/app/query/base.py (1)

204-208: Approve changes with suggestions for improvement

The introduction of the try-finally block effectively addresses the PR objective by ensuring that queries are always removed from running_queries, even in edge cases where exceptions occur. This change improves the reliability of resource management and fixes the reported bug.

However, consider the following suggestions to further enhance error handling and maintain system observability:

  1. Add explicit exception handling to log the error before it's potentially suppressed.
  2. Re-raise the exception after cleanup to inform the caller about the failure.

Here's a suggested implementation that incorporates these improvements:

def run_query(self, query: Query):
    if not self.capacity_available:
        raise MaxQueriesRunningError(
            f"Only {self.max_parallel_queries} allowed. Currently running {self}"
        )

    self.running_queries[query.query_id] = query
    try:
        query.start()
    except Exception as e:
        query.logger.exception(f"Error occurred while running query: {e}")
        raise  # Re-raise the exception after logging
    finally:
        # always remove this
        del self.running_queries[query.query_id]

This implementation ensures that:

  1. Exceptions are logged, maintaining visibility into errors.
  2. The query is always removed from running_queries.
  3. The original exception is re-raised, allowing callers to handle or respond to the error appropriately.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 40e7c9b and 679dada.

📒 Files selected for processing (1)
  • sidecar/app/query/base.py (1 hunks)

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

🧹 Outside diff range and nitpick comments (2)
sidecar/tests/app/query/test_base.py (2)

124-124: Fix typo in function name

There's a typo in the function name. "manger" should be "manager".

-def test_query_manger_run_query_exception():
+def test_query_manager_run_query_exception():

124-140: Add a comment explaining the test's purpose

Consider adding a docstring or comment to explain the purpose of this test. This will help other developers understand the specific scenario being tested.

Add a comment like this at the beginning of the function:

def test_query_manager_run_query_exception():
    """
    Test that when an exception occurs during query execution:
    1. The exception is properly raised
    2. The query is removed from running_queries
    3. The query manager's capacity is restored
    """
🧰 Tools
🪛 Ruff

134-134: pytest.raises(Exception) should be considered evil

(B017)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 679dada and fcaaf2a.

📒 Files selected for processing (1)
  • sidecar/tests/app/query/test_base.py (1 hunks)
🧰 Additional context used
🪛 Ruff
sidecar/tests/app/query/test_base.py

134-134: pytest.raises(Exception) should be considered evil

(B017)

🔇 Additional comments (1)
sidecar/tests/app/query/test_base.py (1)

124-140: LGTM: Test logic is sound

The overall logic of the test is good. It correctly verifies that:

  1. The exception is raised
  2. The start method is called exactly once
  3. The query is not left in the running_queries list
  4. The query manager's capacity is available after the exception

These checks ensure that the QueryManager handles exceptions gracefully and maintains its state correctly.

🧰 Tools
🪛 Ruff

134-134: pytest.raises(Exception) should be considered evil

(B017)

sidecar/tests/app/query/test_base.py Show resolved Hide resolved
Copy link
Collaborator

@akoshelev akoshelev left a comment

Choose a reason for hiding this comment

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

nice test!

sidecar/tests/app/query/test_base.py Outdated Show resolved Hide resolved
Co-authored-by: Alex Koshelev <akoshelev@users.noreply.github.com>
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: 0

🧹 Outside diff range and nitpick comments (1)
sidecar/tests/app/query/test_base.py (1)

124-140: Improve exception handling specificity

The test function effectively verifies the behavior of QueryManager when an exception occurs during query execution. However, using a broad Exception class makes the test less precise and could potentially catch unintended exceptions.

Consider implementing the following improvements:

  1. Define a specific exception class for query start errors:
class QueryStartError(Exception):
    pass
  1. Update the test to use this specific exception:
 def mock_exception():
-    raise Exception
+    raise QueryStartError("Error starting query")

 with mock.patch(
     "sidecar.app.query.base.Query.start", side_effect=mock_exception
 ) as mock_start:
-    with pytest.raises(Exception):
+    with pytest.raises(QueryStartError):
         query_manager.run_query(query)

These changes will make the test more precise and address the static analysis warning about using pytest.raises(Exception).

🧰 Tools
🪛 Ruff

134-134: pytest.raises(Exception) should be considered evil

(B017)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fcaaf2a and 89979f1.

📒 Files selected for processing (1)
  • sidecar/tests/app/query/test_base.py (1 hunks)
🧰 Additional context used
🪛 Ruff
sidecar/tests/app/query/test_base.py

134-134: pytest.raises(Exception) should be considered evil

(B017)

@eriktaubeneck eriktaubeneck merged commit d3253a8 into main Sep 27, 2024
3 checks passed
@eriktaubeneck eriktaubeneck deleted the query-running-bug branch September 27, 2024 04:00
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.

2 participants