Skip to content

fix(333): export a List[Dict] element as an object so the schema loads its own data - #405

Merged
sromoam merged 14 commits into
devfrom
fix/333-list-dict-export
Oct 30, 2026
Merged

sromoam merged 14 commits into
devfrom
fix/333-list-dict-export

Conversation

@sromoam

@sromoam sromoam commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #333.

The bug

to_json_schema() exported the element of a List[Dict[...]] field as items: {"type": "string"}, so from_json_schema() rebuilt it as List[str] and the re-imported model rejected the data the original accepted.

class M(StructuredModel):
    ld: List[Dict[str, str]] = ComparableField(threshold=0.9)

R = StructuredModel.from_json_schema(M.to_json_schema())
R(ld=[{"a": "x", "b": "y"}])
# dev: ValidationError: ld.0 Input should be a valid string [type=string_type, input_value={'a': 'x', 'b': 'y'}]

Measured on dev (d1f0f80): re-imported annotation Optional[List[str]], original scores 0.5, the re-imported model cannot load the data.

Why the clip half is not changed

The issue's second defect (x-aws-stickler-clip-under-threshold: false in the export) is already correct on dev since #316. That value is what the engine actually uses: a list of mappings is object-grade, so clipping defaults off and a partly correct element keeps its credit. The issue reasoned that, once items was fixed, the field would come back as a primitive list with clipping off. With items: {"type": "object"} it comes back as List[dict], which is object-grade too, so false is the right value.

The issue's suggestion (keep the amendment out of the export, so it writes true) would now make the export wrong. Measured on this branch by setting the exported key to true by hand: the re-imported field scores 0.0 where the original scores 0.5. Guard tests pin the exported clip to the resolved clip for every field.

The change

In the list branch of to_json_schema(), an element that ConfigurationHelper.is_mapping_annotation accepts (dict, Dict[...], the Mapping family, Annotated around any of them) exports as free-form {"type": "object"}, or ["object", "null"] for an optional element. The importer already reads that as dict. The same applies to the type from_pydantic() declares a mapping as, Annotated[Any, BeforeValidator(jsonable_mapping)], which is_mapping_annotation does not accept (StructuredModel._is_mapping_element). to_stickler_config() writes a mapping element as List[Dict] (List[Optional[Dict]] for an optional element); on a from_pydantic() model it writes List[Any], so a reloaded config still scores a malformed prediction instead of rejecting it. Both exports carry the comparator, threshold, weight and clip from get_comparison_info() for every mapping list, declared or not. A declared ComparableField whose annotation resolves only at model_rebuild() now exports ANLS* with clip off, what the engine scores with, instead of Levenshtein with clip on.

Before and after

Every list element shape the exporter handles was exported on both trees and diffed property for property (34 shapes). Only mapping elements changed. A wider run (28 shapes, 10 declaration styles, 3 placements, as StructuredModel and through from_pydantic(), 1,344 cases, both export formats, re-imported and scored) on dev 4a6ef00 and this branch found no case that works on dev and fails here, and no changed score:

Field annotation items on dev items on branch Re-import loads original data
List[Dict[str, str]], List[Dict[str, Any]], List[dict] "string" "object" dev no, branch yes
List[Mapping], MutableMapping, OrderedDict, DefaultDict, Counter "string" "object" dev no, branch yes
List[Annotated[Dict[str, str], ...]] "string" "object" dev no, branch yes
Optional[List[Dict]], list[dict[str, str]] | None "string" "object" dev no, branch yes
List[Optional[Dict]], List[Dict | None] ["string", "null"] ["object", "null"] dev no, branch yes
from_pydantic() model with List[Dict[...]] / List[Optional[Dict]] "string" / ["string", "null"] "object" / ["object", "null"] dev no, branch yes
user-written Annotated[Any, BeforeValidator(jsonable_mapping)] element "string" "object" dev no, branch yes
List[str/int/float/bool/date/bytes/Any/Enum/Literal], List[Optional[str]], List[Union[str, int]], List[List[...]], List[Model], List[BaseModel], List[Union[Dict, str]], Dict and Mapping fields unchanged unchanged unchanged

