Skip to content

Clean up: warn when functionality is not available #638

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

Merged
merged 8 commits into from
Apr 26, 2025
Merged

Conversation

jan-janssen
Copy link
Member

@jan-janssen jan-janssen commented Apr 26, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new function to retrieve cached task data from a specified directory.
  • Bug Fixes

    • Improved reliability of cache data retrieval by always including the relevant function in module exports.
  • Documentation

    • Enhanced docstring for the queue ID retrieval function to provide clearer usage details.
  • Refactor

    • Updated and streamlined import paths for several functions across the codebase to improve maintainability.

Copy link
Contributor

coderabbitai bot commented Apr 26, 2025

Warning

Rate limit exceeded

@jan-janssen has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 21 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 0f8975e and c5ef8ad.

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

Walkthrough

This change moves the get_cache_data function from its previous location in executorlib.standalone.hdf and executorlib.task_scheduler.file.hdf to a new dedicated module, executorlib.standalone.cache. All relevant imports throughout the codebase are updated to reference the new module for get_cache_data and related entities. The __init__.py file is updated to always export get_cache_data directly. Additionally, some imports in other modules are localized or updated to reflect the new module organization, and redundant code such as suppressed imports and unused variables are removed.

Changes

File(s) Change Summary
executorlib/__init__.py Changed conditional import of get_cache_data to unconditional import from standalone.cache; always exported.
executorlib/standalone/cache.py New module defining get_cache_data for reading cached HDF5 data from a cache directory.
executorlib/task_scheduler/file/hdf.py Removed get_cache_data; now imports group_dict from standalone.cache; improved docstring for get_queue_id.
executorlib/task_scheduler/file/backend.py,
executorlib/task_scheduler/file/queue_spawner.py,
executorlib/task_scheduler/file/shared.py,
executorlib/task_scheduler/interactive/shared.py,
tests/test_cache_backend_execute.py,
tests/test_standalone_hdf.py
Updated imports of dump, load, get_output, get_runtime, and get_queue_id to use task_scheduler.file.hdf instead of standalone.hdf.
executorlib/executor/flux.py Moved import of FluxPythonSpawner and validate_max_workers inside function; removed suppressed import.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MainModule
    participant StandaloneCache
    participant HDF5File

    User->>MainModule: Call get_cache_data(cache_directory)
    MainModule->>StandaloneCache: get_cache_data(cache_directory)
    StandaloneCache->>HDF5File: Open and read cache.h5out files
    HDF5File-->>StandaloneCache: Return deserialized data
    StandaloneCache-->>MainModule: Return list of cache data dicts
    MainModule-->>User: Return cache data
Loading

Possibly related PRs

  • Get data from cache #525: Originally introduced get_cache_data in executorlib.standalone.hdf.py, which this PR now moves and refactors.
  • Implement Caching #435: Added cache directory support and caching mechanisms, directly related to the handling of cache data in this PR.
  • Create cache directory #601: Modified the internal implementation of get_cache_data to support nested directory structures, which is further refactored in this PR.

Poem

In the warren of code, a cache now stands,
Moved to its burrow with careful hands.
Imports tidied, exports made clear,
Cache data retrieval is always near.
Hopping through modules, no more to roam,
The rabbit now finds its cache at home.
🐇✨

✨ 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.
    • 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.
  • @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

codecov bot commented Apr 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.82%. Comparing base (ba0f8ab) to head (c5ef8ad).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #638      +/-   ##
==========================================
+ Coverage   96.67%   96.82%   +0.14%     
==========================================
  Files          29       30       +1     
  Lines        1293     1291       -2     
==========================================
  Hits         1250     1250              
+ Misses         43       41       -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: 0

🧹 Nitpick comments (4)
executorlib/task_scheduler/file/cache.py (4)

19-19: Consider moving import to module level.

The h5py import is placed inside the function body rather than at the module level like other imports. This creates inconsistency in the import style. Unless there's a specific reason for lazy loading, consider moving this import to the top of the file with other imports.


22-25: Reconsider directory creation logic.

The current implementation creates directories for every task key regardless of whether the file already exists:

file_name = os.path.join(cache_directory, task_key, "cache.h5out")
os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
if os.path.exists(file_name):
    # Process file...

This seems inefficient. Consider only creating directories when necessary or reordering these operations for better clarity:

- file_name = os.path.join(cache_directory, task_key, "cache.h5out")
- os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
- if os.path.exists(file_name):
+ file_name = os.path.join(cache_directory, task_key, "cache.h5out")
+ if os.path.exists(file_name):

