Repository navigation
fix: break list assignment ties so scores ignore element order - #660
pcbeingused33 wants to merge 8 commits into
Conversation
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
vawsgit
left a comment
There was a problem hiding this comment.
✅ LGTM!
Verified at b8de657. No medium or high findings.
What was checked
- Issue #658 example: on
devthe 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 withassert 2 == 1) and pass here. - Full suite (
pytest tests -n0): 6754 passed, 13 skipped, 1 xfailed on the branch; 6751 passed ondev. Thebertandllmextras were installed and their tests run: 143 passed, 1 skipped.ruffis 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_matrixreturns the matrix unchanged.HungarianHelperbuilds its matcher without the argument, soList[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:198or:522each fail all 3 tests. - The branch is not behind
dev. The CHANGELOG entry is under[Unreleased]→### Fixed.
Non-blocking (low)
- The tests do not check the second sort key. Replacing
hungarian.py:217withbonus = above * 1.0(count only) orabove * (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. - The threshold pass-through in
comparison_helper_base.py:86and:401is not covered. Setting either toNoneleaves the tests green, becausecompare_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. - The description says 6738 passed; the current count is 6754.
- CI has not run yet: this is a fork PR and the workflows need maintainer approval.
mangeshraut712
left a comment
There was a problem hiding this comment.
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-9at n=1 down to1.01e-9at n=100), so it cannot outrank a real gap. tie_break_threshold=Noneis a no-op._ranking_matrixreturns the same object (isidentity), so direct callers are untouched.- Reported scores are unchanged.
calculate_metricson["a","b"]vs["b","a"]reports1.0for 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:
-
Threshold inclusivity is inherited.
_ranking_matrixusesThresholdHelper.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>. -
np.vectorizeon the matrix. It's a Python-level loop under the hood, so for a largeList[float]field this adds a per-cell Python call on top of the Munkres solve. GivenHUNGARIAN_SIZE_WARNING_THRESHOLDalready caps practical sizes at 10000 cells, it's fine; a plainsimilarity_matrix >= thrwould be faster but would drop the float-precision handling, which is the point of reusingThresholdHelper. 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
left a comment
There was a problem hiding this comment.
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
- 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, butList[StructuredModel]still breaks a tie by position: with the issue's strings wrapped inclass 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, ondevand 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
- 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_entriesresolves the fallback threshold (404 to 407) only after callingget_optimal_assignments, so the matcher getsNoneand 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; withmatch_threshold=0.7it returns 1 every time. Moving thatif 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. - CHANGELOG entry (suggestion inline). The neighbouring entries open with a bold lead and link the issue, and
tie_break_thresholdis a new argument on the exportedHungarianMatcher, 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.
| - 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). |
There was a problem hiding this comment.
A possible wording, with a bold lead, the issue link and the new argument:
| - 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.
|
The list contract now states the tie rule after the
This comment was drafted with AI assistance. |
sromoam
left a comment
There was a problem hiding this comment.
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
tie_break_thresholdcan'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, whichis_pair_excludedshipped in with 1.1.0:HungarianMatcher(None, 10000, True, 0.7, excluded)now binds the callable totie_break_thresholdand fails withTypeError: '>=' not supported between instances of 'float' and 'function'._match_non_structured_listsis 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.- CHANGELOG entry. It merges into
## [1.1.0], under### Fixed. Please mergedevand move it under## [Unreleased], in a new### Fixed. It moves counts and scores for a list whose pairings tie, so RELEASING.md also wants itsUpgrade note:phrase, for example "Upgrade note: counts and scores can move for a primitive, dict or plain-model list whose pairings tie."
Smaller
- 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-p00.875, g1-p10.75, g2-p20.125, g0-p10.75, g1-p20.75, g2-p00.25and everything else0.0, on a field withthreshold=0.7, clip_under_threshold=True. Two pairings tie at1.75with two pairs at the bar each, and every ordering should score(0.875 + 0.75) / 3. That passes here, and fails both ondevand with the count-only bonus.
|
Thanks @sromoam — all three items are in this update:
This comment was drafted with AI assistance. |
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
HungarianMatchersupports an internal_tie_break_thresholdattribute (defaultNone, leaving the 1.1.0 public signature andis_pair_excludedpositional 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_listssetsmatcher._tie_break_threshold = thresholdfor both scalar-list scoring and the report collectors' fallback matcher (get_optimal_assignments), so non-match reports follow the same pairing.collect_list_entriesresolves 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.List[StructuredModel]still breaks a tie by element position.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 positionalHungarianMatchersignature) and aCHANGELOG.mdentry under[Unreleased]→### Fixedwith 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 leftmatch_thresholdunset, because the default was filled in only after matching.Testing
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 positionalHungarianMatchersignature.test_list_assignment_ties.py,tests/common/algorithms/,test_list_item_subfield_parity.py, andtest_non_match_documentation.pypass (437 passed).Checklist
CHANGELOG.mdentry added under[Unreleased], or not needed becausenothing user-visible changed (see RELEASING.md)
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.