Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
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
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,23 @@ Each release links to full notes on the
later on subscripting
([#350](https://github.com/awslabs/stickler/issues/350))

- **Breaking:** on the zero-config path (`stickler.evaluate()`, `eval_for()`,

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 (conventions): this entry is labelled Breaking, but every commit subject on the branch is fix(auto): ... with no ! and no BREAKING CHANGE: footer. CONTRIBUTING.md requires Conventional Commits and links the spec, which marks a breaking change with ! or a BREAKING CHANGE: footer. Release notes and the version bump are derived from commit subjects, so the squash commit should read fix(auto)!: ..., or include the footer.

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.

Fair point. The new commit is fix(auto)!: with a BREAKING CHANGE: footer, and the squash title will be fix(auto)!: ....

`StructuredModel.from_pydantic()`), a field marked `Field(exclude=True)` is no
longer evaluated. It was left out of the dump but kept in the inferred model,
so it was blank on both sides: a wrong value scored `1.0` and was listed in
`field_scores` and `explain()` as compared, and a required one raised
`ValidationError`. It is now absent from `field_scores`, `explain()`,
`non_matches` and reports, at any depth, so a value kept out of serialization
is never scored or published. A nested model left with no field to score is
left out the same way. `exclude_if` is decided per value: a value it keeps is
scored, and a value it omits is absent, like `None`, so a required field it
omits no longer raises. A `StructuredModel` is unchanged: its
`ComparableField`s declare what is compared, so an excluded field there is
still scored, and `evaluate()` now agrees with `compare_with()` on it instead
of scoring `1.0`. See
[Excluded fields](https://awslabs.github.io/stickler/API-Reference/auto/#excluded-fields)
([#379](https://github.com/awslabs/stickler/issues/379))

- **Breaking:** a `None` element in a list is now absent. It is left out
before matching, so it is never paired, counted or scored, and a list of only
`None` is an empty list. A float `NaN` element counts as `None`; an empty
Expand Down Expand Up @@ -126,6 +143,24 @@ Each release links to full notes on the
was a false discovery, false alarm or false negative, so `field_comparisons`
agrees with `non_matches`.

- **`stickler.evaluate()` and `eval_for()` now read a model dumped by
alias.** With `serialize_by_alias=True` the dump carried alias keys that the
inferred model never read, so the field was blank on both sides: a wrong
value scored `1.0`, and a required field raised `ValidationError`. Plain
models now reach it keyed by field name. A `StructuredModel` keeps its alias
keys, and a `serialization_alias`, which its validation never reads, is
keyed by field name, so `evaluate()` agrees with `compare_with()`.
Serializers and `ser_json_*` config still apply
([#378](https://github.com/awslabs/stickler/issues/378))

- **`StructuredModel.from_json()` keeps a nested `StructuredModel` whole.** It
passed each nested model on as its `model_dump()`, which drops every
`exclude=True` field, so a nested excluded field read blank on both sides and
`compare_with()` scored a wrong value `1.0`. The nested model's
`extra_fields` were lost the same way. Both are now put back into that dict,
at any depth, so a `mode="before"` validator still receives one
([#379](https://github.com/awslabs/stickler/issues/379))

- **A `RootModel` is now refused when the evaluator is built, instead of failing
once per document or scoring a wrong value `1.0`.** `eval_for()` accepted one
and returned a spec. What happened next depended on the root type:
Expand Down
32 changes: 32 additions & 0 deletions docs/docs/API-Reference/auto.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,38 @@ result.explain()["invoice_id"]
`explain()` on the `EvalSpec` instead omits `score` and `raw_similarity`, since no pair has been
scored yet — use it to review the configuration before running a dataset.

## Excluded fields

A field marked `Field(exclude=True)` is not evaluated, at any depth: in nested models, list
elements and dict values.

```python
class Answer(BaseModel):
value: str
reasoning: str = Field(exclude=True)

result = stickler.evaluate(Answer(value="42", reasoning="..."),
Answer(value="42", reasoning="something else"))
result.field_scores # {'value': 1.0}
```

`reasoning` does not appear in `field_scores`, `explain()`, `non_matches` or an HTML report, and
it carries no weight in `overall_score`. A required excluded field is not required by the
evaluation either. A nested model left with no field to score is left out the same way.

The reasoning: `exclude` marks a field as outside the model's output, which on a `response_model`
is usually a reasoning trace or internal notes. Scoring it would grade text nobody asked to be
graded, and reporting a mismatch would publish a value the author chose not to serialize.

- **`exclude_if` is decided per value, as Pydantic decides it.** A value it keeps is scored. A
value it omits is absent, like `None`: never read or published, and missing against a kept
value. A required field it can omit is not required.
- **A `StructuredModel` is different.** Its `ComparableField`s declare what is compared, and
`exclude` there only affects serialization, so the field is scored by `compare_with()` and by
`stickler.evaluate()` alike.
- **To score an excluded field,** remove `exclude`, or evaluate an explicit `StructuredModel`
that declares the field.

## Inference

The rules behind every decision above, plus the precedence between the type signal and the
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/Getting-Started/ultra-quick-start.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ result.explain()["vendor_name"]["verdict"]
| name and type disagree (`amount: str`) | the type wins | a comparator that cannot parse the type would mis-score |
| a nested model | recurse into it | field-by-field |
| a `List[Model]` | Hungarian matching | order-independent |
| `Field(exclude=True)` | not scored | outside the model's output ([details](../API-Reference/auto.md#excluded-fields)) |
| `exclude_if` | scored per value | a value it omits is absent, like `None` |

Full rules and rationale live in [`src/stickler/auto/README.md`](https://github.com/awslabs/stickler/blob/main/src/stickler/auto/README.md).

Expand Down
38 changes: 38 additions & 0 deletions src/stickler/auto/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ Every decision is recorded in `InferredSpec.provenance` and surfaced by
`weight_hints=True`.
- **Semantic / BERT / LLM are never auto-selected.** They need embeddings/creds
and would surprise as a silent default.
- **Excluded fields are not evaluated.** A plain-model field with
`exclude=True` is left out of the shadow model, so it never reaches
`field_scores`, `explain()`, `non_matches` or a report. Neither does a field
holding a model left with nothing to score. `exclude_if` decides per value,
so that field stays in: a value it omits is absent, like `None`, and a
required one is not required. A `StructuredModel` is used as configured, so its excluded
fields are still scored. The rule and its reasons are in
[Excluded fields](../../../docs/docs/API-Reference/auto.md#excluded-fields)
([#379](https://github.com/awslabs/stickler/issues/379)).
- **Unavailable comparators degrade.** If `rapidfuzz` (Fuzzy) or
`python-dateutil` (Date) is missing, the field falls back to Levenshtein/Exact
and the degrade is recorded in provenance.
Expand All @@ -139,6 +148,35 @@ 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.

A field the shadow model cannot read is blank on both sides, and blank against
blank scores as a match. `evaluate()` keeps pydantic's own dump, so serializers
and `ser_json_*` config apply as usual, then walks it beside the instance and
fixes three things:

- A plain model's alias keys (`serialize_by_alias=True`) are renamed to field
names, which the shadow model reads
([#378](https://github.com/awslabs/stickler/issues/378)). A `StructuredModel`
and everything under it validate through their own config, so they get the
key that validation reads: an alias stays, and a `serialization_alias`, which
validation never reads, becomes the field name.
- On a plain model, a field holding a model with nothing left to score is
dropped, so it is not counted as an undeclared field.
- Inside a `StructuredModel`, a field marked `exclude=True` or `exclude_if` is
dumped from its annotation and added back, so `evaluate()` scores it as
`compare_with()` does ([#379](https://github.com/awslabs/stickler/issues/379)).
Annotated serializers and the parent's `ser_json_*` settings apply to it; a
`@field_serializer` does not. One that fails to dump stays out.
`StructuredModel.extra_fields` is the engine's own and is never added. On a
plain model nothing is added back: the shadow model has no such field (see
Honesty rules).

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, and a class whose
dump never needs a change keeps pydantic's dump as is, decided once per class.
Anything else the walk leaves alone is kept, not copied.

`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
that with a JSON blob. Keys and values are still normalized (so a
Expand Down
64 changes: 61 additions & 3 deletions src/stickler/auto/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,54 @@ def specs_for(
return result


def is_excluded(field_info: FieldInfo) -> bool:
"""Whether pydantic always leaves the field out of serialization.

Only ``exclude=True`` counts. ``exclude_if`` decides per value, so that
field stays in the shadow model and a value it omits reads as absent.
"""
return bool(field_info.exclude)


def has_exclude_if(field_info: FieldInfo) -> bool:
return getattr(field_info, "exclude_if", None) is not None


def left_out(field_info: FieldInfo, _visiting: Optional[set] = None) -> bool:
"""Whether a plain model's shadow leaves the field out (#379).

That is an ``exclude=True`` field, or one holding a plain model (alone or
as a list element) with nothing left to score once its own excluded fields
are gone. A ``StructuredModel`` is used as configured and keeps both.
"""
if is_excluded(field_info):
return True
annotation, _ = unwrap_optional(field_info.annotation)
kind = _field_kind(annotation)
if kind == "model_list":
annotation, _ = unwrap_optional(_list_element(annotation))
elif kind != "model":
return False
return not _has_scorable_field(
annotation, set() if _visiting is None else _visiting
)


def _has_scorable_field(cls: Type[BaseModel], _visiting: set) -> bool:
# A StructuredModel is used as configured, and _build refuses a cycle or a
# model with no fields at all, so all three count as scorable here.
if issubclass(cls, StructuredModel) or cls in _visiting or not cls.model_fields:
return True
_visiting.add(cls)
try:
return any(
not left_out(field_info, _visiting)
for field_info in cls.model_fields.values()
)
finally:
_visiting.discard(cls)


def _inferred_provenance(cls: Type[BaseModel], name: str) -> tuple:
"""The inference trail for a field, or empty if the author configured it.

Expand Down Expand Up @@ -181,6 +229,8 @@ def _collect_specs(
for name, field_info in cls.model_fields.items():
if name in _RESERVED_FIELD_NAMES:
continue
if not is_structured and left_out(field_info):
continue # not in the shadow model, so not explained either
path = f"{prefix}{name}"
annotation, _ = unwrap_optional(field_info.annotation)
kind = _field_kind(annotation)
Expand Down Expand Up @@ -338,8 +388,12 @@ def _build(
try:
registry = get_global_registry()
field_definitions: Dict[str, Tuple[Any, Any]] = {}
skipped = False

for name, field_info in cls.model_fields.items():
if left_out(field_info):

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): the documented from_pydantic() recipe reports false alarms on identical documents.

When every field of a nested model is excluded, this line removes the model from the shadow model. pydantic's dump still writes its key, and only _restore drops it.

class Trace(BaseModel):
    steps: str = Field('', exclude=True)
class Out(BaseModel):
    answer: str
    trace: Optional[Trace] = None
    traces: List[Trace] = []

Pass identical documents through StructuredModel.from_pydantic(Out).from_json(doc.model_dump()). Head gives tp/fa/fp 1/2/2 and precision 0.333. Dev gives 3/0/0 and precision 1.0. This also happens with trace=None. The BulkStructuredModelEvaluator recipe at ultra-quick-start.md:194 reports cm_f1 0.8 on perfect predictions (dev: 1.0).

This contradicts CHANGELOG line 98 ("left out the same way") and auto/README.md:149 ("safe either way"). The shadow model must ignore the key, or the docs must say the recipe does not work for these models.

skipped = True
continue
if name in _RESERVED_FIELD_NAMES:
raise TypeError(
f"evaluate() cannot mirror field {cls.__name__}.{name}: "
Expand All @@ -364,7 +418,8 @@ def _build(
if not field_definitions:

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 nested model whose fields are all excluded now makes the whole evaluate() raise. _build recurses into nested plain models, so a nested model such as a reasoning trace (class Trace(BaseModel): steps: str = Field("", exclude=True)) inside class Out(BaseModel): answer: str; trace: Trace = Trace() raises TypeError: evaluate() needs at least one field to score; Trace defines none outside exclude=True / exclude_if. On dev, evaluate(Out(answer="a"), Out(answer="a")) returned {'answer': 1.0, 'trace': 1.0}. The raise is right for the top-level class only. For a nested class with no scorable fields, drop the parent field from the shadow model (and from explain()) instead of raising.

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.

Agreed. A nested plain model with nothing left to score is now left out along with its parent field, in the inferred model, in explain() and in the dump. Your Out/Trace case gives {'answer': 1.0} with no false alarm. Only the top-level class still raises. See test_a_nested_model_with_only_excluded_fields_is_left_out.

raise TypeError(
f"evaluate() needs at least one field to score; "
f"{cls.__name__} defines none."
f"{cls.__name__} defines none"
+ (" outside exclude=True, which is not scored." if skipped else ".")
)

model_name = _valid_identifier(f"{cls.__name__}Eval")
Expand Down Expand Up @@ -405,7 +460,10 @@ def _field_definition(
# An omitted optional field materializes as None after model_dump, so the
# shadow must accept None whenever the source annotation does OR the field
# can be absent. Any admits None by definition.
nullable = was_optional or not field_info.is_required() or annotation is Any
# A value exclude_if omits is absent from the dump, so that field can be
# absent too, whatever its annotation says.
absent_ok = not field_info.is_required() or has_exclude_if(field_info)
nullable = was_optional or absent_ok or annotation is Any

if kind == "model":
child = _shadow_for(
Expand Down Expand Up @@ -473,7 +531,7 @@ def _field_definition(
match_threshold=match_threshold,
)
wire = _scalar_wire_type(annotation)
default = ... if field_info.is_required() else None
default = None if absent_ok else ...
return (
Optional[wire] if nullable else wire,
_comparable_from_spec(spec, default=default),
Expand Down
Loading
Loading