Coverage for src/governed_harness/gates/exceptions.py: 95%
36 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Which findings an exception in force covers (``review.exceptions``)."""
3from __future__ import annotations
5from collections.abc import Iterable
6from dataclasses import dataclass, field
7from datetime import datetime
9from governed_harness.domain.models import ExceptionRecord, ExceptionScope, Finding
10from governed_harness.reporting.fingerprint import finding_fingerprint
12EXCEPTION_REASON_PREFIX = "EXCEPTION_APPLIED_"
15def scope_matches(scope: ExceptionScope, finding: Finding) -> bool:
16 path = finding.location.path if finding.location else None
17 if scope.rule_id != finding.rule_id:
18 return False
19 if scope.path is not None and scope.path != path: 19 ↛ 20line 19 didn't jump to line 20 because the condition on line 19 was never true
20 return False
21 return scope.fingerprint is None or scope.fingerprint == finding_fingerprint(finding)
24@dataclass
25class ExceptionApplication:
26 kept: list[Finding] = field(default_factory=list)
27 excepted: list[Finding] = field(default_factory=list)
28 used: list[ExceptionRecord] = field(default_factory=list)
30 @property
31 def reason_codes(self) -> tuple[str, ...]:
32 return tuple(f"{EXCEPTION_REASON_PREFIX}{item.exception_id}" for item in self.used)
35def apply_exceptions(
36 findings: Iterable[Finding], exceptions: Iterable[ExceptionRecord], now: datetime
37) -> ExceptionApplication:
38 """Split ``findings`` into those that still count and those covered by an exception in
39 force at ``now``."""
40 active = [item for item in exceptions if item.active_at(now)]
41 result = ExceptionApplication()
42 used: dict[str, ExceptionRecord] = {}
43 for finding in findings:
44 record = next(
45 (item for item in active if any(scope_matches(s, finding) for s in item.scope)),
46 None,
47 )
48 if record is None:
49 result.kept.append(finding)
50 else:
51 result.excepted.append(finding)
52 used.setdefault(record.exception_id, record)
53 result.used = list(used.values())
54 return result
57def exception_ids(reason_codes: Iterable[str]) -> list[str]:
58 return [
59 code.removeprefix(EXCEPTION_REASON_PREFIX)
60 for code in reason_codes
61 if code.startswith(EXCEPTION_REASON_PREFIX)
62 ]