Repository navigation
fix(349)!: export plain models and nested lists, refuse model unions - #414
Conversation
to_json_schema() and to_stickler_config() fell back to "string" / "str" for
any annotation missing from their type tables. A plain BaseModel, a list of
plain models and a list of lists all took that fallback, so the re-imported
field was str (or List[str], or an unknown type in the config) and could not
load the data the original model accepted. The guard meant to stop a nested
model reaching the fallback checked `isinstance(field_type, type)`, which is
False for Union[Card, Bank], so that union exported as "string" too.
from_json_schema() builds exactly that union from a multi-arm anyOf, so a
schema-only round trip broke.
- A plain BaseModel is scored as one object, as a mapping is, so it exports
as a free-form {"type": "object"} ("dict" in a Stickler config, List[dict]
for a list) and re-imports as dict with its comparison settings. Its own
field types are not exported.
- A list of lists exports as nested arrays, so List[List[float]] and
List[List[Dict]] reload. The element goes through the existing primitive
list branch, so that branch stays the one place that writes a list
property.
- to_stickler_config() has no type for a union with a model arm, or for a
StructuredModel inside a nested list, so both exporters raise ValueError
for these and follow one rule. JSON Schema could express the union (anyOf),
and that export could follow; a model inside a nested list would also
need importer work. Optional and
Annotated wrappers are stripped at every level before the check.
Mapping fields and List[Dict] elements are left alone here: the first is
handled in awslabs#360, the second in awslabs#405.
Refs awslabs#349 (parts B and C)
sromoam
left a comment
There was a problem hiding this comment.
Thanks @Thanatos9404. Refusing model unions instead of silently writing "string" is the right call, and the nested-array export is a real improvement. I measured everything below on 7faefc0 with the import pinned to the PR tree.
Two things to fix, both about valid models that now fail to export:
Annotatedaround a nested model is refused. The export dispatch (structured_model.py:1847) stripsOptionalbut notAnnotated. A supported nested field therefore skips the recursive branch and reaches_refuse_scalar_export. For example,card: Optional[Annotated[Card, Field(description="d")]](how pydantic storesAnnotated[Card, Field(...)] | None) andcards: List[Annotated[Card, "m"]]both raise "Cannot export Card as a scalar" on both exporters. RunningConfigurationHelper.strip_annotation_wrappersin the dispatch, for both the field and the list element, should send them down the recursive path.- A single-level list is called a nested list.
_refuse_scalar_exportsetsnested=Trueafter removing one list level (:2011), butfield_to_propertyandfield_to_stickler_configpass it the whole field annotation. Soitems: Optional[Annotated[List[Card], Field(description="d")]]raises "has no type for a StructuredModel inside a nested list". Please add these two shapes totest_export_roundtrip_shapes.py. They're what let this slip through.
Not blocking, but please narrow the CHANGELOG and test docstring claim ("neither exporter writes a structured field as a scalar"). The check doesn't look inside container arms or containers yet:
Union[List[Card], str]andUnion[Dict[str, Card], str]still export as"string".List[List[Dict[str, Card]]]andTuple[Card, ...]don't raise.- A
List[List[Union[str, int]]]leaf still falls back to"string"(:2054).
I'll file those as a follow-up so this PR doesn't grow. The helper consolidation (_json_type_schema and the four plain-model overrides) can wait too.
Both exporters stripped Optional but not Annotated before dispatching, so a nested model declared as Optional[Annotated[Card, Field(...)]] or List[Annotated[Card, "m"]] skipped the recursive branch and was refused as a scalar. The field and the list element now go through strip_annotation_wrappers, so they export as the model, and an annotated scalar exports as its own type instead of a string. _refuse_scalar_export now takes the field's whole annotation and counts list levels, so a single List[Card] is no longer reported as a nested list. Both list branches pass it the whole field. The CHANGELOG entry and the test docstring now say which shapes the refusal does not reach yet. Refs awslabs#349
|
Thanks for measuring this so carefully. Both fixes are in bcc24de: the export dispatch now runs |
sromoam
left a comment
There was a problem hiding this comment.
Thanks @Thanatos9404, this is exactly what was needed. I re-measured on bcc24de with the import pinned to the PR tree.
Optional[Annotated[Card, Field(description="d")]],List[Annotated[Card, "m"]]andOptional[Annotated[List[Card], Field(description="d")]]now take the recursive path on both exporters. Each round-trips throughfrom_json_schema()andmodel_from_json()with the same scores as the original.- Having
_refuse_scalar_exportcount list depth on the whole annotation is a cleaner rule than before, and the single-level test pins it. - Nearby shapes (
Optional[Card],List[Optional[Card]], outerAnnotated, nested primitive lists, plain models) still round-trip, and the model-union and nested-list refusals still refuse. The suite passes on its own and merged withdev.
The narrowed CHANGELOG reads well, and I'll track the container cases in #426.
One heads-up, no action needed here: this overlaps with #405 in the to_stickler_config() list branch. Whichever lands second keeps #405's List[Dict] mapping branch first, then your plain-model dict fallback.
Approving. Thanks again for the careful follow-up.
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 2 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 4 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Finding 3: B307
Description: Code Snippet: Finding 4: B307
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-10-19T21:24:27+00:00 |
… optional elements nullable Review follow-ups on #405: - docs: a list of lists exports nested arrays since #414; drop "or another list" from the string-export sentence. - to_stickler_config() writes List[Optional[Dict]] for an optional mapping element, so the re-imported model accepts None elements again. - A declared ComparableField whose annotation resolves only at model_rebuild() exported Levenshtein with clip on while the engine scored ANLS* with clip off (0.95 vs 0.5 after the round trip). Mapping lists now always export get_comparison_info(), declared or not, and the stale comparator_config is dropped.
… JSON output (#604) * fix(366): refuse a RootModel when the evaluator is built `eval_for()` accepted a `RootModel` and returned a spec. What happened next depended on the root type, and one of the four outcomes was silent: RootModel[list[Point]] AttributeError: 'list' object has no attribute 'keys' RootModel[int] AttributeError: 'int' object has no attribute 'copy' RootModel[dict[str, int]] ValidationError, missing `root` RootModel[Point] scored 1.0 for two values differing in every field The three errors came from `ConfigurationHelper.from_json`, where the dump of a root value arrives as something other than a mapping. They arrived once per document rather than once at configuration time, and named neither `RootModel` nor the field they could not key. The fourth reported a perfect match for a wrong prediction, which is the outcome worth closing. The check sits beside the `BaseModel` guard already at the top of `structured_model_for`, so both public entry points inherit it: `eval_for` reaches it for anything that is not a `StructuredModel`, and `evaluate()` calls `eval_for`. The message names the class and points at declaring the root value as a named field on a `BaseModel`. Issue #366 offered two directions and called the refusal useful on its own even if root-value comparison stays out of scope. This takes that one: a root value is still not compared, and a `RootModel` held in a field is untouched, since it fails on its own terms with a pydantic `ValidationError` that names the field. Suite: 2793 passed, 12 skipped, 1 xfailed, against 2779 on dev. Closes #366 * chore(ci): validate a pull request commit once, not twice `run_pytest.yaml`, `lint.yaml` and `security.yaml` all declared `on: [push, pull_request]`. On a branch in this repository with an open pull request both events fire, so every push validated the same commit twice. On `854fc00e` (PR #384) that is six runs of three workflows, fourteen jobs: ten tests, two lint, two security. The two copies are not guaranteed to agree, which is the sharper reason to drop one. On that same commit the `pull_request` copy passed all five Python versions while the `push` copy failed 3.10, on a wall-clock assertion that measured 41.69s against a 35s budget. One commit, two verdicts. `push` is now limited to `dev` and `main`, which keeps those branches validated while a pull request from a feature branch reports through `pull_request` alone. A pull request whose head is `dev`, as a release promotion to `main` would be, still fires both. `run_pytest.yaml` and `lint.yaml` also take a concurrency group so a superseded pull-request head stops running. A push gets a group of its own, keyed on `github.run_id`: a group holds one running and one pending run, so sharing a group per branch would let a third push cancel the pending one no matter what `cancel-in-progress` says, and that flag only protects the run already executing. `security.yaml` takes the trigger change and no concurrency. `security-pr-comment.yaml` wakes on its completion, a cancellation included, and downloads the `security-reports` artifact; a cancelled scan uploads none, and that consumer fails rather than skipping on a missing artifact, as it did on `b32d3ffd`. Limiting `push` already removes the duplicate run. No behaviour change to the library, so there is no CHANGELOG entry. * fix: restore stdout when print_confusion_matrix output_file write fails Use contextlib.redirect_stdout to ensure sys.stdout is always restored, even when an error occurs during file writing. Previously, any exception between stdout reassignment and restoration would leave stdout pointing at a closed file, breaking all subsequent print() calls in the process. Also catch only OSError from open() instead of all exceptions, and add missing bulk_info_summary to file output branch. Fixes #385 * fix: narrow scope to stdout restoration only Remove OSError narrowing and bulk_info_summary addition from the previous commit to focus solely on fixing the stdout restoration bug described in issue #385. * refactor(296): remove the dead ConfusionMatrixCalculator methods calculate_list_confusion_matrix, calculate_nested_field_metrics and calculate_single_nested_field_metrics only called each other, and their only way in was three StructuredModel wrappers that nothing calls. All six had zero executed lines across the full suite. Remove them, the HungarianHelper, NonMatchesHelper and List imports that only they used, and the refactoring notes that listed the wrappers. StructuredListComparator._calculate_nested_field_metrics is a separate, live method with the same name and is untouched. So are ConfusionMatrixCalculator.__init__, classify_field_for_confusion_matrix and StructuredModel._classify_field_for_confusion_matrix, which StructuredListComparator calls. The 1e-10 threshold window that algorithms/README.md and the HungarianMatcher.calculate_metrics docstring attribute to ConfusionMatrixCalculator lived in the deleted calculate_nested_field_metrics. The method that remains compares with a bare >=, so both now name only ThresholdHelper and ComparisonHelper. Also run ruff format on the calculator file, which only strips the trailing whitespace from 9 blank docstring lines. Closes #296 * fix(383): always call a declared comparator, and drop Tuple/Set Review on #384 (digalaviz): - A declared comparator is now called for any pair of non-structured values, in both compare_with() and compare(). The strict scalar list applies only to an inferred comparator, where an arbitrary object would reach Levenshtein as a near-identical repr. This restores compare() for bytes and custom classes, and fixes compare_with() for them. ComparableFieldConfig carries comparator_explicit, read from the same _comparator_explicit bit the object-grade substitution uses. - Drop Tuple/Set: no set ordering, no tuple/set branch, and an empty tuple or set is no longer absent. Inferred-comparator tuples and sets keep their pre-#383 behaviour in each reader, tracked in #391. With a declared comparator they arrive as the caller supplied them, so a set-aware comparator works. - Mark the CHANGELOG entry Breaking and list what moves for existing callers; scope the stickler.evaluate() sentence to the zero-config path. #392 tracks merging the two readers. * fix(292): format the budget key as a number in Bulk_Confidence_AUROC ErrorCaptureAtBudgetMetric keys budgets with strings such as "0.10" so the dict round-trips through JSONL, and cell 11 of the notebook applied the % format code to those strings, so it raised ValueError: Unknown format code '%' for object of type 'str'. Convert the key with float() before formatting, as the confidence metrics docs already do. Store the outputs of a full run, so a reader sees the real numbers. * fix!: treat a None list element as absent A None element in a list is now left out before matching: 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 string is still a value. This holds for list fields of models and of primitives, in compare_with() and compare(), and reports keep each element's original index. Counting a None as an element credited two of them as a true positive and counted a missed row as a false discovery (or, in a list of models, a true positive), so recall stayed at 1.0. It also removes the order dependence of List[Optional[Model]]: element kind and the Hungarian match_threshold were read from [0], so a leading None skipped the class gate (#386) and took the parent's threshold (#322). The rule is defined in docs/docs/Advanced/classification-logic.md, "None elements in a list". Closes #386. Closes #322. * fix(366): refuse a RootModel in a nested field or list element The guard read the class passed in and nothing below it, so a `RootModel` held in a field or as a list element still reached the builder. Both produced a shadow carrying a single `root` field that no dumped value ever filled: both sides read None, and two values differing in every field scored 1.0. That is the same silent outcome the top-level refusal closed. The check now sits at the top of `_build`, which assembles the shadow class for every model the zero-config builder mirrors, beside the refusals for a recursive graph, a reserved field name and a model with no fields. One check covers the class passed in and every model reached from it, at any depth. `_build`, `_field_definition` and `_shadow_for` carry a `_path` argument so the message names the field rather than only the class: `Holder.pt` for a field, `Holder.items[]` for a list element, since the two reach the builder through different branches. The builder descends through a nested model and a `List[BaseModel]` element, and those are exactly the positions that carried the bug. A `RootModel` reached only through a `Dict` value, a `Tuple`, a `Set` or a union is still built, unchanged, because it is compared as canonical JSON rather than mirrored: two differing values score 0.0 to 0.667 there, never a false 1.0. The previous commit said a `RootModel` held in a field was untouched because it failed on its own terms with a pydantic `ValidationError` naming the field. That holds for `RootModel[list[...]]`, which raised once per document, and not for `RootModel[Model]`, which raised nothing and scored 1.0. The test that asserted it is inverted here, and the CHANGELOG entry corrected. An explicitly configured `StructuredModel` is returned as configured and never mirrored, so the refusal does not reach inside one: its fields keep the comparators the caller declared. `auto/README.md` records that boundary, and that the order of the refusals is not a precedence guarantee, since a model tripping two of them reports whichever its fields reach first. * fix(pretty_print): do not report success when non-match records are absent `print_non_matches` and `print_evaluation_results` printed "No non-matches found - all fields matched successfully!" for `EvalResult.raw` or any `compare_with()` dict computed without `document_non_matches=True`, including one with a wrong field. Such a dict has no `non_matches` key, and the printers fell back to `confusion_matrix["non_matches"]`, a placeholder the engine always writes empty. `_extract_non_matches` now returns None when the results carry no records, distinct from an empty list, and only trusts a populated placeholder. Missing records print a note naming `document_non_matches=True`; an empty list prints "No non-matches found." without the `all_fields_matched` wording removed in #287. A bulk `ProcessEvaluation` built with `document_non_matches=False` gets the same note. Closes #298. * fix(333): export a list of mappings with object items `to_json_schema()` fell back to `{"type": "string"}` for a list element it did not recognise, so `List[Dict[...]]` re-imported as `List[str]` and the round-tripped model raised `ValidationError` on the data the original accepted. A mapping element now exports as `{"type": "object"}` (nullable when the element is optional), which the importer reads back as `dict`. The exported clip setting already matches what the field resolves to: the object-grade substitution writes it into the metadata the exporter reads, so with the items typed correctly the round trip scores as the original did. Tests pin both, plus the stickler-config path. Closes #333. * fix(pretty_print): error on non-result input; actionable note for EvalResult.raw Review follow-ups on the #298 fix. - `print_non_matches` on input that is not a result (an arbitrary object, None, a bare list of records) printed the "pass document_non_matches=True" note, which sends the owner of a list of records after something they already did. It now prints an error, as `print_confusion_matrix` does. - The note now names the remedy for `EvalResult.raw` first: `evaluate()` takes no `document_non_matches`, so passing the `EvalResult` itself is the only actionable advice for the issue's own case. - CHANGELOG: an `evaluator_format=True` dict always carries a `non_matches` list, so it still prints the success line without records. Say so rather than claim every `compare_with()` dict is covered. - Docstring note moved above `Args`. - Tests: non-result input, bulk with records and no failures, and the EvalResult hint on `.raw`. * fix(333): correct the round-trip claims and pin the documented limits The CHANGELOG said to_stickler_config() already exported this shape as List[Dict]; it writes List[Mapping] for a Mapping element, which model_from_json() refuses. The docs paragraph sat under a both-methods heading without saying so, and neither text said the value type is lost (values are no longer coerced) or that a singular mapping field still exports as a string (#349). Kept-settings claims now name weight and are scoped to what ComparableField declared, since a bare field keeps nothing. Tests: assert weight survives, and pin the two documented limits so the docs fail when the shapes start working. * chore: add digalaviz as a maintainer `CODEOWNERS` requested one person on every pull request, so every review in the queue waited on the same reviewer, and a change request could only be withdrawn by them. Adding the second maintainer to the default owner line is what makes the automatic request reach both. `MAINTAINERS.md` is the list `CONTRIBUTING.md` points contributors at, and its "Becoming a maintainer" section puts nomination and approval with the current maintainers, so this lands as a pull request for the existing maintainer to approve rather than as a direct commit. * test(365): pin the stickler surface Strands Evals 1.6.0 reads strands-agents-evals 1.6.0 scores structured output with stickler (StructuredOutputSimilarity, StructuredOutputReport). Its suite pins a released stickler, so only a test here fails on the commit that breaks it. - tests/integrations/strands_corpus.py: five models covering the shapes users pass as structured_output_model, 42 cases, and a verbatim copy of 1.6.0's _passed gate. - test_strands_evals_contract.py (no strands dependency): import paths, eval_for kwargs, evaluate/explain shapes, every EvalResult attribute, that raw["confusion_matrix"]["overall"] carries integer tp/fa/fd/fp/tn/fn, recall = tp/(tp+fn), matched = score >= threshold, the nothing-to-find guard, and aggregate_from_comparisons on stripped and JSON-reloaded raws. - test_strands_evals_snapshot.py + strands_evals_snapshot.json: exact scores, verdicts and aggregate metrics for 40 typical cases. STICKLER_UPDATE_STRANDS_SNAPSHOT=1 regenerates it. - test_strands_evals_e2e.py: the real evaluator through Experiment, offline; skipped without strands_evals, fails if stickler is not this checkout. - CI: a strands-evals job installs strands-agents-evals==1.6.0 without its [stickler] extra and runs tests/integrations on Python 3.10 and 3.14. Refs #365. * ci(365): exempt strands-agents-evals from the cooldown up to the 1.6.0 release * fix(411): report missing non-match records instead of a clean document The HTML report's Non-Matches Analysis section rendered "No non-matches found." for a compare_with() dict computed without document_non_matches=True, including one whose name field scored 0.0, and for a bulk ProcessEvaluation built with document_non_matches=False. DataExtractor.extract_non_matches returned [] both when records had been collected and were empty and when they were never collected, so the renderer had nothing to distinguish them by. It now returns None for the second case and the section says the records are missing and how to collect them. An empty list still renders the success message. tests/reporting/html/test_data_extractors.py pinned the conflation by asserting [] for a ProcessEvaluation whose non_matches is None; that assertion is now is None. Every other test in the directory patches the extractor, which is why the defect survived them, so the new coverage drives real comparison dicts and a real bulk evaluator through SectionGenerator without patching. * fix(349)!: export plain models and nested lists, refuse model unions to_json_schema() and to_stickler_config() fell back to "string" / "str" for any annotation missing from their type tables. A plain BaseModel, a list of plain models and a list of lists all took that fallback, so the re-imported field was str (or List[str], or an unknown type in the config) and could not load the data the original model accepted. The guard meant to stop a nested model reaching the fallback checked `isinstance(field_type, type)`, which is False for Union[Card, Bank], so that union exported as "string" too. from_json_schema() builds exactly that union from a multi-arm anyOf, so a schema-only round trip broke. - A plain BaseModel is scored as one object, as a mapping is, so it exports as a free-form {"type": "object"} ("dict" in a Stickler config, List[dict] for a list) and re-imports as dict with its comparison settings. Its own field types are not exported. - A list of lists exports as nested arrays, so List[List[float]] and List[List[Dict]] reload. The element goes through the existing primitive list branch, so that branch stays the one place that writes a list property. - to_stickler_config() has no type for a union with a model arm, or for a StructuredModel inside a nested list, so both exporters raise ValueError for these and follow one rule. JSON Schema could express the union (anyOf), and that export could follow; a model inside a nested list would also need importer work. Optional and Annotated wrappers are stripped at every level before the check. Mapping fields and List[Dict] elements are left alone here: the first is handled in #360, the second in #405. Refs #349 (parts B and C) * fix(333): round-trip an undeclared list of mappings and a Mapping element on the config path Review feedback on #405. - A `List[Dict]` field declared without `ComparableField` exported no comparison keys, so `from_json_schema()` rebuilt it as ExactComparator at 1.0 with clip on (0.5 became 0.0) and `model_from_json()` refused it for having no comparator. Both exporters now write the comparator, threshold, weight and clip the field resolves. Scalar lists are unchanged (#348). - `to_stickler_config()` writes every mapping element as `List[Dict]`. It wrote `List[Mapping]` / `List[Counter]`, which `model_from_json()` refused. The test that pinned that refusal now asserts the round trip. - Docs name the shapes still exported as a string: a list whose element is a union or another list (#349). * docs(352): state the 1.0 default for enum/const on any type and on array items Review round 2 on #369: - Extension Reference: `enum`/`const` default to 1.0 on any type, and the format/enum/const rule also applies to array `items`. Scalar rows now say "plain". An array of free-form objects defaults to 1.0, like a single one. - README `x-aws-stickler-threshold` default matches the table, including that a declared comparator keeps the 1.0. - README schema example annotates its Overall Score (0.919). - The Evaluation guide no longer calls the README the complete reference, which made the two documents point at each other. - tests/test_readme_examples.py: covers non-string enum/const and array items, runs the quick-start block too, derives each annotated line's field from its `field_scores[...]` key instead of a hand-written label map, and reads files as UTF-8. - The `clean = (` guard now scans README.md, like `_authored_prose`. * fix(349): unwrap Annotated before exporting nested models Both exporters stripped Optional but not Annotated before dispatching, so a nested model declared as Optional[Annotated[Card, Field(...)]] or List[Annotated[Card, "m"]] skipped the recursive branch and was refused as a scalar. The field and the list element now go through strip_annotation_wrappers, so they export as the model, and an annotated scalar exports as its own type instead of a string. _refuse_scalar_export now takes the field's whole annotation and counts list levels, so a single List[Card] is no longer reported as a nested list. Both list branches pass it the whole field. The CHANGELOG entry and the test docstring now say which shapes the refusal does not reach yet. Refs #349 * fix(422): escape field names in the HTML field performance table The table wrote each field name into the page raw, while the chart beside it escaped the same name. The function's local html string shadowed the html module, so the escape could not simply be copied across; rename it, and the same shadowing local in generate_confusion_matrix_heatmap and SectionGenerator.generate_confusion_matrix. Fixes #422 * docs(352): split the README's object rows into with-properties and free-form, link the Extension Reference absolutely A free-form {"type": "object"}, or an array of them, resolves to ExactComparator at 1.0, not recursive comparison at 0.7 or Hungarian at 0.5. Relative docs links do not resolve on the PyPI project page. * fix(333): export the resolved comparison for every mapping list, keep optional elements nullable Review follow-ups on #405: - docs: a list of lists exports nested arrays since #414; drop "or another list" from the string-export sentence. - to_stickler_config() writes List[Optional[Dict]] for an optional mapping element, so the re-imported model accepts None elements again. - A declared ComparableField whose annotation resolves only at model_rebuild() exported Levenshtein with clip on while the engine scored ANLS* with clip off (0.95 vs 0.5 after the round trip). Mapping lists now always export get_comparison_info(), declared or not, and the stale comparator_config is dropped. * test(365): address review on the Strands Evals contract - CI and README: constrain the strands-agents-evals install to uv.lock (uv export --no-emit-project + -c). Unconstrained, it moved idna 3.15 to 3.20. README now uses the same command, including the cooldown cutoff without which 1.6.0 does not resolve, and the bump steps move the cutoff. - conftest.py: the "is this checkout" check now covers every file in tests/integrations, not only the e2e. - TestGuard uses STRANDS_DEFAULT_THRESHOLD instead of 0.7 literals. - TestAggregate evaluates only the requested model's cases; the snapshot builds one spec per model instead of one per case. * fix(333): state each re-imported spelling, document the late-resolved fix Self-review follow-ups on #405: - docs and CHANGELOG: an optional element re-imports as List[Optional[dict]] (from_json_schema) or List[Optional[Dict]] (model_from_json), not List[dict]. - CHANGELOG: a declared ComparableField whose annotation resolves only at model_rebuild() now exports ANLS* with clip off, not Levenshtein with clip on (0.5, not 0.95, after the round trip). - to_stickler_config() keeps a declared comparator_config in its key position instead of moving it after default. * test(365): fail closed on the lock export and finish the review follow-ups - README: write the uv.lock constraints to a mktemp file chained with &&, not a fixed /tmp path. With <(...) a failed export installs unconstrained (idna resolved to 3.20, rc 0); the chain stops instead. - CI: uv export -q, so the step no longer echoes the 221-line export. The comments now say the constraints cover uv.lock's default (no-extras) export; packages locked only under extras (boto3, httpx) can move. - Bump steps name the ==1.6.0 pin and the cutoff in both the workflow and the README command. - .github/workflows/README.md: the strands-evals row says the install is constrained to uv.lock. - Contract suite: STRANDS_DEFAULT_THRESHOLD replaces the last 0.7 literal, and _evaluate shares one spec per model and threshold, as the evaluator does (eval_for calls 790 -> 116). * fix(422): str() the field name, test the chart's escaping, truncate before escaping Review follow-ups: a non-str key in a hand-built results dict no longer raises in the chart or table; the chart gets the same escaping test as the table; the non-matches table truncates before escaping, so the cut cannot split an entity such as &. * fix(431): keep document data from ending the report's <script> block The report embeds each document's values as JSON inside <script>, and json.dumps leaves < as is, so a value carrying </script><script>... ran as its own script when the report was opened. Write <, >, &, U+2028 and U+2029 as \uXXXX in both embedded blobs; the page's JavaScript reads the same data. Fixes #431 * test(431): guard the field-threshold blob with a schema-derived field name Review found that reverting only thresholds_json left every test green, though that path runs injected script in Chrome via a JSON Schema property name. Add that case, and name the route in the CHANGELOG. * chore(deps): bump astral-sh/setup-uv Bumps the github-actions group with 1 update: [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv). Updates `astral-sh/setup-uv` from 10.0.1 to 10.3.0 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/v10.0.1...1c37ad07a6a961277cf70c0d37d6f313000f5884) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-version: 10.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions ... Signed-off-by: dependabot[bot] <support@github.com> * test(399): snapshot the None-in-a-list shapes tagged/none_element and tagged/leading_none carried snapshot=False while the change that moves them was an open PR. That change merged on 2026-10-16 (#399, 9a6f13d, merge commit e403b9b), so the hold-out no longer protects a review in flight: it hides a merged behaviour change from every gate that would register it. test_snapshot_matches runs in the five test jobs as well as the two strands-evals ones, so seven green jobs on dev carry the blind spot. Both shapes were always in CORPUS, exercised by the contract and e2e tests; they were simply absent from the golden file. They now enter it with their current values, regenerated with STICKLER_UPDATE_STRANDS_SNAPSHOT=1. The JSON diff is additive: 40 cases to 42, models 4 to 5, no existing value changed. Building the same snapshot against v1.0.0 (e028427) with the same corpus differs in 22 recorded values -- 6 in tagged/leading_none, 2 in tagged/none_element, 14 under models.Tagged. test_pass is among them: tagged/leading_none goes False to True. The change is merged but not published; PyPI still serves v1.0.0, so that column is what consumers run today. Recording the current values is the point: the next movement of these shapes turns those jobs red instead of passing unnoticed, whichever version number #443 settles on. CorpusCase.snapshot is kept. It is the right mechanism the next time a shape has to be held out; SNAPSHOT_CORPUS still reads it, and no case sets it to False today, so the filter is a no-op for now. The module docstring described the exempt shapes as moved by "an open 1.0.1 change". It is not open any more, so the docstring says what is true now. The CHANGELOG entry is there because the snapshot module's own docstring and tests/integrations/README.md require one for any snapshot change, not because anything user-visible changed. Refs #443. * test(381): snapshot the NaN shapes The Strands corpus had no NaN case, so the snapshot gate could not see 6a259d8 moving test_pass. Add three Lead shapes: NaN where a number is expected (now fails at the default threshold), NaN vs NaN, and NaN vs None (now passes). No existing case's values change; the Lead aggregate moves because it averages over three more cases. * docs(381): list the NaN change as Breaking 6a259d8 changes confusion counts and can move a pass/fail verdict in either direction, including a Strands Evals test_pass going from pass to fail at its default threshold (#443). It went in as fix: under Fixed; move its entry to Changed as Breaking. * docs(381): point the snapshot note at the NaN change by issue, not section * fix(454): coerce document_files keys and paths in the gallery html.escape requires str. Integer keys or paths (common when doc_id comes off a DataFrame column) raised AttributeError and generate_report returned success=False with no page. Coerce both sides before escape so int 1001 and "1001" also agree as the gallery key. * fix(453): escape :.3f/:1f cells after formatting A numeric subclass whose __format__ returns markup could land in the field-performance table/chart and the confusion-matrix percentage cells. Escape the formatted string at each of the five sites. Gauge stays unescaped: int(score * 100) forces a plain int. * chore(deps): bump the github-actions group with 2 updates Bumps the github-actions group with 2 updates: [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) and [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish). Updates `astral-sh/setup-uv` from 10.3.0 to 10.3.1 - [Release notes](https://github.com/astral-sh/setup-uv/releases) - [Commits](https://github.com/astral-sh/setup-uv/compare/1c37ad07a6a961277cf70c0d37d6f313000f5884...18d369b23da25a81e9458561248e1aafff6a70fa) Updates `pypa/gh-action-pypi-publish` from 1.14.2 to 1.14.3 - [Release notes](https://github.com/pypa/gh-action-pypi-publish/releases) - [Commits](https://github.com/pypa/gh-action-pypi-publish/compare/dc37677b2e1c63e2034f94d8a5b11f265b73ba33...7245906fb61fa33a13554f9d5fb856fe61758086) --- updated-dependencies: - dependency-name: astral-sh/setup-uv dependency-version: 10.3.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions - dependency-name: pypa/gh-action-pypi-publish dependency-version: 1.14.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: github-actions ... Signed-off-by: dependabot[bot] <support@github.com> * fix: report-only list fixes: raw_similarity_score, evaluator-format precision/recall and non_matches (#330, #413) (#420) * fix(lists): report the unclipped score as raw_similarity_score A list node reported the clipped, coverage-scaled mean in raw_similarity_score, the same number as threshold_applied_score, so it contradicted its name and compare(). unordered_list_metrics now also returns raw_overall_score, the same mean with no element clipped, and both list comparators report it as raw_similarity_score. Report-only: similarity_score, threshold_applied_score, field_scores, overall_score and every confusion count are unchanged. Nothing that feeds a score, a count, bulk mean_score, or confidence metrics reads raw_similarity_score on a list node. Refs #330. * fix(evaluator_format): read precision and recall from confusion counts Without include_confusion_matrix=True, the evaluator-format overall was a conversion of the score that charged every lost point to precision once the score reached 0.5, and each list field's overall always was. One TP and one FN ([A, B] vs [A]) read precision 0.5 and recall 1.0, the wrong way round, while the same call with the confusion matrix said 1.0 and 0.5. format_for_evaluator now receives the compare_recursive result and reads the root's and each list node's counts, so both equal that node's derived block and honour recall_with_fd. A node with only true negatives keeps the score conversion. Other fields and anls_score are unchanged. Evaluator-format output only: scores and counts are unchanged. * fix(evaluator_format): omit non_matches unless records were requested compare_with(evaluator_format=True) always wrote "non_matches": [], so "not collected" read as "no non-matches" and print_non_matches printed a success message over a document with a wrong field. The key is now present only with document_non_matches=True, as in the default compare_with() dict, so the #404 printers report the records as missing. The HTML report had the same ambiguity: DataExtractor.extract_non_matches returns [] either way. DataExtractor.has_non_match_records tells the two apart, and the non-match section now says records were not collected instead of "No non-matches found." when they were not. Scores and counts are unchanged. Refs #330. Closes #413. * fix: evaluator-format metrics from counts on every path; self-review fixes - evaluator_format overall always reads the compare_recursive counts, so it no longer depends on include_confusion_matrix (an all-TN document read 1.0 without it, 0.0 with it; now 0.0, as `derived` does). The cm-derived branch is gone. - Every field with a TP, FP or FN reads its counts, not a score conversion: an unclipped FD scalar read precision 0.5 recall 1.0, now 0.0/0.0. - explain(): a list's verdict no longer compares its coverage-scaled raw mean to the per-element threshold. - print_non_matches: lead with document_non_matches=True; the EvalResult .raw hint only for a default compare_with() dict. - CHANGELOG: #413 moved to Changed as Breaking, migration advice no longer conflates not-collected with clean; explain() note on #330; P/R entry covers scalar fields and the all-TN case. - Docs: regenerated the evaluator-format example from the page's own Invoice pair; confusion_matrix["non_matches"] documented as an always-empty placeholder; architecture row says who reads raw_similarity_score on a scalar. * revert: keep evaluator-format metric rules as 114c9eb had them Reverts the counts-everywhere change from e42b07a (all-TN overall and per-field metrics) to keep 1.0.1 within the PR's original scope; deferred to a 1.1.0 issue. The overall-from-cm branch, the count fallback and the per-field score conversion are 114c9eb's again, as are their tests and CHANGELOG entry. The regenerated guide example measures the same under the reverted rule; its bullets now describe it. Kept from e42b07a: #413 as Breaking under Changed with the corrected migration advice, the confusion_matrix["non_matches"] placeholder note, the explain() note and list verdict wording, the architecture row (now also naming explain() and DataExtractor.extract_similarity_score), and the printer message order. * docs: correct the raw_similarity_score readers and the evaluator-format list shape * review: narrow list raw-score claims, drop list-of-models verdict, per-item overall in CHANGELOG - raw_similarity_score on List[StructuredModel] stays clipped inside each item: say so in the CHANGELOG, architecture.md and the comparator docstring. - explain() no longer gives a list of models a verdict naming the field threshold; the list clips its pairs at 0.01, so the wording named the wrong cause (no verdict, as on dev). - CHANGELOG: per-item items[i] overall moves too; a TN-only node still depends on include_confusion_matrix (#434). Code comment says the same. - evaluator-format metric dict built in one place. - Tighten a print_non_matches assertion that could not fail. * docs(changelog): measured TN-only and list-of-models raw-score wording - Only a TN-only document's overall depends on include_confusion_matrix; a TN-only list field's overall is 1.0 either way (#434). - List[StructuredModel] raw score moves only where a pair's own score is below the list's 0.01 floor (0.005 reported 0.0, now 0.005). - Drop the duplicate bare (#330). * refactor(395): remove the remaining dead confusion-matrix paths (#398) * refactor(395): remove the remaining dead confusion-matrix paths StructuredModel._calculate_object_level_metrics has no caller. The one call site is inside StructuredListComparator, which does not inherit from StructuredModel and calls its own copy. ConfusionMatrixBuilder's calculator property and _calculator slot are never read. Both had zero executed lines across the full suite. Remove them, the HungarianHelper import that only the first used, and the docstrings that describe the builder as coordinating a ConfusionMatrixCalculator. classify_field_for_confusion_matrix now returns only the six counts. Its one caller, StructuredListComparator._handle_non_hierarchical_field, adds up those counts for every matched pair and primitive sub-field and never read the derived metrics that came with them. It is now a staticmethod that takes the ground truth model, so the StructuredModel wrapper no longer builds a ConfusionMatrixCalculator on every call. The StructuredModel branch in classify_field_for_confusion_matrix stays. is_structured_field_type does not recognise a list element sub-field annotated Union[A, B] or Any, so model values on such a field reach the classifier. Without the branch the default LevenshteinComparator would score the text of the two models, and a pair that scores 0.0 as models would count as a TP. A new test pins it. Also correct the StructuredModel size in the refactoring notes (2029 lines now, not ~1486), and name the shims #390 removed and what does their work now. Refs #395 * docs(395): say which StructuredModel shims remain The refactoring notes still said the private wrappers "were not removed" right above the paragraph listing the four that were. Say the ones that still have callers are kept as forwarding wrappers, and link the _calculate_object_level_metrics removal to #398 instead of the issue. Also stop listing ConfusionMatrixCalculator as the component that calculates the matrix in the ComparisonEngine, AggregateMetricsCalculator and DerivedMetricsCalculator docstrings, number the builder's inline step comments to match its docstring, and give the Levenshtein score in the model-valued sub-field test as about 0.96 (measured 0.9583). Refs #395 * docs(395): call the classified list sub-fields non-list, not primitive Model-valued sub-fields annotated Union or Any also reach the classifier, so "non-list" describes what it handles; simple list sub-fields still go through the element-level dispatch. * fix(336): warn about the nested-field pairs the matcher kept, not every cell (#382) * fix(336): warn about the nested-field pairs the matcher kept, not every cell compare() is the cost function for a list of StructuredModel rows, so the class gate on a nested field ran, and warned, for every cell of the cost matrix. An all-correct List[Holder] scored 1.0 with tp=2 and still warned that a Cat was compared against a Dog, and warn_once then had nothing left for the real mismatch that followed. The gate is now silent while HungarianMatcher fills a cost matrix. The selected pairs are scored again through compare_with outside the matrix, which is where the warning now comes from. Verdicts are unchanged. * fix(336): set the matrix flag where the kept pairs are scored again HungarianMatcher.match set filling_cost_matrix for every caller, including a bare matcher and an Any field's list, whose cell scores are the result. Nothing re-scores those pairs, so the gate's only warning was lost: a kept Cat-vs-Dog pair through HungarianMatcher(StructuredModelComparator()) and an Any field declared with that comparator each warned once on dev and not at all here. Scores and counts were unchanged. HungarianHelper.get_complete_matching_info now sets the flag around its calculate_metrics call instead, the one path whose kept pairs are scored again through compare_with. The None filtering from #399 is unchanged. Tests: the flag-scope tests go through HungarianHelper, a bare matcher is checked not to set it, and the bare matcher, Any-field and dict-value cases each warn exactly once. * fix(336): test the kept pair, wrap the matrix flag, correct the docs The bare-matcher and Any-field tests passed on a discarded Cat-vs-Dog cell's warning, so they would still pass if the kept pair never warned. They now use rows paired by label where only the kept pairs cross classes and every discarded cell is same-class. With the kept-pair warning suppressed, both fail; the previous versions passed. The mapping test passes with or without the deferral, because that warning is keyed per field. It is renamed and documented as a guard against over-silencing only. HungarianHelper no longer imports the private ContextVar. hungarian.py gains scoring_cost_matrix(), a context manager that sets and restores it, and the reset is tested for ValueError and KeyboardInterrupt. filling_cost_matrix() is true for the whole HungarianHelper match, including the solve, and false for a bare matcher; its summary and the flag-scope test name now say so. The CHANGELOG entry states the real scope: warnings are deferred to kept pairs when HungarianHelper matches StructuredModel rows, while a bare HungarianMatcher and an Any field whose list does not start with a model warn on every cell, as before. * fix(336): scope the docs to what the flag does, test the kept pair The CHANGELOG headline claimed no warning about a discarded pair at all. It is now scoped to StructuredModel list rows, and names the residual: a bare matcher, or an Any field whose list starts with a scalar, can still spend the field's one message on a discarded cell. filling_cost_matrix() is described as true while HungarianHelper scores and solves the matrix, not for the whole call and not as false during the re-score, which nested lists perform under the outer flag. The scoring_cost_matrix() docstring no longer promises a reset for a signal that lands between the set and the try. TestASelectedMismatchStillWarns uses the fixture where only the kept pairs cross classes, so it fails if no kept pair warns. An autouse fixture asserts the flag is clear before and after each test, and the flag-scope test is renamed to what it checks. * refactor(336): keep the pair-warning flag in hungarian_helper, document it once The flag's only setter (HungarianHelper) and only reader (ConfigurationHelper.can_compare_object_pair) are both in structured_object_evaluator/models, so it moves out of stickler.algorithms.hungarian, which this PR no longer touches. The two names now share a verb: deferring_pair_warnings() and the defer_pair_warnings() context manager. The rule is explained once, in deferring_pair_warnings(). The context manager, the gate docstring and the helper point there, and the algorithms README section is dropped. get_complete_matching_info states that a caller needing the warnings must score the kept pairs again. No behaviour change. * fix(336): set the pair-warning flag inside the try A KeyboardInterrupt between the set and the try left the flag true for the rest of the context, which in a Jupyter kernel is the session, so every later class-mismatch and mapping warning was silenced. * fix(336): restore the pair-warning flag without a token 79b08e4 moved the set inside the try, but a pending KeyboardInterrupt is raised when ContextVar.set returns, after the value has changed and before the token is stored. The token stayed None, the finally skipped the reset, and the flag stayed true. defer_pair_warnings() now reads the previous value first and sets it back in the finally, so no token is needed. A test proxies the ContextVar so that set() changes the value and then raises KeyboardInterrupt; it failed on 79b08e4 and passes now. Also: the gate docstring's "see there" on one line, the test identifiers renamed from "matrix flag" to pair-warning deferral, and one line in the models README for anyone adding a pair-level warning. --------- Co-authored-by: Spencer Romo <sromo@amazon.com> * fix(423): refuse in specs_for whatever structured_model_for refuses (#430) * fix(423): refuse in specs_for whatever structured_model_for refuses specs_for had no RootModel check, so after #366 it returned specs for the root's internal attribute (pt.root.x), paths that are never scored, for a class the builder refuses. Run the builder first (cached) so both raise the same TypeError. A configured StructuredModel is never built and is skipped. Fixes #423 * 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. --------- Co-authored-by: Spencer Romo <sromo@amazon.com> * fix(417)!: use one threshold tolerance at every classification gate (#421) * fix(417)!: use one threshold tolerance at every classification gate A primitive list element was classified with ThresholdHelper.is_above_threshold, which accepts a score up to 1e-10 under the threshold. The field and nested-model gates in FieldComparator, the List[StructuredModel] pair count and recursion gate, the non_matches and field_comparisons collectors, the list item sub-field classifier, EvalResult.matched, HungarianMatcher.calculate_metrics and the evaluator_format fallback metrics all used a bare >=. A score of 0.7 + 0.1 (0.7999999999999999) against 0.8, such as the Laptop pair in threshold-gated-evaluation.md, was an FD at those gates and a TP on a List[str] element. Route every gate through ThresholdHelper.is_above_threshold. A score inside the tolerance now counts as a TP, keeps its score instead of being clipped to 0.0, and opens a list pair for field-by-field evaluation. Scores further under the threshold are unchanged. HungarianMatcher imports the helper inside calculate_metrics, so stickler.algorithms does not load the evaluator package at import time. Fixes #417 * fix(417): use the tolerant test in binary_compare and the field configs BaseComparator.binary_compare, ComparisonInfo.compare and ComparableFieldConfig.compare still used a bare comparison, so 0.7 + 0.1 against 0.8 was (0, 1) from binary_compare and was clipped to 0.0 by the field configs. They now go through ThresholdHelper, as does the unused StructuredModel._calculate_object_level_metrics. binary_compare imports the helper inside the method, like HungarianMatcher.calculate_metrics. Add a Meeting a Threshold section to thresholds-and-metrics.md and link it from each page that states the >= rule. Correct the Good Match Laptop scenario, where name scores 0.4 and is an FD inside a TP pair, and the algorithms README note on unordered_list_metrics. The CHANGELOG entry names the new gates and the two thresholds that keep an exact comparison. * docs(417): regenerate the threshold gating example from a real run The Result Structure block and the Unmatched Items scenario in threshold-gated-evaluation.md did not match what the page's own example produces. With three products on each side, Hungarian matching pairs Cable with New Product as an FD at 0.133, so there is no FN or FA, and the Mouse pair scores 0.6725. Show the example inputs, replace the block with the real counts and non_matches, retitle the heading over the 0.7999999999999999 pair, and say when an item is left unmatched. The Laptop test now runs the whole example, plus the FN and FA cases. Scope the docstrings in hungarian.py, base.py and the algorithms README to the gates listed in Meeting a Threshold, and use ThresholdHelper.is_below_threshold for the explain() verdict. --------- Co-authored-by: Spencer Romo <sromo@amazon.com> * fix(333): export a from_pydantic() mapping element as an object from_pydantic() declares a mapping as Annotated[Any, BeforeValidator(jsonable_mapping)], which is_mapping_annotation() does not recognise, so to_json_schema() still exported its list items as "string" and the re-imported model rejected its own data. Recognise that wire type in the list export. * docs(333): state the from_pydantic() config spelling and the default_factory limit (#435) * docs(333): state the from_pydantic() export limits, and pin the #435 xfail to ValidationError * fix(report): accept a non-string document identifier The non-matches table escaped doc_id and field_path without converting them first, while the three columns beside them converted. evaluate_dataframe reads doc_id straight off a DataFrame column, so an integer id — ordinary for one read from CSV, parquet or a database — raised and generate_report() returned success=False having written no page at all. Optional[str] on update() is an annotation, not a runtime check, and evaluate_dataframe declares nothing. No issue covers this one; found while reviewing #444. Adds a unit test on the table and an end-to-end regression from a DataFrame carrying an integer doc_id. (cherry picked from commit bccff4356c2225a5eacedeedbb783edcebf4029f) * fix(report): escape the confusion counts in the field performance table tp/fd/fa/fn were written into the table with no escaping and no format spec, unlike the precision/recall/f1 cells beside them, whose :.3f rejects a string by accident. generate_report() publicly accepts a plain dict, so a caller assembling their own metrics — rather than passing a ProcessEvaluation, where these are library-computed ints — could put markup there and have it parsed. The confusion-matrix cell gets the same treatment, though sum() rejects a non-numeric before it is reached. Not reachable from document data, and identical on v1.0.0. Closing it here because #422 fixed the same class one function above in this file, and because a release headlined on stopping a document value running as script should not leave a demonstrated route in the same table. No issue covers these four cells. The regression asserts on what a parser sees — no on* attribute, no script body — rather than on substring absence, since escaping leaves the characters present as inert text. (cherry picked from commit 810bace28ef61cee3f957eccfb55d8cff775d1c2) * docs: say what the U+2028/U+2029 entries actually do json.dumps escapes both under its default ensure_ascii=True, so the two translate entries never fire on today's output. They are defensive depth, not the active guard, and the comment claimed otherwise. (cherry picked from commit b07190cdccc418c3b014f113d96da2e1be36a056) * chore(deps): bump mkdocs-material to 9.7.7 (GHSA-xvg9-69gf-fjrf) Fixes a DOM-based XSS in the search suggestions, affecting >=7.2.0,<9.7.7. The docs site enables the search plugin, and merging this release triggers docs.yml (push to main, filtered to src/**, docs/** and the workflow itself), which would otherwise rebuild and redeploy the public site on the vulnerable version. Scope: the lockfile governs this repo's CI and the docs deploy, since the docs group is a dependency-group rather than an extra. The wheel does carry mkdocs-material, under the `dev` extra and unpinned, so anyone installing stickler-eval[dev] already resolves whatever PyPI serves and is unaffected either way. Taken from #346; that PR's transformers bump is deliberately left out of this hotfix. (cherry picked from commit 1959b2fcaac098894d7b7a65ce9d8c01b2cebcd1) * fix(report): disable pdf.js eval (CVE-2024-4367), and embed a numeric doc_id as a string pdf.js 3.11.174 runs script from a crafted PDF font unless eval is off. Pass isEvalSupported: false to getDocument, the upstream mitigation. The per-document view compares ids as strings, so an integer doc_id from a DataFrame matched nothing and the page kept showing aggregate numbers. _load_individual_results now converts it, matching the tables' str(). Both fixes as specified by vawsgit in the #452 review. * docs(changelog): record the report hardening carried over from #452 * test(report): pin the PDF viewer's only loader call, its reachability and its pdf.js Three tests in a new test_pdf_viewer.py, alongside the existing test_the_pdf_viewer_disables_eval: - the page has exactly one pdfjsLib.getDocument(...) call and it carries isEvalSupported: false. A check for the safe form alone still passes when a second loader is added without the option, e.g. getDocument(u); - the viewer is not embedded without individual_results_jsonl_path; - the pdf.js <script> tag still loads 3.11.174 and has no integrity hash, so the upgrade is a deliberate change. Its failure messages say to invert the integrity assertion then, not delete it. * test(report): cover the doc_id conversion's edge cases Nine tests on _load_individual_results: zero, float and NaN ids become strings; a string id, None and a missing key are left alone; a line that is not an object does not drop the records after it; ids that differ only by type now map to the same string; and every id embedded by generate_report is a string, including one above 2**53. Several guard against a mis-fix rather than the fix: dropping the dict guard, converting None, testing the id for truthiness, or converting only int each pass the existing tests. * test(report): let the truncation test catch escape-then-truncate on the prediction The fixture gave prediction_value the value 'short', so only the ground-truth column could tell truncate-then-escape from escape-then-truncate. Both columns now carry 97 characters and an ampersand, and both are asserted. * docs(changelog): record the report-generation slowdown tracked in #457 Reports generated with individual_results_jsonl_path take longer to write since the script-block escaping: 467 ms against 42 ms at 1.0.0 for 1,000 documents, per #457. Evaluation results are unaffected. * fix(306): accept default_factory on ComparableField (#360) * fix(306): accept default_factory on ComparableField ComparableField forwarded its own `default` to Field() unconditionally, so a caller-supplied `default_factory` collided with it and pydantic rejected the pair. Every collection field was affected, which is the case pydantic's own documentation tells users to write `default_factory` for. Forward `default` only when the caller did not supply a factory. The parameter now defaults to a sentinel rather than None so that an explicitly written `default` is still passed through alongside a factory, letting pydantic raise as it normally would instead of one of the two being dropped here. An omitted `default` keeps its historical None, which the schema generator already reads as a construction-tolerance marker rather than a real default. * docs(306): changelog entry for the default_factory fix Recorded under [Unreleased] per the PR checklist, since the accepted argument set is user-visible. * fix(306): keep default_factory=None from turning a field required The guard added for #306 tested for the KEY, not its value: if "default_factory" in clean_field_kwargs: `None` is pydantic's own signature default for `default_factory`, so a caller forwarding kwargs through a wrapper or a config-driven builder can pass it explicitly without meaning anything by it. Read as "a real factory was supplied", it dropped our own default, and a field that was optional with `None` became required: ComparableField(default_factory=None, comparator=ExactComparator()) before is_required=False default=None N().note = None after is_required=True default=PydanticUndefined N() -> ValidationError: note Field required Checking the value says what the branch actually means: it exists because a real factory conflicts with our default, and `None` is not a real factory. * fix(306): export a factory's value, not PydanticUndefined Both exporters read `FieldInfo.default`, and neither knew about factories. They could not have: on `dev` a `default_factory` field dies at class definition, so these paths were unreachable until #306 made them reachable. `to_stickler_config()` wrote `PydanticUndefined` through verbatim, which is not serialisable, from a method whose whole purpose is producing a config you can write to a file: json.dumps(cfg) -> TypeError: Object of type PydanticUndefinedType is not JSON serializable and the in-process round trip rebuilt the field as required, so `M2(name='a')` raised `ValidationError: tags Field required`. `to_json_schema()` failed the same way but quietly: the default vanished, and `from_json_schema()` rebuilt `tags` as `None` rather than `[]`, so the failure surfaced later at the first `.append()`, away from its cause. Both now go through one helper. For `list`, `dict` and `set` it calls the factory and exports the value it produces, which round-trips and is what a reader expects; any other factory leaves the key out rather than being invoked, since a caller's callable could read a clock or a database and an export should not run it. A set is exported as a list. Exporting the set itself reproduces the first failure above one value type over, and `List[str] = ComparableField(default_factory=set)` is legal: json.dumps(M.to_stickler_config()) -> TypeError: Object of type set is not JSON serializable JSON has no set, and the factory is the builtin called with no arguments, so the value is always empty and the conversion is unambiguous. * docs(306): record the exporter half of the default_factory fix The entry described the field accepting a factory and stopped there, but the two exporters changed as well and both are user-visible: a config that would not serialise now does, and a schema round trip returns `[]` where it used to return `None`. * fix(306): export a factory default on List[StructuredModel] fields Both exporters' list-of-models branches skipped resolve_exportable_default, so subs: List[Sub] = ComparableField(default_factory=list) exported no default and rebuilt as None through model_from_json and from_json_schema. * fix(306): give the unset default a readable repr in the signature * fix(306): export mapping fields as objects and share the default export * test(306): arm the identity factory after the class is built On Python < 3.13, pydantic's inspect.signature(factory) at class definition reaches inspect._signature_is_builtin, which tests `obj in (type, object)` and so calls the factory's __eq__. The trap fired before the export ran, failing the 3.10, 3.11 and 3.12 CI jobs. Arm it once the class exists so the test checks only the export's identity match. * fix(306): export Annotated list factories; state default + default_factory; mark the mapping export Breaking - _exports_as_container strips Annotated as well as Optional (ConfigurationHelper.strip_annotation_wrappers), so Optional[Annotated[List[...], ...]] = ComparableField(default_factory=list) exports "default": [] and rebuilds as [] through both exporters, not None. - default=... beside default_factory mirrors pydantic's Field: ignored, the field is optional. README, docstring and CHANGELOG now say so instead of claiming every pairing raises; a test pins it against pydantic. - The mapping-export CHANGELOG entry moves to Changed and is marked Breaking, as the matching #349 export-type change is. - model-export.md states how a Dict field and a default_factory export and round-trip. * fix(306): keep Optional list and mapping fields nullable through to_stickler_config A Stickler config has no nullable flag; model_from_json() widens a field to Optional only when its default is None. Exporting a factory's [] or {} (or a literal empty one) on an Optional field therefore rebuilt it non-nullable, rejecting the None the original accepts. dev exported no default, so this regressed with the factory export. - to_stickler_config() writes no empty [] / {} default on a nullable field (Annotated stripped); it rebuilds with None, which scores the same. to_json_schema() keeps the default: its "null" type already round-trips. - model_from_json() widens a list_structured_model field with a None default to Optional, as the primitive path does (#149); it rebuilt as List[Model] and rejected None, on dev too. - Round-trip test over Optional[Annotated[List[str]]], Optional[Annotated[List[Model]]], Optional[List[int]], Optional[Dict[str, int]]: both rebuilt models accept None and score all 16 unset/None/empty/ value pairs as the original. - Docs: model-export.md states the Optional rule; CHANGELOG scopes the List[Dict] "string" note to to_json_schema(); README names both default=... and default=PydanticUndefined as accepted beside a factory. * fix(306): keep a non-Optional List[Model] non-nullable over repeated config round trips The list-of-models branch of to_stickler_config() did not write a literal default, so the first rebuild's `[]` went missing in the second export and model_from_json()'s new None-default widening made the field Optional. - Write an empty literal `[]` there, as field_to_stickler_config() does. A non-empty literal holds model instances, which are not JSON, so it is still not exported (include_literal=True would break json.dumps()). - The nullable check reuses is_optional_union(unwrap_annotated(...)). - Correct the docstring: the JSON Schema rebuild accepts None because JsonSchemaImporter widens every non-required field, not because "null" is in the exported type. - Tests: double config round trip of List[Model] with a factory and with a literal [] stays non-nullable; a hand-written non-required list_structured_model accepts None and a required one stays List[Model]. - Docs: model-export.md and CHANGELOG say the Optional rule covers empty defaults only, and that the rebuilt default is None (model_dump() shows null); dynamic-models.md states model_from_json()'s None-default widening. * docs(306): scope the config nullability rules to what they cover - dynamic-models.md: the None-default widening applies to primitive and list_structured_model fields; a structured_model field is never widened. - model-export.md and CHANGELOG: the Optional rule covers an empty list or mapping default only (`""` is written). A List[Model] default that is not written (a non-empty literal, a tuple, a factory other than list, dict or set) rebuilds as Optional with a None default, Optional original or not; None scores the same as []. - json_schema_field_converter.py docstring: "as before #306", not "as on dev". --------- Co-authored-by: Spencer Romo <sromo@amazon.com> * docs: correct the mean_score docstring and the [Plain, NoteSM] table row (#249, #338) (#403) * docs(249): stop promising mean_score for leaves under list parents The _accumulate_field_metrics docstring said mean_score is recorded at every node, "including leaves under list parents". It is not: those leaves carry CM counts only, which the user docs and tests already state. Reword the docstring to match. No behaviour change. Refs #249 (per-leaf scores for list children remain open, post-1.0). * docs(338): split the [Plain, NoteSM] row by annotation The element-gate table is headed with a bare Optional[List[Any]], but its [Plain, NoteSM] vs [Plain, Note2SM] row was measured with a declared comparator. Bare, the pair scores 0.0 under the list-wide gate and 0.5 now, because the bare annotation refuses the Plain pair on its own ([Plain] vs [Plain] scores 0.0), not because of the cross-class rule. Split the row into bare and declared cases in comparison_helper.py and the test docstring. The released 1.0.0 CHANGELOG section is left as is; an Unreleased entry corrects it. No behaviour change. Closes #338. * docs(249,338): fix claims the first two commits left wrong - `_accumulate_field_metrics`: list-of-StructuredModel element fields arrive under `fields`, not `nested_fields`; compare_with no longer emits `nested_fields` (its emitter went in ad19ac8). Note that only a finite score is summed. - bulk-evaluation.md and understanding-results.md said compare_with "only emits the score at the list parent". An object node inside a list element is scored too (`items.addr` gets a mean_score); only the leaves are not. - CHANGELOG: move the #338 correction from `### Fixed` with a `**Documentation:**` prefix to a `### Documentation` section, the heading earlier releases use. Refs #249, #338 * docs(249,338): address review on #403 - Guides: leaves and primitive lists anywhere inside a List[StructuredModel] element have no mean_score, and every path inside an element counts only pairs that met the match threshold (a pair below it emits no element fields). - _accumulate_field_metrics docstring: same scope, replacing "leaves under a list parent". - _ClassGatedComparator and test-class docstrings: both [Plain, NoteSM] rows enforced the cross-class rule under the list-wide gate (bare fd=2). - Pin the bare row: [Plain] vs [Plain] = 0.0, bare [Plain, NoteA] vs [Plain, NoteB] = 0.5 (tp=1, fd=1). - Fix the two surviving "emits only at the list parent" comments in test_bulk_structured_model_evaluator.py. - CHANGELOG: Unreleased Documentation entry for the mean_score guide fix. * docs: list the paths inside a list element that get mean_score Inside a List[StructuredModel] element, only the element's own object and List[StructuredModel] fields (items.addr, items.parts) carry a mean_score, and each document's value is the first matched element pair's score. Every other path inside an element, including objects two or more levels down (items.addr.geo), has confusion-matrix counts only. Fix the CHANGELOG, both guides and the _accumulate_field_metric…
Pull Request
Issue Reference
Refs #349 (parts B and C).
Not in this PR: part A is #407, the
List[Dict]row is #405, and the singularDictrow is left to #360, which already exports a mapping field as an object on both paths.Description of Changes
to_json_schema()andto_stickler_config()fell back to"string"/"str"for any annotation missing from their type tables, and the guard meant to stop a nested model reaching that fallback checkedisinstance(field_type, type), which is False forUnion[Card, Bank]. For the shapes below, each exporter now writes a type its importer reads back as one that holds the same data, or raises:BaseModel, or a list of them{"type": "object"}/"dict"(List[dict]for a list), re-imported asdictwith the declared comparator, threshold, weight and clipList[List[Dict]]List[List]Union[Card, Bank],Union[Plain, str]), also as a list element or insideOptional/AnnotatedValueErroron both exportersList[List[Card]])ValueErroron both exportersChanges Made
structured_model.py: the StructuredModel guard moves into_refuse_scalar_export(), which stripsOptionalandAnnotatedat every level and also refuses a union with a model arm and a StructuredModel inside a nested list. Into_json_schema(), a list of lists or of plain models still goes through the primitive list branch, and itsitemsis then replaced by_json_type_schema()(nested arrays, objects for mappings and plain models). Scalar elements, scalar unions and mapping elements are untouched. Into_stickler_config(), a list of plain models is writtenList[dict]; it wasList[<ClassName>], whichmodel_from_json()refused withUnknown type.json_schema_field_converter.py:field_to_property()andfield_to_stickler_config()call that guard, and write a plain model as"object"/"dict".tests/structured_object_evaluator/test_export_roundtrip_shapes.py, 45 tests.docs/docs/Advanced/model-export.md: one paragraph under the "at a glance" table naming what these shapes export as, what is not kept, and what raises.CHANGELOG.md: one**Breaking:**entry under[Unreleased]/ Changed.Why These Changes Are Needed
The issue's model, one field per model so the union does not stop the others.
e403b9bisdev,8ade791is this branch; "loads" means the re-imported model accepts the issue'sDATAvalue.to_json_schema()on devto_stickler_config()on devchild: Plainstring, ValidationErrorobject, loadsstr, ValidationErrordict, loadseither: Union[Card, Bank]string, ValidationErrorValueErrorstr, ValidationErrorValueErrornested: List[List[float]]string, ValidationErrorarrayofnumber, loadsList[List], loadsmeta: Dict[str, Any]string, ValidationErrorstr, ValidationErrorrows: List[Dict[str, str]]string, ValidationErrorList[Dict], loadskid: Cardobject, loadsstructured_model, loadsfield_to_property()on the issue's C table:Union[Card, Bank]went from{"type": "string"}toValueError,Plainfrom"string"to"object", andCardstill raises. The schema-only loop from part C (from_json_schema(S).to_json_schema()with the two-armanyOf) wrote"string"on dev and then could not reload{"iban": "DE89"}; it now raises at the export.List[List[Dict[str, str]]], which the #405 review pointed here, now round-trips on the JSON path and scores the same (0.9706before and after).I also exported 40 annotations on both trees and compared the exported
type/itemsand whether the re-import loads a sample value. 11 changed: four plain-model spellings (Plain,Optional[Plain],List[Plain],List[Optional[Plain]]), four lists of lists, and three unions with a model arm, which now raise. The other 29 are unchanged, including every mapping spelling, every scalar (date,Decimal,UUID,Enum,Literal,Any,bytes),Card,List[Card],List[Dict[str, str]],Union[str, int],List[Union[str, int]],TupleandSet.Two choices worth flagging:
BaseModelexports as an object, not a raise. The acceptance list asks the guard to cover it. One403b9b, raising there fails 10 tests inTestTheExportedConfigurationMatchesTheEngine, which pin thatto_json_schema()reports the comparator the engine uses for a plain-model field. The engine scores a plain model the way it scores a mapping (is_object_grade_annotation), so a free-form object reloads the data and scores the same, which the tests check. Its own field types are not exported. If you would rather it raise, it is a small change plus those 10 tests.anyOfofCard.to_json_schema()andBank.to_json_schema()re-imports asUnion[Card, Bank]and scores the same. A model inside a nested list would also need importer work: a nested array ofCard.to_json_schema()re-imports asList[List[DynamicModel]], withoutCard's name or settings. The Stickler config has no type for either (itsList[List]re-scoredList[List[Card]]from0.9857to0.9706on dev), so the JSON path raises too, to keep one rule for both exports. AnanyOfexport for the union can follow if you want it.Testing
signal.SIGALRM, details below)Windows, Python 3.12.5,
uv sync --frozen --extra llm,pytest tests -n 6.inspect.getfile(stickler)pointed at the tree named in each row.e403b9b8ade791test_export_roundtrip_shapes.py(45)The 6 failures are the same on both:
test_realistic_deep_nesting.py,AttributeError: module 'signal' has no attribute 'SIGALRM'.On dev, the new tests fail for the reported reasons: 22 because nothing raised (nine union spellings and the nested-model case on both exporters, the schema-only loop,
field_to_property()); 6 because the config wroteList[Plain], whichmodel_from_json()refuses; 2 withValidationErroron the re-imported model; and 8 type assertions on"string"/"str"/List[Plain]. The 7 that pass on dev are guards: the JSON re-import resolves the same comparator, threshold, weight and clip for each of the five fields (the extensions already survived; only the type was wrong), the config still writesList[List]for a list of lists (the documented limit), andfield_to_property()still refuses a bareStructuredModel.The round-trip test has one value wrong in every field; the original and both re-imports give the same field scores and confusion matrix.
test_value_types_are_not_exportedpins the documented limit (a plain model withn: intcoerces"5"; the re-importeddictkeeps"5").ruff checkandruff format --checkpass on the three changed Python files;ruff check .reports the same 16 findings on both trees, all inexamples/.mkdocs buildsucceeds on both trees with the same 9 warnings.Reviewers
@sromoam
Checklist
CHANGELOG.mdentry added under[Unreleased], or not needed becausenothing user-visible changed (see RELEASING.md)
Additional Notes
default_factory=listdefault on both paths, because the new list shapes share the primitive list branch.ComparableField(child: Optional[Plain] = None) exports nox-aws-stickler-*keys, so it re-imports with the importer's defaults (ExactComparatorat1.0) and a one-of-two-wrong pair scores0.0instead of0.5. On dev this export could not reload the data at all. Same cause as the bare-field note in fix(333): export a List[Dict] element as an object so the schema loads its own data #405 (Comparator, threshold and clip resolve differently on the JSON Schema and Stickler-config paths than on the Python path, so #300 and #316 landed on one entry point each #348).dict, which the engine scores slightly differently there:List[List[Plain]]went from0.9762to0.9773in my test pair on both paths (the config path already did this on dev).List[Union[Dict, str]](the other shape the fix(333): export a List[Dict] element as an object so the schema loads its own data #405 review pointed here) and scalar unions such asUnion[str, int]still export as"string";to_stickler_config()still writesList[Optional[X]]asList[X]and a list of lists without its inner type.By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.