Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(auto): cover the review findings on the dump fix
- An excluded value pydantic cannot serialize stays out instead of
  aborting evaluate().
- Excluded fields are compared inside dicts and nested lists, and on a
  StructuredModel (keeping its own key spelling).
- A field serializer, model_serializer or RootModel keeps pydantic's
  output.
- A model-holding field is left out of the parent dump rather than
  serialized twice.
- The exclude_if test skips on a pydantic without it.
  • Loading branch information
sromoam committed Oct 6, 2026
commit cbd3aa0f99c541ff2fd2121f797583ec40bda63d
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ Each release links to full notes on the
that the inferred model never read, and a `Field(exclude=True)` (or
`exclude_if`) field was left out of the dump. Either way the field was blank
on both sides, so a wrong value scored `1.0`, and a required field raised
`ValidationError`. Instances now dump by field name, and excluded fields are
compared. A `StructuredModel` keeps its own dump
`ValidationError`. Plain models now dump by field name (a `StructuredModel`
keeps its own key spelling), and excluded fields are compared at any depth
([#378](https://github.com/awslabs/stickler/issues/378),
[#379](https://github.com/awslabs/stickler/issues/379))

Expand Down
23 changes: 15 additions & 8 deletions src/stickler/auto/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,14 +139,21 @@ affect scores. Both `model_dump()` (native `date`/`Decimal`/`set` objects) and
`model_dump(mode="json")` (already-serialized) validate and score identically,
so `Model.from_json(instance.model_dump())` is safe either way.

`evaluate()` dumps by field name (`by_alias=False`), because the shadow model
reads field names, and it compares fields the dump would leave out
(`exclude=True`, `exclude_if`). A field the shadow model cannot read is blank on
both sides, and blank against blank scores as a match
([#378](https://github.com/awslabs/stickler/issues/378),
[#379](https://github.com/awslabs/stickler/issues/379)). A `StructuredModel`
keeps its own dump, since it validates through its own config. Field serializers
still apply to scalar fields, but not to a field holding a model.
A field the shadow model cannot read is blank on both sides, and blank against
blank scores as a match, so `evaluate()` makes sure every field arrives:

- A plain model dumps by field name (`by_alias=False`), because the shadow
model reads field names
([#378](https://github.com/awslabs/stickler/issues/378)). A `StructuredModel`
and everything under it keep their own key spelling, since they validate
through their own config.
- A field the dump leaves out (`exclude=True`, `exclude_if`) is rebuilt from the
attribute and compared, at any depth, including inside dicts and lists
([#379](https://github.com/awslabs/stickler/issues/379)). The rebuilt value
takes `pydantic_core`'s default JSON form, so `ser_json_*` config does not
apply to it. An excluded value pydantic cannot serialize stays out.
- A field with its own serializer, a model with a `model_serializer`, and a
`RootModel` keep pydantic's output as is.

`dict` is the exception, and deliberately so. It keeps its shape rather than
being flattened to a string, because ANLS\* scores it structurally and cannot do
Expand Down
94 changes: 71 additions & 23 deletions src/stickler/auto/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@

from __future__ import annotations

import json
from typing import Any, Dict, List, Optional, Type, Union

from pydantic import BaseModel
from pydantic_core import to_jsonable_python
from pydantic import BaseModel, PlainSerializer, RootModel, WrapSerializer
from pydantic_core import PydanticSerializationError, to_jsonable_python

from ..structured_object_evaluator.models.structured_model import StructuredModel
from .builder import specs_for, structured_model_for
Expand Down Expand Up @@ -330,36 +331,83 @@ def _dump(instance: BaseModel) -> Dict[str, Any]:
return _wire(instance)


def _wire(value: Any) -> Any:
"""Dump ``value`` keyed by field name, keeping every declared field.
def _wire(value: Any, own_keys: bool = False) -> Any:
"""Dump ``value`` in JSON form, keeping every declared field.

A ``StructuredModel`` validates back through its own class, so its own dump
round-trips. A plain model feeds a shadow model, which reads field names,
so ``by_alias=False`` overrides ``serialize_by_alias=True`` (#378). A field
the dump leaves out (``exclude=True``, ``exclude_if``) is still compared,
so it is rebuilt from the attribute rather than read as blank (#379). So
is any field holding a model, since a nested model can drop fields too.
A field the dump leaves out (``exclude=True``, ``exclude_if``) is blank on
both sides, and blank against blank scores as a match, so it is rebuilt
from the attribute (#379). So is a field holding a model, since a nested
model can drop fields too; that field is left out of the parent's dump
rather than serialized twice.

Keys: a plain model feeds a shadow model, which reads field names, so it
dumps with ``by_alias=False`` (#378). A ``StructuredModel`` validates
through its own classes, so it and everything under it (``own_keys``)
keep their own config's key spelling.

A field with its own serializer, a model with a ``model_serializer`` and a
``RootModel`` keep pydantic's output: the author chose that wire form.
"""
if isinstance(value, StructuredModel):
return value.model_dump(mode="json")
if isinstance(value, BaseModel):
out = value.model_dump(mode="json", by_alias=False)
for name in type(value).model_fields:
raw = getattr(value, name)
if name not in out or _holds_model(raw):
out[name] = _wire(raw)
own_keys = own_keys or isinstance(value, StructuredModel)

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.

#378 is still open for any StructuredModel that uses serialization_alias. Keys under a StructuredModel are kept as dumped because it "validates through its own config". Pydantic validation reads alias/validation_alias, not serialization_alias, so those keys are never read back. Measured on this branch: class SM3(StructuredModel): model_config = ConfigDict(serialize_by_alias=True); code: str = Field("", serialization_alias="Code"); other: str = "", then evaluate(SM3(code="A", other="q"), SM3(code="BBBB", other="q")) gives field_scores={'code': 1.0, ...}. compare_with() scores code 0.0. A plain model nested under a StructuredModel has the same problem (wrong Inner.code scores sm: 1.0). Fix: rename a key to the field's validation key (alias or name) whenever dumped_key differs from it, not only when own_keys is false.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, thanks. Under a StructuredModel the key is now the one validation reads: an alias stays, and a serialization_alias becomes the field name. SM3 scores code 0.0 in both readers, and the nested plain case drops below 1.0. See test_a_serialization_alias_is_read_back.

dump_kwargs = {} if own_keys else {"by_alias": False}
cls = type(value)
if (
isinstance(value, RootModel)
or cls.__pydantic_decorators__.model_serializers
):
return value.model_dump(mode="json", **dump_kwargs)
rebuild = {
name
for name, field in cls.model_fields.items()
if _holds_model(getattr(value, name))
and not _has_field_serializer(cls, name, field)
}
out = value.model_dump(mode="json", exclude=rebuild or None, **dump_kwargs)
by_alias = own_keys and bool(cls.model_config.get("serialize_by_alias"))
for name, field in cls.model_fields.items():
key = (
(field.serialization_alias or field.alias or name) if by_alias else name
)
if name in rebuild:

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.

Medium: excluded model-holding fields abort instead of staying out. A field that is both exclude=True (or exclude_if) and holds a model is in rebuild. This branch calls _wire with no try/except PydanticSerializationError, unlike the elif branch below. The PR description says "An excluded value that pydantic cannot serialize stays out, as before, instead of aborting". That holds only for non-model values.

Reproduction (dev returns 1.0, this branch raises PydanticSerializationError: Unable to serialize unknown type: <class 'Handle'>):

class Handle: pass
class Inner(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    h: Handle
class Doc(BaseModel):
    name: str
    meta: Optional[Inner] = Field(default=None, exclude=True)
d = Doc(name="a", meta=Inner(h=Handle()))
stickler.evaluate(d, d)

Fix: apply the same guard when name in rebuild and the field was excluded from the original dump, for example by checking field.exclude/exclude_if, or by wrapping both branches in the same try. Add a test next to the existing unserializable-excluded-field test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. 8b6bcdd dropped the rebuild branch: an excluded field is now dumped through a TypeAdapter for its annotation, and in 10c60a0 any error from that dump leaves the field out, as on dev. Your Handle repro scores 1.0, and it's pinned in test_an_excluded_unserializable_model_stays_out.

out[key] = _wire(getattr(value, name), own_keys)
elif key not in out:

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.

Medium: StructuredModel.extra_fields is now dumped and re-ingested as an extra field. StructuredModel declares extra_fields: Dict[str, Any] = Field(default_factory=dict, exclude=True) (structured_model.py:549). That field is in model_fields and absent from the dump, so this branch adds it under the key extra_fields. ConfigurationHelper.from_json then treats that key as an undeclared field and stores it inside the new instance's extra_fields.

Measured on this branch with a passthrough StructuredModel:

a = SM.from_json({"name": "x", "zzz": 1})
_dump(a)                      # {'name': 'x', 'zzz': 1, 'extra_fields': {'zzz': 1}}
SM.from_json(_dump(a)).extra_fields  # {'extra_fields': {'zzz': 1}, 'zzz': 1}

The same happens for a StructuredModel nested in a plain model. Scores do not change, because comparison skips extra_fields. The ground_truth/prediction instances on EvalResult and their __stickler_raw_json__ now carry the extra extra_fields key, and each re-dump nests it one more level. Fix: skip extra_fields when the model is a StructuredModel, matching how structured_model.py, confusion_matrix_calculator.py and structured_list_comparator.py already skip it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thanks. Fixed in 10c60a0: the walk skips extra_fields on a StructuredModel, the same way the comparison engine does. test_structured_model_extra_fields_are_not_dumped covers the passthrough case, the nested case, and a from_json(_dump(a)) round trip that keeps extra_fields == {"zzz": 1}.

try:
out[key] = _wire(getattr(value, name), own_keys)
except PydanticSerializationError:
# A type pydantic cannot serialize could not be compared
# anyway; excluding it is how such fields are usually kept
# out of a dump, so leave it out rather than abort.
pass
return out
if isinstance(value, (list, tuple)) and _holds_model(value):
return [_wire(item) for item in value]
return to_jsonable_python(value, by_alias=False)
if not _holds_model(value):
return to_jsonable_python(value)
if isinstance(value, dict):
return {_json_key(k): _wire(v, own_keys) for k, v in value.items()}
return [_wire(item, own_keys) for item in value]


def _holds_model(value: Any) -> bool:
if isinstance(value, BaseModel):
return True
return isinstance(value, (list, tuple)) and any(
isinstance(item, BaseModel) for item in value
)
if isinstance(value, dict):
return any(_holds_model(v) for v in value.values())
if isinstance(value, (list, tuple)):
return any(_holds_model(item) for item in value)
return False


def _has_field_serializer(cls: Type[BaseModel], name: str, field: Any) -> bool:
decorators = cls.__pydantic_decorators__.field_serializers.values()
return any(
name in d.info.fields or "*" in d.info.fields for d in decorators
) or any(isinstance(m, (PlainSerializer, WrapSerializer)) for m in field.metadata)


def _json_key(key: Any) -> str:
"""Spell a mapping key the way ``model_dump(mode="json")`` does."""
key = to_jsonable_python(key)
return key if isinstance(key, str) else json.dumps(key)


def _shared_class(gt: BaseModel, pred: BaseModel) -> Type[BaseModel]:
Expand Down
57 changes: 56 additions & 1 deletion tests/auto/test_risk_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
"""

import datetime
import inspect
from enum import Enum, IntEnum
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union

import pytest
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, field_serializer
from pydantic.alias_generators import to_camel

import stickler
Expand Down Expand Up @@ -392,6 +393,60 @@ class Outer(BaseModel):
assert r.field_scores["inner"] < 1.0
assert r.field_scores["items"] < 1.0

def test_excluded_field_in_a_dict_or_nested_list_is_compared(self):
class Inner(BaseModel):
total: Optional[float] = Field(default=None, exclude=True)

class Outer(BaseModel):
by_key: Dict[str, Inner] = {}
rows: List[List[Inner]] = []

gt = Outer(by_key={"a": Inner(total=1.0)}, rows=[[Inner(total=1.0)]])
pred = Outer(by_key={"a": Inner(total=99.0)}, rows=[[Inner(total=99.0)]])
r = stickler.evaluate(gt, pred)
assert r.field_scores["by_key"] < 1.0
assert r.field_scores["rows"] < 1.0

def test_excluded_field_on_a_structured_model_is_compared(self):
class S(StructuredModel):
name: str = ComparableField()
total: Optional[float] = Field(default=None, exclude=True)

r = stickler.evaluate(S(name="a", total=1.0), S(name="a", total=99.0))
assert r.overall_score < 1.0

def test_unserializable_excluded_field_does_not_abort(self):
class Blob:
pass

class M(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str
raw: Optional[Blob] = Field(default=None, exclude=True)

r = stickler.evaluate(M(name="a", raw=Blob()), M(name="a", raw=Blob()))
assert r.field_scores["name"] == pytest.approx(1.0)

def test_field_serializer_on_a_model_field_is_kept(self):
class Inner(BaseModel):
name: str

class Outer(BaseModel):
inner: Inner

@field_serializer("inner")
def _redact(self, inner):
return {"name": "redacted"}

r = stickler.evaluate(
Outer(inner=Inner(name="abc")), Outer(inner=Inner(name="xyz"))
)
assert r.overall_score == pytest.approx(1.0)

@pytest.mark.skipif(
"exclude_if" not in inspect.signature(Field).parameters,
reason="Field(exclude_if=) needs a newer pydantic",
)
def test_exclude_if_field_is_compared(self):
class M(BaseModel):
note: Optional[str] = Field(
Expand Down
Loading