Skip to content

fix: report refused list elements with field comparison rules - #364

Merged
sromoam merged 10 commits into
awslabs:devfrom
hugosmoreira:bugfix/332-list-reporting
Oct 20, 2026
Merged

sromoam merged 10 commits into
awslabs:devfrom
hugosmoreira:bugfix/332-list-reporting

Conversation

@hugosmoreira

@hugosmoreira hugosmoreira commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Issue #, if available:

Fixes #332.

Description of changes:

Rejected plain-model list pairs receive indexed false-discovery records. Built-in reports reuse scoring's selected pairs and verdicts through operation-local reporting data, keeping private pairing data out of public results. Accepted child results are retained only when reports need them. Existing helper signatures and custom formatters remain supported; custom hooks retain their fallback behavior and may recompute comparisons.

Integrated dev ace4572, including #399. Saved pairs and accepted child-result keys now refer to the original list positions after absent None/float-NaN elements are filtered. This also covers primitive/plain-model scoring and direct report-helper matching. Removed the unreachable structured-list None-pair branch.

Nested-list reasons explain element-level matches when the node verdict differs from the aggregate score's threshold comparison, preserving the score and threshold. Ordinary below-threshold object reasons remain unchanged. Added the requested Unreleased sentence; understanding-results.md and #418 remain outside this PR.

Validation:

  • Regression failures reproduced before the corrections and restored by an archived negative control. Removing only child-result key remapping also fails all four sparse/reordered cache-use checks.
  • Full Linux Python 3.12 suite: 3,188 passed, 12 skipped, one expected failure. Full Windows Python 3.12 suite: 3,182 passed, six failures with the same test IDs and unavailable signal.SIGALRM messages as unchanged dev, 12 skipped, one expected failure.
  • 472 focused tests pass on Windows Python 3.10–3.14, Linux Python 3.12 and from the built wheel. The exact [BUG]: a refused list element is counted as a false discovery but produces no non-match record #332 example, nested-list/object review cases, and 30 additional sparse-list report-option/default-bulk checks pass.
  • Source/test Ruff, changed-test formatting, lock consistency, wheel/sdist builds, source Bandit and the documentation gate pass. Repository-wide Ruff retains the same 16 findings as dev; documentation retains the six annotation warnings permitted by the existing gate.

macOS, live providers, optional BERT/Strands integrations, ASH and the full hosted dependency matrix were not run. Existing custom-hook and redundant structured-scoring limitations remain; no peak-memory or throughput claim is made.

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Signed-off-by: hugosmoreira <hugo.n4@gmail.com>

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @hugosmoreira, and thanks for taking on a second one. The outcome is right: list reports now agree with the counts in the cases #332 describes, and the full suite passes on this head (2762 passed). The concern is how the agreement is reached, because the approach costs a lot on the default path and can still disagree in two cases.

Blocking

1. Reporting redoes the pairing, which triples comparator calls by default. get_optimal_assignments (comparison_helper_base.py:71) runs the field comparator's full n x m Hungarian matrix again for each report, after scoring has already done it. BulkStructuredModelEvaluator turns both reports on by default, so this isn't opt-in. Measured on a List[str] field, 4 vs 4 items:

scoring only                                          16 comparator calls
+ document_non_matches + document_field_comparisons   48 comparator calls

For an LLM, embedding or BERTScore comparator, that's about 3x the cost and latency per document. tests/test_compare_with_call_count.py exists to keep this number down.

2. The reports can still disagree with the counts.

  • Threshold tolerance. process_matched_pairs (:140) uses a bare similarity_score >= match_threshold, while scoring uses ThresholdHelper.is_above_threshold with a 1e-10 tolerance. A comparator returning 0.7 - 1e-12 at threshold 0.7 gives tp=1 in the confusion matrix, but non_matches reports the same pair as a false discovery ("below threshold (0.700 < 0.7)") and field_comparisons shows match=False.
  • Non-deterministic comparators. Because each report calls the comparator again, an LLM or sampling comparator can pair differently on the second call and report an FD the counts never recorded. The PR body mentions this. It's the #332 symptom through a different route.

Suggested fix for both. Scoring already computes the matched pairs in compare_unordered_lists / PrimitiveListComparator. Put them on the field result in recursive_result and have both collectors read them instead of rematching. That removes the extra calls, the tolerance mismatch and the non-determinism together, and it also removes the duplicated matcher setup (see below). If that turns out to be a bigger change than it looks, I'm happy to pair on it.

