Skip to content

Respect model-level strict config in synthesized RootModel __init__ - #5649

Open
soaring0616 wants to merge 4 commits into
pyrefly-org:mainfrom
soaring0616:fix-rootmodel-config-strict
Open

soaring0616 wants to merge 4 commits into
pyrefly-org:mainfrom
soaring0616:fix-rootmodel-config-strict

Conversation

@soaring0616

@soaring0616 soaring0616 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

For a concrete root type (not Any or a type variable), Pyrefly widens the root parameter of the synthesized RootModel.__init__ to Any when strict mode is disabled (pydantic.rs#L165-L169). This allows valid Pydantic runtime coercions (e.g., passing bytes to RootModel[str]) without triggering false positives, preserving root to the concrete type only when strict mode is enabled.

Previously, has_strict was computed in get_pydantic_root_model_type_via_mro (L131-L133), which only captured strictness written on the base class type argument (such as RootModel[StrictInt]), including when inherited from a parent class. As a result, model-level strict=True from model_config or a class keyword, as well as field-level Field(strict=...) on root, were ignored.

This change updates RootModel.__init__ synthesis to respect dataclass.kws.strict and Field(strict=...) on root (including inherited root definitions), while keeping type-level strictness (StrictInt/StrictStr) strict even when Field(strict=False) is set.

To match Pydantic's shallow vs. deep strictness semantics, Field(strict=True) without model-level strict=True preserves concrete types only for leaf root types (a ClassType with no type arguments after stripping None from unions) and falls back to Any for parameterized containers, whereas model-level strict=True remains deep. (See the PR review comments for known caveats regarding wrong outer container types under shallow Field(strict=True) and nested Pydantic models as root.)

Fixes #5242

  • I am a human, and I fully understand the code I am submitting.

What changed

  • pyrefly/lib/alt/class/dataclass.rs:L156:160: Passed dataclass.kws.strict alongside has_strict when calling get_pydantic_root_model_init.
  • pyrefly/lib/alt/class/pydantic.rs:L157:199: Added is_pydantic_root_leaf_type and updated get_pydantic_root_model_init so Field(strict=...) on root overrides model_config, widening non-leaf containers to Any under shallow Field(strict=True) while keeping model-level strict=True deep.
  • pyrefly/lib/test/pydantic/root_model.rs:L353:373: Added test_root_model_config_strict with test classes covering model_config (class Text), class keyword (class Text2), inherited strictness (class Child), and the default lax behavior (class Lax).
  • pyrefly/lib/test/pydantic/strictness.rs:L684:773: Added 4 test functions covering Field(strict=...) precedence over model_config, shallow vs. deep container strictness, and Optional unwrapping.

Test Plan

  • cargo test -p pyrefly --lib -- test::pydantic passes (178 passed; 0 failed; 0 ignored, up from 174):
    • test_root_model_config_strict: model_config, class keyword, inherited strictness, and lax default.
    • test_root_model_field_strict_overrides_config: Field(strict=...) overriding model_config (including inherited root), and StrictStr staying strict over Field(strict=False).
    • test_root_model_field_strict_shallow_containers: Shallow Field(strict=True) on list[int] and dict[str, int] falling back to Any (with known false negative for (1,) documented).
    • test_root_model_config_and_field_strict_deep: Direct and inherited ConfigDict(strict=True) + Field(strict=True) remaining deep.
    • test_root_model_field_strict_optional_unwrapping: Stripping None from Optional[list[int]] (shallow) vs. Optional[int] (strict).

Negative controls

  • Removing the leaf-type check (Some(true) => true) causes test_root_model_field_strict_shallow_containers and test_root_model_field_strict_optional_unwrapping to fail while test_root_model_config_and_field_strict_deep passes.
  • Removing model_strict from Some(true) causes test_root_model_config_and_field_strict_deep to fail while the shallow tests pass.

Other tests

  • Full test suite (test.py): On macOS debug builds, test::cycles::deep_phi_chain_term_expr hits a pre-existing stack overflow (reproduced without this change); the suite passes with PYREFLY_STACK_SIZE=33554432.
  • Formatting & lints: cargo fmt --check and cargo clippy pass with no warnings.

AI disclosure

  • I used Claude and Gemini to study the codebase, provides the possible direction and the test range.
  • I repeatedly test my ideas and confirm the direction, and verify them on my local machine.

@github-actions

This comment has been minimized.

@stroxler stroxler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks pretty good, thanks!

There's one issue: it looks like we aren't correctly having Field settings override what comes from the config / etc. For example this code:

from pydantic import ConfigDict, Field, RootModel

class Text(RootModel[str]):
    model_config = ConfigDict(strict=True)
    x: str = Field(strict=False)

Text(b"hello")

produces a type error, but because x is marked as non-strict explicitly it should be permitted

@soaring0616

Copy link
Copy Markdown
Contributor Author

Thanks for your review and sorry for late reply.

I’ve run your code and found NameError: Unexpected field with name 'x'; only 'root' is allowed as a field of a RootModel. I've discussed with AI and assuming you meant root: str = Field(strict=False):

class Text(RootModel[str]):
    model_config = ConfigDict(strict=True)
    root: str = Field(strict=False)

Text(b"hello")  # Passes in Pydantic, currently errors in this PR

To fix this, I'd like to apply the following precedence rule for RootModel:
strict = type_level or (field_level if field_level is not None else model_level)
This ensures Field(strict=...) overrides model_config (including when root is inherited from a parent class). Note that Annotated[..., Strict(False)] will remain out of scope since BaseModel has the same existing limitation.

There is another question from also the discussion with AI on the first part of that rule: in Pydantic, StrictStr / StrictInt overrides Field(strict=False), and RootModel currently matches that. However, Pyrefly's BaseModel currently lets Field(strict=False) override StrictInt.

class M(BaseModel):
    model_config = ConfigDict(strict=True)
    c: StrictInt = Field(strict=False)

M(c="1")  

I've run it on my local machine and found an error in Pydantic; but no error in Pyrefly.

Would you prefer RootModel to follow Pydantic or match BaseModel? If I don't hear otherwise, I'll stick with Pydantic's behavior.

- Pass type-level and model-level strictness separately into get_pydantic_root_model_init
- Extract field-level strictness from root's Field keywords so it overrides model_config (including inherited fields) while keeping type-level strictness (e.g. StrictStr) highest priority
- Add unit tests covering RootModel strictness precedence
@github-actions github-actions Bot added size/xs and removed size/xs labels Nov 20, 2026
@meta-codesync

meta-codesync Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

This pull request has been imported. If you are a Meta employee, you can view this in D133386946. (Because this pull request was imported automatically, there will not be any future comments.)

@github-actions

This comment has been minimized.

@soaring0616

Copy link
Copy Markdown
Contributor Author

Hi @stroxler, sorry for missing the need to re-request your review after pushing the update. I've re-requested it now.

@stroxler stroxler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry my bad, yes that should have been root, not x.

For the semantics, let's follow Pydantic behavior and not Pyrefly's existing BaseModel bug. It appears that StrictInt/StrictStr remain strict despite Field(strict=False) in the examples discussed.

Any bugs we encounter in the process that aren't directly tied to this change could be fixed by separate PRs (and PRs / issues for more bugs are welcome - the truth is we don't use Pydantic on the Pyrefly team much, so maintaining Pydantic without community help is challenging)


