Skip to content

Select python-re for a repetition whose minimum exceeds its maximum, import a model of a module that a shared import names under an alias, give item counts only to fields that can hold an array, and watch a JSON file named like inline JSON - #6037

Merged
Koudai Aono (koxudaxi) merged 1 commit into
mainfrom
fix1-27
Nov 3, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
mainfrom
fix1-27

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes
    • Improved generated model imports when an imported name conflicts with a model name.
    • Corrected array item-count constraints so they apply to array-compatible fields, not unrelated field types.
    • Refined regex engine selection for repetition patterns where the minimum count exceeds the maximum.
    • Clarified errors for malformed security requirement scopes.
    • Improved detection of file paths versus inline JSON in configuration values and file watching.
  • Documentation
    • Expanded guidance on constraints, configuration fields, import naming, and regex patterns.

@coderabbitai

coderabbitai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Walkthrough

The changes update JSON Schema constraint assembly, generated import binding, regex-engine selection, configuration file detection, and a target-contract error. Regression tests, expected outputs, behavior-diff allowlist entries, and documentation are updated alongside these changes.

Changes: Array-count constraints

Layer / File(s) Summary
Array-count applicability
src/datamodel_code_generator/parser/_value_keywords.py, src/datamodel_code_generator/parser/jsonschema.py, docs/architecture.md
Constraint assembly checks whether a field can hold an array. Property and root fields use different settings for item counts beside model types.
Generated output and behavior cases
tests/main/jsonschema/test_field_constraint_sites.py, tests/data/expected/main/jsonschema/field_constraint_sites/*, scripts/behaviour_diff_allowlist.toml, tests/main/test_payload_validation.refs
Regression cases and accepted output changes cover item counts on array-capable fields and their absence on non-array fields.

Generated import binding

Layer / File(s) Summary
Shared-import name resolution
src/datamodel_code_generator/parser/_passes/_import_binding.py, src/datamodel_code_generator/parser/_passes/imports.py, docs/architecture.md
Import-target resolution records shared-import name conflicts and reserves the relevant names.
Generated import output
tests/main/jsonschema/test_main_jsonschema.py, tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/*, tests/main/test_payload_validation.refs
Regression output covers a generated model import aliased alongside a shared import.

Counted-repetition regex selection

Layer / File(s) Summary
Counted-repetition bounds
src/datamodel_code_generator/_regex_syntax.py, docs/jsonschema.md
The scanner captures repetition bounds and identifies cases where the minimum exceeds the maximum.
Engine selection cases
tests/main/jsonschema/test_pydantic_accepted_forms.py, tests/data/expected/main/jsonschema/pydantic_accepted_forms/*, tests/main/test_payload_validation.refs
Tests cover reversed and ordered repetitions, including spaced and verbose patterns.

Configuration file detection

Layer / File(s) Summary
Shared JSON file detection
src/datamodel_code_generator/_config_fields.py, src/datamodel_code_generator/json_config.py, docs/architecture.md
Shared helpers identify existing file paths, and JSON configuration readers use the shared JSON-file check.
Configuration recovery and watch paths
src/datamodel_code_generator/__main__.py, src/datamodel_code_generator/watch_dependencies.py, tests/main/test_main_watch.py
Recovery and watch-dependency handling use names_file. Tests cover existing and missing files whose names resemble inline JSON.

Target-contract error

Layer / File(s) Summary
Missing scopes validation
src/datamodel_code_generator/_target_contract.py
A missing scopes value receives a distinct error from invalid scope tokens.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Possibly related issues

  • Issue 6035: The changes address item-count constraints derived from contains and minContains when a field cannot hold an array.
  • Issue 6003: The import-binding changes address model-name conflicts caused by shared imports.
  • Issue 5636: The regex changes select the Python engine for counted repetitions whose minimum exceeds their maximum.
  • Issue 6009: The import-binding changes address shared-import name conflicts that can hide a generated model import.

Possibly related PRs

Merge Risk: Moderate · previous review d9eba

Generated models can accept arrays that violate the schema's minimum item count. Preserve array-specific validation for referenced roots and untyped properties without constraining non-array values before merging.

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 lists four changes: python-re engine selection for reversed counted repetitions, aliasing a model import that collides with a shared import name, limiting item counts to fields that can hold…
Docstring Coverage Passed Docstring coverage is 86.96% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title lists four changes: python-re engine selection for reversed counted repetitions, aliasing a model import that collides with a shared import name, limiting item counts to fields that can hold arrays, and watching a JSON file whose name resembles inline JSON. Each appears in the summarized changes (regex engine selection in _regex_syntax.py and the pydantic accepted-forms tests, import binding in _import_binding.py and generated shared_import_named_like_module_and_model files, can_hold_array and counts_beside_models in jsonschema.py and _value_keywords.py, and names_file/json_file with watch tests). The title is accurate but long at 239 characters and 44 words, and it joins four unrelated fixes into one sentence. It does not name a single primary change, so it is broad rather than focused. The objectives confirm these four themes, so the title is related to the changeset and not misleading.

Full details: Docstring Coverage

Explanation

Docstring coverage is 86.96% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 23 functions across 19 files. (8 skipped: 7 unsupported, 1 too large.)

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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 7eac448 and d9ebaaf1f155183c269b8003b25870a1806863db.

Files ignored due to path filters: 9
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/expected/main/generation_platform/client/auth-errors.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/expected/main/jsonschema/pydantic_accepted_forms/counted_repetitions_with_a_minimum_above_the_maximum_select_the_python_engine.payloads.txt is excluded by !tests/data/**/*.txt and included by none
  • tests/data/jsonschema/field_constraint_sites/array_counts_beside_other_types.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/field_constraint_sites/array_counts_root_reference.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/rust_unsupported_reversed_repetition.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/shared_import_named_like_model/api.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/jsonschema/shared_import_named_like_model/common.json is excluded by !tests/data/**/*.json and included by none
  • tests/data/payloads/field_constraint_sites/array_counts_beside_other_types.json is excluded by !tests/data/**/*.json and included by none
