Skip to content

feat(matching): opt-in required_match for physical AI object lists - #539

Merged
sromoam merged 15 commits into
awslabs:devfrom
digalaviz:feature/538-required-match
Dec 1, 2026
Merged

sromoam merged 15 commits into
awslabs:devfrom
digalaviz:feature/538-required-match

Conversation

@digalaviz

@digalaviz digalaviz commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Issue Reference

Closes #538

Description of Changes

this adds an opt-in ComparableField(required_match=True). when objects are paired inside a List[StructuredModel], a pair whose required field is not at or above its resolved threshold is excluded before the Hungarian assignment. a vetoed pair is never paired, so an object left with no allowed partner counts as a false negative or a false alarm, never as tp or fd. the two objects of a vetoed pair can still pair with others: with label required, [a, b] against [b, a] is 2 TP. the default is False, so nothing changes unless a field sets it. #538 has the reasoning, including why weight cannot cover this.

Changes Made

  • comparable_field.py: new required_match: bool = False parameter, stored on json_schema_extra next to threshold and weight.
  • structured_model.py: _collect_required_match_fields records the required fields when the class is defined, and raises ValueError for any annotation other than str, int, float, bool (optionally Optional), and for a single nested model that has required fields. a model_rebuild override runs it again, so a nested class defined further down (pos: "Pos", or under from __future__ import annotations) raises too, at the latest on first instantiation. _fails_required_match(other) applies the rule: a field fails when ThresholdHelper.is_above_threshold is false for its resolved threshold. null on one side fails, null on both sides passes.
  • hungarian.py: HungarianMatcher takes an optional is_pair_excluded callback. an excluded pair costs more than any sum of allowed costs (the highest allowed cost plus min(m, n) times the spread of allowed costs, plus 1), derived from the allowed costs because a comparator may score outside [0, 1], so the solver uses it only when nothing allowed is left. it is then dropped from the matches.
  • hungarian_helper.py: passes is_pair_excluded for StructuredModel lists.
  • CHANGELOG.md: entry under [Unreleased] ### Added, naming the new HungarianMatcher(is_pair_excluded=...) keyword.
  • docs/docs/Guides/Evaluation/README.md: the parameter in the ComparableField table, plus its semantics and limits.

Why These Changes Are Needed

physical AI evaluation scores lists of objects a physical agent perceives, and a detection metric needs "any wrong field means not the same object". weights cannot express that for more than three fields at the default match_threshold 0.7, since each field would need over 30% of the total weight. see #538.

Testing

  • Unit tests added/updated: 69 tests in tests/structured_object_evaluator/: 30 in test_required_match.py, 38 in test_required_match_review.py and 1 in test_required_match_future_annotations.py. they cover default off (counts and score unchanged), one failing axis (1 fn, 1 fa, 0 fd), wrong class, all required fields passing, null on one side and on both, a threshold on the field and one on the comparator, a partial score at and just under its threshold, a non-primitive required field raising, a nested list, empty lists, an inherited required field, wrapped primitives, a better pairing found once a pair is excluded, the reporting paths, a veto across two classes, the nested refusal (including a nested class defined further down), and HungarianMatcher with exclusions against a brute force.
  • Integration tests added/updated
  • Manual testing completed: on 2,515 warehouse detection cases, F1, precision and recall per case equal a separate detection F1 implementation within 1e-9, measured before the rebase (details in [FEATURE]: required_match on ComparableField for physical AI object lists, so a failing field keeps two objects from matching #538).
  • All existing tests pass: uv run pytest on this branch, with dev 3378fe9 merged, gives 7152 passed, 13 skipped, 1 xfailed on Python 3.12 and 3.14, and 7147 passed, 18 skipped, 1 xfailed on 3.10, where 5 more tests skip, gated on the PEP 695 type statement or on extras not installed there. tests/integrations gives 690 passed, 1 skipped. uv run ruff check on the changed files passes.

cost, one machine, 120 x 120 list, four primitive fields, median of 7 runs, three rounds each (not a benchmark):

  • dev: 0.30 to 0.37 s.
  • this branch, option off: 0.30 to 0.34 s, so within noise of dev.
  • this branch, four fields required: 0.39 to 0.55 s. I did not profile this. the only new per-pair work is _fails_required_match in the cost matrix pass.

Reviewers

@sromoam

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable)
  • CHANGELOG.md entry added under [Unreleased]
  • Tests added/updated for new functionality
  • All CI checks are passing
  • Ready for review

