Skip to content
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

Fix memory leak in AsyncCompletions.parse() with dynamically created models #2148

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mousberg
Copy link

Fixes #2146

This PR fixes a memory leak in the manually maintained library code (src/openai/lib/_parsing/_completions.py) where AsyncCompletions.parse() was retaining schema representations of dynamically created Pydantic models indefinitely.

Changes Made:

  • Implemented WeakKeyDictionary cache for schema objects in _parsing/_completions.py
  • Added comprehensive test suite in tests/lib/_parsing/test_memory_leak.py

Technical Details:

The fix uses Python's WeakKeyDictionary to store schema representations, allowing them to be garbage collected when their corresponding model types are no longer referenced. This prevents the unbounded memory growth observed when repeatedly calling parse() with new models created via create_model().

Test Coverage:

New test suite verifies:

  • Schema cache properly handles dynamic models
  • Memory is released when models are no longer referenced
  • Both synchronous and asynchronous usage patterns

References:

…models

This commit fixes a memory leak issue in AsyncCompletions.parse() when repeatedly
called with Pydantic models created via create_model(). The issue was occurring
because schema representations of models were being retained indefinitely.

The fix implements a WeakKeyDictionary cache that allows the schema objects to be
garbage-collected when the model types are no longer referenced elsewhere in code.

Added test cases to verify the fix prevents memory leaks with dynamically created
models.
@mousberg mousberg requested a review from a team as a code owner February 27, 2025 17:32
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.

Possible memory leak in AsyncCompletions.parse()
1 participant