fix: prevent OOM by using file handles and chunked base64 encoding #1951
+166
−60
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes memory spikes that can cause OOM (Out of Memory) errors in the
_interactionslayer when handling file uploads and inline data.Problem
Several functions in the
_interactionslayer were loading entire files into memory before processing, causing OOM errors for large files.Note: The main
aio.files.upload()API (files.py→_api_client.py) is already memory-efficient - it uses 8MB chunked streaming viaanyio.Path().open('rb'). The OOM issues occur in the experimental_interactionslayer.Root Causes Identified
_interactions/_files.py: Usedpath.read_bytes()to load entire files before passing to httpx_interactions/_utils/_transform.py: Base64 encoding loaded entire files withread_bytes()before encoding_interactions/_utils/_utils.py:file_from_path()loaded entire files withread_bytes()Solution
1. File Handle Streaming (
_interactions/_files.py)open(path, 'rb')) instead of loading bytes withread_bytes()IO[bytes]file handles, so this is a drop-in fix2. Chunked Base64 Encoding (
_interactions/_utils/_transform.py)3. File Handle in Utility (
_interactions/_utils/_utils.py)file_from_path()now returns a file handle instead of loaded bytesMemory Flow (Before vs After)
Before:
After:
Testing
Backwards Compatibility
This is a fully backwards-compatible change:
bytesandIO[bytes])