Skip to content

FIX: preserve winning score metadata in all-categories float aggregators - #4330

Open
Chen Yufeiyang (feiiiiii5) wants to merge 3 commits into
microsoft:mainfrom
feiiiiii5:fix/float-scale-all-categories-metadata
Open

Chen Yufeiyang (feiiiiii5) wants to merge 3 commits into
microsoft:mainfrom
feiiiiii5:fix/float-scale-all-categories-metadata

Conversation

@feiiiiii5

Copy link
Copy Markdown
Contributor

Description

When aggregating scores with FloatScaleScorerAllCategories.MAX or MIN, conflicting metadata keys between constituent scores were previously discarded because use_selected_score_metadata was neither supported when group_by_category=False in _create_aggregator_by_category nor enabled on FloatScaleScorerAllCategories.

This aligns FloatScaleScorerAllCategories.MAX and MIN with their FloatScaleScorerByCategory counterparts:

  • Update _create_aggregator_by_category to resolve conflicting metadata from the winning score when use_selected_score_metadata=True and group_by_category=False.
  • Enable use_selected_score_metadata=True on FloatScaleScorerAllCategories.MAX and MIN.
  • Add unit tests verifying metadata preservation and tie-breaking behavior for FloatScaleScorerAllCategories.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 05:15

Copilot AI 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.

🟢 Approval recommended

There are no active review issues for the change preserving winning-score metadata in all-categories MAX and MIN aggregation.

No open issues 🎉

What changed in this PR

This PR aligns all-categories float-score aggregation with per-category behavior by preserving the winning score’s metadata when keys conflict.

Changes:

  • Add selected-score metadata handling when category grouping is disabled.
  • Enable that behavior for FloatScaleScorerAllCategories.MAX and MIN.
  • Add tests for metadata merging and first-winner tie-breaking for MAX.
File Description
tests/​unit/​score/​test_float_scale_score_aggregator.py Tests conflicting metadata resolution for extrema and tie-breaking for MAX.
pyrit/​score/​float_scale/​float_scale_score_aggregator.py Preserves winning metadata in all-categories MAX and MIN aggregation.

Review effort: Balanced

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 PR; the tie-breaking test for MAX is a good addition. A few observations from the diff:

  1. metadata.update(selected_metadata) mutates metadata. I can't see from the hunk where metadata is created. If it is a variable of the enclosing factory (closed over by aggregator) rather than built per call, the update would carry keys from one invocation into the next. Could you confirm it is built fresh inside aggregator? If it is, a test that calls MAX twice on different inputs would guard against this.
  2. next(... if value == raw_result) has no default, so it raises StopIteration if nothing matches, for example if _float_values could ever yield a NaN. I may be missing that it filters those out. Passing a default, or an explicit assertion with a clear message, would make a failure easier to diagnose.
  3. The tie test covers MAX only. MIN uses the same code path with use_selected_score_metadata=True, so a tie case for MIN would complete the coverage.
  4. The new code selects by the unclamped raw_result, while the returned value is clamped. A test with an out-of-range score would show the two agree.

@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and helpful observations, Varun Poojari (@Varunpoojari)!

I've addressed each of the points in the latest commit:

  1. Isolation / Lifecycle of metadata:
    metadata is generated freshly on every call inside aggregator via metadata, category = combine_metadata_and_categories(scores_list), rather than closed over from factory definition time. To guarantee no state leaks across consecutive calls, I've added test_all_categories_max_does_not_leak_metadata_across_invocations, verifying that calling MAX twice on distinct batches isolates the metadata completely.

  2. Guarding against StopIteration:
    Updated the generator in selected_score = next(...) to pass a None default (next(..., None)), both for group_by_category=False and group_by_category=True. If no item matches, selected_score is safely handled without raising an uncaught StopIteration.

  3. Tie-breaking test coverage for MIN:
    Added test_all_categories_min_uses_first_winner_metadata_for_ties to match the existing test for MAX, verifying that MIN preserves the first winning score's metadata in tie scenarios.

  4. Clamping vs unclamped selection:
    Added test_all_categories_extrema_clamp_out_of_range_scores_and_preserve_metadata (using Score.model_construct to bypass validation on out-of-bounds scores). This test verifies that selection operates on the raw extrema to pick the correct metadata, and the returned value is properly clamped to [0.0, 1.0].

@hannahwestra25 hannahwestra25 self-assigned this Nov 21, 2026
result = max(0.0, min(1.0, result))
raw_result = result_func(float_values)
if use_selected_score_metadata:
selected_score = next(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] If no constituent matches raw_result (for example, a NaN score_value assigned after construction), this branch now drops the winner's metadata without any error and returns 1.0. Before this PR, the grouped branch raised here. Please raise an error in both branches (here and line 319). A small shared helper would also remove the duplicated block:

def _select_winner(scores, float_values, raw_result):
    winner = next((s for s, v in zip(scores, float_values, strict=True) if v == raw_result), None)
    if winner is None:
        raise ValueError(f"No constituent score matches aggregate value {raw_result!r}")
    return winner

if use_selected_score_metadata:
    metadata.update(_select_winner(scores_list, float_values, raw_result).score_metadata or {})

assert min_result.metadata == {"severity": 2, "low_only": 1, "high_only": 1}


def test_all_categories_max_uses_first_winner_metadata_for_ties() -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] AVERAGE runs through the same changed branch, but no test checks that it still drops conflicting metadata. Please add a test where the average equals one of the constituent scores, and consider parametrizing the MAX/MIN tie tests:

def test_all_categories_average_omits_conflicting_metadata() -> None:
    scores = [
        _mk_score(0.3, category=["Hate"], metadata={"severity": 1}),
        _mk_score(0.5, category=["Violence"], metadata={"severity": 3}),
        _mk_score(0.7, category=["Sexual"], metadata={"severity": 5}),
    ]
    result = FloatScaleScorerAllCategories.AVERAGE(scores)[0]
    assert result.value == 0.5
    assert "severity" not in result.metadata
@pytest.mark.parametrize("aggregator, tied, other", [
    (FloatScaleScorerAllCategories.MAX, 0.7, 0.3),
    (FloatScaleScorerAllCategories.MIN, 0.2, 0.8),
])
def test_all_categories_extrema_use_first_winner_metadata_for_ties(aggregator, tied, other) -> None:
    ...

Share one winner selector between the grouped and ungrouped branches so an unattributable aggregate raises instead of silently dropping the winner's metadata. Add coverage for AVERAGE and for both branches with a NaN value.
@feiiiiii5

Copy link
Copy Markdown
Contributor Author

Thanks hannahwestra25 — both P2 findings are addressed in 76836a0f.

  1. Added a shared _select_winner() helper that raises ValueError("No constituent score matches aggregate value ...") when nothing matches, and used it in both the grouped and ungrouped branches instead of the next(..., None) + silent-skip blocks.
  2. Added test_all_categories_average_omits_conflicting_metadata (AVERAGE still omits a conflicting key) and test_no_matching_constituent_raises_in_both_branches, parametrized over the all-categories and by-category aggregators with a NaN assigned after construction.

Verification: pytest tests/unit/score/test_float_scale_score_aggregator.py -q → 49 passed; ruff check and format clean on both changed files. Before the fix the NaN case returned a result with dropped metadata; now both branches raise.

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.

4 participants