Repository navigation
Respect model-level strict config in synthesized RootModel __init__ - #5649
soaring0616 wants to merge 4 commits into
Conversation
This comment has been minimized.
This comment has been minimized.
stroxler
left a comment
There was a problem hiding this comment.
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
|
Thanks for your review and sorry for late reply. I’ve run your code and found class Text(RootModel[str]):
model_config = ConfigDict(strict=True)
root: str = Field(strict=False)
Text(b"hello") # Passes in Pydantic, currently errors in this PRTo fix this, I'd like to apply the following precedence rule for There is another question from also the discussion with AI on the first part of that rule: in Pydantic, 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 |
- 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
|
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.) |
This comment has been minimized.
This comment has been minimized.
|
Hi @stroxler, sorry for missing the need to re-request your review after pushing the update. I've re-requested it now. |
stroxler
left a comment
There was a problem hiding this comment.
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)`.
This comment has been minimized.
This comment has been minimized.
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
|
Thank you for your suggestions. I've pushed an update to handle shallow and deep strictness:
AI reminds that there is still one caveat on leaf types: nested Pydantic models as I'll file separate follow-up issues for this nested model root case alongside the pre-existing false positives on |
Summary
For a concrete root type (not
Anyor a type variable), Pyrefly widens therootparameter of the synthesizedRootModel.__init__toAnywhen strict mode is disabled (pydantic.rs#L165-L169). This allows valid Pydantic runtime coercions (e.g., passingbytestoRootModel[str]) without triggering false positives, preservingrootto the concrete type only when strict mode is enabled.Previously,
has_strictwas computed inget_pydantic_root_model_type_via_mro(L131-L133), which only captured strictness written on the base class type argument (such asRootModel[StrictInt]), including when inherited from a parent class. As a result, model-levelstrict=Truefrommodel_configor a class keyword, as well as field-levelField(strict=...)onroot, were ignored.This change updates
RootModel.__init__synthesis to respectdataclass.kws.strictandField(strict=...)onroot(including inheritedrootdefinitions), while keeping type-level strictness (StrictInt/StrictStr) strict even whenField(strict=False)is set.To match Pydantic's shallow vs. deep strictness semantics,
Field(strict=True)without model-levelstrict=Truepreserves concrete types only for leafroottypes (aClassTypewith no type arguments after strippingNonefrom unions) and falls back toAnyfor parameterized containers, whereas model-levelstrict=Trueremains deep. (See the PR review comments for known caveats regarding wrong outer container types under shallowField(strict=True)and nested Pydantic models asroot.)Fixes #5242
What changed
pyrefly/lib/alt/class/dataclass.rs:L156:160: Passeddataclass.kws.strictalongsidehas_strictwhen callingget_pydantic_root_model_init.pyrefly/lib/alt/class/pydantic.rs:L157:199: Addedis_pydantic_root_leaf_typeand updatedget_pydantic_root_model_initsoField(strict=...)onrootoverridesmodel_config, widening non-leaf containers toAnyunder shallowField(strict=True)while keeping model-levelstrict=Truedeep.pyrefly/lib/test/pydantic/root_model.rs:L353:373: Addedtest_root_model_config_strictwith test classes coveringmodel_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 coveringField(strict=...)precedence overmodel_config, shallow vs. deep container strictness, andOptionalunwrapping.Test Plan
cargo test -p pyrefly --lib -- test::pydanticpasses (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=...)overridingmodel_config(including inheritedroot), andStrictStrstaying strict overField(strict=False).test_root_model_field_strict_shallow_containers: ShallowField(strict=True)onlist[int]anddict[str, int]falling back toAny(with known false negative for(1,)documented).test_root_model_config_and_field_strict_deep: Direct and inheritedConfigDict(strict=True)+Field(strict=True)remaining deep.test_root_model_field_strict_optional_unwrapping: StrippingNonefromOptional[list[int]](shallow) vs.Optional[int](strict).Negative controls
Some(true) => true) causestest_root_model_field_strict_shallow_containersandtest_root_model_field_strict_optional_unwrappingto fail whiletest_root_model_config_and_field_strict_deeppasses.model_strictfromSome(true)causestest_root_model_config_and_field_strict_deepto fail while the shallow tests pass.Other tests
test.py): On macOS debug builds,test::cycles::deep_phi_chain_term_exprhits a pre-existing stack overflow (reproduced without this change); the suite passes withPYREFLY_STACK_SIZE=33554432.cargo fmt --checkandcargo clippypass with no warnings.AI disclosure