For each changed shape declared with ComparableField, in default, explicit-clip and explicit-no-clip variants (39 cases): the re-imported field resolves the same comparator, comparator config, threshold, weight and clip, and field and overall scores are identical. Also checked: explicit ExactComparator, ANLSStarComparator(leaf_threshold=0.8), weight 3.0, a List[Dict] inside a nested model and inside a List[Model] element (full confusion matrix identical), and that re-exporting the re-imported model gives the same property.

Docs

docs/docs/Advanced/model-export.md says what both exports write for a list of mappings and what survives the round trip, and states the limits:

CHANGELOG entry under Fixed.

Tests

tests/structured_object_evaluator/test_list_of_mapping_export.py: 38 tests. With the from_pydantic() fix reverted, its two tests fail. #360, now on dev, fixed the default_factory export this PR used to document as a #435 limit, so that strict xfail is now an ordinary test (the default survives the config, and the config serializes with json.dumps).

Full suite

Python 3.12, stickler imported from this branch's checkout (checked with inspect.getfile(stickler)), pytest -n auto: 4063 passed, 13 skipped, 1 xfailed, 0 failed, with current dev merged in. ruff check src tests and docs/check_links.py clean.

Follow-ups found (not changed here)

`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.
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.
@sromoam sromoam added this to the 1.0.1 (Minor) milestone Oct 16, 2026
@sromoam
sromoam requested a review from vawsgit October 16, 2026 15:29
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-30T16:30:18+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-30T16:26:32+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

The table below shows findings by scanner, with status based on severity thresholds and dependencies:

  • Severity levels:
    • Suppressed (S): Findings that have been explicitly suppressed and don't affect scanner status
    • Critical (C): Highest severity findings that require immediate attention
    • High (H): Serious findings that should be addressed soon
    • Medium (M): Moderate risk findings
    • Low (L): Lower risk findings
    • Info (I): Informational findings with minimal risk
  • Duration (Time): Time taken by the scanner to complete its execution
  • Actionable: Number of findings at or above the threshold severity level that require attention
  • Result:
    • PASSED = No findings at or above threshold
    • FAILED = Findings at or above threshold
    • MISSING = Required dependencies not available
    • SKIPPED = Scanner explicitly disabled
    • ERROR = Scanner execution error
  • Threshold: The minimum severity level that will cause a scanner to fail
    • Thresholds: ALL, LOW, MEDIUM, HIGH, CRITICAL
    • Source: Values in parentheses indicate where the threshold is set:
      • global (global_settings section in the ASH_CONFIG used)
      • config (scanner config section in the ASH_CONFIG used)
      • scanner (default configuration in the plugin, if explicitly set)
  • Statistics calculation:
    • All statistics are calculated from the final aggregated SARIF report
    • Suppressed findings are counted separately and do not contribute to actionable findings
    • Scanner status is determined by comparing actionable findings to the threshold
Scanner Suppressed Critical High Medium Low Info Actionable Result Threshold
bandit 0 6 0 0 6574 0 6 FAILED MEDIUM (global)
cdk-nag 0 0 0 0 0 0 0 PASSED MEDIUM (global)
cfn-nag 0 0 0 0 0 0 0 MISSING MEDIUM (global)
checkov 0 0 0 0 0 0 0 PASSED MEDIUM (global)
detect-secrets 0 1 0 0 0 0 1 SKIPPED MEDIUM (global)
grype 0 0 0 0 0 0 0 MISSING MEDIUM (global)
npm-audit 0 0 0 0 0 0 0 PASSED MEDIUM (global)
opengrep 0 0 0 0 0 0 0 MISSING MEDIUM (global)
semgrep 3 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Top 4 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py
1 tests/test_readme_examples.py

Detailed Findings

Show 7 actionable findings

Finding 1: SECRET-HEX-HIGH-ENTROPY-STRING

  • Severity: HIGH
  • Scanner: detect-secrets
  • Rule ID: SECRET-HEX-HIGH-ENTROPY-STRING
  • Location: tests/comparators/test_anls_leaf_semantics.py:89

Description:
Secret of type 'Hex High Entropy String' detected in file 'tests/comparators/test_anls_leaf_semantics.py' at line 89

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Finding 3: B108

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B108
  • Location: tests/comparators/test_anls_leaf_semantics.py:210-212

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

uuid.UUID(int=1),
            pathlib.Path("/tmp/x"),
            b"bytes",

Finding 4: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1363-1369

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

def published_label(node: dict, section: str, object_lists: set) -> str:
            counts_objects = eval(  # noqa: S307
                cond.group(1),
                {},
                {"data": node, "section": section, "OBJECT_LISTS": object_lists},
            )
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 5: B307

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B307
  • Location: tests/structured_object_evaluator/test_rollup_node_semantics.py:1368-1370

Description:
Use of possibly insecure function - consider using safer ast.literal_eval.

Code Snippet:

)
            return eval(unit.group(1), {}, {"counts_objects": counts_objects})  # noqa: S307

Finding 6: B102

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B102
  • Location: tests/test_readme_examples.py:55-57

Description:
Use of exec detected.

Code Snippet:

with contextlib.redirect_stdout(out):
        exec(code, namespace)
    prints = [line for line in code.splitlines() if line.startswith("print(")]

Finding 7: B310

  • Severity: HIGH
  • Scanner: bandit
  • Rule ID: B310
  • Location: .ash/ash_output/converted/jupyter/examples__notebooks__Strands_Evals_FCC_Live_Agent__ipynb-converted.py:83-85

Description:
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.

Code Snippet:

)
with urllib.request.urlopen(url, timeout=60) as resp:
    rows = [item["row"] for item in json.load(resp)["rows"]]

Report generated by Automated Security Helper (ASH) at 2026-10-30T16:30:20+00:00

json_element_type = PYTHON_TYPE_TO_JSON_TYPE.get(
element_type, "string"
)
property_schema = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A List[Dict[str, str]] field declared with a plain Field(default_factory=list) (no ComparableField) still scores differently after the round trip. The export writes only {"type": "array", "items": {"type": "object"}} with no x-aws-stickler-* keys, because _extract_field_metadata finds no comparison metadata. The importer then defaults the field to ExactComparator, threshold 1.0, clip True. The original resolves ANLSStarComparator, threshold 0.7, clip False. Measured on this branch (/tmp worktree of aad6ebd): GT [{"a":"x","b":"y"}] vs pred [{"a":"x","b":"z"}] scores 0.5 on the original and 0.0 on the re-imported model. Re-exporting the re-imported model also differs from the first export. The tests only cover ComparableField-declared fields. Either export the resolved comparison info for this branch, or make the importer resolve the same default for object items that get_comparison_info resolves for List[dict].

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks. Fixed in 5e17922. When a list-of-mappings field declares nothing, both exporters now write the comparator, threshold, weight and clip the engine resolves (ANLS*, match_threshold, no clip). Your pair now scores 0.5 before and after the round trip on both paths, and re-exporting the re-imported schema gives the same properties. The config path had the same gap: model_from_json() refused the bare field for having no comparator, and it now loads. Scalar lists keep the importer defaults; that divergence is #348.

# the importer reads back as `dict`. Falling through to "string"
# re-imported `List[Dict[...]]` as `List[str]`, which then
# rejected the data the original accepted (#333).
if ConfigurationHelper.is_mapping_annotation(element_type):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fix covers only an element that is always a mapping. The same defect remains for List[Union[Dict[str, str], str]]: is_mapping_annotation returns False for a multi-arm union, so the element exports as {"type": "string"}, re-imports as List[str], and the re-imported model raises ValidationError: Input should be a valid string on a dict element the original accepted (measured on this branch). List[List[Dict]] also takes this branch and exports its inner element as "string". A more general change is to map unmapped element types to a type the importer reads back permissively (an anyOf, or omitting type) instead of defaulting to "string", or at least to track these shapes in a follow-up issue next to #349.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: both still export "string", same as on dev. #414 covers List[List[Dict]]. List[Union[Dict, str]] needs arm-by-arm export in the code #414 is reworking, so I've kept it out of this PR, named both shapes as known limits under #349 in model-export.md, and added the union case to #426.

rows: List[Mapping[str, str]] = ComparableField()

config = WithMapping.to_stickler_config()
assert config["fields"]["rows"]["type"] == "List[Mapping]"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test pins a broken round trip as expected behaviour. to_stickler_config() writes List[Mapping] for a List[Mapping[str, str]] field, and model_from_json() then raises ValueError: Unknown type: Mapping on the config the same library produced. A fix should normalise a mapping element to Dict in to_stickler_config() (the importer already accepts List[Dict]). If that is out of scope, link a tracking issue here so the test is understood as a known gap and not a contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, that test was pinning a bug. to_stickler_config() now writes every mapping element (Mapping, MutableMapping, OrderedDict, Counter, dict) as List[Dict], and the test asserts the round trip loads and scores the same. Fixed in 5e17922.

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs changes

The suite passes on aad6ebd. Three blockers:

  1. structured_model.py:1912. A List[Dict] field declared with a plain pydantic Field exports object items with no x-aws-stickler-* keys. The re-imported field resolves different comparator, threshold, and clip defaults, so the same pair scores 0.5 before the round trip and 0.0 after. #405 (comment)
  2. structured_model.py:1906. List[Union[Dict, str]] and List[List[Dict]] still export items as "string". The re-imported model then raises ValidationError on data the original accepts. Fix this or track it explicitly with #349. #405 (comment)
  3. test_list_of_mapping_export.py:114. model_from_json(to_stickler_config()) raises ValueError: Unknown type: 'Mapping', and this test asserts that failure instead of normalising the element to Dict. #405 (comment)

…ment 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).
@sromoam

sromoam commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @vawsgit, all three are addressed in 5e17922:

  1. An undeclared List[Dict] now exports its resolved comparator, threshold, weight and clip on both paths, so it scores the same after the round trip.
  2. to_stickler_config() writes every mapping element as List[Dict], and the test asserts the round trip.
  3. List[List[Dict]] is handled by fix(349)!: export plain models and nested lists, refuse model unions #414, and List[Union[Dict, str]] is tracked in Schema export: a model inside a container union arm, dict or tuple still exports as a scalar or free-form object #426. The docs name both as current limits.

Full suite: 2877 passed, 2 skipped, 1 xfailed.

@sromoam
sromoam requested a review from vawsgit October 19, 2026 16:56
sromoam pushed a commit that referenced this pull request Oct 19, 2026
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)
# Conflicts:
#	src/stickler/structured_object_evaluator/models/structured_model.py
@sromoam
sromoam requested a review from digalaviz as a code owner October 19, 2026 21:40
# Every mapping element is written `Dict`, the spelling
# `model_from_json()` reads. `__name__` wrote
# `List[Mapping]` or `List[Counter]`, which it refused.
field_config["type"] = "List[Dict]"

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking — suggest a follow-on issue. Pre-existing: origin/dev (a1a58ce) already writes List[Dict] for this field and raises the same ValidationError on the None element, so this PR does not change it. A one-clause caveat in model-export.md (Optional elements keep nullability only on the JSON Schema path) would also close it.

A List[Optional[Dict]] element is written as List[Dict], so the to_stickler_config() round trip rejects the original data. element_type here has had Optional stripped by strip_annotation_wrappers, and this branch hardcodes "List[Dict]" without the nullability that to_json_schema() keeps via element_is_nullable.

Measured on 84b890b (tree /tmp/pr405/src, checked with inspect.getfile): oi: List[Optional[Dict[str, str]]] = ComparableField() then model_from_json(M.to_stickler_config())(oi=[{"a": "x"}, None]) raises ValidationError: oi.1 Input should be a valid dictionary. The CHANGELOG ("any mapping (Dict, dict, Mapping, optionally Optional)") and model-export.md ("Both re-import as List[dict] ... so it scores as the original did") both claim this round trip works. Either write the nullable element here (this branch already owns the type string) or narrow both docs to the JSON Schema path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e6163d7 rather than narrowing the docs. to_stickler_config() now writes List[Optional[Dict]] for an optional mapping element, using element_is_nullable the way to_json_schema() does. On b8efbdc, oi: List[Optional[Dict[str, str]]] = ComparableField() round-trips through model_from_json(M.to_stickler_config()) and loads [{"a": "x"}, None]. test_stickler_config_keeps_an_optional_element_nullable checks that the re-imported model scores the same as the original. b8efbdc corrects both docs: the field re-imports as List[Optional[dict]] from the JSON Schema and List[Optional[Dict]] from the config, not List[dict]. The scalar version of this gap (List[Optional[str]] exports List[str] on the config path and rejects None) is pre-existing and out of this PR's shape, so I added it to #435.

"""No ``ComparableField``, so the engine's defaults are what must survive."""

match_threshold = 0.8
rows: List[Dict[str, str]] = Field(default_factory=list)

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking — suggest a follow-on issue. Pre-existing root cause: field_to_stickler_config() writes default: PydanticUndefined for every default_factory field on origin/dev too (measured with a bare List[str]). Scores are unaffected.

The bare-field to_stickler_config() round trip that this PR newly enables is lossy for exactly this declaration, and the test does not catch it. field_to_stickler_config() writes "required": False, "default": PydanticUndefined for a default_factory field. Measured on 84b890b: json.dumps(B.to_stickler_config()) raises TypeError: Object of type PydanticUndefinedType is not JSON serializable, and model_from_json(config)() raises rows: Field required where B() succeeds.

Before this PR model_from_json() refused a bare List[Dict] field outright. Now it loads it, as a required field. The test passes only because it scores in-process and never serializes the config or omits the field. Either export default_factory correctly (json_schema_field_converter.py:156), or add json.dumps plus an omitted-field load to test_undeclared_field_roundtrips_its_resolved_comparison.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed in this PR. You're right that it is pre-existing: on origin/dev 0921f4a, a bare tags: List[str] = Field(default_factory=list) writes "default": PydanticUndefined and json.dumps raises TypeError. On b8efbdc the List[Dict] case behaves as you measured: json.dumps raises TypeError, and loading the re-imported model with the field omitted raises rows: Field required. The fix belongs in the shared converter (json_schema_field_converter.py) and covers every default_factory field, not just mapping lists. A json.dumps assertion here would only pin the bug, so I added it to #435 (1.1.0) with this repro rather than special-casing it in this PR.

Scalar lists keep the importer defaults (#348).
"""
metadata = converter._extract_field_metadata(field_info)
if metadata or not ConfigurationHelper.is_mapping_annotation(element_type):

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking — suggest a follow-on issue. Not reproduced; inferred from the code path.

A declared ComparableField returns its raw attributes here, not what the engine resolves. That is correct only when _install_object_grade_comparators already rewrote _comparator_instance at class definition. For a field that hits the read-time last-resort substitution in get_comparison_info (an annotation not resolvable at class definition, which that comment documents), this exports LevenshteinComparator with clip True while the engine scores with ANLS* and clip False. The re-imported field then scores differently. Calling ConfigurationHelper.get_comparison_info(cls, field_name) for every mapping-list field, declared or not, removes the if metadata split and the divergence.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced and fixed in e6163d7. Mapping lists now always export ConfigurationHelper.get_comparison_info(cls, field_name), whether declared or not. The if metadata split is gone, and the stale comparator_config is dropped when the resolved comparator has none.

Measured with rows: "List[_E]" = ComparableField(threshold=0.9), _E = Dict[str, str], model_rebuild(), one wrong key of two:

  • On 84b890b, both exports carried Levenshtein, comparator_config {"normalize": true} and clip on. Both round trips scored 0.95 against 0.5 for the original.
  • On b8efbdc, both export ANLS* with clip off, and original and both round trips score 0.5. test_late_resolved_field_exports_the_engine_comparator covers both paths.

b8efbdc adds this to the CHANGELOG and keeps a surviving declared comparator_config in its original key position. The same divergence still affects late-resolved plain-BaseModel fields ("_P", "List[_P]"). That shape is outside this PR, so I added it to #435.

# `List[Mapping]` or `List[Counter]`, which it refused.
field_config["type"] = "List[Dict]"
metadata = cls._list_export_metadata(
converter, field_name, field_info, element_type

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking — suggest a follow-on issue. Cleanup only; no behaviour change.

field_to_stickler_config() on line 2208 already extracted _extract_field_metadata(field_info) and merged its extensions into field_config. For a declared field this call extracts and merges the same values a second time. Calling it only when the converter produced no comparator would do the same job. Separately, for scope: resolved-metadata export is special-cased to mapping-list elements. A bare Dict field outside a list and bare scalar lists still export importer defaults (#348). Doing this inside the shared converter (_extract_field_metadata / field_to_property) would fix those fields too, without a per-shape helper.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The double extraction is gone as of e6163d7. On the mapping-list branch, _list_export_metadata now calls only get_comparison_info(). Its result replaces the raw attributes field_to_stickler_config() wrote, so _extract_field_metadata is no longer called a second time. Scalar lists still return _extract_field_metadata unchanged. On scope, I agree that doing this inside the shared converter would also cover a bare Dict field and scalar lists. That is #348 (1.1.0), so I kept this PR to the #333 shape.

Comment thread docs/docs/Advanced/model-export.md Outdated
re-import as `List[dict]` with the comparator, threshold, weight and clip the field resolves, declared
or default, so it scores as the original did. The value type is not exported, so the re-imported field
does not coerce its values. A mapping field that is not in a list, and a list whose element is a union
such as `List[Union[Dict, str]]` or another list, still export as a string

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking (docs untrue). "or another list, still export as a string" is not what the PR head does. Since #414 merged into dev (and into this branch via 84b890b), a list of lists exports as nested arrays. Measured on 84b890b (inspect.getfile(stickler) = this checkout): n: List[List[Dict[str, str]]] = Field(default_factory=list) exports {"type": "array", "items": {"type": "array", "items": {"type": "object"}}}, and the re-imported model loads [[{"a": "x"}]]. Line 20 of this same page already says "A list of lists exports as nested arrays", so the two paragraphs contradict each other. Suggested fix: drop "or another list" so the sentence reads "...and a list whose element is a union such as List[Union[Dict, str]], still export as a string". List[Union[Dict, str]] does still export {"type": "string"} and fail to load a dict element, so the rest of the sentence is accurate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e6163d7. I dropped "or another list", so the sentence now reads "...and a list whose element is a union such as List[Union[Dict, str]], still export as a string". That matches line 20 ("A list of lists exports as nested arrays"). b8efbdc also fixes the re-import spelling in the same paragraph: List[dict] / List[Dict] respectively, and List[Optional[dict]] / List[Optional[Dict]] for an optional element. Measured on b8efbdc with inspect.getfile(stickler) pointing at the checkout.

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs changes

All three earlier blockers are resolved on 84b890b. Two are fixed and re-measured: scores are identical before and after the round trip. The third is documented and tracked under #349 and #426, as the earlier review allowed. One blocker remains:

  1. docs/docs/Advanced/model-export.md:214 says a list whose element is "another list" still exports as a string. That is untrue on this head. Since #414 merged, List[List[Dict]] exports nested arrays, and line 20 of the same page says so. Drop "or another list". #405 (comment)

The other 4 inline comments are non-blocking and are suggestions for follow-on issues. The PR description is also stale: it still says "Nothing else in the exporter changes", but to_stickler_config() now changes too.

… 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.
… 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.
@sromoam

sromoam commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @vawsgit. Two commits address the review:

  • e6163d7: drops "or another list" from the string-export sentence (blocking docs fix). to_stickler_config() now writes List[Optional[Dict]] for an optional mapping element. Mapping lists always export get_comparison_info(), so a declared field whose annotation resolves at model_rebuild() exports ANLS* with clip off instead of Levenshtein with clip on. The round trip previously scored 0.95 against 0.5 for the original; it now scores 0.5.
  • b8efbdc: the docs and CHANGELOG state each re-imported spelling (List[dict] / List[Dict], and List[Optional[dict]] / List[Optional[Dict]]). The CHANGELOG records the late-resolved fix. A declared comparator_config keeps its key position.

Out of scope and added to #435 (1.1.0): default_factory exporting PydanticUndefined (pre-existing on dev), scalar List[Optional[str]] losing nullability on the config path, and late-resolved plain-BaseModel fields exporting Levenshtein with clip on. Converter-level resolved export for bare Dict fields and scalar lists stays in #348.

On b8efbdc (inspect.getfile(stickler) = the checkout): full suite 3195 passed, 2 skipped, 1 xfailed. Strands Evals contract suite 776 passed, 1 xfailed, snapshot unchanged.

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs changes

No regressions found. Diffing 2,718 exports between dev and head showed import failures turning into successes and no other change. However, the CHANGELOG claims more than the code delivers in two places (inline):

  1. structured_model.py:1914 A List[Dict] field on a model built with from_pydantic() still exports string items, so the re-imported model rejects its own data.
  2. CHANGELOG.md:143 A bare List[Dict] = Field(default_factory=list) (this PR's BareRows fixture) re-imports as a required field.

Fix both, or narrow the CHANGELOG wording to the cases that work.

# the importer reads back as `dict`. Falling through to "string"
# re-imported `List[Dict[...]]` as `List[str]`, which then
# rejected the data the original accepted (#333).
if ConfigurationHelper.is_mapping_annotation(element_type):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker (the CHANGELOG headline does not hold): the from_pydantic() element type is not recognised as a mapping.

from_pydantic() types a mapping element as Annotated[Any, BeforeValidator(jsonable_mapping)] (_WireDict in auto/builder.py). is_mapping_annotation() rejects that type, so the export still writes items: {'type': 'string'}.

class Invoice(BaseModel):
    invoice_id: str
    rows: List[Dict[str, str]]
M = StructuredModel.from_pydantic(Invoice)
StructuredModel.from_json_schema(M.to_json_schema())(invoice_id='1', rows=[{'a': 'x', 'b': 'y'}])
# ValidationError: rows.0 Input should be a valid string

model-export.md:31-38 calls this export "the supported way", and CHANGELOG line 129 says a List[Dict[...]] field exported by to_json_schema() can now load its own data. Recognise the wire type here, or narrow the claim to StructuredModel-declared fields.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8187b85. The list export now recognises the type from_pydantic() declares a mapping as (Annotated[Any, BeforeValidator(jsonable_mapping)]), so its items export as object (["object", "null"] when optional), nested ones included. Diffing a 26-field from_pydantic() export before and after, only those items changed and the config is identical; the round trip loads the original data and scores the same. to_stickler_config() still writes List[Any] for these, keeping the tolerance for malformed predictions. c7a943a states the two limits in model-export.md: the JSON Schema re-import rejects a non-mapping prediction element rather than scoring it, and an Optional written inside Annotated loses its null.

Comment thread CHANGELOG.md
`model_from_json()` re-imports as written; it wrote `List[Mapping]` or
`List[Counter]`, which `model_from_json()` refused with `Unknown type`. Both
exports now carry the comparator, threshold, weight and clip the field
resolves even when it is declared without `ComparableField`, so it scores as

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker (the claim is inaccurate): a bare List[Dict] field re-imports as required.

The comparator now exported for a bare List[Dict] = Field(default_factory=list), which is this PR's own BareRows fixture, carries default: PydanticUndefined.

class BareRows(StructuredModel):
    rows: List[Dict[str, str]] = Field(default_factory=list)
R = StructuredModel.model_from_json(BareRows.to_stickler_config())
R()           # ValidationError: rows Field required   (BareRows() gives [])
json.dumps(BareRows.to_stickler_config())   # TypeError

Dev refused this config at import time. This PR moves the failure to every document that omits the field, which contradicts "scores as the original did". The root cause is tracked in #435. Fix the exported default, or narrow this sentence and point to #435.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrowed in 6825739 and c7a943a, pointing to #435 (item 9). The CHANGELOG and model-export.md now say a plain Field(default_factory=...) exports no usable default to to_stickler_config(): the config does not serialize with json.dumps, and the field re-imports as required. Fixing the exported default affects every field kind and #435 still has to choose between the factory value and no default, so it stays there. A strict xfail with raises=ValidationError pins it. The JSON Schema path is unaffected: the field re-imports optional and scores the same.

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.
@sromoam
sromoam requested review from harrycav and vawsgit October 29, 2026 17:06

@harrycav harrycav left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed c7a943a (already contains dev 4a6ef00). The fix holds: List[Dict], Optional, List[Optional], Mapping/Counter/DefaultDict, Annotated, aliases, and nesting inside a model and inside List[Model] all round-trip and score the same as the original. 344 exports of unrelated types are byte-identical to dev, and every exported schema passes check_schema. vawsgit's round-3 points: (1) resolved in 8187b85; (2) resolved by narrowing the wording, tracked in #435.

One question before I approve, inline below: whether this should be Breaking. Plus two small CHANGELOG nits.

Comment thread CHANGELOG.md
was a false discovery, false alarm or false negative, so `field_comparisons`
agrees with `non_matches`.

- **A `List[Dict[...]]` field exported by `to_json_schema()` can now load its

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be Breaking (fix(333)!:, under Changed)? The exported items type changes from "string" to "object", as this entry says at L212, and #349 (7faefc0) filed the same kind of export change as Breaking. Also, a late-resolved rows: "List[_E]" = ComparableField(threshold=0.9) scores 0.95 after a config round trip on dev and 0.5 here. I think 0.5 is the right answer, but it is a visible score change. Happy either way if you see it as a plain fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @harrycav. I'd keep it as a fix. On dev the exported schema couldn't load its own data (the JSON path raised ValidationError, and the config path refused List[Mapping]), so nothing could rely on the old "string" output. The 0.95 came from the reloaded model using a different comparator than the original; 0.5 is what the original scores. The entry states both changes plainly (the items type change and the late-resolved 0.5, not 0.95) so a consumer diffing exports knows to expect them.

Comment thread CHANGELOG.md Outdated
it still writes `List[Any]`, which loads the same data. Both
exports now carry the comparator, threshold, weight and clip the field
resolves even when it is declared without `ComparableField`, so it scores as
the original did (`0.5`, not `0.0`, for one wrong key of two) unless the data

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: "0.5, not 0.0" describes an intermediate PR state (aad6ebd). On dev that field either failed to load on the JSON path or was refused at import on the config path; I never saw 0.0 there.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in 3265ee9. The entry now says such a field could not be re-imported before (the JSON Schema path raised ValidationError, and model_from_json() refused it), instead of comparing against an earlier PR state.

Comment thread CHANGELOG.md
[export guide](https://awslabs.github.io/stickler/Advanced/model-export/)
states. A consumer reading the exported schema
sees the `items` type change from `"string"` to `"object"`.
`to_stickler_config()` now writes a mapping element as `List[Dict]`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: List[dict] and list[dict] | None fields now write List[Dict] where dev wrote List[dict]. Both load, but it is a visible change in the config, so it may be worth a clause.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken in 3265ee9. The entry now notes that a dict element, written List[dict] before, is now written List[Dict]. Both load.

@sromoam

sromoam commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

@harrycav, merged current dev (1f1119f). One conflict, in the list branch of to_json_schema(): kept dev's add_exportable_default from #360 and this PR's _list_export_metadata. #360 also fixed the default_factory export this PR documented as a #435 limit, so a9d4510 drops that caveat from the CHANGELOG and model-export.md and turns the strict xfail into an ordinary test. The re-export test now ignores default: an export writes a default_factory default, but the re-imported field holds a plain one, which no export writes. That's true of every list field on dev, so it belongs in #435. Full suite 4063 passed.

@sromoam
sromoam requested a review from harrycav October 30, 2026 16:26

@harrycav harrycav left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, that reasoning holds: the old export couldn't load its own data, and 0.5 matches the original. Nits taken in 3265ee9. Approving.

@sromoam
sromoam dismissed vawsgit’s stale review October 30, 2026 18:36

Superseded by Harry's review.

@sromoam
sromoam merged commit 34867f9 into dev Oct 30, 2026
14 checks passed
@sromoam
sromoam deleted the fix/333-list-dict-export branch October 30, 2026 18:37
sromoam added a commit that referenced this pull request Nov 20, 2026
… 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 &amp;.

* 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…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: List[Dict[...]] exports clip_under_threshold=false, and its items are mistyped as string

3 participants