Skip to content

Keep null on a nullable object that another branch narrows - #5172

Merged
Koudai Aono (koxudaxi) merged 1 commit into
fe7b-node-testsfrom
fix-5154-typeddict-null
Oct 23, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
fe7b-node-testsfrom
fix-5154-typeddict-null

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Fixes: #5154

Summary by CodeRabbit

  • Bug Fixes
    • Generated models now preserve nullable fields when redundant references are consolidated, including within schema unions. This keeps None valid where the schema allows it and maintains consistent validation across supported model types and generation options.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-22T23:33:35.384885Z e30e405 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
📥 Commits

Reviewing files that changed from the base of the PR and between 77ccefe and f5c869e.

⛔ Files ignored due to path filters: 6
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[dataclasses.dataclass-default].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[msgspec.Struct-default].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[pydantic_v2.BaseModel-default].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[typing.TypedDict-default].payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/jsonschema/nullable_object_narrowed_in_oneof.json is excluded by !tests/data/**/*.json and included by none
📒 Files selected for processing: 10
  • docs/architecture.md
  • src/datamodel_code_generator/model/base.py
  • src/datamodel_code_generator/model/msgspec.py
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[dataclasses.dataclass-default].py
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[msgspec.Struct-default].py
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[pydantic_v2.BaseModel-default].py
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[pydantic_v2.dataclass-default].py
  • tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[typing.TypedDict-default].py
  • tests/main/openapi/test_redundant_reference_null.py
  • tests/main/openapi/test_redundant_reference_null.refs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

📝 Walkthrough

The change prepares field nullability before duplicate model references are redirected. It adds a regression test and generated-output snapshots for nullable properties in a oneOf schema across supported model types.

Changes: Nullable fields in deduplicated models

Layer / File(s) Summary
Prepare nullability for rendered field types
src/datamodel_code_generator/model/base.py, src/datamodel_code_generator/model/msgspec.py, docs/architecture.md
Field implementations identify when a hint renders its own type. Deduplication preparation writes pre-render nullability for those fields. The architecture documentation describes this behavior.
Verify nullable oneOf output across model types
tests/main/openapi/test_redundant_reference_null.py, tests/main/openapi/test_redundant_reference_null.refs, tests/data/expected/main/openapi/redundant_reference_null/reference_null_kept_after_duplicate_deletion[*].py
A parametrized regression test checks schema validation and generated-model parsing. Expected outputs cover dataclasses, msgspec, Pydantic v2 models and dataclasses, and TypedDict.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

  • #5163: Describes loss of None when equivalent object models are merged and one source is nullable. This change updates nullability handling during duplicate-model preparation.
  • #4816: Describes loss of None for a required nullable object after deduplication. This change updates nullability handling in that path.
Merge Risk: ⚪ Minimal · up to f5c86

