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): close the remaining dump-restore gaps from review
- Re-key into a fresh dict, so one field's alias that is another field's
  name no longer overwrites it.
- Skip StructuredModel.extra_fields, which was dumped and re-ingested as
  an extra field (vawsgit).
- An excluded value that fails to dump for any reason stays out, as it
  did before #379, instead of aborting evaluate().
- Excluded fields carry the parent's ser_json_* settings.
- Do not walk anything a serializer produced, including one nested in
  Optional/Union, or refill an excluded field's own serializer output.
- Walk sets, frozensets and deques.
- Skip fields whose annotation cannot hold a model.
- Cache per-class plans and adapters in WeakKeyDictionaries so runtime
  classes can be collected; fold _wire into _dump.
  • Loading branch information
sromoam committed Oct 9, 2026
commit 10c60a0e056dfd11148e088c2236e382f1a72a0a
16 changes: 9 additions & 7 deletions src/stickler/auto/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,16 @@ fixes two things:
and everything under it keep their keys, since they validate through their
own config.
- A field marked `exclude=True` or `exclude_if` is dumped from its annotation and
added back, at any depth
added back, at any depth, including inside lists, sets and dicts
([#379](https://github.com/awslabs/stickler/issues/379)). Annotated
serializers apply to it; a `@field_serializer` does not. One pydantic cannot
serialize stays out.

The walk stops where the dump no longer has the instance's shape (a
`RootModel`, a `model_serializer`, a field serializer), and that output is kept
as is.
serializers and the parent's `ser_json_*` settings apply to it; a
`@field_serializer` does not. One that fails to dump stays out, as before.
`StructuredModel.extra_fields` is the engine's own and is never added.

The walk does not enter a `RootModel`, a `model_serializer`, anything a
serializer produced, or a container whose length changed, since that output no
longer lines up with the instance; it is kept as is. A field whose annotation
cannot hold a model (`List[float]`) is not walked at all.

`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
208 changes: 157 additions & 51 deletions src/stickler/auto/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,34 @@

from __future__ import annotations

import functools
from typing import Annotated, Any, Dict, List, Optional, Tuple, Type, Union
import collections
import weakref
from typing import (
Annotated,
Any,
Dict,
ForwardRef,
List,
Literal,
NamedTuple,
Optional,
Tuple,
Type,
TypeVar,
Union,
get_args,
get_origin,
)

from pydantic import (
BaseModel,
ConfigDict,
PlainSerializer,
PydanticUserError,
RootModel,
TypeAdapter,
WrapSerializer,
)
from pydantic_core import PydanticSerializationError

from ..structured_object_evaluator.models.structured_model import StructuredModel
from .builder import specs_for, structured_model_for
Expand Down Expand Up @@ -325,27 +341,19 @@ class (or a compatible superset, so extra/missing fields are tolerated). The


def _dump(instance: BaseModel) -> Dict[str, Any]:
"""Normalize a pydantic instance to its JSON wire form.
"""Normalize a pydantic instance to the JSON wire form the shadow model reads.

``mode="json"`` is required: it turns ``date``/``datetime`` into ISO
strings and enums into their values, matching the wire types the inferred
comparators expect.
comparators expect. Pydantic's own dump is kept, so serializers and
``ser_json_*`` config apply as usual; :func:`_restore` then corrects the
two ways a field fails to arrive. A field that does not arrive is blank on
both sides, and blank against blank scores as a match.
"""
if not isinstance(instance, BaseModel):
raise TypeError(
f"expected a pydantic BaseModel instance, got {type(instance)!r}"
)
return _wire(instance)


def _wire(instance: BaseModel) -> Any:
"""Pydantic's own JSON dump, corrected where the shadow model cannot read it.

The dump is kept as pydantic produced it, so serializers and ``ser_json_*``
config apply as usual. :func:`_restore` then walks it beside the instance
and fixes the two ways a field goes missing. A missing field is blank on
both sides, and blank against blank scores as a match.
"""
return _restore(instance, instance.model_dump(mode="json"), own_keys=False)

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.

Optional (efficiency): _restore rebuilds every dict and list in each dump in Python, on every EvalSpec.evaluate() call. The EvalSpec docstring calls that the efficient path for a dataset. Because _may_hold_model returns True for Any and for Dict[str, Any], a large JSON payload field is copied in full twice per pair even when nothing needs renaming. When a class's plan has no alias rename and no excluded entry (precompute that once per class), return the pydantic dump unchanged.

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.

Done. Whether a class's dump needs any changes is now decided once per class, and if it doesn't, pydantic's dump is returned as is. The walk also no longer copies anything it leaves alone. A typed nested model goes from about 73µs to 12µs per _dump, roughly the cost of model_dump alone. Any fields are still walked, since they can hold a model.



Expand All @@ -357,32 +365,38 @@ def _restore(value: Any, dumped: Any, own_keys: bool) -> Any:
``StructuredModel`` validates through its own classes, so it and
everything under it (``own_keys``) keep their keys.
- A field marked ``exclude=True`` or ``exclude_if`` is dumped from its
annotation and added back (#379). One pydantic cannot serialize stays out.
annotation and added back (#379). One that fails to dump stays out.

The walk stops wherever the dump no longer has the instance's shape: a
``RootModel``, a ``model_serializer``, a field serializer, or a container
whose length changed. That output is the author's choice and is kept.
The walk does not enter a ``RootModel``, a ``model_serializer``, anything a
serializer produced, or a container whose length changed: that output is
the author's choice, and its shape no longer lines up with the instance.
"""
if isinstance(value, BaseModel):
cls = type(value)
if not isinstance(dumped, dict) or _is_opaque(cls):

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.

Blocker (new regression): with a custom serializer, evaluate() reports false alarms on identical documents.

_restore does not walk the dump when the class has a wrap model_serializer (this line) or the field has a serializer (line 419). In those cases the key of a nested model that was left out survives.

class Lead(BaseModel):
    answer: str = 'a'
    trace: Trace = Trace()   # Trace as in the builder.py:394 comment
    @model_serializer(mode='wrap')
    def ser(self, handler): return handler(self)

evaluate(d, d) gives tp 1, fa 1, precision 0.5. Dev gives tp 2, fa 0, precision 1.0. Through eval_for(), the Strands Evals 1.6.0 test_pass flips from True to False.

return dumped
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.

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.

Blocker (new regression): excluded secrets are scored and published in non_matches.

own_keys keeps propagating below a StructuredModel's own ComparableFields. Excluded values are then refilled and scored on plain models under a StructuredModel, and on StructuredModels inside a plain model's Union/Any/Dict field.

  • Acct2(StructuredModel).cred: Optional[Cred2] with Cred2.token: Optional[str] = Field(None, exclude=True): running evaluate() with differing users puts 'SECRET-GT' in non_matches. Dev does not.
  • Plain M2 with u: Union[S, B], anyv: Any, ds: Dict[str, S], where only the excluded S.secret differs: head scores u 0.0, anyv 0.0, ds 0.818 and publishes both secrets. Dev scores 1.0 and publishes neither.

auto/README.md:170 says "On a plain model nothing is added back". Stop the propagation at the plain-model boundary.

out = dict(dumped)
for name, dumped_key, excluded, serialized in _field_plan(cls):
raw = getattr(value, name, _MISSING)
plan = _field_plan(cls)
# A fresh dict: renaming in place would let one field's alias that is
# another field's name overwrite it.
field_keys = {entry.dumped_key for entry in plan}
out = {k: v for k, v in dumped.items() if k not in field_keys}
for entry in plan:
raw = getattr(value, entry.name, _MISSING)
if raw is _MISSING:
continue # model_construct without it; validation reports it
key = dumped_key if own_keys else name
if dumped_key in out:
item = out.pop(dumped_key)
out[key] = item if serialized else _restore(raw, item, own_keys)
elif excluded:
item = _dump_excluded(cls, name, raw, own_keys)
key = entry.dumped_key if own_keys else entry.name
if entry.dumped_key in dumped:
item = dumped[entry.dumped_key]
if entry.descend and not entry.serialized:
item = _restore(raw, item, own_keys)
out[key] = item

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.

Blocker: a non-firing exclude_if field becomes a false alarm. _restore copies any key present in the dump, including a plain-model field that is_excluded() removed from the shadow model. When exclude_if does not fire, the value is in the dump, the shadow StructuredModel (extra="allow") stores it in __pydantic_extra__, and _count_extra_fields_as_false_alarms counts it as a hallucinated field.

Measured on this branch (/tmp/stickler-pr380/src): class P(BaseModel): a: str; meta: Dict[str,str] = Field(default_factory=dict, exclude_if=lambda v: not v), then evaluate(P(a="x", meta={"k":"v"}), P(a="x", meta={"k":"v"})) gives precision=0.5, f1=0.667 for two identical instances. On dev the same field was scored. Fix: when not own_keys and entry.excluded, skip the entry and do not copy dumped[entry.dumped_key] into out.

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.

Thanks, good catch. Fixed in cbd8c4b: exclude_if is now decided per value, so the field stays declared in the inferred model and a kept value is never an extra. Your repro now gives precision 1.0, pinned in test_a_kept_value_is_not_a_false_alarm.

elif entry.excluded:
item = _dump_excluded(cls, entry, raw, own_keys)
if item is not _MISSING:
out[key] = item
return out
if isinstance(value, (list, tuple)) and isinstance(dumped, list):
if isinstance(value, _SEQUENCES) and isinstance(dumped, list):
if len(value) == len(dumped):
return [_restore(v, d, own_keys) for v, d in zip(value, dumped)]
elif isinstance(value, dict) and isinstance(dumped, dict):
Expand All @@ -396,59 +410,151 @@ def _restore(value: Any, dumped: Any, own_keys: bool) -> Any:

_MISSING: Any = object()

# Pydantic dumps each of these as a list in iteration order, so the dump lines
# up with the instance element by element.
_SEQUENCES = (list, tuple, set, frozenset, collections.deque)


class _FieldPlan(NamedTuple):
name: str
dumped_key: str # the key pydantic's default dump writes
excluded: bool # exclude=True or exclude_if
serialized: bool # a serializer anywhere on the field
descend: bool # the annotation can hold a model, so the walk enters it


# Keyed weakly, so classes built at runtime (create_model, model_from_json) can
# still be collected after they are evaluated.
_PLANS: "weakref.WeakKeyDictionary[type, Tuple[_FieldPlan, ...]]" = (
weakref.WeakKeyDictionary()
)
_ADAPTERS: "weakref.WeakKeyDictionary[type, Dict[str, Optional[TypeAdapter]]]" = (
weakref.WeakKeyDictionary()
)


def _is_opaque(cls: Type[BaseModel]) -> bool:
return issubclass(cls, RootModel) or bool(
cls.__pydantic_decorators__.model_serializers
)


@functools.lru_cache(maxsize=None)
def _field_plan(cls: Type[BaseModel]) -> Tuple[Tuple[str, str, bool, bool], ...]:
"""Per field: name, key in the default dump, excluded, own serializer."""
def _field_plan(cls: Type[BaseModel]) -> Tuple[_FieldPlan, ...]:
plan = _PLANS.get(cls)
if plan is None:
plan = _PLANS[cls] = _build_field_plan(cls)
return plan


def _build_field_plan(cls: Type[BaseModel]) -> Tuple[_FieldPlan, ...]:
by_alias = bool(cls.model_config.get("serialize_by_alias"))
serializers = cls.__pydantic_decorators__.field_serializers.values()
decorators = cls.__pydantic_decorators__.field_serializers.values()
plan = []
for name, field in cls.model_fields.items():
if name == "extra_fields" and issubclass(cls, StructuredModel):
continue # the engine's own bookkeeping, excluded on purpose
dumped_key = (
(field.serialization_alias or field.alias or name) if by_alias else name
)
excluded = bool(field.exclude) or getattr(field, "exclude_if", None) is not None
serialized = any(
name in d.info.fields or "*" in d.info.fields for d in serializers
) or any(
isinstance(m, (PlainSerializer, WrapSerializer)) for m in field.metadata
serialized = (
any(name in d.info.fields or "*" in d.info.fields for d in decorators)
or any(_is_serializer(m) for m in field.metadata)
or _has_serializer(field.annotation)
)
plan.append(
_FieldPlan(
name=name,
dumped_key=dumped_key,
excluded=bool(field.exclude)
or getattr(field, "exclude_if", None) is not None,
serialized=serialized,
descend=_may_hold_model(field.annotation),
)
)
plan.append((name, dumped_key, excluded, serialized))
return tuple(plan)


def _dump_excluded(cls: Type[BaseModel], name: str, raw: Any, own_keys: bool) -> Any:
adapter = _field_adapter(cls, name)
def _is_serializer(meta: Any) -> bool:
return isinstance(meta, (PlainSerializer, WrapSerializer))


def _has_serializer(annotation: Any) -> bool:
"""Whether an ``Annotated`` serializer sits anywhere inside ``annotation``."""
if get_origin(annotation) is Literal:
return False
args = get_args(annotation)
if get_origin(annotation) is Annotated:
return any(_is_serializer(m) for m in args[1:]) or _has_serializer(args[0])
return any(_has_serializer(arg) for arg in args)


def _may_hold_model(annotation: Any) -> bool:
"""Whether a value of ``annotation`` can contain a pydantic model."""
if annotation is Any or annotation is object:
return True
if isinstance(annotation, type):
return issubclass(annotation, BaseModel)
if isinstance(annotation, (TypeVar, ForwardRef, str)):
return True # unresolved: assume it can
origin = get_origin(annotation)
if origin is Literal:
return False
args = get_args(annotation)
if origin is Annotated:
return _may_hold_model(args[0])
return any(_may_hold_model(arg) for arg in args if arg is not Ellipsis)


def _dump_excluded(
cls: Type[BaseModel], entry: _FieldPlan, raw: Any, own_keys: bool
) -> Any:
adapter = _field_adapter(cls, entry.name)
if adapter is None:
return _MISSING
try:
dumped = adapter.dump_python(raw, mode="json")
except PydanticSerializationError:
except Exception:
# Before #379 this field never reached the dump at all, so a value that
# cannot be dumped (an arbitrary type, undecodable bytes, a raising
# serializer) is left out as it always was, rather than aborting.
return _MISSING
Comment on lines +665 to +673

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.

Two notes on this branch, neither blocking.

A bare except Exception around the dump keeps a field out when its own serializer raises, which matches the pre-#379 behaviour and is the right default. It also swallows a programming error in that serializer, and the field then silently returns to scoring a false 1.0 with nothing to diagnose from. A narrower catch, or re-raising anything that is not a serialization failure, would keep the fallback without hiding bugs.

Annotated serializers on an excluded field now execute. Measured on a PlainSerializer over an excluded field: 0 calls per evaluate() at the merge base, 2 at this head. Harmless for a pure function, visible for one with side effects, so it is worth stating as part of the new contract.

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.

Narrowed in ec3cf4b to (PydanticSerializationError, ValueError). It can't separate a serializer bug from an unserializable value, because pydantic wraps whatever a serializer raises in PydanticSerializationError (Error calling function ...). Leaving the field out is what happened before #379, when the serializer never ran. The comment says so, and test_a_raising_serializer_on_an_excluded_field_leaves_it_out pins it. Serializers on excluded fields now run only inside a StructuredModel; that's in the README.

return _restore(raw, dumped, own_keys)
if entry.descend and not entry.serialized:
return _restore(raw, dumped, own_keys)
return dumped


@functools.lru_cache(maxsize=None)
def _field_adapter(cls: Type[BaseModel], name: str) -> Optional[TypeAdapter]:
adapters = _ADAPTERS.get(cls)
if adapters is None:
adapters = _ADAPTERS[cls] = {}
if name not in adapters:
adapters[name] = _build_field_adapter(cls, name)
return adapters[name]


def _build_field_adapter(cls: Type[BaseModel], name: str) -> Optional[TypeAdapter]:
"""A serializer for one field's annotation, ignoring its ``exclude``.

Annotated serializers come along in ``metadata``; a ``@field_serializer``
does not, since it belongs to the class.
Annotated serializers come along in ``metadata`` and the parent's
``ser_json_*`` settings are carried over; a ``@field_serializer`` does not
come along, since it belongs to the class.
"""
field = cls.model_fields[name]
annotation = field.annotation
if field.metadata:
annotation = Annotated[(annotation, *field.metadata)]
try:
return TypeAdapter(annotation)
except PydanticUserError:
return None # e.g. an arbitrary type: it could not be compared anyway
ser_config = {
k: v for k, v in cls.model_config.items() if k.startswith("ser_json_")
}
attempts = [ConfigDict(**ser_config), None] if ser_config else [None]
for config in attempts:
try:
return TypeAdapter(annotation, config=config)
except PydanticUserError:
# `config` is refused when the annotation is itself a model (which
# brings its own); an arbitrary type cannot be dumped at all.
continue
return None


def _shared_class(gt: BaseModel, pred: BaseModel) -> Type[BaseModel]:
Expand Down
Loading
Loading