Smaller

  • Duplicated matcher setup. get_optimal_assignments copies the _ClassGatedComparator wrapping and HungarianMatcher(..., match_threshold=0.0, normalize_values=False) configuration from comparison_helper.py:289-300. If it stays after the fix above, please extract a shared helper so scoring and reporting can't drift apart.
  • src/stickler/algorithms/README.md:80 says "Both internal callers read only matched_pairs" and lists two callers. This PR adds a third that depends on calculate_metrics, so the table needs updating (or goes back to two once the fix above lands).
  • The FD reason is built twice. create_non_match_entry (non_matches_helper.py:193) builds it with get_match_threshold, which falls back to 0.7 for primitives, and _extract_entries_from_objects then overwrites it. Direct callers of create_non_match_entry / create_entry still get the wrong threshold. Passing the threshold in would leave one correct place to build it.
  • Silently ignored arguments. collect_list_entries (comparison_helper_base.py:340) ignores the comparator and threshold it's passed whenever the list holds StructuredModels. Deciding in the caller, or in one shared predicate, would make that visible.
  • CHANGELOG. Please leave the released [1.0.0] section as published and describe the fix under Unreleased. Users on 1.0.0 still have the gap described there, and the v1.0.0 release notes on GitHub still include it.

Thanks again. The diagnosis in this PR is exactly right. It's the plumbing we'd like to change.

@hugosmoreira

Copy link
Copy Markdown
Contributor Author

@sromoam Thank you for the detailed review. I updated this PR to have both report collectors reuse the pairings, scores, and threshold decisions from scoring, rather than rematching. The 4×4 call-count regression now stays at 16 calls with both reports enabled; tests also cover the tolerance boundary and a stateful comparator. I shared the matcher setup used by direct helpers, made unsupported StructuredModel-list overrides explicit, corrected FD reasoning, updated the algorithm caller table, and restored the released 1.0.0 changelog text. I also merged current dev and resolved the Unreleased changelog conflict; GitHub now shows the branch as mergeable. On the merged head, the Windows-compatible suite has 2,792 passing tests, targeted Ruff passes, and package/docs builds complete. The six SIGALRM tests cannot run on Windows (same baseline limitation); hosted Linux checks have not reported a result. Ready for re-review when you have time.

@hugosmoreira

Copy link
Copy Markdown
Contributor Author

@sromoam My previous update was too broad: the primitive-list fix did not eliminate report-time comparisons for accepted StructuredModel children, and I had left the PR description stale.

This revision reuses the standard child results too. Tests cover the default bulk path (16 calls for 4×4 items), nested/reordered lists, the tolerance boundary and existing custom-method signatures. Custom overrides retain their fallback behavior; I have stated that limit in the updated description.

I also checked each smaller review point, including direct-helper thresholds, caller documentation and the released changelog. The 166 focused/related tests pass on Windows Python 3.10, 3.12 and 3.14. The full suite has 2,806 passes and the same six Windows SIGALRM failures reproduced on untouched dev; no hosted Linux result is claimed.

Thanks for the concrete reproductions. They are now covered by regression tests and untouched-source controls.

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this. The reports now agree with scoring: field thresholds and reasons are right on both primitive and nested lists, and the suite passes (1714 passed, macOS, PYTHONPATH pinned to 7664719, baseline 1479c3d).

Blockers (please fix before merge):

  1. _list_matching leaks out of _dispatch_field_comparison (structured_list_comparator.py:99). Confirmed regression: the result now carries pair_results keyed by tuples, so json.dumps raises where it used to work. See the inline comment on comparison_engine.py:459 for the fix I'd suggest: keep pairings in an engine-owned side map instead of in the result tree.
  2. pair_sink= breaks overrides of _compare_unordered_lists (primitive_list_comparator.py:109). An old-signature override raises TypeError on every list field; a **kwargs override that ignores the sink makes the reports disagree with the counts, which is the #332 bug again.

Should fix: retaining every pair's child traversal on every compare_with (structured_list_comparator.py:204).

The rest are non-blocking cleanups, mostly about keeping one source for each classification rule so the reports can't drift from scoring again.