Additional Notes

  • assignment priority is settled in [FEATURE]: required_match on ComparableField for physical AI object lists, so a failing field keeps two objects from matching #538: cardinality first, as many allowed pairs as possible, then similarity. when every field is required at threshold 1.0, every allowed pair scores 1.0, so the two rules agree. they differ when a field that is not required can differ, or with partial-score comparators.
  • scoring change: an object left with no allowed partner adds nothing to the list similarity. with x off by 1.0 m in one Det, overall_score goes from 0.75 to 0.0, and non_matches (with document_non_matches=True) reports one object-level FALSE_NEGATIVE and one FALSE_ALARM instead of a field FALSE_DISCOVERY.
  • limits: a single nested model field has no pairing step, so a nested class with required fields raises ValueError instead of being ignored. a List[List[Det]] is not vetoed, and a list that mixes objects with primitives is vetoed only when the ground truth list's first element that is not None is an object. required_match: warn for nested shapes the veto doesn't reach #678 tracks refusing or warning on these and on the Dict and Union arms. the flag is Python only: to_json_schema() and to_stickler_config() do not write it, and model_from_json() and from_json_schema() do not read it. a subclass that redeclares the field without it drops the veto.

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

@digalaviz
digalaviz requested a review from sromoam as a code owner November 4, 2026 18:01
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Security Scan Results

ASH Security Scan Report

  • Report generated: 2026-11-30T22:27:46+00:00
  • Time since scan: 2 minutes

Scan Metadata

  • Project: ASH
  • Scan executed: 2026-11-30T22:25:12+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 0 0 0 7978 0 0 PASSED 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 0 0 0 0 0 0 PASSED 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 7 0 0 0 0 0 0 PASSED MEDIUM (global)
syft 0 0 0 0 0 0 0 MISSING MEDIUM (global)

Report generated by Automated Security Helper (ASH) at 2026-11-30T22:27:46+00:00

@digalaviz digalaviz changed the title feat(matching): opt-in required_match to veto failing list pairs feat(matching): opt-in required_match for physical AI object lists Nov 4, 2026

@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!

Verified at head 046559f:

  • Off by default, no change. The full output for 1,200 random documents hashes identically on dev and this PR with required_match=False.
  • #538's own example, one coordinate off by 1.0: with required_match=False, the pair scores 0.75 and counts as a true positive, the same as dev. With required_match=True, it scores 0.0 and counts as one false negative plus one false alarm.
  • Matching is optimal. The new pairing equals brute force in all 3,000 checks.
  • Tests pin it. All 7 deliberate code breaks made tests fail. The 30 new tests pass. In the full suite, one timing test failed under parallel load and passes alone.

Maintainer decision, not a blocker: #538 has two open design questions, and nobody has commented on them yet. (1) When some pairs are blocked, should matching maximise the number of matched pairs first, or similarity first? (2) Should the setting live on each field or on the whole model class? This PR answers (2) with the field-level API that #538 proposes, and it is opt-in. Please settle both in #538 before merge, because merging ships this as public API.

Merge note: CHANGELOG.md conflicts with dev. Keeping both sections resolves it.

@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 Diego, this is a really useful feature, and the validation against a separate detection F1 on 2,515 cases is great. The core veto is correct for List[StructuredModel]. Every pairing path we found goes through HungarianHelper and honours it, compare() agrees with compare_with(), and a brute-force check found the optimal assignment in 3,000 of 3,000 random cases with scores in [0, 1]. Requesting changes for gaps in coverage, docs and a few corner cases. Everything below was run against this branch.

Design: cardinality first is the right call

To answer the open question in #538: keep cardinality first. It matches gating in detection and tracking evaluation, and your validation. In practice it differs from similarity first less than it looks. With cls and x required and color/label free, both rules swap two nearby totes, because the cross pairs outscore the one strong match.

What decides the outcome is which fields are required. If every field that identifies an object is required, every wrong pairing is vetoed and both rules report 1 TP, 1 FN, 1 FA. That held even with a fuzzy label required at 0.6. Please say this in the docs (see below), since it's the thing users will get wrong.

