Skip to content

Async Responses Structured Outputs Memory leak #3084

Closed

Description

@savvasp-123

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:

Image

Memory leak in parse_response: ParsedResponse[TextFormatT] causes unbounded pydantic schema rebuilds

Environment

  • openai==2.31.0
  • pydantic>=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

  1. Use the Async Responses .parse() API with a Pydantic model
  2. The memory is not freed

OS

macOS

Activity

  1. added
    bug
    on Apr 14, 2026
  2. jingchang0623-crypto commented on Apr 25, 2026

    @jingchang0623-crypto

    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_rebuild is supposed to be a one-time operation to finalize forward references, but when you combine:

    1. Non-parameterized base classes
    2. Defer_build=True
    3. Multiprocessing forkserver workers

    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:

    # Pre-warm the cache before forking
    _ = MyModel.model_rebuild()

    This forces the rebuild in the parent process, giving all forked workers a pre-cached schema.

  3. ifplusor commented on May 21, 2026

    @ifplusor

    I conducted a detailed investigation.

    ParsedResponseOutputMessage[TextFormatT] and ParsedResponse[TextFormatT] create generic_submodel at runtime via BaseModel.__class_getitem__.

    Although the type of ParsedResponseOutputMessage.content is List[ParsedContent] and the type of ParsedResponse.output is List[ParsedResponseOutputItem], ParsedContent and ParsedResponseOutputItem are still specialized into brand new union types during this process:

    openai.types.responses.parsed_response.ParsedResponseOutputText[TypeVar]
    | openai.types.responses.response_output_refusal.ResponseOutputRefusal

    and

    openai.types.responses.parsed_response.ParsedResponseOutputMessage[TypeVar]
    | openai.types.responses.parsed_response.ParsedResponseFunctionToolCall
    | openai.types.responses.response_file_search_tool_call.ResponseFileSearchToolCall
    | openai.types.responses.response_function_web_search.ResponseFunctionWebSearch
    | openai.types.responses.response_computer_tool_call.ResponseComputerToolCall
    | openai.types.responses.response_computer_tool_call_output_item.ResponseComputerToolCallOutputItem
    | openai.types.responses.response_tool_search_call.ResponseToolSearchCall
    | openai.types.responses.response_tool_search_output_item.ResponseToolSearchOutputItem
    | openai.types.responses.response_reasoning_item.ResponseReasoningItem
    | openai.types.responses.response_output_item.McpCall
    | openai.types.responses.response_output_item.McpApprovalRequest
    | openai.types.responses.response_output_item.McpApprovalResponse
    | openai.types.responses.response_output_item.ImageGenerationCall
    | openai.types.responses.response_output_item.LocalShellCall
    | openai.types.responses.response_output_item.LocalShellCallOutput
    | openai.types.responses.response_output_item.LocalShellCallAction
    | openai.types.responses.response_output_item.McpListTools
    | openai.types.responses.response_code_interpreter_tool_call.ResponseCodeInterpreterToolCall
    | openai.types.responses.response_compaction_item.ResponseCompactionItem
    | openai.types.responses.response_function_shell_tool_call.ResponseFunctionShellToolCall
    | openai.types.responses.response_function_shell_tool_call_output.ResponseFunctionShellToolCallOutput
    | openai.types.responses.response_apply_patch_tool_call.ResponseApplyPatchToolCall
    | openai.types.responses.response_apply_patch_tool_call_output.ResponseApplyPatchToolCallOutput
    | openai.types.responses.response_function_tool_call_output_item.ResponseFunctionToolCallOutputItem
    | openai.types.responses.response_custom_tool_call.ResponseCustomToolCall
    | openai.types.responses.response_custom_tool_call_output_item.ResponseCustomToolCallOutputItem

    This is not a problem in itself. However, it is common to create new contexts via asyncio.create_task in asyn web servers, or maybe by spawning threads (#2672). These operations make new/empty Pydantic's GenericTypesCache. As a result, for every context, generic_submodel is recreated for ParsedResponseOutputMessage[TextFormatT] and ParsedResponse[TextFormatT], and new specialized union types are also created for ParsedContent and ParsedResponseOutputItem.

    These types eventually pass to _CachedTypeAdapter through the call chain:

    BaseModel.construct -> _construct_field -> construct_type -> validate_type -> _validate_non_model_type

    Each such union type has a different hash. Because _CachedTypeAdapter is unbound, an unbounded number of TypeAdapter instances are created and cached, leading to unbounded memory growth over time.

  4. ifplusor commented on May 22, 2026

    @ifplusor

    Update:

    Since the generic type variables of ParsedResponseOutputText, ParsedResponseOutputMessage, and ParsedResponse are all ContentType, Pydantic treats their type_args as identical. Then, in the call chain collect_model_fields -> FieldInfo.apply_typevars_map, they are replaced with TextFormatT.

    To address this, I tried creating and using distinct TypeVar for ParsedResponseOutputText, ParsedResponseOutputMessage, and ParsedResponse to break the replace_types condition, and no new union types are specialized. Test results show that this solution works effectively.

  5. added a commit that references this issue on Jun 1, 2026
    936d17c
  6. snipd-kevin commented on Aug 31, 2026

    @snipd-kevin

    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 take text_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:

    • reusing a single AsyncOpenAI client for the process lifetime
    • gc.collect() / del
  7. kdincx commented on Sep 13, 2026

    @kdincx

    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, using AsyncOpenAI().responses.stream() with text_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 wraps pydantic._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]) and openai/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 (free TextFormatT TypeVar -> model_rebuild() always returns False -> pydantic's generic-model cache never populates -> a fresh SchemaValidator/SchemaSerializer gets 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 by if 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 / streamed parsed values 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.

  8. marcuswood-oai commented on Sep 18, 2026

    @marcuswood-oai
    Contributor

    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.

  9. added a commit that references this issue on Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions