Repository navigation
Align extra_slots support in pydanticgen, per-class enabled - #3630
noelmcloughlin wants to merge 24 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3630 +/- ##
==========================================
+ Coverage 82.47% 85.69% +3.21%
==========================================
Files 166 166
Lines 20890 20939 +49
Branches 4416 4428 +12
==========================================
+ Hits 17230 17944 +714
+ Misses 2735 2026 -709
- Partials 925 969 +44
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
On the pydanticgen part, there's a parallel conversation happening in a other PR re: json schema gen, and I think that the option for the generator to override the schema should be removed (previously it was not overriding the schema because there was no way to control extra slots in the schema). Implementing extra slots also requires handling the expression form where a type is set for https://pydantic.dev/docs/validation/latest/concepts/models/#extra-data |
|
I think the feature might be contained enough to do python and pydanticgen in one PR, but with the addition of handling the expression form, it might balloon a bit. If it becomes unwieldy, In general I would favor splitting it by generator rather than doing boolean form first and then expression form for both, just because I think we should ship the complete feature at a time. Might be worth doing that now and splitting PR before further work done, but up to you. Re: the requested deprecation/pydanticgen part, I don't want to take work off your plate that youve already started, but I was planning on doing it this week anyway, and would be happy to help with that if its proving tricky. If you do the implementation, i can handle doing the deprecation notice for the generator param (unless you are interested in checking out how that works, at which point ofc explore!) Just offering help if its wanted and a bit of guidance so it doesn't feel like I'm asking for huge changes without help, but again not trying to be overbearing or discouraging by taking it from you. |
|
here I did the classes:
Base:
attributes:
x:
range: integer
Other:
attributes:
y:
range: string
ExtraAllowed:
is_a: Base
extra_slots:
allowed: true
ExtraNotAllowed:
is_a: Base
extra_slots:
allowed: false
ExtraString:
is_a: Base
description: "Only extra fields that are strings are valid"
extra_slots:
range_expression:
range: string
ExtraClass:
is_a: Base
description: "Only extra fields that match a class are valid"
extra_slots:
range_expression:
range: Other
ExtraAnyOf:
is_a: Base
description: "Union of allowed types"
extra_slots:
range_expression:
any_of:
- range: string
- range: integer
ExtraCardinality:
is_a: Base
description: "Limit cardinality of multivalued extra slots"
extra_slots:
range_expression:
range: integer
multivalued: true
maximum_cardinality: 5
AnyClass:
class_uri: linkml:Any
description: "The Any type implicitly allows any extra slots"
the generated pydantic looks like this (removed the meta declarations for simplicity's sake) class Base(ConfiguredBaseModel):
x: Optional[int] = Field(default=None)
class Other(ConfiguredBaseModel):
y: Optional[str] = Field(default=None)
class ExtraAllowed(Base):
model_config = ConfigDict(extra = "allow")
x: Optional[int] = Field(default=None)
class ExtraNotAllowed(Base):
model_config = ConfigDict(extra = "forbid")
x: Optional[int] = Field(default=None)
class ExtraString(Base):
"""
Only extra fields that are strings are valid
"""
__pydantic_extra__: dict[str, Annotated[str, Field(...)]]
model_config = ConfigDict(extra = "allow")
x: Optional[int] = Field(default=None)
class ExtraClass(Base):
"""
Only extra fields that match a class are valid
"""
__pydantic_extra__: dict[str, Annotated[Other, Field(...)]]
model_config = ConfigDict(extra = "allow")
x: Optional[int] = Field(default=None)
class ExtraAnyOf(Base):
"""
Union of allowed types
"""
__pydantic_extra__: dict[str, Annotated[Union[int, str], Field(...)]]
model_config = ConfigDict(extra = "allow")
x: Optional[int] = Field(default=None)
class ExtraCardinality(Base):
"""
Limit cardinality of multivalued extra slots
"""
__pydantic_extra__: dict[str, Annotated[list[int], Field(..., max_length=5)]]
model_config = ConfigDict(extra = "allow")
x: Optional[int] = Field(default=None) |
sneakers-the-rat
left a comment
There was a problem hiding this comment.
just reviewing the pydanticgen part, did not review pythongen part.
all of that looks good to me, my only requested changes are for the tests. For pydanticgen, i'm pretty sure that the test cases ported over from jsonschemagen in test_pydanticgen cover all the cases in test_extra_slots_per_class, so we might be able to just remove those, but someone else double check that.
- split test cases for python and pydanticgen and put them in their respective test modules, or put the new test module in
tests/test_generators/pythonto avoid adding new single-purpose test modules intest_generatorswhich is already large - want to avoid string comparison tests whenever possible when functional tests that use live objects are cheap enough to do (they are here, especially when the generation and module compilation is done in a module-scoped fixture and reused, see tests in
test_pydanticgen)
| def _extract_class_block(code: str, class_name: str) -> str: | ||
| """Return the source block for ``class_name`` up to the next top-level class.""" | ||
| marker = f"class {class_name}(" | ||
| start = code.index(marker) | ||
| rest = code[start + len(marker) :] | ||
| next_class = rest.find("\nclass ") | ||
| end = start + len(marker) + (next_class if next_class != -1 else len(rest)) | ||
| return code[start:end] |
There was a problem hiding this comment.
cheap enough and definitely more functionally airtight to just validate against real data and real classes, see added test cases
There was a problem hiding this comment.
split into pythongen and pydanticgen tests, put in test_pythongen and test_pydanticgen, or else put in the python subfolder - want to avoid one-off test modules in test_generators
| if isinstance(slot, AnonymousSlotExpression): | ||
| if not slot.required: | ||
| result.attribute.range = f"Optional[{result.attribute.range}]" | ||
| elif not (slot.required or slot.identifier or slot.key) and not slot.designates_type: |
There was a problem hiding this comment.
(self-commenting to explain, this is my code and not @noelmcloughlin 's so blame is with me):
somewhat awkward, the first leg is not and'ed because that should be "if we are an anonymous slot expression, make us optional if we are not required. otherwise if we are not an anonymous slot expression (and these other conditions) ... "
this method is way overloaded and should be split up, but not attempting here. easiest path to do the range_expression implementation by reusing most of the template and most of the logic in this method.
|
Thanks @sneakers-the-rat for the valuable review and additional commits. Let me know if this is urgent for you - will make time - otherwise I may be delayed returning to this PR. |
Silvanoc
left a comment
There was a problem hiding this comment.
Two minor points raised by an AI review (which I've confirmed myself).
| elif cls.extra_slots.range_expression: | ||
| result = self.generate_slot(cls.extra_slots.range_expression, cls) | ||
| return result.attribute | ||
| else: | ||
| return "allow" if cls.extra_slots.allowed else "forbid" |
There was a problem hiding this comment.
JSON-Schema generator checks first extra_slots.allowed and then extra_slots.range_expression. IMO they should apply the same logic, though it's unclear to me which is the "right" one.
There was a problem hiding this comment.
@Silvanoc is correct, my implementation was backwards.
|
@noelmcloughlin I could make good use of this fix. Could I help you moving forward on this? |
|
Sure - I will look this later today or tomorrow |
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
…cgen Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
…expression Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
sneakers-the-rat
left a comment
There was a problem hiding this comment.
I think the main question I have here is comprehension on my part, is the thing we need to handle with the changes re: ancestry knowing when we need to set an explicit __pydantic_extra__: dict[str, Any] when allow == True on models that are children and would otherwise inherit a more restrictive annotation? It seems like that too would need to be a general need for any OO generator that would need to be able to "open up" its parents constraints, so it seems like something that maybe should go on the schemaview, as we should not do too much schema introspection and ancestry reconstruction in a generator.
That's my only thought here with any weight, the rest are clarification questions, because i have gotten a little foggy on this. In general I think it's p much done, just nibbling around the edges.
| return slist | ||
|
|
||
| @staticmethod | ||
| def _extra_slots_allowed(cls: ClassDefinition) -> bool | AnonymousSlotExpression | None: |
There was a problem hiding this comment.
I don't really know why this needs to be a separate method, as a method name like this implies return type is a bool, "are they allowed or not," and i see the place where it's used is not really simplified by this, and ends up repeating the same conditions again. I think we can just do this there, and i think it can be as simple as
if cls.extra_slots.allowed is not None:
return cls.extra_slots.allowed
elif cls.extra_slots.range_expression:
return self.generate_slot(cls.extra_slots.range_expression, cls)
else:
return NoneThere was a problem hiding this comment.
ah i see this is pretty much what it was before. is the purpose here avoiding the extra line explicitly declaring __pydantic_extra__: dict[str, Any] whenever allow == True ?
There was a problem hiding this comment.
I thought I posted reply a few hours ago. I must have switch view or commented on wrong PR :-(
Agree name is misleading, renamed to _extra_slots_setting in f16dc34
No, it's separate because _get_extra_for_class is also used to read for every ancestor, to get metamodel value, not a generated slot.
Yes, __pydantic_extra__: dict[str, Any] line is only when ancestor types its extra values, because that's the only case where extra="allow" alone still inherits the parent's type. Otherwise Pydantic accepts extra values of any type like before
| if extra == "allow" and typed_ancestor: | ||
| # An ancestor's typed __pydantic_extra__ would still limit the extra values, | ||
| # so this class accepts values of any type, as an empty expression does. | ||
| return SlotResult( | ||
| attribute=PydanticAttribute(name="__anonymous__", range="Any", as_annotated=True), | ||
| source=AnonymousSlotExpression(), | ||
| ) | ||
| return extra |
There was a problem hiding this comment.
i don't think I understand this. if our ancestor has __pydantic_extra__ and we don't override it, we inherit it. If we override it, we should override it, but i don't know what this is doing - is this how we open things back up if our parent has an expression, but we have allowed: true? linkml doesn't have a strict monotonicity guarantee, but i have heard a lot of grumblings about how we probably should, and this would be a case where we would be violating it
There was a problem hiding this comment.
is this how we open things back up if our parent has an expression, but we have
allowed: true
Yes - the parents range_expression opened up for a child with allowed:true. I guess you are concerned that accepting values of any type violates monotonicity, for example slot-usage: LinkML schemas are monotonic. This means it’s not possible to override existing constraints, new constraints are always additive and “layered on”
As my PR comments mention, I mainly looked at jsonschemagen.py when doing this PR so influenced as I am not following every discussion.
jsonschemagen
Three places show jsonschemagen relaxing relaxing on its parent (like teenagers :-):
-
each class gets own
additionalproperties:
https://github.com/noelmcloughlin/linkml/blob/23d59b5cb076688df618f274c331ab30a7affe6e/packages/linkml/src/linkml/generators/jsonschemagen.py#L572 -
Only
cls.extra_slotsis read, never ancestor's:
https://github.com/noelmcloughlin/linkml/blob/23d59b5cb076688df618f274c331ab30a7affe6e/packages/linkml/src/linkml/generators/jsonschemagen.py#L1058-L1067 -
The parents
additionalPropertiesare never applied to the child
https://github.com/noelmcloughlin/linkml/blob/23d59b5cb076688df618f274c331ab30a7affe6e/packages/linkml/src/linkml/generators/jsonschemagen.py#L576-L577
pydanticgen
Pydantic classes inherit, so we need to override to prevent generated code drifting from the schema. Here is a reproducer trying to show that drift.
### /tmp/test_extra_override.py
from typing import Any
from pydantic import BaseModel, ConfigDict, ValidationError
# parent accepts only integers, child allowed: true.
class TypedParent(BaseModel):
__pydantic_extra__: dict[str, int]
model_config = ConfigDict(extra="allow")
class OpenChild(TypedParent):
model_config = ConfigDict(extra="allow")
class OpenChildOverride(TypedParent):
__pydantic_extra__: dict[str, Any]
model_config = ConfigDict(extra="allow")
# parent has allowed: true, child no extra_slots (default: forbid).
class OpenParent(BaseModel):
model_config = ConfigDict(extra="allow")
class DefaultChild(OpenParent):
pass
class DefaultChildOverride(OpenParent):
model_config = ConfigDict(extra="forbid")
for expect, classes in (
("\nparent accepts only integer extras, child has allowed: true, so child should accept x='a'",
(OpenChild, OpenChildOverride)),
("\nparent has allowed: true, child no extra_slots (forbid), so child should reject x='a'",
(DefaultChild, DefaultChildOverride)),
):
print(expect)
for cls in classes:
try:
cls(x="a")
print(" ", cls.__name__, "accepts x='a'")
except ValidationError:
print(" ", cls.__name__, "rejects x='a'")$ uv run python /tmp/test_extra_override.py
parent accepts only integer extras, child has allowed: true, so child should accept x='a'
OpenChild rejects x='a'
OpenChildOverride accepts x='a'
parent has allowed: true, child no extra_slots (forbid), so child should rejectx='a'
DefaultChild accepts x='a'
DefaultChildOverride rejects x='a'There was a problem hiding this comment.
For contrast jsonschemagen.py does walk class_ancestors to pick up ancestor's rules.
https://github.com/noelmcloughlin/linkml/blob/23d59b5cb076688df618f274c331ab30a7affe6e/packages/linkml/src/linkml/generators/jsonschemagen.py#L583-L585
but doesn't inherit extra_slots, matching the metamodel (see #4145 desc).
There was a problem hiding this comment.
So the metamodel doesn't require monotonicity, and schemas can relax, so this code makes pydanticgen.py match
There was a problem hiding this comment.
As aside, Mixins. Maybe the LinkML specification should discourage extra_slots: { allowed: true } on Mixins because it feels little strange, and implementations may ignore anyway. I recall raising Mixins in a Java PR comment, and it was agreed to ignore (cannot remember PR details, maybe unrelated to extra_slots)
There was a problem hiding this comment.
to be clear i am perfectly fine with non-monotonic schema, i am only bringing that up because i am aware it's important to others.
the behavior makes sense to me, thanks for the explanation. I think that this is evidence that we need to make changes to how extra_slots is handled in schemaview, it should be propagated and merged to children in the same way across generators. i assume this is what you did in schemaview changes, haven't looked yet. I think the thing you did where you only do it when the child overrides is probably the best for the output, normally we don't need to do that, avoid cluttering very class with allow:true with a redundant __pydantic_extra__ unless it needs it.
| elif isinstance(element, AnonymousSlotExpression): | ||
| # the same ranges for an expression, such as the range_expression of extra_slots, | ||
| # which SchemaView.slot_range_as_union does not accept | ||
| expressions = [element, *element.exactly_one_of, *element.any_of] | ||
| needed_classes.extend([e.range for e in expressions if e.range in all_classes]) |
There was a problem hiding this comment.
can i get a little explanation here? it seems like this is something that should go in the schemaview as well, and if it doesn't accept it, then it should? it seems like this would be a more general need than just for pydanticgen.
There was a problem hiding this comment.
Done. It touches schemaview lightly (but Core team are reviewers). It feels cleaner.
As per docstring, Schemaview's slot_range_as_union refuses an AnonymousSlotExpression because isinstance(slot, SlotDefinition) is too narrow - so we are fixing that here
| elif cls.extra_slots.range_expression: | ||
| result = self.generate_slot(cls.extra_slots.range_expression, cls) | ||
| return result.attribute | ||
| else: | ||
| return "allow" if cls.extra_slots.allowed else "forbid" |
There was a problem hiding this comment.
@Silvanoc is correct, my implementation was backwards.
I think we just sort of have to do the removal! the deprecation warning should only be emitted during tests by default (and the linkml tests are already ridiculously noisy, so it's fine if we eat our own deprecation warnings)
this sounds like a pydantic bug to me - link to the reproducer you're referring to? |
@noelmcloughlin that's perfectly fine for me, since I'm currently only interested in the Pydantic part for the OpenAPI generator 😄 |
…tting Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
…tic_extra Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
6e6e3ca to
7ca4ac1
Compare
…s_union Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
The bug is on this PR (either my code, or symptom of changes). I was wondering whether to fix now or leave until afterwards so that is why I did not address yet. # # /tmp/extra_pattern.yaml
id: https://example.org/extra_pattern
name: extra_pattern
imports:
- linkml:types
default_range: string
classes:
Tagged:
attributes:
x:
range: integer
extra_slots:
range_expression:
range: string
pattern: "^[a-z]+$"REPL |
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Thanks. The tests fully cover your examples now |
|
Should I fix
# # /tmp/extra_pattern.yaml
id: https://example.org/extra_pattern
name: extra_pattern
imports:
- linkml:types
default_range: string
classes:
Tagged:
attributes:
x:
range: integer
extra_slots:
range_expression:
range: string
pattern: "^[a-z]+$" |
@noelmcloughlin This PR is only partially covering Even better would be to have (additional to the documentation) full |
Silvanoc
left a comment
There was a problem hiding this comment.
No critical issues, but a couple of things that IMO should get fixed before merging.
| deprecated_in=SemVer.from_str("1.11.1"), | ||
| removed_in=SemVer.from_str("1.13.0"), |
There was a problem hiding this comment.
These versions should be bumped up.
| type=click.Choice(["allow", "ignore", "forbid"], case_sensitive=False), | ||
| default="forbid", |
There was a problem hiding this comment.
This default will trigger the warning on direct linkml generate pydantic call, no matter how the CLI call looks like. None is needed as default. Same issue appears in cli declaration below.
There was a problem hiding this comment.
This default will trigger the warning on direct linkml generate pydantic call, no matter how the CLI call looks like. None needed as default. Same applies to the CLI option --extra-fields?.
| + Import( | ||
| module="typing", | ||
| objects=[ | ||
| ObjectImport(name="Annotated"), |
There was a problem hiding this comment.
Import only needed when as_annotated == True, right? It shouldn't be added unconditionally.
| default_name: ClassVar[str] = "ConfiguredBaseModel" | ||
| name: str = Field(default_factory=lambda: PydanticBaseModel.default_name) | ||
| extra_fields: Literal["allow", "forbid", "ignore"] = "forbid" | ||
| extra_fields: Literal["allow", "forbid", "ignore"] | None = "forbid" |
There was a problem hiding this comment.
Is it on purpose that there is no direct equivalent for extra_fields="ignore" with extra_slots?
There was a problem hiding this comment.
I had to research this and answer is on purpose afaik. #2241 lays them out side by side but JSON shape was implemented (linkml/linkml-model#205). I was wondering if "ignore" should be added to Metamodel but it has no value is what I learned.
extra_slots says whether extra data makes an instance invalid, and both ignore and allow accept extra data. Uniquely Pydantic can choose to load extra or throw away (ignore), JSON/Shacl only allow or reject.
From #2241 side by side
JSON Schema allows additionalProperties to be
false - no extra values allowed
true - any extra values allowed
object - extra values that validate against that schema
Pydantic allows ConfigDict(allow=) to be
forbid - raise a validation error on additional values
ignore - silently drop extra values
allow - default allow any extra values, optionally validating against __pydantic_extra__ if present
I presume you are asking because of extra_fields depreciation. We could keep extra_fields as a generator wide default for classes without extra_slots if you see a problem.
A schema class without extra_slots will "forbid all additional data" and this defines what conforming data is, but extra_fields would allow a person to relax that default for their own model. Maybe its an older model reading newer data, a vendored model they don't own. extra fields is a declared non-conformance by the user, but the generators maintainers still control this (Pydantic extra=ignore).
Anyway, other generators handle open or closed classes with their own options: json --not-closed and shacl has --closed/--non-closed. So gen-pydantic's extra_fields is the same kind of setting. I could add support via #3972
I'm not sure this PR should depreciate....
- pydantic_validation_plugin.py has "closed=false" and closed=self.closed
- validation_context.py maps extra_fields="forbid" if closed else "ignore" if closed is None else "allow".
- sqlalchemygen.py: PydanticGenerator(self.original_schema, extra_fields="allow", gen_mixin_inheritance=False)
- openapigen.py:561: PydanticGenerator(materialized_schema, extra_fields="allow").compile_module()
There was a problem hiding this comment.
Maybe renaming extra_fields to extra_slots is another option, see linkml/linkml-model#261 (comment)
I believe @sneakers-the-rat is okay with fixing gaps in this PR. I will revisit tomorrow or Wednesday, as self-contained commits. |
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
94c6612 to
0e29537
Compare
# Conflicts: # packages/linkml/src/linkml/utils/deprecation.py
Signed-off-by: noelmcloughlin <noel.mcloughlin@gmail.com>
Summary
Fixes pydanticgen part of #3629
cls.extra_slots.allowedand emits per-class behavior that matches schemaAnonymousSlotExpressionHow was this tested?
Added unit tests
Areas of uncertainty
Checklist
AI Assistance
LLM assisted