Skip to content

Commit 5c020e2

Browse files
authored
Merge pull request #141 from Refactron-ai/fix/117-branch-coverage-safe
fix(verify): a changed conditional's untested branch cannot earn SAFE
2 parents 7a7d08e + b60292c commit 5c020e2

14 files changed

Lines changed: 617 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,40 @@ Versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
---
99

10+
## [0.4.5] — 2026-09-01
11+
12+
### Fixed — a changed conditional with an untested branch could earn `SAFE`
13+
14+
The coverage rule was statement-level: a changed `if`/`elif` counted as covered
15+
the moment its header executed. So a change to a conditional whose one branch no
16+
test entered earned `SAFE` with the changed behaviour untested. A changed
17+
conditional is one of the most common regression shapes, and it is exactly where
18+
statement coverage is weakest.
19+
20+
`SAFE` now also requires that changed conditionals were fully branched. With
21+
`coverage.py --branch`, a changed line reported as a partially-taken branch
22+
floors the verdict at `UNPROVEN`, and the reason names it:
23+
24+
```
25+
[UNPROVEN] Tests pass, but a changed conditional has a branch no test took
26+
(calc.py:3). Add a test that enters the other branch.
27+
```
28+
29+
The decision was made on measurement, not assertion (ADR-14). `--branch` added
30+
no runtime cost on a real 600-test suite. The flip is surgical: it bites only a
31+
changed conditional with an untaken arc, never straight-line code (0% affected)
32+
or a fully-exercised conditional, so it cannot make `SAFE` unreachable for
33+
ordinary changes.
34+
35+
Fail-safe throughout: without `--branch` data the check falls back to the
36+
statement rule, and absent data never grants `SAFE`. The rule can only move
37+
`SAFE` to `UNPROVEN`, never the other way.
38+
39+
Branch coverage is Python-only, like the rest of the coverage check. A
40+
TypeScript or mixed diff still caps at `UNPROVEN`.
41+
42+
---
43+
1044
## [0.4.4] — 2026-08-21
1145

1246
### Fixed — a pytest config file could turn `UNSAFE` into `SAFE`

