Skip to content

Conversation

@jan-janssen
Copy link
Member

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

Even when the user does not define a specific working directory, otherwise the submission script and the error log gets overwritten.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of job working directories by automatically creating a subdirectory based on the command name, ensuring better organization of job files.
  • Tests
    • Added a new test to verify job execution without specifying a working directory, ensuring consistent behavior.
    • Enhanced existing tests to validate cache directory contents and job completion status.

Even when the user does not define a specific working directory, otherwise the submission script and the error log gets overwritten.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 2, 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 12 minutes and 0 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 da6f689 and 0d9ce2b.

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

Walkthrough

The logic for setting the working directory when submitting a job has been updated. Instead of always using the cache directory, the code now derives a subdirectory name from the command's last argument, creates that subdirectory under the cache directory if it doesn't exist, and sets it as the working directory. Additionally, a test was added to verify executor behavior when the cwd is not specified.

Changes

File(s) Change Summary
executorlib/task_scheduler/file/queue_spawner.py Made cache_directory mandatory; changed working directory logic to create/use a subdirectory under cache directory based on command argument.
tests/test_fluxclusterexecutor.py Added test_executor_no_cwd to test executor behavior without specifying cwd in resource dict; enhanced test_executor with additional assertions.

Poem

In the warren of code where tasks are spun,
A new folder is made for each job begun.
No more crowding in one cachey space,
Each command gets its own little place.
🗂️🐇 The scheduler hops, neat and spry,
Making new homes as jobs pass by!

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

@codecov
Copy link

codecov bot commented Jul 2, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.89%. Comparing base (5f87bb4) to head (0d9ce2b).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #698      +/-   ##
==========================================
+ Coverage   96.81%   96.89%   +0.08%     
==========================================
  Files          29       29              
  Lines        1317     1319       +2     
==========================================
+ Hits         1275     1278       +3     
+ Misses         42       41       -1     

☔ 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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5f87bb4 and 981b77e.

📒 Files selected for processing (1)
  • executorlib/task_scheduler/file/queue_spawner.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: notebooks
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-mpich.yml)
  • GitHub Check: unittest_win
  • GitHub Check: unittest_flux_mpich
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-openmpi.yml)
  • GitHub Check: unittest_old
  • GitHub Check: unittest_flux_openmpi
  • GitHub Check: unittest_openmpi (macos-latest, 3.13)
  • GitHub Check: notebooks_integration
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.11)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.11)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.13)
  • GitHub Check: unittest_mpich (macos-latest, 3.13)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.12)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.12)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.13)

