Skip to content

fix: break list assignment ties so scores ignore element order - #660

Open
pcbeingused33 wants to merge 8 commits into
awslabs:devfrom
pcbeingused33:fix/658-hungarian-tie
Open

pcbeingused33 wants to merge 8 commits into
awslabs:devfrom
pcbeingused33:fix/658-hungarian-tie

Conversation

@pcbeingused33

@pcbeingused33 pcbeingused33 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #658

Description of Changes

A List[str] field no longer scores differently when its elements are reordered and several one-to-one assignments tie on total similarity. A direct non-match collector that omits the threshold uses that same tie rule.

Changes Made

  • HungarianMatcher supports an internal _tie_break_threshold attribute (default None, leaving the 1.1.0 public signature and is_pair_excluded positional slot unchanged). When set, assignments with equal total similarity are ranked by the number of pairs meeting the threshold, then by the similarity those pairs add up to. Only the cost matrix the solver sees changes; reported pair scores are unchanged.
  • _match_non_structured_lists sets matcher._tie_break_threshold = threshold for both scalar-list scoring and the report collectors' fallback matcher (get_optimal_assignments), so non-match reports follow the same pairing.
  • collect_list_entries resolves a missing threshold before it asks for assignments. A call that passes only a comparator no longer breaks the tie by position and then classifies the pairs against the default.
  • The list contract states the tie rule for a primitive, dict or plain-model list. Known gaps notes that List[StructuredModel] still breaks a tie by element position.
  • Added tests/structured_object_evaluator/test_list_assignment_ties.py (including a table-comparator test pinning the second sort key and a regression test for the 1.1.0 positional HungarianMatcher signature) and a CHANGELOG.md entry under [Unreleased] → ### Fixed with an upgrade note.

Why These Changes Are Needed

Tied assignments can split differently around the field's threshold, and the solver picked among them by position, so reordering a list changed TP/FD and the score (0.5 vs 0.25 for the lists in the issue). This takes the second option suggested in the issue: prefer the assignment with more pairs above the threshold, then the higher sum among those pairs. List[StructuredModel] matching is not changed here. The direct collector had the same split whenever the caller left match_threshold unset, because the default was filled in only after matching.

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing completed
  • All existing tests pass

The tie tests cover every ordering of both lists from the issue, with and without clip_under_threshold, the non-match report, a direct collector call that passes only a comparator, the second tie-break key (sum of above-threshold pairs), and the 1.1.0 positional HungarianMatcher signature. test_list_assignment_ties.py, tests/common/algorithms/, test_list_item_subfield_parity.py, and test_non_match_documentation.py pass (437 passed).

Checklist

  • Code follows the project's coding standards
  • Self-review of code completed
  • Documentation updated (if applicable)
  • CHANGELOG.md entry added under [Unreleased], or not needed because
    nothing user-visible changed (see RELEASING.md)
  • Tests added/updated for new functionality
  • All CI checks are passing
  • Ready for review

Additional Notes

Targets dev, per CONTRIBUTING.

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

Disclosure: this change was prepared with an AI coding agent.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@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 b8de657. No medium or high findings.

What was checked

  • Issue #658 example: on dev the two orderings score 0.5 (2 TP, 1 FD) and 0.25 (1 TP, 2 FD). On this branch both score 0.5 (2 TP, 1 FD).
  • The 3 new tests fail on dev (the non-match test with assert 2 == 1) and pass here.
  • Full suite (pytest tests -n0): 6754 passed, 13 skipped, 1 xfailed on the branch; 6751 passed on dev. The bert and llm extras were installed and their tests run: 143 passed, 1 skipped. ruff is clean on the changed files.
  • Brute force: 3000 random matrices (2x2 to 6x6, square and rectangular; thresholds 0, 0.5, 0.7, 1.0) checked against every assignment. The chosen total was never below the optimum, and among tied assignments the choice was always the best by pair count, then by sum.
  • The bonus can only override a real similarity difference smaller than about 1e-9/p (p = number of pairs). Measured: at p=2 the higher total is kept down to a difference of 1e-9; at p=50 down to 1e-12. That is float-rounding scale.
  • 120-string lists: on dev, 5 shuffles gave 3 different scores (0.6472, 0.6361, 0.6417). On this branch every shuffle gives 0.6611 with 92 TP. Runtime 0.05 s vs 0.04 s.
  • With tie_break_threshold=None, _ranking_matrix returns the matrix unchanged. HungarianHelper builds its matcher without the argument, so List[StructuredModel] matching is unchanged, as the description says.
  • Edge cases: empty lists, all-zero matrix, threshold 0 and 1, and 3x5 / 5x3 matrices all behave correctly.
  • Mutations the tests catch: returning the plain matrix, subtracting the bonus, and dropping the threshold at comparison_helper.py:198 or :522 each fail all 3 tests.
  • The branch is not behind dev. The CHANGELOG entry is under [Unreleased] → ### Fixed.

Non-blocking (low)

  1. The tests do not check the second sort key. Replacing hungarian.py:217 with bonus = above * 1.0 (count only) or above * (similarity_matrix / (pairs + 1)) (sum only) still passes all 3 tests. The code is correct; a case with equal pair counts but different above-threshold sums would cover it.
  2. The threshold pass-through in comparison_helper_base.py:86 and :401 is not covered. Setting either to None leaves the tests green, because compare_with(document_non_matches=True) reuses the scoring pass. With both removed, _collect_enhanced_non_matches(compare_recursive(...), pred) on the issue's second ordering returns 2 false discoveries instead of 1.
  3. The description says 6738 passed; the current count is 6754.
  4. CI has not run yet: this is a fork PR and the workflows need maintainer approval.

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

Tested the PR head (07a563bff) in a clean worktree against dev.

Result: 3/3 pass (test_list_assignment_ties.py). Teeth confirmed two ways: on dev the file fails with TypeError: unexpected keyword argument 'tie_break_threshold' (import-level), and with the kwarg kept but _ranking_matrix short-circuited to return similarity_matrix, the behavioral symptom from #658 reproduces exactly:

assert {(tp, fd) for _, tp, fd in results} == {(2, 1)}
E   assert {(1, 2), (2, 1)} == {(2, 1)}          # order-dependent TP/FD
E   AssertionError: assert 2 == 1                  # non_matches has 2 entries

The exhaustive test (6×6 permutations × 2 clip_under_threshold modes, asserting every ordering gives (tp=2, fd=1) and an identical score) is the right shape for an order-independence bug.

The tie-break math holds. I checked the invariants the PR claims directly against _ranking_matrix:

  • One more pair above the threshold outranks any similarity sum. On equal totals, diag with 1 above vs anti with 0 above → diag wins; 2 above vs 1 above → 2 wins. The per-assignment bonus is bounded at ~1e-9 regardless of n (1.5e-9 at n=1 down to 1.01e-9 at n=100), so it cannot outrank a real gap.
  • tie_break_threshold=None is a no-op. _ranking_matrix returns the same object (is identity), so direct callers are untouched.
  • Reported scores are unchanged. calculate_metrics on ["a","b"] vs ["b","a"] reports 1.0 for each pair — the raw similarity, not the ranked value.

Randomized differential, 2000 problems. I generated random matrices (n=1..6), solved each with plain Munkres and with the PR's ranked matrix, and brute-forced the true set of optimal assignments. 0 mismatches: the total is always preserved, and whenever the optimum is unique the chosen assignment is identical. 1182 of the 2000 had tied optima, so the tie-break was actually exercised — it only ever picks among genuinely equal-total assignments.

Two small notes, neither blocking:

  1. Threshold inclusivity is inherited. _ranking_matrix uses ThresholdHelper.is_above_threshold, which is >= with float-precision handling. So on a tie, a pair sitting exactly at the threshold counts as "above" for tie-break purposes. That's consistent with how TP is counted elsewhere, and I think it's right — just worth one sentence in the docstring so a reader doesn't assume strict >.

  2. np.vectorize on the matrix. It's a Python-level loop under the hood, so for a large List[float] field this adds a per-cell Python call on top of the Munkres solve. Given HUNGARIAN_SIZE_WARNING_THRESHOLD already caps practical sizes at 10000 cells, it's fine; a plain similarity_matrix >= thr would be faster but would drop the float-precision handling, which is the point of reusing ThresholdHelper. I'd leave it.

The scope is correctly narrow: List[StructuredModel] is untouched (that path doesn't go through _match_non_structured_lists), and get_optimal_assignments threads match_threshold through so the non-match report pairs the same way as the score. CHANGELOG entry is in place. LGTM.

@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 @pcbeingused33, this is a well-scoped fix. I checked 07a563b: since vawsgit's approval only dev was merged in, and the PR's own changes are as they were. The #658 lists score 0.5 and 0.25 on dev and 0.5 in all 36 orderings here, which also holds through Optional, Annotated, a nested model, a List[str] inside a list item, JSON Schema and model_from_json. The three new tests fail on dev and pass here, and the full suite passes at this head.

Must fix

  1. The list contract should state the tie rule (docs/docs/Advanced/classification-logic.md:45). That table is the single statement of how a list field is treated, and which of two equally good pairings wins now decides TP and FD. After the ["a", "b"] example, something like: "When pairings tie on total similarity, a primitive, dict or plain-model list takes the one with more pairs meeting the bar, then the one where those pairs score more." The same row says order does not matter, but List[StructuredModel] still breaks a tie by position: with the issue's strings wrapped in class Item(StructuredModel): s: str = ComparableField(threshold=0.7), three of the six prediction orderings give 2 TP / 1 FD and the other three 1 TP / 2 FD, on dev and here. Leaving that path alone in this PR is fine, but please add it to the Known gaps note under the table (:52, which then lists five behaviours).

Smaller

  1. A direct collector call that passes only a comparator still pairs by position (src/stickler/structured_object_evaluator/models/comparison_helper_base.py:398). collect_list_entries resolves the fallback threshold (404 to 407) only after calling get_optimal_assignments, so the matcher gets None and no tie-break, and the pairs are then classified against 0.7. NonMatchesHelper().collect_list_non_matches("values", ["bcc", "caaa", "cbac"], pred, comparator=LevenshteinComparator()) returns 1 non-match for three orderings of ["baaa", "bbaa", "bbac"] and 2 for the other three; with match_threshold=0.7 it returns 1 every time. Moving that if match_threshold is None: block above the call fixes it, and the full suite still passes with that change. A test over those orderings would also cover vawsgit's item 2. His item 1 (nothing pins the second sort key) is still open too.
  2. CHANGELOG entry (suggestion inline). The neighbouring entries open with a bold lead and link the issue, and tie_break_threshold is a new argument on the exported HungarianMatcher, a public signature change in RELEASING.md's terms, so the entry should name it.

One heads-up: we're not merging anything outside the 1.1.0 milestone until 1.1.0 lands, so this will wait until after that even once it's ready. #539, which is in 1.1.0, has since merged into dev and adds its own argument in the same place in HungarianMatcher.__init__, so this now conflicts with dev. Please bring dev in after 1.1.0 lands rather than now.

Comment thread CHANGELOG.md Outdated
Comment on lines +272 to +274
- A list field of scalar values no longer scores differently when elements are
reordered and several assignments tie on total similarity. The tie now goes to
the assignment with more pairs meeting the field's threshold (#658).

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 possible wording, with a bold lead, the issue link and the new argument:

Suggested change
- A list field of scalar values no longer scores differently when elements are
reordered and several assignments tie on total similarity. The tie now goes to
the assignment with more pairs meeting the field's threshold (#658).
- **A list of values scores the same in any order when pairings tie.** The
solver picked among equally good pairings by position, so reordering a
`List[str]` could move it from 2 TP and 1 FD (`0.5`) to 1 TP and 2 FD
(`0.25`). A tie now goes to the pairing with more pairs meeting the field's
threshold, then to the one where those pairs score more.
`List[StructuredModel]` is unchanged. `HungarianMatcher` takes the rule as a
new `tie_break_threshold` argument, off by default
([#658](https://github.com/awslabs/stickler/issues/658)).

A collector that passed only a comparator resolved the default threshold
after matching, so equal-total assignments were still chosen by position.
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

The list contract now states the tie rule after the ["a", "b"] example, and the Known gaps note records that List[StructuredModel] still breaks a tie by position. collect_list_entries resolves a missing threshold before get_optimal_assignments, so a collector call that passes only LevenshteinComparator reports one non-match for every ordering of the #658 lists, the same as match_threshold=0.7. The changelog entry has a bold lead, links #658, and names the new tie_break_threshold argument.

dev is not in this update. 1.1.0 is still open, so the conflict from #539 can wait until that release lands.

This comment was drafted with AI assistance.

@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 @pcbeingused33, the tie rule in the list contract, the Known gaps line and the collector change all look right. I checked 182c34b merged with dev at 9680269d (1.1.0). The #658 lists give 2 TP and 1 FD in every ordering, the four tests in test_list_assignment_ties.py fail on dev and pass here, and the full suite gives 7483 passed, 3 skipped, 1 xfailed. The new collector test also covers vawsgit's item 2: passing None instead of the threshold at either call site now fails it.

Must fix

  1. tie_break_threshold can't ship in 1.1.1 as a public argument (src/stickler/algorithms/hungarian.py:42). This is a 1.1.1 fix, and RELEASING.md allows no new public API in a patch. It also takes the fifth slot, which is_pair_excluded shipped in with 1.1.0: HungarianMatcher(None, 10000, True, 0.7, excluded) now binds the callable to tie_break_threshold and fails with TypeError: '>=' not supported between instances of 'float' and 'function'. _match_non_structured_lists is the only caller, so a private attribute it sets on the matcher it builds (matcher._tie_break_threshold = threshold) keeps the fix and leaves the 1.1.0 signature alone. The CHANGELOG's sentence about the new argument then goes.
  2. CHANGELOG entry. It merges into ## [1.1.0], under ### Fixed. Please merge dev and move it under ## [Unreleased], in a new ### Fixed. It moves counts and scores for a list whose pairings tie, so RELEASING.md also wants its Upgrade note: phrase, for example "Upgrade note: counts and scores can move for a primitive, dict or plain-model list whose pairings tie."

Smaller

  1. The second sort key is still unpinned (vawsgit's item 1). With the bonus cut to above * 1.0, all four tests still pass. A table comparator pins it: over ["g0", "g1", "g2"] against ["p0", "p1", "p2"], score g0-p0 0.875, g1-p1 0.75, g2-p2 0.125, g0-p1 0.75, g1-p2 0.75, g2-p0 0.25 and everything else 0.0, on a field with threshold=0.7, clip_under_threshold=True. Two pairings tie at 1.75 with two pairs at the bar each, and every ordering should score (0.875 + 0.75) / 3. That passes here, and fails both on dev and with the count-only bonus.

@sromoam sromoam added the anytime Non-breaking improvement off the release critical path: merge whenever it's ready label Dec 4, 2026
@pcbeingused33

Copy link
Copy Markdown
Contributor Author

Thanks @sromoam — all three items are in this update:

  • Removed tie_break_threshold from HungarianMatcher.__init__ so the 1.1.0 signature (including is_pair_excluded in the fifth positional slot) is unchanged. _match_non_structured_lists now sets matcher._tie_break_threshold = threshold, and a new test pins the positional is_pair_excluded slot.
  • Merged dev and moved the CHANGELOG.md entry under ## [Unreleased] → ### Fixed, dropping the mention of a new argument and adding the Upgrade note: sentence.
  • Added the table-comparator test pinning the second sort key (higher sum of above-threshold pairs when counts tie), verified to fail under a count-only bonus.

This comment was drafted with AI assistance.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

anytime Non-breaking improvement off the release critical path: merge whenever it's ready

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: List[str] scores depend on element order when the Hungarian assignment ties

4 participants