"similarity_score": raw_similarity,
"threshold_applied_score": threshold_applied_score,
"weight": weight,
"_list_matching": {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocker. This scoring-only _list_matching payload (including pair_results keyed by (gt_idx, pred_idx) tuples) is returned unstripped from ComparisonDispatcher.dispatch_field_comparison and from StructuredModel._dispatch_field_comparison, whose docstring says it is kept for external callers.

Repro on 7664719: gt._dispatch_field_comparison('items', gt.items, pr.items) now has a _list_matching key, and json.dumps(result, default=str) raises TypeError: keys must be str, int, float, bool or None, not tuple. On 1479c3d the same call serializes. Each result also keeps a full recursive traversal for every list pair alive.


# The collectors have consumed the scoring-only pairings. Keep the
# public recursive/confusion-matrix result shape unchanged.
if _retain_recursive_result:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocker (root cause of the comment above). Pairing data travels inside the public result tree and is stripped at several separate exits (compare_recursive, the compare_with recursive result, the compare_with confusion matrix), so any exit without a strip leaks it. _dispatch_field_comparison is one already; a new public helper or collector would be the next.

Suggested fix: keep the pairings in a side map owned by the engine and keyed by field path, which the collectors read. Public dicts then never hold private keys and need no strip-on-exit. That also removes the extra tree walks noted at line 465.

# `threshold_applied_score = raw_similarity` line below, so that line
# preserved a score that had already been thrown away.
matched_pairs = []
match_result = self.parent_model._compare_unordered_lists(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocker. Scoring now passes a new pair_sink= keyword to the overridable parent_model._compare_unordered_lists, and the reports trust whatever that call puts in the sink.

  • A subclass that overrides _compare_unordered_lists with the old signature raises TypeError: unexpected keyword argument 'pair_sink' on every list field.
  • An override that accepts **kwargs but doesn't fill the sink yields empty pairs, so every element shows up as FN/FA in non_matches and field_comparisons while the confusion matrix counts TPs.

That breaks the "custom overrides keep their fallback" guarantee this PR gives for compare_with and compare_recursive. Detecting an override (or an unfilled sink) and falling back to the old path would keep it.

else:
# Use individual comparison with threshold application (same as .compare_with())
individual_result = gt_item.compare_with(pred_item)
if type(gt_item).compare_with is StructuredModel.compare_with:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Should fix. pair_results keeps every matched pair's full child traversal on every compare_with, even with no reports requested and for pairs below match_threshold that the reports never descend into.

A bulk run with document_non_matches=False over documents with hundreds of nested line items now holds one recursive result per Hungarian pair at every nesting level until the top-level call returns. Before, each child result was dropped right after reading overall_score. Caching only when reports are requested, and only for pairs with score >= match_threshold, avoids this. (The PR notes memory wasn't benchmarked.)

# Get field configuration for threshold
info = gt_object._get_comparison_info(nested_field_name)
field_is_match = field_score >= info.threshold
if (

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. This primitive-list special case applies ThresholdHelper's tolerance to the list's aggregate field_scores value, which scoring never classifies against the threshold (scoring classifies elements). For a List[str] subfield, field_score is the coverage-scaled average from unordered_list_metrics, so the comment "Primitive-list scoring accepts values within tolerance" doesn't describe this number.

The reused pair_result['recursive_result'] already holds scoring's per-field verdicts; reading recursive_result['fields'][name] instead of type-sniffing gt_nested_val[0] would keep scalars, nested models and lists on one rule.

"_list_matching": {
"pairs": matched_pairs,
"threshold": threshold,
"verdicts": [

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. verdicts repeats the threshold rule already applied in unordered_list_metrics (tolerant) and in _calculate_object_level_metrics (bare >=, also repeated at structured_list_comparator.py:102). If either changes, the report verdicts silently stop matching the counts, which is the disagreement #332 fixed. Returning the verdicts from the function that already classifies the pairs keeps one source.

and isinstance(pred_val, list)
):
# Use FieldComparisonHelper for primitive list collection
matching = field_result.get("_list_matching")

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. This fallback block that builds matching_kwargs is copied, with small differences, into NonMatchCollector (non_match_collector.py:107), and this copy adds its own StructuredModel check that repeats the ValueError guard in collect_list_entries. The two copies already differ (one checks gt_val[0], the other relies on branch order). One helper on ComparisonHelperBase that resolves the comparator from the model would remove both copies and the raise.

entry["reason"] = (
f"below threshold ({similarity_score:.3f} < {threshold})"
)
if reason is None:

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. create_non_match_entry now has two overlapping ways to set an FD reason (match_threshold and a ready-made reason). The list path always passes reason, so match_threshold is reachable only through create_entry, and a caller passing both silently loses match_threshold. Could this keep just one?

is_match,
similarity_score,
reason,
**({"pair_result": pair_result} if pair_result is not None else {}),

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. process_matched_pairs passes pair_result (only when not None) to _extract_entries_from_objects, but the abstract signature wasn't updated to declare it. A subclass that follows the abstract signature works for primitive lists, then raises TypeError on the first threshold-passing StructuredModel pair. Adding pair_result=None to the abstract method fixes the contract.

result["_recursive_result"] = recursive_result
else:
self._drop_list_matching(recursive_result)
if "confusion_matrix" in result:

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. Each public compare_with walks the result tree twice more to strip _list_matching: once on recursive_result, once on the confusion-matrix copies made before the collectors ran. Building the confusion matrix after stripping, or keeping the data out of the tree (see line 459), removes both walks.

Pass new report options only to explicitly named hook parameters and
retain custom public non-match formatters. Cover old signatures,
forwarding wrappers, nested extraction and exception propagation.

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @hugosmoreira, this round lands both blockers and the should-fix. Pairings now live in an operation-local ReportingContext, so _dispatch_field_comparison and compare_with results serialize again. Overrides of _compare_unordered_lists keep their original call, and the reports fall back cleanly. Child traversals are kept only for accepted pairs, and only when a report asks for them. All seven cleanups are addressed too, and the NaN alignment in 20d13e7 is a nice catch. On 44f68ce, scores and confusion matrices matched dev exactly across 400 random documents, and with reports on, comparator calls dropped from 139 to 61, the same as scoring alone.

One thing before merge: documentation. Rows for nested list and nested object fields inside a list element now report match=False whenever scoring recorded any FD, FA or FN beneath them, even when the row's score is above the threshold. That makes field_comparisons agree with non_matches, and I think it's the right call. But docs/docs/Guides/Evaluation/understanding-results.md:391 still defines match as "Whether the score met the threshold", and the CHANGELOG doesn't mention the change. That file isn't in this diff, so there's no inline comment for it: please update that table row to say that a nested list or object row matches only when scoring recorded no FD, FA or FN beneath it. The other two points are inline.

field_result = field_results.get(nested_field_name)
if field_result is not None:
metrics = field_result.get("overall", field_result)
field_is_match = not any(metrics.get(key, 0) for key in ("fd", "fa", "fn"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This changes the documented meaning of match for nested list and object rows. Repro: one list element with tags ["red","green","blue"] vs ["red","green"] (threshold 0.5). Dev reports match=True, score=0.667, and this branch reports match=False, score=0.667. Agreeing with non_matches (which lists tags[2]) seems right to me, so this only needs the docs row described in the review summary.

# Create reason for this specific field
field_reason = self.generate_comparison_reason(field_is_match, field_score, info.threshold)
if field_result is not None and "fields" in field_result and not field_is_match:
field_reason = "non-matching or unmatched items"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This reason replaces the score and threshold, and it also fires for a single nested object below its threshold. In the repro, addr goes from "below threshold (0.000 < 0.5)" to "non-matching or unmatched items", though it's one object. Could this override apply only when the verdict disagrees with score >= threshold, and keep the score in the text? For example: "score 0.667 >= 0.5, but 1 item did not match".

Comment thread CHANGELOG.md
and preserve scoring's threshold tolerance. Standard structured-child reports
reuse scored child results; custom comparison overrides retain their fallback.
Field-comparison rows treat float `NaN` as missing, consistently with scoring,
both for top-level fields and fields in accepted structured-list pairs.

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.

Please add one sentence here: nested list and nested object rows in field_comparisons now report match=False when scoring recorded any non-match beneath them, even if their score meets the threshold. Users who filter on match will see those rows change.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-10-20T18:13:29+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-10-20T18:11:20+00:00
  • ASH version: 3.1.2

Summary

Scanner Results

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

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

Top 2 Hotspots

Files with the highest number of security findings:

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

Detailed Findings

Show 4 actionable findings

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

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

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

Code Snippet:

Secret of type Hex High Entropy String detected

Finding 2: B108

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

Description:
Probable insecure usage of temp file/directory.

Code Snippet:

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

Finding 3: B307

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

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

Code Snippet:

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

Finding 4: B307

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

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

Code Snippet:

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

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

@hugosmoreira

Copy link
Copy Markdown
Contributor Author

Before I update the guide and changelog, could you confirm the intended scope of the nested-object rule? I reproduced the tags example, but a nested object behaves differently on this PR's published 20d13e7.

With three exact-match address fields, two matching and one differing, items[0].addr reports score=0.667, match=True at threshold 0.5, while non_matches contains items[0].addr.postcode. The outer list pair is accepted at match_threshold=0.5. The helper reads the object's overall counts, which classify its own score; the failed leaf appears separately in the descendant counts.

Reproduction on 20d13e7

Imported file verified with inspect.getfile(stickler): E:/CODEX/OpenSource1/verification/stickler-364-review-20261015/published/src/stickler/__init__.py, extracted from that commit.

import inspect
import stickler
from stickler import ComparableField, ExactComparator, StructuredModel

print(inspect.getfile(stickler))

class Address(StructuredModel):
    city: str = ComparableField(comparator=ExactComparator())
    country: str = ComparableField(comparator=ExactComparator())
    postcode: str = ComparableField(comparator=ExactComparator())

class Item(StructuredModel):
    match_threshold = 0.5
    addr: Address = ComparableField(threshold=0.5)

class Document(StructuredModel):
    items: list[Item]

gt = Document(items=[Item(addr=Address(city="a", country="b", postcode="c"))])
pred = Document(items=[Item(addr=Address(city="a", country="b", postcode="z"))])
result = gt.compare_with(pred, include_confusion_matrix=True,
                         document_non_matches=True, document_field_comparisons=True)
print(result["field_comparisons"])
print(result["non_matches"])

Should I preserve this object-level classification and document the list/object distinction, or should nested-object rows also become non-matches whenever any descendant fails? I recommend preserving the current classification for this documentation revision. The separate reason-text correction is local; I have held the guide/changelog edits pending this clarification.

@sromoam sromoam added this to the 1.0.1 (Minor) milestone Oct 15, 2026
@sromoam

sromoam commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Thanks @hugosmoreira, you're right, and my Oct 14 wording was wrong. Please keep the current classification. I measured on 20d13e7, and objects and lists already follow one rule: a row's match is its own node's classification. A value or object row matches when its score clears its threshold. A list row matches when every element paired as a TP, with no FD, FA or FN at the element level. A failure deeper down gets its own row and its own non_matches entry: your addr example reports items[0].addr as a match with items[0].addr.postcode failing, and a list whose element pairs but has a failing leaf reports the list row as a match with the leaf failing.

To save you a docs round: we're writing a single "Lists" contract for the docs in a separate PR, and it will define match this way in understanding-results.md. So you don't need to touch that file. What's left here:

  • Rebase on dev. fix!: treat a None list element as absent (#386, #322) #399 merged today and makes a None list element absent, so this branch currently brings the old behaviour back ([a, None] vs [a, None] reports 2 TP). Please re-run tests/structured_object_evaluator/test_list_leading_none.py after merging dev; fix!: treat a None list element as absent (#386, #322) #399 touched the same reporting files, so expect a few conflicts there.
  • The reason string. An accepted inner list whose item has a failing leaf reports "within threshold tolerance (0.333333333333 vs 0.5)". The row is a match because its own counts are clean, not because 0.333 is within tolerance of 0.5. Something like "all elements matched" would be accurate.
  • A CHANGELOG line under Unreleased: a nested list row inside a list element now reports match=False when an element was an FD, FA or FN, so field_comparisons agrees with non_matches.

Thanks for pushing on this, the question sharpened the contract.

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @hugosmoreira. Everything from the earlier rounds still holds on 20d13e7, and the classification you argued for is the one we're keeping. Three things are left, then I'd like to approve this for 1.0.1. They're the same three as my Oct 16 comment, with more detail on the rebase, which turns out to need a small code change.

Before merge

  1. Rebase on dev (#399), plus a small index fix.
    • The text conflicts are small: 8 hunks, half of them imports.
    • The catch is semantic. Since #399, compare_struct_list_with_scores matches on NullHelper.present(...) lists. So the pairs this PR stores in the ReportingContext (structured_list_comparator.py:86 and :220) count positions after the None elements are removed, while the collectors read the original lists.
    • A straight merge fails 4 tests in test_list_leading_none.py. For example, rows=[None, A, B] vs [A, None] reports rows[1] as a non-match.
    • The fix: map the pairs and the pair_results keys back with NullHelper.present_indices before storing them. That fixed all four in my scratch merge.
    • Two follow-ons: test_direct_collectors_share_nullable_list_dispatch (tests/test_list_reporting_review.py:339) expects 2 rows at :356, which is 1 under #399. And the gt_item is None or pred_item is None branch (structured_list_comparator.py:202) is dead once the lists are filtered.
  2. Reason text for list and object rows (field_comparison_helper.py:162-164).
    • An accepted inner list with a failing leaf reports "within threshold tolerance (0.333333333333 vs 0.5)". It matches because all its elements paired, not because of tolerance.
    • The override on :164 also replaces "below threshold (0.000 < 0.5)" for a single nested object.
    • Suggestion: override only when the verdict disagrees with score >= threshold, with reasons like "all elements matched (score 0.333 < 0.5)" and "score 0.667 >= 0.5, but 1 item did not match". Leave the normal reason otherwise.
  3. One CHANGELOG sentence under Unreleased, next to your #332 entry: a nested list row inside a list element now reports match=False when an element was an FD, FA or FN, so field_comparisons agrees with non_matches. If it's easier, say so and I'll add it at merge.

Nothing else from me. The field-comparisons follow-up in #418 is planned for 1.1.0, so please leave it out of this PR.

Thanks for sticking with this one. It's been a careful piece of work.

@sromoam

sromoam commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Hi @hugosmoreira, a quick check-in. We are aiming to cut 1.0.1 this week and would like this in it. What is left is the rebase on #399 with the index remap, the reason string and the CHANGELOG line.

If we have not heard from you by midday tomorrow (Tuesday, Oct 20), we will finish those on your branch, or continue from a copy of it, so #332 can make the release. Your commits and credit stay either way. If you would rather finish it yourself, or need a little more time, just say so and we will wait.

@hugosmoreira

Copy link
Copy Markdown
Contributor Author

Thanks for the clarification and detailed review. I'd like to finish the remaining changes myself. I'll rebase onto dev, map the saved pairings and child results back to the original list indices, correct the reason strings and add the changelog sentence. I'll leave understanding-results.md and #418 out of this PR and rerun the required checks before updating the branch.

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @hugosmoreira, this is ready. I re-checked cc2bd10 against current dev, and all three items are done:

  • Index remap after #399. Saved pairs and pair_results now carry original indices (structured_list_comparator.py:100-109). Thanks also for covering the primitive and plain-model paths (comparison_helper.py:171-186, :430-434). I probed:

    • leading, trailing and middle None elements, and None on both sides;
    • an FD next to a None;
    • nested lists with a None in the outer list.

    non_matches and field_comparisons report original indices every time, and the direct collectors agree with compare_with. Single-level output is identical to dev.

  • Reason text. The override now fires only when the verdict and score >= threshold disagree (field_comparison_helper.py:163-182). Accepted inner lists read "all elements matched (score 0.333 < 0.5)", rejected ones say how many items did not match, and single nested objects keep their normal reason.

  • CHANGELOG. The sentence at CHANGELOG.md:125-127 reads well.

On my side, the full suite (3160 passed), the Strands Evals contract suite (776 passed, snapshot unchanged) and ruff are all clean, and it merges cleanly into dev.

One optional nit, fine to skip: at field_comparison_helper.py:172, repr(field_score) prints np.float64(0.699999999999) when a comparator returns a numpy float inside the tolerance window. repr(float(field_score)) would avoid that.

Thank you for seeing this one through. It's a careful fix, and #332 will make 1.0.1.

@sromoam
sromoam merged commit a1a58ce into awslabs:dev Oct 20, 2026
8 checks passed
sromoam added a commit that referenced this pull request Nov 17, 2026
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.
sromoam added a commit that referenced this pull request Nov 17, 2026
…r 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.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: a refused list element is counted as a false discovery but produces no non-match record

2 participants