Comment on lines +53 to +55
folder = command[-1].split("_i.h5")[0]
cwd = os.path.join(cache_directory, folder)
os.makedirs(cwd, exist_ok=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation and improve robustness of folder name extraction.

The current implementation has several potential issues:

  1. Missing input validation: No check if command is empty, which would cause IndexError on command[-1]
  2. Brittle string parsing: The code assumes command[-1] contains "_i.h5", but if it doesn't, the entire string becomes the folder name
  3. Path security: The folder name comes from user input and could contain path traversal characters like "../"

Consider this more robust implementation:

-            folder = command[-1].split("_i.h5")[0]
-            cwd = os.path.join(cache_directory, folder)
-            os.makedirs(cwd, exist_ok=True)
+            if not command:
+                raise ValueError("Command list cannot be empty")
+            
+            # Extract folder name safely
+            last_arg = command[-1]
+            if "_i.h5" in last_arg:
+                folder = last_arg.split("_i.h5")[0]
+            else:
+                # Fallback: use basename without extension
+                folder = os.path.splitext(os.path.basename(last_arg))[0]
+            
+            # Sanitize folder name to prevent path traversal
+            folder = os.path.basename(folder)  # Remove any path components
+            if not folder or folder in (".", ".."):
+                folder = "default_job"
+            
+            cwd = os.path.join(cache_directory, folder)
+            os.makedirs(cwd, exist_ok=True)
📝 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
folder = command[-1].split("_i.h5")[0]
cwd = os.path.join(cache_directory, folder)
os.makedirs(cwd, exist_ok=True)
if not command:
raise ValueError("Command list cannot be empty")
# Extract folder name safely
last_arg = command[-1]
if "_i.h5" in last_arg:
folder = last_arg.split("_i.h5")[0]
else:
# Fallback: use basename without extension
folder = os.path.splitext(os.path.basename(last_arg))[0]
# Sanitize folder name to prevent path traversal
folder = os.path.basename(folder) # Remove any path components
if not folder or folder in (".", ".."):
folder = "default_job"
cwd = os.path.join(cache_directory, folder)
os.makedirs(cwd, exist_ok=True)
🤖 Prompt for AI Agents
In executorlib/task_scheduler/file/queue_spawner.py around lines 53 to 55, add
validation to ensure the command list is not empty before accessing command[-1]
to prevent IndexError. Check if the last element contains the expected "_i.h5"
substring before splitting; if not, handle it gracefully or raise an error.
Sanitize the extracted folder name to remove or neutralize any path traversal
characters like "../" to avoid security risks. Use a safe method to construct
the folder path and then create the directory with os.makedirs as before.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 981b77e and 9535958.

📒 Files selected for processing (2)
  • executorlib/task_scheduler/file/queue_spawner.py (2 hunks)
  • tests/test_fluxclusterexecutor.py (1 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 (3)
executorlib/executor/flux.py (1)
  • FluxClusterExecutor (209-387)
executorlib/standalone/serialize.py (1)
  • cloudpickle_register (9-28)
tests/test_cache_fileexecutor_mpi.py (1)
  • mpi_funct (20-25)
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.11)
  • GitHub Check: unittest_flux_mpich
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.12)
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.11)
  • GitHub Check: unittest_openmpi (macos-latest, 3.13)
  • GitHub Check: unittest_win
  • GitHub Check: unittest_openmpi (ubuntu-latest, 3.13)
  • GitHub Check: unittest_mpich (ubuntu-latest, 3.12)
  • GitHub Check: unittest_mpich (macos-latest, 3.13)
  • GitHub Check: unittest_flux_openmpi
  • GitHub Check: notebooks_integration
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-mpich.yml)
  • GitHub Check: notebooks
  • GitHub Check: benchmark (ubuntu-latest, 3.13, .ci_support/environment-openmpi.yml)
🔇 Additional comments (1)
tests/test_fluxclusterexecutor.py (1)

43-45: Changes to existing test look good.

The modifications to the existing test method appear to be formatting or annotation changes and don't affect the test logic.

Comment on lines 47 to 58
def test_executor_no_cwd(self):
with FluxClusterExecutor(
resource_dict={"cores": 2},
block_allocation=False,
cache_directory="executorlib_cache",
) as exe:
cloudpickle_register(ind=1)
fs1 = exe.submit(mpi_funct, 1)
self.assertFalse(fs1.done())
self.assertEqual(len(os.listdir("executorlib_cache")), 2)
self.assertEqual(fs1.result(), [(1, 2, 0), (1, 2, 1)])
self.assertTrue(fs1.done())
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Test may not correctly validate the separate working directory behavior.

The new test method is good but has a few concerns:

  1. Directory structure validation: Both tests check len(os.listdir("executorlib_cache")) == 2, but if the new logic creates subdirectories when cwd is not specified, shouldn't the directory structure be different between the two tests?

  2. Single job limitation: The test only submits one job, but the PR objective mentions creating "separate working directories for each job". Consider adding a test that submits multiple jobs to verify they get separate directories.

Let me verify the expected behavior by checking the implementation:

Consider adding a test that submits multiple jobs to better validate the separate directory functionality:

