Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Extra check around face score and different face comparison thresholds

laurenspriema468efb3479d
diff --git a/infra/ml/test/comparator/compare.py b/infra/ml/test/comparator/compare.py
index 5ccab8023f..183d314edd 100644
--- a/infra/ml/test/comparator/compare.py
+++ b/infra/ml/test/comparator/compare.py
@@ -7,6 +7,10 @@ from typing import Any, Mapping, Sequence
from ground_truth.schema import FaceResult, ParityResult
+STATUS_PASS = "pass"
+STATUS_WARNING = "warning"
+STATUS_FAIL = "fail"
+
def _l2_norm(values: Sequence[float]) -> float:
return math.sqrt(sum(value * value for value in values))
@@ -91,20 +95,30 @@ class ThresholdConfig:
clip_cosine_distance: float = 0.015
cross_platform_clip_cosine_distance: float = 0.015
face_embedding_cosine_distance: float = 0.015
+ face_embedding_warning_cosine_distance: float = 0.035
box_iou_threshold: float = 0.80
face_match_iou_floor: float = 0.05
landmark_error_threshold: float = 0.03
score_delta_threshold: float = 0.10
+ min_face_score_for_comparison: float = 0.80
+
+ def __post_init__(self) -> None:
+ if self.face_embedding_warning_cosine_distance < self.face_embedding_cosine_distance:
+ raise ValueError(
+ "face_embedding_warning_cosine_distance must be >= face_embedding_cosine_distance"
+ )
def to_dict(self) -> dict[str, float]:
return {
"clip_cosine_distance": self.clip_cosine_distance,
"cross_platform_clip_cosine_distance": self.cross_platform_clip_cosine_distance,
"face_embedding_cosine_distance": self.face_embedding_cosine_distance,
+ "face_embedding_warning_cosine_distance": self.face_embedding_warning_cosine_distance,
"box_iou_threshold": self.box_iou_threshold,
"face_match_iou_floor": self.face_match_iou_floor,
"landmark_error_threshold": self.landmark_error_threshold,
"score_delta_threshold": self.score_delta_threshold,
+ "min_face_score_for_comparison": self.min_face_score_for_comparison,
}
@@ -115,15 +129,19 @@ class AggregateMetric:
p99: float
max: float
threshold: float
+ warning_threshold: float | None
+ status: str
passed: bool
- def to_dict(self) -> dict[str, float | int | bool]:
+ def to_dict(self) -> dict[str, float | int | bool | str | None]:
return {
"count": self.count,
"p95": self.p95,
"p99": self.p99,
"max": self.max,
"threshold": self.threshold,
+ "warning_threshold": self.warning_threshold,
+ "status": self.status,
"passed": self.passed,
}
@@ -135,12 +153,14 @@ class ComparisonFinding:
message: str
value: float | None = None
threshold: float | None = None
+ severity: str = STATUS_FAIL
def to_dict(self) -> dict[str, Any]:
payload: dict[str, Any] = {
"file_id": self.file_id,
"metric": self.metric,
"message": self.message,
+ "severity": self.severity,
}
if self.value is not None:
payload["value"] = self.value
@@ -154,6 +174,7 @@ class FileMetricMeasurement:
metric: str
value: float | None
threshold: float | None
+ status: str
passed: bool
direction: str | None = None
count: int | None = None
@@ -165,6 +186,7 @@ class FileMetricMeasurement:
"metric": self.metric,
"value": self.value,
"threshold": self.threshold,
+ "status": self.status,
"passed": self.passed,
"direction": self.direction,
"count": self.count,
@@ -177,17 +199,22 @@ class FileMetricMeasurement:
@dataclass(frozen=True)
class FileComparisonStatus:
file_id: str
+ status: str
passed: bool
metrics: tuple[FileMetricMeasurement, ...]
failures: tuple[ComparisonFinding, ...]
+ warnings: tuple[ComparisonFinding, ...]
def to_dict(self) -> dict[str, Any]:
return {
"file_id": self.file_id,
+ "status": self.status,
"passed": self.passed,
"metrics": [metric.to_dict() for metric in self.metrics],
"failure_count": len(self.failures),
"failures": [failure.to_dict() for failure in self.failures],
+ "warning_count": len(self.warnings),
+ "warnings": [warning.to_dict() for warning in self.warnings],
}
@@ -201,9 +228,12 @@ class ComparisonReport:
extra_files: tuple[str, ...]
aggregates: Mapping[str, AggregateMetric]
findings: tuple[ComparisonFinding, ...]
+ warnings: tuple[ComparisonFinding, ...]
file_statuses: tuple[FileComparisonStatus, ...]
passing_files: tuple[str, ...]
+ warning_files: tuple[str, ...]
failing_files: tuple[str, ...]
+ status: str
passed: bool
def to_dict(self) -> dict[str, Any]:
@@ -211,8 +241,10 @@ class ComparisonReport:
"total_reference_files": self.total_reference_files,
"checked_files": self.checked_files,
"pass_count": len(self.passing_files),
+ "warning_count": len(self.warning_files),
"fail_count": len(self.failing_files),
"passing_files": list(self.passing_files),
+ "warning_files": list(self.warning_files),
"failing_files": list(self.failing_files),
}
return {
@@ -227,15 +259,23 @@ class ComparisonReport:
for metric_name, metric in self.aggregates.items()
},
"findings": [finding.to_dict() for finding in self.findings],
+ "warnings": [warning.to_dict() for warning in self.warnings],
"file_summary": file_summary,
"file_statuses": [file_status.to_dict() for file_status in self.file_statuses],
"passing_files": list(self.passing_files),
+ "warning_files": list(self.warning_files),
"failing_files": list(self.failing_files),
+ "status": self.status,
"passed": self.passed,
}
-def _make_aggregate(values: list[float], threshold: float) -> AggregateMetric:
+def _make_aggregate(
+ values: list[float],
+ threshold: float,
+ *,
+ warning_threshold: float | None = None,
+) -> AggregateMetric:
if not values:
return AggregateMetric(
count=0,
@@ -243,20 +283,34 @@ def _make_aggregate(values: list[float], threshold: float) -> AggregateMetric:
p99=0.0,
max=0.0,
threshold=threshold,
+ warning_threshold=warning_threshold,
+ status=STATUS_PASS,
passed=True,
)
p95 = _percentile(values, 95.0)
p99 = _percentile(values, 99.0)
maximum = max(values)
- passed = p95 <= threshold and p99 <= threshold and maximum <= threshold
+ if p95 <= threshold and p99 <= threshold and maximum <= threshold:
+ status = STATUS_PASS
+ elif (
+ warning_threshold is not None
+ and p95 <= warning_threshold
+ and p99 <= warning_threshold
+ and maximum <= warning_threshold
+ ):
+ status = STATUS_WARNING
+ else:
+ status = STATUS_FAIL
return AggregateMetric(
count=len(values),
p95=p95,
p99=p99,
max=maximum,
threshold=threshold,
- passed=passed,
+ warning_threshold=warning_threshold,
+ status=status,
+ passed=status != STATUS_FAIL,
)
@@ -329,24 +383,34 @@ def compare_result_sets(
missing_files = tuple(sorted(set(reference_results) - set(candidate_results)))
extra_files = tuple(sorted(set(candidate_results) - set(reference_results)))
findings: list[ComparisonFinding] = []
+ warnings: list[ComparisonFinding] = []
file_failures: dict[str, list[ComparisonFinding]] = {
file_id: [] for file_id in reference_results
}
+ file_warnings: dict[str, list[ComparisonFinding]] = {
+ file_id: [] for file_id in reference_results
+ }
file_metrics: dict[str, list[FileMetricMeasurement]] = {
file_id: [] for file_id in reference_results
}
- def add_finding(finding: ComparisonFinding) -> None:
+ def add_failure(finding: ComparisonFinding) -> None:
findings.append(finding)
if finding.file_id in file_failures:
file_failures[finding.file_id].append(finding)
+ def add_warning(warning: ComparisonFinding) -> None:
+ warnings.append(warning)
+ if warning.file_id in file_warnings:
+ file_warnings[warning.file_id].append(warning)
+
def add_file_metric(
*,
file_id: str,
metric: str,
value: float | None,
threshold: float | None,
+ status: str,
passed: bool,
direction: str | None = None,
count: int | None = None,
@@ -360,6 +424,7 @@ def compare_result_sets(
metric=metric,
value=value,
threshold=threshold,
+ status=status,
passed=passed,
direction=direction,
count=count,
@@ -369,11 +434,12 @@ def compare_result_sets(
)
for missing_file in missing_files:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=missing_file,
metric="file_presence",
message=f"Missing from {candidate_platform}",
+ severity=STATUS_FAIL,
),
)
add_file_metric(
@@ -381,16 +447,18 @@ def compare_result_sets(
metric="file_presence",
value=0.0,
threshold=1.0,
+ status=STATUS_FAIL,
passed=False,
direction="==",
message=f"Missing from {candidate_platform}",
)
for extra_file in extra_files:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=extra_file,
metric="file_presence",
message=f"Unexpected file in {candidate_platform}",
+ severity=STATUS_FAIL,
),
)
@@ -405,6 +473,17 @@ def compare_result_sets(
reference = reference_results[file_id]
candidate = candidate_results[file_id]
+ reference_faces = tuple(
+ face
+ for face in reference.faces
+ if face.score >= thresholds.min_face_score_for_comparison
+ )
+ candidate_faces = tuple(
+ face
+ for face in candidate.faces
+ if face.score >= thresholds.min_face_score_for_comparison
+ )
+
clip_distance = cosine_distance(reference.clip.embedding, candidate.clip.embedding)
clip_distances.append(clip_distance)
add_file_metric(
@@ -412,38 +491,48 @@ def compare_result_sets(
metric="clip_cosine_distance",
value=clip_distance,
threshold=clip_threshold,
+ status=STATUS_PASS if clip_distance <= clip_threshold else STATUS_FAIL,
passed=clip_distance <= clip_threshold,
direction="<=",
message="CLIP cosine distance",
)
if clip_distance > clip_threshold:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="clip_cosine_distance",
message="CLIP cosine distance exceeded threshold",
value=clip_distance,
threshold=clip_threshold,
+ severity=STATUS_FAIL,
),
)
- reference_face_count = len(reference.faces)
- candidate_face_count = len(candidate.faces)
+ reference_face_count = len(reference_faces)
+ candidate_face_count = len(candidate_faces)
add_file_metric(
file_id=file_id,
metric="reference_face_count",
value=float(reference_face_count),
threshold=None,
+ status=STATUS_PASS,
passed=True,
- message=f"{reference_platform} face count",
+ message=(
+ f"{reference_platform} face count (score >= "
+ f"{thresholds.min_face_score_for_comparison:.2f})"
+ ),
)
add_file_metric(
file_id=file_id,
metric="candidate_face_count",
value=float(candidate_face_count),
threshold=None,
+ status=STATUS_PASS,
passed=True,
- message=f"{candidate_platform} face count",
+ message=(
+ f"{candidate_platform} face count (score >= "
+ f"{thresholds.min_face_score_for_comparison:.2f})"
+ ),
)
face_count_delta = abs(reference_face_count - candidate_face_count)
add_file_metric(
@@ -451,24 +540,26 @@ def compare_result_sets(
metric="face_count_delta",
value=float(face_count_delta),
threshold=0.0,
+ status=STATUS_PASS if face_count_delta == 0 else STATUS_FAIL,
passed=face_count_delta == 0,
direction="<=",
message="Absolute face count difference",
)
- if len(reference.faces) != len(candidate.faces):
- add_finding(
+ if reference_face_count != candidate_face_count:
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="face_count",
message="Face count mismatch",
- value=float(abs(len(reference.faces) - len(candidate.faces))),
+ value=float(face_count_delta),
+ severity=STATUS_FAIL,
),
)
matches = _match_faces(
- reference.faces,
- candidate.faces,
+ reference_faces,
+ candidate_faces,
min_iou_for_match=thresholds.face_match_iou_floor,
)
maximum_possible_matches = min(reference_face_count, candidate_face_count)
@@ -477,6 +568,7 @@ def compare_result_sets(
metric="matched_face_count",
value=float(len(matches)),
threshold=float(maximum_possible_matches),
+ status=STATUS_PASS if len(matches) == maximum_possible_matches else STATUS_FAIL,
passed=len(matches) == maximum_possible_matches,
direction="==",
count=len(matches),
@@ -494,6 +586,7 @@ def compare_result_sets(
metric="unmatched_reference_face_count",
value=float(unmatched_reference_face_count),
threshold=0.0,
+ status=STATUS_PASS if unmatched_reference_face_count == 0 else STATUS_FAIL,
passed=unmatched_reference_face_count == 0,
direction="<=",
message=(
@@ -506,6 +599,7 @@ def compare_result_sets(
metric="unmatched_candidate_face_count",
value=float(unmatched_candidate_face_count),
threshold=0.0,
+ status=STATUS_PASS if unmatched_candidate_face_count == 0 else STATUS_FAIL,
passed=unmatched_candidate_face_count == 0,
direction="<=",
message=(
@@ -515,23 +609,25 @@ def compare_result_sets(
)
if unmatched_reference_face_count > 0:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="unmatched_reference_face_count",
message="Unmatched reference faces after IoU-gated matching",
value=float(unmatched_reference_face_count),
threshold=0.0,
+ severity=STATUS_FAIL,
),
)
if unmatched_candidate_face_count > 0:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="unmatched_candidate_face_count",
message="Unmatched candidate faces after IoU-gated matching",
value=float(unmatched_candidate_face_count),
threshold=0.0,
+ severity=STATUS_FAIL,
),
)
@@ -540,6 +636,7 @@ def compare_result_sets(
metric="face_match_iou_floor",
value=thresholds.face_match_iou_floor,
threshold=None,
+ status=STATUS_PASS,
passed=True,
message="Minimum IoU required to keep a match",
)
@@ -550,8 +647,8 @@ def compare_result_sets(
file_score_deltas: list[float] = []
file_embedding_distances: list[float] = []
for reference_index, candidate_index, iou in matches:
- reference_face = reference.faces[reference_index]
- candidate_face = candidate.faces[candidate_index]
+ reference_face = reference_faces[reference_index]
+ candidate_face = candidate_faces[candidate_index]
embedding_distance = cosine_distance(
reference_face.embedding,
@@ -567,13 +664,14 @@ def compare_result_sets(
file_iou_shortfalls.append(iou_shortfall)
iou_errors.append(iou_shortfall)
if iou_shortfall > 0:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="face_box_iou",
message="Face box IoU below threshold",
value=iou,
threshold=iou_threshold,
+ severity=STATUS_FAIL,
),
)
@@ -583,24 +681,26 @@ def compare_result_sets(
candidate_face.landmarks,
)
except ValueError:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="landmarks",
message="Landmark count mismatch",
+ severity=STATUS_FAIL,
),
)
else:
file_landmark_errors.append(landmark_error)
landmark_errors.append(landmark_error)
if landmark_error > thresholds.landmark_error_threshold:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="landmark_error",
message="Landmark error exceeded threshold",
value=landmark_error,
threshold=thresholds.landmark_error_threshold,
+ severity=STATUS_FAIL,
),
)
@@ -608,24 +708,42 @@ def compare_result_sets(
file_score_deltas.append(score_delta)
score_deltas.append(score_delta)
if score_delta > thresholds.score_delta_threshold:
- add_finding(
+ add_failure(
ComparisonFinding(
file_id=file_id,
metric="score_delta",
message="Face score delta exceeded threshold",
value=score_delta,
threshold=thresholds.score_delta_threshold,
+ severity=STATUS_FAIL,
),
)
if embedding_distance > thresholds.face_embedding_cosine_distance:
- add_finding(
- ComparisonFinding(
- file_id=file_id,
- metric="face_embedding_cosine_distance",
- message="Face embedding cosine distance exceeded threshold",
- value=embedding_distance,
- threshold=thresholds.face_embedding_cosine_distance,
+ if embedding_distance <= thresholds.face_embedding_warning_cosine_distance:
+ add_warning(
+ ComparisonFinding(
+ file_id=file_id,
+ metric="face_embedding_cosine_distance",
+ message=(
+ "Face embedding cosine distance in warning band "
+ f"({thresholds.face_embedding_cosine_distance:.3f} - "
+ f"{thresholds.face_embedding_warning_cosine_distance:.3f})"
+ ),
+ value=embedding_distance,
+ threshold=thresholds.face_embedding_warning_cosine_distance,
+ severity=STATUS_WARNING,
+ ),
+ )
+ else:
+ add_failure(
+ ComparisonFinding(
+ file_id=file_id,
+ metric="face_embedding_cosine_distance",
+ message="Face embedding cosine distance exceeded threshold",
+ value=embedding_distance,
+ threshold=thresholds.face_embedding_cosine_distance,
+ severity=STATUS_FAIL,
),
)
@@ -636,6 +754,7 @@ def compare_result_sets(
metric="face_box_iou_min",
value=min_iou,
threshold=None,
+ status=STATUS_PASS,
passed=True,
count=len(file_ious),
message="Minimum IoU across matched faces",
@@ -646,10 +765,11 @@ def compare_result_sets(
metric="face_box_iou_shortfall_max",
value=max_iou_shortfall,
threshold=0.0,
+ status=STATUS_PASS if max_iou_shortfall <= 0.0 else STATUS_FAIL,
passed=max_iou_shortfall <= 0.0,
direction="<=",
count=len(file_iou_shortfalls),
- message="Maximum IoU shortfall against size-aware thresholds",
+ message="Maximum IoU shortfall against configured threshold",
)
else:
add_file_metric(
@@ -657,6 +777,11 @@ def compare_result_sets(
metric="face_box_iou_min",
value=None,
threshold=None,
+ status=(
+ STATUS_PASS
+ if reference_face_count == 0 and candidate_face_count == 0
+ else STATUS_FAIL
+ ),
passed=reference_face_count == 0 and candidate_face_count == 0,
count=0,
applicable=False,
@@ -667,6 +792,11 @@ def compare_result_sets(
metric="face_box_iou_shortfall_max",
value=None,
threshold=0.0,
+ status=(
+ STATUS_PASS
+ if reference_face_count == 0 and candidate_face_count == 0
+ else STATUS_FAIL
+ ),
passed=reference_face_count == 0 and candidate_face_count == 0,
direction="<=",
count=0,
@@ -681,6 +811,11 @@ def compare_result_sets(
metric="landmark_error_max",
value=max_landmark_error,
threshold=thresholds.landmark_error_threshold,
+ status=(
+ STATUS_PASS
+ if max_landmark_error <= thresholds.landmark_error_threshold
+ else STATUS_FAIL
+ ),
passed=max_landmark_error <= thresholds.landmark_error_threshold,
direction="<=",
count=len(file_landmark_errors),
@@ -692,6 +827,11 @@ def compare_result_sets(
metric="landmark_error_max",
value=None,
threshold=thresholds.landmark_error_threshold,
+ status=(
+ STATUS_PASS
+ if reference_face_count == 0 and candidate_face_count == 0
+ else STATUS_FAIL
+ ),
passed=reference_face_count == 0 and candidate_face_count == 0,
direction="<=",
count=0,
@@ -706,6 +846,11 @@ def compare_result_sets(
metric="score_delta_max",
value=max_score_delta,
threshold=thresholds.score_delta_threshold,
+ status=(
+ STATUS_PASS
+ if max_score_delta <= thresholds.score_delta_threshold
+ else STATUS_FAIL
+ ),
passed=max_score_delta <= thresholds.score_delta_threshold,
direction="<=",
count=len(file_score_deltas),
@@ -717,6 +862,11 @@ def compare_result_sets(
metric="score_delta_max",
value=None,
threshold=thresholds.score_delta_threshold,
+ status=(
+ STATUS_PASS
+ if reference_face_count == 0 and candidate_face_count == 0
+ else STATUS_FAIL
+ ),
passed=reference_face_count == 0 and candidate_face_count == 0,
direction="<=",
count=0,
@@ -726,12 +876,19 @@ def compare_result_sets(
if file_embedding_distances:
max_embedding_distance = max(file_embedding_distances)
+ if max_embedding_distance <= thresholds.face_embedding_cosine_distance:
+ embedding_status = STATUS_PASS
+ elif max_embedding_distance <= thresholds.face_embedding_warning_cosine_distance:
+ embedding_status = STATUS_WARNING
+ else:
+ embedding_status = STATUS_FAIL
add_file_metric(
file_id=file_id,
metric="face_embedding_cosine_distance_max",
value=max_embedding_distance,
threshold=thresholds.face_embedding_cosine_distance,
- passed=max_embedding_distance <= thresholds.face_embedding_cosine_distance,
+ status=embedding_status,
+ passed=embedding_status != STATUS_FAIL,
direction="<=",
count=len(file_embedding_distances),
message="Maximum face embedding cosine distance across matched faces",
@@ -742,6 +899,11 @@ def compare_result_sets(
metric="face_embedding_cosine_distance_max",
value=None,
threshold=thresholds.face_embedding_cosine_distance,
+ status=(
+ STATUS_PASS
+ if reference_face_count == 0 and candidate_face_count == 0
+ else STATUS_FAIL
+ ),
passed=reference_face_count == 0 and candidate_face_count == 0,
direction="<=",
count=0,
@@ -763,38 +925,77 @@ def compare_result_sets(
"face_embedding_cosine_distance": _make_aggregate(
face_embedding_distances,
thresholds.face_embedding_cosine_distance,
+ warning_threshold=thresholds.face_embedding_warning_cosine_distance,
),
}
for metric_name, metric in aggregates.items():
- if metric.passed:
+ if metric.status == STATUS_PASS:
continue
- add_finding(
+ if metric.status == STATUS_WARNING:
+ add_warning(
+ ComparisonFinding(
+ file_id="*aggregate*",
+ metric=metric_name,
+ message="Aggregate threshold gate in warning band",
+ value=metric.max,
+ threshold=metric.warning_threshold,
+ severity=STATUS_WARNING,
+ ),
+ )
+ continue
+ add_failure(
ComparisonFinding(
file_id="*aggregate*",
metric=metric_name,
message="Aggregate threshold gate failed",
value=metric.max,
threshold=metric.threshold,
+ severity=STATUS_FAIL,
),
)
report_findings = tuple(findings)
+ report_warnings = tuple(warnings)
sorted_reference_files = sorted(reference_results)
file_statuses = tuple(
FileComparisonStatus(
file_id=file_id,
+ status=(
+ STATUS_FAIL
+ if file_failures[file_id]
+ else STATUS_WARNING
+ if file_warnings[file_id]
+ else STATUS_PASS
+ ),
passed=not file_failures[file_id],
metrics=tuple(file_metrics[file_id]),
failures=tuple(file_failures[file_id]),
+ warnings=tuple(file_warnings[file_id]),
)
for file_id in sorted_reference_files
)
passing_files = tuple(
- file_status.file_id for file_status in file_statuses if file_status.passed
+ file_status.file_id
+ for file_status in file_statuses
+ if file_status.status == STATUS_PASS
+ )
+ warning_files = tuple(
+ file_status.file_id
+ for file_status in file_statuses
+ if file_status.status == STATUS_WARNING
)
failing_files = tuple(
- file_status.file_id for file_status in file_statuses if not file_status.passed
+ file_status.file_id
+ for file_status in file_statuses
+ if file_status.status == STATUS_FAIL
+ )
+ report_status = (
+ STATUS_FAIL
+ if report_findings
+ else STATUS_WARNING
+ if report_warnings
+ else STATUS_PASS
)
return ComparisonReport(
@@ -806,10 +1007,13 @@ def compare_result_sets(
extra_files=extra_files,
aggregates=aggregates,
findings=report_findings,
+ warnings=report_warnings,
file_statuses=file_statuses,
passing_files=passing_files,
+ warning_files=warning_files,
failing_files=failing_files,
- passed=not report_findings,
+ status=report_status,
+ passed=report_status != STATUS_FAIL,
)
diff --git a/infra/ml/test/tests/test_comparator.py b/infra/ml/test/tests/test_comparator.py
index 07018acc51..c6cc75a7cf 100644
--- a/infra/ml/test/tests/test_comparator.py
+++ b/infra/ml/test/tests/test_comparator.py
@@ -314,6 +314,168 @@ def test_compare_result_sets_fails_on_face_count_mismatch() -> None:
assert face_count_metric.passed is False
+def test_compare_result_sets_ignores_faces_below_min_score_threshold() -> None:
+ reference = _result(
+ file_id="score-filter.jpeg",
+ platform="python",
+ clip_seed=41,
+ faces=(
+ _face(510, x=0.18, y=0.14, score=0.95),
+ _face(511, x=0.62, y=0.50, score=0.79),
+ ),
+ )
+ candidate = _result(
+ file_id="score-filter.jpeg",
+ platform="android",
+ clip_seed=41,
+ faces=(
+ _face(510, x=0.18, y=0.14, score=0.95),
+ ),
+ )
+
+ report = compare_result_sets(
+ reference_platform="python",
+ candidate_platform="android",
+ reference_results={reference.file_id: reference},
+ candidate_results={candidate.file_id: candidate},
+ )
+
+ assert report.status == "pass"
+ assert report.passed is True
+ assert report.findings == ()
+ assert report.warning_files == ()
+ assert report.failing_files == ()
+ assert report.passing_files == ("score-filter.jpeg",)
+
+ file_status = report.file_statuses[0]
+ assert file_status.status == "pass"
+ assert file_status.passed is True
+ assert file_status.failures == ()
+ assert file_status.warnings == ()
+
+ reference_count = next(
+ metric for metric in file_status.metrics if metric.metric == "reference_face_count"
+ )
+ candidate_count = next(
+ metric for metric in file_status.metrics if metric.metric == "candidate_face_count"
+ )
+ assert reference_count.value == pytest.approx(1.0)
+ assert candidate_count.value == pytest.approx(1.0)
+ assert not any(finding.metric == "face_count" for finding in report.findings)
+
+
+def test_compare_result_sets_marks_face_embedding_warning_band() -> None:
+ reference_face = _face(620, x=0.24, y=0.20, score=0.93)
+ candidate_face = FaceResult(
+ box=reference_face.box,
+ landmarks=reference_face.landmarks,
+ score=reference_face.score,
+ embedding=_jittered_vector(reference_face.embedding, index=0, delta=0.2),
+ )
+ reference = _result(
+ file_id="embedding-warning.jpeg",
+ platform="python",
+ clip_seed=17,
+ faces=(reference_face,),
+ )
+ candidate = ParityResult(
+ file_id=reference.file_id,
+ clip=reference.clip,
+ faces=(candidate_face,),
+ runner_metadata=_metadata("ios"),
+ )
+
+ report = compare_result_sets(
+ reference_platform="python",
+ candidate_platform="ios",
+ reference_results={reference.file_id: reference},
+ candidate_results={candidate.file_id: candidate},
+ )
+
+ assert report.status == "warning"
+ assert report.passed is True
+ assert report.findings == ()
+ assert report.failing_files == ()
+ assert report.warning_files == ("embedding-warning.jpeg",)
+ assert report.passing_files == ()
+ assert any(
+ warning.metric == "face_embedding_cosine_distance"
+ and warning.file_id == "embedding-warning.jpeg"
+ for warning in report.warnings
+ )
+ assert any(warning.file_id == "*aggregate*" for warning in report.warnings)
+
+ file_status = report.file_statuses[0]
+ assert file_status.status == "warning"
+ assert file_status.passed is True
+ assert file_status.failures == ()
+ assert any(
+ warning.metric == "face_embedding_cosine_distance"
+ for warning in file_status.warnings
+ )
+
+ embedding_metric = next(
+ metric
+ for metric in file_status.metrics
+ if metric.metric == "face_embedding_cosine_distance_max"
+ )
+ assert embedding_metric.status == "warning"
+ assert embedding_metric.passed is True
+ assert embedding_metric.value is not None
+ assert 0.015 < embedding_metric.value <= 0.035
+
+
+def test_compare_result_sets_fails_face_embedding_above_warning_band() -> None:
+ reference_face = _face(721, x=0.16, y=0.21, score=0.91)
+ candidate_face = FaceResult(
+ box=reference_face.box,
+ landmarks=reference_face.landmarks,
+ score=reference_face.score,
+ embedding=_jittered_vector(reference_face.embedding, index=0, delta=0.3),
+ )
+ reference = _result(
+ file_id="embedding-fail.jpeg",
+ platform="python",
+ clip_seed=29,
+ faces=(reference_face,),
+ )
+ candidate = ParityResult(
+ file_id=reference.file_id,
+ clip=reference.clip,
+ faces=(candidate_face,),
+ runner_metadata=_metadata("desktop"),
+ )
+
+ report = compare_result_sets(
+ reference_platform="python",
+ candidate_platform="desktop",
+ reference_results={reference.file_id: reference},
+ candidate_results={candidate.file_id: candidate},
+ )
+
+ assert report.status == "fail"
+ assert report.passed is False
+ assert report.failing_files == ("embedding-fail.jpeg",)
+ assert report.warning_files == ()
+ assert any(
+ finding.metric == "face_embedding_cosine_distance" for finding in report.findings
+ )
+
+ file_status = report.file_statuses[0]
+ assert file_status.status == "fail"
+ assert file_status.passed is False
+
+ embedding_metric = next(
+ metric
+ for metric in file_status.metrics
+ if metric.metric == "face_embedding_cosine_distance_max"
+ )
+ assert embedding_metric.status == "fail"
+ assert embedding_metric.passed is False
+ assert embedding_metric.value is not None
+ assert embedding_metric.value > 0.035
+
+
def test_compare_result_sets_reports_unmatched_faces_after_iou_gating() -> None:
reference = _result(
file_id="offset-face.jpeg",
@@ -487,3 +649,14 @@ def test_compare_platform_matrix_rejects_duplicate_file_ids() -> None:
"android": (android_primary, android_duplicate),
}
)
+
+
+def test_threshold_config_rejects_invalid_warning_threshold() -> None:
+ with pytest.raises(
+ ValueError,
+ match="face_embedding_warning_cosine_distance must be >=",
+ ):
+ ThresholdConfig(
+ face_embedding_cosine_distance=0.02,
+ face_embedding_warning_cosine_distance=0.01,
+ )
diff --git a/infra/ml/test/tools/compare_parity_outputs.py b/infra/ml/test/tools/compare_parity_outputs.py
index f34c594ffa..78553039d1 100755
--- a/infra/ml/test/tools/compare_parity_outputs.py
+++ b/infra/ml/test/tools/compare_parity_outputs.py
@@ -84,12 +84,20 @@ def main() -> int:
thresholds=thresholds,
)
+ overall_status = (
+ "fail"
+ if any(report.status == "fail" for report in reports)
+ else "warning"
+ if any(report.status == "warning" for report in reports)
+ else "pass"
+ )
all_files_passed = all(report.passed for report in reports)
output_payload = {
"generated_at": datetime.now(UTC).isoformat(),
"ground_truth_platform": ground_truth_platform,
"thresholds": thresholds.to_dict(),
"all_files_passed": all_files_passed,
+ "status": overall_status,
"passed": all_files_passed,
"comparisons": _serialize_reports(reports),
}
@@ -99,14 +107,18 @@ def main() -> int:
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(json.dumps(output_payload, indent=2, sort_keys=True))
- failed_reports = [report for report in reports if not report.passed]
+ failed_reports = [report for report in reports if report.status == "fail"]
+ warning_reports = [report for report in reports if report.status == "warning"]
print(f"Comparisons executed: {len(reports)}")
print("Comparison mode: file-level (no global pass/fail gate)")
+ print(f"Overall comparison status: {overall_status.upper()}")
for report in reports:
print(
f" {report.reference_platform} -> {report.candidate_platform}: "
- f"{len(report.passing_files)}/{report.total_reference_files} files pass, "
- f"{len(report.failing_files)} fail"
+ f"{len(report.passing_files)} pass, "
+ f"{len(report.warning_files)} warning, "
+ f"{len(report.failing_files)} fail "
+ f"(total: {report.total_reference_files})"
)
if failed_reports:
print("Comparisons with failing files:")
@@ -115,6 +127,13 @@ def main() -> int:
f" {report.reference_platform} -> {report.candidate_platform} "
f"({len(report.findings)} findings)"
)
+ if warning_reports:
+ print("Comparisons with warning files:")
+ for report in warning_reports:
+ print(
+ f" {report.reference_platform} -> {report.candidate_platform} "
+ f"({len(report.warnings)} warnings)"
+ )
if args.fail_on_any_file_failure and failed_reports:
return 1
diff --git a/infra/ml/test/tools/render_face_detection_overlays.py b/infra/ml/test/tools/render_face_detection_overlays.py
index 1d81dc5fca..0801993264 100644
--- a/infra/ml/test/tools/render_face_detection_overlays.py
+++ b/infra/ml/test/tools/render_face_detection_overlays.py
@@ -138,6 +138,7 @@ def _render_detections(
file_id: str,
platform: str,
faces: list[Mapping[str, Any]],
+ min_score: float,
) -> Image.Image:
image = Image.fromarray(image_rgb, mode="RGB").convert("RGBA")
draw = ImageDraw.Draw(image, mode="RGBA")
@@ -146,7 +147,9 @@ def _render_detections(
point_radius = max(2, round(min(width, height) * 0.004))
font = ImageFont.load_default()
- header = f"{platform} | {file_id} | faces={len(faces)}"
+ header = (
+ f"{platform} | {file_id} | faces(score >= {min_score:.2f})={len(faces)}"
+ )
_draw_label(
image=image,
draw=draw,
@@ -242,6 +245,7 @@ def _iter_file_results(
results: list[Mapping[str, Any]],
*,
only_file_ids: set[str] | None,
+ min_score: float,
) -> list[tuple[str, list[Mapping[str, Any]]]]:
selected: list[tuple[str, list[Mapping[str, Any]]]] = []
for item in results:
@@ -253,7 +257,16 @@ def _iter_file_results(
continue
if not isinstance(faces, list):
continue
- typed_faces = [face for face in faces if isinstance(face, Mapping)]
+ typed_faces = []
+ for face in faces:
+ if not isinstance(face, Mapping):
+ continue
+ score_value = face.get("score")
+ if not isinstance(score_value, (int, float)):
+ continue
+ if float(score_value) < min_score:
+ continue
+ typed_faces.append(face)
selected.append((file_id, typed_faces))
return selected
@@ -294,6 +307,12 @@ def main() -> int:
default=[],
help="Only render specific file_id values (repeatable).",
)
+ parser.add_argument(
+ "--min-score",
+ type=float,
+ default=0.8,
+ help="Minimum detection score required to draw a face overlay (default: 0.8).",
+ )
args = parser.parse_args()
repo_root = _repo_root(ML_DIR)
@@ -330,6 +349,7 @@ def main() -> int:
file_results = _iter_file_results(
platform_results,
only_file_ids=only_file_ids,
+ min_score=args.min_score,
)
if not file_results:
print(f"[skip] {platform}: no matching results")
@@ -363,6 +383,7 @@ def main() -> int:
file_id=file_id,
platform=platform,
faces=faces,
+ min_score=args.min_score,
)
output_path = platform_output_dir / f"{_safe_output_name(file_id)}.png"
rendered.save(output_path)
diff --git a/infra/ml/test/tools/render_parity_html_report.py b/infra/ml/test/tools/render_parity_html_report.py
index e3b6fd6148..2e249d74d9 100755
--- a/infra/ml/test/tools/render_parity_html_report.py
+++ b/infra/ml/test/tools/render_parity_html_report.py
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import Any
IST = timezone(timedelta(hours=5, minutes=30), name="IST")
+_STATUS_ORDER = {"fail": 0, "warning": 1, "pass": 2}
def _format_value(value: object) -> str:
@@ -21,12 +22,30 @@ def _format_value(value: object) -> str:
return str(value)
-def _status_class(passed: bool) -> str:
- return "pass" if passed else "fail"
+def _optional_bool(value: object) -> bool | None:
+ return value if isinstance(value, bool) else None
-def _status_label(passed: bool) -> str:
- return "PASS" if passed else "FAIL"
+def _normalize_status(value: object, *, passed: bool | None = None) -> str:
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in _STATUS_ORDER:
+ return normalized
+ if passed is not None:
+ return "pass" if passed else "fail"
+ return "fail"
+
+
+def _status_class(value: object, *, passed: bool | None = None) -> str:
+ return _normalize_status(value, passed=passed)
+
+
+def _status_label(value: object, *, passed: bool | None = None) -> str:
+ return _normalize_status(value, passed=passed).upper()
+
+
+def _status_rank(value: object, *, passed: bool | None = None) -> int:
+ return _STATUS_ORDER[_normalize_status(value, passed=passed)]
def _format_generated_timestamp(value: object) -> str:
@@ -80,17 +99,27 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
candidate = str(comparison.get("candidate_platform", "unknown"))
file_summary = comparison.get("file_summary") or {}
pass_count = int(file_summary.get("pass_count", 0))
+ warning_count = int(file_summary.get("warning_count", 0))
fail_count = int(file_summary.get("fail_count", 0))
total_files = int(file_summary.get("total_reference_files", 0))
+ findings = comparison.get("findings", [])
+ warnings = comparison.get("warnings", [])
+ finding_count = len(findings) if isinstance(findings, list) else 0
+ warning_finding_count = len(warnings) if isinstance(warnings, list) else 0
html_parts: list[str] = []
html_parts.append(f"<h2>{html.escape(candidate)} vs {html.escape(reference)}</h2>")
- html_parts.append("<table><thead><tr><th>Pass</th><th>Fail</th><th>Total</th></tr></thead><tbody>")
+ html_parts.append(
+ "<table><thead><tr><th>Pass</th><th>Warning</th><th>Fail</th><th>Total</th>"
+ "<th>Findings</th></tr></thead><tbody>"
+ )
html_parts.append(
"<tr>"
f"<td class='pass'>{pass_count}</td>"
+ f"<td class='warning'>{warning_count}</td>"
f"<td class='fail'>{fail_count}</td>"
f"<td>{total_files}</td>"
+ f"<td>{finding_count} fail / {warning_finding_count} warning</td>"
"</tr>"
)
html_parts.append("</tbody></table>")
@@ -112,7 +141,15 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
continue
rows.append(status)
- rows.sort(key=lambda row: (bool(row.get("passed", False)), str(row.get("file_id", ""))))
+ rows.sort(
+ key=lambda row: (
+ _status_rank(
+ row.get("status"),
+ passed=_optional_bool(row.get("passed")),
+ ),
+ str(row.get("file_id", "")),
+ )
+ )
html_parts.append("<h3>Files</h3>")
if not rows:
@@ -121,22 +158,31 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
for status in rows:
file_id = str(status.get("file_id", ""))
- passed = bool(status.get("passed", False))
+ file_status = _normalize_status(
+ status.get("status"),
+ passed=_optional_bool(status.get("passed")),
+ )
failures = status.get("failures", [])
if not isinstance(failures, list):
failures = []
+ warnings = status.get("warnings", [])
+ if not isinstance(warnings, list):
+ warnings = []
metrics = status.get("metrics", [])
if not isinstance(metrics, list):
metrics = []
html_parts.append(
f"<details><summary>{html.escape(file_id)} "
- f"<span class='{_status_class(passed)}'>{_status_label(passed)}</span></summary>"
+ f"<span class='{_status_class(file_status)}'>{_status_label(file_status)}</span> "
+ f"(fail: {len(failures)}, warning: {len(warnings)})"
+ "</summary>"
)
html_parts.append(
"<table><thead><tr>"
- "<th>Metric</th><th>Value</th><th>Threshold</th><th>Direction</th><th>Passed</th><th>Count</th><th>Applicable</th><th>Note</th>"
+ "<th>Metric</th><th>Value</th><th>Threshold</th><th>Direction</th>"
+ "<th>Status</th><th>Count</th><th>Applicable</th><th>Note</th>"
"</tr></thead><tbody>"
)
if metrics:
@@ -147,7 +193,10 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
value = html.escape(_format_value(metric.get("value")))
threshold = html.escape(_format_value(metric.get("threshold")))
direction = html.escape(_format_value(metric.get("direction")))
- metric_passed = bool(metric.get("passed", False))
+ metric_status = _normalize_status(
+ metric.get("status"),
+ passed=_optional_bool(metric.get("passed")),
+ )
count = html.escape(_format_value(metric.get("count")))
applicable = bool(metric.get("applicable", True))
message = html.escape(str(metric.get("message", "")))
@@ -157,7 +206,7 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
f"<td>{value}</td>"
f"<td>{threshold}</td>"
f"<td>{direction}</td>"
- f"<td class='{_status_class(metric_passed)}'>{_status_label(metric_passed)}</td>"
+ f"<td class='{_status_class(metric_status)}'>{_status_label(metric_status)}</td>"
f"<td>{count}</td>"
f"<td>{'yes' if applicable else 'no'}</td>"
f"<td>{message}</td>"
@@ -170,21 +219,55 @@ def _render_comparison(comparison: dict[str, Any]) -> str:
html_parts.append("</tbody></table>")
html_parts.append("<h4>Threshold Failures</h4>")
- html_parts.append("<table><thead><tr><th>Metric</th><th>Value</th><th>Threshold</th><th>Message</th></tr></thead><tbody>")
+ html_parts.append(
+ "<table><thead><tr><th>Metric</th><th>Value</th><th>Threshold</th>"
+ "<th>Severity</th><th>Message</th></tr></thead><tbody>"
+ )
if failures:
for failure in failures:
if not isinstance(failure, dict):
continue
+ severity = _normalize_status(
+ failure.get("severity"),
+ passed=_optional_bool(failure.get("passed")),
+ )
html_parts.append(
"<tr>"
f"<td>{html.escape(str(failure.get('metric', '-')))}</td>"
f"<td>{html.escape(_format_value(failure.get('value')))}</td>"
f"<td>{html.escape(_format_value(failure.get('threshold')))}</td>"
+ f"<td class='{_status_class(severity)}'>{_status_label(severity)}</td>"
f"<td>{html.escape(str(failure.get('message', '')))}</td>"
"</tr>"
)
else:
- html_parts.append("<tr><td colspan='4' class='muted'>None</td></tr>")
+ html_parts.append("<tr><td colspan='5' class='muted'>None</td></tr>")
+ html_parts.append("</tbody></table>")
+
+ html_parts.append("<h4>Threshold Warnings</h4>")
+ html_parts.append(
+ "<table><thead><tr><th>Metric</th><th>Value</th><th>Threshold</th>"
+ "<th>Severity</th><th>Message</th></tr></thead><tbody>"
+ )
+ if warnings:
+ for warning in warnings:
+ if not isinstance(warning, dict):
+ continue
+ severity = _normalize_status(
+ warning.get("severity"),
+ passed=_optional_bool(warning.get("passed")),
+ )
+ html_parts.append(
+ "<tr>"
+ f"<td>{html.escape(str(warning.get('metric', '-')))}</td>"
+ f"<td>{html.escape(_format_value(warning.get('value')))}</td>"
+ f"<td>{html.escape(_format_value(warning.get('threshold')))}</td>"
+ f"<td class='{_status_class(severity)}'>{_status_label(severity)}</td>"
+ f"<td>{html.escape(str(warning.get('message', '')))}</td>"
+ "</tr>"
+ )
+ else:
+ html_parts.append("<tr><td colspan='5' class='muted'>None</td></tr>")
html_parts.append("</tbody></table>")
html_parts.append("</details>")
@@ -229,6 +312,7 @@ def render_report(
"details{margin:10px 0;border:1px solid #e4e7ec;border-radius:8px;padding:8px 10px;background:#fff;}"
"summary{cursor:pointer;font-weight:600;}"
".pass{color:#067647;font-weight:600;}"
+ ".warning{color:#b54708;font-weight:600;}"
".fail{color:#b42318;font-weight:600;}"
".muted{color:#667085;}"
".chip{display:inline-block;padding:3px 8px;border-radius:999px;background:#f2f4f7;margin-right:6px;font-size:12px;}"
diff --git a/infra/ml/test/tools/render_parity_markdown_report.py b/infra/ml/test/tools/render_parity_markdown_report.py
index 614b28b260..2395adfb8e 100644
--- a/infra/ml/test/tools/render_parity_markdown_report.py
+++ b/infra/ml/test/tools/render_parity_markdown_report.py
@@ -8,6 +8,7 @@ from pathlib import Path
from typing import Any
IST = timezone(timedelta(hours=5, minutes=30), name="IST")
+_STATUS_ORDER = {"fail": 0, "warning": 1, "pass": 2}
def _format_value(value: object) -> str:
@@ -20,6 +21,28 @@ def _format_value(value: object) -> str:
return str(value)
+def _optional_bool(value: object) -> bool | None:
+ return value if isinstance(value, bool) else None
+
+
+def _normalize_status(value: object, *, passed: bool | None = None) -> str:
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in _STATUS_ORDER:
+ return normalized
+ if passed is not None:
+ return "pass" if passed else "fail"
+ return "fail"
+
+
+def _status_label(value: object, *, passed: bool | None = None) -> str:
+ return _normalize_status(value, passed=passed).upper()
+
+
+def _status_rank(value: object, *, passed: bool | None = None) -> int:
+ return _STATUS_ORDER[_normalize_status(value, passed=passed)]
+
+
def _format_generated_timestamp(value: object) -> str:
if value is None:
return "-"
@@ -103,14 +126,20 @@ def _render_platform_outputs(platform_stats: dict[str, dict[str, Any]]) -> list[
def _render_aggregate_table(aggregates: dict[str, Any]) -> list[str]:
lines = [
- "| Metric | Count | P95 | P99 | Max | Threshold | Passed |",
- "| --- | ---: | ---: | ---: | ---: | ---: | --- |",
+ (
+ "| Metric | Count | P95 | P99 | Max | Threshold | Warning Threshold | "
+ "Status |"
+ ),
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |",
]
for metric_name in sorted(aggregates):
metric = aggregates[metric_name]
if not isinstance(metric, dict):
continue
- passed = bool(metric.get("passed", False))
+ status = _normalize_status(
+ metric.get("status"),
+ passed=_optional_bool(metric.get("passed")),
+ )
lines.append(
"| "
+ " | ".join(
@@ -121,7 +150,8 @@ def _render_aggregate_table(aggregates: dict[str, Any]) -> list[str]:
_escape_cell(_format_value(metric.get("p99"))),
_escape_cell(_format_value(metric.get("max"))),
_escape_cell(_format_value(metric.get("threshold"))),
- "PASS" if passed else "FAIL",
+ _escape_cell(_format_value(metric.get("warning_threshold"))),
+ _status_label(status),
]
)
+ " |"
@@ -132,7 +162,7 @@ def _render_aggregate_table(aggregates: dict[str, Any]) -> list[str]:
def _render_metric_rows(metrics: list[dict[str, Any]]) -> list[str]:
lines = [
- "| Metric | Value | Threshold | Direction | Passed | Count | Applicable | Note |",
+ "| Metric | Value | Threshold | Direction | Status | Count | Applicable | Note |",
"| --- | ---: | ---: | --- | --- | ---: | --- | --- |",
]
if not metrics:
@@ -143,6 +173,10 @@ def _render_metric_rows(metrics: list[dict[str, Any]]) -> list[str]:
for metric in metrics:
if not isinstance(metric, dict):
continue
+ status = _normalize_status(
+ metric.get("status"),
+ passed=_optional_bool(metric.get("passed")),
+ )
lines.append(
"| "
+ " | ".join(
@@ -151,7 +185,7 @@ def _render_metric_rows(metrics: list[dict[str, Any]]) -> list[str]:
_escape_cell(_format_value(metric.get("value"))),
_escape_cell(_format_value(metric.get("threshold"))),
_escape_cell(_format_value(metric.get("direction"))),
- "PASS" if bool(metric.get("passed", False)) else "FAIL",
+ _status_label(status),
_escape_cell(_format_value(metric.get("count"))),
"yes" if bool(metric.get("applicable", True)) else "no",
_escape_cell(metric.get("message", "")),
@@ -163,27 +197,32 @@ def _render_metric_rows(metrics: list[dict[str, Any]]) -> list[str]:
return lines
-def _render_failure_rows(failures: list[dict[str, Any]]) -> list[str]:
+def _render_finding_rows(findings: list[dict[str, Any]]) -> list[str]:
lines = [
- "| Metric | Value | Threshold | Message |",
- "| --- | ---: | ---: | --- |",
+ "| Metric | Value | Threshold | Severity | Message |",
+ "| --- | ---: | ---: | --- | --- |",
]
- if not failures:
- lines.append("| - | - | - | None |")
+ if not findings:
+ lines.append("| - | - | - | - | None |")
lines.append("")
return lines
- for failure in failures:
- if not isinstance(failure, dict):
+ for finding in findings:
+ if not isinstance(finding, dict):
continue
+ severity = _normalize_status(
+ finding.get("severity"),
+ passed=_optional_bool(finding.get("passed")),
+ )
lines.append(
"| "
+ " | ".join(
[
- _escape_cell(failure.get("metric", "-")),
- _escape_cell(_format_value(failure.get("value"))),
- _escape_cell(_format_value(failure.get("threshold"))),
- _escape_cell(failure.get("message", "")),
+ _escape_cell(finding.get("metric", "-")),
+ _escape_cell(_format_value(finding.get("value"))),
+ _escape_cell(_format_value(finding.get("threshold"))),
+ _status_label(severity),
+ _escape_cell(finding.get("message", "")),
]
)
+ " |"
@@ -200,7 +239,10 @@ def _render_file_statuses(statuses: list[dict[str, Any]]) -> list[str]:
statuses = sorted(
statuses,
key=lambda status: (
- bool(status.get("passed", False)),
+ _status_rank(
+ status.get("status"),
+ passed=_optional_bool(status.get("passed")),
+ ),
str(status.get("file_id", "")),
),
)
@@ -209,20 +251,25 @@ def _render_file_statuses(statuses: list[dict[str, Any]]) -> list[str]:
[
"### File Status Index",
"",
- "| File | Status | Failure Count |",
- "| --- | --- | ---: |",
+ "| File | Status | Failure Count | Warning Count |",
+ "| --- | --- | ---: | ---: |",
]
)
for status in statuses:
if not isinstance(status, dict):
continue
+ file_status = _normalize_status(
+ status.get("status"),
+ passed=_optional_bool(status.get("passed")),
+ )
lines.append(
"| "
+ " | ".join(
[
_escape_cell(status.get("file_id", "-")),
- "PASS" if bool(status.get("passed", False)) else "FAIL",
+ _status_label(file_status),
_escape_cell(_format_value(status.get("failure_count"))),
+ _escape_cell(_format_value(status.get("warning_count"))),
]
)
+ " |"
@@ -235,20 +282,28 @@ def _render_file_statuses(statuses: list[dict[str, Any]]) -> list[str]:
if not isinstance(status, dict):
continue
file_id = str(status.get("file_id", "-"))
- passed = bool(status.get("passed", False))
+ file_status = _normalize_status(
+ status.get("status"),
+ passed=_optional_bool(status.get("passed")),
+ )
metrics = status.get("metrics", [])
if not isinstance(metrics, list):
metrics = []
failures = status.get("failures", [])
if not isinstance(failures, list):
failures = []
+ warnings = status.get("warnings", [])
+ if not isinstance(warnings, list):
+ warnings = []
- lines.append(f"#### `{file_id}` ({'PASS' if passed else 'FAIL'})")
+ lines.append(f"#### `{file_id}` ({_status_label(file_status)})")
lines.append("")
lines.append("Metrics:")
lines.extend(_render_metric_rows(metrics))
lines.append("Threshold failures:")
- lines.extend(_render_failure_rows(failures))
+ lines.extend(_render_finding_rows(failures))
+ lines.append("Threshold warnings:")
+ lines.extend(_render_finding_rows(warnings))
return lines
@@ -261,15 +316,24 @@ def _render_comparison(comparison: dict[str, Any]) -> list[str]:
file_summary = {}
pass_count = int(file_summary.get("pass_count", 0))
+ warning_count = int(file_summary.get("warning_count", 0))
fail_count = int(file_summary.get("fail_count", 0))
total_files = int(file_summary.get("total_reference_files", 0))
checked_files = int(file_summary.get("checked_files", comparison.get("checked_files", 0)))
+ findings = comparison.get("findings", [])
+ warnings = comparison.get("warnings", [])
+ finding_count = len(findings) if isinstance(findings, list) else 0
+ warning_finding_count = len(warnings) if isinstance(warnings, list) else 0
lines: list[str] = [
f"## {candidate} vs {reference}",
"",
- f"- Summary: {pass_count} pass / {fail_count} fail / {total_files} total reference files",
+ (
+ f"- Summary: {pass_count} pass / {warning_count} warning / {fail_count} fail / "
+ f"{total_files} total reference files"
+ ),
f"- Checked files: {checked_files}",
+ f"- Threshold findings: {finding_count} fail / {warning_finding_count} warning",
"",
]
@@ -362,14 +426,12 @@ def render_report(
platform_stats = _platform_stats(report_path.parent)
generated_at = _format_generated_timestamp(payload.get("generated_at"))
- overall_passed = bool(payload.get("passed", False))
lines: list[str] = [
"# ML Indexing Parity Report (LLM-Optimized Markdown)",
"",
f"- Generated (IST): {generated_at}",
f"- Ground truth platform: {ground_truth_platform}",
- f"- Overall report status: {'PASS' if overall_passed else 'FAIL'}",
f"- Comparisons shown: {len(comparisons)}",
"",
"This report is structured for agent parsing and includes exhaustive file-level data.",
diff --git a/infra/ml/test/tools/run_suite.sh b/infra/ml/test/tools/run_suite.sh
index c58558bc96..06571fc0fb 100755
--- a/infra/ml/test/tools/run_suite.sh
+++ b/infra/ml/test/tools/run_suite.sh
@@ -1563,6 +1563,7 @@ from collections import OrderedDict
from pathlib import Path
LOWER_IS_WORSE_METRICS = {"face_box_iou"}
+STATUS_ORDER = {"FAIL": 0, "WARNING": 1, "PASS": 2}
def _fmt_float(value: float) -> str:
@@ -1630,6 +1631,23 @@ def _summarize_file_failures(failures: list[dict[str, object]]) -> str:
)
+def _summarize_file_warnings(warnings: list[dict[str, object]]) -> str:
+ if not warnings:
+ return "-"
+
+ by_metric: "OrderedDict[str, list[dict[str, object]]]" = OrderedDict()
+ for warning in warnings:
+ metric = str(warning.get("metric", "unknown_metric"))
+ by_metric.setdefault(metric, []).append(warning)
+
+ summaries: list[str] = []
+ for metric, metric_warnings in by_metric.items():
+ occurrence_count = len(metric_warnings)
+ message = str(metric_warnings[0].get("message", "threshold warning"))
+ summaries.append(f"{metric} x{occurrence_count}: {message}")
+ return "; ".join(summaries)
+
+
def _escape_cell(value: str) -> str:
return value.replace("|", "\\|")
@@ -1659,6 +1677,7 @@ for comparison in comparisons:
file_summary = {}
total_files = int(file_summary.get("total_reference_files", comparison.get("total_reference_files", 0)))
pass_count = int(file_summary.get("pass_count", len(comparison.get("passing_files", []))))
+ warning_count = int(file_summary.get("warning_count", len(comparison.get("warning_files", []))))
fail_count = int(file_summary.get("fail_count", len(comparison.get("failing_files", []))))
file_statuses = comparison.get("file_statuses", [])
@@ -1671,32 +1690,44 @@ for comparison in comparisons:
if not isinstance(file_status, dict):
continue
file_id = str(file_status.get("file_id", ""))
- passed = bool(file_status.get("passed", False))
+ status_value = str(file_status.get("status", "")).strip().upper()
+ if status_value not in STATUS_ORDER:
+ status_value = "PASS" if bool(file_status.get("passed", False)) else "FAIL"
failures = file_status.get("failures", [])
if not isinstance(failures, list):
failures = []
- status = "PASS" if passed else "FAIL"
- details = _summarize_file_failures(failures)
- rows.append((file_id, status, details))
+ warnings = file_status.get("warnings", [])
+ if not isinstance(warnings, list):
+ warnings = []
+ if status_value == "FAIL":
+ details = _summarize_file_failures(failures)
+ elif status_value == "WARNING":
+ details = _summarize_file_warnings(warnings)
+ else:
+ details = "-"
+ rows.append((file_id, status_value, details))
else:
passing_files = [str(file_id) for file_id in comparison.get("passing_files", [])]
+ warning_files = [str(file_id) for file_id in comparison.get("warning_files", [])]
failing_files = [str(file_id) for file_id in comparison.get("failing_files", [])]
for file_id in passing_files:
rows.append((file_id, "PASS", "-"))
+ for file_id in warning_files:
+ rows.append((file_id, "WARNING", "No warning detail available in report"))
for file_id in failing_files:
rows.append((file_id, "FAIL", "No failure detail available in report"))
if not rows:
continue
- rows.sort(key=lambda row: (row[1] == "PASS", row[0]))
+ rows.sort(key=lambda row: (STATUS_ORDER.get(row[1], 3), row[0]))
print()
print(
f"### {candidate_platform} vs {ground_truth_platform} "
- f"({pass_count} pass / {fail_count} fail / {total_files} total)"
+ f"({pass_count} pass / {warning_count} warning / {fail_count} fail / {total_files} total)"
)
- print("| File | Status | Failure Details |")
+ print("| File | Status | Details |")
print("| --- | --- | --- |")
for file_id, status, details in rows:
print(
@@ -1821,17 +1852,26 @@ for comparison in comparisons:
if not isinstance(file_summary, dict):
file_summary = {}
pass_count = int(file_summary.get("pass_count", len(comparison.get("passing_files", []))))
+ warning_count = int(file_summary.get("warning_count", len(comparison.get("warning_files", []))))
fail_count = int(file_summary.get("fail_count", len(comparison.get("failing_files", []))))
total_files = int(file_summary.get("total_reference_files", comparison.get("total_reference_files", 0)))
- summary_by_platform[candidate_platform] = (pass_count, fail_count, total_files)
+ summary_by_platform[candidate_platform] = (
+ pass_count,
+ warning_count,
+ fail_count,
+ total_files,
+ )
print(f"File-level summary (vs {ground_truth_platform}):")
for platform in selected_platforms:
if platform == ground_truth_platform:
continue
if platform in summary_by_platform:
- pass_count, fail_count, total_files = summary_by_platform[platform]
- print(f" {platform}: {pass_count} pass / {fail_count} fail / {total_files} total")
+ pass_count, warning_count, fail_count, total_files = summary_by_platform[platform]
+ print(
+ f" {platform}: "
+ f"{pass_count} pass / {warning_count} warning / {fail_count} fail / {total_files} total"
+ )
else:
print(f" {platform}: unavailable (no platform results)")
PY