Skip to content

Conversation

@jan-janssen
Copy link
Member

@jan-janssen jan-janssen commented Jul 16, 2025

Summary by CodeRabbit

  • New Features
    • Added a function to terminate tasks found in a cache directory, allowing for easier cleanup of queued jobs.
    • Made this new task termination feature available in the public API when supported by the environment.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 16, 2025

Walkthrough

A new function, terminate_tasks_in_cache, was introduced in the queue_spawner module to recursively find and terminate queued tasks based on files in a cache directory. The executorlib package now conditionally exposes this function in its public API, depending on the successful import from the queue_spawner module. Tests were added to verify the termination functions execute without errors.

Changes

File(s) Change Summary
executorlib/task_scheduler/file/queue_spawner.py Added terminate_tasks_in_cache to scan cache directories, extract queue IDs, and terminate jobs; updated docstrings for backend parameter.
executorlib/init.py Conditionally imported and exposed terminate_tasks_in_cache in __all__ for public API access.
tests/test_fluxclusterexecutor.py Added tests for terminate_with_pysqa and terminate_tasks_in_cache verifying execution and return values; updated imports accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant executorlib
    participant queue_spawner
    participant FileSystem
    participant QueueSystem

    User->>executorlib: import terminate_tasks_in_cache
    executorlib->>queue_spawner: import terminate_tasks_in_cache (if available)

    User->>queue_spawner: terminate_tasks_in_cache(cache_directory)
    queue_spawner->>FileSystem: Recursively scan for *_i.h5 files
    loop For each found file
        queue_spawner->>queue_spawner: get_queue_id(file)
        queue_spawner->>QueueSystem: terminate_with_pysqa(queue_id, config_directory, backend)
    end
Loading

Poem

In the warren of tasks, deep and wide,
A new bunny hops to seek and decide—
Through cachey tunnels, it finds each queue,
Snipping old jobs, making space anew.
Now with a whisker-twitch, you can call,
And terminate tasks—one hop for all!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.

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

🧹 Nitpick comments (2)
executorlib/task_scheduler/file/queue_spawner.py (2)

130-131: Fix unused loop variable.

The static analysis tool correctly identifies that the folder variable is not used within the loop body.

-    for root, folder, files in os.walk(cache_directory):
+    for root, _, files in os.walk(cache_directory):

131-131: Consider using a more robust file filtering approach.

The current string slicing approach for filtering files ending with "_i.h5" works but could be improved for better readability and maintainability.

-        hdf5_file_lst += [os.path.join(root, f) for f in files if f[-5:] == "_i.h5"]
+        hdf5_file_lst += [os.path.join(root, f) for f in files if f.endswith("_i.h5")]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2735ed8 and a8b8c8c.

📒 Files selected for processing (2)
  • executorlib/__init__.py (1 hunks)
  • executorlib/task_scheduler/file/queue_spawner.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
executorlib/task_scheduler/file/queue_spawner.py (1)
executorlib/task_scheduler/file/hdf.py (1)
  • get_queue_id (98-112)
executorlib/__init__.py (1)
executorlib/task_scheduler/file/queue_spawner.py (1)
  • terminate_tasks_in_cache (116-138)
🪛 Ruff (0.12.2)
executorlib/task_scheduler/file/queue_spawner.py

130-130: Loop control variable folder not used within loop body

Rename unused folder to _folder

(B007)

🔇 Additional comments (1)
executorlib/__init__.py (1)

39-44: Well-implemented conditional import pattern.

The conditional import follows Python best practices for optional functionality. The try-except block gracefully handles import failures, and the function is only exposed in the public API when successfully imported.

Comment on lines 116 to 128
def terminate_tasks_in_cache(
cache_directory: str,
config_directory: Optional[str] = None,
backend: Optional[str] = None,
):
"""
Delete all jobs stored in the cache directory from the queuing system
Args:
cache_directory (str): The directory to store cache files.
config_directory (str, optional): path to the config directory.
backend (str, optional): name of the backend used to spawn tasks.
"""
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