The nullable oneOf case has regression coverage, and no issue requiring a fix before merge was established.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: preserving null for a nullable object when another branch narrows it.
Linked Issues check Passed Issue #5154 requires preservation of None for the nullable item field in the oneOf branch that does not narrow item. DataModel._prepare_dedup_key now materializes field nullability before du…
Out of Scope Changes check Passed The source changes implement nullability preservation during duplicate deletion. The architecture documentation explains that behavior. The regression test and generated snapshots verify the issue sce…
Docstring Coverage Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 8 files. (2 skipped: 2 …
Full details: Linked Issues check

Explanation

Issue #5154 requires preservation of None for the nullable item field in the oneOf branch that does not narrow item. DataModel._prepare_dedup_key now materializes field nullability before duplicate deletion. The regression test covers nullable_object_narrowed_in_oneof.json, including typing.TypedDict, valid and invalid payloads, and generated output snapshots. The TypedDict snapshot preserves NotRequired[Item | None].

Full details: Out of Scope Changes check

Explanation

The source changes implement nullability preservation during duplicate deletion. The architecture documentation explains that behavior. The regression test and generated snapshots verify the issue scenario across supported model types. These changes support issue #5154 and do not demonstrate unrelated scope.

Full details: Docstring Coverage

Explanation

Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 8 files. (2 skipped: 2 unsupported.)

✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codspeed

codspeed Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 24.38%

2 warnings

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚠️ Base and head ran on different runner types

Some benchmarks with significant performance changes were compared across different runner types, so the changes might not come from the code. Run base and head on the same runner type, or use CodSpeed Macro Runners for more stable results.

Learn more about Macro Runners

Open the report in CodSpeed to investigate

❌ 50 regressed benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_perf_unique_items_nested_model_validation 1.6 ms 2.6 ms -39.2%
❌ test_perf_unique_items_runtime_scalar_validation 1.5 ms 2.4 ms -37.51%
❌ test_perf_pydantic_field_name_resolution 952.1 µs 1,493 µs -36.23%
❌ test_perf_simple_pydantic_v2_field_construction 5.9 ms 8.6 ms -31.04%
❌ test_perf_multiple_files_input 2.3 s 3.2 s -28.49%
❌ test_perf_extreme_large_schema 8.5 s 11.8 s -28.32%
❌ test_perf_duplicate_names 574.6 ms 795.8 ms -27.79%
❌ test_perf_pattern_properties_adapter_reuse 2.2 ms 3 ms -27.71%
❌ test_perf_kubernetes_style_pydantic_v2 1.5 s 2.1 s -27.71%
❌ test_perf_simple_msgspec_unset_field_rendering 85.1 ms 117.3 ms -27.41%
❌ test_perf_large_models_pydantic_v2 2 s 2.7 s -27.21%
❌ test_perf_graphql_style_pydantic_v2 468 ms 642.5 ms -27.16%
❌ test_perf_large_models_typed_dict[legacy-requiredness] 657.1 ms 898 ms -26.82%
❌ test_perf_empty_pydantic_v2_field_render_plans 23.9 ms 32.5 ms -26.38%
❌ test_perf_all_options_enabled 3.4 s 4.7 s -26.27%
❌ test_perf_openapi_large 2 s 2.7 s -25.94%
❌ test_perf_load_pyproject_config[mapping-None] 170.5 µs 229.8 µs -25.79%
❌ test_perf_client_calls[async] 20 ms 27 ms -25.74%
❌ test_perf_aws_style_openapi_pydantic_v2 1.4 s 1.9 s -25.47%
❌ test_perf_unique_items_permuted_object_validation 40.7 ms 54.6 ms -25.44%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix-5154-typeddict-null (f5c869e) with fe7b-node-tests (77ccefe)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@github-actions

Copy link
Copy Markdown
Contributor

@codecov

codecov Bot commented Oct 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@koxudaxi
Koudai Aono (koxudaxi) merged commit 68c4973 into main Oct 23, 2026
25 of 26 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the fix-5154-typeddict-null branch October 23, 2026 04:16
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The PR is an internal bug fix to nullability handling during duplicate model deletion. DataModel._prepare_dedup_key now writes pre-render nullability for every field whose hint renders its own type. It does this through a new private hook, _hint_renders_own_type, which msgspec overrides via a refactored private helper, _hint_meta. That restores the legacy L3 import-nullability behavior, so a field keeps the None of the nullable model it named when dedup points it at an equivalent model without one. For example, Model2.item correctly renders as Item or None and accepts null as the schema allows. No existing expected output files were changed. Only new test fixtures were added, and the option and default variants produce identical output. No CLI options, public Python API, templates, defaults, Python version support or error handling changed. The only removed lines are doc wording and private-method internals moved into a helper. This corrects wrong output in a narrow edge case to match the schema and earlier behavior, so it is not a breaking change.


This analysis was produced by the release draft workflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TypedDict output drops null from a nullable object property narrowed in another oneOf branch

1 participant