Skip to content

fix: Preserve non-comparable field verdicts - #544

Open
lj1166 wants to merge 3 commits into
awslabs:devfrom
lj1166:fix-field-comparison-verdict
Open

lj1166 wants to merge 3 commits into
awslabs:devfrom
lj1166:fix-field-comparison-verdict

Conversation

@lj1166

@lj1166 lj1166 commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #509

Description of changes:

Preserve the dispatcher's non-comparable verdict when collecting field comparisons. This prevents a type mismatch with a zero threshold from being reported as match: True while the confusion matrix correctly counts it as an FD.

Add a regression test for an Any field comparing a string with a list at threshold 0.0.

Tests:

uv run pytest tests/structured_object_evaluator/test_field_comparison_collection.py tests/structured_object_evaluator/test_rollup_node_semantics.py -q
uv run ruff check src/stickler/structured_object_evaluator/models/comparison_dispatcher.py src/stickler/structured_object_evaluator/models/field_comparison_collector.py tests/structured_object_evaluator/test_field_comparison_collection.py

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

Follow-up validation: non-comparable verdicts live in operation-local reporting context rather than public confusion-matrix fields. Focused Windows/Python 3.12 UTF-8 run: 70 passed. Clean Linux source snapshots: prior head 2,056 passed / 3 skipped; fixed head 2,057 passed / 3 skipped in the full structured-object-evaluator suite. Native Windows broader suite has six pre-existing SIGALRM-platform failures; no Windows full-suite pass is claimed. CHANGELOG updated under Unreleased / Fixed.

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

I reproduced the issue and verified the proposed fix against current dev.

Measured baseline on dev

import stickler, inspect; print(inspect.getfile(stickler))
from typing import Any
from stickler.structured_object_evaluator import ComparableField, StructuredModel

class AnyValue(StructuredModel):
    value: Any = ComparableField(threshold=0.0)

result = AnyValue(value="abc").compare_with(
    AnyValue(value=[1]),
    include_confusion_matrix=True,
    document_field_comparisons=True,
)
print("field_comparisons:", result["field_comparisons"])
print("confusion_matrix overall:", result["confusion_matrix"]["fields"]["value"]["overall"])

Output on dev (src/stickler/__init__.py):

field_comparisons: [{'expected_key': 'value', 'expected_value': 'abc', 'actual_key': 'value', 'actual_value': [1], 'match': True, 'score': 0.0, 'weighted_score': 0.0, 'reason': 'above threshold (0.000 >= 0.0)'}]
confusion_matrix overall: {'tp': 0, 'fa': 0, 'fd': 1, 'fp': 1, 'tn': 0, 'fn': 0, ...}

As shown, dev produces a contradiction where confusion_matrix classifies the type mismatch as a false discovery (fd: 1), but field_comparisons reports 'match': True because ThresholdHelper.is_above_threshold(0.0, 0.0) evaluates to True.

Verification with PR #544

With this change applied:

  • comparison["match"] is correctly False.
  • comparison["reason"] is 'not comparable', cleanly aligning with the confusion matrix.
  • All 17 tests in tests/structured_object_evaluator/test_field_comparison_collection.py pass.

Suggestions

  1. Changelog entry: Consider adding a bullet in CHANGELOG.md under [Unreleased] -> ### Fixed describing the fix, e.g.:
    - `collect_field_comparisons` now preserves the dispatcher's non-comparable verdict so type-mismatched fields with `threshold=0.0` are reported with `match: False` and `reason: "not comparable"` rather than being marked as matches (#509).
  2. Private key hygiene: Adding _not_comparable: True to _not_comparable() causes the key to appear in result["confusion_matrix"]["fields"][field_name]. Because it has a leading underscore, it treats it as private/internal metadata, which is clean and safe, but worth keeping in mind if consumers inspect dictionary keys directly.

@hayleypark

Copy link
Copy Markdown
Contributor

Thanks @lj1166, taking this. On a first read the fix looks right; full review after the release work. Two things for then: the _not_comparable marker leaks into confusion_matrix["fields"][...], and it needs a CHANGELOG entry under [Unreleased] → Fixed. Please also change the body to Fixes #509 so the issue closes on merge.