Add input validation for cache_directory parameter.

The function doesn't validate that the cache_directory exists or is accessible, which could lead to unclear error messages.

def terminate_tasks_in_cache(
    cache_directory: str,
    config_directory: Optional[str] = None,
    backend: Optional[str] = None,
):
    """
    Delete all jobs stored in the cache directory from the queuing system

    Args:
        cache_directory (str): The directory to store cache files.
        config_directory (str, optional): path to the config directory.
        backend (str, optional): name of the backend used to spawn tasks.
    """
+    if not os.path.exists(cache_directory):
+        raise ValueError(f"Cache directory does not exist: {cache_directory}")
+    if not os.path.isdir(cache_directory):
+        raise ValueError(f"Cache directory is not a directory: {cache_directory}")

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In executorlib/task_scheduler/file/queue_spawner.py around lines 116 to 128, the
function terminate_tasks_in_cache lacks validation for the cache_directory
parameter. Add input validation to check if cache_directory exists and is
accessible before proceeding. If the directory does not exist or is not
accessible, raise a clear and descriptive exception to prevent unclear errors
later in the function.

Comment on lines 133 to 138
for f in hdf5_file_lst:
terminate_with_pysqa(
queue_id=get_queue_id(f),
config_directory=config_directory,
backend=backend,
)
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

Add error handling for individual task termination failures.

The function doesn't handle cases where get_queue_id returns None or where terminate_with_pysqa might fail for individual files. This could cause the entire operation to fail when only some tasks have issues.

    for f in hdf5_file_lst:
-        terminate_with_pysqa(
-            queue_id=get_queue_id(f),
-            config_directory=config_directory,
-            backend=backend,
-        )
+        try:
+            queue_id = get_queue_id(f)
+            if queue_id is not None:
+                terminate_with_pysqa(
+                    queue_id=queue_id,
+                    config_directory=config_directory,
+                    backend=backend,
+                )
+        except Exception:
+            # Continue processing other files even if one fails
+            pass
📝 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
for f in hdf5_file_lst:
terminate_with_pysqa(
queue_id=get_queue_id(f),
config_directory=config_directory,
backend=backend,
)
for f in hdf5_file_lst:
try:
queue_id = get_queue_id(f)
if queue_id is not None:
terminate_with_pysqa(
queue_id=queue_id,
config_directory=config_directory,
backend=backend,
)
except Exception:
# Continue processing other files even if one fails
pass
🤖 Prompt for AI Agents
In executorlib/task_scheduler/file/queue_spawner.py around lines 133 to 138, add
error handling inside the loop to manage cases where get_queue_id returns None
or terminate_with_pysqa raises an exception. For each file, check if
get_queue_id returns a valid ID before calling terminate_with_pysqa, and wrap
the termination call in a try-except block to catch and log errors without
stopping the entire loop.

@jan-janssen jan-janssen marked this pull request as draft July 16, 2025 20:44
@codecov
Copy link

codecov bot commented Jul 16, 2025

Codecov Report

Attention: Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.

Project coverage is 96.85%. Comparing base (5836485) to head (b276552).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
executorlib/__init__.py 60.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #739      +/-   ##
==========================================
- Coverage   96.96%   96.85%   -0.12%     
==========================================
  Files          31       31              
  Lines        1385     1398      +13     
==========================================
+ Hits         1343     1354      +11     
- Misses         42       44       +2     

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

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

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

96-102: Good test setup, but consider adding verification of internal calls.

The test properly sets up the cache directory with a test HDF5 file containing queue_id data, which matches the expected workflow. However, consider enhancing the test to verify that the termination actually occurs:

+    @unittest.mock.patch('executorlib.task_scheduler.file.queue_spawner.terminate_with_pysqa')
+    def test_terminate_tasks_in_cache(self, mock_terminate):
         file = os.path.join("executorlib_cache", "test_i.h5")
         dump(file_name=file, data_dict={"queue_id": 1})