Based on an AI review, I think there's one more tweak we need in this change:

For RootModel[list[int]] with root: list[int] = Field(strict=True), Pydantic accepts ["1"] and converts it to [1]. Field strictness affects the outer list, not its elements. The PR instead synthesizes a list[int] parameter and would reject that valid input.

- Preserve concrete `root` types under `Field(strict=True)` without strict
  `model_config` only when `root` is a leaf type (a `ClassType` with no type
  arguments after excluding `None` from unions).
- Fall back to `Any` for non-leaf containers (`list`, `dict`, etc.) so coerced
  elements do not trigger false positives.
- Keep deep strictness when `strict=True` is set on `model_config` (directly
  or via inheritance) alongside `Field(strict=True)`.
@github-actions github-actions Bot added size/s and removed size/xs labels Nov 25, 2026
@github-actions

This comment has been minimized.

@github-actions github-actions Bot added size/s and removed size/s labels Nov 25, 2026
@github-actions

Copy link
Copy Markdown

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@soaring0616

Copy link
Copy Markdown
Contributor Author

Thank you for your suggestions. I've pushed an update to handle shallow and deep strictness:

  • Shallow Field(strict=True)(when model-level strictness is off): Leaf root types (e.g. int and Optional[int]) keep their concrete type, while parameterized containers (list[int], dict[str, int], list[int] | None) now fall back to Any so element coercion doesn't trigger false positives. This introduces a false negative, though, when the outer container type itself is wrong (e.g. passing (1,) to list[int] won't error even though Pydantic rejects it).
  • Deep model_config strictness: When model_config sets strict=True (directly or via inheritance), strictness remains deep and preserves the concrete container type.
  • Type-level strictness: StrictInt/StrictStr continues to stay strict despite Field(strict=False), matching Pydantic.

AI reminds that there is still one caveat on leaf types: nested Pydantic models as root (e.g. RootModel[InnerModel]) still retain their type under both Field(strict=True) and model_config strictness. Because Pydantic still accepts dict inputs (such as {“a”:1}) for nested models in strict mode, this leads to a false positive.

I'll file separate follow-up issues for this nested model root case alongside the pre-existing false positives on BaseModel fields with Field(strict=True) on containers, and RootModel[list[StrictInt]].

This branch has not been deployed

No deployments
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.

Pyrefly's synthesized Pydantic RootModel constructor ignores model-level strict=True

2 participants