9-34: Consider adding error handling for file operations.

The function performs file I/O operations without any error handling for cases like:

  • Permission issues when accessing directories or files
  • Corrupted HDF5 files
  • Unexpected file formats

Consider adding try-except blocks to gracefully handle these scenarios and provide meaningful error messages.

Example:

def get_cache_data(cache_directory: str) -> list[dict]:
    import h5py
    
    file_lst = []
    try:
        for task_key in os.listdir(cache_directory):
            file_name = os.path.join(cache_directory, task_key, "cache.h5out")
            if os.path.exists(file_name):
                try:
                    with h5py.File(file_name, "r") as hdf:
                        file_content_dict = {
                            key: cloudpickle.loads(np.void(hdf["/" + key]))
                            for key in group_dict.values()
                            if key in hdf
                        }
                    file_content_dict["filename"] = file_name
                    file_lst.append(file_content_dict)
                except (IOError, OSError) as e:
                    # Log the error or handle it appropriately
                    print(f"Error reading file {file_name}: {str(e)}")
    except (IOError, OSError) as e:
        # Log the error or handle it appropriately
        print(f"Error accessing directory {cache_directory}: {str(e)}")
    
    return file_lst

17-17: Fix typo in docstring.

There's a small typo in the docstring return description:

- list[dict]: List of dictionaries each representing on of the HDF5 files in the cache directory.
+ list[dict]: List of dictionaries each representing one of the HDF5 files in the cache directory.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd1830a and 62793be.

📒 Files selected for processing (3)
  • executorlib/__init__.py (1 hunks)
  • executorlib/standalone/hdf.py (1 hunks)
  • executorlib/task_scheduler/file/cache.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • executorlib/init.py
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: unittest_flux_openmpi
  • GitHub Check: notebooks_integration
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.12)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.13)
  • GitHub Check: unittest_openmpi (macos-latest, 3.13)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.13)
  • GitHub Check: unittest_mpich (macos-latest, 3.13)
  • GitHub Check: unittest_old
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.11)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.12)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.11)
  • GitHub Check: unittest_win
  • GitHub Check: notebooks
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-openmpi.yml)
  • GitHub Check: unittest_flux_mpich
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-mpich.yml)
🔇 Additional comments (1)
executorlib/standalone/hdf.py (1)

100-108: Good improvement to documentation.

The addition of a detailed docstring for get_queue_id improves code readability and maintains consistency with the documentation style of other functions in this file.

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)
executorlib/standalone/cache.py (1)

32-32: Directory creation in a read function could have side effects.

This function primarily reads cache data, but it's also creating directories with os.makedirs(). Creating directories in what appears to be a read-only function might have unintended side effects or be confusing to users.

Consider separating directory creation from data reading functionality to maintain clear separation of concerns:

- os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
+ if not os.path.exists(os.path.join(cache_directory, task_key)):
+     continue
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 62793be and 0f8975e.

📒 Files selected for processing (9)
  • executorlib/__init__.py (1 hunks)
  • executorlib/standalone/cache.py (1 hunks)
  • executorlib/task_scheduler/file/backend.py (1 hunks)
  • executorlib/task_scheduler/file/hdf.py (2 hunks)
  • executorlib/task_scheduler/file/queue_spawner.py (1 hunks)
  • executorlib/task_scheduler/file/shared.py (1 hunks)
  • executorlib/task_scheduler/interactive/shared.py (1 hunks)
  • tests/test_cache_backend_execute.py (1 hunks)
  • tests/test_standalone_hdf.py (1 hunks)
✅ Files skipped from review due to trivial changes (5)
  • executorlib/task_scheduler/file/queue_spawner.py
  • tests/test_standalone_hdf.py
  • executorlib/task_scheduler/file/backend.py
  • executorlib/task_scheduler/interactive/shared.py
  • tests/test_cache_backend_execute.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • executorlib/init.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
executorlib/task_scheduler/file/shared.py (1)
executorlib/task_scheduler/file/hdf.py (2)
  • dump (10-25)
  • get_output (55-71)
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: unittest_mpich (macos-latest, 3.13)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.13)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.12)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.11)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.11)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.12)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.13)
  • GitHub Check: unittest_openmpi (macos-latest, 3.13)
  • GitHub Check: unittest_old
  • GitHub Check: notebooks_integration
  • GitHub Check: unittest_flux_openmpi
  • GitHub Check: unittest_flux_mpich
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-openmpi.yml)
  • GitHub Check: unittest_win
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-mpich.yml)
  • GitHub Check: notebooks
  • GitHub Check: minimal