Must fix

  1. A required field inside a nested model in a list item is silently ignored. In List[Obj] where Obj.pos: Pos and Pos.x is required_match=True, x off by 1.0 still gives a TP at 0.875, because Obj._required_match_fields == ('cls',). Either recurse into nested StructuredModel fields in fails_required_match, or raise in _collect_required_match_fields when a nested model declares a required field.
  2. Mixed classes in one list are asymmetric. Only the ground-truth class's flags are read. Gold Det vs pred LooseDet is vetoed; swap them and it's a TP at 0.75. Please pick a rule (we'd suggest the union of both sides' required fields) and test it.
  3. The exclusion cost assumes scores in [0, 1]. BaseComparator doesn't clamp, so a custom comparator scoring outside [0, 1] breaks the max(m, n) + 1 bound: 138 of 3,000 random assignments with scores in [-3, 5] weren't cardinality first. Either clamp similarities before building the cost matrix, or derive the sentinel from the actual cost range. Add a brute-force property test at the HungarianMatcher level, with m and n up to 4 and scores both inside and outside [0, 1].
  4. Docs that now contradict the feature:
    • docs/docs/Advanced/hungarian-matching.md says the assignment "maximizes total similarity" and that only partnerless items become FN or FA. Add the exclusion step, and qualify the FN plus FA rule.
    • classification-logic.md: add one Lists rule for the veto.
    • model-export.md says comparison is identical after a round trip. It isn't for required_match.
    • src/stickler/algorithms/README.md says k "is always min(m, n)" and that only one of fn and fa can be non-zero. One vetoed pair gives fn 1 and fa 1.
    • The comment in hungarian.py (around :353) says the counts "cover max(m, n) items once each". With exclusions, it's m + n − k.
  5. The README paragraph needs an example and the key rule. Rewrite it as a few bullets with the Det example from #538. Cover:
    • when to use required_match instead of weight;
    • that a vetoed pair counts as FN plus FA and adds nothing to the list score (0.75 becomes 0.0);
    • "mark every field that identifies an object as required; fields that aren't can be traded off by the matcher, so similar objects may be paired with each other".

Tests to add

All 30 tests assert counts through one path. Please add one case with one vetoed pair and one matched pair, asserting:

  • overall_score;
  • non_matches: the dets[0] object-level FALSE_NEGATIVE and FALSE_ALARM;
  • the aggregate matrix. Today it's {tp 4, fn 0, fa 0}, so the vetoed objects disappear from aggregate. That's the existing rule for unmatched objects, but the veto now triggers it for wrong objects, so please document it;
  • evaluator_format=True;
  • BulkStructuredModelEvaluator;
  • compare() == compare_with()["overall_score"].

Also:

  • "" and NaN as null on one side;
  • every pair excluded for 2x2 and 2x3;
  • a direct HungarianMatcher(is_pair_excluded=...) test;
  • parametrize the rejected types: Literal, Enum, date, Decimal, Union[int, str].

Smaller

  • Enum and Literal are rejected, but they're the natural types for a class label, and compare_field_raw already scores them like primitives. Consider accepting them.
  • threshold=0.0 on a required field means the veto never fires. Warn, or document it.
  • Export: to_json_schema() and to_stickler_config() drop the flag silently. Warn when a field sets it, until export supports it.
  • List[Union[str, Det]] with a str first goes through _match_non_structured_lists and skips the veto. Raise or document.
  • explain() and the HTML report never show the flag.
  • Shape: fails_required_match re-scores the required fields that the pair's similarity already compared, and repeats the null rule compare_field_raw applies. Computing the veto once while scoring each pair would remove the duplicate pass. It would also let vetoed cells skip the full recursive score, which accounts for most of the +21% at 120x120. Resolve the thresholds once per class, in _collect_required_match_fields, rather than per cell. Moving the post-assignment drop into the list comparator would keep HungarianMatcher general-purpose. These are optional, but they'd keep a single source of truth.

Happy to pair on any of this.

@sromoam
sromoam requested a review from harrycav November 16, 2026 21:43
@sromoam sromoam added this to the 1.1.0 milestone Nov 18, 2026
- a required field below its threshold excludes the pair from the
  list assignment, so both objects stay unmatched (fn 1, fa 1, no fd)
- the exclusion is a cost above every allowed total, so a better
  allowed pairing is found and vetoed pairs are minimised first
- only primitive fields may be required, anything else raises when
  the class is defined
- default False leaves counts and scores unchanged
- states that a veto takes priority over similarity
- states that a single nested object has no pairing step to veto
…h classes

