Skip to content

fix(383): let date, Decimal, UUID, Enum, tuple and set fields reach their comparator - #384

Merged
digalaviz merged 4 commits into
devfrom
fix/383-scalar-dispatch
Oct 15, 2026
Merged

digalaviz merged 4 commits into
devfrom
fix/383-scalar-dispatch

Conversation

@sromoam

@sromoam sromoam commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #383.

On an explicit StructuredModel, a field typed date, datetime, time, timedelta, Decimal, UUID or Enum never reached its comparator. The dispatcher treated only str, int and float as scalars, so these fell through to the mismatched-types case: an identical value scored 0.0 and was counted as a false discovery, and a declared comparator (including DateComparator) was never called. The zero-config path (stickler.evaluate() on a plain pydantic model) was unaffected, because its shadow models convert these values first.

Change

One rule for both readers. comparison_helper.scalar_pair_reaches_comparator decides whether a pair of non-structured values (not a list, dict or model) reaches the field's comparator. Both the dispatcher (compare_with) and compare_field_raw (compare() and the Hungarian cost matrix) use it, so they can't disagree, which #233 requires.

  • A declared comparator is always called. The caller chose it for these values, and it decides what it can score, as it already does for a dict or a plain model. That covers bytes, a custom class, a tuple or set, or a date against its ISO string under DateComparator. ComparableFieldConfig.comparator_explicit carries the existing _comparator_explicit bit.
  • An inferred comparator sees only values it can be trusted with: str/int/float, numbers (Decimal included), related date/time/timedelta/UUID values, and members of related Enum classes. Enum is checked first, because an IntEnum/StrEnum member is also an int/str. Anything else is a mismatch, because an arbitrary object would reach LevenshteinComparator as a near-identical <Foo object at 0x...> repr.

Out of scope: Tuple/Set with an inferred comparator keep their dev behaviour in each reader, tracked in #391. #392 (1.1.0) tracks merging the two readers into one implementation, which is the root cause of their drift.

Breaking, per the CHANGELOG entry:

  • compare() with an inferred comparator for a date against its ISO string, bytes or an arbitrary object goes from 1.0 to 0.0, matching compare_with();
  • with an inferred comparator, IntEnum/StrEnum cross-class or member-against-value pairs become a mismatch;
  • a declared comparator is now called in compare_with() where it used to score 0.0.

Docs

Tests

tests/structured_object_evaluator/test_scalar_field_dispatch.py has 77 tests:

  • identical and different values for each type, and a spy confirming the declared comparator is called;
  • DateComparator and NumericComparator cases;
  • the inferred comparator's strictness: unrelated types, bytes, arbitrary objects, IntEnum classes;
  • declared comparators for bytes, a custom class, a date against its ISO string, and a set-aware comparator;
  • a compare()/compare_with() agreement test over mixed pairs, with inferred and declared comparators.

On dev, 60 of them fail. On the previous head 854fc00, 4 fail: the cases review found.

The full suite passes on Python 3.10, 3.12 and 3.14: 2856 passed, 12 skipped, 1 xfailed, measured with PYTHONPATH pinned to this checkout.

…heir comparator

On an explicit StructuredModel the dispatcher treated only str, int and
float as scalars, so a field typed date, datetime, time, timedelta,
Decimal, UUID or Enum fell through to the mismatched-types case: an
identical value scored 0.0 and counted as a false discovery, and the
declared comparator was never called. Tuple and Set fields hit the same
case, because only list takes the list path.

- Route a pair of related scalars (an explicit type list) to the field's
  comparator. Unrelated types and arbitrary objects stay a mismatch.
- Score two tuples, or two sets, as one value, as stickler.evaluate()
  does, sorting a set first; compare_field_raw does the same so
  compare() agrees with compare_with().
- Treat an empty tuple or set as absent, like an empty list.

Closes #383
@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-15T13:38:29+00:00
  • Time since scan: 3 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-15T13:35:14+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 3 0 0 5784 0 3 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 2 Hotspots

Files with the highest number of security findings:

Finding Count File Location
2 tests/comparators/test_anls_leaf_semantics.py
2 tests/structured_object_evaluator/test_rollup_node_semantics.py

Detailed Findings

Show 4 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: 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 3: B307

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

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 4: B307

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

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

Report generated by Automated Security Helper (ASH) at 2026-10-15T13:38:31+00:00

@sromoam
sromoam requested a review from digalaviz October 13, 2026 19:23
Resolve the conflicts with #381 (NaN as absent): both changes extend the
same null rules, so NullHelper.is_effectively_null_for_primitives and the
_maybe_absent guard now treat NaN and empty tuples/sets as absent, and the
null rule in classification-logic.md and the CHANGELOG keep both entries.
… gaps

