Skip to content

fix: actually use asyncio#2963

Closed
laf070810 wants to merge 3 commits intosnakemake:mainfrom
laf070810:fix-asyncio
Closed

fix: actually use asyncio#2963
laf070810 wants to merge 3 commits intosnakemake:mainfrom
laf070810:fix-asyncio

Conversation

@laf070810
Copy link
Copy Markdown
Contributor

@laf070810 laf070810 commented Jul 14, 2024

It seems that asyncio is not used correctly. Current implementation runs without IO concurrency, which can be seen by adding some timing outputs.

For example, the _finish_jobs function in scheduler.py will wait for the postprocess of all jobs sequentially, thus the total execution time of _finish_jobs is the sum of all postprocess execution time, which can be slow when the computation scales up.

This PR facilitates the actual use of asyncio. By making the changes in this PR, the total execution time of _finish_jobs will be in theory the max of all postprocess execution times (slightly longer in reality), which can be much shorter than the sum of times. I can already see a significant speedup in one of my use cases.

This PR is just a proposal for now. Asyncio usage in other parts of snakemake may have the same issue. We can proceed with a full fix if this proposal is thought to be correct.

The file diff on github may not be intuitive. The change is simply surrounding the codes with async with and replacing await with asyncio.TaskGroup().create_task() when possible.

QC

  • The PR contains a test case for the changes or the changes are already covered by an existing test case.
  • The documentation (docs/) is updated to reflect the changes or this is not necessary (e.g. if the change does neither modify the language nor the behavior or functionalities of Snakemake).

Summary by CodeRabbit

  • New Features

    • Enhanced concurrency in job post-processing, improving efficiency and responsiveness.
    • Added detailed timing metrics for job scheduling and processing stages.
  • Bug Fixes

    • Improved error handling during job processing, ensuring better robustness.
  • Documentation

    • Added logging for performance metrics related to post-processing and scheduling operations.

@laf070810
Copy link
Copy Markdown
Contributor Author

Well, some observations still show that it is sequential. I may need further investigation.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 13, 2024

Warning

Rate limit exceeded

@johanneskoester has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 12 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

Files that changed from the base of the PR and between 168232c and f8e2ded.

Walkthrough

The recent changes enhance the efficiency and observability of the Snakemake workflow management system. The introduction of asyncio.TaskGroup allows for concurrent task execution in the postprocess function and the _finish_jobs method, improving performance during I/O-bound operations. Additionally, detailed timing metrics have been added to the scheduling process, enabling better performance monitoring and debugging. Overall, these modifications lead to a more responsive and efficient job scheduling workflow.

Changes

Files Change Summary
snakemake/jobs.py Refactored postprocess function to utilize asyncio.TaskGroup, enabling concurrent task execution and improved performance metrics with timing logs.
snakemake/scheduler.py Enhanced schedule method with detailed timing metrics for job scheduling, and refactored _finish_jobs for concurrent job post-processing using TaskGroup.

Poem

In the garden of code, we hop and play,
With tasks that run fast, like a sunny day.
As rabbits we cheer, for the speed we gain,
Async adventures, no more waiting in vain!
🐰✨ With timing anew, our workflows align,
In Snakemake's embrace, we all brightly shine!


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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
Copy Markdown
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: 5

Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between b70c0db and 168232c.

Files selected for processing (2)
  • snakemake/jobs.py (2 hunks)
  • snakemake/scheduler.py (6 hunks)
Additional context used
Ruff
snakemake/scheduler.py

199-199: Trailing comma missing

Add trailing comma

(COM812)


209-209: Trailing comma missing

Add trailing comma

(COM812)


296-296: Trailing comma missing

Add trailing comma

(COM812)


336-336: Trailing comma missing

Add trailing comma

(COM812)


341-341: Trailing comma missing

Add trailing comma

(COM812)


354-354: Undefined name asyncio

(F821)


365-365: Trailing comma missing

Add trailing comma

(COM812)


373-373: Trailing comma missing

Add trailing comma

(COM812)


384-384: Trailing comma missing

Add trailing comma

(COM812)


401-401: Trailing comma missing

Add trailing comma

(COM812)


418-418: Trailing comma missing

Add trailing comma

(COM812)

snakemake/jobs.py

1142-1142: Trailing comma missing

Add trailing comma

(COM812)


1156-1156: Trailing comma missing

Add trailing comma

(COM812)


1157-1157: Trailing comma missing

Add trailing comma

(COM812)


1171-1171: Trailing comma missing

Add trailing comma

(COM812)


1176-1176: Replace aliased errors with OSError

Replace IOError with builtin OSError

(UP024)


1177-1181: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


1178-1180: Use f-string instead of format call

Convert to f-string

(UP032)


1180-1180: Trailing comma missing

Add trailing comma

(COM812)

Comment thread snakemake/scheduler.py
Comment thread snakemake/scheduler.py
Comment thread snakemake/scheduler.py
handle_log=True,
handle_touch=True,
)
async with asyncio.TaskGroup() as tg:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Import the asyncio module.

The asyncio module is used but not imported, which will cause a NameError at runtime.

+ import asyncio
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
async with asyncio.TaskGroup() as tg:
import asyncio
async with asyncio.TaskGroup() as tg:
Tools
Ruff

354-354: Undefined name asyncio

(F821)

Comment thread snakemake/jobs.py
Comment on lines +1176 to +1181
except IOError as e:
raise WorkflowError(
"Error recording metadata for finished job "
"({}). Please ensure write permissions for the "
"directory {}".format(e, self.dag.workflow.persistence.path)
)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Address static analysis suggestions.

  1. Replace IOError with OSError as IOError is an alias for OSError in Python 3.
  2. Use raise ... from None to distinguish exceptions from errors in exception handling.
  3. Convert to f-string for consistency and readability.
- except IOError as e:
+ except OSError as e:
- raise WorkflowError(
-     "Error recording metadata for finished job "
-     "({}). Please ensure write permissions for the "
-     "directory {}".format(e, self.dag.workflow.persistence.path)
- )
+ raise WorkflowError(
+     f"Error recording metadata for finished job ({e}). "
+     f"Please ensure write permissions for the directory {self.dag.workflow.persistence.path}"
+ ) from None
Tools
Ruff

1176-1176: Replace aliased errors with OSError

Replace IOError with builtin OSError

(UP024)


1177-1181: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


1178-1180: Use f-string instead of format call

Convert to f-string

(UP032)


1180-1180: Trailing comma missing

Add trailing comma

(COM812)

Comment thread snakemake/jobs.py
@sonarqubecloud
Copy link
Copy Markdown

Comment thread snakemake/jobs.py
Comment on lines +1141 to +1150
tg.create_task(
self.dag.check_and_touch_output(
self,
wait=self.dag.workflow.execution_settings.latency_wait,
ignore_missing_output=ignore_missing_output,
# storage not yet handled, just require the local files
wait_for_local=True,
)
)
self.dag.unshadow_output(self, only_log=error)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this is problematic. The idea of the await was that the check_and_touch happens before the stuff below like the unshadow. If I don't get this wrong here, now the check and touch happens in the background, in theory in parallel to the unshadow?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One example, in general all the steps currently conducted in postprocess should happen in the order they are defined in the code.

@johanneskoester
Copy link
Copy Markdown
Contributor

I think I will close this for now because of my concerns. Nevertheless, feel free to reopen or create a new one as a follow up if I missed something here. Thanks a lot for the suggestion, I still really appreciate the discussion!

@coderabbitai coderabbitai Bot mentioned this pull request Jul 24, 2025
2 tasks
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