‎CODE_STYLE.md‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,14 @@ Concrete coding rules for this repository. These extend `CLAUDE.md` (project ins
2323
```ts
2424
function f(x: 'a' | 'b'): number {
2525
switch (x) {
26-
case 'a': return 1;
27-
case 'b': return 2;
28-
default: { const _: never = x; throw new Error(`unreachable: ${x as string}`); }
26+
case 'a':
27+
return 1;
28+
case 'b':
29+
return 2;
30+
default: {
31+
const _: never = x;
32+
throw new Error(`unreachable: ${x as string}`);
33+
}
2934
}
3035
}
3136
```
@@ -44,10 +49,23 @@ Concrete coding rules for this repository. These extend `CLAUDE.md` (project ins
4449

4550
### Comments
4651

47-
- Default to **no comments**. Names should explain *what*.
48-
- A comment is appropriate when it explains *why* the code is non-obvious: a workaround for a specific bug, a hidden invariant, a subtle compatibility constraint.
49-
- Never explain *what* the code does. The code does that.
50-
- Never reference issue numbers, PRs, or "added by X for Y" in comments — that's PR description territory and rots.
52+
- Default to **no comments**. Names should explain _what_.
53+
- A comment is appropriate when it explains _why_ the code is non-obvious: a workaround for a specific bug, a hidden invariant, a subtle compatibility constraint. In this repo, a genuine false-`SAFE` trap is the archetype worth a comment.
54+
- Never explain _what_ the code does. The code does that.
55+
- **The test: if deleting the comment loses no information a competent reader couldn't recover from the code in ten seconds, delete it.** Restating a spread, a field init, a type guard, or an obvious control-flow choice is slop, not documentation.
56+
- **One comment per non-obvious decision, not one per hunk.** A change does not need a running narration. Most edits need zero comments. Reach for a comment when you catch yourself about to be surprised re-reading this in six months — not by default.
57+
- **Prefer one line.** A multi-line comment is earned only when the rationale genuinely needs it (a subtle invariant, a reproduced bug). If the reason fits in a clause, use a clause.
58+
- An ADR reference is fine (`ADR-14`) when the full reasoning lives there — it is an anchor, not a narration. Do not also paste the ADR's argument inline.
59+
60+
```ts
61+
// slop — restates the code:
62+
// Conditional spread so an absent field stays absent under exactOptionalPropertyTypes.
63+
...(x ? { x } : {})
64+
65+
// earned — names a trap the code cannot show:
66+
// Checked BEFORE the covered-line short-circuit: a partial branch DID execute,
67+
// so it would otherwise count as covered and return a false SAFE.
68+
```
5169

5270
### File organization
5371

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
# ADR-14: A changed statement in a partially-taken branch blocks SAFE
2+
3+
> Status: **Accepted**
4+
> Date: 2026-09-01
5+
> Deciders: @omsherikar
6+
> Closes: #117. Follow-up to ADR-11 (`11-safe-coverage-rule.md`).
7+
8+
## Context
9+
10+
`SAFE` rests on a statement-level coverage rule (ADR-11): every coverable changed
11+
statement must have executed. But statement execution does not mean the changed
12+
*logic* was exercised. A changed `if`/`elif` whose header ran but whose branch a
13+
test never entered counts as "covered," so the change earns `SAFE` with a branch
14+
nobody tested.
15+
16+
A changed conditional is one of the most common shapes of a real regression, and
17+
it is exactly where a statement-level answer is weakest: the header executed, so
18+
the statement is covered, while the behaviour that changed sits in a branch no
19+
test took.
20+
21+
Real example, measured. `playground/legacy-python/dispatch.py`:
22+
23+
```python
24+
if isinstance(shape, Circle):
25+
return math.pi * shape.radius * shape.radius
26+
elif isinstance(shape, Square):
27+
return shape.side * shape.side
28+
elif isinstance(shape, Rectangle): # line 32 — executed
29+
return shape.width * shape.height
30+
raise TypeError("unknown shape") # line 34 — arc 32→34 never taken
31+
```
32+
33+
`coverage.py --branch` reports `missing_branches: [[32, 34]]`: the arc from the
34+
final `elif` to the `raise` was never taken, because no test passed an unknown
35+
shape. Statement coverage of line 32 is complete. Change line 32 and it earns
36+
`SAFE` today, with the error path untested.
37+
38+
ADR-11 recorded this as an explicit follow-up. #117 required the decision be made
39+
on **measured** cost and flip rate, not asserted, because `SAFE` had already
40+
tightened twice in the 0.4.x line and over-tightening it into unreachability
41+
would make the verdict ignored rather than honest.
42+
43+
## Measurements
44+
45+
Both taken on this repository's `playground/` before the decision.
46+
47+
**Cost (AC1).** On `large-python` (1,201 files, 600 tests), a real suite:
48+
49+
| run | wall-clock |
50+
| --- | --- |
51+
| `coverage run` (statement) | 10.48s, 10.04s |
52+
| `coverage run --branch` | 9.93s, 9.91s |
53+
54+
`--branch` added **no measurable runtime cost** — the branch runs were marginally
55+
faster, within noise. The JSON report grew ~1.5x (3.66 MB → 5.60 MB), a parse
56+
cost, not a run cost. The issue's "measurably slower" concern is not borne out.
57+
58+
**Flip surface (AC2).** Branch gating only flips a `SAFE` when a *changed*
59+
statement is itself a partially-taken branch. Density of that shape:
60+
61+
| repo | statements | partial branches | share |
62+
| --- | --- | --- | --- |
63+
| `large-python` (straight-line) | 30,600 | 0 | 0% — branch gating is a no-op |
64+
| `legacy-python` (real control flow) | 73 | 1 | 1.4% |
65+
66+
This is the load-bearing finding. ADR-11 flips a `SAFE` for **any** diff touching
67+
an uncovered statement in a partially-covered file — a broad surface. Branch
68+
gating flips only a diff whose changed lines are **conditionals with an untaken
69+
arc** — a strict, narrow subset, and precisely the false-SAFE case. Straight-line
70+
changes and fully-exercised conditionals are untouched. Stacking this on ADR-11
71+
therefore adds a small, targeted flip, not a second broad tightening.
72+
73+
## Decision
74+
75+
**A changed statement that `coverage.py` reports as a partially-taken branch
76+
blocks `SAFE`, flooring the verdict to `UNPROVEN`.**
77+
78+
Formally: with branch data available, a changed statement disqualifies `SAFE` if
79+
it is the source line of an arc in the file's `missing_branches`. This is added
80+
to the ADR-11 conjunct; both must hold for `SAFE`.
81+
82+
`coverage run` gains `--branch`. The JSON parse reads `missing_branches` per file
83+
alongside the existing `executed_lines` / `missing_lines`.
84+
85+
Two boundaries keep the direction fail-safe:
86+
87+
1. **Unavailable branch data never grants `SAFE`.** An older `coverage.py`, a
88+
parse that yields no `missing_branches`, or a measurement failure falls back
89+
to the ADR-11 statement rule — it never uses absent branch data as evidence of
90+
a covered branch. Missing information floors, it does not clear.
91+
2. **The rule only tightens.** It can move `SAFE` → `UNPROVEN` and nothing else.
92+
No path it introduces can move `UNSAFE` or `UNPROVEN` → `SAFE`. The branch gap
93+
is enforced in two places: `attributeChangedLines` folds it into
94+
`changedLinesCovered` (the ADR-11 conjunct), and `fuseVerdict`'s `SAFE` gate
95+
independently asserts `partialBranches` is empty. The second is defence in
96+
depth: it makes a future producer of `partialBranches` fail safe by
97+
construction rather than by remembering to floor `changedLinesCovered`.
98+
99+
`reportVersion` stays `1`: `missing_branches` is additive to the coverage sub-
100+
object, no field is renamed, removed or retyped. The **semantics** of `verdict`
101+
tighten, which `engineVersion` (ADR-13) already exists to disambiguate for a
102+
consumer storing fleet history.
103+
104+
Version: **patch**, shipping in 0.4.x, per the repository's earned-minor policy.
105+
The changelog leads with what `SAFE` now means, since the version number does not
106+
carry it.
107+
108+
## Alternatives considered
109+
110+
### Alternative A: disclose, don't block
111+
112+
Report partial branches as an advisory (like `changedStatements` before ADR-11)
113+
and leave the verdict `SAFE`.
114+
115+
Rejected. This is the exact shape ADR-11 rejected: a verdict that claims proof it
116+
does not have, with the shortfall disclosed beside it. Every automated consumer
117+
gates on `verdict`, not on a branch advisory. A changed conditional with an
118+
untested branch is a textbook false `SAFE`; disclosing it is not a substitute for
119+
declining to certify it.
120+
121+
### Alternative B: gate on the partial-branch COUNT (ratio threshold)
122+
123+
Block only when partial branches exceed some fraction of changed statements.
124+
125+
Rejected for the reason ADR-11 rejected a coverage ratio: an arbitrary constant
126+
at the centre of the honesty of the verdict, indefensible at every value, and
127+
inexplicable in a sentence. One untested branch on a changed line is one untested
128+
branch.
129+
130+
### Alternative C: leave it at statement level
131+
132+
The status quo. Rejected: it is the open false-SAFE surface #117 exists to close,
133+
and the measured cost of closing it is ~zero.
134+
135+
## Consequences
136+
137+
- **Positive.** The most common regression shape — a changed conditional — can no
138+
longer earn `SAFE` with a branch no test entered. `SAFE` moves closer to
139+
meaning what its reason says.
140+
- **Positive.** Fail-safe only. Every verdict this changes moves `SAFE` →
141+
`UNPROVEN`; measured flip surface is narrow and surgical.
142+
- **Positive.** No runtime cost (measured). The usability objection the issue
143+
raised does not materialise: it cannot make `SAFE` unreachable for straight-line
144+
code (0% affected) and bites conditional changes only where a branch is
145+
genuinely untested.
146+
- **Negative.** A changed conditional in a weakly-tested repo now reads
147+
`UNPROVEN` where it read `SAFE`. That is an honest report of an untested branch,
148+
but it must be explained by the reason string, not left as a bare downgrade.
149+
- **Neutral.** Report ~1.5x larger. Parse cost only; no user-visible effect.
150+
- **Neutral.** Exit codes unchanged — `SAFE` and `UNPROVEN` both exit 0.
151+
152+
## Compliance
153+
154+
- **Red-first (AC3):** a changed `if`/`elif` whose one branch never executes, with
155+
a green suite and complete statement coverage, must return `UNPROVEN`. Proven
156+
failing against `main` (where it returns `SAFE`) before the fix.
157+
- **Negative (AC4):** a changed conditional whose branches are all exercised must
158+
still reach `SAFE`. Proven passing, so the rule does not over-block.
159+
- **Fallback:** a run without branch data (branch parse empty) falls back to the
160+
ADR-11 rule and does not crash or wrongly grant `SAFE`.
161+
- **ADR-11's cross-file statement test must keep passing unmodified**, proving the
162+
statement conjunct was not traded away.
163+
164+
## Open questions / follow-ups
165+
166+
- [ ] Path and condition coverage (`a and b` where only `a` was evaluated). A
167+
strictly larger gap than branches; out of scope here.
168+
- [ ] Non-Python languages. Coverage is Python-only, so this rule never applies to
169+
a TypeScript diff, which already caps at `UNPROVEN`.
170+
- [ ] #116, mutation testing: coverage — statement or branch — proves a line
171+
*executed*, not that a test *asserts* on it. The next layer.

‎docs/changelog.mdx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,30 @@ description: Release history for Refactron, newest first.
77
Refactron follows [Semantic Versioning](https://semver.org/). The full,
88
unabridged log lives in [`CHANGELOG.md`](https://github.com/Refactron-ai/refactron/blob/main/CHANGELOG.md).
99

10+
<Update label="0.4.5" description="September 1, 2026">
11+
**A changed conditional with an untested branch could earn `SAFE`.**
12+
13+
Coverage was statement-level: a changed `if`/`elif` counted as covered once its
14+
header executed, so a change to a conditional whose one branch no test entered
15+
earned `SAFE` with the changed behaviour untested.
16+
17+
`SAFE` now also requires changed conditionals to be fully branched. A changed
18+
line coverage.py reports as a partially-taken branch floors at `UNPROVEN`, and
19+
the reason names it:
20+
21+
```
22+
[UNPROVEN] Tests pass, but a changed conditional has a branch no test took
23+
(calc.py:3). Add a test that enters the other branch.
24+
```
25+
26+
Decided on measurement (ADR-14): `--branch` added no runtime cost on a real
27+
600-test suite, and the flip is surgical — it bites only a changed conditional
28+
with an untaken arc, never straight-line code or a fully-tested conditional, so
29+
it cannot make `SAFE` unreachable for ordinary changes. Fail-safe throughout:
30+
the rule only moves `SAFE` to `UNPROVEN`, and absent branch data falls back to
31+
the statement rule. Python-only, like the rest of coverage.
32+
</Update>
33+
1034
<Update label="0.4.4" description="August 21, 2026">
1135
**A pytest config file could turn `UNSAFE` into `SAFE`.** If your project sets
1236
`addopts` or `testpaths`, read this.

‎docs/verification/verdicts.mdx‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,27 @@ by hand instead of asking for an impossible test.
5959
A change consisting _entirely_ of excluded statements does not reach `SAFE`:
6060
there is nothing a test could have proven about it.
6161

62+
`SAFE` also requires that changed **conditionals** were fully branched. A changed
63+
`if`/`elif` whose header ran but one of whose branches no test entered floors at
64+
`UNPROVEN`, even when statement coverage is complete: the behaviour that changed
65+
sits in a branch nobody tested. The reason names the line so you know which test
66+
to add:
67+
68+
```
69+
[UNPROVEN] Tests pass, but a changed conditional has a branch no test took
70+
(calc.py:3). Add a test that enters the other branch.
71+
```
72+
73+
A conditional whose branches are all exercised still reaches `SAFE`, so this
74+
never blocks a fully-tested change. Branch coverage is Python-only, like the rest
75+
of the coverage check.
76+
77+
This covers statement-level branches — `if`, `elif`, `while`, `for`/`else`,
78+
`match`. It does not cover an untested path inside a comprehension filter, a
79+
ternary, or a boolean short-circuit (`a and b`): `coverage.py` does not report
80+
those as branches, so a changed expression of that kind can still read `SAFE`
81+
with a sub-path untested.
82+
6283
<Note>
6384
This is stricter than it was in 0.4.0. The old rule cleared a whole file as
6485
soon as **one** changed statement in it ran, so a diff changing 40 statements
@@ -245,14 +266,12 @@ If you pass a `testCmd` that names a subset of the suite, the verdict floors at
245266
one test that would have caught the change was never selected.
246267

247268
<Note>
248-
**What this check can and cannot see.** Refactron reads the command string,
249-
the environment, and your pytest configuration. It recognises `pytest`,
250-
`unittest`, `vitest` and `jest` and
251-
their common flags — but not every flag of every plugin. A command carrying an
252-
option it does not recognise is reported `unknown` rather than `full`, and
253-
`unknown` does not floor the verdict. Treat this as a strong check on the
254-
shapes it knows, not a guarantee that no narrowing can ever reach `SAFE`. If
255-
you need certainty, run the bare command.
269+
**What this check can and cannot see.** Refactron reads the command string, the environment, and
270+
your pytest configuration. It recognises `pytest`, `unittest`, `vitest` and `jest` and their
271+
common flags — but not every flag of every plugin. A command carrying an option it does not
272+
recognise is reported `unknown` rather than `full`, and `unknown` does not floor the verdict.
273+
Treat this as a strong check on the shapes it knows, not a guarantee that no narrowing can ever
274+
reach `SAFE`. If you need certainty, run the bare command.
256275
</Note>
257276

258277
A worked example. One file, one change (`return x * 2` to `return x * 3`), and
@@ -273,10 +292,10 @@ tell the two apart. The scope of the run is what distinguishes them.
273292
Refactron classifies your command into three buckets, and reports the result on
274293
`testScope`:
275294

276-
| Scope | Meaning | Can be SAFE |
277-
| ---------- | ----------------------------------------------------------- | ----------- |
278-
| `full` | Parsed, and names no filter | yes |
279-
| `narrowed` | Names a path, node id, `-k`, `-m`, `-t`, `--onlyChanged`, … | no |
295+
| Scope | Meaning | Can be SAFE |
296+
| ---------- | -------------------------------------------------------------------- | ----------- |
297+
| `full` | Parsed, and names no filter | yes |
298+
| `narrowed` | Names a path, node id, `-k`, `-m`, `-t`, `--onlyChanged`, … | no |
280299
| `unknown` | Not recognised (`make test`, `npm test`, a flag on a wrapper script) | yes |
281300

282301
**Naming a directory counts as narrowing**, including `pytest tests/`. Tests can

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "refactron",
3-
"version": "0.4.4",
3+
"version": "0.4.5",
44
"description": "A verification layer for code change: verify any diff for a SAFE / UNSAFE / UNPROVEN verdict, from the CLI or over MCP.",
55
"author": "Om Sherikar <omsherikar0229@gmail.com>",
66
"bin": {

‎refactron-py/refactron/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,6 @@
1414
distribution metadata and the runtime value cannot drift apart.
1515
"""
1616

17-
__version__ = "0.4.4"
17+
__version__ = "0.4.5"
1818

1919
__all__ = ["__version__"]

0 commit comments

Comments
 (0)