Skip to content

Fix deep hierarchy type inheritance in allOf property overrides#2843

Merged
koxudaxi merged 1 commit intomainfrom
fix/allof-deep-hierarchy-type-inheritance
Dec 28, 2025
Merged

Fix deep hierarchy type inheritance in allOf property overrides#2843
koxudaxi merged 1 commit intomainfrom
fix/allof-deep-hierarchy-type-inheritance

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Dec 28, 2025

Fixes: #2645

Summary by CodeRabbit

  • New Features

    • Enhanced JSON Schema generator to properly handle complex class inheritance hierarchies with property overrides across multiple levels.
    • Improved cycle prevention when resolving inherited types in deeply nested inheritance patterns.
  • Tests

    • Added comprehensive test coverage for complex inheritance scenarios, including deep hierarchies and property overrides.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 28, 2025

📝 Walkthrough

Walkthrough

The PR fixes allOf class hierarchy generation by enhancing _get_inherited_field_type with cycle detection, recursive traversal, and robust reference resolution. Four new test cases validate deep inheritance hierarchies with property overrides and inline allOf structures.

Changes

Cohort / File(s) Summary
Core inheritance logic fix
src/datamodel_code_generator/parser/jsonschema.py
Enhanced _get_inherited_field_type signature to include visited parameter for cycle prevention. Added per-base tracking to avoid infinite loops, improved ref path computation (supports paths with/without "#" fragment), robust parent schema loading, and recursive resolution through parent allOf constraints when direct properties are absent.
Test coverage
tests/main/jsonschema/test_main_jsonschema.py
Four new test functions: test_main_all_of_deep_hierarchy_property_override, test_main_all_of_very_deep_hierarchy_property_override, test_main_all_of_hierarchy_property_not_in_ancestor, test_main_all_of_hierarchy_inline_allof. Each invokes run_main_and_assert against corresponding expected output files.
Expected outputs for generated models
tests/data/expected/main/jsonschema/all_of_*.py (4 files)
Generated Pydantic model hierarchies demonstrating: deep 3-level inheritance with type overrides, very deep 5-level inheritance with progressive field overrides and defaults, hierarchies where overridden properties skip intermediate ancestors, and inline allOf with parent property overrides.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

breaking-change-analyzed

Poem

🐰 With whiskers twitched and hop so keen,
We traverse hierarchies deep and clean,
Cycles dodged, refs resolved true,
allOf now works—the inheritance's due!
Rabbits rejoice, the schema's at peace,

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main fix: resolving deep hierarchy type inheritance issues in allOf property overrides.
Linked Issues check ✅ Passed The PR fixes the regression reported in issue #2645 by restoring proper class hierarchy generation for allOf schemas with property overrides across multiple inheritance levels.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the allOf deep hierarchy type inheritance issue; core logic fixes, expected outputs, and corresponding tests are all in scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/allof-deep-hierarchy-type-inheritance

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 and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Dec 28, 2025

📚 Docs Preview: https://pr-2843.datamodel-code-generator.pages.dev

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Dec 28, 2025

CodSpeed Performance Report

Merging #2843 will not alter performance

Comparing fix/allof-deep-hierarchy-type-inheritance (4ba0ba7) with main (95cd6d5)

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

Summary

✅ 11 untouched
⏩ 98 skipped1

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 28, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.49%. Comparing base (95cd6d5) to head (4ba0ba7).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2843   +/-   ##
=======================================
  Coverage   99.49%   99.49%           
=======================================
  Files          90       90           
  Lines       14353    14376   +23     
  Branches     1717     1723    +6     
=======================================
+ Hits        14281    14304   +23     
  Misses         37       37           
  Partials       35       35           
Flag Coverage Δ
unittests 99.49% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi force-pushed the fix/allof-deep-hierarchy-type-inheritance branch from 49d2677 to 4ba0ba7 Compare December 28, 2025 18:10
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/datamodel_code_generator/parser/jsonschema.py (1)

1778-1778: Remove unused noqa directive.

The # noqa: PLR0912 directive is no longer needed as the function no longer triggers the "too many branches" rule.

