Repository navigation
Description
Confirm this is an issue with the Python library and not an underlying OpenAI API
- This is an issue with the Python library
Describe the bug
Using the AsyncResponses client to parse structured outputs there are pydantic models left behind which causes memory to accumulate. Flame graph of the memory leak:
Memory leak in parse_response: ParsedResponse[TextFormatT] causes unbounded pydantic schema rebuilds
Environment
openai==2.31.0pydantic>=2- Python 3.13
Description
openai/lib/_parsing/_responses.py calls construct_type_unchecked with TypeVar-subscripted generics:
construct_type_unchecked(type_=ParsedResponseOutputText[TextFormatT], ...)
construct_type_unchecked(type_=ParsedResponseOutputMessage[TextFormatT], ...)
construct_type_unchecked(type_=ParsedResponse[TextFormatT], ...)TextFormatT is a free module-level TypeVar. Pydantic cannot resolve a free TypeVar, so model_rebuild(raise_errors=False) returns False on every call. This means MockCoreSchema._built_memo is never populated, and a new SchemaValidator/SchemaSerializer (heavy Rust objects) is allocated on every single responses.parse() call. These accumulate without bound.
Root Cause
Pydantic's MockCoreSchema._get_built() only caches its result (_built_memo) when model_rebuild succeeds (returns True). For ParsedResponse[TextFormatT] where TextFormatT is unresolved, model_rebuild always returns False, so the cache is never set and the rebuild runs on every access.
Fix
Use the non-parameterized base classes instead:
construct_type_unchecked(type_=ParsedResponseOutputText, ...)
construct_type_unchecked(type_=ParsedResponseOutputMessage, ...)
construct_type_unchecked(type_=ParsedResponse, ...)This is functionally identical at runtime — ParsedResponse and related classes guard their parameterised fields behind if TYPE_CHECKING:, so the type argument has no runtime effect:
class ParsedResponse(Response, GenericModel, Generic[ContentType]):
if TYPE_CHECKING:
output: List[ParsedResponseOutputItem[ContentType]] # never executed at runtime
else:
output: List[ParsedResponseOutputItem]Impact
In a long-running server making repeated responses.parse() calls, RSS grows linearly with request count and the process will eventually OOM.
To Reproduce
- Use the Async Responses
.parse()API with a Pydantic model - The memory is not freed
OS
macOS
Activity
fix(parsing): drop TextFormatT parameterization in parse_response (op…
jingchang0623-crypto commentedon Apr 25, 2026
Memory leak in structured outputs with Pydantic — the model_rebuild infinite loop of sadness.
This is a classic case of optimization gone wrong. Pydantic's
model_rebuildis supposed to be a one-time operation to finalize forward references, but when you combine:You get a perfect storm where each process rebuilds schemas independently, never caching, never stopping.
The memory leak isn't in your code — it's in the gap between Pydantic's caching assumptions and how the OpenAI SDK handles model registration across process boundaries.
The fix in #3118 is correct: parameterized base classes give Pydantic a stable cache key. But the real question is: why isn't this documented in big red letters? Memory leaks from model_rebuild are a known issue in the Pydantic ecosystem.
We documented a similar pattern in agent self-referencing systems where infinite recursion in validation caused cascading memory growth: https://miaoquai.com/stories/agent-self-review-infinite-recursion.html
The pattern is the same: tools meant to optimize (model_rebuild, agent self-review) become bottlenecks when assumptions break.
For production deployments, consider:
This forces the rebuild in the parent process, giving all forked workers a pre-cached schema.
ifplusor commentedon May 21, 2026
I conducted a detailed investigation.
ParsedResponseOutputMessage[TextFormatT]andParsedResponse[TextFormatT]creategeneric_submodelat runtime viaBaseModel.__class_getitem__.Although the type of
ParsedResponseOutputMessage.contentisList[ParsedContent]and the type ofParsedResponse.outputisList[ParsedResponseOutputItem],ParsedContentandParsedResponseOutputItemare still specialized into brand new union types during this process:and
This is not a problem in itself. However, it is common to create new contexts via
asyncio.create_taskin asyn web servers, or maybe by spawning threads (#2672). These operations make new/empty Pydantic'sGenericTypesCache. As a result, for every context,generic_submodelis recreated forParsedResponseOutputMessage[TextFormatT]andParsedResponse[TextFormatT], and new specialized union types are also created forParsedContentandParsedResponseOutputItem.These types eventually pass to
_CachedTypeAdapterthrough the call chain:BaseModel.construct -> _construct_field -> construct_type -> validate_type -> _validate_non_model_typeEach such union type has a different hash. Because
_CachedTypeAdapteris unbound, an unbounded number ofTypeAdapterinstances are created and cached, leading to unbounded memory growth over time.ifplusor commentedon May 22, 2026
Update:
Since the generic type variables of
ParsedResponseOutputText,ParsedResponseOutputMessage, andParsedResponseare allContentType, Pydantic treats theirtype_argsas identical. Then, in the call chaincollect_model_fields -> FieldInfo.apply_typevars_map, they are replaced withTextFormatT.To address this, I tried creating and using distinct
TypeVarforParsedResponseOutputText,ParsedResponseOutputMessage, andParsedResponseto break thereplace_typescondition, and no new union types are specialized. Test results show that this solution works effectively.fix: avoid response parse validator leak (closes openai#3084)
snipd-kevin commentedon Aug 31, 2026
We're hitting this in production too.
Same pattern: memory climbs steadily and eventually OOMs. We were however never able to reproduce it locally. We ran hundreds of requests on macOS and in Docker and they allstayed flat. It only shows up on Cloud Run under real traffic.
For us it's anything that goes through
parse_response(), i.e. the helpers that taketext_format=:client.responses.parse(text_format=...)client.responses.stream(text_format=...)Switching to
client.responses.create(...)with the same schema passed as a plain{"type": "json_schema", "strict": true, ...}dict, and validating the response ourselves, stops the growth completely. That was the only difference between our leaking and non-leaking deploys.We validated this on two separate prod services of ours, one using the streaming helper, and one the non-streaming one - on SDK 2.14.0 and 3.3.1. The memory leak retains roughly 0.8 MB per call in both.
Things that did not help us, in case it saves anyone time:
AsyncOpenAIclient for the process lifetimegc.collect()/delkdincx commentedon Sep 13, 2026
We independently ran into this in production — happy to add confirmation plus some data points.
We run several Google ADK-based agent services on
openai==2.54.0, usingAsyncOpenAI().responses.stream()withtext_format=<pydantic model>for structured output. We were chasing an unexplained RSS leak (services hitting a self-imposed recycle threshold every 15-50 minutes under load) and eventually built a small runtime diagnostic that wrapspydantic._internal._model_construction.ModelMetaclass.__new__to log the call stack every time a new class gets constructed.That instrumentation caught
openai/lib/_parsing/_responses.py:parse_response(ParsedResponseOutputText[TextFormatT],ParsedResponseOutputMessage[TextFormatT],ParsedResponse[TextFormatT]) andopenai/lib/streaming/responses/_responses.py:handle_event(ResponseTextDoneEvent[TextFormatT]) firing hundreds of times within ~20 minutes under moderate traffic — matching exactly the root cause described in this issue (freeTextFormatTTypeVar ->model_rebuild()always returnsFalse-> pydantic's generic-model cache never populates -> a freshSchemaValidator/SchemaSerializergets allocated on every call).We backported the fix suggested here (dropping the
[TextFormatT]subscript on those four call sites, since the parametrized fields are guarded byif TYPE_CHECKING:anyway) as a local patch on top of v2.54.0. After deploying, our self-recycle rate dropped from ~14/hour to 0 within the first ~70 minutes of observation, and the object-count growth trend on the affected processes flattened out. Correctness was unaffected in our testing -output_parsed/ streamedparsedvalues were identical before and after the patch.Happy to share the patch diff if it's useful. Would be great to see this land upstream - it's a clean, low-risk fix based on the analysis already in this thread.
fix(parsing): drop TextFormatT parameterization in parse_response to …
marcuswood-oai commentedon Sep 18, 2026
Sorry for the delay, and thanks for flagging this and sharing the reproduction! The fix covers both parsing and streaming and is included in v3.16.2, which we’re preparing to release now. Please let us know if you still see memory growth after upgrading.
release: 3.16.2 (openai#3903)