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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ Each release links to full notes on the

### Changed

- **Breaking:** `to_json_schema()` and `to_stickler_config()` no longer write a
plain pydantic `BaseModel`, a list of lists or a union of models as a string.
Both fell back to `"string"` / `"str"` for a type they had no entry for, so
the re-imported model could not load the data the original accepted. A plain
model field, or a list of them, now exports as a free-form object
(`{"type": "object"}`, `"dict"` in a Stickler config), since it is scored as
one object the way a mapping is, and re-imports as `dict` with the
comparator, threshold, weight and clip setting it declared; its own field
types are not exported. A list of lists, including `List[List[Dict]]`,
exports as nested arrays. A consumer reading the exported schema sees these
types change. `to_stickler_config()` has no type for a union with a model
arm, such as the `Union[Card, Bank]` that `from_json_schema()` builds from a
multi-arm `anyOf`, or for a `StructuredModel` inside a nested list
(`List[List[Card]]`), so both methods now raise `ValueError` for these, to
keep one rule, where they returned a schema that could not load the original
data or (for the nested list, in the Stickler config) scored it differently.
Parts B and C of [#349](https://github.com/awslabs/stickler/issues/349)

- **Breaking:** a `StructuredModel` field typed `date`, `datetime`, `time`,
`timedelta`, `Decimal`, `UUID` or `Enum` now reaches its comparator, and a
declared comparator is always called. The dispatcher treated only `str`,
Expand Down
10 changes: 10 additions & 0 deletions docs/docs/Advanced/model-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@ Stickler provides three methods for exporting model schemas. Two support round-t
| `to_stickler_config()` | Custom Stickler JSON | Yes | `model_from_json()` | Hand-editing, version control |
| `model_json_schema()` | Pydantic JSON Schema | No | N/A | API docs, LLM tool specs, runtime inspection |

A plain Pydantic `BaseModel` field, or a list of them, is scored as one object and exports as a
free-form object (`{"type": "object"}`, `"dict"` in a Stickler config). It re-imports as `dict` with
its comparison settings, but its own field types are not exported, so the re-imported field does
not coerce values. A list of lists exports as nested arrays; `to_stickler_config()` writes it as
`List[List]`, without the inner element type. A plain model inside a nested list comes back as a
`dict`, which can score slightly differently there. `to_stickler_config()` has no type for a union
with a model arm (`Union[Card, Bank]`, `Union[Plain, str]`) or for a `StructuredModel` inside a
nested list (`List[List[Card]]`), so both methods raise for these, to keep one rule
([#349](https://github.com/awslabs/stickler/issues/349)).

Both round-trip methods are also reachable from a plain Pydantic `BaseModel` that was never written
as a `StructuredModel`, by converting first:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from pydantic.fields import FieldInfo

from .configuration_helper import ConfigurationHelper
from .optional_annotation import unwrap_optional

# Bidirectional type mappings for export
Expand Down Expand Up @@ -78,26 +79,28 @@ def field_to_property(
field_type = unwrapped
is_nullable = True

# A StructuredModel must never reach the scalar fallback below. It has
# its own schema -- properties, nested thresholds, comparators -- and
# `PYTHON_TYPE_TO_JSON_TYPE.get(..., "string")` would silently discard
# all of it, emitting a schema that rebuilds into a structurally
# different model. Raise rather than produce a wrong schema quietly.
# A StructuredModel, or a union with a model arm, must never reach the
# scalar fallback below. `PYTHON_TYPE_TO_JSON_TYPE.get(..., "string")`
# would silently discard its schema, emitting one that rebuilds into a
# structurally different model. Raise rather than produce a wrong
# schema quietly.
#
# Deliberately scoped to StructuredModel, not to every dict miss:
# Deliberately scoped to models, not to every dict miss:
# Decimal, UUID and enums legitimately export as "string".
from .structured_model import StructuredModel

if isinstance(field_type, type) and issubclass(field_type, StructuredModel):
raise ValueError(
f"Cannot export nested model field as a scalar: annotation "
f"{field_type!r} is a StructuredModel. Export it via its own "
f"to_json_schema() instead of field_to_property()."
)
StructuredModel._refuse_scalar_export(field_type)

json_type = PYTHON_TYPE_TO_JSON_TYPE.get(field_type, "string")
property_schema = {"type": [json_type, "null"] if is_nullable else json_type}

# A plain BaseModel is scored as one object, as a mapping is
# (`ConfigurationHelper.is_object_grade_annotation`), so it exports as a
# free-form object, which re-imports as `dict`. As "string" it rebuilt
# as `str` and rejected the original data (#349).
if ConfigurationHelper.is_plain_model_annotation(field_type):
property_schema["type"] = ["object", "null"] if is_nullable else "object"

# Extract metadata and build extensions using consolidated helper
metadata = self._extract_field_metadata(field_info)
extensions = self._build_comparison_extensions(
Expand Down Expand Up @@ -132,6 +135,13 @@ def field_to_stickler_config(
"""
stickler_type = PYTHON_TYPE_TO_STICKLER_TYPE.get(field_type, "str")
field_config = {"type": stickler_type}
# As in field_to_property(): a model or a union with a model arm cannot
# be written as a scalar, and a plain BaseModel is written as `dict`.
from .structured_model import StructuredModel

StructuredModel._refuse_scalar_export(field_type)
if ConfigurationHelper.is_plain_model_annotation(field_type):
field_config["type"] = "dict"

# Extract metadata and build extensions using consolidated helper
metadata = self._extract_field_metadata(field_info)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,17 @@ def to_json_schema(cls) -> Dict[str, Any]:
metadata, output_format="json_schema"
)
property_schema.update(extensions)
# The element type above is "string" for a list of lists or
# of plain models, which re-imported as List[str] and
# rejected the original data (#349). Write the structure
# instead, after refusing what neither export can write.
cls._refuse_scalar_export(element_type)
if get_origin(
ConfigurationHelper.strip_annotation_wrappers(element_type)
) is list or ConfigurationHelper.is_plain_model_annotation(
element_type
):
property_schema["items"] = cls._json_type_schema(args[0])
else:
# Primitive type - use converter for consistent formatting.
# field_type is already unwrapped above, so pass whether the
Expand Down Expand Up @@ -1974,6 +1985,77 @@ def _is_structured_model_type(field_type: Type) -> bool:
except TypeError:
return False

@staticmethod
def _refuse_scalar_export(field_type: Type) -> None:
"""Raise for an annotation the exporters cannot write.

A StructuredModel is written through its own ``to_json_schema()`` /
``to_stickler_config()``, and one reaching a scalar exporter would lose
its whole schema. ``to_stickler_config()`` has no type for a union with
a model arm, or for a StructuredModel inside a nested list, so
``to_json_schema()`` refuses both as well and the two exports follow one
rule. Both were written as ``"string"`` / ``"str"`` or ``List[List]``,
which re-imported as a different field (#349). ``Optional`` and
``Annotated`` are stripped at every level.
"""
strip = ConfigurationHelper.strip_annotation_wrappers
inner = strip(field_type)
if isinstance(inner, type) and issubclass(inner, StructuredModel):
raise ValueError(
f"Cannot export {inner!r} as a scalar: it is a StructuredModel, "
f"which the exporters write through its own to_json_schema() and "
f"to_stickler_config()."
)
nested = False
while get_origin(inner) is list and get_args(inner):
inner, nested = strip(get_args(inner)[0]), True
if union_args(inner):
arms = [strip(arm) for arm in union_args(inner)]
if any(
isinstance(arm, type) and issubclass(arm, BaseModel) for arm in arms
):
raise ValueError(
f"Cannot export {field_type!r}: to_stickler_config() has no "
f"type for a union with a model arm, so to_json_schema() "
f"refuses it too, to keep one rule for both exports."
)
elif nested and isinstance(inner, type) and issubclass(inner, StructuredModel):
raise ValueError(
f"Cannot export {field_type!r}: to_stickler_config() has no type "
f"for a StructuredModel inside a nested list, so to_json_schema() "
f"refuses it too, to keep one rule for both exports."
)

@staticmethod
def _json_type_schema(element_type: Type) -> Dict[str, Any]:
"""The JSON Schema ``items`` for a list element that is not a model.

A list is an array of its own element, and a mapping or plain
``BaseModel`` is a free-form ``{"type": "object"}``, which
``from_json_schema()`` reads back as ``dict``: both are scored as one
object (``ConfigurationHelper.is_object_grade_annotation``), and the
types of their values are not exported. Call it after
:meth:`_refuse_scalar_export`, which rejects what this cannot write.
"""
from .json_schema_field_converter import PYTHON_TYPE_TO_JSON_TYPE

inner, nullable = unwrap_optional(unwrap_annotated(element_type))
inner = unwrap_annotated(inner)
if get_origin(inner) is list and get_args(inner):
schema = {
"type": "array",
"items": StructuredModel._json_type_schema(get_args(inner)[0]),
}
elif ConfigurationHelper.is_mapping_annotation(
inner
) or ConfigurationHelper.is_plain_model_annotation(inner):
schema = {"type": "object"}
else:
schema = {"type": PYTHON_TYPE_TO_JSON_TYPE.get(inner, "string")}
if nullable:
schema["type"] = [schema["type"], "null"]
return schema

@classmethod
def to_stickler_config(cls) -> Dict[str, Any]:
"""Export model as custom Stickler JSON configuration.
Expand Down Expand Up @@ -2078,7 +2160,14 @@ def to_stickler_config(cls) -> Dict[str, Any]:
field_config = converter.field_to_stickler_config(
element_type, field_info
)
field_config["type"] = f"List[{element_type.__name__}]"
# A plain model's class name is not a type model_from_json()
# knows; it is written as `dict`, as the singular field is.
element_name = (
"dict"
if ConfigurationHelper.is_plain_model_annotation(element_type)
else element_type.__name__
)
field_config["type"] = f"List[{element_name}]"
else:
# Primitive type - use converter for consistent formatting
field_config = converter.field_to_stickler_config(
Expand Down
Loading