🔎 Proposed fix
-    def _get_inherited_field_type(  # noqa: PLR0912
+    def _get_inherited_field_type(
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 95cd6d5 and 4ba0ba7.

⛔ Files ignored due to path filters (4)
  • tests/data/jsonschema/all_of_deep_hierarchy_property_override.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/all_of_hierarchy_inline_allof.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/all_of_hierarchy_property_not_in_ancestor.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/all_of_very_deep_hierarchy_property_override.json is excluded by !tests/data/**/*.json and included by none
📒 Files selected for processing (6)
  • src/datamodel_code_generator/parser/jsonschema.py
  • tests/data/expected/main/jsonschema/all_of_deep_hierarchy_property_override.py
  • tests/data/expected/main/jsonschema/all_of_hierarchy_inline_allof.py
  • tests/data/expected/main/jsonschema/all_of_hierarchy_property_not_in_ancestor.py
  • tests/data/expected/main/jsonschema/all_of_very_deep_hierarchy_property_override.py
  • tests/main/jsonschema/test_main_jsonschema.py
🧰 Additional context used
🧬 Code graph analysis (5)
tests/main/jsonschema/test_main_jsonschema.py (2)
tests/main/conftest.py (2)
  • output_file (98-100)
  • run_main_and_assert (244-408)
src/datamodel_code_generator/__init__.py (1)
  • chdir (245-255)
src/datamodel_code_generator/parser/jsonschema.py (1)
src/datamodel_code_generator/reference.py (3)
  • Reference (141-200)
  • get (965-967)
  • add_ref (787-810)
tests/data/expected/main/jsonschema/all_of_hierarchy_property_not_in_ancestor.py (2)
src/datamodel_code_generator/model/base.py (1)
  • name (826-828)
tests/data/expected/main/jsonschema/all_of_hierarchy_inline_allof.py (2)
  • Parent (12-14)
  • Child (17-18)
tests/data/expected/main/jsonschema/all_of_deep_hierarchy_property_override.py (2)
tests/data/expected/main/jsonschema/all_of_very_deep_hierarchy_property_override.py (3)
  • Entity (14-15)
  • Thing (18-20)
  • Person (23-25)
src/datamodel_code_generator/model/base.py (1)
  • name (826-828)
tests/data/expected/main/jsonschema/all_of_very_deep_hierarchy_property_override.py (2)
tests/data/expected/main/jsonschema/all_of_deep_hierarchy_property_override.py (3)
  • Entity (10-11)
  • Thing (14-16)
  • Person (19-20)
src/datamodel_code_generator/model/base.py (1)
  • name (826-828)
🪛 Ruff (0.14.10)
src/datamodel_code_generator/parser/jsonschema.py

1778-1778: Unused noqa directive (non-enabled: PLR0912)

Remove unused noqa directive

(RUF100)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: py312-isort6 on Ubuntu
  • GitHub Check: 3.10 on Ubuntu
  • GitHub Check: py312-isort7 on Ubuntu
  • GitHub Check: 3.10 on Windows
  • GitHub Check: 3.13 on Windows
  • GitHub Check: 3.12 on Windows
  • GitHub Check: 3.14 on Windows
  • GitHub Check: 3.11 on Windows
  • GitHub Check: Analyze (python)
  • GitHub Check: benchmarks
🔇 Additional comments (6)
tests/data/expected/main/jsonschema/all_of_deep_hierarchy_property_override.py (1)

1-20: Expected model correctly encodes deep allOf hierarchy and property override

Entity → Thing → Person inheritance and the type overrides look consistent with the intended fix: Person preserves the str base type while adding optionality and a default, and constraints on Thing.name are carried as expected. No changes needed.

tests/main/jsonschema/test_main_jsonschema.py (1)

1426-1471: New allOf deep-hierarchy tests align with existing patterns and cover the regression well

The four added tests follow the established chdir(JSON_SCHEMA_DATA_PATH) + run_main_and_assert pattern, target the correct JSON inputs, and assert against the corresponding expected Python artifacts. The docstrings clearly document the deep/very-deep, missing-ancestor, and inline-allOf scenarios, giving good coverage for the fixed inheritance logic. No issues found.

src/datamodel_code_generator/parser/jsonschema.py (1)

1778-1820: LGTM! The enhanced _get_inherited_field_type method properly handles deep hierarchies.

The implementation correctly:

  • Adds cycle detection via the visited frozenset to prevent infinite loops
  • Recursively traverses grandparent references through allOf constraints
  • Constructs proper ref paths for both fragment-based (#/...) and plain paths

This addresses the regression from v0.38.0 where deep class hierarchies with allOf stopped producing proper inheritance.

tests/data/expected/main/jsonschema/all_of_hierarchy_inline_allof.py (1)

1-18: LGTM! Test fixture correctly validates inline allOf hierarchy generation.

The generated models demonstrate proper inheritance where Child extends Parent and overrides the status field with a different default value, which is the expected behavior for the inline allOf scenario.

tests/data/expected/main/jsonschema/all_of_hierarchy_property_not_in_ancestor.py (1)

1-21: LGTM! Test fixture validates property inheritance when property is not in root ancestor.

This correctly tests the scenario where a property (category) is introduced at an intermediate level (Parent) and overridden at the child level, while Grandparent has a different property (name). The inheritance chain is properly maintained.

tests/data/expected/main/jsonschema/all_of_very_deep_hierarchy_property_override.py (1)

1-30: LGTM! Test fixture validates very deep hierarchy with property overrides.

This 5-level inheritance chain (BaseEntityThingPersonSpecificPerson) effectively validates the recursive traversal enhancement. The type field is progressively overridden with different defaults at each level, and SpecificPerson correctly overrides the id field from the root Base class—demonstrating the fix works across the full inheritance depth.

@koxudaxi koxudaxi merged commit 19f1fb7 into main Dec 28, 2025
38 checks passed
@koxudaxi koxudaxi deleted the fix/allof-deep-hierarchy-type-inheritance branch December 28, 2025 18:15
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix that improves the handling of deep inheritance hierarchies in allOf property overrides. The changes are:

  1. Code change analysis: The _get_inherited_field_type method in jsonschema.py was enhanced to recursively traverse the inheritance chain when looking for type information in parent schemas. It now:

    • Added a visited parameter to track already-visited references and prevent cycles
    • Added logic to traverse allOf references in parent schemas to find grandparent types
  2. No breaking changes because:

    • The function signature change adds an optional parameter (visited) with a default value (None), which is backward compatible
    • This is an internal method (prefixed with _) not part of the public API
    • The change fixes incorrect behavior where type information wasn't properly inherited in deep hierarchies
    • Generated code output is corrected to be more accurate, not changed in a breaking way
    • No CLI or API changes were made
    • No default behavior changes that would affect working schemas
    • No template changes required
  3. Nature of the fix: Previously, when a child schema had an allOf reference to a parent that itself had an allOf reference to a grandparent, the type resolution would not recursively look up the inheritance chain. This caused incorrect or missing type annotations in generated code. The fix makes the type resolution work correctly for deep hierarchies, which is a bug fix that produces more correct output.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jan 1, 2026

🎉 Released in 0.51.0

This PR is now available in the latest release. See the release notes for details.

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.

Version >= 0.38 breaks allof class hierarchy

1 participant