Skip to content

fix: report-only list fixes: raw_similarity_score, evaluator-format precision/recall and non_matches (#330, #413) - #420

Merged
sromoam merged 11 commits into
devfrom
fix/list-report-scores
Oct 28, 2026
Merged

sromoam merged 11 commits into
devfrom
fix/list-report-scores

Conversation

@sromoam

@sromoam sromoam commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Report-only fixes: list raw_similarity_score, evaluator-format precision/recall and non_matches

Three reporting fixes, one breaking (#413). No score and no confusion count changes, and nothing the Strands Evals integration reads changes (checked below). A fourth fix, the bulk mean_score copied from the first pair, is not in this PR: it would change a value the Strands Evals contract pins. Tracked in #428 (1.1.0).

Refs #330. Closes #413.

1. raw_similarity_score on a list node is now unclipped (#330, item 2)

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 (sum(pair scores) / max(len(gt), len(pred)), same arithmetic as the score so the two are bit-identical when nothing was clipped), and both list comparators report it.

["apple", "banana"] vs ["apple", "banxxx"], Levenshtein, threshold 0.9 before after
raw_similarity_score 0.5 0.75 (= compare())
similarity_score, threshold_applied_score, field_scores, overall_score 0.5 0.5
counts tp 1, fd 1 tp 1, fd 1

Who reads it: EvalResult.explain() (raw_similarity, verdict) and the HTML field extractor. Nothing that feeds a score, a count, bulk mean_score (reads threshold_applied_score), aggregate_from_comparisons, or the confidence accumulator reads it; non_match_collector and field_comparison_collector read it only on non-list fields. On a List[StructuredModel] raw moves only where a pair's own score is below the list's 0.01 floor (one pair at 0.005 reported 0.0 and now reports 0.005), because each pair's score is the item's own overall_score, so raw stays clipped inside each item (#330). explain() gives a list of models no verdict, as before.

2. evaluator_format=True precision and recall no longer swap on a missed value

Without include_confusion_matrix=True, overall was convert_score_to_binary_metrics(score), which charges every lost point to precision once the score reaches 0.5; each list field's overall and each items[i] overall always used it. 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 (honouring recall_with_fd) whether or not the confusion matrix was requested. A node with only true negatives keeps the old conversion; for the document's overall that still differs with include_confusion_matrix=True (#434). Scalar and nested-model field metrics and anls_score are unchanged; moving those to counts too is #434 (1.1.0).

one TP, one FN ([A, B] vs [A]) before after
overall precision / recall 0.5 / 1.0 1.0 / 0.5
list field overall precision / recall 0.5 / 1.0 1.0 / 0.5
same call with include_confusion_matrix=True, overall 1.0 / 0.5 1.0 / 0.5

Strands Evals 1.6.0 never calls evaluator_format (grepped strands_evals/evaluators/deterministic/structured_output.py).

3. evaluator_format=True omits non_matches unless records were requested (#413)

It always wrote "non_matches": [], so print_non_matches printed ✅ No non-matches found. 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, and the #404 printers say the records are missing.

Since #412, DataExtractor.extract_non_matches returns None when no records were collected, so the HTML report already tells the two states apart; this PR adds evaluator-format coverage (2 tests in tests/reporting/html/test_html_non_match_records.py). The printer now leads with document_non_matches=True and shows the EvalResult .raw hint only for a default compare_with() dict.

Breaking: result["non_matches"] on evaluator-format output without document_non_matches=True now raises KeyError; test "non_matches" in result or request the records.

No in-repo caller indexes ["non_matches"] on evaluator-format output without requesting records.

Not included: bulk mean_score copied from the first pair

StructuredListComparator._handle_hierarchical_field copies the first pair's raw_similarity_score / similarity_score / threshold_applied_score onto the aggregated node for any structured field inside List[StructuredModel] items, a nested list or a nested object alike (one code path). Bulk mean_score for those paths then depends on element order: the same two documents with their items reversed give outers.inner and outers.obj mean 1.0 vs 0.5, counts identical.

Both ways to fix it change ProcessEvaluation.field_metrics, which Strands Evals returns to users through StructuredOutputReport.metrics() and which the contract snapshot pins. Measured on this branch merged with test/365-strands-evals-contract:

  • dropping the copied keys: models.Order.field_metrics.shipments.items.mean_score: missing (expected 0.875) (775 passed, 1 failed)
  • averaging across pairs instead: shipments.items.mean_score: 0.875 -> 0.9375

No snapshot case has a nested object inside list items, so an object-only fix would pass, but it would leave nested lists order-dependent and make two shapes in the same item behave differently. Left for a deliberate change with a snapshot update. bulk-evaluation.md (line 142) is still wrong for these paths and is not edited here.

Invariance check

A seeded random corpus of 720 documents, run on this branch and on origin/dev (003b5f1, detached worktree), every value dumped and diffed leaf by leaf:

  • 360 StructuredModel documents in three schemas: List[str] (clipped, unclipped, exact) and List[float]; an Order with List[Item] whose items hold a nested List[str] and a nested object, a two-level List[Outer] with List[Inner] and a nested Inner object per item, a nested model, a weighted field, a Dict[str, str]; a flat model with a Dict[str, Any]. Each compared six ways: compare_with with every report flag, default compare_with, compare(), and three evaluator-format calls (recall_with_fd random).
  • 360 zero-config documents through eval_for(PlainInvoice, match_threshold=0.7, weight_hints=False).evaluate(), the Strands path: nested plain model, List[str], List[PlainLine] with a nested List[str], optional dict.
  • Bulk per schema: BulkStructuredModelEvaluator.compute() and aggregate_from_comparisons over the stored results (metrics, field_metrics counts and mean_score, non-match records).

Identical on both trees: overall_score, field_scores, every confusion count at every node (overall, aggregate, derived), similarity_score, threshold_applied_score, compare(), non-match records, EvalResult.overall_score/matched/precision/recall/f1/accuracy/field_scores, raw["confusion_matrix"], and all bulk output. The only differences (12,780 leaves) were the intended keys: raw_similarity_score on list nodes (140, none on a non-list node), explain() raw_similarity/verdict on list fields (87), evaluator-format P/R/F1/accuracy on overall and list overall (10,285; the root overall with the confusion matrix included never moved), and evaluator-format non_matches presence (2,268). On the branch, all 936 evaluator-format overall / list overall values with a TP, FP or FN equal that node's derived block exactly.

Strands Evals contract

This branch merged locally with test/365-strands-evals-contract (scratch worktree, tree identical to this branch's head):

  • tests/integrations with strands-agents-evals 1.6.0 installed: 776 passed, 1 xfailed
  • tests/integrations without it: 605 passed, 1 skipped

Tests

New: test_list_raw_similarity_score.py (9), test_evaluator_format_counts.py (9), test_evaluator_format_non_matches.py (8). On origin/dev, 16 of the 26 fail: 3 raw-score, 8 precision/recall, 5 non_matches/printer/HTML. The rest pin unchanged behaviour (scores, the FA case, requested records).

Full suite at /Users/sromo/Development/stickler-worktrees/wreports (stickler imported from its src/), pytest tests -n 6: 3051 passed, 2 skipped, 1 xfailed at 4eeca21 (merged with current dev). The 720-document invariance run above predates the merge; the later commits change only explain() list-verdict wording, printer wording and docs, none of which feeds a score or a count. One run had a wall-clock flake in test_performance_benchmark.py::test_performance_large_list_comparison; it passes when run alone.

Docs: architecture.md score table and list-clipping note, the evaluator-format section of Guides/Evaluation/README.md (real example, count-based metrics, non_matches presence), and CHANGELOG Unreleased > Fixed, one entry per fix. classification-logic.md is untouched.

Update (Oct 20)

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

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-28T19:55:09+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-28T19:52:18+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 4 0 0 6357 0 4 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 3 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
1 tests/test_readme_examples.py

Detailed Findings

Show 5 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:1363-1369

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

Code Snippet:

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

Finding 4: B307

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

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

Code Snippet:

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

Finding 5: B102

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

Description:
Use of exec detected.

Code Snippet:

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

Report generated by Automated Security Helper (ASH) at 2026-10-28T19:55:10+00:00

Reconciles #413 with #412 (#411). #412 made DataExtractor.extract_non_matches
return None when no records were collected, and the HTML non-match section
renders the "records missing" note for None. That covers what
has_non_match_records did here, so the helper and its section_generator
branch are dropped and those files match dev. With non_matches now absent
from an evaluator_format=True dict unless requested, the extractor returns
None for it and the report shows the note, not "No non-matches found.".

The evaluator-format HTML tests move to test_html_non_match_records.py,
which drives the renderer without mocks; the bulk case was already there.

CHANGELOG: the #298 and #411 entries no longer list evaluator_format=True
as uncovered (the #425 gap stays), and the #413 entry says it closes it.
…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.
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.
# Conflicts:
#	src/stickler/structured_object_evaluator/models/primitive_list_comparator.py
#	src/stickler/structured_object_evaluator/models/structured_list_comparator.py

return match_result.get("overall_score", 0.0)
score = match_result.get("overall_score", 0.0)
return score, match_result.get("raw_overall_score", score)

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

raw_similarity_score on a List[StructuredModel] is still the clipped score. Each pair's score in threshold_corrected_pairs is the item's compare_with()["overall_score"], and that value already zeroes every nested field that missed its threshold. raw_overall_score therefore averages clipped values, so the docstring's "no pair clipped" and the CHANGELOG line "raw_similarity_score on a list node is now the unclipped score" do not hold for this comparator.

Reproduced on this branch: It.code is Levenshtein at threshold 0.9, and D(items=[It(code="banana")]) vs D(items=[It(code="banxxx")]) reports raw_similarity_score == 0.0 and threshold_applied_score == 0.0. The unclipped similarity is 0.5. Either compute the pair's raw score from unclipped child scores, or narrow the docstring, CHANGELOG and architecture.md claims to primitive lists.

Reviewer note: the CHANGELOG entry also says "List[StructuredModel] is in practice unchanged", and the docstring is accurate at the list level (no pair is clipped by the list comparator; the clipping is inside each item's own compare_with()). No score or count changes. Suggest clarifying the docstring and CHANGELOG headline in a follow-on.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Narrowed rather than computed from unclipped child scores, which is a larger change and now a 1.1.0 follow-up, #437.

  • 89064de: the CHANGELOG headline says "primitive list node". The comparator docstring and architecture.md say a List[StructuredModel] raw score is unclipped at the list level only, because each pair's score is the item's own overall_score. Your repro is pinned in test_structured_list_raw_is_clipped_inside_each_item (banana/banxxx at 0.9 gives raw 0.0, threshold-applied 0.0).
  • bc21423: "in practice unchanged" is gone. Measured against origin/dev 0921f4a, a list of models moves only where a pair's own score is below the list's 0.01 floor. One pair at 0.005 went from raw 0.0 to 0.005, and 1.0 + 0.005 went from 0.5 to 0.5025. Pairs at 0.5, 1.0 + 0.5 and 0.0 are identical on both trees.

elif EvaluatorFormatHelper._has_decisions(
(recursive_result or {}).get("overall")
):
# The same counts, read before the confusion matrix is built, so

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

A node with only true negatives still gets different precision and recall depending on include_confusion_matrix. The comment on this line says precision and recall "do not depend on include_confusion_matrix". When _has_decisions is False (for example both sides all-None), the else branch returns convert_score_to_binary_metrics(1.0) = precision/recall/f1 1.0. With include_confusion_matrix=True, the first branch returns the derived block, which is 0.0/0.0/0.0.

Reproduced on this branch: E().compare_with(E(), evaluator_format=True)["overall"] returns precision 1.0. Adding include_confusion_matrix=True returns precision 0.0. The README documents the gap, but the code comment and the CHANGELOG ("equal that node's derived block") do not. Make the TN-only case use one rule on both paths, or correct the comment.

Reviewer note: this behaviour is pre-existing; dev (origin/dev) gives the same 1.0 vs 0.0 for this input. The comment on this line sits inside the _has_decisions branch, where it holds, and the CHANGELOG states that a node with no TP, FP or FN "keeps its previous value". No regression from this PR.

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 it is pre-existing; this is the second half of #434 (1.1.0).

)

# Get individual item metrics by comparing list items
items_metrics = EvaluatorFormatHelper.calculate_list_item_metrics(

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

Per-item items[i]["overall"] metrics also change, and the CHANGELOG does not say so. calculate_list_item_metrics calls gt_item.compare_with(pred_item, evaluator_format=True) for each matched pair. Each of those calls now reaches the count-based branch through its own recursive_result, so every fields[<list>]["items"][i]["overall"] changes from the score conversion to counts. The CHANGELOG entry lists only the root overall and each list field's overall. Add the per-item overall to that entry so consumers of items know it changed too.

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.

Done in 89064de. The CHANGELOG entry now says each items[i] of a List[StructuredModel] field is that pair's own evaluator-format result, so its overall moves the same way. test_per_item_overall_reads_counts pins it: [Pair(a="x", b="y")] vs [Pair(a="x")] gives items[0].overall precision 1.0 and recall 0.5.

)
if self._is_list_field(name):
entry["verdict"] = (
f"each paired element < threshold {threshold} -> "

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

The verdict names a threshold that does not do the clipping for a List[StructuredModel] field. For a list of models, explain() reports the spec threshold (for example 0.7 for inferred models). StructuredListComparator clips pairs at a classification threshold of 0.01, and each pair's score comes from the item's own compare_with. A list-of-models field that scores 0.0 with raw_similarity in (0, 0.01) would get "each paired element < threshold 0.7 -> clipped to 0.0", which names the wrong threshold as the cause. Limit this wording to primitive lists, or report the threshold that actually applies.

Reviewer note: reaching this message for a list of models needs every paired item score in (0, 0.01). It is display text only; no score changes.

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.

Done in 89064de. explain() gives a List[StructuredModel] field no verdict, as on dev. The list clips its pairs at 0.01, not at the field's threshold, so the old wording named the wrong cause. test_explain_gives_no_verdict_for_a_list_of_models pins your case: score 0.0, raw_similarity 0.005, no verdict. Primitive lists keep their verdict, and the CHANGELOG now says "a primitive list". A verdict that names the 0.01 floor is in the 1.1.0 follow-up, #437.

use_color=False,
)

assert "b" in capsys.readouterr().out

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

This assertion cannot fail. The output of print_non_matches always contains the letter b, from headers and words such as "number", whether or not the record for field b is printed. Assert on something specific to the record instead, such as the field path together with its non-match type or the values y/z.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 89064de. The test now asserts the record line itself, 📍 b: "y" → "z", so it fails if field b's record is not printed.

# The same counts, read before the confusion matrix is built, so
# precision and recall do not depend on include_confusion_matrix.
overall_metrics = EvaluatorFormatHelper._metrics_from_counts(
recursive_result["overall"], overall_score, recall_with_fd

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

(Optional cleanup.) (recursive_result or {}).get("overall") is computed twice in this if/elif chain, and the confusion-matrix branch above builds the same five-key dict that _metrics_from_counts returns. Bind overall_counts = (recursive_result or {}).get("overall") once. Then have the first branch return the same shape from cm_derived, so the evaluator-format metric dict is built in one place.

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.

Done in 89064de. overall_counts is bound once. Both the confusion-matrix branch and _metrics_from_counts now build the metric dict through one helper, _metrics_from_derived.

# only: `overall_score` above stays the field's score, and the
# counts were settled before either was computed. Same arithmetic
# as above, so the two are bit-identical when nothing was clipped.
raw_similarities = [score for _, _, score in matched_pairs]

@vawsgit vawsgit Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking — suggest a follow-on issue.

(Optional cleanup.) raw_similarities makes a second pass over matched_pairs to rebuild values the clipping loop above already reads. Accumulate the raw sum in that same loop, raw_sum += score, and drop the list.

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.

Kept as is, on purpose: the second pass is what keeps raw_similarity_score bit-identical to threshold_applied_score when nothing was clipped.

  • On a List[StructuredModel] the pair scores are plain Python floats (each item's overall_score), and on 3.12+ sum() of plain floats uses compensated summation, which a running += does not.
  • Measured on this branch (Python 3.12.6) over 500 random List[StructuredModel] comparisons with no pair clipped: with sum() as written, raw equals threshold-applied in all 500. With a running raw_sum += score, 136 of 500 differ in the last bit. Across all 1000 sum() calls, 306 disagree with +=, for example 2.795634920634921 vs 2.7956349206349205.
  • Primitive lists happen to give numpy float64 pair scores, where the two agree (0 of 4000), but the list-of-models path would split the two scores for no reason.
  • The list is at most max(len(gt), len(pred)) long, so the second pass costs nothing measurable next to the pairing.

@vawsgit vawsgit left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ LGTM!

I measured on 6a6e390. No score or confusion-matrix count changes, and no exception path found. The 7 inline comments are non-blocking and are suggestions for follow-on issues. The most useful is r4329292357: raw_similarity_score on a List[StructuredModel] stays clipped at the nested-field level. A wording clarification would cover it.

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

sromoam commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @vawsgit. All seven inline notes are answered. The fixes are in two commits on top of 6a6e390:

I kept the sum() second pass in unordered_list_metrics; the reasoning and numbers are in the inline reply. Scores and counts are unchanged.

Measured on the PR tree at bc21423 (Python 3.12.6), compared against origin/dev 0921f4a. Full suite: 3189 passed, 2 skipped, 1 xfailed. Strands Evals contract suite: 776 passed, 1 xfailed, snapshot unchanged.

Follow-ups: the TN-only rule stays in #434 (1.1.0). A new 1.1.0 issue, #437, covers an unclipped raw score and an accurate verdict for List[StructuredModel].

@sromoam

sromoam commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

@vawsgit, heads-up before merging: two commits landed after your approval, both answering your inline notes. The one behaviour change is in 89064de: explain() no longer gives a threshold verdict for a List[StructuredModel] field, since that pair is clipped by the list at 0.01, not at the field threshold. The rest is a refactor (_metrics_from_derived), docstrings and tests. Merged dev in (eb721c8, CHANGELOG-only conflict); CI is green.

@sromoam
sromoam merged commit 1f46ece into dev Oct 28, 2026
14 checks passed
@sromoam
sromoam deleted the fix/list-report-scores branch October 28, 2026 19:57
mangeshraut712 pushed a commit to mangeshraut712/stickler that referenced this pull request Nov 3, 2026
…lder

1.0.1 ships no breaking change. compare_with(evaluator_format=True) without
document_non_matches=True dropped the 'non_matches' key, so
result['non_matches'] raised KeyError where 1.0.0 returned [].

Restore the key as an empty UncollectedNonMatches, a list subclass that
equals [], serialises as [] and survives deepcopy and pickle. The printers,
the HTML DataExtractor, EvalResult.non_matches and the bulk evaluator read
it as 'not collected', so awslabs#420's fix stands: only a collected empty list
prints 'No non-matches found.'. A DeprecationWarning fires once per process
saying the key is omitted from 1.0.2; internal per-item comparisons are
excluded so a caller who requested records is not warned.
sromoam added a commit that referenced this pull request Nov 18, 2026
…at disagree with it (#419)

* docs: state the list contract in one place, and correct the claims that disagree with it

* docs: link the None-list row gap to #418

* docs: link the first-pair mean_score exception to #428

* docs: narrow the raw_similarity_score gap to List[StructuredModel] after #420

* docs(lists): correct the list contract against dev

Drop the gap bullets that #364 and #421 fixed, and replace the rest with one
short known-gaps note without issue links. State the bar for a list declared
without ComparableField (the class match_threshold), say that a runtime
match_threshold does not move a List[StructuredModel] bar, and limit the
unordered claim to a list's own elements: a nested list element is one value,
and on the zero-config path it and a list in an Any field match exactly.

* docs(results): drop the fixed match gap and correct weighted_score for list rows

#364 made a nested list row's match a bool and built element rows with the
field's comparator, so the 'On dev' sentence is removed. A primitive list
element row's weighted_score is its raw, unclipped similarity, unweighted.
The clip note now points at the Score rule instead of restating it, and the
remaining gaps link the contract's known-gaps note instead of issues.

* docs(thresholds): correct what the runtime match_threshold gates

On the zero-config path it is also the field threshold of nested plain-model
and dict fields, and on a StructuredModel it reaches only matched, so the
cheat sheet no longer says it overrides the model threshold. The parameter
goes to evaluate() or eval_for(), not EvalSpec. State the bare-annotation
list bar, qualify 'FN and FA are impossible for an equal-length list' for
None elements, point list clipping at the Score rule, and make the All Four
example runnable with measured values.

* docs(threshold-gated): qualify equal-length pairing for None, link the Score rule

The page now carries dev's measured worked scenario (Laptop is a TP under the
1e-10 tolerance) and runnable compare_with block. On top of it: an item is
left unmatched only when one list is longer once None elements are removed,
and Score Aggregation points list fields at the contract's Score rule.

* docs(hungarian): make the Result Structure checkable and nest leaf counts under overall

Add the gt/pred construction and the compare_with call, and show each
field's counts under its overall key as the result does. Drop 'warns' from
the JSON Schema threshold note: an exported 0.5 is ignored silently.

* docs: point list clipping at the Score rule, and limit the unordered claim

'Lists apply it per element' was wrong for List[StructuredModel] and for
dict and plain-model lists, which do not clip by default. Those pages now
link the contract's Score rule. Best Practices no longer says every list is
unordered, and architecture.md states the clip default per field kind
without an issue link.

* docs(auto): state every effect of the runtime match_threshold in the facade docstrings

On a plain pydantic class it is also the field threshold of nested
plain-model and dict fields, as src/stickler/auto/README.md already says.
Drop the issue number from the rendered API docstring.

* docs(changelog): re-add the list contract entry under Unreleased

The entry is rewritten against dev: the fixed report gaps and the Laptop FD
are gone, the raw_similarity_score and bulk mean_score lines are dropped
(dev's own entries cover them), and each remaining limit links its own issue.

* docs(auto): describe the List[BaseModel] clip gap without an issue link

* docs(lists): word the known gaps as defects, not as places the table is wrong

* docs(thresholds): the runtime match_threshold also gates zero-config List[dict] elements

On a plain pydantic class the runtime value is the element bar of a
List[dict] field as well as of List[Model], at every nesting level. A
primitive list keeps its inferred threshold (0.7 for List[str]). Say so in
What it gates, the precedence row, Key Rule 3, the cheat sheet, both facade
docstrings and the CHANGELOG entry.

* docs: clip_under_threshold is off by default on dict and plain-model fields

Measured on a StructuredModel with threshold 0.9 and one key of three
different: a dict and a plain-model field each score 0.6667 by default and
0.0 with clip_under_threshold=True. The parameter table gave the default as
True for every non-list field, and three paragraphs said "(the default)"
without the exception.

* docs: qualify the equal-length pairing claims for None elements

[P1, None] vs [P1, P2] holds two items on each side and gives tp=1 fa=1,
because None elements are removed before pairing. The thresholds worked
example still said unmatched items appear only when lengths differ, and the
threshold-gated paragraph qualified only its second sentence.

* docs(lists): scope the order claim to a list field's elements

"A list's elements" also covers the inner list of a List[List[str]], which
scores 0.8 when reordered on a StructuredModel and 0.0 zero-config, and a
list held in an Any field, which scores 0.0 zero-config. Use the Pairing
row's scope in Best Practices, the List order edge case and the CHANGELOG.

* docs(lists): mark the List[StructuredModel] clip behaviour as a known gap, and scope list defaults to Python

The intro now says the table is how Stickler treats a list field and that
Known gaps lists where the code does not yet follow it. The Score row
describes what clip_under_threshold does on List[StructuredModel] today (an
FD pair keeps 0.5 with clip True or False) and calls it a known gap rather
than a rule, as do architecture.md and the CHANGELOG.

The Bar and Score defaults hold for Python declarations only. The JSON
Schema importer passes clip True: a free-form object array with ANLS* at 0.9
scores 0.0 there and 0.6667 as a Python List[dict]. Both rows and
architecture.md now link the JSON Schema defaults, and the Bar row points at
the zero-config defaults.

* docs(lists): fix the review nits on reports, null lists and examples

- Reports row and understanding-results: an element of a primitive, dict or
  plain-model list is one row whatever its classification, and a dict or
  plain-model element is not expanded (measured ds[0] and ps[1], TP, with
  no leaf rows).
- Known gaps: a None list is reported differently from [] in
  field_comparisons. Against another None it gets one row, while every
  other pair of null lists ([] vs [], [] vs None, [None] vs None, ...)
  gets none, although each counts one TN.
- aggregate-metrics: say the [A, B] vs [A] example has two-field items.
- CHANGELOG: the Hungarian result block is checkable, not runnable.

* docs(lists): scope the Reports row to field_comparisons, and say non_matches keeps only FD, FN and FA rows

The row said non_matches and field_comparisons both get one row per element
of a primitive, dict or plain-model list, whatever its classification. Only
field_comparisons does. Measured on HEAD and dev with ds: List[Dict[str, str]],
ps: List[Plain] and ts: List[str]: field_comparisons has ds[0], ps[0], ps[1],
ts[0] and ts[1], while non_matches has only ps[1] (FD) and ts[1] (FN); FA
elements and FD leaves of a TP item appear in both. match is a
field_comparisons key, so the row now says so.

* docs(lists): scope the clip defaults to a StructuredModel declared in Python, and the zero-config list threshold to the field name

The zero-config path is declared in Python too, and infers clip per field: a
plain Z(notes: List[str], tags: List[str], description: str) gives notes and
description FuzzyComparator@0.6 with clip off, and tags Levenshtein@0.7 with
clip on. On 'alpha beta gamma delta' vs 'omega theta kappa' notes and
description are FD and keep 0.5128, tags is FD at 0.0 (HEAD and dev).

The Score row, architecture.md and understanding-results.md now say 'on a
StructuredModel declared in Python' and link the JSON Schema and zero-config
defaults, as the Bar row does. The runtime match_threshold section said a
primitive list keeps 0.7 for List[str]; the inferred threshold depends on the
field name (0.7 for tags, 0.6 for notes). The CHANGELOG bullet uses the same
scope.

* docs(json-schema): x-aws-stickler-infer-unspecified also infers the clip setting

The extension reference said x-aws-stickler-clip-under-threshold defaults to
true in every position and that the flag infers a comparator, threshold and
weight. With the flag, a property that names no comparator takes its clip
setting from inference. Measured on HEAD and dev: a free-form object and an
array of them get ANLSStarComparator@0.7 with clip off and keep 0.6667, and a
notes string or string array gets FuzzyComparator@0.6 with clip off; without
the flag they get Exact@1.0 or Levenshtein@0.5 with clip on and score 0.0. A
stated threshold or clip key still wins.

* docs(json-schema): keep the clip Default cell at true, and put the inferred case in Purpose

tests/test_readme_examples.py pins the Default column against an undeclared
schema, where clip is true for every property. The inferred case belongs to
the flag, so the cell keeps true and Purpose points at the paragraph below.

* docs(thresholds): fix the list rows the dev merge left inconsistent

Follow-up to the origin/dev merge (69e178c), which resolved conflicts with
#577 in thresholds-and-metrics.md and CHANGELOG.md.

- Key Rule 2 took #577's "Match threshold on the element class controls
  object-level TP/FD classification for list matching", which contradicts the
  precedence rows for other lists. Scope it to List[StructuredModel] and point
  other lists at the table. Measured on this tree: on a StructuredModel with
  match_threshold 0.85, a bare List[Plain] pair at 0.8 is FD (bar 0.85, the
  containing class); declared with ComparableField() a 0.6 pair is TP (bar
  0.5); a zero-config List[Item] pair at 0.9 is TP with no runtime value and
  FD at runtime 0.95.
- Restore this branch's primitive/dict/plain-model list pairing row,
  including its link to the list contract's Bar row, which the merge had
  replaced with a pointer to the declaration table.
- CHANGELOG: the #484 entry already says a runtime match_threshold sets only
  matched on a StructuredModel, so this branch's sub-bullet now states only
  the zero-config behaviour and keeps the #416 link.

The merge also dropped "`spec.explain()` shows the resolved values." from
Runtime Match Threshold. It stays dropped: on a plain class holding
List[SMEl] with SMEl.match_threshold 0.85, at runtime 0.5, explain() reports
threshold 0.5 while a 0.8 pair is FD, so it misreports the List[StructuredModel]
carve-out the paragraph now states.

* docs(thresholds): keep the List[StructuredModel] exception in Key Rule 3 and the CHANGELOG
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.

compare_with(evaluator_format=True) returns an empty non_matches list when records were not requested

2 participants