Fixes and Safety¶
heki check --fix rewrites an OPT finding only when heki proves that the rewrite keeps what
the program does. This page shows the fix commands, what each finding offers, and what a fix
must prove.
Fix commands¶
$ heki check --diff # preview (exit code 1 when something would change)
$ heki check --fix # apply safe, unconditional fixes
$ heki check --fix --include-size-dependent # also the proven-safe size-dependent rewrites
$ heki check --fix --unsafe-fixes # also the unsafe fixes
- A fix comes with a report:
--fixapplies only the fixes of the reports shown. A report whose rewrite heki proves safe has a safe fix, and it is exact only when its other premises hold too: anOPT120report in awhileloop is heuristic even when its rewrite is proven safe, because the loop's trip count is open.OPT101andOPT102run by default, so a run without configuration applies their fixes. Over another loop than one the data sizes, anOPT101orOPT102rewrite is heuristic, and its fix applies with--heuristicor when its rule is selected. - The size-dependent rules (
OPT103,OPT110,OPT111,OPT120,OPT121,OPT130) are opt-in: their rewrites are proven, but the loops they report were rarely large enough to matter (Rule precision). --include-size-dependentruns the size-dependent rules with a rewrite (OPT110,OPT111,OPT120,OPT121,OPT130; notOPT103, which has no rewrite), as ifextend-selectnamed them. The flag alone changes no file: with--fixit applies their proven rewrites in every function (with--diff, it shows them), also over a loop whose trip count the data does not decide. After the fixes, the run lists their reports it could not rewrite, each with the obligation that blocks it.- An unsafe fix may change what the program does, and applies only with
--unsafe-fixes. One rule has one: aMUT118report for a Python 3.15 target replaces theobject()sentinel withsentinel("NAME"), whose type, repr, and pickling differ (Fix safety). --difftakes the same flags as--fixand writes nothing.- With
--touched, or files given as paths,--fixand--diffrewrite only those files. A shown report in another file (one whose call chain reaches a touched file) keeps its fix, and the run says how many it left: a pre-commit hook never rewrites a file the commit left alone.
What each finding offers¶
Every OPT rule finds a quadratic or linear-per-iteration pattern that has a faster equivalent.
Two independent questions decide whether heki offers the rewrite:
| Question | Possible answers |
|---|---|
| Safety: does the rewrite keep the program's behavior? | every proof obligation is Established, Blocked (cannot be proven here), or Disproved (a concrete counterexample shape exists) |
| Profitability: is the rewrite faster for every input? | unconditional, or size-dependent (it can be slower for tiny inputs or for loops that run zero times) |
Safety¶
| Obligations | What you get |
|---|---|
| All established | A diagnostic with a fix. A statement whose shape heki does not rewrite (a parenthesized x = (x + [i]), an annotated x: list = x + [i]) gets a diagnostic saying the rewrite is proven safe, to be made by hand. |
| One blocked | A diagnostic naming the first blocking obligation, and no fix. |
| One disproved | Nothing: the pattern only looks quadratic, and rewriting it would be a bug. |
Profitability¶
| Profitability | Rules | Certainty | Applied by |
|---|---|---|---|
| Unconditional (faster from the first iteration) | OPT101, OPT102 |
exact (the proven reports) | heki check --fix |
| Size-dependent | OPT110, OPT111, OPT120, OPT121, OPT130 (opt-in) |
exact (the proven reports over a loop the data sizes) | heki check --fix --include-size-dependent |
| Size-dependent, no rewrite | OPT103 (opt-in), OPT112, OPT113 |
OPT103 exact (the proven reports over a loop the data sizes), OPT113 exact (its exact tier), OPT112 heuristic |
none: suggestion only |
When the size is fixed¶
A size-dependent rule reports nothing when the code fixes the size:
- the container holds at most 16 items and nothing grows it past that or lets it escape. It
is a display without
*/**unpacking, a string constant, a builtin constructor of an iterable the code fixes (list(range(7)),tuple(".;:"),sorted(NAMES),list()), a slice with constant bounds (cases[:3],paths[-2:]), or a comprehension over fixed iterables ([c for c in LABELS if c in wanted]). Shrinking it (expected.pop(0)onexpected = [b"a", b""]) and read-only builtins are fine, and so is filling a new list a fixed number of times (ids.append(card["id"])in a loop over at most 6 cards). A tuple or a string stays fixed whatever other code does with it, unless other code rebinds its name (cfg.STATEMENTS = tuple(rows)). This holds also through local names, module constants, and other modules' module-level displays and class attributes, read in a function or in a module body; - the loop runs a fixed number of times: over such a container, a
rangeof constants with at most 16 steps, or an iterable a test on every path to the loop caps (if not 1 <= len(cards) <= 6: raise ValueError(...),assert len(xs) <= 3, also after a loop that shrinks it, when nothing on the way to the loop grows it or hands it to other code); - the list is rebuilt in every iteration;
- the loop's own test caps the accumulator:
while len(buf) < 10.
These facts decide profitability only, never safety. A size known only at run time does not count: a list whose size depends on the input is reported even when it always holds three items.
What a fix must prove¶
The analysis behind the OPT rules is separate from the one behind the other rules, and
deliberately conservative:
| Obligation | Why | Example |
|---|---|---|
| No type annotation is trusted | a subclass can override __contains__ or __add__ |
x: list[int] = WeirdList(...) is not a list for heki |
| The object is created in the function and never escapes | heki counts anything it cannot see as shared: parameters, globals, attributes, values passed to unknown functions, names captured by closures | sink(rows) inside the loop blocks rows.append(...) |
| Access is exclusive: no other variable, iterator, or view still refers to the old object after the statement | an in-place update would change what they see | for v in x: x = x + [v] ends, but x.append(v) would loop forever, so heki reports nothing |
| Evaluation order and exceptions are kept | a rewrite must not call anything earlier or later | {**d, f(): g()} becomes d.update({f(): g()}), not d[f()] = g(), which would call g first |
| Builtin names are the builtins | the module can rebind them | trusted only while nothing rebinds them: an assignment, a global store, from m import *, any call of globals(), or a module that patches builtins (a .pyi stub never runs, so its import builtins does not count) |
| Locals change only through the code | eval, exec, locals(), sys._getframe, and frame attributes can change them behind any analysis |
candidates in such functions are always blocked; heki assumptions lists these places in a project |
The scope analysis is checked against CPython's symtable, and adversarial programs that break a
naive rewrite are run on CPython: see Development.
How --fix applies fixes¶
- It applies the fixes that do not overlap.
- It analyzes the result again and repeats until nothing changes, at most ten passes: a fix that becomes provable after another one is applied too.
- It reports what is left.
| Case | What happens |
|---|---|
A suppressed diagnostic (# heki: ignore[...]) |
It is never fixed. |
| A file that changed on disk meanwhile (an editor saved it) | It is not written: the run keeps that save, reports an error, and exits with code 2. Run --fix again. |
| Fixes of a pass that would leave a file that does not parse | None of them is applied to that file, and the run exits with code 2 (a heki bug to report). |
\n, \r\n, or lone \r line breaks |
Fixes work the same, and the lines they insert use the file's own line break. |
--diff prints the paths every other output format prints (relative to the working directory),
so patch -p1 applies it where heki ran.
Fixes keep type checkers and isort satisfied¶
A collections.deque rewrite (OPT120, OPT121) also rewrites the variable's annotation and
adds the import:
$ heki check --diff --include-size-dependent jobs.py
--- a/jobs.py
+++ b/jobs.py
@@ -1,11 +1,12 @@
"""Job queue."""
+import collections
import os
def drain(jobs: list[int]) -> int:
- queue: list[int] = list(jobs)
+ queue: collections.deque[int] = collections.deque(list(jobs))
total = 0
while queue:
- total += queue.pop(0)
+ total += queue.popleft()
return total
Would fix 1 issue(s) in 1 file(s).
- An annotation the fix cannot rewrite (
Sequence[int], a union), or another annotated declaration of the variable, blocks the fix. - So does a variable the list reaches that is also bound to another object (
s = [...]befores = queue, or a parameters): a type checker gives the variable one type, which would not accept the deque. import collectionsgoes into the module's block of standard-library imports, in the order that block follows: straight imports first, or sorted by module as withforce-sort-within-sections.- Without such a block, it starts one before the other imports. In a module without imports, it
follows the docstring and
__future__imports, with the blank lines isort expects. - It never goes above a shebang, an encoding declaration, or a
from __future__import, and only imports run before it, so the rewritten function cannot run beforecollectionsis bound. - An existing
from collections import dequeorimport collectionsis reused only when it runs unconditionally (not underif TYPE_CHECKING:), nothing else binds or deletes the name (no other store, nodelin a function declaring itglobal, no star import that may rebind it), and it names the standard library's module (notfrom .collections import deque).