Skip to content

Bugs when combining reuse_model=True with collapse_root_models=True and use_title_as_name=True #3082

@aschamberger

Description

@aschamberger

Describe the bug
Schema context (repro_schema.json):
Inline property definitions with the same title generate deduplicated
root-type aliases (e.g. type Timestamp = str). Properties with
different constraints but the same base type produce root-type aliases
whose rendered output is identical — their dedup key is the same:

  ShortCode (maxLength=8): key = 'type M = str'
  Timestamp (no constraints): key = 'type M = str'

get_dedup_key() does NOT incorporate field constraints into the key,
so reuse_model considers them identical and merges them.

Bug 1 – IndexError / UndefinedError crash:
reuse_model removes the duplicate root-type model, leaving it with
empty fields. Downstream code crashes when accessing fields[0]:
- __collapse_root_models: root_type_model.fields[0] → IndexError
- TypeStatement.jinja2: fields[0] → UndefinedError

Bug 2 – Wrong constraints on collapsed fields:
If the crash in bug 1 is guarded, reuse_model still merges root-type
aliases that carry different constraints. collapse_root_models then
calls ConstraintsBase.merge_constraints(root_type_field.constraints, ...)
using the surviving model's constraints for ALL referencing fields.
Example: Timestamp fields incorrectly get max_length=8 from ShortCode.
(This is demonstrated by inspecting internal model state.)

Example schema:
repro_schema.json

Used commandline:
repro_bugs.py

Expected behavior

datamodel-codegen-reuse-model.patch

Version:

  • OS: Ubuntu 24.04
  • Python version: 3.14
  • datamodel-code-generator version: 0.55.0

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions