Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,19 @@ Each release links to full notes on the
the caller declared
([#366](https://github.com/awslabs/stickler/issues/366))

- **`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))

- **An unrecognized key in a model config is now reported instead of dropped.**
`model_from_json` read a closed set of keys and ignored everything else, so
`"threshhold": 0.99` built at the fallback 0.5 with no exception and no warning,
Expand Down
18 changes: 18 additions & 0 deletions 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 @@ -137,7 +138,24 @@ def specs_for(
under a dotted path (``lines.sku``), so every comparator decision at every
depth is auditable. Primitive-list fields report the spec of the ELEMENT
type, matching what the builder actually installs.

Raises the same ``TypeError`` as :func:`structured_model_for` for any class
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 _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
)
registry = get_global_registry()
result: Dict[str, InferredSpec] = {}
_collect_specs(
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
69 changes: 67 additions & 2 deletions tests/auto/test_rootmodel_rejected.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
from pydantic import BaseModel, RootModel

import stickler
from stickler import ComparableField, eval_for
from stickler.auto.builder import structured_model_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 @@ -190,3 +190,68 @@ class Configured(StructuredModel):
# a perfect match. Asserting only `name` would pass even if `pt` returned
# the false 1.0 this work removes everywhere else.
assert result.field_scores["pt"] < 1.0


class _Holder(BaseModel):
name: str
pt: RootModel[Point]


class _ListHolder(BaseModel):
items: List[RootModel[Point]]


@pytest.mark.parametrize(
"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_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, match="a RootModel holds one unnamed value") as exc:
specs_for(cls)
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():
"""The configured path is never built, so ``specs_for`` does not refuse it."""

class Configured(StructuredModel):
name: str = ComparableField(default="")
pt: Optional[RootModel[Point]] = ComparableField(default=None)

assert "name" in eval_for(Configured).explain()
Loading