- a nested object is not paired, so its required fields never vetoed
- the veto reads the fields required by either class, so swapping ground
  truth and prediction gives the same result
- a comparator may score outside [0, 1], which broke the fixed bound
- the cost is now above any sum of allowed costs for the matrix at hand
- one veto and one match through compare_with, non_matches,
  evaluator_format and the bulk evaluator
- classes with different required fields, nulls and rejected types
- the matcher against a brute force, with scores inside and outside [0, 1]
- add the exclusion phase and the FN plus FA rule for a vetoed pair
- state that export drops the flag and that aggregate omits vetoed objects
- add an example and the rule to mark every identifying field as required
@digalaviz
digalaviz force-pushed the feature/538-required-match branch from 046559f to 8d60ce5 Compare November 18, 2026 16:44
@digalaviz

Copy link
Copy Markdown
Contributor Author

pushed the review fixes at 8d60ce5:

  • a nested model with a required field now raises ValueError when the class is defined
  • the veto reads the fields required by either class, so swapping ground truth and prediction gives the same result
  • the exclusion cost is derived from the allowed costs, so scores outside [0, 1] stay cardinality first (checked against a brute force)
  • docs: exclusion step, FN plus FA rule, an example and the "mark every identifying field" rule
  • tests: one vetoed and one matched pair through compare_with, non_matches, evaluator_format and the bulk evaluator; nulls; rejected types; the matcher on its own

not changed: export warnings, Enum and Literal support, and the single-pass scoring refactor. Dict and Union containers of a nested model are not checked, and the docs say so. open question for the maintainers: document that limit, or recurse into nested models.

…atch

# Conflicts:
#	CHANGELOG.md
#	docs/docs/Advanced/classification-logic.md
#	docs/docs/Guides/Evaluation/README.md
#	src/stickler/structured_object_evaluator/models/structured_model.py
@digalaviz

Copy link
Copy Markdown
Contributor Author

@sromoam pushed 649ad4a, ready for another look:

  • merged dev after the 1.0.2 release; the veto rules now sit in the Pairing and Counts rows of the list contract table
  • fixed a bug my last push added: checking both classes' required fields also scored a same-class pair in the reverse direction, so an asymmetric comparator such as NumericComparator(relative_tolerance=0.1) vetoed x=100 vs x=90, which the field itself scores as a TP. every required field is now scored ground truth first, and only a different class adds its own required fields. pinned by test_a_required_field_is_scored_ground_truth_first_as_the_field_is
  • corrected the CHANGELOG line on aggregate: vetoed objects are left out when a sibling was accepted, and fall back to the list's own counts when none was

all five must-fix items and the tests you listed are in. not in this PR:

  • export warnings, accepting Enum and Literal, and the single-pass scoring refactor
  • explain() and the HTML report do not show the flag
  • List[Union[str, Det]] with a str first and List[List[Det]] skip the veto

for the last one, do you prefer that I document it here or raise a ValueError when the class is defined?

@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!

required.append(field_name)
cls._required_match_fields = tuple(required)

# a nested object is not paired, so its required fields would never

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.

Optional, not a blocker. This check runs once, when the class is defined, so it misses a nested class that is defined later. I measured this on this head: pos: "PosF" declared before class PosF (with x required_match=True), then ObjF.model_rebuild(), raises nothing, and ObjF._required_match_fields == ('cls',). So PosF.x is ignored without a warning, which is the silent case the check was added to stop. A module using from __future__ import annotations reaches the same state whenever the nested class comes after the parent. A one-line note beside the Dict/Union limit in the Evaluation guide would cover it. Rechecking the nested fields once the class is complete would also fix it.

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.

+1 to vawsgit, and this is Must fix 2 in my review. pydantic's automatic rebuild goes through model_rebuild, so this catches the forward reference. I checked it raises your error on first instantiation, with a string annotation and under from __future__ import annotations:

@classmethod
def model_rebuild(cls, *args, **kwargs):
    rebuilt = super().model_rebuild(*args, **kwargs)
    if rebuilt:
        cls._collect_required_match_fields()
    return rebuilt

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. StructuredModel.model_rebuild now runs _collect_required_match_fields() again after pydantic rebuilds the class, so pos: "Pos" declared before class Pos, and the same under from __future__ import annotations, raise the nested ValueError on first instantiation. Tests: test_a_nested_model_defined_further_down_is_refused_on_first_use in test_required_match_review.py and in the new test_required_match_future_annotations.py.

