Skip to content

Commit 4d156c4

Browse files
fix: address bugbot review feedback
- Move _cov_instance None check inside lock (TOCTOU race fix) - Fix branch counting to only include actual branch points, not all arcs
1 parent 5b3354b commit 4d156c4

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

drift/core/coverage_server.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,9 @@ def take_coverage_snapshot(baseline: bool = False) -> dict:
102102
Returns:
103103
dict of { filePath: { "lines": {...}, "totalBranches": N, "coveredBranches": N, "branches": {...} } }
104104
"""
105-
if _cov_instance is None:
106-
raise RuntimeError("Coverage not initialized")
107-
108105
with _lock:
106+
if _cov_instance is None:
107+
raise RuntimeError("Coverage not initialized")
109108
_cov_instance.stop()
110109
coverage = {}
111110

@@ -176,20 +175,30 @@ def _get_branch_data(data, filename: str) -> dict:
176175
missing_arcs = analysis.missing_branch_arcs()
177176
executed_arcs = set(data.arcs(filename) or [])
178177

179-
branch_lines: dict[int, dict] = {}
180-
178+
# Group executed arcs by from_line (skip negative entry arcs)
179+
executed_by_line: dict[int, list[int]] = {}
181180
for from_line, to_line in executed_arcs:
182181
if from_line < 0:
183182
continue
184-
if from_line not in branch_lines:
185-
branch_lines[from_line] = {"total": 0, "covered": 0}
186-
branch_lines[from_line]["total"] += 1
187-
branch_lines[from_line]["covered"] += 1
188-
189-
for from_line, to_lines in missing_arcs.items():
190-
if from_line not in branch_lines:
191-
branch_lines[from_line] = {"total": 0, "covered": 0}
192-
branch_lines[from_line]["total"] += len(to_lines)
183+
executed_by_line.setdefault(from_line, []).append(to_line)
184+
185+
# A line is a branch point if:
186+
# - it appears in missing_arcs (at least one path wasn't taken), OR
187+
# - it has multiple executed arcs (multiple paths from same line)
188+
branch_point_lines = set(missing_arcs.keys())
189+
for from_line, to_lines in executed_by_line.items():
190+
if len(to_lines) > 1:
191+
branch_point_lines.add(from_line)
192+
193+
branch_lines: dict[int, dict] = {}
194+
195+
for from_line in branch_point_lines:
196+
executed_count = len(executed_by_line.get(from_line, []))
197+
missing_count = len(missing_arcs.get(from_line, []))
198+
branch_lines[from_line] = {
199+
"total": executed_count + missing_count,
200+
"covered": executed_count,
201+
}
193202

194203
branches = {str(line): info for line, info in branch_lines.items()}
195204

0 commit comments

Comments
 (0)