+    def test_executor_multiple_jobs_no_cwd(self):
+        with FluxClusterExecutor(
+            resource_dict={"cores": 2},
+            block_allocation=False,
+            cache_directory="executorlib_cache",
+        ) as exe:
+            cloudpickle_register(ind=1)
+            fs1 = exe.submit(mpi_funct, 1)
+            fs2 = exe.submit(mpi_funct, 2)
+            
+            # Verify both jobs complete successfully
+            self.assertEqual(fs1.result(), [(1, 2, 0), (1, 2, 1)])
+            self.assertEqual(fs2.result(), [(2, 2, 0), (2, 2, 1)])
+            
+            # Verify separate directories were created
+            cache_contents = os.listdir("executorlib_cache")
+            self.assertGreater(len(cache_contents), 2, "Expected separate directories for each job")

🏁 Script executed:

#!/bin/bash
# Description: Check how the working directory logic works when cwd is not specified
# Expected: Find the logic that creates subdirectories based on command arguments

ast-grep --pattern 'def execute_with_pysqa($$$) {
  $$$
}'

# Also check for any directory creation logic
rg -A 10 -B 5 "cache_directory.*cwd|cwd.*cache_directory"

Length of output: 2974


Enhance directory‐structure assertions and add multi‐job coverage

The queue_spawner now creates a separate subdirectory under executorlib_cache for each task when no cwd is specified, whereas with an explicit cwd all output lands directly in that directory. The existing test_executor_no_cwd only checks that there are two entries, but doesn’t verify they are directories—and the “with cwd” test likewise only checks the count, not that they’re files. Also, we should submit more than one job to ensure each job still gets its own workspace.

Please update tests/test_fluxclusterexecutor.py around lines 47–58 as follows:

• In test_executor_no_cwd, after listing executorlib_cache, assert that each entry is a directory:

entries = os.listdir("executorlib_cache")
self.assertEqual(len(entries), 2)
for e in entries:
    self.assertTrue(
        os.path.isdir(os.path.join("executorlib_cache", e)),
        f"Expected '{e}' to be a subdirectory for a task"
    )

• In the corresponding “with cwd” test, assert that entries are files, not directories:

entries = os.listdir("executorlib_cache")
self.assertEqual(len(entries), 2)
for e in entries:
    self.assertTrue(
        os.path.isfile(os.path.join("executorlib_cache", e)),
        f"Expected '{e}' to be a file in the shared cwd"
    )

• Add a new test to submit two separate jobs and verify each gets its own subdirectory:

+    def test_executor_multiple_jobs_no_cwd(self):
+        with FluxClusterExecutor(
+            resource_dict={"cores": 2},
+            block_allocation=False,
+            cache_directory="executorlib_cache",
+        ) as exe:
+            cloudpickle_register(ind=1)
+            # Submit two distinct jobs
+            fs1 = exe.submit(mpi_funct, 1)
+            fs2 = exe.submit(mpi_funct, 2)
+
+            # Ensure both complete correctly
+            self.assertEqual(fs1.result(), [(1, 2, 0), (1, 2, 1)])
+            self.assertEqual(fs2.result(), [(2, 2, 0), (2, 2, 1)])
+
+            # Verify separate subdirectories for each task of each job
+            entries = os.listdir("executorlib_cache")
+            # Expect 4 subdirectories: 2 tasks × 2 jobs
+            self.assertEqual(len(entries), 4)
+            for e in entries:
+                path = os.path.join("executorlib_cache", e)
+                self.assertTrue(os.path.isdir(path), f"{path} should be a directory")

This will ensure both the per‐task directory logic and multi‐job isolation are properly validated.

🤖 Prompt for AI Agents
In tests/test_fluxclusterexecutor.py around lines 47 to 58, enhance the
test_executor_no_cwd by asserting that each entry in the "executorlib_cache"
directory is a subdirectory, not just checking the count. Similarly, in the
corresponding "with cwd" test, assert that entries are files rather than
directories. Additionally, add a new test that submits two separate jobs and
verifies each job gets its own subdirectory under "executorlib_cache" to ensure
multi-job workspace isolation is properly tested.

@jan-janssen jan-janssen merged commit 94dfa66 into main Jul 3, 2025
51 of 53 checks passed
@jan-janssen jan-janssen deleted the slurm_working_directory branch July 3, 2025 01:34
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