zenml-io / zenml

ZenML 🙏: Build portable, production-ready MLOps pipelines. https://zenml.io.
https://zenml.io
Apache License 2.0
3.79k stars 414 forks source link

Fix S3 artifact store memory leak and other improvements #2802

Closed stefannica closed 1 week ago

stefannica commented 2 weeks ago

Describe changes

This PR fixes a memory leak was observed while using the ZenML dashboard to view the logs of a pipeline or the visualization of an artifact that logged through an S3 Artifact Store linked to an AWS Service Connector.

How to reproduce

NOTE: even with this patch applied, the memory usage may still go up until it reaches a stable value. This depends largely on the number of threads that the server is allowed to create (default: 40). It is recommended to configure the number of threads to something low like 2 or 3 (by using the ZENML_SERVER_THREAD_POOL_SIZE environment variable when running the server) to reach that memory usage plateau faster.

Details

The investigation lead to the following findings:

  1. the s3fs library used in the S3 Artifact Store caches all its S3FileSystem client instances permanently, based on the constructor input arguments. In a more dynamic and long-lived environment like the ZenML server, this means that a new S3FileSystem is created (and never de-allocated) for every new set of credentials. Given that the AWS Service Connector generates temporary credentials, the number of cached S3FileSystem clients slowly grows with every invocation of the pipeline logs or artifact visualization endpoint until the server runs out of memory.

Solution: S3FileSystem instance caching is a class-level setting. This PR disables instance caching by sub-classing S3FileSystem and using the sub-class in the ZenML S3 Artifact Store implementation:

class ZenMLS3Filesystem(s3fs.S3FileSystem):

    cachable = False
  1. with the caching out of the picture, a second bug was revealed: S3FileSystem client instances were incorrectly de-allocated by the garbage collector, leading to additional memleaks. The exact root cause of this was not clearly identified even though it was fixed, but a likely explanation is included here.

s3fs is using asyncio at its core, but also provides support for synchronous calls by maintaining its own asyncio event loop thread and converting sync calls in asyncio tasks. s3fs also uses aiobotocore instead of botocore for that same reason and the aiobotocore clients are implemented using asynchronous context managers (more details on this below).

Normally, an async botocore client is used like this, where the client is created and deallocated in the same code block:

    session = aiobotocore.session.AioSession(**self.kwargs)
    async with self.session.create_client("s3", config=self.conf) as client:
        # do work with client

However, in the case of a class like S3FileSystem, where the client needs to be reused across different calls happening at different times, the aiobotocore client context manager needs to be entered during initialization and exited during cleanup:

async def initialize_client(self):
    self.session = aiobotocore.session.AioSession(**self.kwargs)
    client = self.session.create_client(
                "s3", config=self.conf
    )
    self._s3 = await s3creator.__aenter__()

async def cleanup_client(self):
    await self._s3.__aexit__(None, None, None)

The problem comes from when and how the cleanup is called: it needs to run as an asyncio task and therefore it needs to be invoked at a time when an asyncio event loop still exists i.e. before the garbage collector deallocates the event loop resources. The cleanup might also need to be run using the same event loop as the initialization - which is the assumed source for the second memleak: he way s3fs was doing de-initialization was buggy in that it was not using the same event loop as the one used for initialization.

Side-changes

Some more changes are included that help make the ZenML server leaner and more efficient concerning memory usage:

Pre-requisites

Please ensure you have done the following:

Types of changes

coderabbitai[bot] commented 2 weeks ago

[!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.


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 - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit .` - `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 Configration 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](https://discord.com/invite/GsXnASn26c) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
jlopezpena commented 2 weeks ago

You might want to report this upstream, there seems to have been a lingering issue since 2021 at least: https://github.com/fsspec/s3fs/issues/481