Repository navigation
fix(hungarian): count a low score pair as fd and not as fn - #289
Conversation
calculate_metrics derives fn and fp as len(list) minus tp, so a pair that the assignment produced, and that the method returns inside matched_pairs, is also counted as a false negative when its score sits below match_threshold. The same pair is reported as matched and as missing at the same time. This commit adds the contract as a test, before any code changes. The 96 assertions that the current code violates carry xfail(strict=True), so the suite fails if one of them starts passing while its marker is still there. The 52 assertions that must keep the value they have today carry no marker and pass now. That half is what makes the claim "only one key changes value" checkable instead of asserted in prose. The file also pins two things that nothing in the suite checked before. One is that a caller can recompute precision, recall and f1 from the counts in the same dict, since the method computes them from list lengths instead, which is a different route. The other is that the old fn value stays recoverable as fn plus fd, which is the migration note for callers. Suite moves from 1949 passed to 2001 passed and 96 xfailed. No behaviour changes here. Refs awslabs#231
calculate_metrics derived fn and fp as len(list) minus tp, so a pair the assignment produced, and that the method returns inside matched_pairs, was also counted as a false negative when its score sat below match_threshold. The same pair was reported as matched and as missing at the same time. A caller could not tell a wrong value apart from a value the model never produced. The assignment now decides what is paired, and the threshold only splits the paired items into tp and fd. Two keys join the returned dict. fd counts pairs that score below the threshold, and fa counts predictions with no partner. fn keeps its name and counts only ground truth items with no partner. BREAKING (calculate_metrics): fn is lower by fd for any input where a pair scores below the threshold. A caller that needs the old number reads fn plus fd. Nothing else changes value. fp stays the rollup fd plus fa, which still equals the number of predictions that are not true positives, and precision, recall, f1 and matched_pairs are the same for every input. The five return sites became one. Three were empty list branches with their own hardcoded rates, and one was the single item shortcut with its own copy of the counting. tp plus fp equals the prediction length and tp plus fn plus fd equals the ground truth length, so both rates have a closed form denominator and those branches were not needed. That also removes the second place where the shortcut could drift away from the general path, which is what awslabs#224 was about. Tests move with the behaviour. The contract file drops its 96 xfail markers. Six assertions across two files are rebaselined, and the docstring in test_hungarian_path_parity.py asked for exactly this update if the fn semantics were ever separated from the threshold. Those files also gain assertions on fd and fa, so a test can now state that no item is without a partner instead of only implying it in its name. Suite moves from 2001 passed and 96 xfailed to 2097 passed. Fixes awslabs#231
The worked list example in classification logic reported TP=2, FA=2, FN=1, FD=0 for a three item ground truth against a four item prediction. The assignment pairs three of them, so "green" is paired with "orange" at 0.17 and is an FD, and only one prediction is left over. The correct counts are TP=2, FD=1, FA=1, FN=0. The FP total was right either way, which is why the error went unnoticed. The example now shows the pairing it is describing, since which items get paired is the part a reader cannot infer. The hungarian matching page already stated the rule correctly, so it gains only a note that calculate_metrics follows it too, and did not before awslabs#231. Two new README files, one for src/stickler/algorithms and one for tests/common/algorithms, as AGENTS.md asks for. The source one records what each count means with its closed form, the two traps that make tp unreadable, and the fact that both internal callers read only matched_pairs. The test one says what each of the three files is for, since they overlap on purpose and the reason is not obvious from their names. The changelog entry carries the migration note for a direct caller of calculate_metrics. The old fn is fn plus fd. Refs awslabs#231
calculate_metrics had a branch that built an empty pair list when either side was empty. match() already returns no pairs for that input, and the counting after the branch reads the same either way, so the branch only restated what the callee guarantees. Removing it drops a special case from the method and makes the note in the match() docstring true. That note says calculate_metrics counts on the empty return rather than treating it as an error, which was not the case while this branch stood in front of it. It also puts the guard in match() under test through the public path, where it was reachable only by a direct call before. Two branches remain. One is the single item shortcut, which exists to skip the solver, and the other is every other shape. Refs awslabs#231
Security Scan ResultsASH Security Scan Report
Scan Metadata
SummaryScanner ResultsThe table below shows findings by scanner, with status based on severity thresholds and dependencies:
Top 1 HotspotsFiles with the highest number of security findings:
Detailed FindingsShow 2 actionable findingsFinding 1: SECRET-HEX-HIGH-ENTROPY-STRING
Description: Code Snippet: Finding 2: B108
Description: Code Snippet: Report generated by Automated Security Helper (ASH) at 2026-09-03T20:39:37+00:00 |
sromoam
left a comment
There was a problem hiding this comment.
Thanks @digalaviz. The code is correct and I could not find a behavioural bug in it. Verified rather than read: the new calculate_metrics was diffed against a reimplementation of the previous one across 4000 random shapes and thresholds, and tp, fp, precision, recall, f1 and matched_pairs are bit-identical, with the migration identity old_fn == fn + fd holding everywhere. The removed empty-list branches are correctly subsumed by match() returning [], np.array([]), and folding the 1x1 fast path into the shared counting code is the right call. 2097 passed, 12 skipped, ruff check clean.
Requesting changes on the documentation this PR adds, because two pieces of it would mislead the next person on the exact subject of the fix.
1. The new README says HungarianMatcher is shared with the ANLS Star path. It is not.
src/stickler/algorithms/README.md:6:
It is shared by the traditional and the ANLS Star evaluation paths.
There are two internal callers, both on the traditional path:
models/hungarian_helper.py:13 HungarianMatcher(StructuredModelComparator())
models/comparison_helper.py:113 HungarianMatcher(...)
ANLS Star has its own implementation and does not go through this class at all:
trees/list_tree.py:6 from munkres import Munkres, make_cost_matrix
trees/list_tree.py:55 def _hungarian(...)
The harm is specific and lands on the thing this PR fixes. This README exists to orient maintainers, and it tells them the #231 FD/FN correction reached the ANLS Star path. It did not. Someone auditing anls_score for the same conflation will read this, conclude it is already covered, and stop looking.
Worth noting this is another instance of #135, the two parallel evaluation paths. A cross-reference in the README would help more than the current sentence does.
2. recall can no longer be rederived from the counts beside it
m = HungarianMatcher(comparator=LevenshteinComparator(), match_threshold=0.9)
m.calculate_metrics(["red", "blue", "green"], ["red", "yellow", "orange", "blue"])returned: {'tp': 2, 'fd': 1, 'fp': 2, 'fn': 0, 'recall': 0.6667}
recall as returned : 0.6667
TP/(TP+FN) from the returned counts : 1.0 <- the project's documented default
TP/(TP+FN+FD) : 0.6667
recall = tp / m implements TP/(TP+FN+FD), which is the recall_with_fd=True convention. But the dict now returns an fn that excludes FD, so the returned dict contradicts itself: fn=0 sits beside a recall computed as though fn=1. Before this PR fn=1 and the two agreed.
The docstring at line 281 flags the divergence from MetricsHelper, which is good, but nothing flags that the returned dict is internally inconsistent. Either expose the convention as a parameter, or say plainly in the Returns block that recall here follows recall_with_fd=True and cannot be recomputed from the fn beside it.
3. Three documentation sites now contradict their own examples
docs/docs/Advanced/classification-logic.md-- the corrected worked example now yieldsFN=0, but the Derived Metrics table further down the same page still statesRecall = TP / (TP + FN). A reader applying the page's own formula to the page's own example gets1.0for a case where one of three ground-truth values was never found.docs/docs/Advanced/hungarian-matching.md:45-- the added paragraph sayscalculate_metrics"returns these same four counts if you call it directly", and it sits immediately above the FD-and-recall table whose default row readsTP / (TP + FN)with "an FD is invisible to recall".calculate_metricsuses the other row.src/stickler/algorithms/README.md:71andCHANGELOG.md:39-- both nameHungarianHelper.match_lists, which does not exist. The method isHungarianHelper.get_complete_matching_info(models/hungarian_helper.py:15). The changelog uses it to justify "no evaluator score changes", so a reader verifying that claim greps formatch_listsand finds nothing.
Not findings, recorded so they are not re-investigated
match()hangs indefinitely if a comparator returnsNaN, because munkres never converges. Reproduced, butmatch()is untouched here and the previouscalculate_metricsreached it identically. Pre-existing.test_hungarian_path_parity.pyfailsruff format --check. Also pre-existing ona4a1249, and CI runsruff checkrather than a format check.- The breaking change sits in
[Unreleased]under### FixedwhileRELEASING.md:25implies a major bump. 0.7.0 shipped two breaking changes as a minor, so this matches precedent for a 0.x project. No action.
Happy to approve once the docs match the behaviour. The counting change itself I would take as is.
Review of the awslabs#231 fix found three documentation errors, all on the subject of the fix itself. The algorithms README said HungarianMatcher is shared with the ANLS Star path. It is not: both internal callers are on the traditional path, and trees/list_tree.py calls Munkres itself in ANLSList._hungarian, turning the assignment into averaged NLS scores rather than into these counts. As written the README told a maintainer auditing anls_score for the same FD/FN conflation that awslabs#231 had already covered it. It now cross-references awslabs#135, the two parallel evaluation paths, and says that the fix reaches only this class. calculate_metrics returns recall as tp / m, which is TP/(TP+FN+FD), the recall_with_fd=True convention, beside an fn that excludes FD. The dict therefore cannot be read as a whole: the project's default TP/(TP+FN) over these keys gives a higher number. Stated in the Returns block, where a direct caller looks, and in the README. Documented rather than exposed as a parameter, so no returned value moves. classification-logic.md stated Recall = TP / (TP + FN) below a worked example that now yields FN=0, so the page's own formula scored 1.000 for a case where one of three ground-truth values was never found. hungarian-matching.md pointed at the default row of the FD-and-recall table for a method that uses the other row. Also renames HungarianHelper.match_lists, which does not exist, to get_complete_matching_info in the README and the changelog. The changelog uses it to justify "no evaluator score changes", so the name has to be greppable. Documentation only, no behavior change. 2097 passed, 12 skipped; ruff check clean on src and tests; mkdocs build resolves the new anchor.
|
Thanks @sromoam — all three are fixed in 746054a. Documentation only, no behaviour change.
One correction to my own first pass at that sentence: I had written that list_tree.py "derives
3a. classification-logic.md. Two layers, since a reader may only skim the table: the Recall row 3b. hungarian-matching.md. The paragraph now says its recall key follows the recall_with_fd=True 3c. match_lists. Renamed to HungarianHelper.get_complete_matching_info in both the README and the Verification: 2097 passed, 12 skipped; ruff check src tests clean; mkdocs build resolves the new Left alone deliberately, per your notes: the NaN hang in match(), the ruff format drift in |
|
@digalaviz can you pls resovle the merge conflict, and I'll review this ASAP? |
Resolve the CHANGELOG.md conflict under [Unreleased]. Both sides appended sections, so the resolution keeps both: the two awslabs#231 entries move into the single ### Fixed list that dev introduced, ahead of the awslabs#233 entries, and dev's ### Removed, ### Performance and ### Changed sections are untouched. No upstream commit touched src/stickler/algorithms/hungarian.py or its tests. 358c455 (awslabs#233) edited two of this branch's docs files and merged cleanly; it adopts the same FD vocabulary at object level.
|
@sromoam Conflict resolved — ready for review. I merged The conflict was only
Re-verified the claims the CHANGELOG entry makes, since #233 refactored the Full suite on the merge result: 2183 passed, 12 skipped, 0 failures. |
# Conflicts: # CHANGELOG.md
sromoam
left a comment
There was a problem hiding this comment.
Approving. All four documentation findings are fixed, and I verified them against the branch rather than reading the diff.
| Finding | Now |
|---|---|
README claimed HungarianMatcher is shared with the ANLS Star path |
Corrected, and the #135 cross-reference makes it more useful than the sentence I asked for |
recall could not be rederived from the fn beside it |
Stated in the Returns block and at the call-out in hungarian-matching.md |
| Three doc sites contradicted their own examples | All three fixed |
HungarianHelper.match_lists does not exist |
Gone from the README and the changelog |
The classification-logic.md fix went further than the finding: naming the trap explicitly ("the mixed-matching example above scores recall 1.000 even though "green" was never found"), giving the recall_with_fd=True value beside it, and stating that calculate_metrics always uses the second formula. That is the version I would have asked for if I had thought of it.
Re-verified on 381ff52:
Mixed Matching tp=2 fd=1 fa=1 fn=0 fp=2 green <-> orange at 0.17
recall 1.000 default / 0.667 with_fd
Below-Threshold tp=0 fd=3 fa=0 fn=0
2267 passed, 12 skipped ruff check clean
mkdocs 9 warnings (unchanged from dev)
181 passed in tests/common/algorithms/
Every count the two pages publish reproduces, including the pairing that produces them, so the worked examples are now derived from the engine rather than asserted next to it.
On the recall convention. I offered either a parameter or documentation, and you took documentation, which is a legitimate reading of the finding. Recording what that leaves behind so it is not rediscovered as a bug: the returned dict is still internally inconsistent, with fn=0 sitting beside a recall computed as though fn=1. It is now labelled rather than silent, which was the actual complaint. Making recall agree with its own fn would be a second breaking change to the same function, so if we want it, it wants to ride in the same release as this one rather than after it. I will raise that separately and it is not a condition of this PR.
I resolved the CHANGELOG.md conflict for you rather than sending you back around, since #290 and #300 both landed under this branch. Both sides were additive under ### Fixed, so nothing was dropped: your two bullets sit above the ones from dev, and I checked both directions (0 of dev's bullets missing, 0 of yours) plus no duplicated headings, because I have twice eaten someone's release note in exactly this kind of resolution.
One scheduling note, no action needed from you: #295 adds a paragraph immediately after the same Derived Metrics table in classification-logic.md. The two are compatible in content, yours is the more important paragraph, and I will rebase #295 onto this rather than the other way round.
Nice work on this one. The bug was real, the fix is minimal, and TestTheValuesThatMustNotChange is the thing that made it reviewable.
Pull Request
Issue Reference
Fixes #231
Description of Changes
HungarianMatcher.calculate_metricsderivedfnandfpaslen(list) - tp.So a pair the assignment produced, and that the method returns inside
matched_pairs, was also counted as a false negative when its score fell belowmatch_threshold. The same pair was reported as matched and as missing at thesame time, which makes a wrong value indistinguishable from a value the model
never produced.
The rule the project already documents is different, and the docs were right
while the code was wrong. Hungarian
Matching says
"the threshold splits matched pairs into TP and FD, it does not un-match them".
ComparisonHelper.unordered_list_metricsalready implemented exactly that. ThisPR brings
calculate_metricsin line with both.Changes Made
calculate_metricsnow returnsfd(pairs below the threshold) andfa(predictions with no partner).
fnkeeps its name and counts only groundtruth items with no partner.
their own hardcoded rate values, and one was the single item shortcut with its
own copy of the counting.
Raises: ValueErroronmatch()was removed. It documented an error themethod never raises, and the empty input contract is documented instead.
tests/common/algorithms/test_hungarian_fd_contract.py, 148 tests.test_hungarian.pyandtest_hungarian_path_parity.py, plus new assertions onfdandfa.Logic was
wrong and is corrected. See below.
src/stickler/algorithms/README.mdandtests/common/algorithms/README.md, asAGENTS.mdasks for.CHANGELOG.mdentry under[Unreleased]with the migration note.Why These Changes Are Needed
The five categories only carry information if they are disjoint. With
fntracking the threshold instead of the pairing, a caller cannot answer "did the
model miss this, or get it wrong" from the counts, and the two failures need
different responses.
Breaking change, and how far it reaches
fnis lower byfdfor any input where a pair scores below the threshold. Adirect caller that needs the old number reads
fn + fd, whichTestTheOldFnValueIsRecoverablepins for every shape so the note cannot gostale.
Nothing else changes value.
fpis still the rollupfd + fa, which stillequals the number of predictions that are not true positives, and
precision,recall,f1andmatched_pairsare identical for every input.TestTheValuesThatMustNotChangeholds 52 assertions that passed before the fixand still pass, so that claim is checkable rather than asserted here.
No evaluator score changes. Both internal callers read only
matched_pairs:HungarianHelper.match_listsmetrics["matched_pairs"]ComparisonHelper.compare_unordered_listsmetrics["matched_pairs"]Neither reads a count or a rate, which is why the full suite stayed green
through the behaviour change.
calculate_metricsis public in its own rightthough, so this is still breaking for a direct caller.
The documentation error
The worked list example claimed
TP=2, FA=2, FN=1, FD=0for a three itemground truth against a four item prediction. The assignment pairs three of them,
so
"green"is paired with"orange"at 0.17:"red""red""blue""blue""green""orange""yellow"So the counts are
TP=2, FD=1, FA=1, FN=0. The example had treated"green"and
"orange"as two unmatched items rather than as one low score pair, whichis the same conflation as the code defect. The
FPtotal came out right eitherway, which is why it went unnoticed. The example now shows the pairing, since
which items get paired is the part a reader cannot infer.
Testing
The tests were written first, with the 96 assertions that the old code violated
under
xfail(strict=True). A strict marker fails the suite if its assertionstarts passing while the marker is still there, so the red to green transition
is recorded rather than claimed, and no marker could be left behind. All 96
turned green on the fix and the markers were removed in the same commit.
Suite goes from 1949 passed to 2097 passed and 12 skipped. Coverage of
hungarian.pyis 88 percent, and the remaining gaps are the pre existingast.literal_evalfailure path, the size warning and the exception handler.One expectation in the new file was wrong and was corrected rather than the
implementation: it asserted precision 1.0 whenever the prediction list is empty,
which contradicts the repository's own behaviour of scoring 0.0 when there was
something to find. Saying nothing must not read as perfect precision.
Reviewers
Checklist
CHANGELOG.mdentry added under[Unreleased]Additional Notes
Four commits, each meant to be readable on its own: the contract as a test, the
fix, the docs, and one small simplification that lets
match()own the emptylist case.
The audit behind this turned up other things in the same file that are out of
scope here and are better as their own issues. Happy to open them, or to fold
any of them in if a maintainer prefers:
match_threshold=0.0is a capture all sentinel that silently makestpmeaningless. It warns at the model layer but not at this one.
>=whileThresholdHelper,ComparisonHelperandConfusionMatrixCalculatoraccept a score up to1e-10under the threshold, so the same score classifies differently in thetwo places.
recallcounts an FD against the score here, whileMetricsHelper.calculate_derived_metricsdefaults to excluding it, so thesame counts read differently as
cm_recall.normalize_valuesdefaults toTrue, which overrides a field's declaredcomparator and makes
List[bbox]unscoreable. Two of three call sitesalready opt out.
match()prints and re-raises on failure rather than logging._normalize_valuemapsNoneto"", which bypassesBaseComparator'sNonepolicy.