From 167577614d6aa850c5e49bafbebd3062cfc010ad Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 11:29:59 -0500 Subject: [PATCH 1/8] feat(score): persist specificity and confusion counts in ObjectiveScorerMetrics --- .../scorer_evaluation/scorer_evaluator.py | 16 ++++-- .../score/scorer_evaluation/scorer_metrics.py | 22 ++++++++ tests/unit/score/test_scorer_evaluator.py | 35 ++++++++++++ tests/unit/score/test_scorer_metrics.py | 53 +++++++++++++++++++ tests/unit/score/test_scorer_metrics_io.py | 16 ++++++ 5 files changed, 138 insertions(+), 4 deletions(-) diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index d3e65ea0ec..f464e39830 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -855,13 +855,16 @@ def _compute_metrics( gold_scores = np.round(np.median(all_human_scores, axis=0)) majority_model_scores = np.round(np.median(all_model_scores, axis=0)) - true_positive = np.sum((gold_scores == 1) & (majority_model_scores == 1)) - false_positive = np.sum((gold_scores == 0) & (majority_model_scores == 1)) - true_negative = np.sum((gold_scores == 0) & (majority_model_scores == 0)) - false_negative = np.sum((gold_scores == 1) & (majority_model_scores == 0)) + true_positive = int(np.sum((gold_scores == 1) & (majority_model_scores == 1))) + false_positive = int(np.sum((gold_scores == 0) & (majority_model_scores == 1))) + true_negative = int(np.sum((gold_scores == 0) & (majority_model_scores == 0))) + false_negative = int(np.sum((gold_scores == 1) & (majority_model_scores == 0))) accuracy = (true_positive + true_negative) / gold_scores.size precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) > 0 else 0.0 recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) > 0 else 0.0 + specificity = ( + float(true_negative / (true_negative + false_positive)) if (true_negative + false_positive) > 0 else None + ) f1_score = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0 num_responses = all_human_scores.shape[1] @@ -874,7 +877,12 @@ def _compute_metrics( accuracy_standard_error=np.sqrt(accuracy * (1 - accuracy) / gold_scores.size), precision=precision, recall=recall, + specificity=specificity, f1_score=f1_score, + true_positive=true_positive, + false_positive=false_positive, + true_negative=true_negative, + false_negative=false_negative, num_scorer_trials=num_scorer_trials, dataset_name=dataset_name, dataset_version=dataset_version, diff --git a/pyrit/score/scorer_evaluation/scorer_metrics.py b/pyrit/score/scorer_evaluation/scorer_metrics.py index 0f5ede65ee..33cc3effb6 100644 --- a/pyrit/score/scorer_evaluation/scorer_metrics.py +++ b/pyrit/score/scorer_evaluation/scorer_metrics.py @@ -272,12 +272,29 @@ class ObjectiveScorerMetrics(ScorerMetrics): Args: accuracy (float): The accuracy of the model scores when using the majority vote of human scores as the gold label. + accuracy_standard_error (float): The standard error of the accuracy estimate. f1_score (float): The F1 score of the model scores, an indicator of performance of the LLM scorer in its alignment with human scores. precision (float): The precision of the model scores, an indicator of the model's accuracy in its positive predictions. recall (float): The recall of the model scores, an indicator of the model's ability to correctly identify positive labels. + specificity (float | None, optional): The true negative rate ``TN / (TN + FP)`` over + evaluated responses that reached a verdict. ``None`` when there are no gold-negative + responses (whereas ``precision`` and ``recall`` retain their existing ``0.0`` + convention when undefined) or for metrics recorded before this field existed. + true_positive (int | None, optional): Number of gold-positive responses scored positive + among evaluated responses that reached a verdict (``num_responses``). ``None`` for + metrics recorded before this field existed. + false_positive (int | None, optional): Number of gold-negative responses scored positive + among evaluated responses that reached a verdict (``num_responses``). ``None`` for + metrics recorded before this field existed. + true_negative (int | None, optional): Number of gold-negative responses scored negative + among evaluated responses that reached a verdict (``num_responses``). ``None`` for + metrics recorded before this field existed. + false_negative (int | None, optional): Number of gold-positive responses scored negative + among evaluated responses that reached a verdict (``num_responses``). ``None`` for + metrics recorded before this field existed. trial_scores (np.ndarray | None): The raw scores from each trial. Shape is (num_trials, num_responses). Useful for debugging and analyzing scorer variance. """ @@ -287,6 +304,11 @@ class ObjectiveScorerMetrics(ScorerMetrics): f1_score: float precision: float recall: float + specificity: float | None = field(default=None, kw_only=True) + true_positive: int | None = field(default=None, kw_only=True) + false_positive: int | None = field(default=None, kw_only=True) + true_negative: int | None = field(default=None, kw_only=True) + false_negative: int | None = field(default=None, kw_only=True) @dataclass diff --git a/tests/unit/score/test_scorer_evaluator.py b/tests/unit/score/test_scorer_evaluator.py index 5704ac31f8..fd69864a8d 100644 --- a/tests/unit/score/test_scorer_evaluator.py +++ b/tests/unit/score/test_scorer_evaluator.py @@ -403,6 +403,15 @@ def test_compute_objective_metrics_perfect_agreement(mock_objective_scorer): assert metrics.f1_score == 1.0 assert metrics.precision == 1.0 assert metrics.recall == 1.0 + assert metrics.specificity is None + assert metrics.true_positive == 2 + assert metrics.false_positive == 0 + assert metrics.true_negative == 0 + assert metrics.false_negative == 0 + assert ( + metrics.true_positive + metrics.false_positive + metrics.true_negative + metrics.false_negative + == metrics.num_responses + ) def test_compute_objective_metrics_partial_agreement(mock_objective_scorer): @@ -418,7 +427,33 @@ def test_compute_objective_metrics_partial_agreement(mock_objective_scorer): assert metrics.accuracy == 0.5 assert metrics.precision == 0.5 assert metrics.recall == 1.0 + assert metrics.specificity == 0.0 assert metrics.f1_score == pytest.approx(2 * 0.5 * 1.0 / (0.5 + 1.0)) + assert metrics.true_positive == 1 + assert metrics.false_positive == 1 + assert metrics.true_negative == 0 + assert metrics.false_negative == 0 + + +def test_compute_objective_metrics_specificity_and_confusion_counts(mock_objective_scorer): + evaluator = ObjectiveScorerEvaluator(scorer=mock_objective_scorer) + # 5 responses: gold = [1, 1, 0, 0, 0], model = [1, 0, 0, 0, 1] + # TP=1, FN=1, TN=2, FP=1 -> specificity = 2 / 3 + all_human_scores = np.array([[1, 1, 0, 0, 0]]) + all_model_scores = np.array([[1, 0, 0, 0, 1]]) + metrics = evaluator._compute_metrics( + all_human_scores=all_human_scores, all_model_scores=all_model_scores, num_scorer_trials=1 + ) + assert metrics.true_positive == 1 + assert metrics.false_negative == 1 + assert metrics.true_negative == 2 + assert metrics.false_positive == 1 + assert ( + metrics.true_positive + metrics.false_positive + metrics.true_negative + metrics.false_negative + == metrics.num_responses + ) + assert metrics.recall == pytest.approx(0.5) + assert metrics.specificity == pytest.approx(2 / 3) def test_compute_harm_metrics_perfect_agreement(mock_harm_scorer): diff --git a/tests/unit/score/test_scorer_metrics.py b/tests/unit/score/test_scorer_metrics.py index 315807818f..956084bdfd 100644 --- a/tests/unit/score/test_scorer_metrics.py +++ b/tests/unit/score/test_scorer_metrics.py @@ -110,6 +110,11 @@ def test_objective_metrics_round_trip_keeps_every_serializable_field(self, tmp_p f1_score=0.8, precision=0.85, recall=0.75, + specificity=0.95, + true_positive=1, + false_positive=0, + true_negative=1, + false_negative=0, num_scorer_trials=3, dataset_name="test_dataset", dataset_version="1.0", @@ -123,6 +128,11 @@ def test_objective_metrics_round_trip_keeps_every_serializable_field(self, tmp_p f.write(json_str) loaded = ObjectiveScorerMetrics.from_json_file(str(file_path)) assert loaded.num_input_responses == 3 + assert loaded.specificity == 0.95 + assert loaded.true_positive == 1 + assert loaded.false_positive == 0 + assert loaded.true_negative == 1 + assert loaded.false_negative == 0 expected = dataclasses.asdict(metrics) expected.pop("trial_scores") @@ -131,6 +141,26 @@ def test_objective_metrics_round_trip_keeps_every_serializable_field(self, tmp_p assert actual == expected assert loaded.trial_scores.tolist() == [[True, False], [False, False], [True, True]] + def test_objective_metrics_load_from_legacy_json_without_specificity_or_counts(self, tmp_path): + legacy = { + "num_responses": 10, + "num_human_raters": 3, + "accuracy": 0.9, + "accuracy_standard_error": 0.05, + "f1_score": 0.8, + "precision": 0.85, + "recall": 0.75, + } + file_path = tmp_path / "legacy_objective.json" + file_path.write_text(json.dumps({"metrics": legacy}), encoding="utf-8") + loaded = ObjectiveScorerMetrics.from_json_file(file_path) + assert loaded.accuracy == 0.9 + assert loaded.specificity is None + assert loaded.true_positive is None + assert loaded.false_positive is None + assert loaded.true_negative is None + assert loaded.false_negative is None + def test_to_json_rejects_values_that_are_not_numpy_or_json(self): metrics = ObjectiveScorerMetrics( num_responses=10, @@ -304,6 +334,29 @@ def test_get_all_objective_metrics_custom_file_path(self, tmp_path): assert len(results) == 2 assert all(isinstance(r.metrics, ObjectiveScorerMetrics) for r in results) + def test_get_all_objective_metrics_shipped_file_loads_every_row(self): + """Test that every row in the shipped objective_achieved_metrics.jsonl loads without silent drops.""" + from pyrit.common.path import SCORER_EVALS_PATH + + shipped_path = SCORER_EVALS_PATH / "objective" / "objective_achieved_metrics.jsonl" + raw_rows = [json.loads(line) for line in shipped_path.read_text(encoding="utf-8").splitlines() if line.strip()] + assert len(raw_rows) > 0 + + results = get_all_objective_metrics() + assert len(results) == len(raw_rows) + + for raw_row, loaded in zip(raw_rows, results, strict=True): + raw_metrics = raw_row["metrics"] + if "specificity" not in raw_metrics: + assert loaded.metrics.specificity is None + else: + assert loaded.metrics.specificity == raw_metrics["specificity"] + for count_field in ("true_positive", "false_positive", "true_negative", "false_negative"): + if count_field not in raw_metrics: + assert getattr(loaded.metrics, count_field) is None + else: + assert getattr(loaded.metrics, count_field) == raw_metrics[count_field] + def test_get_all_objective_metrics_empty_file(self, tmp_path): """Test handling of empty JSONL file.""" objective_dir = tmp_path / "objective" diff --git a/tests/unit/score/test_scorer_metrics_io.py b/tests/unit/score/test_scorer_metrics_io.py index 9802b63815..c943085862 100644 --- a/tests/unit/score/test_scorer_metrics_io.py +++ b/tests/unit/score/test_scorer_metrics_io.py @@ -166,6 +166,22 @@ def test_metrics_to_registry_dict_includes_values(): assert result["num_responses"] == 100 +def test_metrics_to_registry_dict_omits_none_specificity_and_keeps_zero_counts(): + metrics = _make_objective_metrics( + specificity=None, + true_positive=10, + false_positive=0, + true_negative=0, + false_negative=0, + ) + result = _metrics_to_registry_dict(metrics) + assert "specificity" not in result + assert result["true_positive"] == 10 + assert result["false_positive"] == 0 + assert result["true_negative"] == 0 + assert result["false_negative"] == 0 + + # --- find_objective_metrics_by_eval_hash tests --- From c776c2b86a41adf6bb845ed4dce59e86e779bff4 Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 11:33:51 -0500 Subject: [PATCH 2/8] feat(analytics): add 95% Wilson confidence interval to OutcomeStatistics --- doc/code/analytics/0_attack_results.md | 1 + doc/code/framework.md | 2 +- pyrit/analytics/outcome_statistics.py | 28 +++++++++-- pyrit/models/analytics.py | 48 ++++++++++++++++++- .../unit/analytics/test_outcome_statistics.py | 42 ++++++++++++++++ tests/unit/models/test_analytics.py | 20 ++++++++ 6 files changed, 135 insertions(+), 6 deletions(-) diff --git a/doc/code/analytics/0_attack_results.md b/doc/code/analytics/0_attack_results.md index dfdbc02033..7887d99677 100644 --- a/doc/code/analytics/0_attack_results.md +++ b/doc/code/analytics/0_attack_results.md @@ -20,6 +20,7 @@ policies together: | Field | Denominator | Meaning | |---|---|---| | `success_rate_decided` | Successes + failures | Success among decided outcomes, the existing ASR default. | +| `success_rate_ci_lower`, `success_rate_ci_upper` | Successes + failures | 95% Wilson score confidence interval bounds for the observed decided-outcome rate (`None` when `total_decided == 0`). | | `success_rate_all` | All four outcomes | Success among every selected result, including errors and undetermined outcomes. | `success_rate` remains the compatible stored field; `success_rate_decided` is its diff --git a/doc/code/framework.md b/doc/code/framework.md index c10332e3eb..192b3bde85 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -368,7 +368,7 @@ The below talks about responsibilities of most modules in the PyRIT library - `compute_scenario_statistics` owns execution-unit identity (atomic attack, technique configuration, and seed group), latest-attempt selection, and historical retry/error counts. It passes selected outcomes to the shared outcome calculator. SDK callers, the GUI backend's run detail and progress views, and the console, JSON, and HTML reports present its results (`ScenarioExecutionStatistics`, `ScenarioExecutionUnit`, and `ScenarioProgressCounts` in `pyrit.models`). The GUI run-history list aggregates counts in SQL (`MemoryInterface._build_scenario_history_aggregate_statement`) so it can page over many runs, then uses the shared percentage helper; `tests/unit/analytics/test_scenario_statistics_parity.py` keeps the paths in agreement. - Scenario attempts are ordered by timestamp, then their canonical lowercase UUID string. SQL Server uses this string order rather than its native UUID order for history ranking and progress pagination. Explicit seed attribution wins; an objective alone matches a planned seed group only when that match is unique. Legacy runs with identifier-only seed identities are recounted with the shared analytics. - Shared analytics contracts (filters, dimensions, typed values, reports, facets, result pages, and `AttackStats`) live in `pyrit.models.analytics`. They validate data without querying memory or calculating statistics. `AttackResultSelection` defines selection modes without changing existing callers. -- `compute_outcome_statistics` owns both success-rate denominators, totals, and shares. `success_rate_decided` (the explicit alias of `success_rate`) divides by successes plus failures; `success_rate_all` divides by all outcomes. `combine_outcome_statistics` revalidates and combines disjoint counts, never averages rates. Attack and scenario analytics share the same `OutcomeStatistics` model and calculations after independently selecting their populations. Models reject contradictory supplied totals/rates; they do not select populations or replace the supplied numbers. +- `compute_outcome_statistics` owns both success-rate denominators, the 95% Wilson confidence interval for the decided rate, totals, and shares. `success_rate_decided` (the explicit alias of `success_rate`) divides by successes plus failures; `success_rate_all` divides by all outcomes. `combine_outcome_statistics` revalidates and combines disjoint counts, never averages rates. Attack and scenario analytics share the same `OutcomeStatistics` model and calculations after independently selecting their populations. Models reject contradictory supplied totals/rates; they do not select populations or replace the supplied numbers. - `analyze_results` and `compute_technique_stats_async` remain maintained APIs. Their `include_outcome_statistics=True` option exposes the shared statistics directly; default `AttackStats` results retain their six-field shape. Existing scenario percentage fields also retain their defaults. Only the already-deprecated sync memory wrappers and `ScenarioResult.objective_achieved_rate` are scheduled for removal in 1.4.0. - [`AttackResultAnalytics`](./analytics/0_attack_results.md) provides async saved-result reports, lightweight result pages, and facet lookups. It supplies both shared success rates, display labels and exact additional drill-down predicates, and counts every saved result ID rather than latest scenario execution units. Memory owns cohort SQL and consistent projections; the SDK owns their interpretation. - Analytics facades sharing a memory instance share one loop-bound, bounded report/quick-query controller. Close that shared SDK lifetime before replacing or disposing memory; cancellation does not free a running query's slot before its actual session cleanup. SDK lifecycle is independent of backend runtime integration. diff --git a/pyrit/analytics/outcome_statistics.py b/pyrit/analytics/outcome_statistics.py index 5fcfdf723b..6161788c6d 100644 --- a/pyrit/analytics/outcome_statistics.py +++ b/pyrit/analytics/outcome_statistics.py @@ -6,6 +6,7 @@ from __future__ import annotations from collections import Counter +from math import sqrt from typing import TYPE_CHECKING from pyrit.models import AttackOutcome, OutcomeStatistics @@ -15,6 +16,8 @@ from pyrit.models import AttackStats +_WILSON_Z_95 = 1.959963984540054 + def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome, int]) -> OutcomeStatistics: """ @@ -22,15 +25,17 @@ def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome This function neither queries memory nor chooses result IDs, retries, roles, or scenario units. ``success_rate_decided`` (also ``success_rate``) uses success + failure; ``success_rate_all`` - uses every outcome. Both are proportions, not rounded percentages. + uses every outcome. ``success_rate_ci_lower`` and ``success_rate_ci_upper`` give the 95% Wilson + score confidence interval for the decided rate. All are proportions, not rounded percentages. Args: counts (Mapping[str, int] | Mapping[AttackOutcome, int]): Nonnegative saved-outcome counts. Omitted outcomes mean zero observations. Returns: - OutcomeStatistics: Counts, both denominator policies, and whole-population shares. - Empty denominators produce None; empty outcome shares are zero. + OutcomeStatistics: Counts, both denominator policies, 95% Wilson confidence interval bounds + for the decided rate, and whole-population shares. Empty denominators produce None; empty + outcome shares are zero. Raises: ValueError: If an outcome is unsupported or a count is not a nonnegative integer. @@ -42,6 +47,7 @@ def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome errors = values.get(AttackOutcome.ERROR, 0) decided = successes + failures total = decided + undetermined + errors + ci_lower, ci_upper = _wilson_ci(successes=successes, total=decided) return OutcomeStatistics( successes=successes, failures=failures, @@ -51,6 +57,8 @@ def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome total_results=total, success_rate=_rate(successes=successes, total=decided), success_rate_all=_rate(successes=successes, total=total), + success_rate_ci_lower=ci_lower, + success_rate_ci_upper=ci_upper, decided_share=_rate(successes=decided, total=total), outcome_shares={ outcome: _rate(successes=values.get(outcome, 0), total=total) or 0.0 for outcome in AttackOutcome @@ -122,3 +130,17 @@ def _validated_counts(counts: Mapping[str, int] | Mapping[AttackOutcome, int]) - def _rate(*, successes: int, total: int) -> float | None: return successes / total if total else None + + +def _wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | None]: + if not total: + return None, None + p = successes / total + inv_n = 1 / total + z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n + denom = 1.0 + z2_inv_n + center = (p + 0.5 * z2_inv_n) / denom + half_width = _WILSON_Z_95 * sqrt(max(0.0, (p * (1.0 - p) + 0.25 * z2_inv_n) * inv_n)) / denom + lower = 0.0 if successes == 0 else float(max(0.0, center - half_width)) + upper = 1.0 if successes == total else float(min(1.0, center + half_width)) + return lower, upper diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 4518c46598..3dadca8bc4 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -9,7 +9,7 @@ from dataclasses import dataclass, field from datetime import UTC, datetime from enum import Enum -from math import isclose, isfinite +from math import isclose, isfinite, sqrt from typing import Annotated, Any, ClassVar, Self from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, computed_field, field_validator, model_validator @@ -19,6 +19,7 @@ _OutcomeCount = Annotated[int, Field(strict=True, ge=0)] _OutcomeRate = Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)] +_WILSON_Z_95 = 1.959963984540054 @dataclass @@ -45,6 +46,9 @@ class AttackAnalyticsStatistics(AttackStats): ``success_rate_decided`` (also available as ``success_rate``) uses successes / decided results; errors and undetermined outcomes do not enter that denominator. + ``success_rate_ci_lower`` and ``success_rate_ci_upper`` give the 95% Wilson score + confidence interval for ``success_rate_decided`` (``None`` when ``total_decided == 0`` + or when omitted on older payloads). ``success_rate_all`` instead includes every outcome in its denominator, as do ``decided_share`` and ``outcome_shares``. Rates with no applicable denominator are ``None``; shares for an empty cohort @@ -54,7 +58,8 @@ class AttackAnalyticsStatistics(AttackStats): ``total_results`` can therefore describe distinct saved IDs or latest scenario units. The model does not select attempts or infer a counting policy. Construction and explicit revalidation reject contradictory supplied values. - The nullable all-outcome rate preserves older payloads that omit that field. + The nullable all-outcome rate and confidence-interval bounds preserve older + payloads that omit those fields. """ success_rate: _OutcomeRate | None @@ -67,6 +72,8 @@ class AttackAnalyticsStatistics(AttackStats): decided_share: _OutcomeRate | None outcome_shares: dict[AttackOutcome, _OutcomeRate] success_rate_all: _OutcomeRate | None = field(default=None, kw_only=True) + success_rate_ci_lower: _OutcomeRate | None = field(default=None, kw_only=True) + success_rate_ci_upper: _OutcomeRate | None = field(default=None, kw_only=True) def __post_init__(self) -> None: """Validate the supplied statistics without recalculating or replacing fields.""" @@ -105,6 +112,12 @@ def validate_consistency(self) -> None: self._validate_rate( name="success_rate", value=self.success_rate, numerator=self.successes, denominator=self.total_decided ) + self._validate_wilson_ci( + lower=self.success_rate_ci_lower, + upper=self.success_rate_ci_upper, + numerator=self.successes, + denominator=self.total_decided, + ) self._validate_rate( name="decided_share", value=self.decided_share, numerator=self.total_decided, denominator=self.total_results ) @@ -163,6 +176,37 @@ def _validate_rate( ): raise ValueError(f"{name} must agree with its outcome counts.") + @staticmethod + def _validate_wilson_ci(*, lower: float | None, upper: float | None, numerator: int, denominator: int) -> None: + if lower is None and upper is None: + return + if ( + denominator == 0 + or lower is None + or upper is None + or isinstance(lower, bool) + or isinstance(upper, bool) + or not isinstance(lower, (int, float)) + or not isinstance(upper, (int, float)) + or not isfinite(lower) + or not isfinite(upper) + or not 0 <= lower <= upper <= 1 + ): + raise ValueError("success_rate confidence interval must agree with its outcome counts.") + p = numerator / denominator + inv_n = 1 / denominator + z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n + denom = 1.0 + z2_inv_n + center = (p + 0.5 * z2_inv_n) / denom + half_width = _WILSON_Z_95 * sqrt(max(0.0, (p * (1.0 - p) + 0.25 * z2_inv_n) * inv_n)) / denom + expected_lower = 0.0 if numerator == 0 else max(0.0, center - half_width) + expected_upper = 1.0 if numerator == denominator else min(1.0, center + half_width) + if not ( + isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=1e-12) + and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=1e-12) + ): + raise ValueError("success_rate confidence interval must agree with its outcome counts.") + # Preserve the existing class/constructor identity while sharing it beyond attack reports. OutcomeStatistics = AttackAnalyticsStatistics diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index f2b9c2abe4..d621668de7 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -5,6 +5,7 @@ from itertools import product import pytest +from scipy.stats import binomtest from pyrit.analytics import combine_outcome_statistics, compute_outcome_statistics from pyrit.analytics.outcome_statistics import success_percentage @@ -31,6 +32,20 @@ def test_both_denominators_use_the_same_selected_outcome_counts( assert statistics.success_rate_all == (successes / total if total else None) assert statistics.decided_share == (decided / total if total else None) assert statistics.outcome_shares == {outcome: count / total if total else 0.0 for outcome, count in counts.items()} + if decided == 0: + assert statistics.success_rate_ci_lower is None + assert statistics.success_rate_ci_upper is None + else: + expected_ci = binomtest(successes, decided).proportion_ci(confidence_level=0.95, method="wilson") + assert statistics.success_rate_ci_lower == pytest.approx(expected_ci.low, rel=1e-12, abs=1e-12) + assert statistics.success_rate_ci_upper == pytest.approx(expected_ci.high, rel=1e-12, abs=1e-12) + assert ( + 0.0 + <= statistics.success_rate_ci_lower + <= statistics.success_rate + <= statistics.success_rate_ci_upper + <= 1.0 + ) assert isinstance(statistics, OutcomeStatistics) assert isinstance(statistics, AttackStats) @@ -57,6 +72,8 @@ def test_empty_population_rates_are_unavailable_not_zero() -> None: statistics = compute_outcome_statistics({}) assert statistics.success_rate is None assert statistics.success_rate_all is None + assert statistics.success_rate_ci_lower is None + assert statistics.success_rate_ci_upper is None assert statistics.decided_share is None assert statistics.total_results == 0 assert set(statistics.outcome_shares.values()) == {0.0} @@ -69,6 +86,31 @@ def test_large_integer_counts_validate_without_float_overflow() -> None: assert statistics.total_results == 4 * count assert statistics.success_rate_decided == 0.5 assert statistics.success_rate_all == 0.25 + assert statistics.success_rate_ci_lower == 0.5 + assert statistics.success_rate_ci_upper == 0.5 + + +@pytest.mark.parametrize( + ("successes", "failures", "expected_lower", "expected_upper"), + [ + (0, 50, 0.0, 0.07134759913335872), + (25, 25, 0.3664451431682858, 0.6335548568317142), + (50, 0, 0.9286524008666414, 1.0), + ], +) +def test_wilson_confidence_interval_boundaries_and_interior( + successes: int, failures: int, expected_lower: float, expected_upper: float +) -> None: + statistics = compute_outcome_statistics({"success": successes, "failure": failures, "undetermined": 5, "error": 3}) + scipy_ci = binomtest(successes, successes + failures).proportion_ci(confidence_level=0.95, method="wilson") + assert statistics.success_rate_ci_lower == pytest.approx(expected_lower, rel=1e-12, abs=1e-12) + assert statistics.success_rate_ci_upper == pytest.approx(expected_upper, rel=1e-12, abs=1e-12) + assert statistics.success_rate_ci_lower == pytest.approx(scipy_ci.low, rel=1e-12, abs=1e-12) + assert statistics.success_rate_ci_upper == pytest.approx(scipy_ci.high, rel=1e-12, abs=1e-12) + if successes == 0: + assert statistics.success_rate_ci_lower == 0.0 + if failures == 0: + assert statistics.success_rate_ci_upper == 1.0 @pytest.mark.parametrize("counts", [{"unexpected": 1}, {"success": -1}, {"success": True}, {"error": 1.5}]) diff --git a/tests/unit/models/test_analytics.py b/tests/unit/models/test_analytics.py index 322b45e270..4030ae10a0 100644 --- a/tests/unit/models/test_analytics.py +++ b/tests/unit/models/test_analytics.py @@ -128,6 +128,10 @@ def test_scenario_counts_reject_contradictory_outcomes(changes: dict[str, int], {"outcome_shares": {AttackOutcome.SUCCESS: 1.0}}, {"success_rate": float("nan")}, {"success_rate_all": float("inf")}, + {"success_rate_ci_lower": None}, + {"success_rate_ci_upper": None}, + {"success_rate_ci_lower": 0.4, "success_rate_ci_upper": 0.6}, + {"success_rate_ci_lower": 0.8, "success_rate_ci_upper": 0.2}, ], ) def test_shared_statistics_reject_inconsistent_counts_and_rates(changes: dict[str, object]) -> None: @@ -138,6 +142,22 @@ def test_shared_statistics_reject_inconsistent_counts_and_rates(changes: dict[st TypeAdapter(OutcomeStatistics).validate_python({**asdict(statistics), **changes}) +def test_shared_statistics_accept_legacy_payload_without_confidence_interval_and_reject_empty_decided_ci() -> None: + statistics = compute_outcome_statistics({"success": 1, "failure": 1, "error": 2}) + legacy_payload = asdict(statistics) + legacy_payload.pop("success_rate_ci_lower") + legacy_payload.pop("success_rate_ci_upper") + restored = TypeAdapter(OutcomeStatistics).validate_python(legacy_payload) + assert restored.success_rate_ci_lower is None + assert restored.success_rate_ci_upper is None + + empty_decided = compute_outcome_statistics({"error": 2}) + with pytest.raises(ValidationError): + TypeAdapter(OutcomeStatistics).validate_python( + {**asdict(empty_decided), "success_rate_ci_lower": 0.0, "success_rate_ci_upper": 1.0} + ) + + def test_reembedding_mutated_outcomes_revalidates_the_counts() -> None: statistics = compute_outcome_statistics({"success": 1}) statistics.successes = 5 From 6207f3c3a59971781456a0665dd9132bc4ff0aec Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 12:47:12 -0500 Subject: [PATCH 3/8] fix(analytics): prevent Wilson CI underflow and enforce relative tolerance --- pyrit/analytics/outcome_statistics.py | 2 +- pyrit/models/analytics.py | 6 +++--- tests/unit/analytics/test_outcome_statistics.py | 10 ++++++++++ tests/unit/models/test_analytics.py | 8 ++++++++ 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pyrit/analytics/outcome_statistics.py b/pyrit/analytics/outcome_statistics.py index 6161788c6d..e86097b3be 100644 --- a/pyrit/analytics/outcome_statistics.py +++ b/pyrit/analytics/outcome_statistics.py @@ -140,7 +140,7 @@ def _wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | Non z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n denom = 1.0 + z2_inv_n center = (p + 0.5 * z2_inv_n) / denom - half_width = _WILSON_Z_95 * sqrt(max(0.0, (p * (1.0 - p) + 0.25 * z2_inv_n) * inv_n)) / denom + half_width = _WILSON_Z_95 * sqrt(max(0.0, p * (1.0 - p) + 0.25 * z2_inv_n)) * sqrt(inv_n) / denom lower = 0.0 if successes == 0 else float(max(0.0, center - half_width)) upper = 1.0 if successes == total else float(min(1.0, center + half_width)) return lower, upper diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 3dadca8bc4..9108aa8965 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -198,12 +198,12 @@ def _validate_wilson_ci(*, lower: float | None, upper: float | None, numerator: z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n denom = 1.0 + z2_inv_n center = (p + 0.5 * z2_inv_n) / denom - half_width = _WILSON_Z_95 * sqrt(max(0.0, (p * (1.0 - p) + 0.25 * z2_inv_n) * inv_n)) / denom + half_width = _WILSON_Z_95 * sqrt(max(0.0, p * (1.0 - p) + 0.25 * z2_inv_n)) * sqrt(inv_n) / denom expected_lower = 0.0 if numerator == 0 else max(0.0, center - half_width) expected_upper = 1.0 if numerator == denominator else min(1.0, center + half_width) if not ( - isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=1e-12) - and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=1e-12) + isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=0.0) + and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=0.0) ): raise ValueError("success_rate confidence interval must agree with its outcome counts.") diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index d621668de7..811811e5e6 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -90,6 +90,16 @@ def test_large_integer_counts_validate_without_float_overflow() -> None: assert statistics.success_rate_ci_upper == 0.5 +def test_skewed_large_integer_counts_do_not_underflow_wilson_interval() -> None: + total = 10**200 + statistics = compute_outcome_statistics({"success": 1, "failure": total - 1}) + assert statistics.success_rate_ci_lower is not None + assert statistics.success_rate_ci_upper is not None + assert 0.0 < statistics.success_rate_ci_lower < statistics.success_rate < statistics.success_rate_ci_upper + assert statistics.success_rate_ci_lower == pytest.approx(1.7655213934448394e-201, rel=1e-12, abs=0.0) + assert statistics.success_rate_ci_upper == pytest.approx(5.664049203893855e-200, rel=1e-12, abs=0.0) + + @pytest.mark.parametrize( ("successes", "failures", "expected_lower", "expected_upper"), [ diff --git a/tests/unit/models/test_analytics.py b/tests/unit/models/test_analytics.py index 4030ae10a0..da0e2f1185 100644 --- a/tests/unit/models/test_analytics.py +++ b/tests/unit/models/test_analytics.py @@ -157,6 +157,14 @@ def test_shared_statistics_accept_legacy_payload_without_confidence_interval_and {**asdict(empty_decided), "success_rate_ci_lower": 0.0, "success_rate_ci_upper": 1.0} ) + small_rate = compute_outcome_statistics({"success": 1, "failure": 10**14 - 1}) + with pytest.raises(ValueError, match="confidence interval"): + replace(small_rate, success_rate_ci_lower=0.0, success_rate_ci_upper=0.0) + with pytest.raises(ValidationError): + TypeAdapter(OutcomeStatistics).validate_python( + {**asdict(small_rate), "success_rate_ci_lower": 0.0, "success_rate_ci_upper": 0.0} + ) + def test_reembedding_mutated_outcomes_revalidates_the_counts() -> None: statistics = compute_outcome_statistics({"success": 1}) From c71badaf35671e1f70653049b099d57accbaba57 Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 12:49:06 -0500 Subject: [PATCH 4/8] test(analytics): align skewed Wilson CI constants with exact z-score --- tests/unit/analytics/test_outcome_statistics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index 811811e5e6..2d9f7e4470 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -96,8 +96,8 @@ def test_skewed_large_integer_counts_do_not_underflow_wilson_interval() -> None: assert statistics.success_rate_ci_lower is not None assert statistics.success_rate_ci_upper is not None assert 0.0 < statistics.success_rate_ci_lower < statistics.success_rate < statistics.success_rate_ci_upper - assert statistics.success_rate_ci_lower == pytest.approx(1.7655213934448394e-201, rel=1e-12, abs=0.0) - assert statistics.success_rate_ci_upper == pytest.approx(5.664049203893855e-200, rel=1e-12, abs=0.0) + assert statistics.success_rate_ci_lower == pytest.approx(1.765245549351526e-201, rel=1e-12, abs=0.0) + assert statistics.success_rate_ci_upper == pytest.approx(5.664934265758973e-200, rel=1e-12, abs=0.0) @pytest.mark.parametrize( From 42ebba452fd4d0d4db25bddeb76253a8407f5181 Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 13:09:12 -0500 Subject: [PATCH 5/8] fix(analytics): compute Wilson CI in Decimal to prevent subnormal underflow --- pyrit/analytics/outcome_statistics.py | 25 +++++++++++------- pyrit/models/analytics.py | 26 ++++++++++++------- .../unit/analytics/test_outcome_statistics.py | 13 ++++++++++ tests/unit/models/test_analytics.py | 8 ++++++ 4 files changed, 52 insertions(+), 20 deletions(-) diff --git a/pyrit/analytics/outcome_statistics.py b/pyrit/analytics/outcome_statistics.py index e86097b3be..fa79ace533 100644 --- a/pyrit/analytics/outcome_statistics.py +++ b/pyrit/analytics/outcome_statistics.py @@ -6,7 +6,7 @@ from __future__ import annotations from collections import Counter -from math import sqrt +from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext from typing import TYPE_CHECKING from pyrit.models import AttackOutcome, OutcomeStatistics @@ -16,7 +16,7 @@ from pyrit.models import AttackStats -_WILSON_Z_95 = 1.959963984540054 +_WILSON_Z_95 = Decimal("1.959963984540054") def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome, int]) -> OutcomeStatistics: @@ -135,12 +135,17 @@ def _rate(*, successes: int, total: int) -> float | None: def _wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | None]: if not total: return None, None - p = successes / total - inv_n = 1 / total - z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n - denom = 1.0 + z2_inv_n - center = (p + 0.5 * z2_inv_n) / denom - half_width = _WILSON_Z_95 * sqrt(max(0.0, p * (1.0 - p) + 0.25 * z2_inv_n)) * sqrt(inv_n) / denom - lower = 0.0 if successes == 0 else float(max(0.0, center - half_width)) - upper = 1.0 if successes == total else float(min(1.0, center + half_width)) + with localcontext() as ctx: + ctx.prec = 50 + ctx.Emin = MIN_EMIN + ctx.Emax = MAX_EMAX + n = Decimal(total) + p = Decimal(successes) / n + q = Decimal(total - successes) / n + z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) / n + denom = Decimal(1) + z2_inv_n + center = (p + Decimal("0.5") * z2_inv_n) / denom + half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom + lower = 0.0 if successes == 0 else float(max(Decimal(0), center - half_width)) + upper = 1.0 if successes == total else float(min(Decimal(1), center + half_width)) return lower, upper diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 9108aa8965..75693047a6 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -8,8 +8,9 @@ import uuid from dataclasses import dataclass, field from datetime import UTC, datetime +from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext from enum import Enum -from math import isclose, isfinite, sqrt +from math import isclose, isfinite from typing import Annotated, Any, ClassVar, Self from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, computed_field, field_validator, model_validator @@ -19,7 +20,7 @@ _OutcomeCount = Annotated[int, Field(strict=True, ge=0)] _OutcomeRate = Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)] -_WILSON_Z_95 = 1.959963984540054 +_WILSON_Z_95 = Decimal("1.959963984540054") @dataclass @@ -193,14 +194,19 @@ def _validate_wilson_ci(*, lower: float | None, upper: float | None, numerator: or not 0 <= lower <= upper <= 1 ): raise ValueError("success_rate confidence interval must agree with its outcome counts.") - p = numerator / denominator - inv_n = 1 / denominator - z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) * inv_n - denom = 1.0 + z2_inv_n - center = (p + 0.5 * z2_inv_n) / denom - half_width = _WILSON_Z_95 * sqrt(max(0.0, p * (1.0 - p) + 0.25 * z2_inv_n)) * sqrt(inv_n) / denom - expected_lower = 0.0 if numerator == 0 else max(0.0, center - half_width) - expected_upper = 1.0 if numerator == denominator else min(1.0, center + half_width) + with localcontext() as ctx: + ctx.prec = 50 + ctx.Emin = MIN_EMIN + ctx.Emax = MAX_EMAX + n = Decimal(denominator) + p = Decimal(numerator) / n + q = Decimal(denominator - numerator) / n + z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) / n + denom = Decimal(1) + z2_inv_n + center = (p + Decimal("0.5") * z2_inv_n) / denom + half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom + expected_lower = 0.0 if numerator == 0 else float(max(Decimal(0), center - half_width)) + expected_upper = 1.0 if numerator == denominator else float(min(Decimal(1), center + half_width)) if not ( isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=0.0) and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=0.0) diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index 2d9f7e4470..f041622378 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -99,6 +99,19 @@ def test_skewed_large_integer_counts_do_not_underflow_wilson_interval() -> None: assert statistics.success_rate_ci_lower == pytest.approx(1.765245549351526e-201, rel=1e-12, abs=0.0) assert statistics.success_rate_ci_upper == pytest.approx(5.664934265758973e-200, rel=1e-12, abs=0.0) + subnormal_total = 10**324 + subnormal_stats = compute_outcome_statistics({"success": 100, "failure": subnormal_total - 100}) + assert subnormal_stats.success_rate_ci_lower is not None + assert subnormal_stats.success_rate_ci_upper is not None + assert ( + 0.0 + < subnormal_stats.success_rate_ci_lower + < subnormal_stats.success_rate + < subnormal_stats.success_rate_ci_upper + ) + assert subnormal_stats.success_rate_ci_lower == 8.4e-323 + assert subnormal_stats.success_rate_ci_upper == 1.235e-322 + @pytest.mark.parametrize( ("successes", "failures", "expected_lower", "expected_upper"), diff --git a/tests/unit/models/test_analytics.py b/tests/unit/models/test_analytics.py index da0e2f1185..78cefe6a8d 100644 --- a/tests/unit/models/test_analytics.py +++ b/tests/unit/models/test_analytics.py @@ -165,6 +165,14 @@ def test_shared_statistics_accept_legacy_payload_without_confidence_interval_and {**asdict(small_rate), "success_rate_ci_lower": 0.0, "success_rate_ci_upper": 0.0} ) + subnormal_rate = compute_outcome_statistics({"success": 100, "failure": 10**324 - 100}) + with pytest.raises(ValueError, match="confidence interval"): + replace(subnormal_rate, success_rate_ci_lower=1e-322, success_rate_ci_upper=1e-322) + with pytest.raises(ValidationError): + TypeAdapter(OutcomeStatistics).validate_python( + {**asdict(subnormal_rate), "success_rate_ci_lower": 1e-322, "success_rate_ci_upper": 1e-322} + ) + def test_reembedding_mutated_outcomes_revalidates_the_counts() -> None: statistics = compute_outcome_statistics({"success": 1}) From a41557a6cc8e150e0b2aca9fe7298940f860b4a1 Mon Sep 17 00:00:00 2001 From: Nithin Date: Tue, 3 Nov 2026 16:37:44 -0500 Subject: [PATCH 6/8] fix(analytics): use explicit Decimal context to isolate Wilson CI from caller traps --- pyrit/analytics/outcome_statistics.py | 17 ++++++++++++----- pyrit/models/analytics.py | 17 ++++++++++++----- tests/unit/analytics/test_outcome_statistics.py | 13 +++++++++++++ tests/unit/models/test_analytics.py | 10 ++++++++++ 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/pyrit/analytics/outcome_statistics.py b/pyrit/analytics/outcome_statistics.py index fa79ace533..573b8bc632 100644 --- a/pyrit/analytics/outcome_statistics.py +++ b/pyrit/analytics/outcome_statistics.py @@ -6,7 +6,7 @@ from __future__ import annotations from collections import Counter -from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext +from decimal import MAX_EMAX, MIN_EMIN, ROUND_HALF_EVEN, Context, Decimal, localcontext from typing import TYPE_CHECKING from pyrit.models import AttackOutcome, OutcomeStatistics @@ -16,6 +16,16 @@ from pyrit.models import AttackStats +_WILSON_DECIMAL_CONTEXT = Context( + prec=50, + rounding=ROUND_HALF_EVEN, + Emin=MIN_EMIN, + Emax=MAX_EMAX, + capitals=1, + clamp=0, + flags=[], + traps=[], +) _WILSON_Z_95 = Decimal("1.959963984540054") @@ -135,10 +145,7 @@ def _rate(*, successes: int, total: int) -> float | None: def _wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | None]: if not total: return None, None - with localcontext() as ctx: - ctx.prec = 50 - ctx.Emin = MIN_EMIN - ctx.Emax = MAX_EMAX + with localcontext(_WILSON_DECIMAL_CONTEXT): n = Decimal(total) p = Decimal(successes) / n q = Decimal(total - successes) / n diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 75693047a6..7858b37df4 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -8,7 +8,7 @@ import uuid from dataclasses import dataclass, field from datetime import UTC, datetime -from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext +from decimal import MAX_EMAX, MIN_EMIN, ROUND_HALF_EVEN, Context, Decimal, localcontext from enum import Enum from math import isclose, isfinite from typing import Annotated, Any, ClassVar, Self @@ -20,6 +20,16 @@ _OutcomeCount = Annotated[int, Field(strict=True, ge=0)] _OutcomeRate = Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)] +_WILSON_DECIMAL_CONTEXT = Context( + prec=50, + rounding=ROUND_HALF_EVEN, + Emin=MIN_EMIN, + Emax=MAX_EMAX, + capitals=1, + clamp=0, + flags=[], + traps=[], +) _WILSON_Z_95 = Decimal("1.959963984540054") @@ -194,10 +204,7 @@ def _validate_wilson_ci(*, lower: float | None, upper: float | None, numerator: or not 0 <= lower <= upper <= 1 ): raise ValueError("success_rate confidence interval must agree with its outcome counts.") - with localcontext() as ctx: - ctx.prec = 50 - ctx.Emin = MIN_EMIN - ctx.Emax = MAX_EMAX + with localcontext(_WILSON_DECIMAL_CONTEXT): n = Decimal(denominator) p = Decimal(numerator) / n q = Decimal(denominator - numerator) / n diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index f041622378..9229193dd7 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -2,6 +2,7 @@ # Licensed under the MIT license. from dataclasses import asdict +from decimal import ROUND_CEILING, FloatOperation, Inexact, Rounded, Subnormal, localcontext from itertools import product import pytest @@ -113,6 +114,18 @@ def test_skewed_large_integer_counts_do_not_underflow_wilson_interval() -> None: assert subnormal_stats.success_rate_ci_upper == 1.235e-322 +def test_wilson_interval_ignores_caller_decimal_traps_and_rounding() -> None: + expected = compute_outcome_statistics({"success": 1, "failure": 1}) + with localcontext() as ctx: + ctx.rounding = ROUND_CEILING + ctx.traps[Inexact] = True + ctx.traps[Rounded] = True + ctx.traps[Subnormal] = True + ctx.traps[FloatOperation] = True + statistics = compute_outcome_statistics({"success": 1, "failure": 1}) + assert statistics == expected + + @pytest.mark.parametrize( ("successes", "failures", "expected_lower", "expected_upper"), [ diff --git a/tests/unit/models/test_analytics.py b/tests/unit/models/test_analytics.py index 78cefe6a8d..07e766ae12 100644 --- a/tests/unit/models/test_analytics.py +++ b/tests/unit/models/test_analytics.py @@ -4,6 +4,7 @@ import json from dataclasses import asdict, replace from datetime import UTC, datetime +from decimal import ROUND_CEILING, FloatOperation, Inexact, Rounded, Subnormal, localcontext from zoneinfo import ZoneInfo import pytest @@ -173,6 +174,15 @@ def test_shared_statistics_accept_legacy_payload_without_confidence_interval_and {**asdict(subnormal_rate), "success_rate_ci_lower": 1e-322, "success_rate_ci_upper": 1e-322} ) + payload = asdict(statistics) + with localcontext() as ctx: + ctx.rounding = ROUND_CEILING + ctx.traps[Inexact] = True + ctx.traps[Rounded] = True + ctx.traps[Subnormal] = True + ctx.traps[FloatOperation] = True + assert TypeAdapter(OutcomeStatistics).validate_python(payload) == statistics + def test_reembedding_mutated_outcomes_revalidates_the_counts() -> None: statistics = compute_outcome_statistics({"success": 1}) From 564e095690192528540a84f26e8984fe3553bda0 Mon Sep 17 00:00:00 2001 From: Nithin Date: Thu, 12 Nov 2026 20:34:29 -0500 Subject: [PATCH 7/8] refactor(analytics): deduplicate wilson confidence interval helper --- pyrit/analytics/outcome_statistics.py | 32 ++---------------- pyrit/models/analytics.py | 48 +++++++++++++++++++-------- 2 files changed, 37 insertions(+), 43 deletions(-) diff --git a/pyrit/analytics/outcome_statistics.py b/pyrit/analytics/outcome_statistics.py index 573b8bc632..1733ac1214 100644 --- a/pyrit/analytics/outcome_statistics.py +++ b/pyrit/analytics/outcome_statistics.py @@ -6,28 +6,16 @@ from __future__ import annotations from collections import Counter -from decimal import MAX_EMAX, MIN_EMIN, ROUND_HALF_EVEN, Context, Decimal, localcontext from typing import TYPE_CHECKING from pyrit.models import AttackOutcome, OutcomeStatistics +from pyrit.models.analytics import compute_wilson_ci if TYPE_CHECKING: from collections.abc import Iterable, Mapping from pyrit.models import AttackStats -_WILSON_DECIMAL_CONTEXT = Context( - prec=50, - rounding=ROUND_HALF_EVEN, - Emin=MIN_EMIN, - Emax=MAX_EMAX, - capitals=1, - clamp=0, - flags=[], - traps=[], -) -_WILSON_Z_95 = Decimal("1.959963984540054") - def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome, int]) -> OutcomeStatistics: """ @@ -57,7 +45,7 @@ def compute_outcome_statistics(counts: Mapping[str, int] | Mapping[AttackOutcome errors = values.get(AttackOutcome.ERROR, 0) decided = successes + failures total = decided + undetermined + errors - ci_lower, ci_upper = _wilson_ci(successes=successes, total=decided) + ci_lower, ci_upper = compute_wilson_ci(successes=successes, total=decided) return OutcomeStatistics( successes=successes, failures=failures, @@ -140,19 +128,3 @@ def _validated_counts(counts: Mapping[str, int] | Mapping[AttackOutcome, int]) - def _rate(*, successes: int, total: int) -> float | None: return successes / total if total else None - - -def _wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | None]: - if not total: - return None, None - with localcontext(_WILSON_DECIMAL_CONTEXT): - n = Decimal(total) - p = Decimal(successes) / n - q = Decimal(total - successes) / n - z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) / n - denom = Decimal(1) + z2_inv_n - center = (p + Decimal("0.5") * z2_inv_n) / denom - half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom - lower = 0.0 if successes == 0 else float(max(Decimal(0), center - half_width)) - upper = 1.0 if successes == total else float(min(Decimal(1), center + half_width)) - return lower, upper diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 064a6f2681..567621cc59 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -34,6 +34,33 @@ _WILSON_Z_95 = Decimal("1.959963984540054") +def compute_wilson_ci(*, successes: int, total: int) -> tuple[float | None, float | None]: + """ + Calculate the 95% Wilson score confidence interval for a proportion. + + Args: + successes (int): Number of successful observations. + total (int): Total number of decided observations. + + Returns: + tuple[float | None, float | None]: The (lower, upper) confidence interval bounds, + or (None, None) when total is 0. + """ + if not total: + return None, None + with localcontext(_WILSON_DECIMAL_CONTEXT): + n = Decimal(total) + p = Decimal(successes) / n + q = Decimal(total - successes) / n + z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) / n + denom = Decimal(1) + z2_inv_n + center = (p + Decimal("0.5") * z2_inv_n) / denom + half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom + lower = 0.0 if successes == 0 else float(max(Decimal(0), center - half_width)) + upper = 1.0 if successes == total else float(min(Decimal(1), center + half_width)) + return lower, upper + + @dataclass class AttackStats: """Compatible six-field statistics for attack analysis results.""" @@ -205,19 +232,14 @@ def _validate_wilson_ci(*, lower: float | None, upper: float | None, numerator: or not 0 <= lower <= upper <= 1 ): raise ValueError("success_rate confidence interval must agree with its outcome counts.") - with localcontext(_WILSON_DECIMAL_CONTEXT): - n = Decimal(denominator) - p = Decimal(numerator) / n - q = Decimal(denominator - numerator) / n - z2_inv_n = (_WILSON_Z_95 * _WILSON_Z_95) / n - denom = Decimal(1) + z2_inv_n - center = (p + Decimal("0.5") * z2_inv_n) / denom - half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom - expected_lower = 0.0 if numerator == 0 else float(max(Decimal(0), center - half_width)) - expected_upper = 1.0 if numerator == denominator else float(min(Decimal(1), center + half_width)) - if not ( - isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=0.0) - and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=0.0) + expected_lower, expected_upper = compute_wilson_ci(successes=numerator, total=denominator) + if ( + expected_lower is None + or expected_upper is None + or not ( + isclose(lower, expected_lower, rel_tol=1e-12, abs_tol=0.0) + and isclose(upper, expected_upper, rel_tol=1e-12, abs_tol=0.0) + ) ): raise ValueError("success_rate confidence interval must agree with its outcome counts.") From d0bb972bad384c070df743cc7761cfa7b782c0c7 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Fri, 13 Nov 2026 09:56:11 -0800 Subject: [PATCH 8/8] Preserve Wilson upper bounds below floating-point range Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/analytics/0_attack_results.md | 2 ++ pyrit/models/analytics.py | 7 +++++-- tests/unit/analytics/test_outcome_statistics.py | 8 ++++++++ tests/unit/models/test_analytics.py | 11 +++++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/doc/code/analytics/0_attack_results.md b/doc/code/analytics/0_attack_results.md index 7887d99677..e60dcd160f 100644 --- a/doc/code/analytics/0_attack_results.md +++ b/doc/code/analytics/0_attack_results.md @@ -33,6 +33,8 @@ has `success_rate_decided=None` and `success_rate_all=0.0`. Neither rate require use that whole selected cohort. Empty outcome shares are zero, and an empty cohort's decided share is `None`. All proportions are between 0 and 1. Both success rates are calculated from counts, never by averaging subgroup rates. +If a positive Wilson upper bound is too small to represent as a float, it rounds +outward to the smallest positive float rather than collapsing the interval to zero. Population selection is separate from denominator selection. A failed attempt followed by a successful retry yields 50% raw-result ASR even if the diff --git a/pyrit/models/analytics.py b/pyrit/models/analytics.py index 567621cc59..dcc3803995 100644 --- a/pyrit/models/analytics.py +++ b/pyrit/models/analytics.py @@ -10,7 +10,7 @@ from datetime import UTC, datetime from decimal import MAX_EMAX, MIN_EMIN, ROUND_HALF_EVEN, Context, Decimal, localcontext from enum import Enum -from math import isclose, isfinite +from math import isclose, isfinite, nextafter from typing import Annotated, Any, ClassVar, Self from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, computed_field, field_validator, model_validator @@ -57,7 +57,10 @@ def compute_wilson_ci(*, successes: int, total: int) -> tuple[float | None, floa center = (p + Decimal("0.5") * z2_inv_n) / denom half_width = (_WILSON_Z_95 * ((p * q + Decimal("0.25") * z2_inv_n) / n).sqrt()) / denom lower = 0.0 if successes == 0 else float(max(Decimal(0), center - half_width)) - upper = 1.0 if successes == total else float(min(Decimal(1), center + half_width)) + upper_decimal = Decimal(1) if successes == total else min(Decimal(1), center + half_width) + upper = float(upper_decimal) + if upper == 0.0 and upper_decimal > 0: + upper = nextafter(0.0, 1.0) return lower, upper diff --git a/tests/unit/analytics/test_outcome_statistics.py b/tests/unit/analytics/test_outcome_statistics.py index 9229193dd7..31f0ba32f9 100644 --- a/tests/unit/analytics/test_outcome_statistics.py +++ b/tests/unit/analytics/test_outcome_statistics.py @@ -114,6 +114,14 @@ def test_skewed_large_integer_counts_do_not_underflow_wilson_interval() -> None: assert subnormal_stats.success_rate_ci_upper == 1.235e-322 +@pytest.mark.parametrize("total", [10**325, 10**400]) +@pytest.mark.parametrize("successes", [0, 1]) +def test_wilson_upper_bound_rounds_outward_below_float_range(total: int, successes: int) -> None: + statistics = compute_outcome_statistics({"success": successes, "failure": total - successes}) + assert statistics.success_rate_ci_lower == 0.0 + assert statistics.success_rate_ci_upper == 5e-324 + + def test_wilson_interval_ignores_caller_decimal_traps_and_rounding() -> None: expected = compute_outcome_statistics({"success": 1, "failure": 1}) with localcontext() as ctx: diff --git a/tests/unit/models/test_analytics.py b/tests/unit/models/test_analytics.py index 71fc4adecf..f9f8b3ab08 100644 --- a/tests/unit/models/test_analytics.py +++ b/tests/unit/models/test_analytics.py @@ -184,6 +184,17 @@ def test_shared_statistics_accept_legacy_payload_without_confidence_interval_and assert TypeAdapter(OutcomeStatistics).validate_python(payload) == statistics +@pytest.mark.parametrize("total", [10**325, 10**400]) +def test_shared_statistics_reject_collapsed_ci_below_float_range(total: int) -> None: + statistics = compute_outcome_statistics({"success": 1, "failure": total - 1}) + payload = asdict(statistics) + assert TypeAdapter(OutcomeStatistics).validate_python(payload) == statistics + with pytest.raises(ValueError, match="confidence interval"): + replace(statistics, success_rate_ci_upper=0.0) + with pytest.raises(ValidationError, match="confidence interval"): + TypeAdapter(OutcomeStatistics).validate_python({**payload, "success_rate_ci_upper": 0.0}) + + def test_reembedding_mutated_outcomes_revalidates_the_counts() -> None: statistics = compute_outcome_statistics({"success": 1}) statistics.successes = 5