openai-python icon indicating copy to clipboard operation
openai-python copied to clipboard

Unrestricted caching keyed by generated types causes memory leak in multi-threaded regimes

Open rona-sh opened this issue 1 year ago • 5 comments

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • [x] This is an issue with the Python library

Describe the bug

In the OpenAI.responses.parse function, as part of validating the formatted response so it matches the required text_format (denoted hereinafter MyClass), the code creates the type ParsedResponseOutputMessage[MyClass], which is later passed to an unbounded lru_cache of pydantic.TypeAdapter.

In a multi-threaded setting, pydantic generates the type anew, and so its hash changes in every run, increasing the cache size ad infinitum. Concretely, a standard webserver that uses the responses.parse function is affected.

This issue reproduces under any model, and regardless of user input or target class.

To Reproduce

Consider the following snippet:

from openai import OpenAI
from pydantic import BaseModel
import psutil


class Fact(BaseModel):
    fact: str


client = OpenAI()
model = "gpt-4.1-nano"

def f():
    _ = client.responses.parse(model=model, input="Give a fun fact", text_format=Fact)
    print(psutil.Process().memory_info().rss / 2**20)

f invokes a responses.parse call, and prints the memory usage (in MB).

When running it on a single thread, the memory usage changes minimally:

for _ in range(10):
    f()

However, when running it on multiple threads (such as in default webserver), more memory is used for every request:

import time
import threading

for _ in range(10):
    time.sleep(0.1)
    threading.Thread(target=f).start()

Code snippets


OS

macOS

Python version

Python v3.12.11

Library version

openai v1.107.0

rona-sh avatar Sep 30 '25 10:09 rona-sh

We're also affected by this issue. Would love a fix upstream so we don't have to maintain a separate fork.

mnicstruwig avatar Oct 06 '25 16:10 mnicstruwig

@mnicstruwig Until this is addressed, consider the following fix:

import openai._models

openai._models.TypeAdapter = openai._models.lru_cache()(openai._models._TypeAdapter)

This overrides the library's cache to have a maximum size of 128 objects. While the types are still generated anew, bounding the cache's size prevents the memory leak. This is not optimal because it renders the caching mechanism useless, but it's manageable.

rona-sh avatar Oct 08 '25 07:10 rona-sh

It should be fixed now, @rona-sh—could you confirm that?

karpetrosyan avatar Feb 17 '26 08:02 karpetrosyan

Rechecked this against current main at be928151: the issue is still reproducible without any API call.

Using one fixed BaseModel response format and four newly-created ThreadPoolExecutor(max_workers=16) pools (200 local parse_response() calls per pool), the process-wide cached TypeAdapter count grew:

initial: 2
wave 1: 36
wave 2: 62
wave 3: 88
wave 4: 116

Sequential calls reuse the same entries; creating fresh worker threads triggers new runtime generic identities.

I also checked the existing open attempts (#2676, #2873, and #3068), so I am not opening another overlapping PR. A narrow root-fix direction that passes the responses tests, full mypy/Pyright, and the Pydantic v1 lane locally is to construct the three ParsedResponse*[TextFormatT] runtime specializations once at module import and reuse those stable class objects inside parse_response(). After one warm-up pool, three additional fresh pools leave the TypeAdapter cache size unchanged. This preserves the existing parameterized runtime models while avoiding a global cache-policy change.

If maintainers prefer that direction over the broader cache changes or the non-parameterized runtime classes, it could be folded into one of the existing PRs.

Hughhhhcoder avatar Sep 08 '26 08:09 Hughhhhcoder

Thanks for reporting this! Fixed by #3088, released in v3.16.2. We verified the threaded reproduction: cached type adapters previously grew with each fresh thread pool and now remain stable. Please upgrade to v3.16.2 or later. Closing as resolved.

marcuswood-oai avatar Sep 18 '26 22:09 marcuswood-oai