[BUG] create_model_from_schema drops the null member of {"type": ["object", "null"]} depending on member order (id() reuse in in_progress cache)
Description
create_model_from_schema builds the wrong type for a nested object declared with a list-form type, e.g. {"type": ["object", "null"], "properties": {...}}: the field comes out as the bare nested model instead of Optional[model], so a null value the schema explicitly allows is rejected with a ValidationError.
Root cause: _build_model_from_schema registers the schema it is building in in_progress keyed by id(schema), but only the id is stored, not the dict. The list-form type branch in _json_schema_to_pydantic_type (added in #7281) creates a temporary {**json_schema, "type": member} dict per member. The "object" member's temporary dict is registered and then freed; the "null" member's temporary dict is allocated at the same address, so in_progress.get(id(json_schema)) hits the cache and returns the nested model instead of None. Union[Model, Model] collapses to Model.
Because it depends on memory reuse the result is order-dependent: ["null", "object"] works, ["object", "null"] does not. With several nullable nested objects in one schema a later field can also receive the model built for an earlier one. The merged dict produced for allOf is registered and freed the same way.
This affects MCP tool schemas from non-Python servers (the .NET/System.Text.Json style that #7281 added support for) whenever a nullable parameter is an object.
Steps to Reproduce
- Install crewai (main @ 738c8e19e, or 1.15.23).
- Run the script below (no LLM, no network).
- Observe that for
["object", "null"]the annotation is the bare nested class andModel(filter=None)raises; for["null", "object"]it isOptional[...]andNoneis accepted.
Expected behavior
Both orderings produce Optional[<nested model>], Model(filter=None) is accepted, and each nullable nested object field gets its own model regardless of allocation order.
Screenshots/Code snippets
import sys
import typing
from pydantic import ValidationError
from crewai.utilities.pydantic_schema_utils import create_model_from_schema
def build(type_order: list[str]) -> type:
return create_model_from_schema(
{
"title": "Args",
"type": "object",
"properties": {
"filter": {
"type": type_order,
"properties": {"field": {"type": "string"}},
"required": ["field"],
}
},
"required": ["filter"],
}
)
failed = False
for order in (["object", "null"], ["null", "object"]):
Model = build(order)
annotation = Model.model_fields["filter"].annotation
print(f"type={order!r:20} -> annotation={annotation!r}")
try:
Model(filter=None)
print(" filter=None accepted (expected)")
except ValidationError as e:
failed = True
print(" filter=None REJECTED (bug):", str(e).splitlines()[0])
sys.exit(1 if failed else 0)
Operating System
Other (specify in additional context)
Python Version
3.12
crewAI Version
main @ 738c8e19e (1.15.23)
crewAI Tools Version
n/a (not needed to reproduce)
Virtual Environment
Venv (uv)
Evidence
type=['object', 'null'] -> annotation=<class 'crewai.utilities.pydantic_schema_utils.FilterOption0'>
filter=None REJECTED (bug): 1 validation error for Args
type=['null', 'object'] -> annotation=typing.Optional[crewai.utilities.pydantic_schema_utils.FilterOption1]
filter=None accepted (expected)
Possible Solution
Store the schema dict alongside the model in in_progress (value (schema, model)) so the dict stays alive for as long as its id() is a key; then a temporary member dict can never be freed and have its id recycled while the cache still references it. Three signatures and the cache lookup change; no behaviour change otherwise. I have this fix with two regression tests ready and can open a PR if that approach is acceptable.
Additional context
OS: macOS 15 (Darwin 24.3.0). Existing tests only cover scalar list-form types (["string", "null"] etc.), which is why this was not caught by #7281's tests.
Disclosure: found, reproduced and the draft fix tested locally with the help of an AI coding agent (Claude Code); reviewed before filing. Per CONTRIBUTING.md this should carry the llm-generated label; I cannot apply labels as an external contributor, so flagging it here for a maintainer.
Root cause confirmed in lib/crewai/src/crewai/utilities/pydantic_schema_utils.py line 1243.
_json_schema_to_pydantic_type processes a list-form type such as {"type": ["object", "null"], "properties": {...}} by creating a temporary dict {**json_schema, "type": member} for every member in a list comprehension. The temporary dict for "object" is registered in in_progress by id() inside _build_model_from_schema. After the comprehension iteration, that dict is GC'd. Python can then reuse its id() for the "null" member's temporary dict, causing in_progress to return the wrong cached model for "null" and producing Model instead of Optional[Model]. A null value the schema explicitly allows is then rejected with a ValidationError.
Fix: handle "null" directly as type(None) without creating a temporary dict. This eliminates the id() reuse hazard entirely. Non-null members still use the existing path, but each dict is now kept alive in a named variable for the duration of the loop body.
4 regression tests added covering both ["object", "null"] and ["null", "object"] member orders. The two accepts_none tests fail on the unpatched code and pass with the fix.
PR: https://github.com/crewAIInc/crewAI/pull/7913
This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue was closed because it has been stalled for 5 days with no activity.