Files selected for processing: 27
  • docs/architecture.md
  • docs/jsonschema.md
  • scripts/behaviour_diff_allowlist.toml
  • src/datamodel_code_generator/__main__.py
  • src/datamodel_code_generator/_config_fields.py
  • src/datamodel_code_generator/_regex_syntax.py
  • src/datamodel_code_generator/_target_contract.py
  • src/datamodel_code_generator/json_config.py
  • src/datamodel_code_generator/parser/_passes/_import_binding.py
  • src/datamodel_code_generator/parser/_passes/imports.py
  • src/datamodel_code_generator/parser/_value_keywords.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • src/datamodel_code_generator/watch_dependencies.py
  • tests/data/expected/main/jsonschema/field_constraint_sites/field_constraint_sites[array_counts_beside_other_types-extra_args7].py
  • tests/data/expected/main/jsonschema/field_constraint_sites/root_model_of_a_reference_takes_no_item_counts.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/IPv4Address.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/__init__.py
  • tests/data/expected/main/jsonschema/main_jsonschema/shared_import_named_like_module_and_model/api.py
  • tests/data/expected/main/jsonschema/pydantic_accepted_forms/counted_repetitions_with_a_minimum_above_the_maximum_select_the_python_engine.py
  • tests/main/jsonschema/test_field_constraint_sites.py
  • tests/main/jsonschema/test_field_constraint_sites.refs
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/jsonschema/test_pydantic_accepted_forms.py
  • tests/main/jsonschema/test_pydantic_accepted_forms.refs
  • tests/main/test_main_watch.py
  • tests/main/test_payload_validation.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.

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 3, 2026 03:16
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

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 ✅ Completed 2026-11-03T03:18:22.444782Z d9ebaaf Draft marked ready
ℹ️ 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.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d9ebaaf1f1

ℹ️ About Codex in GitHub

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

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "Codex (@codex) review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

@codspeed

codspeed Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 54.64%

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

⚠️ 52 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚡ 52 improved benchmarks
⏩ 98 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_perf_simple_msgspec_unset_field_rendering 590 ms 321.9 ms +83.27%
⚡ test_perf_client_calls[sync] 44.8 ms 25 ms +79.15%
⚡ test_perf_client_calls[async] 49.5 ms 28.1 ms +75.88%
⚡ test_perf_scalar_root_collapsed_builtin 236.9 ms 136.5 ms +73.57%
⚡ test_perf_simple_pydantic_v2_field_construction 14.6 ms 8.7 ms +66.75%
⚡ test_perf_load_pyproject_config[config-None] 371.8 µs 223.8 µs +66.1%
⚡ test_perf_load_pyproject_config[mapping-multiple] 388.3 µs 234.6 µs +65.53%
⚡ test_perf_large_models_typed_dict[total-false-requiredness] 1,361.5 ms 824.1 ms +65.21%
⚡ test_perf_local_reference_file_resolution 153.5 ms 93.6 ms +64.03%
⚡ test_perf_load_pyproject_config[config-multiple] 388.3 µs 236.8 µs +63.97%
⚡ test_perf_load_pyproject_config[mapping-None] 373.1 µs 228.1 µs +63.54%
⚡ test_perf_large_models_single_module_stdout 1.8 s 1.1 s +62.84%
⚡ test_perf_large_models_pydantic_v2_builtin 1,511.8 ms 928.7 ms +62.8%
⚡ test_perf_inherited_required_fields[required-base-first] 744.8 ms 458.7 ms +62.37%
⚡ test_perf_large_models_msgspec 2.3 s 1.4 s +62.33%
⚡ test_perf_large_models_pydantic_v2_builtin_double_quotes 1,564.5 ms 966 ms +61.96%
⚡ test_perf_inherited_required_fields[partial-base-first] 1,188.1 ms 737.1 ms +61.19%
⚡ test_perf_large_models_typed_dict[legacy-requiredness] 1,345.6 ms 837.7 ms +60.62%
⚡ test_perf_inherited_required_fields[required-derived-first] 842.7 ms 524.7 ms +60.6%
⚡ test_perf_ordinary_array_constraint_generation 2.3 s 1.4 s +60.14%
... ... ... ... ...

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

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix1-27 (3815ee8) with main (50cbac2)

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. ↩

