Skip to content

Commit 08c001e

Browse files
authored
Merge pull request #151 from Refactron-ai/feat/149-constant-mutation
feat(verify): mutate constants in --mutate to catch unasserted values
2 parents 256681a + 7c4d4e1 commit 08c001e

8 files changed

Lines changed: 457 additions & 57 deletions

File tree

‎dev-docs/decisions/15-mutation-downgrade.md‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,40 @@ arithmetic (`+`↔`-`, `*`↔`/`, `//`↔`/`), and boolean (`and`↔`or`). A reg
6969
changed lines was rejected: it would mutate inside strings and produce false
7070
survivors, i.e. false `UNPROVEN`s. Fail-safe, but needlessly noisy.
7171

72+
**Constants (#149).** The mutant set was later extended to constants — numbers,
73+
strings, and `True`/`False`/`None` — because an operator-only set left a real
74+
false-green: a changed `return 2` earned `SAFE` under `--mutate` (zero mutable
75+
operators). The same tokenize discipline holds: a constant inside a string or
76+
comment is part of that STRING/COMMENT token and is never mutated.
77+
78+
Replacement rules, chosen to guarantee a different, valid, behaviour-changing
79+
literal: a number maps to `0`, except a zero-valued literal (`0`, `0.0`, `0x0`,
80+
`0j`) maps to `1` so the mutant is never numerically equal; a non-empty string
81+
maps to `""` and an already-empty one to a sentinel; `True`↔`False` and `None`→
82+
`True` (flipping both truthiness and an `is None` identity check).
83+
84+
Docstrings are excluded so an inert string cannot manufacture a false survivor.
85+
They are located by their AST span — module, class, function, inline
86+
`def f(): "doc"`, and implicit-concatenated `"a" "b"` alike — rather than a
87+
tokenize line-start heuristic, which misses the inline and concatenated shapes;
88+
AST is used ONLY to locate docstrings, mutation positions stay tokenize. Other
89+
bare literal statements (a bare string, number, or bool) are skipped by the
90+
tokenize bare-expression check.
91+
92+
Constants are numerous, so the flat budget is filled OPERATORS-FIRST: a constant
93+
must never evict a higher-signal operator mutant past the cap and quietly weaken
94+
the check to a truncated `SAFE`. The budget/sampling question the counts now press
95+
on is tracked as its own follow-up.
96+
97+
Known fail-safe imprecisions, none a false `SAFE`: an empty f-string on Python
98+
< 3.12 (`f""`, one STRING token there) maps to `""`, an equivalent mutant (a false
99+
`UNPROVEN`); on 3.12+ f-strings are not mutated at all. A bytes literal maps to a
100+
str (a cross-type mutant, never equivalent). A constant the code genuinely ignores
101+
survives — an honest `SAFE`→`UNPROVEN` on a thin suite.
102+
103+
Still downgrade-only: the worst a constant mutant can add is a false `UNPROVEN`,
104+
never a false `SAFE`.
105+
72106
Python-only, like coverage. `reportVersion` stays `1`: the mutation evidence is
73107
an additive optional field. `engineVersion` (ADR-13) already distinguishes the
74108
semantics change.
@@ -143,9 +177,12 @@ Rejected as a non-goal. The changed-statement set (already computed in
143177
on POSIX; the two hang tests skip on win32.
144178

145179

146-
- [ ] Return-value and statement-deletion operators. A larger mutant set catches
147-
more, at more runtime. Start with operator swaps.
148-
- [ ] A mutant budget / sampling cap for very large diffs, so cost stays bounded.
180+
- [x] Constant operators (numbers, strings, `True`/`False`/`None`) — done in #149.
181+
- [ ] Return-value (#150) and statement-deletion operators. A larger mutant set
182+
catches more, at more runtime. Return-value is blocked on a sentinel /
183+
equivalent-mutant decision; statement-deletion must keep the mutant valid.
184+
- [ ] A smarter mutant budget / sampling cap for very large diffs (#149 fills it
185+
operators-first as a floor; constants make the flat cap bite sooner).
149186
- [ ] Non-Python languages. Python-only, like coverage.
150187
- [ ] Condition/path coverage (#140) is a coverage-side gap; mutation is the
151188
assertion-side one. They are complementary.

‎docs/verification/verdicts.mdx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,10 @@ Coverage proves a changed statement _ran_. It does not prove any test would
8686
_fail_ if that statement's behaviour changed. A line a test executes but never
8787
asserts on counts as covered and earns `SAFE`.
8888

89-
`refactron verify-diff --mutate` closes that gap. It perturbs the operators in
90-
your changed statements — a boundary (`<=` → `<`), an arithmetic sign, a boolean
91-
`and`/`or` — reruns your suite against each, and if any mutant **survives** (the
89+
`refactron verify-diff --mutate` closes that gap. It perturbs the operators and
90+
constants in your changed statements — a boundary (`<=` → `<`), an arithmetic
91+
sign, a boolean `and`/`or`, or a constant (a number, a string, `True`/`False`/
92+
`None`) — reruns your suite against each, and if any mutant **survives** (the
9293
suite still passes), the verdict floors at `UNPROVEN`, naming the survivor:
9394

9495
```

‎src/cli/verify-diff-command.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ export function formatMutationNote(mutation: VerdictReport['mutation']): string
173173
return `note: --mutate did not run (${mutation.skippedReason ?? 'no conclusion'}); this verdict is not mutation-checked`;
174174
}
175175
if (mutation.tested === 0) {
176-
return `note: --mutate found no mutable operators in the changed statements; nothing to check`;
176+
return `note: --mutate found no mutable operators or constants in the changed statements; nothing to check`;
177177
}
178178
const parts: string[] = [];
179179
if (mutation.truncated) {

‎src/verify/checks/_py/mutate.py‎

Lines changed: 168 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
#!/usr/bin/env python3
2-
"""Emit operator mutants for the changed lines of one Python file (ADR-15, #116).
2+
"""Emit operator and constant mutants for the changed lines of one Python file
3+
(ADR-15, #116; constants #149).
34
45
stdin: one JSON object {"path": str, "changed_lines": [int, ...]}
5-
stdout: JSON list of {"line", "col", "endCol", "orig", "repl", "op"}, one per
6-
mutable operator token found on a changed line.
6+
stdout: JSON list of {"line", "col", "endCol", "orig", "repl", "op", "kind"}, one
7+
per mutable token found on a changed line. `kind` is "operator" or
8+
"constant" so the runner can fill its budget operators-first (a constant
9+
must never evict a higher-signal operator mutant past the cap).
10+
11+
Tokenize, not regex or AST, for the mutation positions: token boundaries are
12+
exact, string and comment contents are separate token types and so are never
13+
mutated, and the operator's own position is what a swap needs (AST gives operand
14+
positions, not the operator). AST is used ONLY to locate docstrings (below), which
15+
tokenize cannot identify without reimplementing the grammar.
716
8-
Tokenize, not regex or AST: token boundaries are exact, string and comment
9-
contents are separate token types and so are never mutated, and the operator's
10-
own position is what a swap needs (AST gives operand positions, not the operator).
1117
A mutant that turns out syntactically invalid is the runner's problem, not ours:
12-
it simply runs and is classified as killed, which is the fail-safe direction.
18+
it simply runs and is classified as killed, which is the fail-safe direction. The
19+
only failure mode a richer mutant set can add is a false SURVIVOR (an equivalent
20+
mutant), i.e. a false UNPROVEN, never a false SAFE, since mutation is
21+
downgrade-only.
1322
"""
23+
import ast
1424
import io
1525
import json
1626
import sys
@@ -32,37 +42,165 @@
3242
"//": "/",
3343
}
3444
NAME_SWAP = {"and": "or", "or": "and"}
45+
# The keyword constants (#149). None -> True flips truthiness AND identity, so it
46+
# is caught by both a boolean use and an `is None` check.
47+
CONST_NAME_SWAP = {"True": "False", "False": "True", "None": "True"}
48+
49+
# Tokens that begin a logical line. A constant whose previous significant token is
50+
# one of these AND whose next significant token is a NEWLINE is a standalone
51+
# expression statement (a bare string, a bare literal) — inert, so mutating it
52+
# manufactures a survivor no test can kill. Docstrings that are NOT this simple
53+
# shape (inline `def f(): "doc"`, implicit-concatenated `"a" "b"`) are caught by
54+
# the AST span check instead.
55+
_LINE_START = frozenset(
56+
{tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT, tokenize.ENCODING}
57+
)
58+
59+
60+
def _num_repl(s: str) -> str:
61+
"""A different, valid numeric literal. Zero-valued literals (0, 0.0, 0x0, 0j)
62+
map to 1 rather than 0 so the mutant is never numerically equal to the
63+
original; everything else maps to 0."""
64+
try:
65+
is_zero = ast.literal_eval(s) == 0
66+
except Exception:
67+
is_zero = s == "0"
68+
return "1" if is_zero else "0"
69+
70+
71+
def _str_repl(s: str) -> str:
72+
"""A different, valid string literal: empty string for a non-empty literal, a
73+
sentinel for an already-empty one.
74+
75+
Fail-safe imprecision, documented rather than special-cased: a bytes literal
76+
maps to a str (`b"x"` -> `""`), a cross-type mutant that is never equivalent
77+
(so no false UNPROVEN) but is usually killed on sight. An EMPTY f-string on
78+
Python < 3.12 (`f""`, one STRING token there) maps to `""`, which is
79+
behaviourally equal -> an equivalent mutant -> a false UNPROVEN; on 3.12+ an
80+
f-string is FSTRING_* tokens and is not mutated at all. Both are downgrade-only
81+
and rare."""
82+
try:
83+
v = ast.literal_eval(s)
84+
empty = v == "" or v == b""
85+
except Exception:
86+
empty = False
87+
return '"__mut__"' if empty else '""'
88+
89+
90+
def _docstring_spans(source: str) -> list:
91+
"""(lineno, col, end_lineno, end_col) for every docstring, so the tokenize
92+
pass can skip string tokens that are (part of) one. A docstring is
93+
behaviour-inert, so mutating it manufactures a survivor no test could ever kill
94+
(a false UNPROVEN). AST identifies them exactly — inline, implicit-concatenated
95+
and multi-line alike — where a tokenize heuristic cannot. A parse failure
96+
yields no spans (the tokenize pass then also fails, or degrades fail-safe)."""
97+
try:
98+
tree = ast.parse(source)
99+
except (SyntaxError, ValueError):
100+
return []
101+
spans = []
102+
holders = (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
103+
for node in ast.walk(tree):
104+
if not isinstance(node, holders):
105+
continue
106+
body = getattr(node, "body", None)
107+
if not body:
108+
continue
109+
first = body[0]
110+
if (
111+
isinstance(first, ast.Expr)
112+
and isinstance(first.value, ast.Constant)
113+
and isinstance(first.value.value, (str, bytes))
114+
):
115+
c = first.value
116+
spans.append((c.lineno, c.col_offset, c.end_lineno, c.end_col_offset))
117+
return spans
118+
119+
120+
def _in_docstring(spans: list, row: int, col: int) -> bool:
121+
for (l, c, el, ec) in spans:
122+
if l <= row <= el and (row > l or col >= c) and (row < el or col < ec):
123+
return True
124+
return False
125+
126+
127+
def _significant(toks: list, i: int, step: int):
128+
"""Nearest token before (step -1) or after (step +1) index i that is not a
129+
comment or a non-logical newline."""
130+
j = i + step
131+
while 0 <= j < len(toks):
132+
if toks[j].type not in (tokenize.COMMENT, tokenize.NL):
133+
return toks[j]
134+
j += step
135+
return None
136+
137+
138+
def _is_bare_stmt(toks: list, i: int) -> bool:
139+
prev = _significant(toks, i, -1)
140+
nxt = _significant(toks, i, +1)
141+
at_line_start = prev is None or prev.type in _LINE_START
142+
ends_stmt = nxt is not None and nxt.type == tokenize.NEWLINE
143+
return at_line_start and ends_stmt
144+
145+
146+
def _mutation_for(toks: list, i: int, spans: list):
147+
"""(replacement, kind) for the token at index i, or None if it is not mutable.
148+
Constants are skipped when they are behaviour-inert (a bare expression
149+
statement, or any part of a docstring)."""
150+
tok = toks[i]
151+
if tok.type == tokenize.OP and tok.string in OP_SWAP:
152+
return OP_SWAP[tok.string], "operator"
153+
if tok.type == tokenize.NAME and tok.string in NAME_SWAP:
154+
return NAME_SWAP[tok.string], "operator"
155+
if tok.type == tokenize.NAME and tok.string in CONST_NAME_SWAP:
156+
if _is_bare_stmt(toks, i):
157+
return None
158+
return CONST_NAME_SWAP[tok.string], "constant"
159+
if tok.type == tokenize.NUMBER:
160+
if _is_bare_stmt(toks, i):
161+
return None
162+
return _num_repl(tok.string), "constant"
163+
if tok.type == tokenize.STRING:
164+
(row, col) = tok.start
165+
if _is_bare_stmt(toks, i) or _in_docstring(spans, row, col):
166+
return None
167+
return _str_repl(tok.string), "constant"
168+
return None
35169

36170

37171
def mutants(source: str, changed: set) -> list:
38-
out = []
39172
try:
40-
toks = tokenize.generate_tokens(io.StringIO(source).readline)
41-
for tok in toks:
42-
(row, col) = tok.start
43-
(erow, ecol) = tok.end
44-
if row not in changed or row != erow:
45-
continue
46-
if tok.type == tokenize.OP and tok.string in OP_SWAP:
47-
repl = OP_SWAP[tok.string]
48-
elif tok.type == tokenize.NAME and tok.string in NAME_SWAP:
49-
repl = NAME_SWAP[tok.string]
50-
else:
51-
continue
52-
out.append(
53-
{
54-
"line": row,
55-
"col": col,
56-
"endCol": ecol,
57-
"orig": tok.string,
58-
"repl": repl,
59-
"op": tok.string + "->" + repl,
60-
}
61-
)
173+
toks = list(tokenize.generate_tokens(io.StringIO(source).readline))
62174
except (tokenize.TokenError, IndentationError, SyntaxError):
63175
# A file we cannot tokenize yields no mutants rather than crashing the
64176
# run. Mutation is opt-in evidence; its absence never grants SAFE.
65177
return []
178+
spans = _docstring_spans(source)
179+
out = []
180+
for i, tok in enumerate(toks):
181+
(row, col) = tok.start
182+
(erow, ecol) = tok.end
183+
if row not in changed or row != erow:
184+
continue
185+
res = _mutation_for(toks, i, spans)
186+
if res is None:
187+
continue
188+
repl, kind = res
189+
if repl == tok.string:
190+
# A mutant equal to the original is a survivor no test could ever
191+
# kill; never emit one.
192+
continue
193+
out.append(
194+
{
195+
"line": row,
196+
"col": col,
197+
"endCol": ecol,
198+
"orig": tok.string,
199+
"repl": repl,
200+
"op": tok.string + "->" + repl,
201+
"kind": kind,
202+
}
203+
)
66204
return out
67205

68206

‎src/verify/mutation.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,12 @@ const SIDECAR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'chec
2121
export interface SurvivingMutant {
2222
file: string;
2323
line: number;
24-
// Structured, not "+->-": return-value and statement-deletion operators (the
25-
// ADR-15 roadmap) cannot be an orig->repl string, so the encoding would break.
24+
// The original source token, paired with `mutatedTo` as an orig->repl pair. An
25+
// operator (`<=`), a boolean name (`and`), OR a constant literal (`2`, `"hi"`,
26+
// `None`) since #149 — the field name predates constants but the slot has always
27+
// held the original token. Structured, not "+->-": statement-deletion (the
28+
// ADR-15 roadmap) has no orig->repl target and will add a `kind` discriminator
29+
// additively then, which a constant does not need.
2630
operator: string;
2731
mutatedTo: string;
2832
}
@@ -49,6 +53,10 @@ export interface Mutant {
4953
orig: string;
5054
repl: string;
5155
op: string;
56+
// "operator" or "constant" (#149). The budget is filled operators-first so a
57+
// constant never evicts a higher-signal operator mutant past the cap. Absent
58+
// (older sidecar / unrecognised) is treated as non-constant, i.e. kept first.
59+
kind?: string;
5260
}
5361

5462
export interface MutationInput {
@@ -153,9 +161,21 @@ export async function runMutation(input: MutationInput): Promise<MutationResult>
153161
}
154162
}
155163
if (all.length === 0)
156-
return { ...empty, ran: true, skippedReason: 'no mutable operators in the changed statements' };
157-
158-
const chosen = all.slice(0, budget);
164+
return {
165+
...empty,
166+
ran: true,
167+
skippedReason: 'no mutable operators or constants in the changed statements',
168+
};
169+
170+
// Operators before constants (#149): constants are far more numerous and have a
171+
// higher equivalent-mutant rate, so a flat positional cap would let a constant
172+
// evict a higher-signal operator mutant a smaller diff would have tested. A
173+
// stable partition keeps token order within each group.
174+
const ordered = [
175+
...all.filter((x) => x.m.kind !== 'constant'),
176+
...all.filter((x) => x.m.kind === 'constant'),
177+
];
178+
const chosen = ordered.slice(0, budget);
159179
const survivors: SurvivingMutant[] = [];
160180
let killed = 0;
161181
let inconclusive = 0;

0 commit comments

Comments
 (0)