- One rule, comparison_helper.comparable_scalar_pair, now decides which
  non-container pairs reach the comparator, for both the dispatcher
  (compare_with) and compare_field_raw (compare and the Hungarian cost
  matrix). Before, compare() scored a tuple against a set, or a date
  against its ISO string, as 1.0 while compare_with() called it a
  mismatch.
- Order sets at any depth (utils.canonical.order_sets, keyed on sorted
  JSON), so a set nested in a tuple or a set of frozensets can no longer
  score identical values apart. Tuples keep their order and type.
- Compare a Decimal with an int or float as numbers.
- Check Enum first, so two IntEnum/StrEnum classes, or a member against a
  bare value, are a mismatch rather than compared as int/str.
- Fix the misnamed tuple-vs-list test and assert compare() too; add a
  compare()/compare_with() agreement test over mixed pairs.

@digalaviz digalaviz 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.

The scalar half of this looks right. I reproduced the date, Decimal, UUID and Enum cases and they behave as described. Checking Enum first is a good catch, since an IntEnum member is also an int, and _related avoids needing a date/datetime pair table. The _maybe_absent guard carrying its own measurement is nice to see.

Requesting changes on the Tuple/Set half, where I hit two reproducible problems. Both are in the inline comments:

  1. Every set/frozenset becomes a tuple before the field's comparator sees it, so a set-aware comparator that worked on dev through compare() now raises TypeError on both readers.
  2. order_sets is not deterministic when two elements share a _json_sort_key, so two equal sets can canonicalize to different tuples and score below 1.0.

Tuple and Set are not among the types #383 names, so leaving them out would be the smallest route to green and keeps this a focused scalar fix. If you would rather keep them, collection comparison probably deserves its own contract and issue.

On the CHANGELOG (CHANGELOG.md:41): the entry sits under ### Fixed without the - **Breaking:** prefix, but it does move results for existing callers. compare() on a date against its ISO string goes 1.0 to 0.0, cross-class IntEnum matching narrows (the entry itself says "where they used to compare as int/str"), and an empty tuple or set now counts as absent. This file marks that class of change breaking elsewhere, in the comparator-threshold and object-threshold entries. The stickler.evaluate() sentence holds for the zero-config shadow-model path; scoping it there would keep it from reading as cover for explicit compare().

The red test (3.10) is not from this PR. The same head SHA passed it at 23.63s on the pull_request run and failed at 41.69s on the push run, against a hard-coded 35s wall clock. A local A/B (two worktrees, n=9 x 2) does show a real 3.6% slowdown on the comparison path, comfortably inside the budget against dev's 22.81s. Happy to share the figures, and the assertion itself looks worth a separate issue.

Comment on lines +237 to +240
if (isinstance(gt_val, tuple) and isinstance(pred_val, tuple)) or (
isinstance(gt_val, (set, frozenset)) and isinstance(pred_val, (set, frozenset))
):
return order_sets(gt_val), order_sets(pred_val)

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 converts every set/frozenset to a tuple before the field's configured comparator sees it, which changes behaviour on a path that worked before.

Measured on 854fc00e against dev 70e9afb, with a set field whose comparator is purpose-built (len(a & b) / len(a | b)):

dev this PR
compare_with 0.0, comparator never called TypeError, receives ('tuple','tuple')
compare() 1.0, receives ('set','set') TypeError, receives ('tuple','tuple')

compare() scored identical sets 1.0 and disjoint sets 0.0 before this change, so this turns a correct result into an unhandled exception mid-run.

There is a separate ordering problem in canonical.py, in my other comment.

Since Set and Tuple sit outside what #383 names, dropping them here is the smallest fix. If they stay, it would help to state the comparator input contract (values arrive as the caller supplied them, coercion belongs to the comparator) and add a test with a set-aware custom comparator.

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, and dropped. Tuple/Set is out of this PR in b88d81b: there's no tuple/set branch, no set ordering, and an empty tuple or set is no longer absent. #391 tracks collection comparison as its own design question.

With a declared comparator (see the reply on :627), values now arrive as the caller supplied them, so your set-aware comparator works in both readers. test_a_set_reaches_a_set_aware_comparator_as_a_set pins it with a Jaccard comparator: {"a","b"} against {"b","c"} scores 1/3 in compare_with() and compare(). With an inferred comparator, tuples and sets keep exactly their dev behaviour in each reader.