One change from the sketch: the override passes _parent_namespace_depth + 1 to super().model_rebuild(). pydantic reads the caller's frame at a fixed depth, so with the extra frame it looked in the override and lost names local to the caller. With the sketch as written, Holder.model_rebuild() on a class whose "LaterPosition" is defined in the same function raises PydanticUndefinedAnnotation, and tests/decisions/test_review_regressions.py::test_forward_reference_is_not_cached_empty (from #540) fails. test_model_rebuild_still_resolves_names_local_to_its_caller pins it.

Limit: the error comes from the rebuild, so it is raised once. If a caller catches it, a second instantiation succeeds, because the class is complete by then.

…atch

# Conflicts:
#	docs/docs/Advanced/classification-logic.md

@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 Diego. The merge is clean (it also merges cleanly with today's dev), CI is green, and the ground-truth-first fix is right: I reproduced the relative_tolerance over-veto on the commit before it, and your new test pins it. With the option off, the full output is byte-identical to dev on 390 list scenarios and four bulk runs, and the matcher agreed with brute force on 18,000 random cases. Two fixes are left, both small. The inline suggestions are committable.

Must fix

  1. A veto removes a candidate pair. It doesn't make that pair's two objects an FN plus an FA. They become an FN or an FA only when no allowed partner is left. With label required, gt [a, b] vs pred [b, a] vetoes (0,0) and (1,1) and gives 2 TP. gt [a] vs pred [b, a] vetoes (0,0) and gives 1 TP and 1 FA. The per-pair wording is in seven places: the list contract Counts row (classification-logic.md:47), hungarian-matching.md:47-48, the Evaluation README :99, src/stickler/algorithms/README.md:49, the hungarian.py:366 comment, the required_match docstring (comparable_field.py:162-164) and the CHANGELOG. Your new aggregate sentence in the CHANGELOG is right. Two more README lines: the example at :95 gives the list's score, since a Det against a Det scores 0.5 with or without the flag. And since 649ad4a, :101's "swapping gives the same result" doesn't hold with an asymmetric comparator: gt R(x=100) vs pred R2(x=90) is a TP, gt R2(x=90) vs pred R(x=100) is vetoed. The same fields are checked whichever class is ground truth, which is the part worth saying.
  2. The nested refusal misses a class defined further down (vawsgit's inline comment). pos: "Pos" declared before class Pos, or from __future__ import annotations with Pos below, defines fine. Pos.x is then ignored, and x wrong gives FD 0.5, while README :102 says a direct nested field is refused. Please re-run _collect_required_match_fields() from a model_rebuild override and add a test. The sketch is on vawsgit's thread; I checked it raises your error on first instantiation, with a string annotation and under the future import.

Also please

  • Rename fails_required_match to _fails_required_match unless you mean it as public API. As written it becomes a public method on every StructuredModel in 1.1.0, and renaming it now is cheaper than after the release.
  • The CHANGELOG should name HungarianMatcher(is_pair_excluded=...). It's in the CHANGELOG suggestion.
  • The PR description is stale: the sentinel, the test count, and the nested case, which now raises.

Your question

For List[List[Det]] and lists that mix primitives with objects, please document them here, in the :103 bullet (suggestion inline). Refusing or warning on them, and on the Dict and Union arms, is #678.

Follow-ups

Filed so they don't block this PR: #678 (shapes the veto doesn't reach), #679 (export and import), #680 (explain() and the HTML report), #681 (single-pass veto), #682 (Enum and Literal), #683 (the "Meeting a Threshold" docs). Two dev bugs I hit along the way, not caused by this PR: #684 (matching hangs on a non-finite score) and #685 (List[Union[str, Model]] raises).

The field-level and cardinality-first questions from #538 are settled there.

| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. A pair that a `required_match` field vetoes is never paired, and the assignment pairs as many allowed pairs as it can before it maximises similarity. |
| Bar | `List[StructuredModel]`: the element class's `match_threshold`; a runtime `match_threshold` does not change it. A field `threshold` there raises `ValueError` in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a `StructuredModel` declared in Python: the field's `threshold`, else a threshold named on the comparator, else `0.5` when declared with `ComparableField()`, or the class `match_threshold` (`0.7` unless set) when declared without it (`tags: List[str]`). JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../Getting-Started/thresholds-and-metrics.md#4-runtime-match-threshold)). A pair that [meets](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold) the bar is a TP. |
| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). |
| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A veto removes a pair, not its two objects: gt [a, b] vs pred [b, a] with label required vetoes (0,0) and (1,1) and gives 2 TP. Maybe replace "The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD." with:

