Skip to content

fix: resolve OpenAPI generation crash for Optional/Union model outputs#5636

Open
abdogomaa201099 wants to merge 1 commit into
bentoml:mainfrom
abdogomaa201099:fix/openapi-optional-union-ref
Open

fix: resolve OpenAPI generation crash for Optional/Union model outputs#5636
abdogomaa201099 wants to merge 1 commit into
bentoml:mainfrom
abdogomaa201099:fix/openapi-optional-union-ref

Conversation

@abdogomaa201099

@abdogomaa201099 abdogomaa201099 commented Jun 14, 2026

Copy link
Copy Markdown

An endpoint whose return annotation is a single Pydantic model wrapped in Optional[...], ... | None, or Union[...] made /docs.json raise KeyError: 'ents/schemas/...'. _flatten_field collapses the resulting top-level anyOf into a bare $ref, then sliced the ref with a hard-coded #/$defs/ prefix length and looked it up in an (empty) defs map.

Make the ref-name extraction robust (rsplit('/', 1)[-1]) and only inline references that exist in the local $defs; references to registered component schemas (#/components/schemas/...) are now left intact instead of crashing. Also route the request/response schema construction through a helper that maps a top-level $ref onto Schema's renamed ref field.

Adds regression tests covering Optional/Union/List model outputs.

What does this PR address?

No prior issue — bug discovered while testing Optional[Model] return types.

Before submitting:

An endpoint whose return annotation is a single Pydantic model wrapped in
`Optional[...]`, `... | None`, or `Union[...]` made `/docs.json` raise
`KeyError: 'ents/schemas/...'`. `_flatten_field` collapses the resulting
top-level `anyOf` into a bare `$ref`, then sliced the ref with a hard-coded
`#/$defs/` prefix length and looked it up in an (empty) defs map.

Make the ref-name extraction robust (`rsplit('/', 1)[-1]`) and only inline
references that exist in the local `$defs`; references to registered
component schemas (`#/components/schemas/...`) are now left intact instead
of crashing. Also route the request/response schema construction through a
helper that maps a top-level `$ref` onto `Schema`'s renamed `ref` field.

Adds regression tests covering Optional/Union/List model outputs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@abdogomaa201099
abdogomaa201099 requested a review from a team as a code owner June 14, 2026 07:06
@abdogomaa201099
abdogomaa201099 requested review from jianshen92 and removed request for a team June 14, 2026 07:06
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.

1 participant