Comment thread src/stickler/utils/canonical.py Outdated
Comment on lines +82 to +109
def order_sets(value: Any) -> Any:
"""``value`` with every set, at any depth, replaced by a tuple in fixed order.

For a ``Tuple`` or ``Set`` field scored as one value (#383). A comparator
that reads ``str(value)`` would otherwise score two equal sets apart when
they iterate differently, and a set nested inside a tuple or another set
has the same problem. Elements are ordered by their sorted-key JSON form,
which is defined for mixed and nested elements alike; native ``sorted``
is not (it raises on mixed types and uses subset order for sets).

Tuples and lists keep their order and their type, so a comparator that
reads structure (``BBoxIoUComparator`` on a 4-tuple) still gets a tuple.
Anything else is returned unchanged.
"""
if isinstance(value, (set, frozenset)):
items = [order_sets(item) for item in value]
return tuple(sorted(items, key=_json_sort_key))
if isinstance(value, tuple):
return tuple(order_sets(item) for item in value)
if isinstance(value, list):
return [order_sets(item) for item in value]
return value


def _json_sort_key(value: Any) -> str:
return json.dumps(
to_jsonable_python(value, fallback=str), sort_keys=True, default=str
)

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.

_json_sort_key is not injective, so this order is not fixed when two distinct elements map to the same key. to_jsonable_python(b"a") renders to "a", so b"a" and "a" share the key '"a"', and stable sorted then falls back to set iteration order.

left, right = {b"a", "a"}, {"a", b"a"}
assert left == right
order_sets(left)   # ('a', b'a')
order_sets(right)  # (b'a', 'a')

Reproduced with PYTHONHASHSEED pinned to 0, 1 and 2. Under each seed, four sets that are all == to each other give two distinct order_sets outputs in one process, decided by construction order.

End to end, a set field holding {b"a", "a"} against an equal set built the other way:

comparator compare_with compare() expected
explicit ExactComparator 0.0 0.0 1.0
inferred default 0.818 0.818 1.0

The default path is wrong too, just quieter: 0.818 reads like rounding rather than a bug.

test_order_sets_is_deterministic_for_nested_and_mixed_sets uses elements with distinct sort keys, so it cannot catch this. A type-name tie-breaker would fix bytes against str, though not two objects of one type whose canonical keys collide.

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 for the repro. order_sets is gone with the Tuple/Set half, so this no longer applies. I've recorded the b"a"/"a" key collision in #391, so whoever designs set comparison doesn't sort by JSON form again.

Comment on lines +625 to +627
pair = comparable_scalar_pair(self_value, other_value)
if pair is None:
return 0.0

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.

pair is None here returns 0.0 without calling the configured comparator, for every type outside the allowlist, bytes and user-defined classes included.

bytes, with an equality comparator declared on a f: bytes field:

dev this PR
identical b"abc", compare() 1.0, 1 call 0.0, 0 calls
identical b"abc", compare_with 0.0, 0 calls 0.0, 0 calls

A non-pydantic class with __eq__ and a comparator written for it behaves the same way: compare() goes 1.0 to 0.0, zero calls.

Converging the two readers is the right goal for #233, but converging on never calling a declared comparator drops the caller's stated intent without a signal. Since compare() feeds the Hungarian cost matrix, it can also shift list pairings.

The repr argument in the docstring is convincing for an inferred comparator, where two <Foo object at 0x...> reprs really would match falsely. It reads differently for a comparator written for the type. bytes shows the tension: _json_sort_key renders it well enough to collide with str inside order_sets, while this gate treats it as too foreign to reach a comparator at all.

A couple of ways out: leave the gate off types that already worked, or carry the existing _comparator_explicit bit into dispatch and honour an explicit comparator. A warning when a declared comparator is skipped would at least make it visible, close to what #350 did for unknown config keys.

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.

You're right. Converging the two readers on "never call it" was the wrong way to make them agree. In b88d81b, a comparator the field declared is always called for a pair of non-structured values, in both readers, using the existing _comparator_explicit bit (now carried on ComparableFieldConfig). The strict scalar list applies only to an inferred comparator, where the repr argument holds.

On your cases, compare_with() / compare():

dev before now
bytes, identical, declared equality comparator 0.0 / 1.0 0.0 / 0.0 1.0 / 1.0
custom class 1 unit apart, declared distance comparator 0.0 / 0.9 0.0 / 0.0 0.9 / 0.9
date vs "2026-09-14", DateComparator 0.0 / 1.0 0.0 / 0.0 1.0 / 1.0

