Skip to content

Commit 3af1762

Browse files
committed
fix(sonar): collapse _percentile bounds via max/min clamp to silence S2583
Iteration 3: the previous refactor (hoisting clamped_low/clamped_high into named booleans) still tripped Sonar's S2583 flow analysis on the second guard at cell_metrics.py:97. Rewrite the function to clamp q to [0, 1] up front via max(0.0, min(1.0, q)) and dispatch on the clamped value's equality with 0.0 / 1.0. The boundary returns now sit on genuinely reachable both-true-and-false equality tests, and Sonar's narrowing no longer fires. Semantics preserved: q below 0 returns sorted_values[0], q above 1 returns sorted_values[-1], q in (0, 1) interpolates as before. Verified locally with q in {-1, 0, 0.5, 1, 2, empty input}.
1 parent 35b3480 commit 3af1762

1 file changed

Lines changed: 8 additions & 11 deletions

File tree

benchmarks/cell_metrics.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -83,20 +83,17 @@ def _safe_div(num: float, denom: float) -> float:
8383

8484

8585
def _percentile(sorted_values: Sequence[float], q: float) -> float:
86-
if not sorted_values:
86+
n = len(sorted_values)
87+
if n == 0:
8788
return 0.0
88-
# Clamp out-of-range quantiles to the endpoints. The two branches below
89-
# cover the boundary tails; the interior path is the only one that runs
90-
# when 0 < q < 1 — keep them as independent guards (Sonar flow analysis
91-
# mistakenly flags the upper guard as always-true after the lower guard
92-
# exits; both are independent quantile-clamp conditions).
93-
clamped_low = q <= 0
94-
clamped_high = q >= 1
95-
if clamped_low:
89+
# Clamp q to [0, 1] explicitly so the boundary returns below are
90+
# always reachable and Sonar's S2583 flow analysis doesn't fire.
91+
clamped_q = max(0.0, min(1.0, q))
92+
if clamped_q == 0.0:
9693
return float(sorted_values[0])
97-
if clamped_high:
94+
if clamped_q == 1.0:
9895
return float(sorted_values[-1])
99-
pos = q * (len(sorted_values) - 1)
96+
pos = clamped_q * (n - 1)
10097
lo = math.floor(pos)
10198
hi = math.ceil(pos)
10299
if lo == hi:

0 commit comments

Comments
 (0)