@coderabbitai coderabbitai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

  • Fix comments: Fix CodeRabbit comments on this PR

Base automatically changed from fix1-26 to main November 3, 2026 04:47
…import a model of a module that a shared import names under an alias, give item counts only to fields that can hold an array, and watch a JSON file named like inline JSON

Fixes for the unresolved review findings of #6013, #6014, #6016, #6032 and #6033.

The scan of regex syntax reads the two counts of a counted repetition and reports one whose minimum exceeds its maximum,
which the Rust engine rejects at import. Python's `re` reads such a repetition as text where whitespace or a verbose
comment is inside (`a{ 3 , 2 }`), so the model selects python-re; without whitespace both engines reject it, as before.

A model imported from its module because a shared import binds the module's name (`from .IPv4Address import
OrderedDict`) rebound `OrderedDict` where another shared import (`--external-ref-mapping common.json=collections`)
binds it too, and the field typed by the mapped type got the model. The import takes an alias then (`OrderedDict_1`):
`ReferenceImportTarget.reserve_name` keeps the resolver of the module from giving it the shared name, in the import it
adds and in the replay of the released names.

`scope_problem` names the shape of scopes that are not an array of strings before it judges tokens, so a scheme that
takes no scope tokens (`apiKey`, `http`) no longer reports "requires valid scope tokens" for `bearer: 42`.

The item counts that boolean `items` and `contains` imply belong to an array. A root model took them for every type
since the root read them as a property does, so `{"type": "string", "contains": true, "minContains": 2}` became
`min_length=2` and rejected the strings the schema accepts, as the property of that schema always did, and a root
that names a model (`{"$ref": "#/$defs/Names", "contains": true, "minContains": 2}`) got a `min_length` that Pydantic
cannot apply to a model, which raised at the first array. A field whose type is no array (a scalar, a mapping, `Any`)
takes none (`can_hold_array`), and neither does a root beside a model, as in 0.88.0; a custom type and a union with an
array keep them. An object property beside a model keeps them as in 0.88.0 (row `legacy-property-counts-beside-models`).
The behaviour diff against 0.88.0 accepts the property change of the new fixture.

The allowlist entries of the property maps of a type list that joins an array match the minProperties and
maxProperties change only (the constraint, default, required and constructor-order lines it makes), not any change of
that field.

A JSON option value that starts like inline JSON names a file where one exists, which the option reads first
(`json_file`, moved from `json_config` to `_config_fields`). `--watch` watches that file (`names_file`) in the watch
graph of a run and in the recovery of a failed plan; the resolver of the planned job is unchanged.
@codecov

codecov Bot commented Nov 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Koudai Aono (koxudaxi) added a commit that referenced this pull request Nov 3, 2026
Hyphenated directory (#6039). A directory is read as importable by its name once its `-` is `_`, as the output writes it
(`written_name`): `café-models` is written to `café_models/` and imported by that name, as the files of 0.88.0 were
written, where the check came before the `-` was replaced and the directory was sanitized as a file's name is
(`caf__models`), so it moved and two directories of the same length (`café-models`, `cafè-models`) shared one package. The
import of such a directory was a syntax error up to 0.88.0 (`from .café-models import a`), so only output that failed to
import changes.

Names an additional import binds (#6041). A type of a module that writes a dotted name writes the first name of it where
the module's names are read (`ipaddress.IPv4Address` binds `ipaddress`), not the last one. The check of the imports every
module writes that a model of the module shadows reads that first name (`iter_python_type_expr_head_names`), so a model
named like the last name of a qualified runtime symbol (`x-python-import` `symbols`) keeps its name, as in 0.88.0. The
name a model or an import takes anew where a shared import binds the name it had skips the names the shared imports bind
(`shared_import_bindings`), so `IPv4Address1` is not given to a model where `mymod.IPv4Address1` is imported by every
module, nor `Status_1` or `list_1` to the import a package names anew.

Enum member defaults (#6040). `set_default_enum_member` writes a member by the expression its type names the enum by when
it runs, so a default kept naming the import that the passes of the imports named anew afterwards (`Status` for
`Status as Status_1`, `list.Pop` for `list_1.Pop`) and the generated module failed to import. The two passes that name an
import anew write the new expression into the members of the defaults that use it (`name_enum_member`, a store mutation
with its row in the fact table).

Item counts (#6037). The item counts that `contains` and boolean `items` imply belong to a field whose schema admits an
array (it declares no type, or an array is one of them) as well as whose type can hold one: a string typed
`datetime.date` and an object with array values (`{"type": "object", "additionalProperties": {"type": "array"}}`) took
`min_length` from them, which raised `Unable to apply constraint` for a date and rejected the maps with fewer keys.
@koxudaxi
Koudai Aono (koxudaxi) merged commit 64af1d1 into main Nov 3, 2026
165 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the fix1-27 branch November 3, 2026 07:53
Koudai Aono (koxudaxi) added a commit that referenced this pull request Nov 3, 2026
…, so a run without models does not load it (#6043)

* Import the type expression reader of the model renames where they run, so a run without models does not load it

* Fix the unresolved review findings of #6037, #6039, #6040 and #6041

Hyphenated directory (#6039). A directory is read as importable by its name once its `-` is `_`, as the output writes it
(`written_name`): `café-models` is written to `café_models/` and imported by that name, as the files of 0.88.0 were
written, where the check came before the `-` was replaced and the directory was sanitized as a file's name is
(`caf__models`), so it moved and two directories of the same length (`café-models`, `cafè-models`) shared one package. The
import of such a directory was a syntax error up to 0.88.0 (`from .café-models import a`), so only output that failed to
import changes.

Names an additional import binds (#6041). A type of a module that writes a dotted name writes the first name of it where
the module's names are read (`ipaddress.IPv4Address` binds `ipaddress`), not the last one. The check of the imports every
module writes that a model of the module shadows reads that first name (`iter_python_type_expr_head_names`), so a model
named like the last name of a qualified runtime symbol (`x-python-import` `symbols`) keeps its name, as in 0.88.0. The
name a model or an import takes anew where a shared import binds the name it had skips the names the shared imports bind
(`shared_import_bindings`), so `IPv4Address1` is not given to a model where `mymod.IPv4Address1` is imported by every
module, nor `Status_1` or `list_1` to the import a package names anew.

Enum member defaults (#6040). `set_default_enum_member` writes a member by the expression its type names the enum by when
it runs, so a default kept naming the import that the passes of the imports named anew afterwards (`Status` for
`Status as Status_1`, `list.Pop` for `list_1.Pop`) and the generated module failed to import. The two passes that name an
import anew write the new expression into the members of the defaults that use it (`name_enum_member`, a store mutation
with its row in the fact table).

Item counts (#6037). The item counts that `contains` and boolean `items` imply belong to a field whose schema admits an
array (it declares no type, or an array is one of them) as well as whose type can hold one: a string typed
`datetime.date` and an object with array values (`{"type": "object", "additionalProperties": {"type": "array"}}`) took
`min_length` from them, which raised `Unable to apply constraint` for a date and rejected the maps with fewer keys.

* Provide the module the additional imports of the renamed-import test name, so the output imports on Python 3.10
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: Breaking changes detected

Reasoning: The full diff was read. The behaviour diff gate marks the array_counts_beside_other_types cells as accepted for Pydantic BaseModel, Pydantic dataclass and msgspec under default options. The new can_hold_array check in the field constraint assembly drops the implied item counts from string and mapping properties, so default generated code changes: MinLen or Meta min_length is removed, and the pydantic dataclass default and constructor order change. This is reported as a code generation change. The other changes are not breaking. Reversed counted repetitions selecting the python-re engine fix models that previously failed at import. The import alias for a model whose name a shared import also binds fixes an edge-case collision. Watch mode now also tracks JSON option files whose names look like inline JSON. The private helpers _json_file and _path_is_file were moved into _config_fields as json_file. The client security scope error message was reworded, but the input still fails the same way. The other accepted cells in the gate come from earlier changes whose allowlist patterns were only tightened here.

Content for Release Notes

Code Generation Changes


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.

1 participant