-        self.assertIsNone(terminate_tasks_in_cache(
+        
+        result = terminate_tasks_in_cache(
             cache_directory="executorlib_cache",
             backend="flux",
-        ))
+        )
+        
+        self.assertIsNone(result)
+        mock_terminate.assert_called_once_with(
+            queue_id=1,
+            config_directory=None,
+            backend="flux"
+        )

This would verify that terminate_with_pysqa is called with the correct queue_id extracted from the cache file.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8b8c8c and b276552.

📒 Files selected for processing (2)
  • executorlib/task_scheduler/file/queue_spawner.py (3 hunks)
  • tests/test_fluxclusterexecutor.py (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • executorlib/task_scheduler/file/queue_spawner.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/test_fluxclusterexecutor.py (2)
executorlib/task_scheduler/file/queue_spawner.py (2)
  • terminate_with_pysqa (94-115)
  • terminate_tasks_in_cache (118-142)
executorlib/task_scheduler/file/hdf.py (1)
  • dump (11-28)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-openmpi.yml)
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-mpich.yml)
  • GitHub Check: notebooks_integration
🔇 Additional comments (1)
tests/test_fluxclusterexecutor.py (1)

12-12: LGTM: Import statement is correctly placed.

The import statement is properly structured within the try-except block to handle missing dependencies gracefully.

Comment on lines +62 to +63
def test_terminate_with_pysqa(self):
self.assertIsNone(terminate_with_pysqa(queue_id=1, backend="flux"))
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

Enhance test coverage for better validation.

The current test only verifies that the function executes without errors, but doesn't validate the actual termination behavior. Consider:

  1. Mock the QueueAdapter: Use mocking to verify that get_status_of_job and delete_job are called appropriately
  2. Test edge cases: Test scenarios where the job doesn't exist or is already finished
  3. Parameterize backends: Test both "slurm" and "flux" backends if possible

Example improvement:

+    @unittest.mock.patch('executorlib.task_scheduler.file.queue_spawner.QueueAdapter')
+    def test_terminate_with_pysqa(self, mock_qa_class):
+        mock_qa = mock_qa_class.return_value
+        mock_qa.get_status_of_job.return_value = "running"
+        
+        result = terminate_with_pysqa(queue_id=1, backend="flux")
+        
+        self.assertIsNone(result)
+        mock_qa.get_status_of_job.assert_called_once_with(process_id=1)
+        mock_qa.delete_job.assert_called_once_with(process_id=1)
-    def test_terminate_with_pysqa(self):
-        self.assertIsNone(terminate_with_pysqa(queue_id=1, backend="flux"))
📝 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
def test_terminate_with_pysqa(self):
self.assertIsNone(terminate_with_pysqa(queue_id=1, backend="flux"))
@unittest.mock.patch('executorlib.task_scheduler.file.queue_spawner.QueueAdapter')
def test_terminate_with_pysqa(self, mock_qa_class):
mock_qa = mock_qa_class.return_value
mock_qa.get_status_of_job.return_value = "running"
result = terminate_with_pysqa(queue_id=1, backend="flux")
self.assertIsNone(result)
mock_qa.get_status_of_job.assert_called_once_with(process_id=1)
mock_qa.delete_job.assert_called_once_with(process_id=1)
🤖 Prompt for AI Agents
In tests/test_fluxclusterexecutor.py around lines 62 to 63, the test for
terminate_with_pysqa only checks for no errors but does not verify the
function's behavior. Enhance the test by mocking the QueueAdapter to assert that
get_status_of_job and delete_job are called correctly. Add tests for edge cases
such as when the job does not exist or is already finished. Also, parameterize
the test to cover both "slurm" and "flux" backends to ensure broader coverage.

@jan-janssen jan-janssen merged commit 71bb2fb into main Jul 16, 2025
29 of 31 checks passed
@jan-janssen jan-janssen deleted the terminate_tasks_in_cache branch July 16, 2025 21:34
@coderabbitai coderabbitai bot mentioned this pull request Aug 5, 2025
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