"A vetoed pair is never paired, so an element left with no allowed partner is unpaired: an FN or an FA, never an FD."

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.

Applied as suggested.

Comment on lines +47 to +48
become FN or FA. An excluded pair is never assigned, so its two items each
have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item

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.

Suggested change
become FN or FA. An excluded pair is never assigned, so its two items each
have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item
become FN or FA. An excluded pair is never assigned, so an item left with no
allowed partner is an FN or an FA, never an FD. Both items of an excluded pair
can still be paired with someone else. This holds identically for a one-item list and a hundred-item

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.

Applied as suggested.

Comment thread docs/docs/Guides/Evaluation/README.md Outdated
x: float = ComparableField(threshold=0.9)
```

A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP.

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.

Suggested change
A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP.
In a `List[Det]`, a `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` counts as one FN plus one FA, and the list scores `0.0`. Without `required_match` the pair is a TP and the list scores `0.5`.

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.

Applied as suggested. Measured: the pair scores the same either way, and the list scores 0.5 without the flag and 0.0 with it (1 FN, 1 FA).

Comment thread docs/docs/Guides/Evaluation/README.md Outdated

- A required field that is not at or above its resolved threshold (the field's `threshold`, else one named on the comparator, else `0.5`) vetoes the pair before the Hungarian assignment. A threshold of `0.0` never vetoes a pair whose values are both present.
- A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. Mark every field that identifies an object as required. A field that is not required can be traded off by the matcher, so similar objects may be paired with each other.
- The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score.

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.

Suggested change
- The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score.
- An object left with no allowed partner counts as a False Negative (ground truth) or a False Alarm (prediction), never as a False Discovery, and adds nothing to the list score. The two objects of a vetoed pair can still pair with others: with `label` required, `[a, b]` against `[b, a]` is 2 TP.

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.

Applied as suggested. Measured: [a, b] against [b, a] is 2 TP, and [a] against [b, a] is 1 TP and 1 FA.

Comment thread docs/docs/Guides/Evaluation/README.md Outdated
- A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. Mark every field that identifies an object as required. A field that is not required can be traded off by the matcher, so similar objects may be paired with each other.
- The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score.
- A value that is null on one side fails; null on both sides passes.
- When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same 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.

Since 649ad4a, each field is scored ground truth first, so with an asymmetric comparator swapping can change the result (gt R(x=100) vs pred R2(x=90) is a TP, gt R2(x=90) vs pred R(x=100) is vetoed, with relative_tolerance=0.1). That's right, it's how the field itself scores. Only the sentence needs to change:

Suggested change
- When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same result.
- When the two objects have different classes, a field required by either class can veto the pair, whichever of them is the ground truth. Each required field is scored ground truth first, as the field itself is.

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.

Applied as suggested. Measured with NumericComparator(relative_tolerance=0.1) on a required x: gt R(x=100) against pred R2(x=90) is 1 TP, gt R2(x=90) against pred R(x=100) is 1 FN and 1 FA.

Comment thread src/stickler/algorithms/README.md Outdated
Comment on lines +48 to +49
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1.

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.

Suggested change
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1.
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero. With exclusions both can be: a 1 x 1 input
whose pair is vetoed gives `fn` 1 and `fa` 1.

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.

Applied as suggested. Measured: a 1 x 1 input whose pair is vetoed gives fn 1 and fa 1.

Comment thread src/stickler/algorithms/hungarian.py Outdated
Comment on lines +365 to +367
# match() assigns exactly min(m, n) pairs unless pairs are excluded. The
# four counts below cover m + n - k items, so a vetoed pair leaves one
# item in fn and one in fa. The threshold splits the pairs into tp and

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.

Suggested change
# match() assigns exactly min(m, n) pairs unless pairs are excluded. The
# four counts below cover m + n - k items, so a vetoed pair leaves one
# item in fn and one in fa. The threshold splits the pairs into tp and
# match() assigns exactly min(m, n) pairs unless pairs are excluded. The
# four counts below cover m + n - k items, so an item left without an
# allowed partner lands in fn or fa. The threshold splits the pairs into tp and

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.

Applied, rewrapped to the comment's width.

Comment on lines +162 to +164
list of objects (default: False). A vetoed pair is excluded
before the assignment, so its two objects are left
unmatched, one false negative and one false alarm. A

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.

Suggested change
list of objects (default: False). A vetoed pair is excluded
before the assignment, so its two objects are left
unmatched, one false negative and one false alarm. A
list of objects (default: False). A vetoed pair is excluded
before the assignment. An object left with no allowed
partner is a false negative or a false alarm, never a false discovery. A

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.

Applied, rewrapped to the docstring's width.

Comment thread CHANGELOG.md Outdated
Comment on lines +35 to +46
- `ComparableField(required_match=True)` makes a primitive field a veto when
objects are paired in a list: a pair whose required field is not at or above
its threshold is excluded before the assignment and counts as one false
negative and one false alarm, never a false discovery. Off by default; scores
and counts do not change unless a field sets it. Only `str`, `int`, `float`
and `bool` fields may be required, and a class may not hold a single nested
model that has required fields (`ValueError` when the class is defined). When
the two objects have different classes, a field required by either one vetoes
the pair. The vetoed objects follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. Python only: `to_json_schema()` and `to_stickler_config()` do not
write it, and `model_from_json()` and `from_json_schema()` do not read it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The per-pair clause (Must fix 1), plus the new matcher keyword. Your aggregate sentence stays:

Suggested change
- `ComparableField(required_match=True)` makes a primitive field a veto when
objects are paired in a list: a pair whose required field is not at or above
its threshold is excluded before the assignment and counts as one false
negative and one false alarm, never a false discovery. Off by default; scores
and counts do not change unless a field sets it. Only `str`, `int`, `float`
and `bool` fields may be required, and a class may not hold a single nested
model that has required fields (`ValueError` when the class is defined). When
the two objects have different classes, a field required by either one vetoes
the pair. The vetoed objects follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. Python only: `to_json_schema()` and `to_stickler_config()` do not
write it, and `model_from_json()` and `from_json_schema()` do not read it.
- `ComparableField(required_match=True)` makes a primitive field a veto when
objects are paired in a list: a pair whose required field is not at or above
its threshold is excluded before the assignment, which keeps as many allowed
pairs as it can. An object left with no allowed partner counts as a false
negative or a false alarm, never a false discovery. Off by default; scores
and counts do not change unless a field sets it. Only `str`, `int`, `float`
and `bool` fields may be required, and a class may not hold a single nested
model that has required fields (`ValueError` when the class is defined). When
the two objects have different classes, a field required by either one vetoes
the pair. The unmatched objects follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. `HungarianMatcher` takes a new `is_pair_excluded` keyword for this.
Python only: `to_json_schema()` and `to_stickler_config()` do not write it,
and `model_from_json()` and `from_json_schema()` do not read it.

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.

Applied, with one addition: the nested refusal now says ValueError when the class is defined, or on first use for a nested class defined further down.

Comment on lines +686 to +688
``self`` is the ground truth. Both classes' required fields are read, so
swapping ground truth and prediction gives the same answer when their
classes differ. Every field is scored ground truth first, as the field

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.

Optional, same point as README :101: with an asymmetric comparator, swapping can change the answer. "Both classes' required fields are read, so the same fields are checked whichever class is ground truth" would be exact.

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.

Applied: "Both classes' required fields are read, so the same fields are checked whichever class is ground truth."

…atch

# Conflicts:
#	CHANGELOG.md
#	src/stickler/structured_object_evaluator/models/structured_model.py
- a vetoed pair's objects can still pair with others: with `label`
  required, `[a, b]` against `[b, a]` is 2 TP, and `[a]` against
  `[b, a]` is 1 TP and 1 FA
- only an object left with no allowed partner is an FN or an FA
- the Evaluation example gives the list score: the pair scores 0.5
  either way, the list 0.5 without the flag and 0.0 with it
- swapping ground truth and prediction can change the result with an
  asymmetric comparator, so state what holds instead: the same fields
  are checked whichever class is ground truth
- document that a `List[List[Det]]` is not vetoed, and that a mixed
  list is vetoed only when the ground truth list's first present
  element is an object
- a nested class named before it is defined (`pos: "Pos"`, or under
  `from __future__ import annotations`) is a string when the parent is
  defined, so the nested refusal missed it and `Pos.x` was ignored
- `model_rebuild` now runs `_collect_required_match_fields()` again;
  pydantic calls it on first instantiation, so the `ValueError` comes
  then at the latest
- the override passes one more frame of `_parent_namespace_depth`, so a
  forward reference to a class local to the caller still resolves
- it is only called by the Hungarian helper, so it should not ship as a
  public method on every `StructuredModel` in 1.1.0
- renaming it before the release costs nothing; after it, it would be a
  breaking change
- a veto removes a candidate pair; only an object left with no allowed
  partner is an FN or an FA
- name the new `HungarianMatcher(is_pair_excluded=...)` keyword
- the nested refusal also covers a nested class defined further down,
  on first use
@digalaviz

Copy link
Copy Markdown
Contributor Author

Both must-fixes and the three asks are done, and current dev is merged in. The full suite passes on the merged branch on Python 3.10, 3.12 and 3.14.

  • Must fix 1: the per-pair wording is fixed in all the places you listed, plus the test_required_match.py module docstring, which had the same claim. I measured every example before applying it. One change on :103: a mixed list is vetoed when the ground truth list's first element that is not None is an object, so the bullet says that (evidence on the thread).
  • Must fix 2: model_rebuild reruns the check, with two tests and one change from the sketch: it passes one more frame of _parent_namespace_depth, without which names local to the caller no longer resolve and a feat(469): evaluate System One decision models #540 test fails (details on the thread). The option off is unchanged: the rerun only raises for a nested class that has required fields.
  • fails_required_match is now _fails_required_match. docs(examples): add a warehouse 3D detection regression notebook #644 does not call it outside the commits it shares with this branch.
  • The CHANGELOG names HungarianMatcher(is_pair_excluded=...).
  • The PR description is updated: the sentinel, the test count (69), the nested case and the settled assignment priority.
  • Merging dev had two conflicts, both from entries added at the same place. In StructuredModel.__pydantic_init_subclass__ I kept both calls, _collect_required_match_fields() and then feat(469): evaluate System One decision models #540's _require_optional_decision_fields(). In the CHANGELOG I kept feat(export): name variable-length, nested and list tuple types #642's tuple entry and put the required_match entry after it.

digalaviz added a commit to digalaviz/stickler that referenced this pull request Dec 1, 2026

@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 Diego, approving. I checked each fix on 2e1986ad: the per-pair FN plus FA wording is gone everywhere, _fails_required_match is private, and the forward-referenced nested class now raises on direct instantiation. CI is green, and the diff against dev touches no CI or build files.

Two small things, not blocking. Either land them here or I'll take them in a follow-up:

  1. _collect_required_match_fields has the "unwrap Optional/Annotated until stable" loop twice. ConfigurationHelper.strip_annotation_wrappers already does this and the file uses it elsewhere, and hand-rolled copies of this check have caused bugs before.
  2. The ComparableField(...) parameter block in src/stickler/structured_object_evaluator/README.md (around :333) doesn't list required_match yet.

I've added a few narrow shapes to #678: a forward-referenced nested class whose holder is only ever built through a parent's list (the refusal doesn't fire there), mixed lists whose first ground-truth element isn't a model, cross-class pairs where only the prediction's class declares the required field, and a class holding both a single nested Det and a List[Det].

@sromoam
sromoam merged commit ce0f710 into awslabs:dev Dec 1, 2026
11 checks passed
digalaviz added a commit to digalaviz/stickler that referenced this pull request Dec 1, 2026
…abs#539 ref

- awslabs#539 merged, so required_match ships in 1.1.0; the badge, install
  line, warning and preflight error pointed at refs/pull/539/head
- until 1.1.0 is released the install is git+...@dev, then
  stickler-eval>=1.1.0
- outputs unchanged: a clean python:3.12-slim run on this tree gives
  the same results sha256 and the same tables; only timings differ
digalaviz added a commit to digalaviz/stickler that referenced this pull request Dec 2, 2026
- a wrong class is now FN plus FA through required_match on cls, so
  cm_recall reads 0.5 without recall_with_fd; match_threshold stays only
  for the IoU bar, which required_match cannot express
- Hungarian never makes a vetoed pair, and every printed count, the bulk
  metrics and the Use-Cases table row match dev with awslabs#539
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.

[FEATURE]: required_match on ComparableField for physical AI object lists, so a failing field keeps two objects from matching

3 participants