So compare_with() is fixed for these too, which is the bug #383 reported. The root cause of the two readers drifting is that they're separate implementations; #392 (1.1.0) tracks merging them.

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

sromoam commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @digalaviz, all four points are addressed in b88d81b:

The full suite passes on Python 3.10, 3.12 and 3.14 (2856 passed, 12 skipped, 1 xfailed). Of the 77 tests in test_scalar_field_dispatch.py, 4 fail on 854fc00: exactly your declared-comparator and set-aware cases.

@sromoam
sromoam requested a review from digalaviz October 15, 2026 13:51
sromoam pushed a commit that referenced this pull request Oct 15, 2026
`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.

@digalaviz digalaviz 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.

All three blocking findings are addressed in b88d81b. Measured on b88d81b against dev
70e9afb:

case, compare_with() / compare() dev 70e9afb head b88d81b
set field, declared Jaccard, identical sets 0.0, FD, 0 calls / 1.0 1.0, TP / 1.0, both receive a set
set field, declared equality comparator, {b"a","a"} against an equal set 0.0, FD / 1.0 1.0 / 1.0
bytes, declared equality comparator, identical 0.0, FD / 1.0 1.0 / 1.0
custom class, declared distance comparator, 1 unit apart 0.0, FD / 0.9 0.9 / 0.9
date against its ISO string, DateComparator 0.0, FD / 1.0 1.0 / 1.0
Decimal("1.5") against 1.5, inferred 0.0, FD / 1.0 1.0 / 1.0
two distinct objects, inferred 0.0, FD / 0.9211 0.0 / 0.0
dict field, inferred 1.0 / 1.0 unchanged
tuple and set, inferred 0.0, FD / 1.0 unchanged, #391

order_sets and the Tuple/Set expansion are gone, canonical.py is untouched, and the CHANGELOG
entry now sits under ### Changed with the - **Breaking:** prefix and names the compare() and
list-matching direction. Full suite on b88d81b: 2856 passed, 12 skipped, 1 xfailed, and the same
counts merged with dev 9db859d, which this branch is two commits behind. All
18 checks are green, test (3.10) included on both the push and the pull_request run, so the wall
clock flake has not recurred. ruff format --check still reports comparison_helper.py and
configuration_helper.py, identically on dev, so that is not from this PR.

Four notes, none blocking.

The title says tuple and set fields reach their comparator, and that holds only for a declared one.
items: Set[str] = ComparableField() against an identical value is still 0.0 and an FD in
compare_with() on this head, same as dev. The title lands in the squash commit, so dropping
tuple and set from it would keep the log accurate.

The legacy dict form of x-comparison cannot tell an inferred comparator from a declared one.
ComparableField(threshold=0.8) with no comparator still exports
"comparator_type": "LevenshteinComparator", so one annotation gets two answers: the original
model refuses two distinct Blob() values at 0.0 and an FD, while the same model rebuilt from its
own exported dict reads comparator_explicit=True and scores them 0.864865 as a TP in both
readers. Not a regression, dev's compare() scored that pair 0.864865 too, but the new bit does
not survive the round trip. Probably its own issue.

Declaring the default comparator is now a decision rather than a no-op. Any field with
ComparableField(comparator=LevenshteinComparator()), two distinct Blob() values: dev reported
0.0 and an FD in compare_with(), this head reports 0.837838 and a TP, which is the repr hazard
the new docstring describes, re-entered deliberately. Covered by the entry's custom-class bullet,
worth knowing because Levenshtein is also what the inferred path installs.

compare_with() can now raise where it returned 0.0, and the "Results move for existing callers"
list does not mention it. StructuredModelComparator declared on a field holding Decimal("1")
against a date raises TypeError here; dev's compare() already raised the identical error, so
the readers agree and this is the contract I asked for, but the population that hits it is #383's
own: someone who declared a string-oriented comparator on a date field and lived with the 0.0. One
sentence in the entry closes it.

Smaller: the comment on _COLLECTIONS says tuples and sets keep their pre-#383 behaviour "in each
reader". That holds for an inferred comparator. With a declared one, compare_with() now scores
them, (1,) against (1,) moving from 0.0 and an FD to 1.0 and a TP. The CHANGELOG bullet states
it correctly.

@digalaviz
digalaviz merged commit d1f0f80 into dev Oct 15, 2026
18 checks passed
@digalaviz
digalaviz deleted the fix/383-scalar-dispatch branch October 15, 2026 16:49
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.

StructuredModel fields typed date, datetime, time, Decimal, UUID or Enum score 0.0 against an identical value

2 participants