Signed-off-by: luojie <16602829831@163.com>
@lj1166

lj1166 commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Addressed in dd9c393. The non-comparable verdict now lives in operation-local ReportingContext, so it is not serialized into confusion-matrix fields or direct dispatcher results. Added a nested-field regression and a public-result assertion; both reproduce the leak on the prior head. Added the Unreleased → Fixed changelog entry and changed the PR body to Fixes #509.

Validation uses the checkout's src explicitly. Focused Windows/Python 3.12 with UTF-8: 70 passed. Clean Linux source snapshots: prior head 2,056 passed / 3 skipped; fixed head 2,057 passed / 3 skipped across tests/structured_object_evaluator. Scoped Ruff passes. The broader native Windows run has six SIGALRM-platform failures; no Windows full-suite pass claimed.

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

needs changes

The code fix is correct and scoped to #509. One medium issue: the CHANGELOG entry conflicts with dev and describes the change wrongly. Measured at head dd9c393.

stickler/CHANGELOG.md

Lines 12 to 16 in dd9c393

### Fixed
- Field comparison reports retain the dispatcher's non-comparable verdict at a
zero threshold, without exposing internal verdict metadata in confusion matrices
([#509](https://github.com/awslabs/stickler/issues/509)).

  1. Conflict. git merge-tree origin/dev dd9c393 reports CONFLICT (content) in CHANGELOG.md, because dev already has a ### Fixed section under [Unreleased]. Move the bullet under that section.
  2. The entry understates the change. It says the verdict is kept "at a zero threshold". In fact, field_comparisons[].reason becomes not comparable at every threshold. Two Any fields compared as "abc" vs [1]:
dev:  v (threshold 0.5)  match=False  reason='below threshold (0.000 < 0.5)'
      w (threshold 0.0)  match=True   reason='above threshold (0.000 >= 0.0)'
PR:   v (threshold 0.5)  match=False  reason='not comparable'
      w (threshold 0.0)  match=False  reason='not comparable'

Anyone who matches on reason strings will see the first change, and the note does not mention it. "Without exposing internal verdict metadata in confusion matrices" describes an internal detail of an earlier head, so it can go. Suggested bullet: "field_comparisons now reports a type-mismatched pair as match: False, reason: "not comparable", matching the confusion matrix's FD. It was previously reported as a match at threshold 0.0, and with a 'below threshold' reason otherwise (#509)."

Verified and cleared

  • #509 reproduces on dev (match: True, CM fd: 1) and is fixed here (match: False, CM unchanged).
  • 400 random documents without non-comparable fields, every reporting flag on: the full JSON is byte-identical on dev and the PR. In a mixed-type run, only the reason text changed (256 rows). No score, CM count or match value changed.
  • Full suite: 4093 passed, 13 skipped, 1 xfailed. tests/structured_object_evaluator: 2057 passed, 3 skipped, matching the body.
  • Mutations are caught: removing report_context.not_comparable.add(...), dropping not is_not_comparable and, and re-adding the earlier head's _not_comparable key.
  • No state leaks between same-named fields in parents, list items or nested children. hayleypark's two points are addressed.

Non-blocking (low): non_matches still says below threshold (0.000 < 0.0) for the same pair. That predates this PR, and #509 does not ask for it. It is worth a follow-up issue.

Signed-off-by: luojie <16602829831@163.com>
@lj1166

lj1166 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the changelog feedback in ec2988c, merging current dev 232982e without rewriting branch history. The #509 bullet is now under dev's existing Unreleased → Fixed section, preserves the other entries, and explains the not comparable reason at positive thresholds as well as the corrected match at 0.0. Removed the obsolete internal-metadata wording.

Validated the merged checkout explicitly through PYTHONPATH=/root/stickler544-1111/src: tests/structured_object_evaluator passes 2,059 tests / 3 skipped. No conflict remains with the fetched dev. The scope stays #509; non_matches reason wording remains outside this change.

@sromoam sromoam left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the careful follow-ups here. Moving the verdict into ReportingContext was the right call, and the nested regression test is a nice touch.

Measured against this branch (ec2988c, stickler imported from the checkout), with dev at 8c56dfa for comparison. Two Any fields holding "abc" vs [1]:

dev:  w (threshold 0.0)  match=True   reason='above threshold (0.000 >= 0.0)'   CM fd=1
      v (threshold 0.5)  match=False  reason='below threshold (0.000 < 0.5)'    CM fd=1
PR:   w (threshold 0.0)  match=False  reason='not comparable'                   CM fd=1
      v (threshold 0.5)  match=False  reason='not comparable'                   CM fd=1

The confusion matrix is identical to dev, a comparable pair at threshold 0.0 is still a match (as the zero-threshold docs say), and reusing a ground-truth instance does not carry the verdict into the next call. Both new tests fail on dev and pass here. The one blocker is that dev has moved since your last merge.

Must fix

  • Conflicts with dev again, now in comparison_dispatcher.py as well as CHANGELOG.md. #535 folded the dict branch (CASE 4) and the plain-BaseModel branch (CASE 5) into one elif, so dev has two _not_comparable call sites instead of three. Git only conflicts on the CASE 4/5 comment and elif header. Take dev's combined block there, and the auto-merged calls already pass field_name. In CHANGELOG.md, keep dev's new ### Fixed bullets and add yours alongside them. I tried that resolution on a scratch merge with dev 8c56dfa: test_field_comparison_collection.py passes (19, including both new tests), and so do test_rollup_node_semantics.py, test_scalar_field_dispatch.py, test_nested_plain_basemodel.py, and test_list_reporting_review.py.

Smaller

  • docs/docs/Guides/Evaluation/understanding-results.md:391 defines match as "Whether the score met the threshold." That was already loose on dev at threshold 0.0 (false alarm, false negative, and unmatched list rows report match: False), and this PR adds not comparable pairs, so it is a good moment to tighten it. Suggested row: "Whether the pair counted as a match: both values present and comparable, and the score met the threshold. Always False for a false alarm, a false negative, or a not comparable pair, whatever the threshold." The same idea applies at docs/docs/Getting-Started/Contributing/architecture.md:235, which says raw_similarity_score "decides match in field_comparisons".
  • field_comparison_collector.py:154-157: the no-context fallback runs when a nested model's class overrides compare_recursive. There, the same type-mismatched pair reads not comparable at threshold 0.0 but below threshold (0.000 < 0.5) at 0.5, because fd > 0 with a 0.0 score looks like an ordinary miss. match is False either way, so the verdict is right; only the reason differs from the context path. Tests reach this branch (for example test_nested_compare_recursive_override_keeps_its_original_signature), but always with fd == 0, so none makes it True, and replacing it with False still passes. A short test with an overriding nested model and a not-comparable pair at a positive threshold, plus a one-line comment on when this runs, would pin it.
  • CHANGELOG.md:24: the bullet reads as covering every type-mismatched pair, but a mismatched leaf inside a List[StructuredModel] item still reports score 0.000 >= 0.0, but 1 item did not match (same on dev), and the override path above keeps below threshold at positive thresholds. List items are rightly outside #509, so scoping the bullet to top-level and nested-model fields would keep it accurate.

# prevents ANLS* substitution. Scored, warned, and not raised -- see
# ConfigurationHelper.can_score_object.
return self._not_comparable(weight)
return self._not_comparable(weight, field_name)

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.

dev folded this CASE 4 branch and CASE 5 below into one elif (#535), so this hunk conflicts now. Take dev's combined comment and elif; the auto-merged _not_comparable(weight, field_name) calls are already right.

is_not_comparable = (
field_name in report_context.not_comparable
if report_context is not None
else (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This fallback runs when a nested model overrides compare_recursive. Tests reach it but never with fd > 0, so replacing it with False still passes. Measured there for the same pair: not comparable at 0.0, below threshold (0.000 < 0.5) at 0.5. Could you add a test for that case and a short comment on when this branch runs?

Comment thread CHANGELOG.md

### Fixed

- `field_comparisons` now reports a type-mismatched pair as `match: False` 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.

Conflicts with dev's new ### Fixed entries; keep both sides. Small wording nit: list-item leaves still report the old reason, so 'top-level and nested-model fields' would be more exact.

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

needs changes

Both points from my review of dd9c393 are fixed in ec2988c. The one blocker left is that the branch conflicts with dev again, the same point sromoam raised. The conflict is mechanical, and the fix still works after resolving it. Measured at head ec2988c against dev c70ca6e.

Must fix

The branch does not merge into current dev. git merge-tree --write-tree origin/dev ec2988c reports CONFLICT (content) in two files:

  • # CASE 4: Both are dicts, whose keys the model did not declare
    # A dict annotation says "I do not know these keys", so there is no
    # per-key comparison config to apply and the whole mapping is scored as
    # one unit. Routed through the primitive path deliberately: that method
    # is only "primitive" in name -- it calls the field's configured
    # comparator, classifies TP/FD against the FIELD threshold, and honours
    # clip_under_threshold, which is exactly the treatment a dict needs.
    #
    # Before this branch existed, a dict fell through to the mismatched-types
    # branch and scored
    # 0.0 even against an identical copy of itself, and the comparator the
    # field declared was never consulted (#297). Zero-config evaluation
    # installs ANLSStarComparator here, which gives partial credit; see
    # stickler.comparators.anls.
    elif isinstance(gt_val, dict) and isinstance(pred_val, dict):
    if not ConfigurationHelper.can_compare_object_pair(
    self.model.__class__, field_name, info.comparator, gt_val, pred_val
    ):
    # Reachable via `Any` or a multi-arm union, or a mapping annotation
    # (including Optional[Dict]) with an explicit comparator that
    # prevents ANLS* substitution. Scored, warned, and not raised -- see
    # ConfigurationHelper.can_score_object.
    return self._not_comparable(weight, field_name)
    return self.field_comparator.compare_primitive_with_scores(
    gt_val, pred_val, field_name
    )
    # CASE 5: A nested plain pydantic BaseModel, which is not a StructuredModel
    # so CASE 3 does not reach it.
    #
    # It fell through to the mismatched-types branch below and scored 0.0
    # against an IDENTICAL object, reported as a false discovery: a perfect
    # match that is also a failure, which is the contradiction #287 removed
    # elsewhere. Meanwhile `List[plain BaseModel]` already scored correctly,
    # because CASE 2 sends anything that is not a StructuredModel element to
    # the primitive list comparator. So the singular and list forms of the
    # same shape disagreed.
    #
    # Routed through the primitive path for the same reason CASE 4 sends a
    # dict there: that method is only "primitive" in name. It calls the
    # field's configured comparator, classifies TP/FD against the field
    # threshold, and honours clip_under_threshold.
    #
    # This makes the two forms agree rather than introducing a third
    # behaviour. Scoring a plain BaseModel structurally, field by field, is
    # what `StructuredModel` is for and what `stickler.evaluate()` does by
    # wrapping one; doing it here instead would make a nested plain model
    # behave differently from the same model inside a list, trading this
    # inconsistency for another. See #135.
    #
    # The models are passed through UNCONVERTED, exactly as CASE 4 passes a
    # dict. Stringifying here looked equivalent because Levenshtein and Exact
    # coerce internally anyway, but it silently defeats any comparator that
    # reads structure: `ANLSStarComparator` scored 0.9091 on a stringified
    # model against 0.5000 on the same model in a list, which is the very
    # asymmetry this branch exists to remove. The comparator decides its own
    # coercion; the dispatcher does not decide for it.
    #
    # Two conditions have to hold before the pair is scored, and both live in
    # `ConfigurationHelper.can_compare_object_pair` rather than here: the two
    # values must describe the same shape, and the field's comparator must be
    # able to score an object at all. They are composed there because
    # `compare()` reaches the same question through `compare_field_raw` and a
    # list element reaches it through the Hungarian cost matrix, so spelling
    # either rule here is how the readers drift apart -- which is exactly what
    # happened twice while this branch was in review.
    #
    # A correctly annotated field never reaches the mismatch case: pydantic
    # refuses a `Dog` for an `Optional[Cat]` field at construction. It fires
    # where the annotation permitted both -- `Union[Cat, Dog]`, `Any`,
    # `object` -- or where a subclass was supplied for its base, which
    # `Optional[Base]` accepts.
    #
    # `info.comparator` is the one STEP 1 already resolved. Reading it again
    # here cost a third `_get_comparison_info` for one field in one dispatch,
    # and that call is not free: it builds a fresh `ANLSStarComparator` every
    # time, once per cell of a Hungarian cost matrix.
    elif isinstance(gt_val, BaseModel) and isinstance(pred_val, BaseModel):
    if not ConfigurationHelper.can_compare_object_pair(
    runs from the # CASE 4 comment to the CASE 5 elif. dev (#535) replaced this block with one # CASE 4/5 comment and one combined elif. Take dev's block. Your _not_comparable(weight, field_name) calls at dev's two remaining call sites then merge automatically. No other _not_comparable callers exist in src or tests.
  • stickler/CHANGELOG.md

    Lines 23 to 29 in ec2988c

    - `field_comparisons` now reports a type-mismatched pair as `match: False` and
    `reason: "not comparable"`, matching the confusion matrix's false discovery.
    It was previously reported as a match at threshold 0.0, and with a
    `below threshold` reason at positive thresholds
    ([#509](https://github.com/awslabs/stickler/issues/509)).
    conflicts with the #506, #478, pretty-printer, #508 and #541 bullets that dev added to ### Fixed. Keep both sides. dev's #541 bullet has no blank line after it, so add one above yours.

I resolved it that way on a scratch merge. Full suite: 4571 passed, 3 skipped, 1 xfailed. Ruff on the four changed files passes. The #509 reproduction gives the same output as the PR head.

My previous findings

  1. CHANGELOG placement: fixed, then conflicted again by newer dev. ec2988c moved the bullet under [Unreleased] ### Fixed and merged cleanly with dev 232982e. The new conflict comes from dev commits after that.
  2. Bullet understated the change: fixed. It now says the reason becomes not comparable at positive thresholds too, and the internal-metadata wording is gone.

Verified and cleared

  • True diff (git diff origin/dev...ec2988c, merge base 232982e): 5 files, +66/-9. ec2988c changes only CHANGELOG.md besides the merge.
  • Suite at ec2988c (stickler imported from the checkout's src): tests/structured_object_evaluator 2067 passed, 2 skipped. Full suite 4135 passed, 3 skipped, 1 xfailed.
  • #509, Any fields with "abc" vs [1]:
dev:  w (threshold 0.0)  match=True   reason='above threshold (0.000 >= 0.0)'  CM fd=1
      v (threshold 0.5)  match=False  reason='below threshold (0.000 < 0.5)'   CM fd=1
PR:   w (threshold 0.0)  match=False  reason='not comparable'                  CM fd=1
      v (threshold 0.5)  match=False  reason='not comparable'                  CM fd=1
      ok ("abc" vs "xyz", threshold 0.0)  match=True  CM tp=1
  • No _-prefixed keys in confusion_matrix["fields"]. No verdict leaks between same-named fields in a parent, a nested model and a List[StructuredModel] item. Reusing a ground-truth instance does not carry the verdict into the next call.
  • Mutations are caught (2 failures each): removing report_context.not_comparable.add(...), removing not is_not_comparable and, removing the not comparable reason branch, and replacing the context lookup with False.

Non-blocking (low): replacing the no-context fallback in field_comparison_collector.py:154-157 with False still passes every test, as sromoam noted. match is False on that path either way. sromoam's docs and bullet-scope points are also worth taking, but they do not block.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

field_comparisons reports match: True for a pair the confusion matrix counts as FD (not comparable, threshold 0.0)

5 participants