Skip to content
Merged
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(423): don't run the builder check from EvalSpec.explain()
A spec holds either the shadow the builder already built, so the check
cannot fail, or a hand-written eval_model, which the builder's verdict on
source_cls does not bear on. Running it there made explain() raise for
EvalSpec(Node, NodeSM) with a recursive Node, which worked on dev.

Pin the #423 symptom directly (RootModel message naming the field), add a
recursive-model case for specs_for, and say in the CHANGELOG which other
classes it now refuses.
  • Loading branch information
harrycav committed Oct 20, 2026
commit a8b0164c32cb00f0f398a8d6f485290fb9bc7e58
17 changes: 11 additions & 6 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,17 @@ Each release links to full notes on the
the caller declared
([#366](https://github.com/awslabs/stickler/issues/366))

- **`specs_for` now refuses a `RootModel` too, with the builder's message.**
After #366 it still returned specs for the root's internal `root` attribute,
such as `pt.root.x`, a path no data carries and that is never scored. It now
raises the same `TypeError` as `structured_model_for` for any class the
builder refuses. An explicitly configured `StructuredModel` is never built,
so it is not checked: a `RootModel` reached through one is still described
- **`specs_for` now refuses what the builder refuses, starting with a
`RootModel`.** After #366 it still returned specs for the root's internal
`root` attribute, such as `pt.root.x`, a path no data carries and that is
never scored. It now raises the same `TypeError` as `structured_model_for`
for any class the builder refuses: a `RootModel`, a recursive model, a field
named `extra_fields`, or a model with no fields. A class that is not a
pydantic model now raises `TypeError` rather than `AttributeError`.
`explain()` on an `EvalSpec` is unchanged: its model was either already
built, or written by hand and never built. An explicitly configured
`StructuredModel` is never built either, so it is not checked: a `RootModel`
reached through one is still described
([#423](https://github.com/awslabs/stickler/issues/423))

- **A float `NaN` is now absent, the same as `None`.** Two identical `NaN`s
Expand Down
10 changes: 9 additions & 1 deletion src/stickler/auto/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ def specs_for(
*,
weight_hints: bool = False,
match_threshold: float = 0.7,
_check_buildable: bool = True,
) -> Dict[str, InferredSpec]:
"""Return the inferred spec per field (for ``.explain()``), keyed by
dotted path.
Expand All @@ -142,8 +143,15 @@ def specs_for(
it refuses, such as a ``RootModel``: specs for a model that cannot be built
would describe paths that are never scored. A ``StructuredModel`` is used
as configured and never built, so it is not checked.

``_check_buildable=False`` skips that check, for ``EvalSpec.explain()``: a
spec either holds the shadow the builder already built, so the check
cannot fail, or a hand-written ``eval_model``, which the builder's verdict
on ``cls`` does not bear on.
"""
if not (isinstance(cls, type) and issubclass(cls, StructuredModel)):
if _check_buildable and not (
isinstance(cls, type) and issubclass(cls, StructuredModel)
):
# Cached, so this is free when the builder already ran (#423).
structured_model_for(
cls, weight_hints=weight_hints, match_threshold=match_threshold
Expand Down
1 change: 1 addition & 0 deletions src/stickler/auto/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ def explain(self) -> Dict[str, Dict[str, Any]]:
self.source_cls,
weight_hints=self._weight_hints,
match_threshold=self._match_threshold,
_check_buildable=False,
).items():
out[name] = {
"comparator": spec.comparator_name,
Expand Down
52 changes: 40 additions & 12 deletions tests/auto/test_rootmodel_rejected.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
from pydantic import BaseModel, RootModel

import stickler
from stickler import ComparableField, eval_for
from stickler import ComparableField, EvalSpec, eval_for
from stickler.auto.builder import specs_for, structured_model_for
from stickler.structured_object_evaluator.models.structured_model import StructuredModel

Expand Down Expand Up @@ -202,21 +202,49 @@ class _ListHolder(BaseModel):


@pytest.mark.parametrize(
"cls",
[row[0] for row in ROOTS] + [_Holder, _ListHolder],
"cls, where",
[(row[0], row[0].__name__) for row in ROOTS]
+ [(_Holder, "_Holder.pt"), (_ListHolder, "_ListHolder.items[]")],
ids=ROOT_IDS + ["field", "list-element"],
)
def test_specs_for_refuses_what_the_builder_refuses(cls):
"""``specs_for`` reported ``root.*`` paths that are never scored (#423).

It describes the model the builder makes, so it refuses whatever the
builder refuses, with the same message and the same path.
def test_specs_for_refuses_a_root_model_and_names_where(cls, where):
"""``specs_for`` reported ``root.*`` paths, such as ``pt.root.x``, that are
never scored (#423). It now refuses with the builder's RootModel message,
which names the class or the field that holds the root.
"""
with pytest.raises(TypeError) as built:
structured_model_for(cls)
with pytest.raises(TypeError) as described:
with pytest.raises(TypeError, match="a RootModel holds one unnamed value") as exc:
specs_for(cls)
assert str(described.value) == str(built.value)
assert where in str(exc.value)


def test_specs_for_refuses_a_recursive_model_too():
"""The check is the builder's, so it covers more than RootModel: a
recursive model, which ``eval_for`` refuses, is refused here as well."""

class Node(BaseModel):
name: str
children: List["Node"] = []

with pytest.raises(TypeError, match="recursive"):
specs_for(Node)


def test_explain_on_a_hand_written_eval_model_does_not_run_the_builder():
"""An ``EvalSpec`` given its own ``eval_model`` never uses the builder, so
the builder refusing ``source_cls`` must not break ``explain()``. Here the
source is recursive, which the builder refuses, and the spec still scores.
"""

class Node(BaseModel):
name: str
children: List["Node"] = []

class NodeSM(StructuredModel):
name: str = ComparableField()

spec = EvalSpec(Node, NodeSM, weight_hints=False, match_threshold=0.7)
assert spec.evaluate(Node(name="a"), Node(name="a")).overall_score == pytest.approx(1.0)
assert "name" in spec.explain()


def test_explain_on_a_structured_model_holding_a_root_model_field_still_works():
Expand Down
Loading