🔇 Additional comments (5)
executorlib/task_scheduler/file/shared.py (1)

11-11: Updated import path looks good.

The import has been updated to use executorlib.task_scheduler.file.hdf instead of the previous location. This change is consistent with the refactoring strategy to centralize HDF-related functionality in this module.

executorlib/task_scheduler/file/hdf.py (2)

7-7: Import change for group_dict is appropriate.

The group_dict import now comes from the newly created executorlib.standalone.cache module, properly aligning with the refactoring strategy to centralize cache-related functionality.


92-100: Good addition of detailed docstring.

Adding a comprehensive docstring for the get_queue_id function improves code documentation and maintainability. The docstring clearly explains the function's purpose, parameters, and return value.

executorlib/standalone/cache.py (2)

1-14: Clean implementation of module and constants.

The new module and group_dict definition look well-organized with clear naming conventions. Moving this dictionary to the cache module makes sense since it's used for cache data field mapping.


17-27: Lazy import of h5py aligns with PR objective.

The function docstring is clear, and importing h5py within the function body (rather than at the module level) is a good pattern that allows the module to be imported even when h5py is not available. This aligns with the PR objective to "warn when functionality is not available."

Comment on lines +29 to +42
file_lst = []
for task_key in os.listdir(cache_directory):
file_name = os.path.join(cache_directory, task_key, "cache.h5out")
os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
if os.path.exists(file_name):
with h5py.File(file_name, "r") as hdf:
file_content_dict = {
key: cloudpickle.loads(np.void(hdf["/" + key]))
for key in group_dict.values()
if key in hdf
}
file_content_dict["filename"] = file_name
file_lst.append(file_content_dict)
return file_lst
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

Missing error handling for file operations.

The function doesn't include error handling for scenarios like corrupted HDF5 files, permission issues, or other I/O errors that might occur when reading files.

Consider adding try-except blocks to handle potential exceptions:

 for task_key in os.listdir(cache_directory):
     file_name = os.path.join(cache_directory, task_key, "cache.h5out")
     os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
     if os.path.exists(file_name):
-        with h5py.File(file_name, "r") as hdf:
-            file_content_dict = {
-                key: cloudpickle.loads(np.void(hdf["/" + key]))
-                for key in group_dict.values()
-                if key in hdf
-            }
-        file_content_dict["filename"] = file_name
-        file_lst.append(file_content_dict)
+        try:
+            with h5py.File(file_name, "r") as hdf:
+                file_content_dict = {
+                    key: cloudpickle.loads(np.void(hdf["/" + key]))
+                    for key in group_dict.values()
+                    if key in hdf
+                }
+                file_content_dict["filename"] = file_name
+                file_lst.append(file_content_dict)
+        except (OSError, KeyError, ValueError) as e:
+            # Log or handle the error as appropriate
+            print(f"Error reading cache file {file_name}: {e}")
+            continue
📝 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
file_lst = []
for task_key in os.listdir(cache_directory):
file_name = os.path.join(cache_directory, task_key, "cache.h5out")
os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
if os.path.exists(file_name):
with h5py.File(file_name, "r") as hdf:
file_content_dict = {
key: cloudpickle.loads(np.void(hdf["/" + key]))
for key in group_dict.values()
if key in hdf
}
file_content_dict["filename"] = file_name
file_lst.append(file_content_dict)
return file_lst
file_lst = []
for task_key in os.listdir(cache_directory):
file_name = os.path.join(cache_directory, task_key, "cache.h5out")
os.makedirs(os.path.join(cache_directory, task_key), exist_ok=True)
if os.path.exists(file_name):
try:
with h5py.File(file_name, "r") as hdf:
file_content_dict = {
key: cloudpickle.loads(np.void(hdf["/" + key]))
for key in group_dict.values()
if key in hdf
}
file_content_dict["filename"] = file_name
file_lst.append(file_content_dict)
except (OSError, KeyError, ValueError) as e:
# Log or handle the error as appropriate
print(f"Error reading cache file {file_name}: {e}")
continue
return file_lst

@jan-janssen jan-janssen reopened this Apr 26, 2025
@jan-janssen jan-janssen merged commit 83691dd into main Apr 26, 2025
31 checks passed
@jan-janssen jan-janssen deleted the import-error branch April 26, 2025 10:12
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.

1 participant