Skip to content

Limit max concurrent template runs #3627

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

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from

Conversation

schustmi
Copy link
Contributor

@schustmi schustmi commented Apr 30, 2025

Describe changes

This PR limits the amount of concurrent template runs.

Pre-requisites

Please ensure you have done the following:

  • I have read the CONTRIBUTING.md document.
  • I have added tests to cover my changes.
  • I have based my new branch on develop and the open PR is targeting develop. If your branch wasn't based on develop read Contribution guide on rebasing branch to develop.
  • IMPORTANT: I made sure that my changes are reflected properly in the following resources:
    • ZenML Docs
    • Dashboard: Needs to be communicated to the frontend team.
    • Templates: Might need adjustments (that are not reflected in the template tests) in case of non-breaking changes and deprecations.
    • Projects: Depending on the version dependencies, different projects might get affected.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Other (add details above)

@schustmi schustmi requested a review from stefannica April 30, 2025 13:09
Copy link
Contributor

coderabbitai bot commented Apr 30, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.

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.

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.

@github-actions github-actions bot added internal To filter out internal PRs and issues enhancement New feature or request labels Apr 30, 2025
@schustmi
Copy link
Contributor Author

@stefannica I've changed this now to handle all the run template requests in a sequential manner with a configurable amount of worker threads. These threads are however additional threads on top of the ones that are created/used by fastapi. Do you think this is a good idea or should I try to get the worker threads from the same pool, while still somehow limiting the concurrency?

Comment on lines 59 to 62
run_template_executor = ThreadPoolExecutor(
max_workers=server_config().max_concurrent_template_runs
)

Copy link
Contributor

Choose a reason for hiding this comment

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

Global objects like these are problematic because they get created the moment you import the module and allocate resources even though the actual functionality isn't used.

I recommend the following alternative approach similar to what is used in zenml/zen_server/utils.py:

  • declare a nullable global variable for this
  • have helper functions for initialization/cleanup. Call these from the FastAPI startup/shutdown hooks. Cleanup is particularly important, because you might want to wait for the threads to finish running or kill/join the running threads altogether before exiting.
  • have a getter function for actual use

Comment on lines 444 to 451
if data.get("max_concurrent_template_runs", None) is None:
# Block a maximum of 1/4 of the thread pool size for concurrent
# template runs
thread_pool_size = data.get(
"thread_pool_size", DEFAULT_ZENML_SERVER_THREAD_POOL_SIZE
)
data["max_concurrent_template_runs"] = int(thread_pool_size) // 4

Copy link
Contributor

Choose a reason for hiding this comment

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

If this is a "before" validator, does that mean that these values might be strings ?

Comment on lines 250 to 251
else:
run_template_executor.submit(_task_with_analytics_and_error_handling)
Copy link
Contributor

Choose a reason for hiding this comment

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

The number of threads is limited, but not the queue size. This means that you can still run into a situation where the server is flooded with requests and eventually croak due to OOM.

I recommend you also cap the queue size to match the thread pool size. This is a good way to create back-pressure and actually make the client wait (and/or eventually time out) if it's creating too many parallel run template requests instead of killing the server.

Yes, this means that FastAPI request threads will eventually be blocked waiting for the run template threads to complete. I think this is perfectly acceptable, as it gives server admins a knob that they can properly calibrate without compromising the server's reliability.

One more thing you can do is to make the submit requests cancellable: if the client times out, FastAPI also has the option to notify you that the request timed out (see https://fastapiexpert.com/blog/category/fastapi/#understanding-client-disconnection-in-fastapi). If you don't handle client disconnects for jobs like these, they will just keep on running. I.e. you can run await request.is_disconnected() to check if the request was cancelled before you execute anything in the worker thread.

Copy link
Contributor

github-actions bot commented May 5, 2025

ZenML CLI Performance Comparison (Threshold: 1.0s, Timeout: 60s, Slow: 5s)

❌ Failed Commands on Current Branch (feature/limit-concurrent-template-runs)

  • zenml stack list: Command failed on run 1 (exit code: 1)
  • zenml pipeline list: Command failed on run 1 (exit code: 1)
  • zenml model list: Command failed on run 1 (exit code: 1)

🚨 New Failures Introduced

The following commands fail on your branch but worked on the target branch:

  • zenml stack list
  • zenml pipeline list
  • zenml model list

Performance Comparison

Command develop Time (s) feature/limit-concurrent-template-runs Time (s) Difference Status
zenml --help 1.582295 ± 0.023685 1.581487 ± 0.006481 ±0.000s ✓ No significant change
zenml model list Not tested Failed N/A ❌ Broken in current branch
zenml pipeline list Not tested Failed N/A ❌ Broken in current branch
zenml stack --help 1.590047 ± 0.011402 1.610616 ± 0.019000 +0.021s ✓ No significant change
zenml stack list Not tested Failed N/A ❌ Broken in current branch

Summary

  • Total commands analyzed: 5
  • Commands compared for timing: 2
  • Commands improved: 0 (0.0% of compared)
  • Commands degraded: 0 (0.0% of compared)
  • Commands unchanged: 2 (100.0% of compared)
  • Failed commands: 3 (NEW FAILURES INTRODUCED)
  • Timed out commands: 0
  • Slow commands: 0

Environment Info

  • Target branch: Linux 6.11.0-1012-azure
  • Current branch: Linux 6.11.0-1012-azure
  • Test timestamp: 2025-05-05T09:25:03Z
  • Timeout: 60 seconds
  • Slow threshold: 5 seconds

@schustmi schustmi requested a review from stefannica May 5, 2025 09:21
Comment on lines 156 to 158
max_concurrent_template_runs: The maximum number of concurrent template
runs that can be executed on the server. If not specified, the
default value of 1/4 of the thread pool size will be used.
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
max_concurrent_template_runs: The maximum number of concurrent template
runs that can be executed on the server. If not specified, the
default value of 1/4 of the thread pool size will be used.
max_concurrent_template_runs: The maximum number of concurrent template
runs that can be executed on the server.

The last part is no longer accurate, is it ?

Comment on lines +110 to +117
def shutdown(self, **kwargs: Any) -> None:
"""Shutdown the executor.

Args:
**kwargs: Keyword arguments to pass to the shutdown method of the
executor.
"""
self._executor.shutdown(**kwargs)
Copy link
Contributor

Choose a reason for hiding this comment

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

This isn't called anywhere. Are you missing the cleanup/deinitialization part ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added the call in the fastapi shutdown event handler

return _run_template_executor


def initialize_run_template_executor() -> None:
Copy link
Contributor

Choose a reason for hiding this comment

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

What about a de-initialize/cleanup function?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added this in a the fastapi shutdown event

@schustmi schustmi requested a review from stefannica May 6, 2025 08:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request internal To filter out internal PRs and issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants