# heki
> Experimental static checker for Python that tracks side effects and mutations across function calls.
---
Source: https://heki.koxudaxi.dev/
# heki
🧱 heki (壁, Japanese for "wall") is a static checker for Python, written in Rust. It tracks side
effects and mutations across function calls.
By default, it catches blocking calls in `async` code, database queries in loops, quadratic
loops, and in-place changes to read-only parameters and to `lru_cache` results. You can also add
rules in `pyproject.toml` to restrict which functions may mutate state or reach I/O.

These reports are *exact*: built only from facts heki established, by rules whose every report
on a corpus was checked by hand ([Rule precision](https://heki.koxudaxi.dev/precision/#certifications)).
[](https://pypi.org/project/heki/)
[](https://pypi.org/project/heki/)
[](https://github.com/koxudaxi/heki/actions/workflows/ci.yml)
[](https://github.com/koxudaxi/heki/blob/main/LICENSE)
⚡ Try it in your project's root, without installing: `uvx heki check`
---
### A blocking call two helpers below an `async def`
```python
# app/users.py
import requests
def fetch_name(user_id: int) -> str:
return requests.get(f"https://api.example.com/users/{user_id}", timeout=5).text
def load_user(user_id: int) -> dict[str, str]:
return {"id": str(user_id), "name": fetch_name(user_id)}
```
```python
# app/api.py
from app.users import load_user
async def get_user(user_id: int) -> dict[str, str]:
return load_user(user_id)
```
```console
$ heki check
app/api.py:5:12: EFF101 (async-blocking-call) [error] `app.users.load_user` always runs the waiting call `requests.get` on the event loop (2 calls down, on every path)
|
5 | return load_user(user_id)
| ^
= related: app/api.py:5:12: `get_user` calls `app.users.load_user`
= related: app/users.py:8:41: `load_user` calls `app.users.fetch_name`
= related: app/users.py:5:12: `fetch_name` calls `requests.get`
= help: offload it with `asyncio.to_thread`, or use an async client
Found 1 diagnostic(s) in 2 file(s).
note: 4 heuristic rule(s) are off; enable them with `--heuristic` or `lint.heuristic = true`
EFF101 (async-blocking-call): `heki rule EFF101`, https://heki.koxudaxi.dev/rules/async-blocking-call/
```
### A query one helper below a loop
```python
# app/orders.py
import sqlite3
def customer_name(cursor: sqlite3.Cursor, customer_id: int) -> str:
cursor.execute("SELECT name FROM customers WHERE id = ?", (customer_id,))
return str(cursor.fetchone()[0])
def order_summaries(cursor: sqlite3.Cursor, orders: list[tuple[int, int]]) -> list[str]:
lines: list[str] = []
for order_id, customer_id in orders:
lines.append(f"#{order_id} {customer_name(cursor, customer_id)}")
return lines
```
```console
$ heki check
app/orders.py:11:37: EFF103 (loop-db-query) [warning] every iteration over parameter `orders` sends a database statement: `sqlite3.Cursor.execute` (through `app.orders.customer_name`)
|
11 | lines.append(f"#{order_id} {customer_name(cursor, customer_id)}")
| ^
= related: app/orders.py:11:37: `order_summaries` calls `app.orders.customer_name`
= related: app/orders.py:5:5: `customer_name` calls `sqlite3.Cursor.execute`
= help: batch the queries, or load the data once before the loop
Found 1 diagnostic(s) in 1 file(s).
heki check does not fail on 1 report(s) shown now: warnings, and heuristic reports, which can be wrong about the code and count as warnings; `fail-on = "warning"` in the lint settings makes them fail it.
note: 4 heuristic rule(s) are off; enable them with `--heuristic` or `lint.heuristic = true`
EFF103 (loop-db-query): `heki rule EFF103`, https://heki.koxudaxi.dev/rules/loop-db-query/
```
Ruff, ty, Pyrefly, pyright, and mypy report nothing for either example with their default settings.
### How heki differs
The difference is the model, not reaching across files: type checkers already follow types
across modules. heki models effects and aliases, what code does:
| Tool | Models | heki adds |
| --- | --- | --- |
| Ruff | syntax and style | the effects behind a call: a blocking call, a query, or a write, wherever it happens |
| ty, Pyrefly, pyright, mypy | declared types | in-place changes, through aliases and helpers, to `frozen`, `ReadOnly`, and `Final` fields and to `Sequence` / `Mapping` / `AbstractSet` arguments |
| tach, import-linter | which modules may import which | which functions write or read a field, call a function, or reach I/O; which modules may import which, knowing when each import runs (experimental); planned: these tools' contracts read as heki contracts |
Their stricter settings do not close the gap. The second example above is fully annotated and
passes Ruff's annotation rules (`ANN`), `mypy --strict`, pyright's strict mode, and Pyrefly's
`strict` preset, yet it sends one query per order: the types are right, and what the code does
is slow. heki leaves syntax, style, and types to these tools, and keeps doing so as they grow:
use it next to them.
### What a first run shows
Run `uvx heki check` (or `heki check` once [installed](https://heki.koxudaxi.dev/installation/)) in the directory with
`pyproject.toml`:
- An error reports a bug that can be critical: a wrong result, an exception, a lost update, a
deadlock, an event loop held up for every other task, like the first example above, or a
broken contract. A warning reports slower code, like the second, or a bug that is rarely
harmful.
- An exact error fails the run (exit code 1). Warnings, and heuristic reports, which can be
wrong about the code, are printed and do not fail it (exit code 0).
[`--fail-on warning`](https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint)
(`lint.fail-on = "warning"`) makes them fail it too.
- A note at the end says how many heuristic rules were left off; `--heuristic` runs them.
- Next, [`heki recommend`](https://heki.koxudaxi.dev/recommend/) (experimental) says which rules would report on the
project, what heki could not see, and the contracts the code already keeps, with the keys to
add.
### Your conventions, checked instead of reviewed
The checks above need no configuration: `EFF101` and `EFF103` are exact and run by default.
The rules of your own project, which you keep today by review, by AST scripts, or by run-time
guards in tests, and which a coding agent cannot know unless a check tells it, can be added as a
few lines of [configuration](https://heki.koxudaxi.dev/configuration/).
For example, these lines say that only the functions in `app.store` may change `Order.items`:
```toml
[[tool.heki.write-owners]]
name = "order-store"
targets = ["app.models.Order.items"]
allowed-writers = ["app.store.*"]
```
A function in `app/api.py` that appends to `order.items` through a helper breaks it:
```console
$ heki check
app/api.py:9:5: MUT201 (write-owner-violation) [error, heuristic] `add_gift_wrap` writes `app.models.Order.items` (through a helper) via `app.api._append` outside the write owners of `order-store`
|
9 | _append(order.items, "gift-wrap")
| ^
= related: app/api.py:9:5: `add_gift_wrap` calls `app.api._append`
```
The report is heuristic: the contract rules are not [certified](https://heki.koxudaxi.dev/precision/#certifications)
yet, and a `MUT201` report can rest on an alias or a helper's write on one path only.
heki follows aliases, helpers, and subclasses, with no decorators and nothing running at run
time. Each kind of rule has its own contract:
| What you want to keep | Contract | Main keys |
| --------------------- | -------- | --------- |
| Only `app.store` changes `Order.items` | `write-owners` | `targets = ["Order.items"]`, `allowed-writers = ["app.store.*"]` |
| Only `app.billing` reads `Order.card_token` | `read-owners` | `targets = ["Order.card_token"]`, `allowed-readers = ["app.billing.*"]` |
| Only `app.admin` calls `app.db.reset` | `call-owners` | `targets = ["app.db.reset"]`, `allowed-callers = ["app.admin.*"]` |
| No caller changes the settings `load_settings` returns to everyone | `readonly-returns` | `producers = ["app.config.load_settings"]`, `deep = true` |
| Every change of `Order.items` is followed by `order_changed()` | `invalidation` | `targets = ["Order.items"]`, `invalidators = ["app.cache.order_changed"]` |
| Code in `app.render` makes no blocking call | `effect-boundaries` | `scopes = ["app.render.*"]`, `forbid = ["blocking"]` |
See [Contracts](https://heki.koxudaxi.dev/configuration/#contracts) for every key.
### A safety net for reviews and coding agents
- The [language server](https://heki.koxudaxi.dev/lsp/) checks while you edit and re-checks only what an edit can affect.
- [`heki snapshot`](https://heki.koxudaxi.dev/adoption/#effect-snapshots-mut103) records what each public function does, and `MUT103` reports a function that gained an
effect, which a diff does not show.
- [Coding agents](https://heki.koxudaxi.dev/coding-agents/) get the same checks as JSON, and an
[Agent Skill](https://heki.koxudaxi.dev/coding-agents/#agent-skill-experimental) teaches them the workflow.
- [`heki inspect`](https://heki.koxudaxi.dev/coding-agents/#what-a-function-does-heki-inspect-experimental) (experimental)
says what one function does, so an agent does not read its callees to find out.
!!! warning "Experimental"
The exact rules are certified, but heki is still under active development: rules,
configuration keys, diagnostics, and output formats can change between releases without a
deprecation period. Try it on your code and report what it gets wrong.
## ✨ Why heki?
Types say what values are; heki checks what code does:
- **Aliases and in-place changes:** which objects a function changes, through any alias, helper,
or subclass.
- **Contracts:** who may write, read, or call what, and which code may reach I/O.
- **Proven rewrites:** quadratic patterns are rewritten only when the rewrite is proven, not
guessed.
### What code does, not what types it has
These rules are exact and run by default. Each report shows the chain of calls that leads to it.
| What goes wrong | Rule |
| --- | --- |
| A blocking call that a call in an `async def` always runs, several helpers below | [`EFF101`](https://heki.koxudaxi.dev/rules/async-blocking-call/) |
| A database statement on every iteration of a loop over data | [`EFF103`](https://heki.koxudaxi.dev/rules/loop-db-query/) |
| A `Sequence` / `Mapping` / `AbstractSet` argument changed in place by a helper | [`MUT110`](https://heki.koxudaxi.dev/rules/readonly-param-mutation/) |
| A list, dict, or set that an `lru_cache` / `cache` function returned, changed in place | [`MUT114`](https://heki.koxudaxi.dev/rules/cached-result-mutation/) |
| A change of a builtin container that is lost because the object is new and nothing holds it (`list(xs).sort()`) | [`MUT119`](https://heki.koxudaxi.dev/rules/change-lost-on-new-object/) |
| A DataFrame or array concatenated with itself on every loop iteration | [`DATA101`](https://heki.koxudaxi.dev/rules/loop-carried-concat/) |
| A list rebuilt, or a dict or set merged, on every loop iteration, and a nested-loop join | `OPT101`, `OPT102`, `OPT113` ([fixes](https://heki.koxudaxi.dev/fixes/)) |
The size-dependent rewrites (`OPT103`, `OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130`) are exact
too, but opt-in: the loops they report were rarely large enough to matter
([Rule precision](https://heki.koxudaxi.dev/precision/#certifications)).
To certify a rule, two reviewers check by hand every exact report it makes on the development
corpus (378 packages and 30.75 million lines, plus packages added for rules with few reports), and
one run on a frozen holdout of 100 packages is checked too. Neither may hold a false claim.
`EFF101` and `EFF103`, the rules of the two examples above, had 287 and 103 reports on the corpus
and 152 and 122 on the holdout, none false.
[Rule precision](https://heki.koxudaxi.dev/precision/#certifications) lists every certified rule.
*Heuristic* reports can be wrong about the code. They are opt-in (`heki check --heuristic`), and
every output labels them.
The other rules are heuristic or opt-in, and the [contract](https://heki.koxudaxi.dev/configuration/#contracts) rules run
once you declare a contract: see [Rules](https://heki.koxudaxi.dev/rules/) and [Rule precision](https://heki.koxudaxi.dev/precision/).
### Fast, quiet, and easy to adopt
- A 100,000-line project is checked in a few seconds.
- [`heki recommend`](https://heki.koxudaxi.dev/recommend/) (experimental) prints advice on the project's configuration,
with the keys to add to `[tool.heki]`.
- A report needs evidence: when heki cannot tell, [it stays quiet](https://heki.koxudaxi.dev/scope/#when-heki-cannot-tell).
- Configuration, suppression comments, and output formats follow Ruff, and a [baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines) fails CI
only on new findings.
## 🔓 What Python leaves open
| What Python leaves open | What other languages enforce | What heki checks |
| --- | --- | --- |
| Any code can change any object it reaches | ownership and borrowing (Rust), `const` / `readonly` | read-only parameters, fields, and views changed through helpers (`MUT110`, `MUT108`, `MUT120`); `write-owners` / `read-owners` contracts (`MUT201`, `MUT203`) |
| A signature does not say what a function does | effect types, `IO` in the type (Haskell) | blocking calls reached from `async def`, and clients and queries in loops (`EFF101`–`EFF103`); `effect-boundaries` (`EFF201`); effect snapshots (`MUT103`) |
| Shared mutable objects hide changes | value semantics, immutability by default | stale cached properties and hashes (`MUT101`, `MUT107`); changed shared return values (`MUT114`, `MUT202`); writes an `invalidation` contract must announce (`MUT208`) |
| Dynamic dispatch blocks optimizations | static types let a compiler prove a rewrite | quadratic patterns (`OPT`), rewritten only when proven under CPython's semantics |
## 🔧 Rewrites proven under CPython's semantics
The `OPT` rules find quadratic list, dict, set, bytes, and queue patterns. `heki check --fix`
rewrites one only when it proves that the program behaves the same:
- it trusts no type annotation (a subclass can override `__add__`);
- any other reference to the object blocks an in-place update;
- evaluation order and exceptions are kept;
- builtins count only while the module does not rebind them.
A `collections.deque` rewrite also updates the annotation and adds the import:
```console
$ 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).
```
`--fix` alone applies the rewrites that are faster for every input (`OPT101`, `OPT102`). A
size-dependent one like this comes from an opt-in rule: `--include-size-dependent` runs those
rules and applies their rewrites.
The scope analysis is checked against CPython's `symtable` on 3.11 to 3.15, and adversarial
programs that break a naive rewrite must all be blocked on CPython. When a proof fails, the
report names the missing obligation instead of offering a fix. See [Fixes and safety](https://heki.koxudaxi.dev/fixes/).
## 👉 Next steps
- 🎯 See what heki [covers and does not cover](https://heki.koxudaxi.dev/scope/).
- 📦 [Install heki](https://heki.koxudaxi.dev/installation/) and 🚀 [run it on a project](https://heki.koxudaxi.dev/getting-started/).
- ⚙️ [Configure](https://heki.koxudaxi.dev/configuration/) rule selection, contracts, and the Python version.
- 📏 Browse the [53 rules](https://heki.koxudaxi.dev/rules/), and see [how precise each one is](https://heki.koxudaxi.dev/precision/).
- 🔧 Read how [fixes are proven safe](https://heki.koxudaxi.dev/fixes/).
- 🪜 [Adopt it gradually](https://heki.koxudaxi.dev/adoption/) with a Ratchet baseline in CI.
- 🖥️ Use it from [your editor](https://heki.koxudaxi.dev/lsp/) or 🤖 [a coding agent](https://heki.koxudaxi.dev/coding-agents/).
## 📛 Name
*heki* is 壁, "wall", in its Sino-Japanese (*on*) reading, the one used in compounds such as
防火壁 (*bōkaheki*, "firewall"). On its own the character is usually read *kabe*.
---
Source: https://heki.koxudaxi.dev/scope/
# Scope and Limitations
This page says what heki checks, what it leaves to other tools, where its knowledge comes from,
and what it does when it cannot tell.
## What heki covers
1. The core is what a program does across functions and modules: effects, changes to state,
aliasing, purity, and async and resource behavior. One file or one type cannot decide these.
2. Walls are contracts you write, or that [`heki recommend`](https://heki.koxudaxi.dev/recommend/) proposes, on who may
write, read, call, reach an effect, and import what. Which modules may import which, and
import cycles, are walls
([ADR-022](https://github.com/koxudaxi/heki/blob/main/docs/DESIGN_HISTORY_AND_ADR.md#adr-022)).
heki's import rules ship as experimental: the `import-boundaries` contracts, and opt-in rules for
import cycles, circular imports that fail, and imports of test code or of dependencies
declared only for development or in an extra. Reading tach's and import-linter's contracts is
planned.
3. Patterns and style that one file decides belong to linters such as Ruff and isort, and type
correctness to type checkers.
4. An idea from another language's tools is taken when it fits the core or the walls and passes
the evidence gate: counts on a corpus, real harm, and no false exact claim
([How a rule gets into heki](https://heki.koxudaxi.dev/scope/#how-a-rule-gets-into-heki)).
5. Framework knowledge enters as catalog data
([`[[tool.heki.ecosystem]]`](https://heki.koxudaxi.dev/configuration/#ecosystem-knowledge-toolhekiecosystem)). heki has
no rules written for one framework.
## Where heki fits
| Tool | Looks at | Example |
| ---- | -------- | ------- |
| A linter such as [Ruff](https://docs.astral.sh/ruff/) | Syntax and style, one file at a time | `time.sleep()` written directly in an `async def`; a discarded `asyncio.create_task(...)` |
| A type checker such as [ty](https://github.com/astral-sh/ty) | Whether values match their declared types | a `str` passed where an `int` is expected |
| An import-graph checker such as [tach](https://github.com/gauge-sh/tach) or [import-linter](https://github.com/seddonym/import-linter) | Which modules may import which | `app.api` importing `app.db` when the declared layers forbid it; planned in heki: these tools' contracts read as heki contracts, and which imports run while a module loads |
| heki | What code does, not what types it has: effects and aliases, through any number of calls | an `async def` that reaches `requests.get` three helpers away; a model field written outside the store that owns it; an attribute `__hash__` reads changing after the object went into a `set` |
heki differs from these tools in what it models: effects and aliases. It leaves syntax and types
to the tools that model them, also as they grow. Where another tool covers part of a case, heki
keeps the rest: Ruff's `RUF006` reports discarded tasks, so `EFF107` reports only the tasks bound
to a variable.
### Clean for Ruff, ty, and tach; broken all the same
```python
# app/clients.py
import requests
def fetch_json(url: str) -> dict:
return requests.get(url, timeout=5).json()
# app/users.py
from app.clients import fetch_json
def load_profile(user_id: int) -> dict:
return fetch_json(f"https://api.example.com/users/{user_id}")
def load_user(user_id: int) -> dict:
return {"id": user_id, **load_profile(user_id)}
# app/api.py
from app.users import load_user
async def handler(user_id: int) -> dict:
return load_user(user_id) # blocks the event loop three calls down
```
```python
# app/models.py: only `Store.*` may write `Model.fields` (a write-owners contract)
class Model:
def __init__(self) -> None:
self.fields: list[str] = []
class Store:
def add_field(self, model: Model, name: str) -> None:
model.fields.append(name)
def add_default(fields: list[str]) -> None:
fields.append("id")
def parse(model: Model) -> None:
fields = model.fields
add_default(fields) # changes `Model.fields` behind the store's back
```
```toml
[[tool.heki.write-owners]]
name = "model-store"
targets = ["Model.fields"]
allowed-writers = ["Store.*"]
```
Each of these passes, because each tool sees one step:
| Command | Sees | Does not see |
| ------- | ---- | ------------ |
| `ruff check --select ASYNC,B,RUF,PERF,PL,SIM,FURB,S` | `requests.get` only when it is written in the `async def` itself | the call three helpers down |
| `ty check` | a `list[str]` passed where a `list[str]` is expected | that `add_default` changes `Model.fields` |
| `tach check` (with `app.api` → `app.users` → `app.clients` declared) | `app.api` importing `app.users`, which is allowed | what `load_user` does |
heki follows the call into `load_user` and the alias into `add_default`:
```console
$ heki check --output-format concise
app/api.py:5:12: EFF101 `app.users.load_user` always runs the waiting call `requests.get` on the event loop (3 calls down, on every path)
app/models.py:17:5: MUT201 [heuristic] `parse` writes `Model.fields` (through a helper) via `app.models.add_default` outside the write owners of `model-store`
Found 2 diagnostic(s) in 4 file(s).
note: 4 heuristic rule(s) are off; enable them with `--heuristic` or `lint.heuristic = true`
```
## Where heki pays off
| Code | What heki finds |
| ---- | --------------- |
| Async services, and web or database code written in layers of helpers | blocking calls that reach the event loop, clients and queries created inside loops (N+1), I/O while a lock or a transaction is held |
| Large code bases that protect shared state by convention, review, or their own checkers | contract violations, followed through aliases, helpers, and subclasses |
| Loops over growing collections | proven-safe rewrites and suggestions for quadratic patterns |
In small scripts, or code that is mostly synchronous and self-contained, a linter and a type
checker cover most of what matters, and heki reports little.
## What heki does not do
| Check | Use instead |
| ----- | ----------- |
| Style, formatting, and syntax | a linter such as Ruff |
| Type errors | a type checker such as ty |
| Import order, required imports, import conventions, relative-import style, and the `lazy` policy of one file | a linter such as Ruff (`I`, `ICN`, `TID252`, `TID254`, `TID255`), or isort for the order |
| Dead code and duplicated code | Ruff or [vulture](https://github.com/jendrikseipp/vulture) |
| Constant-factor micro-optimizations, such as hoisting `re.compile` | no heki rule |
- heki does not change your code's shape: it adds no decorators, contract types, or runtime
checks, and it does not compile or rewrite code at build time.
- heki never runs or instruments your program, and reads no profile of it.
## Where heki's knowledge comes from
| Source | What it tells heki | Extend it with |
| ------ | ------------------ | -------------- |
| Its own analysis | an SSA form of every function; aliases (copies, attributes, and the iterators and views derived from an object); what each function mutates and which effects it reaches, propagated over the project's call graph until nothing changes | - |
| A catalog of library behavior | `requests.get` blocks on the network; `asyncio.to_thread(fn)` and `@sync_to_async` run a function on another thread; `logging` calls are never reported; `sqlite3.connect()` returns a `Connection`; `threading.Lock` is a synchronous lock | [`[[tool.heki.ecosystem]]`](https://heki.koxudaxi.dev/configuration/#ecosystem-knowledge-toolhekiecosystem) |
| Contracts you declare | who may write, read, or call (`write-owners`, `read-owners`, `call-owners`); which returned objects are shared (`readonly-returns`); which changes must be announced (`invalidation`); which functions must not reach I/O or writes (`effect-boundaries`); which modules a module may import (`import-boundaries`) | [contracts](https://heki.koxudaxi.dev/configuration/#contracts) in the configuration |
| Type annotations, as hints only | which class an object has and which method a call reaches: `session: Session` makes `session.execute(...)` a database call | annotations in your code |
- heki does not analyze the source of the standard library or of installed packages: the
catalog declares their effects.
- Contracts need no decorators, no special types, and nothing at run time.
- The checking rules (`MUT`, `EFF`, `DATA`, `OPT112`, `OPT113`) use annotations. The rewriting
rules never read them, because a subclass can override any method (see
[Fixes and Safety](https://heki.koxudaxi.dev/fixes/#what-a-fix-must-prove)).
### How a call is resolved
heki looks for the callee in this order:
1. local constructors and imports;
2. annotations;
3. attributes `__init__` or `__post_init__` assigns and globals the module body assigns: the
join of what every store of each binds;
4. the class hierarchy, up to eight overriding methods.
It also follows container item types (`list[Model]`), return annotations along the MRO,
`isinstance` narrowing, unions of up to three classes, and project `Protocol`s.
## When heki cannot tell
A rewrite and an exact report make the same choice when information is missing, in opposite
directions; a heuristic report makes it only for some premises:
| | A rewrite (`OPT` fix) | An exact report | A heuristic report |
| - | --------------------- | --------------- | ------------------ |
| Needs | a proof | every premise of its claim established | evidence, with some premises open |
| What heki cannot see | counts as shared and blocks the fix | stops the report | stops it for an unresolved call; does not stop it for the premises its rule page marks open |
| What you get | the diagnostic names the failed obligation: `[not auto-fixable: ...]` | no report: a missed finding, never a guess | a report labelled `heuristic`, which can be wrong about the code |
Each rule page lists the premises of its claim under "What a report states", and which of them
a heuristic report may not have established ([Rule Precision](https://heki.koxudaxi.dev/precision/)).
A report that crosses functions shows its call chain as related locations. A call heki cannot
resolve is not followed:
- a value of type `Any`, or an unannotated parameter;
- a method name computed at run time;
- a call with more than eight possible overrides;
- a method no project class along a class's MRO defines, when a base of the class is a value
heki cannot name where its class statement runs (`class Derived(base)` with `base` a
parameter, a local, or a call's result), which may define it; such a class is no subclass of
any project class either;
- a function outside the checked files that the catalog does not list.
Two more cases stay quiet by design:
- A branch the caller's arguments switch off is not followed: `load(name, cache=False)` does not
reach the request under `if cache:`.
- A client or query created only while an attribute is unset counts once per object, not once
per loop iteration, and so does a `functools.cached_property` getter; one created only while
a module global or a local variable the loop carries is unset (or a first-iteration flag
holds), or right before the loop ends (`break`, `return`, `raise`), counts once per loop.
- A blocking wait on a `concurrent.futures.Future` known to be done (`if f.done():`, after
`await asyncio.wrap_future(f)`) returns at once.
- `queue.Queue.put` waits only on a queue known to be bounded: a positive `maxsize` on some
path, every path known. A `put` on a queue heki cannot follow to where it is built is not
reported.
A file that cannot be read or does not parse is reported (exit code 2), and every other file is
checked as usual. A file that does not parse cannot run either, so heki assumes nothing it would
do: it calls nothing, defines no subclass, and patches no `builtins`. Its module still owns its
name: `import requests` reaches a project's own `requests.py`, and while that file does not
parse, the names under it resolve to nothing, never to the `requests` of the catalog.
A function whose model would pass its size budget (4 units per byte of its source, at most
50,000; real code stays below one unit per byte) is left unmodeled: heki rewrites nothing in it
and treats its body as one call it cannot resolve. `heki assumptions` lists it with the hazard
`unmodeled`. A function whose proof state (a fact per variable per block) would pass 8 cells per
byte of its source, at most 250,000, gets no `OPT` finding: heki does not try to prove a rewrite
in it. A function whose lazy initializations (the blocks each covers, and the walks that find
them) would take more than 8 cells per byte of its source, at most 250,000, has none of them
recognized: in a heuristic report its clients and queries count as made on every iteration,
and an exact report stops there.
A heuristic report goes the other way for the premises its rule page marks open: a branch heki
cannot decide counts as taken, a loop in which heki cannot show that a call runs once counts as
running it on every iteration, and a size heki cannot bound counts as data-sized (the code does
not fix it at 16 items or fewer). A loop over a list that is small by its nature (the columns of
a table, a handful of options) is reported: the report states a loop whose size the code does
not bound, and whether the loop is slow is the harm, which the rule cannot see. When an open
premise is false (a bound the code states that heki does not read, a call that cannot run on
every iteration), the report is wrong about the code, which is why it is heuristic. An exact
report never claims a size: it names the input a loop steps through.
Missed findings close as heki learns more:
| heki lacks | Add |
| ---------- | --- |
| the class of a value | an annotation |
| your blocking or offloading APIs | an entry in [`[[tool.heki.ecosystem]]`](https://heki.koxudaxi.dev/configuration/#ecosystem-knowledge-toolhekiecosystem) |
| the rules of your shared state | a [contract](https://heki.koxudaxi.dev/configuration/#contracts) |
## Known limitations
### Dynamic names
`setattr(obj, "fields", v)`, `getattr(obj, "fields")`, `getattr(obj, "method")(...)`, and
`obj.__dict__["fields"]`:
- **Followed** when the name is a constant: a literal, a module-level `Final` string
(`KEY: Final = "_key"`), also when imported, re-exported, or bound to another `Final` name, a
module-level string bound once in its module, or a class constant declared `ClassVar` or
`Final` and bound once (`Model.KEY`, `self.KEY`, `cls.KEY`).
- **Not followed** for a module-level name without `Final` that another module rebinds or deletes,
one bound in a loop, or before a star import that may rebind it or on only some of the paths
after it (`if flag: from m import *` / `else: KEY = "x"`), a class constant stored on its
class or an instance outside the class body (`Model.KEY = "x"`; from another module, only one
without `Final`), a class constant a subclass defines again, is given its own value
(`Child.KEY = "x"`), or inherits first from another base it lists before the class
(`class Child(Other, Model)`; read on that subclass, or on an instance or `cls` that may be one),
a `Final` field of a dataclass or of a class a `dataclass_transform` builds read on an instance
(`Keys("x").KEY` is `"x"`), or on a class object whose default a class with `slots=True` or built
by a transform replaces, or a computed name.
- `setattr` and `object.__setattr__` are followed through a module-level name bound once to them
(`_set = object.__setattr__`) and called on their module (`builtins.setattr`), and `getattr(obj, "fields")` is `obj.fields` itself: changing
what it returns changes the attribute's object.
- `vars(obj)` (the builtin, not a name shadowing it) is `obj.__dict__`: an entry stored, deleted,
set by a container method, or updated in place (`vars(obj) |= other`, also on
`obj.__dict__`) through either is a write of the attribute it names. Where reading it runs no
code of the instance's classes, the namespace is a builtin `dict`, so its methods resolve
(`obj.__dict__.get(KEY)` is no call heki cannot resolve); a class object's namespace is a
read-only proxy and has no class.
- A write-owners contract sees a container change through what a method or a property returns
when it returns the attribute itself on every `return` (`node.members().append(x)` with
`return self.items`) and every class the object may be runs it. A `cached_property` hands out
nothing: what the instance keeps can be replaced.
- A `write-owners` contract with `unresolved = "report"` reports the writes heki cannot tie to a
class ([`MUT205`](https://heki.koxudaxi.dev/rules/unresolved-guarded-write/)).
- A private helper hands its accesses to the callers heki sees. A helper some code also hands on
as a value (a table, a class attribute, an argument) has callers heki does not see: an owner
contract with `unresolved = "report"` judges it as if it had no callers, and one without lets
its callers decide.
- An effect boundary is silent where heki cannot see: a call it cannot resolve, or a write on an
object of unknown class, in a scope's reach. With `unresolved = "report"` it reports them
(`EFF201`).
### Objects without a known class
- Reads and writes through `Any` or unannotated parameters are not tied to a class, so contracts
on that class do not see them. A contract with `unresolved = "report"` reports them by name:
writes under [`MUT205`](https://heki.koxudaxi.dev/rules/unresolved-guarded-write/), reads under
[`MUT206`](https://heki.koxudaxi.dev/rules/unresolved-guarded-read/), and method calls under
[`MUT207`](https://heki.koxudaxi.dev/rules/unresolved-guarded-call/).
- A write in an unannotated helper is still found where a caller passes it an object of a known
class. A read is not.
- Not typed: values declared `Any` or `types.ModuleType`, generics substituted through
unbounded `TypeVar`s (a bounded or constrained one gives its bound or constraints), names a
module binds to a type expression more than once or with type parameters (a type alias bound
once names its value), calls of a subscripted class other than a builtin or `collections`
container (`Box[int]()`), and calls of `type[C]` attributes.
- A module-level table of functions (`HANDLERS = {"create": create}`) gives the value of a key
a string constant gives, and one of its values for any other key, only while no code changes
it in place; a change through a call it is handed to (`register(HANDLERS)`) is not seen.
Changing a dict, set, or list a global or an attribute holds in place joins what the change
adds to its items when heki types it (`append(x)` with `x: Field`, `extend` or `+=` of a list
of known items, `d[k] = v` with `v` of a known class), and leaves its items untyped otherwise.
A change of an item it holds (`d[k].append(x)`) is not seen.
- A function a value holds is known where the code that makes the value shows it: a field of a
`NamedTuple` or a frozen dataclass whose generated constructor the code calls (also through a
table of such instances bound once), the function a factory returns when every `return` gives
one, and a class attribute bound to `functools.partial` of a function, read through the class
or wrapped in `staticmethod`. A call through a field of a dataclass that is not frozen, one with
a `__post_init__`, or a class a `dataclass_transform` decorator builds, through a value handed
in as a parameter (a view or a callback a caller passes), through a plain `partial` attribute
read on an instance (Python 3.14 binds the instance to it, older versions do not), and through
a `partial` holding a positional argument is a call heki cannot resolve.
- The type of a module global or an instance attribute joins every store of it through a
receiver whose type heki knows: `self`, an instance of the class (a parameter `obj: Helper`,
`cls()` in a class method, one the storing module keeps in its own attribute or global, as
in `self.base.client = ...`), the module (also imported in a function, or through `setattr` or
`vars`). A store through a receiver without a known type (`def configure(obj): obj.client =
...`, a parameter whose default is the module) is not joined, nor is one through a `Protocol`
value, so the join of the other stores may be wrong for values it stores. The same holds
for a receiver read from an attribute or a global of another module (`def swap(app: App):
app.state.client = ...`, where `App`'s module types `state`), and a receiver kept in an
attribute or a global of the storing module has the type that module's stores give it: when
yet another module stores an instance of another class there (`owner.base = Other()`), a store
through it is not joined into that class.
- The items of a container an attribute or a global holds are those of the values its stores
bind (`self.clients = [httpx.Client()]`): what another function adds to the container
(`self.clients.append(client)`, `self.clients += [client]`) is not joined, so a loop over it
takes every item to be of the classes the stores give.
- `__setstate__` restoring an instance's namespace from its state keeps the attributes' types when
the class's `__getstate__` builds the state from the instance's own attributes. One putting an
attribute's value under another attribute's name (`return {"client": self.other}`) is not seen.
- A store into an instance's namespace through a method called with a `*` argument
(`self.__dict__.setdefault(*pair)`) is not seen.
- Two shapes of module-level names that no linted code writes are taken wrongly. After a
`global` statement at the module level (where it does nothing), a store of the name in a `try`
body counts as run even when a call before it in the body raises, and a list bound to
`__all__` counts as unchanged when the module body appends to it. A `TYPE_CHECKING` that a
branch binds to the flag after the module bound it to something else (`TYPE_CHECKING = True`,
then `if cond: from typing import TYPE_CHECKING`) counts as the flag on every path, so imports
under a later `if TYPE_CHECKING:` count as not running.
### Names the catalog does not list
Catalog lookups are exact. These contribute no effect until you add them with
[`[[tool.heki.ecosystem]]`](https://heki.koxudaxi.dev/configuration/#ecosystem-knowledge-toolhekiecosystem):
- a class reached through another public name: `from sqlalchemy import Engine` for
`sqlalchemy.engine.Engine`, `redis.StrictRedis` for `redis.Redis`;
- a method the catalog does not list;
- objects reached through subscripts or framework attributes, which have no known class:
`client["app"]["users"]`, Django's `Model.objects`.
### Properties
- **Followed:** reading a `@property` or `functools.cached_property` of a project class runs its
getter. Its effects, writes, and the attributes it reads count for the reader, also through
base classes, overriding subclasses, and `super()`. The getter's return annotation types the
value read.
- **Not followed:** a property that also defines a setter or deleter (`@x.setter`), and
`x = property(get_x)`.
### Read-only types
- `MUT110` follows `Sequence` / `Mapping` / `AbstractSet` / `ReadOnly` parameters into the
helpers they are handed to, any number of calls deep. A helper parameter annotated with a mutable type is left
to the type checker, and a container inside the argument does not count.
- `MUT108` (opt-in) follows frozen dataclasses, `NamedTuple`s, classes that a
`dataclass_transform(frozen_default=True)` in the checked files builds, `Final` / `ReadOnly`
attributes, and `ReadOnly` `TypedDict` keys. It does not see the transforms of installed
packages (attrs, Pydantic), and an instance the function constructs itself counts as under
construction.
- `MUT120` (opt-in) follows read-only views, classes and protocols of properties without a
setter: a helper that does not see the view's type and rebinds one of its properties, and the
container a property returns changed in place. A write through the view itself is left to the
type checker.
### Generators and coroutines
A generator's body runs where it is iterated:
| Followed | Not followed |
| -------- | ------------ |
| a `for` loop or a comprehension | a generator handed to anything else: `StreamingResponse(rows())`, a container |
| unpacking, `yield from` | a generator only stepped with `next()` |
| a consuming call: `list(...)`, `"".join(...)`, `items.extend(...)` | a generator unpacked into a call: `f(*rows())` |
| a lazy wrapper iterated there: `enumerate(...)` | |
| a project function iterating it | |
- A generator a function returns runs where its caller iterates it.
- A generator nothing iterates (a call as a statement, a value only tested for truth) never runs
its body; `EFF116` reports such calls.
- A generator expression counts where it is written.
- A coroutine runs where it is awaited; one only scheduled (`asyncio.create_task`) is checked on
its own.
- Iterating an object runs its class's `__iter__` only for classes the catalog lists (a
SQLAlchemy `Query`). The `__iter__` methods of project classes are not followed.
### Guards
- **Followed:** a test of the function's own input: truthiness, `is None`, `isinstance` with
builtin classes, the `io` classes, or `os.PathLike`, or `hasattr` with a string literal, also
after the function rebinds the input on some paths (`if buf is None: buf = StringIO()`).
- **Decided by:** constants, displays and comprehensions, `io.StringIO` / `io.BytesIO` objects
the caller constructs, and the literal defaults of omitted parameters (`hasattr` only for the
methods of the file protocol: `read`, `write`, `close`, ...); not by an f-string, the result of
another call, or an instance of a subclass.
- **Not followed:** `a or b` (no guard on either value), and `isinstance` with project classes or
annotated types.
- A lazy initialization needs a direct test and the store in the function itself: a test in a
caller of the method that stores, a test combined with `or` / `and`, and memos keyed by an
argument (`@lru_cache`, a dict) are not followed.
- A future is known to be done only through `f.done()` and `await asyncio.wrap_future(f)`, not
through an event or another future its done callback sets.
- A queue is known to be bounded through local variables, the attributes its class family's own
bodies and methods store, module globals, and parameters whose project callers decide (a
helper's at each call, an `async def`'s by the join of every caller). Not followed: stores into
an attribute from outside the class family, a `maxsize` checked to be positive but not known,
an integer constant imported from another module or passed on through a parameter other than
a literal default, and a queue whose function has no project caller.
- `EFF201` does not use guards.
- An object a factory function returns counts as obtained once, like a pooled connection.
### Separate scopes
- Generator expressions and lambdas are analyzed as functions of their own:
`next(b for b in bs if b.id == a.id)` inside a loop is not reported as a nested-loop join.
- Two lambdas in one function share the qualified name `f..`, so heki may
attribute one lambda's effects to a call of the other:
```python
import requests
async def handler(url: str) -> int:
fetch = lambda: requests.get(url, timeout=5)
size = lambda: len(url)
return size() # reported as reaching `requests.get` (EFF101)
```
### Metaprogramming and frameworks
`__getattr__` proxies, metaclasses, classes created at run time, and framework machinery
(validators, ORM lazy loading, dependency injection) are not modeled. heki has no
framework-specific rules.
### The target Python version
Results follow [`target-version`](https://heki.koxudaxi.dev/configuration/#top-level-settings), which defaults to the
oldest version `requires-python` admits.
- From Python 3.12, list, set, and dict comprehensions run in the enclosing function (PEP 709): a
comprehension inside a loop can be reported for `py312` and not for `py311`.
- From Python 3.14, annotations are evaluated lazily in `__annotate__` scopes (PEP 649).
- From Python 3.15, `sentinel` is a builtin (PEP 661): a `MUT118` report recommends it, and
has a fix that uses it; for an older version it names `typing_extensions.sentinel`.
- The parser reads Python 3.15 syntax for every target version: `lazy import` (PEP 810) is a lazy
import also in code for an older version.
- Syntax newer than the target version is analyzed, not reported: that is Ruff's check.
### Source encodings
heki reads the encoding a PEP 263 declaration names: UTF-8 (with or without a BOM), Latin-1, and
ASCII. A file declaring any other encoding is reported as an error and not checked. Unlike a file
that does not parse, such a file runs: what it defines and does stays unknown to the analysis of
the other files.
### Sizes known only at run time
Whether a collection is small is decided from the code: a list whose size depends on the
input counts as large, even when it always holds three items. The rules this affects are marked size-dependent;
[Fixes and Safety](https://heki.koxudaxi.dev/fixes/#when-the-size-is-fixed) lists what counts as a fixed size.
### Callers outside the checked files
Contracts reason about the callers heki sees: a private helper hands its reports to its callers,
and a function called only from allowed writers is not reported. Code outside the run, such as
tests left out of it, is not known.
## Measured and not taken
These shapes were measured on the Stage 0-A corpus (378 packages, 30.75 million lines) and not built.
Each failed the bar for a default rule: at least 10 % of the judged sample harmful, and no false exact
claim.
- Late binding of loop variables: 132 closures in 38 packages beyond the 3,865 names Ruff B023
reports; every harmful one is already a B023 report, and heki found none that B023 misses.
- Resource use after close: 289 sites in 80 packages, 8 % harmful, with false exact claims. Left to
runtime and review.
- Resource leaks across calls: 1,848 sites in 162 packages, 4 % harmful; about half are direct
constructors that Ruff `SIM115` and Pylint `R1732` flag.
- Command-query separation (a `get_*`, `is_*`, or property that changes state): 11,558 sites in 254
packages, 4 % harmful; most are caches heki does not see as caches.
- Dropped results of pure calls: 59,083 sites in 327 packages, no harm in the sample; the real bugs
are `str` methods on `str` values, which pyright `reportUnusedCallResult` covers.
- Stale caches: 199 sites in 54 packages, 5 % harmful; Ruff B019 and Pylint W1518 flag the cache on
a method.
- `asyncio.run` under a running loop: 71 sites in 12 packages, 1 of 25 judged right; nearly all are
guarded by a test heki does not model.
- Writes lost in a child process: 62 sites in 27 packages, 4 % harmful.
- `Popen` pipes left unread: 22 sites in 13 packages, 5 % harmful.
- `CancelledError` swallowed: 466 sites in 62 packages, none harmful as judged; flake8-async
`ASYNC103` and `ASYNC104` cover the shape.
- `BytesIO` read without a seek: 69 sites in 7 packages, 57 of them one test suite; too rare.
- Opposite lock orders: 106 ordered pairs of named locks in 31 packages, no pair in opposite order.
- An `except` clause that nothing in its `try` body raises, through its calls: 2,730 clauses in 157 packages
for project exceptions and 3,597 in 153 for library ones; of 60 judged, one was harmful, and that one is a
one-statement shape. Which exceptions a function can raise is planned as a `heki inspect` fact instead.
## How a rule gets into heki
heki only takes checks that need what it can prove. A proposed rule goes through four questions,
in order:
1. **Can the syntax of one file decide it?** Then it belongs in a linter such as Ruff.
2. **Is it a type error, or can an annotation express it?** Then it belongs in a type checker
such as ty. heki's part is to say where the code already keeps what such an annotation would
state, so that the annotation can be written and the type checker checks it from then on
(planned in [`heki recommend`](https://heki.koxudaxi.dev/recommend/),
[ADR-023](https://github.com/koxudaxi/heki/blob/main/docs/DESIGN_HISTORY_AND_ADR.md#adr-023)).
3. **Can one import statement decide it?** Its order, its form, or a banned name: then it
belongs in a linter such as Ruff.
4. **Does it need at least one of the proofs below?** Only then is it a heki rule.
A heki rule is measured on a corpus and reviewed by hand before it is enabled by default. Where
another tool covers part of it, heki keeps only the rest (`EFF107` and Ruff's `RUF006`). An idea
from another language's tools goes through the same questions, and joins with counts on a corpus,
real harm in the reports, and no false exact claim.
The proofs heki can make, on five axes:
| Axis | What heki establishes | Used by |
| ---- | --------------------- | ------- |
| Control flow | which statements can run after which: CFG paths, loops and their bounds, exception edges | `MUT106`, `MUT113`, `MUT208`, `EFF102`, `EFF103`, `EFF106`, `EFF109`, `EFF110`, `EFF114`, `DATA101`, `OPT` |
| Calls | which functions a call reaches across modules, and what they do (summaries propagated over the call graph) | `EFF101`, `EFF109`, `EFF110`, `EFF112`, `EFF114`, `EFF115`, `EFF116`, `EFF117`, `EFF201`, `MUT103`, `MUT108`, `MUT110`, `MUT120`, `MUT112`, `MUT113`, `MUT119`, `MUT201`–`MUT204`, `MUT208` |
| Aliases | which names, iterators, and views refer to one object; whether it is unique to its frame and of an exact builtin type | `MUT202`, `MUT201`, `MUT204`, `MUT108`, `MUT110`, `MUT120`, `MUT112`, `MUT119`, `EFF107`, `EFF109`, `EFF110`, `EFF112`, `OPT101`–`OPT130` |
| Effects | which blocking, network, file, or database work runs, from the catalog of library behavior | `EFF101`–`EFF106`, `EFF201`, `DATA101` |
| State | which attributes and containers a function reads, writes, or mutates, and who may do so | `MUT101`, `MUT107`, `MUT108`, `MUT110`, `MUT120`, `MUT111`, `MUT112`, `MUT113`, `MUT201`–`MUT204`, `MUT208` |
---
Source: https://heki.koxudaxi.dev/installation/
# Installation
heki is a single executable: its Python package ships only that executable and installs no
Python dependencies into your environment.
## With uv, pipx, or pip
=== "uv"
```console
$ uv tool install heki
$ uvx heki check # or run it without installing
```
=== "pipx"
```console
$ pipx install heki
```
=== "pip"
```console
$ pip install heki
```
As a development dependency of a project:
```console
$ uv add --dev heki
```
Wheels are published for these platforms:
| OS | Architectures |
| -- | ------------- |
| Linux | x86-64, AArch64, x86-64 musl |
| macOS | Apple silicon, Intel |
| Windows | x86-64 |
## From source
heki needs Rust 1.99 or newer:
```console
$ git clone https://github.com/koxudaxi/heki
$ cd heki
$ cargo install --path crates/heki
```
## Check the installation
```console
$ heki --version
$ heki rule --all
```
## Supported Python versions
- heki analyzes code written for Python 3.11 to 3.15.
- It does not need a Python interpreter to run.
- The version of the checked code comes from
[`target-version`](https://heki.koxudaxi.dev/configuration/#top-level-settings), or from `requires-python`; see
[Scope](https://heki.koxudaxi.dev/scope/#the-target-python-version) for what it changes.
---
Source: https://heki.koxudaxi.dev/getting-started/
# Getting Started
This page runs heki on a project, reads a diagnostic, applies a fix, and picks the rules.
## Run it
From the root of a project (the directory with `pyproject.toml`):
```console
$ heki check
$ heki check --heuristic
```
The first command runs the exact rules that are not opt-in, and the rules of the
[contracts](https://heki.koxudaxi.dev/configuration/#contracts) you declare. An exact rule is certified: every report it
made on the development corpus and on a frozen holdout corpus was checked by hand, and none was
false ([Rule Precision](https://heki.koxudaxi.dev/precision/#certifications)). Without configuration, it runs:
- [`MUT110` (readonly-param-mutation)](https://heki.koxudaxi.dev/rules/readonly-param-mutation/)
- [`MUT114` (cached-result-mutation)](https://heki.koxudaxi.dev/rules/cached-result-mutation/)
- [`MUT119` (change-lost-on-new-object)](https://heki.koxudaxi.dev/rules/change-lost-on-new-object/)
- [`EFF101` (async-blocking-call)](https://heki.koxudaxi.dev/rules/async-blocking-call/)
- [`EFF103` (loop-db-query)](https://heki.koxudaxi.dev/rules/loop-db-query/)
- [`DATA101` (loop-carried-concat)](https://heki.koxudaxi.dev/rules/loop-carried-concat/)
- [`OPT101` (list-quadratic-concat)](https://heki.koxudaxi.dev/rules/list-quadratic-concat/)
- [`OPT102` (set-dict-quadratic-merge)](https://heki.koxudaxi.dev/rules/set-dict-quadratic-merge/)
- [`OPT113` (nested-loop-equijoin)](https://heki.koxudaxi.dev/rules/nested-loop-equijoin/)
`MUT101`, `MUT111`, and the size-dependent `OPT` rules (`OPT103`, `OPT110`, `OPT111`, `OPT120`,
`OPT121`, `OPT130`) are exact too, but run only when `select` or `extend-select` names them (in `pyproject.toml` or on the command
line, by code or name), or, for the five with a rewrite (not `OPT103`), when
`--include-size-dependent` is given: their reports were rarely harmful ([Rule Precision](https://heki.koxudaxi.dev/precision/)).
A report of an exact rule that did not establish every premise of its claim, such as an `OPT`
rewrite heki could not prove safe, is heuristic. A text run says how many heuristic rules and
reports it left out. `--heuristic` adds them; they can be wrong about the code, and every output
labels them.
heki checks every Python file under the current directory, except the
[excluded and ignored ones](https://heki.koxudaxi.dev/configuration/#which-files-are-checked). Pass directories to narrow
it, or files to look at: a file is checked in its project, so heki still analyzes the whole
project and shows the reports that touch the file.
```console
$ heki check src/
$ heki check app/api.py
```
## Ask what fits the project
`heki recommend` (experimental) analyzes the project as `heki check` does and says which rules
would report here, what heki could not see, and the contracts the code already keeps, with the
keys to add to `[tool.heki]`. It writes no file. A run of `heki check` that shows nothing, on a
project without contracts or a baseline, ends with a line that points to it:
```console
$ heki recommend
```
See [Configuration Advice](https://heki.koxudaxi.dev/recommend/). To adopt heki in a repository step by step, see
[Adopting heki](https://heki.koxudaxi.dev/adoption/).
## Read a diagnostic
```console
app/api.py:5:12: EFF101 (async-blocking-call) [error] `app.users.load_user` always runs the waiting call `requests.get` on the event loop (1 call down, on every path)
|
5 | user = load_user(user_id)
| ^
= related: app/api.py:5:12: `handler` calls `app.users.load_user`
= related: app/users.py:5:12: `load_user` calls `requests.get`
= help: offload it with `asyncio.to_thread`, or use an async client
```
| Part | Meaning |
| ---- | ------- |
| `app/api.py:5:12` | where to look |
| `EFF101 (async-blocking-call)` | the rule's code and name |
| `[error]` | its severity: `error` for a bug that can be critical (a wrong result, an exception, a lost update, a deadlock, an event loop held up for every other task, as here, a broken contract), `warning` for slower code or for a bug that is rarely harmful. An exact error makes `heki check` fail; a warning is shown without failing it, unless `--fail-on warning` (`lint.fail-on = "warning"`) is set. A heuristic report adds `heuristic` (`[error, heuristic]`): it can be wrong about the code, as a premise of its claim can be open, so it counts as a warning and fails the run only with `--fail-on warning` |
| the message | what heki established, in one sentence: here, that the call to `load_user` always runs `requests.get`, a call that waits on the network, on the event loop |
| `related` lines | the hops of the chain of calls behind it, to follow it across files; editors show them as related information you can jump to |
| `help` line | what to do about it |
`heki rule EFF101` explains the rule, its exclusions, and what to do instead. The
[rules reference](https://heki.koxudaxi.dev/rules/) has the same text for every rule.
## Fix what heki can prove
`--fix` applies the rewrites heki proves safe and always faster (`OPT101`, `OPT102`), and
`--diff` shows them first:
```console
$ heki check --diff
--- a/app/report.py
+++ b/app/report.py
@@ -1,5 +1,5 @@
def rows_of(items):
rows = []
for item in items:
- rows = rows + [item]
+ rows.append(item)
return rows
Would fix 1 issue(s) in 1 file(s).
$ heki check --fix
Fixed 1 issue(s) in 1 file(s).
```
`--fix` then reports what is left, such as the `EFF101` above, which has no automatic fix.
When heki cannot prove a fix safe, the help says why, nothing is rewritten, and the report is
heuristic whatever the rule's certainty. Here the list is also handed to other code inside the
loop:
```console
$ heki check --heuristic app/shared.py
app/shared.py:4:9: OPT101 (list-quadratic-concat) [warning, heuristic] `rows = rows + [...]` copies the whole list each time it runs in the loop
|
4 | rows = rows + [item]
| ^
= help: append in place with `rows.append(...)` / `rows.extend(...)` [not auto-fixable: Unique(rows): it may be shared: passed to code heki cannot see (line 5)]
Found 1 diagnostic(s) in 1 file(s).
```
[Fixes and Safety](https://heki.koxudaxi.dev/fixes/) lists which rules are fixed, and what a fix must prove.
## Silence a diagnostic
Append a suppression comment to the reported line:
```python
user = load_user(user_id) # heki: ignore[EFF101]
```
The other forms (`# heki: ignore`, `# noqa: EFF101`) and `per-file-ignores` are in
[Inline suppressions](https://heki.koxudaxi.dev/configuration/#inline-suppressions).
## Choose the rules
```console
$ heki check --select EFF,MUT # only these families
$ heki check --extend-select EFF105 # add an opt-in rule
$ heki check --ignore OPT113 # everything except one rule
```
Codes, code prefixes, and rule names (`async-blocking-call`) are accepted. A prefix does not
enable the opt-in rules, nor the heuristic ones without `--heuristic`: see
[Rule selection](https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint).
## Output formats
```console
$ heki check --output-format json
```
| Format | Prints |
| ------ | ------ |
| `full` (default; `github` in GitHub Actions) | each diagnostic with its source line, call chain, and help |
| `concise` | one line per diagnostic: the message, without the help |
| `json` | every field: also the help, the evidence, the blocker that stops a fix, and the fix edits ([fields](https://heki.koxudaxi.dev/coding-agents/#after-an-edit-heki-check)) |
| `github` | GitHub Actions annotations with the message ([CI](https://heki.koxudaxi.dev/adoption/#continuous-integration)) |
| `sarif` | the message, the location, the call chain, and the help (`properties.help`), for code-scanning dashboards (no evidence or blocker) |
Without `--output-format`, `HEKI_OUTPUT_FORMAT` chooses the format, and in GitHub Actions
(`GITHUB_ACTIONS=true`) it is `github`.
Every format, `--diff`, and the errors of files that cannot be read or parsed print a file's
path relative to the working directory when the file is inside it (otherwise as given), as Ruff
does, and with `/` separators on every platform, Windows included.
### Colors
On a terminal, the `full` and `concise` output and `--diff` are colored as Ruff colors its
output: paths in bold, rule codes in red, the severity, the source frame and its caret, and the
lines a diff removes and adds. The same variables and option as Ruff's decide it, each row over
the rows above it:
| Setting | Colors |
| ------- | ------ |
| stdout is a terminal / a pipe or a file | on / off |
| `NO_COLOR` set (to anything), or `CLICOLOR=0` | off |
| `FORCE_COLOR` set to anything but the empty string, or `CLICOLOR_FORCE` to anything but `0` | on (for a CI log that shows colors) |
| `--color always` / `--color never` | on / off |
`json`, `github`, and `sarif` output never holds colors, and the summary and the errors heki
writes to stderr are not colored.
## Exit codes
| Code | Meaning |
| ---- | ------- |
| `0` | no diagnostics, or only warnings and heuristic reports (they are printed) |
| `1` | an exact error found, or any report with `--fail-on warning` (`lint.fail-on = "warning"`), among the Ratchet regressions when a baseline is used; also when `--update-baseline` refuses a grown entry, a baseline entry matched nothing with [`report-unused-suppressions`](https://heki.koxudaxi.dev/configuration/#unused-suppressions), or `--diff` would change files |
| `2` | configuration error, unknown rule, or a file that cannot be read or has a syntax error; with files given (`heki check src/app.py`, `--touched`), only one of those files fails the run, and the others are named in a note |
---
Source: https://heki.koxudaxi.dev/configuration/
# Configuration
heki reads `[tool.heki]` from `pyproject.toml`, or a `heki.toml` / `.heki.toml` file with the same
keys without the `tool.heki` prefix. Keys are kebab-case, as in Ruff.
```toml
[tool.heki]
target-version = "py312" # default: inferred from project.requires-python
extend-exclude = ["generated"] # added to the default excludes
baseline = "heki-baseline.toml" # Ratchet baseline (heki check, --watch, the server)
[tool.heki.lint]
select = ["MUT", "EFF", "DATA", "OPT"]
extend-select = ["EFF105"]
ignore = ["OPT110"]
per-file-ignores = { "tests/**" = ["EFF"], "scripts/*.py" = ["OPT"] }
relax-async-in-tests = true
fail-on = "warning" # warnings and heuristic reports fail heki check too (default: "error")
[tool.heki.lint.severity]
OPT103 = "warning"
```
## Where heki finds the configuration
1. The project root is the nearest directory at or above the first path given (the current
directory when no path is given) that holds `heki.toml`, `.heki.toml`, or `pyproject.toml`.
The search stops at the top of the enclosing Git working tree (the directory holding `.git`):
a configuration above it belongs to another project. Without a configuration file, the root
is the current directory, as Ruff and ty take it, when it holds the first path; but never a
directory above the top of the Git working tree (then the root is that top), and outside the
current directory and any Git working tree it is the first path's own directory (the
directory given, or the given file's directory). The language server takes its workspace
folder for the current directory.
2. heki reads the first of `heki.toml`, `.heki.toml`, and `pyproject.toml` in that directory. A
`pyproject.toml` without `[tool.heki]` still marks the root: its project gets the defaults.
3. `--config ` names the file instead. The project root stays where step 1 finds it.
One run checks one project: its configuration applies to every file of the run, also to
directories given from another project. Files given name the project of the first one:
`heki check a/one.py b/two.py` checks `a/`'s project and names `b/two.py` in a warning when it is
not in it. Check projects with their own configurations in separate runs: `heki check a/`, then
`heki check b/`.
### Which tables hold the settings
The file's name decides, as Ruff reads `pyproject.toml` and `ruff.toml`:
- A file named `pyproject.toml` holds the settings in `[tool.heki]` (`[tool.heki.lint]`,
`[[tool.heki.ecosystem]]`, ...). Its other tables belong to the packaging standards and other
tools. heki reads only what it infers from them: the default target version
(`project.requires-python`) and the detected source roots (`project.name` and the workspace
tables, see [Workspaces and monorepos](https://heki.koxudaxi.dev/configuration/#workspaces-and-monorepos)).
- Any other file (`heki.toml`, `.heki.toml`, or the file `--config` names, whatever its name)
holds the same keys at its top level, without the `tool.heki` prefix (`[lint]`,
`[[ecosystem]]`).
heki never ignores a setting. These are configuration errors (exit code 2):
- an unknown key in any of heki's tables;
- a `[tool.heki]` table in a file that is not named `pyproject.toml`;
- a heki setting at the top level of a `pyproject.toml` (`[[ecosystem]]` instead of
`[[tool.heki.ecosystem]]`);
- a value of the wrong type, or one the key does not take.
The error shows the line, says what to write instead, and links the section of this page about
the key: the key a misspelled one looks like, the table a key belongs in, or the type a value
takes, with a line to copy. With `--output-format json`, the same error is the object
`{"error": {"message", "path", "line", "column", "help", "docs", "candidates"}}` on stdout.
```text
error: pyproject.toml:5:1: unknown key `select` in [tool.heki]
|
5 | select = ["MUT"]
| ^
= help: `select` is a key of [tool.heki.lint]: move it there
= help: for example: `select = ["EFF", "MUT101"]`
= docs: https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint
```
### Module names follow the source roots
Module names are the paths below a source root (`app/api.py` is `app.api` below the project
root, `src/acme/io.py` is `acme.io` below `src`). heki resolves the imports between the
project's modules by these names, and they appear in messages that name a function by its full
name and in the `target`s of [baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines) entries, whose `path`s
are relative to the project root.
- The `src` setting lists the source roots: directories relative to the project root, like
Ruff's `src` and ty's `environment.root`. A file below several of them is named below the
deepest one, and a file below none is named below the project root. `src` does not accept
globs yet (Ruff's does): list the directories.
- Without `src`, heki detects the source roots as ty does: `src`, the directory named after the
project (`project.name` of the `pyproject.toml`, else the root's own name) when it holds a
directory of the same name (`acme/acme/`), and `python` (the maturin layout), each when it is
a directory and not a package (no `__init__.py`). A source root that is a package is imported
by its own name (`src.helpers`).
- Without `src`, heki also detects the members of the project's uv, Hatch, and PDM workspaces
(see [Workspaces and monorepos](https://heki.koxudaxi.dev/configuration/#workspaces-and-monorepos)).
- Other layouts need `src`: a subdirectory application whose directories are imported as
top-level packages (`backend/config/env.py` imported as `config.env`) takes
`src = ["backend"]`, and a `lib/` layout (`lib/matplotlib`) takes `src = ["lib"]`.
#### Workspaces and monorepos
In a workspace, each member is a package of its own, installed from its own directory. Without
`src`, heki reads the workspace tables of the root's `pyproject.toml` and names each member's
modules the way installing the member names them, so a call from one member into another
resolves without configuration:
- the members: uv's `[tool.uv.workspace]` (`members` and `exclude`), the `workspace.members`
and `workspace.exclude` of every Hatch environment (`[tool.hatch.envs.]`, or
`[envs.]` in a `hatch.toml` next to it; a member may be a `{path = ...}` table), and
PDM's `[tool.pdm.workspace]` (`members`). Members are directories relative to the project root
or globs (`packages/*`; `**` spans directories), and a member must hold a `pyproject.toml`. An
`exclude` glob drops the members of its own table it matches, and its `*` spans directories
as uv matches it.
- a member's source roots are the ones detected for the project root, below the member:
`packages/core/src`, the directory named after the member (`packages/core/core` when it holds
`core/`), and `python`.
- a member without one (a flat layout) has its packages named below it: `packages/api/acme_api/`
is the package `acme_api`. Its other files keep their names below the project root
(`packages/api/main.py` is `packages.api.main`): several members often hold a `main.py` or a
`scripts/` package, and these would otherwise share a name. A package that several members
hold is named below the project root for the same reason.
For example, this uv workspace:
```text
pyproject.toml # [tool.uv.workspace] members = ["packages/*"]
packages/core/pyproject.toml
packages/core/src/acme_core/io.py
packages/api/pyproject.toml
packages/api/acme_api/server.py # from acme_core.io import wait
packages/api/main.py
```
has the source root `packages/core/src` and the member package `packages/api/acme_api`:
`acme_core.io` is `packages/core/src/acme_core/io.py`, so `heki check` run at the root follows
`server.py`'s call to `wait` into the other member. `heki check --generate-prompt` lists both.
The `src` setting replaces the detection, members included: `src = ["packages/core/src",
"packages/api"]` lists the same roots by hand, with `packages/api` naming all of the member's
files below it. Run heki at the workspace root: run inside a member, the member's own
`pyproject.toml` makes the member the project root, and the other members are outside it.
Without a configuration file the project root is where heki runs (see above): in a repository
without one, `heki check` run in `services/api/` names `services/api/app.py` `app`, and its
`from helpers import slow` finds `services/api/helpers.py`; run from the top of the repository,
the same file is `services.api.app` and the import is not resolved. Put a `pyproject.toml` or a
`heki.toml` in the project's directory to fix the root wherever heki runs.
## Top-level settings
| Key | Default | Meaning |
| --- | ------- | ------- |
| `target-version` | the oldest version `project.requires-python` admits, else `py312` | Python version of the code: `py311` … `py315` (or `3.11` … `3.15`). `--target-version` overrides it. See [below](https://heki.koxudaxi.dev/configuration/#the-default-target-version) for the inference and [Scope](https://heki.koxudaxi.dev/scope/#the-target-python-version) for what the version changes. |
| `required-version` | none | A [PEP 440](https://peps.python.org/pep-0440/) version specifier made of operators and plain releases (`">=0.2.6"`; no pre-, post-, or dev-release suffix) the running heki must satisfy; an older or newer one stops with an error. See [Requiring a heki version](https://heki.koxudaxi.dev/configuration/#requiring-a-heki-version). |
| `exclude` | the Ruff defaults (`.git`, `.venv`, `build`, `dist`, `node_modules`, …) | Replaces the excluded paths: globs, matched against the project-relative path and each of its components, and covering everything below a matched directory. |
| `extend-exclude` | `[]` | Adds excluded paths. |
| `src` | the detected source roots | Source roots, relative to the project root: the module names of the files below each are relative to it (`src = ["lib"]` names `lib/pkg/net.py` `pkg.net`). See [Module names follow the source roots](https://heki.koxudaxi.dev/configuration/#module-names-follow-the-source-roots). |
| `baseline` | none | Ratchet baseline file, relative to the project root, used when `--baseline` is not given: by `heki check`, `--watch`, and the language server. See [Ratchet baselines](https://heki.koxudaxi.dev/adoption/#ratchet-baselines). |
### The default target version
Without `target-version`, heki reads `requires-python` from the `pyproject.toml` that holds the
configuration, or, for `heki.toml` or a `--config` file that is not a `pyproject.toml`, from the
`pyproject.toml` at the project root. The same applies to the project name, the declared
dependencies, and the workspace tables: where the configuration file sits does not change them.
It takes the oldest supported version that every clause admits:
| `requires-python` | Target |
| ----------------- | ------ |
| `>=3.11` | `py311` |
| `>=3.11, !=3.11.*` | `py312` |
| `>=3.9, <3.11` (only older versions) | `py311` |
| `>=3.16` (only newer versions) | `py315` |
| `<4` (no lower bound, admits 3.12) | `py312` |
| missing, or not a version specifier | `py312` |
### Requiring a heki version
`required-version` makes a heki that does not satisfy the specifier refuse to run, as Ruff's
`required-version` does. heki checks it before any other key, so a configuration that uses keys
a newer release adds fails with this message on an older heki:
```toml
[tool.heki]
required-version = ">=0.2.6"
```
```text
error: pyproject.toml:2:20: this is heki 0.2.4, but the configuration requires `>=0.2.6`
```
An older heki cannot know which release adds a key it has never heard of. Without
`required-version` (and any heki before the release that added it rejects the key as unknown, like any
other), an unknown key is an error that says only what the table accepts. When the key is not close to a
key of its table (a close one is a typo, and the error offers it), the error also says that the
key may belong to a newer heki, names the running version, and points to `required-version` and
the changelog. It cannot say which release adds the key. `heki version --changelog` prints what
the installed release changed, and the changelog on GitHub lists every release.
### Which files are checked
- Without paths, `heki check` checks every `.py` and `.pyi` file under the current directory.
- Discovery skips hidden files and directories, the paths `exclude` and `extend-exclude` match,
and the entries of `.gitignore` (inside a Git repository), `.ignore`, and `.hekiignore` files.
- Directories given are analyzed as given: heki takes the files it finds there as the whole
program, so a chosen set such as `src` without `tests` keeps the claims of the tests out.
- A file given is checked in its project. Whether a report in it holds depends on its callers,
subclasses, and rebindings anywhere in the project, so `heki check app/api.py` analyzes the
project root heki finds for the file (as above, from wherever heki runs), shows and fails on
the reports that touch the file, and fixes only the file, as
[`--touched`](https://heki.koxudaxi.dev/cli-reference/#heki-check) does: `heki check --touched app/api.py`.
Several files make one run over the project of the first. With directories, the directories
are analyzed and the files select what is shown. A file the project leaves out (excluded,
ignored, or not a `.py` or `.pyi` file) is named in a warning. `--update-baseline` and
`--watch` take directories.
- A file outside any project, with no configuration file and no Git working tree above it, is
analyzed alone, whatever its extension.
- A directory below the project root, given or the current directory, is analyzed as given. When
its files import project modules it leaves out, the run misses what they do, and says so in a
note naming them.
## Rule selection: `[tool.heki.lint]`
| Key | Default | Meaning |
| --- | ------- | ------- |
| `select` | the exact rules that are not opt-in, and the contract rules | Rules to enable instead of the defaults. An empty list enables no rule before `extend-select`, as in Ruff. |
| `extend-select` | `[]` | Rules to add. |
| `ignore` | `[]` | Rules to disable. |
| `per-file-ignores` | `{}` | Glob → rules disabled in matching files (project-relative POSIX paths). As in Ruff, `*` also matches `/`: `scripts/*.py` covers `scripts/tools/worker.py` too. |
| `severity` | `"warning"` for the rules that report slower code (`EFF102`, `EFF103`, `EFF105`, `DATA101`, and the `OPT` rules) and for `MUT110`, which reports a bug that is rarely harmful; `"error"` for the others, which report bugs that can be critical (`EFF101`: a blocked event loop holds up every other task) | Rule → `"error"` or `"warning"`. It changes the output and the SARIF level. By default only exact errors make `heki check` fail: a heuristic report counts as a warning, whatever its severity; `fail-on = "warning"` makes warnings and heuristic reports fail it too. |
| `relax-async-in-tests` | `true` | Skip `EFF101`, `EFF105`, and `EFF106` in test code as pytest finds it: `test_*` functions and the functions nested in them, `test_*.py` and `*_test.py` files, and files under `test/` or `tests/`. |
| `heuristic` | `false` | Whether the heuristic rules that are not opt-in run by default and for a prefix or `ALL`, as the exact rules do. `--heuristic` and `--no-heuristic` override it. |
| `fail-on` | `"error"` | The least severity whose reports make `heki check` (and `--watch`) exit with code 1: `"error"`, or `"warning"` to fail on warnings too. A heuristic report counts as a warning, whatever its severity: it can be wrong about the code, so at `"error"` only exact errors fail the run. Warnings and heuristic reports are reported either way, and the language server shows them. `--fail-on` overrides it. |
| `report-unused-suppressions` | `false` | Report the codes of suppression comments that suppressed no report, and the baseline entries that matched none. See [Unused suppressions](https://heki.koxudaxi.dev/configuration/#unused-suppressions). |
| `require-suppression-codes` | `false` | Report the `# heki: ignore` comments that name no rule. See [Suppressions that name no rule](https://heki.koxudaxi.dev/configuration/#suppressions-that-name-no-rule). |
| `unmatched-contract-entries` | a warning, in a run over the whole project | `"warning"`, `"error"`, or `"ignore"`: what `heki check` does with a contract entry that matches nothing in the analyzed files. An error fails the run. See [Entries that match nothing](https://heki.koxudaxi.dev/configuration/#entries-that-match-nothing). |
- A rule is named by its code (`EFF101`), its name (`async-blocking-call`), a code prefix
(`EFF`, `MUT2`), or `ALL`. An unknown rule is a configuration error.
- Every rule is exact or heuristic ([Rule Precision](https://heki.koxudaxi.dev/precision/)). The defaults, a prefix, and
`ALL` enable the exact rules that are not opt-in, and the contract rules; with
`heuristic = true` they also enable the heuristic rules that are not opt-in, as Ruff's
`preview` does. Its code or name enables a
heuristic rule either way.
- An exact rule's report that did not establish every premise of its claim (an `OPT` report
whose rewrite is not proven) is heuristic, and is shown where a heuristic rule would run: with
`heuristic = true`, or when its code or name is selected.
- A run of `full` or `concise` output that leaves heuristic rules off, or heuristic reports out,
says how many.
- A prefix or `ALL` never enables the opt-in rules (`EFF105`, `EFF106`, `EFF107`, `EFF109`,
`EFF110`, `EFF112`, `EFF114`, `EFF115`, `EFF116`, `IMP101`, `IMP102`, `IMP104`, `IMP301`,
`IMP302`, `MUT101`, `MUT103`, `MUT106`, `MUT107`, `MUT108`, `MUT111`, `MUT112`, `MUT113`,
`MUT115`, `MUT120`, `OPT103`, `OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130`): they need
their exact code or name. In `ignore`, a prefix covers every rule it matches.
- `heki check --include-size-dependent` also runs the opt-in rules whose size-dependent rewrites
it applies (`OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130`), as if `--extend-select` named
them; `ignore` still removes them.
- The command line wins: `--select` replaces `select`, `--extend-select` and `--ignore` add to the
configured lists, and `--heuristic` / `--no-heuristic` replace `heuristic`.
```toml
[tool.heki.lint]
heuristic = true # also the heuristic rules that are not opt-in
```
## Contracts
Contracts declare what no type can say. Each kind is an array of tables with its own rule:
| Contract | Declares | Rule | Certainty |
| -------- | -------- | ---- | --------- |
| [`write-owners`](https://heki.koxudaxi.dev/configuration/#write-owners) | who may write an attribute | `MUT201`; `MUT205` with `unresolved = "report"` | heuristic |
| [`read-owners`](https://heki.koxudaxi.dev/configuration/#read-owners) | who may read an attribute | `MUT203`; `MUT206` with `unresolved = "report"` | heuristic |
| [`call-owners`](https://heki.koxudaxi.dev/configuration/#call-owners) | who may call a function or construct a class | `MUT204`; `MUT207` with `unresolved = "report"` | heuristic |
| [`effect-boundaries`](https://heki.koxudaxi.dev/configuration/#effect-boundaries) | what a scope must not reach: I/O, writes, reads, or calls | `EFF201` | heuristic |
| [`readonly-returns`](https://heki.koxudaxi.dev/configuration/#readonly-returns) | results every caller shares | `MUT202` | heuristic |
| [`invalidation`](https://heki.koxudaxi.dev/configuration/#invalidation) | writes that must be announced | `MUT208` | heuristic |
| [`import-boundaries`](https://heki.koxudaxi.dev/configuration/#import-boundaries) | which modules a module may import (experimental) | `IMP201`; `IMP202` with `unresolved = "report"` | heuristic |
- An `*-owners` contract protects its `targets` and lists who may touch them. A
`*-boundaries` contract is drawn around the code it names (`scopes`, `importers`) and lists
what that code must not reach or import.
- These rules report nothing until a contract exists. The results of `functools.lru_cache` /
`functools.cache` functions are checked without one by `MUT114` (`cached-result-mutation`).
- Declaring a contract selects its rule, whatever its certainty.
- Their reports are heuristic, so they count as warnings for
[`fail-on`](https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint): to make a broken contract fail `heki check`, the
pre-commit hook, and CI, set `fail-on = "warning"` next to the contracts (with a
[baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines), only new reports fail).
- Every name in a contract but `import-boundaries`, whose names are
[module patterns](https://heki.koxudaxi.dev/configuration/#import-boundaries), is a dotted pattern. It matches the full name or any dotted suffix
(`DataModel.fields` matches `pkg.model.DataModel.fields`, not `pkg.BigModel.fields`), and it
may be a glob (`*`, `?`, `[...]`, `{a,b}`).
- A glob's `*` spans dots (`pkg.parser.*` covers the functions of every module under
`pkg.parser`), except in the last segment of a target, which names the attribute, function,
method, or class: `pkg.*._*` names the private members of everything in `pkg`, and no function
of a private module whose own name is public; `pkg.api_*` names `pkg.api_commit`, not
`pkg.api_helpers.api_reset`.
- A name with a module part, `module:qualname`, names definitions of the project modules the
part names, never of their submodules. The module part matches the whole module name, exactly
or as a glob (`pkg.*:run`), not a suffix; the qualified name after the colon matches the whole
name inside the module, a `*` spanning dots. `pkg:*` names everything `pkg/__init__.py`
defines (its functions, classes, methods, nested functions, and module body ``), where
`pkg.*` also covers `pkg.sub.user.sub_user`; `pkg.sub:Store.*` names the methods of `Store` in
`pkg.sub`. In a `Class.attr` target the module part belongs to the class
(`pkg.model:DataModel.fields`), and a call target with one is matched whole (`pkg:*` names
every function, method, and class of `pkg`). Such a name never matches an external symbol, and
`unresolved = "report"` counts its last name (`decide` of `pkg:decide`). A module part that
names no project module is no error: the name matches nothing, which `heki check` warns
about ([Entries that match nothing](https://heki.koxudaxi.dev/configuration/#entries-that-match-nothing)).
- A report of a glob target names the member it matched (`reads
`pkg.types.DataType._flag``); one report standing for several members lists the others.
- An access matching several targets of one contract (a target on a class and one on its
subclass, a protocol's member and its implementation's attribute) is one report of the
contract: it names the target configured first among them, and lists the others (`(also
`A.items`)`).
- A `Class.attr` target covers the subclasses of the class too.
- A private name of a class (`__cache`, `__run`: two leading underscores and not two trailing)
is the member Python's name mangling makes of it (`_Parser__cache` in class `Parser`), and a
name may spell it either way: `pkg.Parser.__run` and `pkg.Parser._Parser__run` (or
`pkg.Parser._Parser__*`) name the same method. An access is matched as Python runs it: inside
`Parser`, `self.__run` reaches `_Parser__run`; outside, a receiver typed `Parser`, a
subclass's `self`, or `type[Parser]` reaches it as `_Parser__run`. A subclass's own private
name (`self.__run` in `JsonParser`, the member `_JsonParser__run`) is another member, and
overrides nothing of its base. With `unresolved = "report"`, the last name of such a target
counts in both spellings (`__run`, and `_Parser__run` for a class the target names); a
target without a class (`__run`) names the member of any class (`other.__run()` in class
`Driver` calls `_Driver__run`).
- A contract heki cannot use is a configuration error: a target that is not `Class.attr`, an
invalid glob, a name with more than one colon or an empty module or qualified name, call
targets whose globs are too many to match together (tens of thousands of complex ones), an
argument list heki cannot read, an invalid glob in `allowed-protocols`, an unknown group, a
group in `relative-imports`, or an `ignored-imports` entry without `->` in `import-boundaries`, or
an unknown value of `forbid`,
`fresh-objects`, `unresolved`, `references`, `attribution`, `own-receiver`,
`unlisted-dict-keys`, `type-checking`, or `reach`.
- With `unresolved = "report"`, a contract also reports the accesses it cannot tie to a class,
each under its own rule (`MUT205` writes, `MUT206` reads, `MUT207` calls): an attribute or
method named like a target, accessed on an object of unknown class (an unannotated parameter,
a loop variable, an untyped call result, `Any`, a protocol whose implementations heki cannot
list). A baseline counts them apart from the violations the typed rules prove. An owner
contract with it also judges a function some code hands on as a value (a display, a class
attribute, an argument, a return: `HANDLERS = [helper]`, `REQUIRE = staticmethod(helper)`)
in that function, as if it had no callers: such a function has callers heki does not see, so
its allowed callers do not allow what it does.
- An attribute named through a string (`setattr`, `getattr`, `__dict__`, `vars`) is followed
when the string is a constant: see [Dynamic names](https://heki.koxudaxi.dev/scope/#dynamic-names).
### `write-owners`
```toml
[[tool.heki.write-owners]]
name = "generation-store"
targets = ["pkg.model.DataModel.fields", "DataType.data_types", 'DataModelFieldBase.extras["init"]']
allowed-writers = ["pkg.parser.generation.*", "Store.*"]
exempt-methods = ["__deepcopy__", "copy_deep"]
forbid-cached-property-on = ["DataModel"]
message = "use GenerationStore.set_fields() instead"
fresh-objects = "allow"
unresolved = "report"
```
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name in reports. |
| `targets` | `[]` | `Class.attr` attributes, or `Class.attr["key"]` for one entry of the container an attribute holds. |
| `allowed-writers` | `[]` | Functions allowed to write the targets. |
| `forbidden-writers` | `[]` | When set, only writes by these functions are reported: see [Allowed and forbidden functions](https://heki.koxudaxi.dev/configuration/#allowed-and-forbidden-functions). |
| `exempt-methods` | `[]` | Construction and copy methods allowed to write the targets. A plain name (`__deepcopy__`) matches any method of that name; a name with a dot or a glob (`DataModel.copy_deep`, `create_*`) is a pattern, as in `allowed-writers`. |
| `forbid-cached-property-on` | `[]` | Classes on which defining a `@cached_property` is itself reported. |
| `message` | none | The help of every report of the contract: where to write instead. |
| `fresh-objects` | `"allow"` | `"allow"` or `"report"`: whether a write that constructs the object it writes is reported. |
| `unresolved` | `"ignore"` | `"ignore"` or `"report"`: whether the writes the contract cannot tie to a class are reported under [`MUT205`](https://heki.koxudaxi.dev/rules/unresolved-guarded-write/). |
| `attribution` | `"call-graph"` | `"call-graph"` or `"lexical"`: which function a write is judged in. See [How contracts report](https://heki.koxudaxi.dev/configuration/#how-contracts-report). |
| `own-receiver` | `"report"` | `"report"` or `"allow"`: whether a write through the receiver of the method it is judged in (`self`, `cls`, `super()`) is allowed. See [How contracts report](https://heki.koxudaxi.dev/configuration/#how-contracts-report). |
| `allowed-protocols` | `[]` | Project protocols (class patterns, their subclasses included): a write through a value typed with one that declares the attribute, itself or through its protocol bases, is allowed. See [How contracts report](https://heki.koxudaxi.dev/configuration/#how-contracts-report). |
| `protocol-subclasses` | `true` | `false`: an `allowed-protocols` pattern names the protocols it matches, not their subprotocols (a protocol deriving from an allowed one stays judged). |
| `unlisted-dict-keys` | `"ignore"` | `"ignore"` or `"report"`: whether a `__dict__` key of a target's class that no `write-owners` target names is reported when it is written; with `unresolved = "report"`, also on an object of unknown class (`MUT205`). |
A container entry (`Class.attr["key"]`):
- matches the writes of that constant key (a literal or a string constant), also by a store
operation a call passes the key to (`set_extra(field, "init", v)` writing `field.extras[key]`,
reported at the call), not a write of the whole container or with a computed key;
- is reported once, under the entry, when its container is a target too;
- in an effect boundary, makes a write of the container under a key heki cannot tell a report of
its own ("under a key heki cannot tell"), unless the boundary allows the whole container.
A write into the entries of a target's container (`model.meta["kw"][name] = v`) is a write of
the target. So is a write through a local alias of the container (`kw = model.meta["kw"]`), also
after an augmented assignment that changes the container in place and so keeps it
(`kw |= other`, `items += more`, `-=`, `&=`, `^=` on a set); one on any other value
(`count += 1`) binds a new object.
With `fresh-objects = "allow"`, a write is no violation when it constructs the object it writes:
- the object was allocated in the same call chain: by calling its class, by `object.__new__`
(`object.__new__(Node)`), by a copy, or by a project function returning a new object;
- nothing can hold it yet: no store, `yield`, closure, or call that may keep it ran before the
write.
A shallow copy's containers are the original's: only rebinding its attributes constructs it.
A project function returns a new object at a call when every value it returns is one, or, on
some paths, an element of an optional parameter (an item, `get`, `pop`, `setdefault`, or an
iteration step of it) that the call leaves at a default without elements or passes such a
constant: `None`, a bool, a number, or an empty string or tuple. `copy_tree(node)` of
`def copy_tree(node, replacements=None)` returning `replacements[id(node)]` or a copy gives a new
object; `copy_tree(node, table)` does not, nor does a call where the default is a dict display
shared by every call (`memo={}`). A call of a function every `return` of which returns one of its
parameters (`def with_origin(field, kind): ...; return field`) gives the object it hands that
parameter: a new one stays new, and the input stays the input.
A store a function makes only where tests of its parameters pass (`if register:`,
`if registry is not None:`, also inside `and`, `or`, and `not`) keeps nothing at a call whose
arguments fail them: a constant, the literal default of a parameter the call leaves out, or a test
the caller has already made of the same input. `copy_tree(node, register=False)` of
`def copy_tree(node, *, register=True)` that calls `copied.register()` under `if register:` gives
a new object, and `attach(copied, keep=False)` of a helper storing its parameter under `if keep:`
leaves `copied` new; `copy_tree(node)` does not. A test of the caller's own parameter is decided at
the calls of the caller. A function records at most four sets of at most four tests for each such
store; past them it keeps the object whatever it is passed. A write a helper makes to its own
parameter after such a store still counts the store.
In an effect boundary, a write a reached function makes to the object one of its parameters
holds constructs that object when every call reaching the function hands it a new object that
nothing kept yet, as the same write in the caller would: `set_flag(copy.copy(node))` with
`def set_flag(node): node.flag = True`. A call handing it the scope function's input, or any
other object, is reported, at that call.
With `unlisted-dict-keys = "report"`, `MUT201` also reports a constant key written through the
namespace of an object of a class a target covers (`field.__dict__[KEY] = v`,
`field.__dict__.setdefault("_cache", v)`, `del vars(field)["k"]`) when no target covering that
class names the key, in this contract or in any other `write-owners` contract, so a new cache key
needs a target first. A target names the keys its attribute pattern matches (`Field._*` names
`_cache`), and an entry target names its container. A key another contract names is that
contract's to guard: its writes are judged by that contract's allowance alone. A contract with only
`forbidden-writers` allows no writer, so it names no key. The contract's
allowance applies to an unlisted key as to a target write. A key a loop takes from a tuple,
list, or set of string constants, or from a module's tuple of them, writes each of them, and so
does the key of each pair a generator of them gives `update`. A key computed at run time has no
name to check (`MUT205`, with `unresolved = "report"`), nor has a copy of the keys of an instance's
namespace or of the fields its class declares, whose keys exist already, and neither has a
write on an object heki cannot type, a helper's parameter that no annotation types included:
with `unresolved = "report"` too, `MUT205` reports such a key (below). A key every function may
write is listed by a contract that allows every writer:
```toml
[[tool.heki.write-owners]]
name = "bookkeeping"
targets = ["pkg.model.Field._derived_from", "pkg.model.Field._seen_*"]
allowed-writers = ["*"]
```
With `unresolved = "report"`, `MUT205` reports:
- an attribute named like a target, written on an object of unknown class;
- a computed attribute name (`setattr(obj, name, v)`, `obj.__dict__[name] = v`,
`obj.__dict__.update(...)`, `vars(obj) |= other`) written on a target class, or on an object
of unknown class, where it may be any target;
- with `unlisted-dict-keys = "report"`, a constant `__dict__` key that no target names for some
class the contract's targets cover, written on an object of unknown class, where it may be a
new key of that class. A helper whose callers hand it only objects of classes no target covers
is not reported, and neither is a class's own initialization through a helper it passes `self`
to.
### `read-owners`
```toml
[[tool.heki.read-owners]]
name = "reference-children"
targets = ["pkg.reference.Reference.children"]
allowed-readers = ["*GenerationIndex*", "*GenerationStore*"]
exempt-methods = ["__deepcopy__"]
message = "read children through GenerationIndex instead"
unresolved = "report"
```
The read side of `write-owners`. A read is `ref.children`, a read through a local alias,
`getattr(ref, "children")`, or `ref.__dict__["children"]`, also through a class object, which
reads the class attribute (`Reference.children`, `cls.children`, a value typed
`type[Reference]`).
A read, or a call (`call-owners`, and an effect boundary's `call-targets` and
`allowed-callees`), through a value typed with a project protocol that declares the member is
judged by the protocol, the type the code uses it through: `def f(h: Host): h._m` reads
`Host._m`, not `_m` of the classes implementing `Host`, and a private method of an
implementation called through the protocol keeps what it reads and calls. A write through such
a value still writes the implementations' attribute. `allowed-protocols` allows the reads, calls,
and writes through the protocols it names, also through a class object typed `type[P]` of such a
protocol (see [How contracts report](https://heki.koxudaxi.dev/configuration/#how-contracts-report)).
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name in reports. |
| `targets` | `[]` | `Class.attr` attributes. A container entry (`Class.attr["key"]`) is a write target only, and a configuration error here. An entry can also name attributes of modules outside the project ([below](https://heki.koxudaxi.dev/configuration/#symbols-outside-the-project)). |
| `allowed-readers` | `[]` | Functions allowed to read the targets. |
| `forbidden-readers` | `[]` | When set, only reads by these functions are reported. |
| `exempt-methods` | `[]` | Methods allowed to read the targets, matched as in `write-owners`. |
| `message` | none | The help of every report of the contract. |
| `unresolved` | `"ignore"` | `"ignore"` or `"report"`: whether the reads of a target's attribute name on an object of unknown class are reported under [`MUT206`](https://heki.koxudaxi.dev/rules/unresolved-guarded-read/). A target ending in a glob (`Context._*`) matches only the names a class it names, or a project subclass, has from project code ([below](https://heki.koxudaxi.dev/configuration/#globs-on-objects-of-unknown-class)). |
| `attribution` | `"call-graph"` | `"call-graph"` or `"lexical"`, as in `write-owners`. |
| `own-receiver` | `"report"` | `"report"` or `"allow"`, as in `write-owners`. |
| `allowed-protocols` | `[]` | As in `write-owners`, for a read or a call through the protocol. |
| `protocol-subclasses` | `true` | As in `write-owners`. |
`MUT203` does not see a read through a parameter without a project-class annotation; with
`unresolved = "report"`, `MUT206` reports it unless every caller binds the parameter to an
instance of a project class outside the targets' classes.
### `call-owners`
```toml
[[tool.heki.call-owners]]
name = "reference-mutators"
targets = ["DataType.replace_reference", "pkg.util.reset_cache", "FinalFacts"]
allowed-callers = ["pkg.parser.generation.*"]
exempt-methods = ["__deepcopy__"]
message = "use a GenerationStore operation instead"
unresolved = "report"
```
The call side of `write-owners`.
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name in reports. |
| `targets` | `[]` | Functions, methods, or classes. A `Class.method` target covers the method's overrides in subclasses; a class target means constructing the class or a subclass, also through a `functools.partial` object holding it and through a library method building an instance of its receiver's class (a pydantic model's `model_construct`, `model_validate` of a dict, `model_copy`). A target may end in an argument list (`DataType(is_dict=True)`, below). An entry can also name functions and classes outside the project ([below](https://heki.koxudaxi.dev/configuration/#symbols-outside-the-project)). |
| `subclasses` | `true` | `false`: a class target means constructing exactly the class, not a subclass (an exception class whose subclasses anyone may raise). `Class.method` targets keep covering overrides. |
| `allowed-callers` | `[]` | Functions allowed to call the targets. |
| `forbidden-callers` | `[]` | When set, only calls by these functions are reported. |
| `exempt-methods` | `[]` | Methods allowed to call the targets, matched as in `write-owners`. |
| `message` | none | The help of every report of the contract. |
| `unresolved` | `"ignore"` | `"ignore"` or `"report"`: whether the calls of a method named like a target (its last name) on an object of unknown class are reported under [`MUT207`](https://heki.koxudaxi.dev/rules/unresolved-guarded-call/). A target ending in a glob matches only the names a class it names, or a project subclass, has from project code ([below](https://heki.koxudaxi.dev/configuration/#globs-on-objects-of-unknown-class)). |
| `references` | `"ignore"` | `"ignore"`, `"calls"`, `"calls-and-bases"`, or `"reads"`: whether a reference handing a target on to be called later counts as a call of it (`[decide]`, `return decide`, `partial(decide)`, `field(default_factory=Rule)`, `obj.callback = self.decide`), with `"calls-and-bases"` a class statement naming a class target among its bases too (`class Derived(Base)`), and with `"reads"` every other use of a target's value as well (`Keys.of(...)`, `Code.OK`, `isinstance(x, Keys)`, `case Keys():`, `tuple[Keys, int]`). |
| `attribution` | `"call-graph"` | `"call-graph"` or `"lexical"`, as in `write-owners`. |
| `own-receiver` | `"report"` | `"report"` or `"allow"`, as in `write-owners`. |
| `targets-call-each-other` | `"allow"` | `"allow"` or `"report"`: whether a target may call the other targets of the contract. `"report"` judges each target like the one target of a contract with the same keys, so one contract listing independent targets reports what one contract per target reports for every call whose candidates all belong to one target. A call that may reach several targets (`obj.reset()` on `obj: Base` with `A.reset` and `B.reset` listed) is judged once for each target it may reach, with only that target guarded, and is reported when any of those judgements reports it; no contract of one target judges that call whole. |
| `allowed-protocols` | `[]` | As in `write-owners`, for a read or a call through the protocol. |
| `protocol-subclasses` | `true` | As in `write-owners`. |
- A call is reported only when every function it may call (each candidate in the class
hierarchy) is a target: `text.replace(...)` on a `str` is never a call of
`DataType.replace_reference`.
- Bound-method aliases (`replace = dt.replace_reference`) and `getattr(dt, "replace_reference")`
with a constant name are followed.
- The targets of a contract may call each other: a call of the guarded operation is checked where
it is made, so what the operation does inside is part of it. That suits a contract whose targets
make up one operation. For a contract listing independent targets, set `targets-call-each-other =
"report"`: a target is then allowed to call itself only, and every call of another target of the
contract is judged like a call of the one-target contract (a call of `pkg.core.a` by the target
`pkg.core.c` is reported unless `allowed-callers` names `c`).
- With `references = "calls"`, a target handed on is reported where it is named ("`f` hands on
`pkg.core.decide`"; a name an import or the module body binds, read in the scope binding it, at
the statement handing it on; a name a class body, a function, a lambda, or a comprehension
nested in a function reads from it, a local import included, at the name): passed to a call, stored in an attribute, an item, or a global, returned,
yielded, raised, or held by a display that is. A use that only names it is no reference: an
argument of `isinstance`, `issubclass`, another builtin that only inspects its arguments
(`print`, `getattr`, `type`), `super`, `typing.cast`, `typing.TypeVar`, `typing.NewType`, or
`contextlib.suppress`; an `except` clause, a class's bases and keywords, a default or an
annotation of a function; a subscript (`Optional[Rule]`), a comparison, a receiver
(`Rule.of(...)`), and a module binding another name to it (an import, `run = core.decide`). A
callable a builtin calls once per item (`sorted(xs, key=decide)`) is a call already.
- A target ending in an argument list, `name(parameter=value, ...)`, names the calls of `name`
that pass each value: `"DataType(is_dict=True)"`, `'container_flags(kind="dict")'`. A value is
`True`, `False`, `None`, an integer, or a string in single or double quotes (no escapes). A call
passes it when heki establishes that the argument bound to the parameter is that constant (a
literal, a string constant bound once, such as a module's `Final` name, or a module's number or
boolean bound once, as `EFF101` evaluates them: `LIMIT = 0`, also imported (by the module or by
a function) or read as an attribute of its module (`settings.LIMIT`), unless a module rebinds
it; an imported name the importing module binds again in a function declaring it
`global`, in another module-level store, or with `del`, or that a star import may rebind, is no
constant there): passed by keyword (also to a class without a project `__init__`, a dataclass or a
pydantic model), by position where every function the call may run binds that position to the
parameter, or left out where every such function's default is the value and only `True`,
`False`, `None`, `0`, or `""` (heki keeps defaults by class and truthiness). A keyword binds as
Python binds it: never a positional-only parameter (with `def f(kind=False, /, **kwargs)`,
`f(kind=True)` leaves `kind` false), and a keyword naming no parameter passes its value under its
name into `**kwargs`; the receiver of a method call is its first position. A `**` operand that is
a mapping the function builds, which nothing changes (a name holding it is only unpacked with
`**`, merged into another mapping, bound to another name, tested, or returned), passes its
entries as keywords: a dict display with string constant keys (literals, or string constants as
above), `DataType(**{"is_dict": True})`, `flags = {"is_dict": True}; DataType(**flags)`; a merge
of mappings (`{**a, **b}`, `dict(a, is_dict=True)`, `a | b` of two mappings the function builds),
which passes the last entry of each key, a mapping heki does not build (a parameter) replacing
every key before it; and a mapping built on several paths (`flags = a if c else b`), which passes
a key where every path passes the same constant for it. Calling a `functools.partial` object the
function makes (through copies) calls what it holds, with the positions it holds first and its
keywords, which a keyword the call writes replaces: after `make = partial(DataType,
is_dict=True)`, `make()` constructs `DataType(is_dict=True)`, reported at `make()`, where the
class is constructed (a call unpacking a mapping with `**` over keywords the object holds is not
followed). A pydantic model's `model_construct` passes its keywords to the fields,
`model_validate` the entries of the dict it is passed, and `model_copy` those of `update`. A
call that raises `TypeError` instead of running the function passes nothing: two keywords of one
name (written and in such a display, or in two displays), a keyword binding a parameter a
position or the receiver binds too, a keyword naming no parameter of a function without
`**kwargs`, a position (the receiver included) past the parameters of a function without
`*args`, or a parameter without a default left unbound where no `*` unpacking or `**` unpacking
of another mapping may bind it. Any other argument (a variable, a call, `*` unpacking, `**`
unpacking of another mapping) is not established, and the call is not reported. A reference passes no arguments, so it never matches. A target with an argument list
names no symbol outside the project; `unresolved = "report"` matches its last name before the
list, whatever the arguments of a call on an object of unknown class.
- With `references = "calls-and-bases"`, a class statement passing a class target as a base is
reported too ("`` subclasses `pkg.core.Base`"), at the base, or at the class statement
for a name an import or the module body binds: the class it makes holds the base, and
constructing it runs the base's initialization unless it overrides it. A base is the value the
statement passes, typed where the statement runs as any value is (a parameter, a local, or a
class-body name of the imported class's name is another value), and matched as a construction
is (with `subclasses = false`, the class itself only); a keyword (`metaclass=Base`) is no base.
- With `references = "reads"`, everything `"calls-and-bases"` counts is reported as before, and
every other use of a target's value is reported too ("`f` reads `pkg.core.Keys`"), where it is
named as a hand-on is: the object of an attribute read, store, or deletion and a method's
receiver (`Keys.of(names)`, `Keys.__annotations__`, `Code.OK`), an argument of a call that only
names it (`isinstance(value, Keys)`, `cast(Keys, x)`, `TypeVar("T", bound=Keys)`), a subscript
or its index (`tuple[Keys, int]`, `Optional[Keys]`), an operand (`f is decide`, `Keys | None`),
a tested condition (`if decide:`), an iterated, awaited, formatted, or `with` value, a dict
display's key, the class of a class pattern (`case Keys():`), the types of an `except` clause
an exception may reach, a decorator, a default of a function or lambda, a keyword of a class
statement, and the cause of `raise ... from`, also through copies and the displays holding it
(`isinstance(value, (Keys, Code))`, a test of a module-level display holding it). No read: a
call (a call of its own), an annotation, evaluated or not (`list[Keys]`, `Keys | None`), the
values Python evaluates only when asked (a `type` statement's value, the bounds and defaults of
type parameters), an import, a name bound to the target by itself (`Alias = Keys`, a local, a
`nonlocal` cell), whose own uses count, and a value nothing uses (`Keys` as an expression
statement). A load handing a target on is reported as a hand-on only. A read is matched as a
construction is, so a subclass counts unless `subclasses = false`; an instance of the class is
no read of it.
### Symbols outside the project
The `targets` of `call-owners` and `read-owners` can also name functions, classes, and module
attributes outside the project, as an effect boundary's `call-targets` and `read-targets` do, so
one contract guards the private members of both:
```toml
[[tool.heki.call-owners]]
name = "no-private-calls"
targets = ["pkg.*._*", "._*"]
forbidden-callers = ["pkg.parser.*"]
[[tool.heki.read-owners]]
name = "no-private-reads"
targets = ["sys._getframe"]
forbidden-readers = ["pkg.parser.*"]
```
- A dotted name starting with the top-level module names that symbol: `sys._getframe` matches a
call of `sys._getframe`, also through `from sys import _getframe`, an alias, or a project
module re-exporting it (an access is judged at the symbol heki resolves it to). A glob in the
last name names the members it matches (`sys._*`). A dotted suffix (`_getframe`), a leading
glob (`*._getframe`), a module part, or an argument list names project code only.
- `.` names the members of every module and class outside the project whose last
name `` matches: `._*` the private ones. A glob there leaves out the names that
are public API although they start with an underscore: dunder (`__name__`) and sunder
(`_missing_`) names, and `_asdict`, `_field_defaults`, `_fields`, `_make`, and `_replace` of
`collections.namedtuple`, the names ruff's `flake8-self` does not report either. A name written
out (`._replace`) matches as written. `` takes one name after it; any other
spelling is a configuration error.
- A `call-owners` target counts the calls of the symbol, a `read-owners` target every other load
of it: `return sys._getframe`, `getframe = sys._getframe`, and an import binding it (`from sys
import _getframe`, at the import, in the function or the module body running it). A name
loaded only to be called there (`_getframe(1)`) is a call, not a read, as `sys._getframe(1)` is.
A reference handing an outside symbol on is no call of it, whatever `references` says.
- Only a call or a read heki resolves counts: a name of unknown origin, or an attribute read by
name (`getattr(sys, name)`), is not reported. With `unresolved = "report"`, an ``
entry matches nothing on an object of unknown class; a written last name (`sys._getframe`)
matches its name there, as any target's last name does.
- The rest of the contract applies as for project targets: the allowed and forbidden functions,
the exempt methods, `attribution`, and the reports of private helpers at their callers. A
class's own initialization and `own-receiver` allow none of these accesses: an outside symbol
is no member of the class making them.
### Globs on objects of unknown class
With `unresolved = "report"`, a `read-owners` or `call-owners` target names the reads or calls of
its last name on objects of unknown class (`MUT206`, `MUT207`). A last name that is a glob
(`Context._*`) matches there only the names a class the target names, or a project subclass of
one, has from project code: the names the class or a project base declares (in its body, set on
its instances by its methods or its module, or stored on the class object), and the names the
code writes on objects typed with one of them or on objects of unknown class. A name only a base
outside the project gives the class is that base's API, which any object may have: with
`targets = ["Context._*"]` and `class Context(NamedTuple)`, an untyped `ctx._replace(...)` is not
reported, and an untyped `ctx._secret()` is when `Context` defines `_secret`.
- A class whose module stores attributes heki cannot name (`setattr(self, name, v)`), or on
whose instances the code writes names computed at run time, may have any name.
- A glob naming no holder (`_*` among the `call-owners` targets) matches the names of every
project class; one naming only modules (`pkg.util.*`) or symbols outside the project matches
none: no object of unknown class has them as members.
- A written-out last name (`Context._replace`) matches by name, and so do the writes `MUT205`
counts: a write may add the member.
### Allowed and forbidden functions
`allowed-writers`, `allowed-readers`, and `allowed-callers` name the functions a contract
allows. `forbidden-writers`, `forbidden-readers`, and `forbidden-callers` name where it applies
instead, so a layer rule ("the parser must not read `Reference.children`") needs no list of every
other layer:
```toml
[[tool.heki.read-owners]]
name = "parser-reads"
targets = ["Reference.children"]
forbidden-readers = ["pkg.parser.*"]
allowed-readers = ["pkg.parser.index.*"]
```
| `allowed-*` | `forbidden-*` | Reported |
| ----------- | ------------- | -------- |
| unset | unset | every access |
| set | unset | accesses outside the allowed functions |
| unset | set | accesses by the forbidden functions |
| set | set | accesses by the forbidden functions, except the allowed ones |
- An access counts as one by a forbidden function when the function that is reported, a private
helper it hands the access through, or the function making the access is forbidden (with
`attribution = "lexical"`, the function holding the access).
- `allowed-*` and `exempt-methods` win wherever they apply on that path, as does the rule for
functions that [only run inside allowed functions](https://heki.koxudaxi.dev/configuration/#how-contracts-report).
### `effect-boundaries`
```toml
[[tool.heki.effect-boundaries]]
name = "pure-render"
scopes = ["*.render", "*.render_module_code", "pkg.domain.*"]
forbid = ["writes-targets", "blocking"]
write-targets = ["DataModel.*", "DataType.*"]
allowed-callees = ["pkg.logging.*"]
message = "render entry points must not mutate model state"
[[tool.heki.effect-boundaries]]
name = "decisions-read-final-facts"
scopes = ["pkg.model._decisions.*"]
forbid = ["reads-targets", "calls"]
read-targets = ["DataType.is_optional", "DataModel._additional_imports"]
call-targets = ["GenerationStore.*"]
[[tool.heki.effect-boundaries]]
name = "pass-sort-base-classes"
scopes = ["pkg.parser.passes.sort_base_classes"]
allow-writes = ["DataModel.base_classes"]
write-universe = ["DataModel.*", "DataModelFieldBase.*", "DataType.*"]
[[tool.heki.effect-boundaries]]
name = "portable-generation"
scopes = ["pkg.generate.*"]
forbid = ["reads-environment"]
import-probes = "report"
```
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The boundary's name in reports. |
| `scopes` | `[]` | Modules, classes, or functions whose functions must stay inside the boundary; nested functions are included. A module body is included only where a pattern names `` (`pkg.gen:`, below). |
| `forbid` | `[]` | What the scope functions must not reach (tokens below). |
| `write-targets` | `[]` | `Class.attr` targets of `writes-targets`, required with it. `Class.attr["key"]` names one entry, as in `write-owners`. |
| `read-targets` | `[]` | `Class.attr` targets of `reads-targets`, required with it: reads as `read-owners` sees them, also inside property getters. A container entry is a configuration error. An entry can also name an attribute of a module outside the project by its full name (`sys.platform`, `os.environ`, below). |
| `call-targets` | `[]` | Functions, methods, or classes of `calls`, required with it, matched as the `targets` of `call-owners` (also with an argument list). An entry can also name a function or class outside the project by its full name (`os.getenv`, `platform.*`, below). |
| `write-universe` | `[]` | `Class.attr` entries: a reached write of one that `allow-writes` does not name is reported, once per written `Class.attr`. |
| `allow-writes` | `[]` | `Class.attr` writes the boundary allows, exempt from `write-targets` too. Needs `write-universe`. |
| `allowed-callees` | `[]` | Functions, classes, modules, or ecosystem symbols whose effects are allowed: paths through them are not followed, and calls of them are no `calls` violation. |
| `fresh-objects` | `"allow"` | `"allow"` or `"report"`: whether a write that constructs the object it writes (as in `write-owners`) counts as a write of the boundary. |
| `references` | `"ignore"` | `"ignore"`, `"calls"`, `"calls-and-bases"`, or `"reads"`, as for `call-owners`: whether a reference handing a `call-targets` entry on (and a class statement naming one among its bases, and any other use of its value) counts for `calls`. |
| `import-probes` | `"allow"` | `"allow"` or `"report"`: whether `reads-environment` also forbids an import probe, an `import` inside a `try` with an `except` clause naming `ImportError` or `ModuleNotFoundError`. `"report"` without `reads-environment` is a configuration error. |
| `unresolved` | `"ignore"` | `"ignore"` or `"report"`: whether the boundary also reports, under `EFF201`, what it cannot judge in its scopes' reach: a call heki resolves to no function, a function it does not model (`eval`, a body too large) or whose body only a stub declares, and a write of an attribute `write-targets` or `write-universe` names on an object of unknown class or under a name computed at run time. Each kind is one report per scope function, at the first one with its chain. |
| `message` | none | The help of every report of the boundary. |
| `forbid` token | Forbids |
| -------------- | ------- |
| `blocking-net`, `blocking-db`, `blocking-fs`, `blocking-subprocess`, `blocking-sync`, `sleep` | that blocking effect |
| `blocking` | all six blocking effects |
| `mutates-params` | changing a parameter in place (for a method, `self` is a parameter) |
| `writes-targets` | writing a `write-targets` attribute |
| `reads-targets` | reading a `read-targets` attribute |
| `calls` | calling a `call-targets` function or class |
| `reads-environment` | reading the environment the program runs in: calling or reading what the ecosystem catalog tags `environment` (below), and import probes with `import-probes = "report"` |
Outside the project, `call-targets` and `read-targets` entries name symbols by their full dotted
name, starting with the top-level module: `os.getenv` matches a call of `os.getenv` (also
`from os import getenv`, `import os as o`), `platform.*` every function of `platform`, and
`sys.platform` a read of `sys.platform` (also `from sys import platform`, or `import sys as s`
and `s.platform`). A dotted suffix (`getenv`), a leading glob (`*.getenv`), or a module part (`os:getenv`) never
names a symbol outside the project, so an entry for project functions keeps its meaning.
`._*` names the private members of every module and class outside the project, as for
the [owner contracts](https://heki.koxudaxi.dev/configuration/#symbols-outside-the-project), whose rules for calls and reads these
entries follow. Only a call or a read
heki resolves counts: an attribute read by name (`getattr(sys, name)`) or on an object of unknown
origin is not reported.
`reads-environment` needs no targets. The ecosystem catalog tags these calls: `os.getenv`,
`os.getenvb`, the functions of `platform` that describe the machine or the interpreter
(`platform.system`, `platform.machine`, `platform.python_version`, ...),
`importlib.util.find_spec`, `importlib.import_module`, `importlib.metadata.version`,
`importlib.metadata.distribution`, `shutil.which`, and `sysconfig.get_config_var`; and these
reads: `os.environ`, `os.environb`, `os.name`, `sys.platform`, `sys.version`,
`sys.version_info`, `sys.hexversion`, `sys.implementation`, and `sys.flags`. An entry set
`excluded = true` (`[[tool.heki.ecosystem]]`, below) is never reported. A call on
`os.environ` (`os.environ.get("X")`) is a read of `os.environ`. One report per scope function
names the first read it reaches and counts every one.
`importlib.import_module(name, package)` and `importlib.util.find_spec(name, package)` read the
environment unless the module they import is established to be the project's own:
- every text `name` may hold names a module of the project (`"pkg.config"`, a module constant,
either of two such texts) that the import finds in the project, or starts with a package of
the project and a dot (`f"pkg.parser.{name}"`, `"pkg.parser." + name`, `"pkg.%s" % name`)
under which it finds only modules of the project (below);
- a relative name (`".config"`, `f"..parser.{name}"`) is anchored at `package`: a text the code
fixes, or the module's own `__package__` or `__name__`;
- the call is not inside a `try` with an `except` clause naming `ImportError` or
`ModuleNotFoundError`: the code expects the import to fail.
Python finds the modules under a package on its `__path__`, the package's own directory unless
code changes it. heki follows what the modules of the project do to the `__path__` of a package,
its own in its `__init__.py` or another's through an import (`plugins.__path__`, `from plugins
import __path__`):
- adding directories after the package's own (`__path__.append(d)`, `__path__.extend(ds)`,
`__path__ += ds`, `__path__ = __path__ + ds`, `__path__ = pkgutil.extend_path(__path__,
__name__)`, also on `__import__("pkgutil")`, and `pkg_resources.declare_namespace`) leaves the
package's own modules found first, but any other name under the package may be an installed
module;
- any other change (`__path__ = [d]`, `__path__.insert(0, d)`, a slice store, `del __path__`), or
a use heki does not follow (the list handed to a function other than a builtin that only reads
it and `pkgutil.iter_modules`, `walk_packages`, or `extend_path`, returned, or stored
elsewhere), may take any name under the package elsewhere, its own modules included. So may a
package whose `__init__.py` heki cannot read.
Reading the path (iterating it, `__path__[0]`, `len(__path__)`, `pkgutil.iter_modules(__path__)`)
changes nothing. A module is found in the project when each package along its name leads the
import there first: heki takes the project's top-level packages to be found in the project, a
regular package of the project is found before the directories added after its parent's own,
and a directory without `__init__.py` is a namespace package with a portion in each directory of
its parent's path, in that order. A name under a package holds only modules of the project when
the packages along it lead to the project's directories alone and no package under it changes
its path: `f"pkg.{name}"` reads the environment once a package anywhere under `pkg` changes its
`__path__`, while a change in another package does not affect it.
A name heki cannot tell (a parameter, `"pkg" + name`, a namespace package without
`__init__.py`) stays a read of the environment, and so does an import of a module the project
does not have. A `call-targets` entry naming `importlib.import_module` matches every call of it.
- Each scope function is checked through any number of calls.
- A module body, what runs when the module is imported, is checked only where a scope names
`` itself: `pkg.gen:` (the body of `pkg.gen`), `pkg.*:` (of every
module under `pkg`), `pkg.gen.`, or `` (of every module). `pkg.*` and
`pkg.gen:*` keep naming the functions only. The body is checked as a scope function is (its
module-level reads, calls, import probes, and writes), and the bodies of its classes, which
run with it, count for what they take from outside the project (environment reads, import
probes, and the external `call-targets` and `read-targets`), not for their other effects.
Reports name it ``.
- A violation inside another scope function is reported there only, once.
- One report per scope function and forbidden kind (or target) stands for every distinct site of
it that the function reaches.
### `readonly-returns`
```toml
[[tool.heki.readonly-returns]]
name = "schema-graph"
producers = ["pkg.parser.SchemaGraphBuilder.schema"]
deep = true
```
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name. |
| `producers` | `[]` | Functions, methods, external symbols, or attributes (`Class.attr`) whose result every caller shares. |
| `deep` | `false` | Protect the values below the result too: its attributes, items, and elements. |
- Functions decorated with `@lru_cache` / `@cache` are protected without configuration, also
through an import alias, but not a `cache` decorator the module defines itself.
- Every function that returns a protected value, or a part of it, on some path is protected too:
wrappers and property getters need no entry of their own.
### `invalidation`
```toml
[[tool.heki.invalidation]]
name = "graph-index"
targets = ["DataType.data_types", "DataModel.fields"]
invalidators = ["GenerationStore.note_changed_models", "GenerationStore.refresh_now"]
exempt-writers = ["pkg.parser.generation.*"]
message = "tell the store which models changed"
```
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name in reports. |
| `targets` | `[]` | `Class.attr` attributes whose writes must be announced. |
| `invalidators` | `[]` | Functions or methods whose call announces the change. |
| `exempt-writers` | `[]` | Functions whose writes need no announcement of their own: the owner's operations, which announce or batch the change themselves, and construction methods. |
| `message` | none | The help of every report of the contract. |
An invalidator call counts when it runs on every path from the write to the function's normal
return:
- directly, or in each branch;
- behind a boolean flag the path sets after the write;
- through a helper that calls one on every path of its own.
What needs no announcement:
- a path that ends by raising: only normal returns count;
- writes to objects that did not exist before the call: an initializer's own `self` (not the
objects reached through its attributes), and objects the function constructs or copies;
- writes to objects the function gets from a call;
- a function whose every caller announces the change after calling it.
A write is followed through local aliases (also in the scopes nested in the function),
container methods, `setattr` / `__dict__`, and helpers. A helper changing an argument it does
not type writes the field or instance its caller binds to it. At most 64 `invalidation`
contracts can be declared.
### `import-boundaries`
```toml
[[tool.heki.import-boundaries]]
name = "facts-leaf"
importers = ["pkg.facts"]
allowed-imports = ["", "pkg._records"]
[[tool.heki.import-boundaries]]
name = "shared-model-backends"
importers = ["pkg.model.shared"]
forbidden-imports = ["pkg.model.backend", "pkg.model.backend.*"]
[[tool.heki.import-boundaries]]
name = "no-root-import"
importers = ["pkg.*"]
forbidden-imports = ["pkg"]
```
Which modules the modules of `importers` may import, checked by
[`IMP201`](https://heki.koxudaxi.dev/rules/import-boundary-violation/). Its names are module patterns: a whole module name
or a glob whose `*` spans dots, never a suffix (`pkg.*` names `pkg.facts` and
`pkg.model.shared`, not `pkg`), or one of the groups `` (the standard library),
`` (the project's modules), and `` (every other module).
| Key | Default | Meaning |
| --- | ------- | ------- |
| `name` | `""` | The contract's name in reports. |
| `importers` | every module | The modules judged. |
| `exempt-importers` | `[]` | Modules of `importers` that are not judged. |
| `allowed-imports` | `[]` | The modules the importers may import: every other import is reported, but those of `relative-imports`. `"pkg.db:Session"` allows one name of a module: only `from pkg.db import Session` imports it (a glob may stand in either part), and another name of `pkg.db` is still reported. |
| `forbidden-imports` | `[]` | When set, only imports of these modules are reported, less the allowed ones, as in [Allowed and forbidden functions](https://heki.koxudaxi.dev/configuration/#allowed-and-forbidden-functions). A contract setting none of `allowed-imports`, `forbidden-imports`, and `relative-imports` allows no imports. |
| `relative-imports` | `[]` | The modules the importers may import only through a relative import ([Relative imports only](https://heki.koxudaxi.dev/configuration/#relative-imports-only)). |
| `ignored-imports` | `[]` | `"importer -> imported"` pairs of module patterns whose imports the contract accepts (`"pkg.cli -> pkg.db"`; `"pkg.cli -> pkg.db:Session"` accepts one name of the module, as in `allowed-imports`). With `reach`, an import accepted or allowed by a name is not followed. |
| `type-checking` | `"ignore"` | `"ignore"` or `"report"`: whether the imports under `if TYPE_CHECKING:`, which never run, count. |
| `reach` | `"statement"` | `"statement"`: each import of an importer is judged. `"import-time"`: every module loading an importer loads while it loads. `"all"`: every module a chain of imports that run leads to. |
| `unresolved` | `"ignore"` | `"ignore"` or `"report"`: whether the imports whose module heki cannot name are reported under [`IMP202`](https://heki.koxudaxi.dev/rules/unresolved-guarded-import/). |
| `message` | none | The help of every report of the contract. |
- An import counts wherever it runs: in the module body, a class body, a function, or lazily,
with or without an `ImportError` handler around it. `importlib.import_module` and
`__import__` with a constant name count as imports of that module.
- `import a.b.c` imports `a.b.c`, not `a` or `a.b`, which it loads first. `from a.b import c`
imports the submodule `a.b.c` when the package has one and binds no `c` before importing it,
and `a.b` otherwise. An import of a module the project lacks below one of its packages fails,
and is no import; `from a.b import c` of a name `a.b` binds nowhere still imports `a.b`, and
may import a module `a.b.c` outside the project's files (a compiled extension module). When
the package binds `c` to an object of its submodule after importing it (`from .c import c`),
`from a.b import c` imports `a.b`, and also `a.b.c` while the package has not run that binding
yet.
- One report per import and module. A report's target, which a
[baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines) counts it by, is the module imported.
- With `reach`, each module reached is reported once per importer, at the import of the importer
that starts a shortest chain to it, with the other steps as related locations. A step through
a parent package counts: loading `pkg.models.base` runs `pkg/models/__init__.py` first. The
packages holding the importer load before it and are never reached. The walks of one contract
share a budget proportional to the import graph, in the order of the modules; past it, the
importers left get no report.
- Definitions are not import targets: who may use a class or a function is a
[`call-owners`](https://heki.koxudaxi.dev/configuration/#call-owners) or [`read-owners`](https://heki.koxudaxi.dev/configuration/#read-owners) contract.
Outside a package, only its public entry: every module but the package's own may import
`app.billing`, and none of the modules under it.
```toml
[[tool.heki.import-boundaries]]
name = "billing-entry"
exempt-importers = ["app.billing", "app.billing.*"]
forbidden-imports = ["app.billing.*"]
message = "import `app.billing` and use what it exports"
```
`from app.billing import Invoice` imports the package, while `from app.billing import invoice`,
`import app.billing.invoice`, and `from app.billing.invoice import Invoice` import the
submodule.
A start-up contract: loading `pkg.cli` must not load `torch`, however many modules lie between
them.
```toml
[[tool.heki.import-boundaries]]
name = "startup"
importers = ["pkg.cli"]
forbidden-imports = ["torch", "torch.*"]
reach = "import-time"
```
#### Relative imports only
A package copied into other packages under another name works only while its modules import
each other relatively: `from pkg._runtime import b` names a package the copy does not have.
```toml
[[tool.heki.import-boundaries]]
name = "runtime-leaf"
importers = ["pkg._runtime", "pkg._runtime.*"]
allowed-imports = [""]
relative-imports = ["pkg._runtime", "pkg._runtime.*"]
```
```python
# pkg/_runtime/a.py
from . import b # allowed
from pkg._runtime import c # IMP201: allowed only through a relative import
```
- An import names a module relatively when it gives the module's place from the importer:
`from . import b`, `from .b import f`, `from .. import c`, and
`importlib.import_module(".b", __package__)` (or `__name__`). By its full name are
`import pkg._runtime.b`, `from pkg._runtime import b`,
`importlib.import_module("pkg._runtime.b")`, `__import__("pkg._runtime.b")`, and a relative
name anchored at a package the code spells, `importlib.import_module(".b", "pkg._runtime")`.
`__import__` with a `level` other than `0` names a module heki cannot tell, which
[`IMP202`](https://heki.koxudaxi.dev/rules/unresolved-guarded-import/) reports with `unresolved = "report"`.
`heki inspect --imports` shows how each import names its modules (`spelling`).
- A module the key matches needs no other entry. Imported relatively, it is allowed, also when
`forbidden-imports` names it; imported by its full name, it is reported, also when
`allowed-imports` names it. An `ignored-imports` pair accepts the import either way. A by-name
import given several names judges each module by the names that give it: one a relative name
and a full name both give counts as named by its full name.
- The key takes module names and globs, not groups: a relative import reaches only the modules of
the importer's own top-level package. An importer outside the package of a module the key
matches cannot name it relatively, so each of its imports of that module is reported.
- The imports judged are the ones the contract counts, as for the other keys: wherever they run,
and under `TYPE_CHECKING` only with `type-checking = "report"`. With `reach`, how an import
names its module is judged only at the importer's own imports (with `"import-time"`, those that
run while it loads): how the modules on a chain import each other is theirs, and a module of the
key that a chain reaches is allowed.
- A report's target is the module imported, as for the other reports of the contract.
### How contracts report
These hold for `write-owners`, `read-owners`, and `call-owners`, and the reporting at callers
holds for `invalidation` too:
- **A class's own initialization is allowed.** An initializer (`__init__`, `__post_init__`,
`__new__`, `model_post_init`, `__setstate__`) of a target class or a subclass may access its own
`self`: directly, through `super().__init__()`, or through helpers it passes `self` to.
- **A nested scope uses the parameters of the functions enclosing it.** A comprehension,
generator expression, lambda, or nested `def` reading a parameter of an enclosing function
(`[self._fmt(x) for x in xs]`) reaches that parameter's object, as a helper the function hands
it does: a call of the scope by that function, or by another scope nested in it, hands the
object over. So a comprehension in `__init__` writing `self.imports` is part of the class's own
initialization. The variable is another object when the function or a nested scope rebinds it
(`self = other`, `nonlocal self`). A closure called away from the function (stored, then
called later elsewhere) still reads the same object, but heki does not tie it to the
parameter: no call of the function hands it over.
- **A function that only runs inside allowed functions is allowed.** Every path of project
callers above it starts in an allowed function, an exempt method, or such an initialization.
- **A private helper reports at its callers.** An access in a private helper (`_name`) with
project callers is reported at the call sites of its first non-private callers. A private
function called only by its own recursion reports its accesses itself.
- **`attribution = "lexical"` judges the code where it is written.** The two rules above do not
apply: an access is judged in the function whose code holds it, whoever calls that function.
A lambda, comprehension, or generator expression is part of the function it is written in, a
class body's code (a class attribute's value, a decorator, a default argument) part of the
function running the class statement (`` for a class at module level), and a nested
`def` a function of its own; the parameters of the function a lambda, comprehension, or generator
expression reads are the function's, wherever it runs. For `write-owners`, a call handing a
typed object to a helper that changes it without knowing its class is the caller's write.
With `unresolved = "report"`, the callers binding a parameter only tell its object's class,
allowed callers included. A class's own initialization stays allowed, a helper it passes
`self` to included when every path of project callers above the helper starts in such an
initialization; so do `exempt-methods`, `fresh-objects`, and the targets of a call contract
calling each other. Effect boundaries have no such key: they judge what their scope functions
reach through any number of calls.
- **`own-receiver = "allow"` allows the accesses through a method's own receiver.** An access is
allowed when the function it is judged in (the function reported, or with `attribution =
"lexical"` the function holding the access) is a method that is no static method, and the
object the member is looked up on may be its first parameter: `self._cache[k] = v`,
`self._seen`, `cls._kind()`, `super()._label()`, `self._norm(x)` of a static method,
`Resolver._label(self)`. A member the class inherits counts like its own. Another parameter, an
attribute of the receiver, a static method called through its class, and the parameter of a
static method or of a function stay reported. By the call graph, a private helper the method
hands its `self` (`_count(self)`) is judged at the method, and is allowed with it, and so are
a comprehension, generator expression, lambda, or private nested `def` the method runs that
uses its `self`; a public nested `def` reports itself, as a public helper does. With
`attribution = "lexical"`, a lambda, comprehension, or generator expression using the method's
`self` is allowed wherever it runs, and a nested `def` is judged by itself, as any helper is.
- **`allowed-protocols` allows the accesses through the protocols it names.** A read, call, or
write through a value typed with a project protocol a pattern names (or a subprotocol of one)
that declares the member, itself or through its protocol bases, is allowed wherever it is
judged, and so is a reference that `references` counts (`return h._helper`). So is one through
a class object typed `type[P]` of such a protocol (a parameter, a local, or an attribute
annotated so: `cls._items_constraints(obj)` with `cls: type[KeywordsHost]`), and one through a
protocol whose implementations heki cannot list, though heki cannot tie either to a class
(`MUT205`, `MUT206`, `MUT207`): `allowed-protocols = ["*Host"]` allows `parser._flag` with `parser: RenderHost` and
`class RenderHost(RuntimeFlags, Protocol)` when `RuntimeFlags` declares `_flag`, while the same
read through `flags: RuntimeFlags` stays reported. With `protocol-subclasses = false`, a
pattern names the protocols it matches only, not their subprotocols: with
`class RuntimeExpressionFlags(GraphBuilderHost, Protocol)`, `allowed-protocols = ["*Host"]`
allows the accesses through `GraphBuilderHost`, and those through `RuntimeExpressionFlags`
stay judged, also of the members it inherits from `GraphBuilderHost`. A write through the
protocol is allowed for the protocol's member and for each implementation's attribute alike.
Accesses through a
protocol that does not declare the member, through an implementation's class, through a value
of unknown class that no annotation types with such a protocol (`unresolved = "report"`), and a
protocol-typed value handed to a helper that changes it without typing its parameter stay
reported. By the call graph, a private method of an implementation that a call
through the protocol runs still hands its writes of its own `self` to the caller.
- **The help names the allowed code that does it today.** After the contract's `message`, the
help of a report names up to three public functions and methods whose own body does what the
report shows from a place the contract allows (an `allowed-*` pattern names them, or the
`forbidden-*` patterns leave them out; for `invalidation`, the functions announcing every
write of the target on every path and the `exempt-writers`), by fully qualified name:
``add entries through `Store`; allowed writers of `Registry.entries`: `pkg.store.Store.add` ``.
Private functions (`_name`), special methods (`__init__`), and the exempt methods are not named.
JSON output gives them with their files as `allowed_examples` (`fqn`, `path`).
### Entries that match nothing
A contract entry that names nothing guards nothing: renaming or removing what it named leaves the
contract silent. `heki check` warns about each such entry, once per kind, key, and text, naming
the contracts that hold it and the existing names one part away (the same holder and a like
last part, or the same last part and a like holder), and
[`heki recommend`](https://heki.koxudaxi.dev/recommend/) lists them:
```console
$ heki check
warning: `targets` entry `pkg.model.Field._gone_cache` of write-owners `field-caches` names no attribute, method, or `__dict__` key of `pkg.model.Field` in the analyzed files; `pkg.model.Field._type_cache` exists
```
- Judged, in the contracts whose rules run: the targets, `allowed-*`, `forbidden-*`,
`exempt-methods`, `allowed-protocols`, and `forbid-cached-property-on` of `write-owners`,
`read-owners`, and `call-owners`; the `scopes`, `write-targets`, `write-universe`, and
`allow-writes` of `effect-boundaries`; and the `targets`, `invalidators`, and
`exempt-writers` of `invalidation`. The `read-targets`, `call-targets`, and
`allowed-callees` of an effect boundary and the `producers` of `readonly-returns` may name
symbols outside the project, and are not judged.
- A `call-owners` or `read-owners` target whose first name is no module of the project may name
code outside it. It is matched when the analyzed files call or read a symbol outside the
project it names, and it is not judged when it is an `` entry or its first name is a
module outside the project (one of the standard library, or one a module of the analyzed files
imports at module level): it is a rule about any use of that code, now or later, and heki
cannot list what such a module has. Any other entry is judged as above, so a misspelled class
(`Feild.removed`) is still reported, and so is an entry naming project code a run over some
files leaves out.
- Each entry is matched as its rule matches it, against the definitions of the analyzed files:
a function pattern names a function, method, class, or module body; a call target a function,
method, or class; an exempt method a method's name; a scope a module, class, or function; a
class pattern a class.
- A `Class.attr` entry needs a project class, and an attribute the class family has: a name its
class body binds (a method, an annotation, an assignment), one its methods or its module set
on its instances, one of a project base, an attribute or a constant `__dict__` key the code
writes on an object typed with the class or a subclass (a `__dict__` key only read does not
exist, except for a `read-owners` target, which guards the reads), or one written on an object heki cannot type. A key a loop takes from a tuple, list, or set of string constants
(`for key in ("_a", "_b")`), or from a module's tuple of them (`for key in RECORDS`), names
each of them, a list or set only while no code changes it, and so does the key of each pair a
generator of them gives `update` (`ns.update((key, v) for key in RECORDS)`). A module
`__getattr__` caching what it serves (`globals()[name] = value`) leaves its module's string
constants bound on every path known, since Python calls it only for a name the module lacks,
unless a decorator wraps it or another module loads it (`keys.__getattr__("KEY")`).
A class whose module stores attributes heki
cannot name (`setattr(self, name, v)`), or that the code gives a name computed at run time,
may have any attribute: an entry naming none of its known ones is not reported, except with
`unmatched-contract-entries = "error"`, as one that names nothing "unless it is one the code
names at run time". A key taken from the namespace of an instance of the class or a
subclass (`for key, value in other.__dict__.items()`, `.keys()`, iterating it or
`vars(other)`, also through `list`, `tuple`, `sorted`, or a copy, and
`obj.__dict__.update(other.__dict__)`) names an attribute the instance has already, as a
`__deepcopy__` copying it does, and a deletion adds none: neither gives the class a name. So
does a key taken from the fields the class or a subclass declares, where a library keeps them
(heki's catalog): a pydantic model's `model_fields`, `__pydantic_fields__`, or `__fields__`
read on the class (`type(obj)`, `obj.__class__`, `cls`) or an instance, with their keys and
pairs as for a namespace; a dataclass's `__dataclass_fields__` and the `name` of each of
`dataclasses.fields(obj)`; an attrs class's `__attrs_attrs__`, `attrs.fields(cls)`, and
`attrs.fields_dict(cls)`.
An attribute that only a base outside the project defines matches when the code
uses it on the class. An entry target (`Class.attr["key"]`) is judged by its attribute.
- An entry whose last part is a glob is a rule about every name it may match, later ones
included: it needs only what holds that part (`pkg.store` of `pkg.store:*`, the class of
`Field._*`, the function of `run.*`). A glob without a literal holder (`*_helper`, `__*__`) is
not judged.
- The names offered are found by comparing an entry with the names that share its holder or its
last part. A run makes at most 64 such comparisons per function and class of the project (at
least 4,096) for all its entries, so of thousands of entries that name nothing in a large
module only the first get names. Every entry is still reported.
- The warnings do not fail the run; with `unmatched-contract-entries = "error"` they are errors,
which fail it, and `"ignore"` turns them off. A suppression comment or a baseline does not
hide them.
- Without the key, only a run over the whole project judges: one whose paths leave out Python
files below the project root (`heki check pkg/stores`) would find unmatched the entries naming
code in the others. A file given is checked in its project, so its run judges. With the key
set, every run judges the files it analyzes.
- `--watch` and the language server do not report them.
## Imports: `[tool.heki.imports]`
Which imports the import rules count, and which distributions provide the modules they import.
| Key | Default | Meaning |
| --- | ------- | ------- |
| `cycle-edges` | `["body"]` | The timing classes of the imports [`IMP101`](https://heki.koxudaxi.dev/rules/import-cycle/) follows when it looks for modules importing each other: `"body"`, `"lazy"`, `"function"`, and `"type-checking"`. |
| `module-distributions` | `{}` | The distributions that may provide a module outside the project, by the module: [`IMP301`](https://heki.koxudaxi.dev/rules/development-dependency-at-import-time/) and [`IMP302`](https://heki.koxudaxi.dev/rules/optional-dependency-at-import-time/) take them for the module and the modules below it, instead of the catalog's and the distributions named like the module. |
```toml
[tool.heki.lint]
extend-select = ["IMP101"]
[tool.heki.imports]
cycle-edges = ["body", "lazy"] # also the lazy imports the module body does not read
```
- `"body"`: an import that runs while its module loads: in the module body or a class body the
module body runs, on any branch or inside `try`. A constant by-name import there
(`importlib.import_module("pkg.db")`) counts, and so does a lazy import (`lazy import`, or a
name a literal `__lazy_modules__` lists) whose name the module body reads.
- `"lazy"`: a lazy import whose name the module body does not read; it runs at its first use.
- `"function"`: an import inside a function, which runs when the function does.
- `"type-checking"`: an import under `if TYPE_CHECKING:`, which never runs.
- An import whose class heki cannot tell (a lazy import whose reads it cannot place) counts for
no class.
`IMP301` and `IMP302` compare the modules a package loads with the distributions its
`pyproject.toml` declares. A distribution provides the modules named like it (PEP 503 names:
`ruamel.yaml` and `ruamel_yaml` are both `ruamel-yaml`), and the catalog knows the common ones
named otherwise (`PyYAML` provides `yaml`, `Pillow` provides `PIL`). For any other,
`module-distributions` says it, and it also settles a module several declared distributions may
provide:
```toml
[tool.heki.imports]
module-distributions = { cv2 = ["opencv-python-headless"], "google.cloud.storage" = ["google-cloud-storage"] }
```
- Each key is a module name; it covers the module and every module below it, and the longest key
naming a module decides it.
- Distribution names are compared as PEP 503 normalizes them. A module the map gives only
distributions the project does not declare is not judged.
## Ecosystem knowledge: `[[tool.heki.ecosystem]]`
heki ships a catalog of blocking, async-safe, and offloading APIs of the standard library and
common packages (`requests`, `httpx`, `aiohttp`, `sqlalchemy`, `django`, `redis`, `pandas`, …).
Add your own or override an entry:
```toml
[[tool.heki.ecosystem]]
symbol = "mypkg.db.run_query"
effects = ["blocking_db", "db_query"]
[[tool.heki.ecosystem]]
symbol = "mypkg.workers.in_thread"
offloads-blocking-arg = 0 # calls its first argument on a thread
async-safe = true
[[tool.heki.ecosystem]]
symbol = "mypkg.logging.emit"
excluded = true # never reported
```
| Key | Meaning |
| --- | ------- |
| `symbol` | Fully qualified function or method name (`package.module.Class.method`). |
| `effects` | Any of `blocking_net`, `blocking_db`, `blocking_subprocess`, `blocking_sync`, `sleep`, `blocking_fs`, `unpooled_client_alloc`, `db_query`, `quadratic_realloc`. |
| `async-safe` | Safe to call from `async def`: it never blocks the event loop, so the blocking effects in `effects` are ignored (`db_query` and `unpooled_client_alloc` still count in loops). |
| `offloads-blocking-arg` | Index of the callable argument this function runs on another thread (the receiver is not counted). |
| `excluded` | Never reported (logging and similar). |
| `copy-sanitizer` | Returns a copy of its first argument (or receiver), ending `MUT202` protection: `"deep"` copies everything below it too; `"shallow"` (or `true`) copies only the object itself, so the values below it stay protected. |
| `return-type` | The class of the objects the call returns (a factory: `mypkg.db.open` returning `sqlite3.Connection`), whose methods are then looked up in the catalog. `"Self"`: an object of the receiver's class (a builder method such as `with_options`, also on a project subclass of the library class). |
| `attribute-type` | The class of what reading the attribute `symbol` names (`package.module.Client.chat`) on an instance of a library class gives, whose members are then looked up in the catalog: `client.chat.completions.create(...)` reaches the catalog's `create`. It takes no other key. The read is typed only where nothing in the project may change it: no project subclass of the class binds the name or defines `__getattribute__`, and no base heki knows nothing of comes before the library class. |
| `sync-lock-or-tx` | A `with` over an instance of this class, or over the result of this call, holds a synchronous lock or a database transaction (`EFF106`); an instance of such a class is a thread lock for `EFF117`. |
| `non-reentrant-lock` | An instance of this class is a lock its holder cannot take again: acquiring it while the same thread or task holds it waits forever (`EFF109`). |
| `one-at-a-time` | Tasks may not be inside this method on one object at once (`EFF110`): `"always"` (a second task's call raises), `"when_unbound"` (only while the object holds no connection, as an `AsyncSession`), or `"unbinds"` (as `"when_unbound"`, and the object holds no connection after the call: `commit`). |
| `writes-in-order` | The call writes an argument to a file or a stream, or serializes it into text, in the order of its elements (`EFF112`): a mapping's keys and a sequence's items in their iteration order. `{ arg = 0, param = "data" }` names the argument (a position not counting the receiver, or a keyword; `{}`: every positional argument, as `print`), `sorted-by = "sort_keys"` the keyword argument that sorts mapping keys first, and `sorted-by-default = true` a call that sorts them unless told otherwise. |
- An override sets the keys it lists on the built-in entry for the same symbol. The keys it leaves
out keep their built-in values; `effects = []` removes every effect.
- An entry may name a function or method of the project, by the module that defines it (the
built-in catalog never describes the project's own functions).
For a project function:
| Key | Effect |
| --- | ------ |
| `effects` | added to what heki finds in its body |
| `excluded` | keeps every effect of the body from its callers |
| `async-safe` | keeps the blocking effects of the body from its callers |
| `return-type` | types its result, over its annotation |
| `offloads-blocking-arg` | the parameter the body offloads, counted as for a library method |
| `copy-sanitizer`, `sync-lock-or-tx`, `non-reentrant-lock`, `one-at-a-time`, `writes-in-order`, `attribute-type` | not read: library symbols only (the project's own declarations type its attributes) |
## Inline suppressions
```python
x = load() # heki: ignore[EFF101]
y = load() # heki: ignore[EFF101, async-blocking-call]
z = load() # heki: ignore
w = load() # noqa: EFF101
```
- A suppression applies to the line of the diagnostic.
- Codes and rule names are accepted.
- A comment without codes (`# heki: ignore`, `# noqa`) silences every rule on that line.
- A bracketed list that is not closed or names no rule (`# heki: ignore[`, `# heki: ignore[]`)
silences nothing.
- To keep a rule away from whole files, use [`per-file-ignores`](https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint).
### Unused suppressions
```toml
[tool.heki.lint]
report-unused-suppressions = true
```
With `report-unused-suppressions = true`, `heki check`, `--watch`, and the language server report
each code of a suppression comment that suppressed no report in the run (`unused-suppression`), as
Ruff's `RUF100` and basedpyright's `reportUnnecessaryTypeIgnoreComment` do:
```console
$ heki check --output-format concise
a.py:6:12: unused-suppression No `EFF101` report on this line to suppress
```
- A code is judged only when its rule ran on the file. A rule that did not run reported nothing a
suppression could match, so its codes are never reported: a heuristic rule left off (select it,
or set `heuristic = true`, to have its suppressions judged), an opt-in rule not selected, a
rule `--select` leaves out or `per-file-ignores` turns off in the file, and `MUT103` without
its summary snapshot.
- A code that names no heki rule is another tool's and stays: `F401` in `# noqa: F401, EFF101`.
A suppression without codes is never reported as unused: a bare `# heki: ignore` covers rules
that did not run, and a bare `# noqa` belongs to Ruff as much as to heki.
- A run judges what it reported, under its configuration: with `relax-async-in-tests`, a
suppression of `EFF101` in a test suppresses nothing. A run over a directory of a project misses
the reports that come from the others (`heki check app` when the blocking call is in `lib/`),
so judge, and fix, on the whole project: to look at some files, name them or pass them to
`--touched`, which keeps the analysis whole, as the pre-commit hook does.
- `heki check --fix` (and `--diff`) removes the unused codes, and the language server offers the
same edit as a quick fix. The other codes stay; a suppression left without codes goes, with
the blanks before it, and so does its line when the comment is alone on it. Other text of the
comment stays (`# type: ignore`). Without the setting, `--fix` leaves suppressions as they are.
- The reports are errors, so they fail `heki check`. A suppression comment does not suppress
them: the setting turns them off. A baseline records them as it records other reports.
- With a [baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines), `heki check` also reports an entry that
matched no report of a rule that ran on its file, when the file was checked, and exits with
code 1: `error: baseline entry a.py::handler EFF101 `time.sleep` matched no report
(`--update-baseline` removes it)`. A heuristic report that the run withholds still matches its
entry. Without the setting, the entry gets a note that it can shrink.
### Suppressions that name no rule
```toml
[tool.heki.lint]
require-suppression-codes = true
```
With `require-suppression-codes = true`, a `# heki: ignore` without codes is reported
(`suppression-without-code`, an error), as basedpyright's `reportIgnoreCommentWithoutRule` does.
Its help names the rules it suppressed in the run (`# heki: ignore[EFF101]`). It still suppresses
every rule on its line: the setting reports the comment and changes nothing else. A bare `# noqa`
is not reported, since Ruff reads it too (its `PGH004` reports it).
---
Source: https://heki.koxudaxi.dev/fixes/
# 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
```console
$ 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: `--fix` applies only the fixes of the reports shown. A report whose
rewrite heki proves safe has a safe fix, and it is [exact](https://heki.koxudaxi.dev/precision/#certifications) only
when its other premises hold too: an `OPT120` report in a `while` loop is heuristic even when
its rewrite is proven safe, because the loop's trip count is open. `OPT101` and `OPT102`
run by default, so a run without configuration applies their fixes. Over another loop than one
the data sizes, an `OPT101` or `OPT102` rewrite is heuristic, and its fix applies with
`--heuristic` or 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](https://heki.koxudaxi.dev/precision/#certifications)).
- `--include-size-dependent` runs the size-dependent rules with a rewrite (`OPT110`, `OPT111`,
`OPT120`, `OPT121`, `OPT130`; not `OPT103`, which has no rewrite), as if `extend-select`
named them. The flag alone changes no file: with `--fix` it 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: a [`MUT118`](https://heki.koxudaxi.dev/rules/sentinel-lost-in-deepcopy/) report for a Python 3.15
target replaces the `object()` sentinel with `sentinel("NAME")`, whose type, repr, and
pickling differ ([Fix safety](https://heki.koxudaxi.dev/rules/sentinel-lost-in-deepcopy/#fix-safety)).
- `--diff` takes the same flags as `--fix` and writes nothing.
- With `--touched`, or files given as paths, `--fix` and `--diff` rewrite 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)` on
`expected = [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 `range` of 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](https://heki.koxudaxi.dev/development/#checks-against-cpython).
## How `--fix` applies fixes
1. It applies the fixes that do not overlap.
2. 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.
3. 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:
```console
$ 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 = [...]` before
`s = queue`, or a parameter `s`): a type checker gives the variable one type, which would
not accept the deque.
- `import collections` goes into the module's block of standard-library imports, in the order
that block follows: straight imports first, or sorted by module as with
`force-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 before `collections` is bound.
- An existing `from collections import deque` or `import collections` is reused only when it runs
unconditionally (not under `if TYPE_CHECKING:`), nothing else binds or deletes the name (no
other store, no `del` in a function declaring it `global`, no star import that may rebind it),
and it names the standard library's module (not `from .collections import deque`).
---
Source: https://heki.koxudaxi.dev/adoption/
# Adopting heki in a Code Base
An existing code base usually has findings you cannot fix at once. This page shows how to adopt
heki step by step:
1. Record today's findings in a [Ratchet baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines), so heki fails only on
new ones.
2. Run it in [pre-commit](https://heki.koxudaxi.dev/adoption/#pre-commit) and [continuous integration](https://heki.koxudaxi.dev/adoption/#continuous-integration).
3. [Roll out more rules](https://heki.koxudaxi.dev/adoption/#rolling-out-rules): contracts for your shared state, and the opt-in
rules where they matter.
4. For a library, save [effect snapshots](https://heki.koxudaxi.dev/adoption/#effect-snapshots-mut103) of its public functions.
To have a coding agent do this, ask it to adopt heki: the [Agent Skill](https://heki.koxudaxi.dev/coding-agents/#agent-skill-experimental)
carries a playbook that proposes the first one or two contracts, writes `heki.toml` with a
`CODEOWNERS` line, the baseline, the hook and the CI job, and runs the whole project before it
finishes.
## Ratchet baselines
A Ratchet baseline records the findings you have today and fails only on new ones:
```console
$ heki check --baseline heki-baseline.toml --update-baseline # record today's findings
$ heki check --baseline heki-baseline.toml # fail on regressions only
```
Set `baseline = "heki-baseline.toml"` in the [configuration](https://heki.koxudaxi.dev/configuration/#top-level-settings)
to use it without the flag, also in `--watch` and the language server.
Entries are keyed by file, function, rule, and target, not by line number, so unrelated edits and
reformatting do not break the baseline ([import cycle groups](https://heki.koxudaxi.dev/adoption/#import-cycle-groups) are keyed by
their modules):
```toml
# heki Ratchet baseline: counts may only shrink (`heki check --update-baseline`).
version = 3
[[entries]]
path = "app/api.py"
qualname = "get_user"
rule_code = "EFF101"
target = "requests.get"
count = 1
[[entries]]
path = "app/jobs.py"
qualname = "refresh"
rule_code = "EFF101"
target = "time.sleep"
count = 2
heuristic = 1
```
The recorded set can only shrink:
| Situation | `heki check` | `heki check --update-baseline` |
| --------- | ------------ | ------------------------------ |
| No baseline file yet | an error (exit code 2) | records today's findings |
| A finding was fixed | a note that the entry can shrink; with [`report-unused-suppressions`](https://heki.koxudaxi.dev/configuration/#unused-suppressions), an entry that matches nothing is an error (exit code 1) | records the smaller entry |
| An entry grew, a recorded heuristic report is exact now, or a new finding appeared | reports it, with a note on the allowed and found counts (exit code 1 for an exact error, and for a warning or a heuristic report with [`fail-on = "warning"`](https://heki.koxudaxi.dev/configuration/#rule-selection-toolhekilint)) | reports it the same way and leaves the file as it is (exit code 1) |
| A recorded exact report is heuristic now | a note that the entry can shrink | records it as heuristic |
| A file could not be analyzed (a syntax error, an unreadable file) | reports the error and the other files' findings (exit code 2); a run over given files fails only on an error in one of them | writes nothing, so the entries of that file are not lost (exit code 2) |
To record new findings on purpose, delete the baseline and record it again.
A run over part of the project (`heki check pkg_a --baseline heki-baseline.toml`) compares and
updates only the entries of the files below its paths: the entries of the other files stay as
they are, since the run did not analyze them. A baseline written before version 3 is updated
whole first. `--update-baseline` takes directories: a file given to `heki check` selects what is
shown, and a baseline records every report of what a run covers.
### What an entry allows
Each entry counts violation sites, not reports (`sites` in JSON output):
- a contract report at the caller of a private helper stands for every write, read, or call
inside the helper;
- an effect boundary report stands for every forbidden call or write its scope function reaches.
So a second violation behind a recorded report is a regression too.
`heuristic` says how many of the sites were [heuristic](https://heki.koxudaxi.dev/precision/) reports, and is left out
when none were. A heuristic report states the weaker claim of the same premises as an exact one,
so an entry allows the claims it recorded and no stronger one: a run regresses when it finds more
sites than `count`, or more exact sites than `count` less `heuristic`. In the example, `refresh`
may have two reports of `EFF101` at `time.sleep`, and one of them may be exact. A recorded
heuristic report that heki proves after a change of the code, or after an upgrade in which heki
proves more, is a regression once: fix it, or record the baseline anew. An exact report that turns
heuristic passes, and `--update-baseline` records it as heuristic. A rule with two tiers keys both
in the same entry: `EFF101` and `EFF103` key a report by the last call of the shortest call chain
to the blocking call or the query, also where the exact report names the call every
implementation runs (a file of version 2 keys it by the call the exact report names).
Older files keep their meaning until `--update-baseline` rewrites them with `version = 3`, which
heki 0.5.0 and earlier cannot read:
- A baseline with `version = 2` does not record which sites were heuristic: any of them may be
exact, as before. `heki check` says so in a note.
- A baseline without a `version` (or with `version = 1`) was written before heki counted sites,
and counts reports. `heki check` says so in a note, and a second site behind a recorded report
is no regression.
- `--update-baseline` compares in the file's own terms first, so nothing that grew is taken in,
then rewrites the file.
A version this heki does not know is an error, and so is a file listing one entry twice (a hand
merge of two baselines).
### Import names
An [`IMP201`](https://heki.koxudaxi.dev/rules/import-boundary-violation/) report of `from m import n`, where `n` is a name
of `m`, has the target `m.n`, and its entry holds the name, so another name of the same module is a
new report. An entry of the module, as heki 0.5.0 and earlier wrote it, keeps covering the names of
its module that have no entry of their own, with the same count, and `--update-baseline` rewrites
it per name. Only a heki that keys these reports by name reads the rewritten entries: the file
has `version = 3`, which heki 0.5.0 and earlier cannot read, so every heki that reads the
baseline must be newer before a rewritten baseline is committed.
### Import cycle groups
An [`IMP101`](https://heki.koxudaxi.dev/rules/import-cycle/) entry records a group of modules that import each other, and
names no file or function:
```toml
[[entries]]
rule_code = "IMP101"
target = "pkg.a, pkg.b, pkg.c"
count = 1
```
A group is covered when one entry holds all of its modules, whichever import closes the cycle
its report shows and whichever function holds that import:
- A group that lost modules, or split into several groups, is covered: a note says the entry
can shrink to the groups there are now, and `--update-baseline` records them.
- A group with a module no entry of it holds is a regression, and so is a group joining two
recorded groups: the note names the groups it joins and the modules none of them holds. A
renamed module is such a module.
- An entry matches no report only when none of its modules is in a group.
A group spans files, so a run decides its entry only when it covers every file of the group: then
the entry is dropped when no group is left within it, or replaced by the groups there are. A run
over part of the project keeps the entries of the other groups, and records every group it
reports. An entry is reported as unused only when the run checked every file of its group and
`IMP101` runs on every one of them (`per-file-ignores` turning it off on one file leaves it
unjudged). An entry written by heki 0.4.0 or earlier names the file and function of the import its
group was reported at; heki reads it as the entry of its group, and `--update-baseline` rewrites
it. heki 0.4.0 and earlier cannot read a group entry written without them, so every heki that reads
the baseline must be newer than 0.4.0 before a rewritten baseline is committed.
## pre-commit
The hook passes the staged Python files, and a staged `pyproject.toml`, `heki.toml`, or
`.heki.toml` at the root, to `heki check --touched`. heki follows calls across files, so it still
analyzes the whole project, but it shows and fails on only the reports in those files and the
reports whose call chain reaches one of them: after a change to `app/users.py`, the `EFF101` in
`app/api.py` that reaches the change through two helpers is shown, and old findings in files the
commit left alone are not. A project can run the hook from its first commit, without a baseline.
That is all a run over touched files can promise. A change can also make a report appear in a
file the commit left alone without a call chain through the change: a module that re-exports
another function, or a return annotation another module relied on. Whether a change added such a
report cannot be told from the code after it, so:
- Without a baseline, the run ends with a note counting the reports that would fail it and are
not shown, and when it passes, its last line says what it looked at (`No reports in or through
2 touched file(s) (40 file(s) analyzed).`), not that all checks passed.
- With a baseline, every regression is shown and fails the run, wherever it is (see below).
- A configuration file can change any report, so naming one (`pyproject.toml`, `heki.toml`,
`.heki.toml`, or `hatch.toml` at the root, the summary snapshot, the baseline) shows every
report, as a run without `--touched` does: a contract added to `heki.toml` is checked in the
whole project.
Use `--touched` while editing and in the hook, and run the whole project, with the baseline, before
finishing a change and in continuous integration. A local hook may also pass the files as paths
(`entry: heki check`): a file given to `heki check` is checked in its project, as with `--touched`.
With `--fix`, the hook rewrites only the staged Python files: the fix of a shown report in another
file is left, and the run says how many were.
```yaml
# .pre-commit-config.yaml
repos:
- repo: https://github.com/koxudaxi/heki-pre-commit
rev: v0.7.0
hooks:
- id: heki
```
[heki-pre-commit](https://github.com/koxudaxi/heki-pre-commit) installs heki from its PyPI wheel, so
there is no compile and no Rust toolchain. Its tags follow heki releases, so `pre-commit autoupdate`
moves `rev` to the latest release.
To build heki from source instead, point `repo` at `https://github.com/koxudaxi/heki` with a release
`rev`. pre-commit then installs the repository as a Python package, which maturin compiles with cargo
(Rust 1.99 or newer; when cargo is not on `PATH`, the build installs Rust into a cache directory
first). That takes a few minutes, and pre-commit keeps the installed hook for later runs.
A local hook can run any version of the PyPI wheel, also without a compile or a Rust toolchain:
=== "uv"
```yaml
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: heki
name: heki
entry: uvx heki check --touched
language: system # needs uv on PATH
types_or: [python, toml]
files: '(\.py|^(pyproject|heki|\.heki)\.toml)$'
pass_filenames: true
require_serial: true
verbose: true # show warnings: they do not fail the hook
```
=== "Without uv"
```yaml
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: heki
name: heki
entry: heki check --touched
language: python
additional_dependencies: [heki]
types_or: [python, toml]
files: '(\.py|^(pyproject|heki|\.heki)\.toml)$'
pass_filenames: true
require_serial: true
verbose: true # show warnings: they do not fail the hook
```
pre-commit appends the files after the hook's `args`, so `--touched` comes last: options for the
`heki` hook go before it (`args: [--fail-on, warning, --touched]`). To check the whole project on
every commit instead, set `args: []` and `pass_filenames: false` on the hook, or drop `--touched`
from a local hook's `entry` and set `pass_filenames: false`.
The hook fails on exact errors and passes with warnings and heuristic reports, which it prints. To
make them fail it too, set `fail-on = "warning"` in `[tool.heki.lint]`, or add `--fail-on warning`
before `--touched`.
With a baseline configured, the hook fails only on new findings. A baseline entry counts every
report of its key, so a run with `--touched` compares all of them and shows every regression: a
grown entry fails the commit wherever its reports are, also in a file the commit left alone, since
the commit added the report. It judges the stale entries of the touched files and of the reports
that touch them only: a stale entry elsewhere is left to a run over the whole project.
## Continuous integration
A run fails (exit code 1) on an exact report of an `error` rule: a bug that can be critical, such
as a call that blocks the event loop (`EFF101`). Warnings (slower code, or a bug that is rarely
harmful) and heuristic reports, which can be wrong about the code, are reported without failing
it, whatever their rule's severity: a contract report, heuristic today, is one of them.
`fail-on = "warning"` in `[tool.heki.lint]` (or `--fail-on warning`) makes them fail it too. A
code base with errors today records them in a [Ratchet baseline](https://heki.koxudaxi.dev/adoption/#ratchet-baselines) first, so
that the job fails only on new ones; [`heki recommend`](https://heki.koxudaxi.dev/recommend/) says how many reports fail
the run now.
=== "GitHub Actions annotations"
```yaml
- run: uvx heki check --output-format github
```
=== "Code scanning (SARIF)"
```yaml
# The job needs `permissions: security-events: write`.
- run: uvx heki check --output-format sarif > heki.sarif || test "$?" -eq 1
- uses: github/codeql-action/upload-sarif@v4
with:
sarif_file: heki.sarif
```
Warnings and heuristic reports become annotations without failing the step (a heuristic report
of an `error` rule is an `error` annotation); `fail-on = "warning"` in `[tool.heki.lint]` (or
`--fail-on warning`) makes them fail it, as in pre-commit.
In GitHub Actions (`GITHUB_ACTIONS=true`), `heki check` writes these annotations without
`--output-format github`. To keep the text output there, pass `--output-format full`, or set
`HEKI_OUTPUT_FORMAT` (any format) in the job's `env`: it applies whenever the option is not given.
On a pull request, a project with old findings can report only what the change touches, as the
pre-commit hook does (the checkout needs `fetch-depth: 0` for the base branch):
```yaml
- run: git diff -z --name-only --diff-filter=d "origin/$BASE...HEAD" -- '*.py' pyproject.toml heki.toml .heki.toml | xargs -0 -r uvx heki check --touched
env:
BASE: ${{ github.base_ref }}
```
`--diff-filter=d` leaves out deleted files, and `xargs -r` skips the run when no Python file
changed.
With SARIF:
- findings become code-scanning alerts, warnings included, and keep the step green (exit code
`1` when one fails the run);
- a configuration, read, or syntax error (exit code `2`) still fails the step; a file heki could
not read or parse is an `error` notification of the run
(`invocations[0].toolExecutionNotifications`, with `executionSuccessful: false`), and the
results of the other files are kept;
- results carry the message, the location, the call chain (`relatedLocations`), and the help
(`properties.help`; SARIF's `rules[].help` is one text per rule, and a report's help can name
the object it is about).
For custom tooling, `--output-format json` gives every field: see
[Coding Agents](https://heki.koxudaxi.dev/coding-agents/#after-an-edit-heki-check).
## Rolling out rules
1. Run [`heki recommend`](https://heki.koxudaxi.dev/recommend/) (experimental): it says which rules would report on
the project, what heki could not see, and the contracts the code already keeps, with the keys
to add. It writes no file.
2. Start with the default rules and a baseline, or `--select` one family at a time. Only the
exact rules that are not opt-in run by default; add the heuristic ones with
`lint.heuristic = true` (or `--heuristic`), or name the ones you want in `extend-select`.
Their reports can be wrong about the code, and every output labels them `heuristic`
([Rule Precision](https://heki.koxudaxi.dev/precision/)).
3. Declare [contracts](https://heki.koxudaxi.dev/configuration/#contracts) for the shared state and the operations you
care about, and effect boundaries for the code that must stay pure. `MUT201`, `MUT203`,
`MUT204`, `MUT208`, and `EFF201` report nothing until a contract exists.
4. Enable the opt-in rules where they matter:
| Rule | Certainty | Turn it on for |
| ---- | --------- | -------------- |
| [`EFF105`](https://heki.koxudaxi.dev/rules/async-blocking-fs/), [`EFF107`](https://heki.koxudaxi.dev/rules/unretained-async-task/) | heuristic | async services |
| [`EFF106`](https://heki.koxudaxi.dev/rules/lock-or-tx-held-across-io/) | heuristic | threaded code, and code that holds database transactions |
| [`MUT103`](https://heki.koxudaxi.dev/rules/summary-effect-regression/) | heuristic | library APIs (with [effect snapshots](https://heki.koxudaxi.dev/adoption/#effect-snapshots-mut103)) |
| [`MUT106`](https://heki.koxudaxi.dev/rules/iterator-double-consumption/) | heuristic | code that passes iterators and generators around |
| [`MUT108`](https://heki.koxudaxi.dev/rules/readonly-type-mutation/) | heuristic | code that relies on frozen dataclasses and `ReadOnly` fields |
| `OPT103`, `OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130` | exact | loops over large inputs; `--include-size-dependent` runs all of them except `OPT103` (which has no rewrite), and `--fix` then applies the rewrites |
5. Use `per-file-ignores` rather than broad `ignore` lists, so new code stays covered.
### From heki 0.1
heki 0.1 ran every rule that is not opt-in by default. Since rules have a certainty, only the
exact ones that are not opt-in do ([Getting Started](https://heki.koxudaxi.dev/getting-started/#run-it) lists them).
- `lint.heuristic = true` restores the rules of 0.1, now labelled `heuristic` in every output,
except the size-dependent `OPT` rules, which are opt-in since 0.3.0: name them in
`extend-select` or `--select`, or pass `--include-size-dependent` for all but `OPT103` (`OPT103`, `OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130`).
- A baseline keeps its entries: their keys (file, function, rule, target) do not change, with one
exception. `MUT109` is now `MUT208` and the old code is no alias, so an entry with rule `MUT109`
no longer matches: its report counts as a regression. Change `rule_code = "MUT109"` to
`"MUT208"` in those entries, or record the baseline anew.
- `heki check --fix` applies the proven fixes of `OPT101` and `OPT102` by default, as in 0.1.
### From heki 0.2 and 0.3
`EFF111` and `EFF113` are no longer codes of their own: their reports are the heuristic reports
of `EFF101` and `EFF103`, labelled `heuristic` and shown, as before, with `lint.heuristic = true`
or where the code is named. The old codes and names are not kept.
- Write `EFF101` for `EFF111` (`async-possibly-blocking-call`) and `EFF103` for `EFF113`
(`loop-possible-db-query`) in `select`, `extend-select`, `ignore`, `per-file-ignores`,
`severity`, and suppression comments. In the configuration the old codes are unknown rules
(exit code 2); a comment naming one suppresses nothing.
- A baseline entry with `rule_code = "EFF111"` or `"EFF113"` no longer matches: its reports count
as regressions. Change the code to `"EFF101"` or `"EFF103"` (adding up the counts of two entries
that then have the same file, function, and target), or record the baseline anew.
### From heki 0.5 and earlier
- `--update-baseline` writes `version = 3`, which heki 0.5.0 and earlier refuse: update heki
everywhere the baseline is read (the pre-commit `rev`, CI) before committing a rewritten
baseline. A file of version 2 is read as before, with a note ([What an entry
allows](https://heki.koxudaxi.dev/adoption/#what-an-entry-allows)).
- Once rewritten, an entry recorded for a heuristic report no longer allows an exact one: a
report that heki proves is a regression once.
- An exact `EFF101` or `EFF103` report is keyed by the last call of the shortest call chain, as a
heuristic one is, in a file of version 3. A file of version 2 keeps the call the report names,
so its entries still match, and `--update-baseline` rewrites them with the new key.
## Effect snapshots (`MUT103`)
For a library, a change in what a public function *does* is worth reviewing even when no rule
fires: it starts mutating an argument, or doing network I/O. Save the effect summaries of the
public functions and check against them:
```console
$ heki snapshot --write # writes .heki-summary-snapshot.json
$ heki check --extend-select MUT103 # reports functions that gained effects
```
1. Commit `.heki-summary-snapshot.json`.
2. When a new effect is intended, refresh the snapshot in the same pull request: the diff of the
JSON file shows reviewers what changed.
A run that cannot analyze every file (a syntax error, an unreadable file) does not write the
snapshot: it reports the errors and exits with code 2, so the entries of those files are not
lost.
---
Source: https://heki.koxudaxi.dev/recommend/
# Configuration Advice
!!! warning "Experimental"
`heki recommend` is experimental: what it prints, its policies, and its JSON object can
still change in any release. See [Experimental Features](https://heki.koxudaxi.dev/experimental/).
`heki recommend` analyzes a project as `heki check` does and prints advice on its
configuration, with counts from the project and the keys to add to `[tool.heki]`. It writes no
file and runs none of the project's code.
```console
$ heki recommend
$ heki recommend app --output-format json
```
It takes the options of `heki check` that decide what is analyzed: `--select`,
`--extend-select`, `--ignore`, `--heuristic` / `--no-heuristic`, `--config`,
`--target-version`, and `--baseline`. The advice is relative to that configuration. `--all`
shows every block of contracts, where the report shows the first 3 of each kind, and lists up
to 50 of the sites that keep blocks at `unresolved = "ignore"`, where it lists 5.
## What it prints
- **The project**: the root, and the files and functions analyzed.
- **Reports now**: what `heki check` prints with the configuration, as exact and heuristic
reports (reports sharing a root cause count once, as `heki check` folds them), the heuristic
reports of exact rules that `lint.heuristic = false` withholds, and the heuristic rules it
leaves off. With a baseline, the reports it allows and the regressions.
- **What keeps reports heuristic**: the heuristic reports of exact claims (the heuristic reports
of exact rules), counted by the premise of the claim each leaves open and why ([Rule
Precision](https://heki.koxudaxi.dev/precision/)), or by the condition of the exact tier that is no premise
("Trip count open": the claim holds, and the change pays off only over a loop the data
sizes). Each row says what the cause states, how many reports leave it open, how many leave
nothing else open, and what closes it: an annotation, which must be true; a change of the
code; heki's catalog, which no configuration sets (the row says where to report the case);
or nothing you can apply. None of it enters the block. A report whose rule records no cause
is counted as "not recorded", never given a guessed one.
- **What heki cannot see**: where heki is silent, so no count of reports applies (see
[below](https://heki.koxudaxi.dev/recommend/#what-heki-cannot-see)).
- **Rules worth enabling here**: every rule the configuration leaves off, and every exact rule
whose heuristic reports it withholds, with the reports naming it in `extend-select` would add
(exact and heuristic, and with a baseline the regressions among them), its consequence, and
the published measurement of how often its reports are right about the code
([Rule Precision](https://heki.koxudaxi.dev/precision/)), or "not measured". Rules without reports here are named on
one line.
- **Contract candidates**: the `write-owners`, `read-owners`, and `effect-boundaries`
contracts the code already keeps, as blocks: the candidates whose entries differ only in their
targets or scopes are one entry. Each block has its confidence, evidence, and the trial run of
its rules that verified it, and the class patterns tried for it ([below](https://heki.koxudaxi.dev/recommend/#blocks-and-class-patterns)).
The first 3 blocks of each kind are shown and declared, and the others counted. Then the
sites heki cannot tie to a class that keep blocks at `unresolved = "ignore"`, each once with
the candidates and blocks it holds back, and the candidates a trial rejected, with the report
it made.
- **Contract entries that match nothing**: the entries of the contracts configured now that name
no definition, attribute, method, or `__dict__` key in the analyzed files, with the existing
names like each, as `heki check` warns about them
([Entries that match nothing](https://heki.koxudaxi.dev/configuration/#entries-that-match-nothing)). They are listed
whatever `lint.unmatched-contract-entries` says, and the section is left out when there is
none.
- **Notes**: what to know to weigh the advice. How many of the reports shown now (with a
baseline, the regressions) make `heki check` fail, with the Ratchet baseline that records them
so that only new ones fail; and at the default `fail-on`, how many do not (warnings, and
heuristic reports, which count as warnings), which `fail-on = "warning"` would make fail it.
When the paths given leave out Python files below the project root, the note names them: heki
takes the files it analyzed as the whole project, so what it says about callers, readers, and
writers holds for those files only. It counts up to 50 such files, among the first 10,000
entries below the root.
- **The keys to add or change**, for the file the project reads its configuration from:
`[tool.heki...]` tables in a `pyproject.toml`, tables at the top level in `heki.toml`,
`.heki.toml`, or a `--config` file. Without a configuration file, the keys go into a new
`pyproject.toml`. The block only adds: an array the file already sets is written whole, with
the additions named in a comment, since TOML cannot append to an array.
## What heki cannot see
heki reports nothing through a call it cannot follow, so these parts list calls, not reports.
For each call it says how many are awaited, how many may hold up an event loop (not awaited, in
an `async def` or in a function one runs on its thread), and how many run in a loop or below
one.
- **Calls of packages heki's catalog does not cover**, by the name an entry of
`[[tool.heki.ecosystem]]` needs (entries are looked up by that exact name, without
inheritance or aliases). heki takes such a call to have no effect. For the 64 names with the
most reach, a trial run gives each a catalog entry that waits on the network and sends a
database query (`effects = ["blocking_net", "db_query"]`) and says what `heki check` would
then print through it, exact and heuristic: "if it waits" (`EFF101`) and "if it sends a query"
(`EFF103`). heki cannot know what a library call does, so no entry enters the block, and the
trial's counts are kept out of every count of reports: add an entry if you know what the call
does.
- **Names heki's catalog lacks in packages it covers**: the same, for the names the trial shows
heki would report through. If such a call waits or sends a query, report it at heki's issue
tracker: the catalog should list it.
- **Calls heki does not resolve**, by function and reason: a parameter without annotation, an
annotation that names no class heki knows, a value annotated `Any`, `object`, or `Callable`, a
name nothing heki sees binds, a protocol whose implementations heki cannot list, a call's
result or an attribute heki gives no class, a method named at run time, more implementations
than heki follows, or a member heki does not find. An annotation would resolve most of them;
an annotation is an edit of the program, so none enters the block.
- **Source roots**: a directory below the project root, neither a source root nor a regular
package (a directory with `__init__.py` is imported by its own name, so heki never takes one
for a source root), below which the dotted path of an import that names no project module is a
file (`backend/config/env.py` for `import config.env`) is a candidate for `src`. An import of
the standard library or of a package heki's catalog covers is no candidate's, and neither is
one whose path is below several directories none of which holds the importing file. The first
8 candidates by imports are tried, each added to `src` with those already taken (the source
roots heki detects are written out with them, since setting `src` turns detection off). A
trial computes the module names with the directory added for every Python file below the
project root, those the paths given leave out included (heki reads them for this; when they
are more than the 50 it reads, no directory is tried), resolves each import as heki's index
does, and takes the directory into the block only when the imports it was tried for name its
own files, no two files of one kind then define one module unless just those files did before,
every import that names a module of the project now, and every import a directory already
taken was taken for, still names the same module of the same file, and every contract of the
configuration and every baseline entry still names what it names now (the rules' matchers
judge each definition by its name now and its name with the directory; a baseline entry must
not spell a module whose name would change). The block is then checked whole: when it would
make some other import resolve into a file below a source root that does not hold the
importing file (`import utils` in `tool.py`, below `svc_a/` and `svc_b/`, would name
`svc_a/utils.py`), the directory that file is below stays out and the others are tried again.
heki cannot tell such a file is the one meant, and the block holds only what the trial
checked. The calls of names of those files are left out of the library names.
- **Functions with an A1 hazard** (frame introspection, `exec`, a body too large to model):
the Soundness lane proves nothing in them. `heki assumptions` lists them.
## Which rules the block enables
A rule enters the block when it reports here, is not experimental, reports bugs (its severity
is `error`), and no published measurement shows real harm below 10%. The other rules are
listed with the reason they stay out:
- slower code, and bugs that are rarely harmful, are worth reading but not worth failing a run
for;
- experimental rules are listed apart, under "Optional", and never enabled;
- a rule the configuration ignores stays ignored;
- `MUT103` compares with a summary snapshot you save with `heki snapshot --write`;
- contract rules run when their contract is declared, so they are not listed here.
## Which contracts the block declares
Candidates are drawn from what the code does, never from names:
- `write-owners`: an attribute of a project class written after its object is constructed only
by functions of one module, and read in at least two other modules. The entry allows the
smallest of `module:Class.*` and `module:*` that covers the writers. An attribute written
only while its objects are constructed (by an initializer, or by a function filling the object
it constructs) gets an entry that allows no writer.
- `read-owners`: a private attribute (`_name`) read only by functions of its class's module,
whose class is used in at least two modules. The entry allows the readers as above.
- An ownership candidate is judged by the accesses of its class's family, the class and its
project subclasses, since its target covers them: their writers and readers, and the modules
reading the attribute on objects of any of them. A method accessing the attribute only
through its own receiver (`self.items.append(x)` in a subclass) may be in any module: when one
is outside the owner's module, the entry sets `own-receiver = "allow"`.
- Test code never defines an owner: an attribute a test function writes (or a private one it
reads) other than through its own receiver gets no candidate, since that access would be a
report of the contract.
- `effect-boundaries`: a module whose functions reach no blocking call, with
`forbid = ["blocking"]`; a package whose every module qualifies is one scope, which names the
package's own module and the modules below it (`["pkg:*", "pkg.*:*"]`), also when it has no
`__init__.py` yet. A scope has at least three functions. A package holding test code names its
other modules one by one, not by a wildcard.
No candidate is drawn from a module holding test code, as `relax-async-in-tests` finds it: a
test file, or a file defining a `test_*` function or method (a test class in Django's
`tests.py`, for one). Its classes get no ownership contract and its functions no boundary. Nor
is one drawn from a module whose name, taken from its path, has a character a pattern cannot
spell literally: a `:`, or glob syntax (`routes/[id].py`).
What the configuration already declares is not proposed: an attribute a `write-owners` or
`read-owners` target names, and a module an effect boundary forbidding every blocking effect
covers. A kind whose rule the configuration ignores is not proposed either. When the block sets
`src`, no contract is proposed, and no verification run counts the block's rules: a new source
root renames modules and resolves imports heki does not resolve now, so run `heki recommend` again
once it is set. Each target has the
module-part form (`app.models:Order.items`), which never matches another project's names.
The contract trial declares every candidate at once, the ownership contracts with
`unresolved = "report"`, and runs their rules (`MUT201` and `MUT205`, `MUT203` and `MUT206`,
`EFF201`) as `heki check` would: inline suppressions and `per-file-ignores` apply, and the
reports inline suppressions drop are counted apart (a rule `per-file-ignores` turns off for a
file reports nothing there). A candidate the rule of its contract (`MUT201`, `MUT203`, `EFF201`)
reports is rejected and listed with the first report, and so is one that hides a report the
configuration's own contracts make now: a target lists its `__dict__` key, on its class and the
subclasses, for every contract, so a contract with `unlisted-dict-keys = "report"` stops
reporting a write of that key on an object of either (`Store.b` hides the report of a write of
`Child.b` when `Child` derives from `Store`). Reports of `MUT205` or `MUT206`, accesses on objects
of unknown class, reject no candidate: they make it medium (below). Of each kind, the trial
declares the first 32 candidates: `write-owners` with the attributes changed in place first, then
by the modules reading them; `read-owners` by the modules using the class; boundaries by their
functions times the functions calling into them from outside. The configuration's own
`write-owners` contracts take places of the 32.
| Confidence | When |
| ---------- | ---- |
| high | the trial reports nothing for the contract, every Python file below the project root was read, parsed, and analyzed (when the paths given leave part of the root out, the count of the files there got to its end and found none), and no function of a boundary's scopes reaches code heki does not see (a call it does not resolve, a library name without a catalog entry, a function it does not model) |
| medium | the trial reports no violation, but `MUT205` or `MUT206` reports accesses on objects of unknown class (they are listed), files were left out (or the count of them stopped before the end) or could not be parsed, or a scope function reaches code heki does not see (it is listed) |
Medium candidates are in the block too, an ownership one with `unresolved = "ignore"`: heki may
not see every access on objects of unknown class (in the files left out or not parsed, for one)
that the rule of such accesses would report. A high one sets `unresolved = "report"`, unless the
configuration ignores that rule (`MUT205`, `MUT206`): it stays ignored, so the entry sets
`unresolved = "ignore"` and the block does not select the rule. A candidate on a subclass is
left out when the one on its base class is kept: a target covers the subclasses of its class.
Every candidate carries the caveat that accesses inside code heki cannot follow are not seen.
### Blocks and class patterns
The kept candidates of one kind whose entries set the same keys but `name` and `targets` (or
`scopes`) are one block: its targets are theirs, and its trial their reports, each once. A
contract reports every access of one of its targets that it does not allow, whichever target it
is, so the block reports what its candidates do. A block's confidence is the lowest of its
candidates', and it is named after its one target or scope, or else after what accesses its
targets (`attributes written by app.store:Store.*`) or where its scopes are.
Where the census sees no function writing an attribute of a class or its subclasses (for
`read-owners`: reading one whose name starts with `_`) that the block does not allow, the block
may name them all by one pattern, `module:Class.*` (`module:Class._*`), which also names the
attributes the code adds later. The pattern trial declares each such pattern alone, with the
block's other keys and `unresolved = "report"`, and runs the rules of its kind: the block names
the pattern in place of the class's targets only when the trial reports nothing for it that they
did not, under the contract's rule, under the rule of accesses on objects of unknown class when
the block reports them (a pattern names any attribute a write of unknown class may add), and by
hiding a report of the configuration's own contracts. A refused pattern is listed with its first
report.
Blocks are ranked within each kind: `write-owners` with an attribute changed in place first,
then by the modules reading their targets times their candidates. The first 3 of each kind are
shown and declared; `--all` shows and declares every one. The sites of `MUT205` and `MUT206`
reports that keep blocks at `unresolved = "ignore"` are listed after the blocks, each once, with
the candidates whose trial reported it and the blocks they are in (shown or not), the first 5 by
the candidates they hold back (`--all`: up to 50). An annotation naming the object's class lets
heki judge such an access by that class.
The verification run then applies the whole block, the rules it enables and the contracts it
declares, as `heki check` would; the counts of the block's rules come from it.
## How the advice is kept honest
- Every count comes from the project, through the analysis `heki check` runs: inline
suppressions, `per-file-ignores`, and the baseline apply as they do there. With the block
applied, `heki check` prints the reports it promises.
- A contract enters the block only when the trial of its rules reports no violation of it on the
code as it is, and hides no report the configuration's own contracts make; accesses on objects
of unknown class make it medium, with `unresolved = "ignore"`. The verification run then
applies the whole block as `heki check` would.
- How often a rule's reports are right is quoted only from published measurements, with their
sample, interval, and date; a rule without one is "not measured". No score is computed.
- What keeps a report heuristic comes from the report itself, as the analysis decided its
tier; a cause the analysis does not record is shown as not recorded, never guessed.
- No library catalog entry enters the block: heki cannot verify what a library call does. What
a trial entry would make `heki check` print is said as a condition ("if it waits") and kept
out of every count of reports. `src` enters only after its trial.
- The same input, configuration, and heki version give the same report, on any machine and
with any number of threads.
- It writes nothing and keeps every value the configuration sets.
[ADR-020](https://github.com/koxudaxi/heki/blob/main/docs/DESIGN_HISTORY_AND_ADR.md#adr-020-heki-recommend-advice-on-the-configuration-from-the-projects-own-analysis)
records these rules and the decisions behind the command.
## Example
A project with three modules and a test file:
```python
# app/users.py
import requests
def fetch_name(user_id: int) -> str:
return requests.get(f"https://api.example.com/users/{user_id}", timeout=5).text
def load_user(user_id: int) -> dict[str, str]:
return {"id": str(user_id), "name": fetch_name(user_id)}
def known_names(names: list[str], source: list[str]) -> list[str]:
known = list(source)
found = []
for name in names:
if name in known:
found.append(name)
return found
```
```python
# app/report.py
def total_and_count(rows: list[int]) -> tuple[int, int]:
items = (r for r in rows)
total = sum(items)
count = len(list(items))
return total, count
def average(rows: list[int]) -> float:
return sum(rows) / len(rows) if rows else 0.0
def spread(rows: list[int]) -> int:
return max(rows) - min(rows) if rows else 0
```
```python
# app/api.py
from app.users import load_user
async def get_user(user_id: int) -> dict[str, str]:
return load_user(user_id)
```
```python
# app/billing.py
import stripe
async def charge(amount: int) -> None:
stripe.Charge.create(amount=amount)
```
```python
# tests/test_users.py
def test_load_user() -> None:
pass
```
```console
$ heki recommend app
heki recommend (experimental) on .: 4 file(s), 13 function(s)
Reports now 1 shown (1 exact, 0 heuristic), 0 heuristic withheld, 4 heuristic rule(s) off
What keeps reports heuristic
1 heuristic report(s) of exact claims: OPT110 1
premise: cause reports only open closed by
Rewrite proven safe: zero-trip-exception-safe 1 0 code
the `set(...)` the rewrite builds before the loop may raise even when the loop runs no time: an element that may be unhashable, or a name that may be unbound there
e.g. app/users.py:14 OPT110
Rewrite proven safe: hash-consistent-probe 1 0 code
the value looked up may compare otherwise through `hash` than through `==`: a custom `__eq__` / `__hash__`, or an unhashable value
e.g. app/users.py:14 OPT110
Nothing here enters the block: an annotation or a change of the code is an edit of the program.
What heki cannot see (no report either way)
calls of packages heki's catalog does not cover: 1 call(s) of 1 name(s) in 1 package(s)
name calls async loops if it waits if it sends a query
stripe.Charge.create 1 1 0 EFF101 1 exact -
Rules worth enabling here
rule reports exact consequence right about the code (published) real harm block
MUT106 1 - bug not measured - yes
OPT110 1 0 slowdown 78% (65-87%), n=50, 2026-11-21 6% no: slower code, not a bug
No reports here: EFF102, EFF105, EFF106, EFF107, EFF109, EFF110, EFF112, EFF114, EFF115, EFF116, EFF117, IMP101, IMP102, IMP104, IMP301, IMP302, MUT101, MUT107, MUT108, MUT111, MUT112, MUT113, MUT115, MUT118, MUT120, OPT103, OPT111, OPT112, OPT120, OPT121, OPT130
MUT103: it compares with a saved summary snapshot: run `heki snapshot --write`, then select it.
Contract candidates
effect-boundaries app.report medium
3 function(s) in 1 module(s) reach no blocking call heki sees
trial: EFF201 0
For every block, accesses inside code heki cannot follow (unresolved calls, libraries without a catalog) are not seen.
Notes
- 1 Python file(s) below the project root were not analyzed (tests/test_users.py): heki takes the analyzed files as the whole project, so what it says about callers, readers, and writers holds for those files only.
- heki check fails on 1 report(s) shown now (exit code 1): a Ratchet baseline records them, so that it fails only on new ones (`heki check --baseline heki-baseline.toml --update-baseline`, then `baseline = "heki-baseline.toml"` in the configuration).
- "if it waits" and "if it sends a query" come from a trial run that gives each library name tried a catalog entry with `effects = ["blocking_net", "db_query"]`: what `heki check` would print if the call waited on the network or sent a database query. heki cannot see what these calls do, so no entry for them is in the block; add one in `[[tool.heki.ecosystem]]` if you know.
pyproject.toml: keys to add or change
[tool.heki.lint]
extend-select = ["MUT106"] # adds MUT106
[[tool.heki.effect-boundaries]]
name = "app.report without blocking calls"
scopes = ["app.report:*"]
forbid = ["blocking"]
```
## Suggestions
A suggestion is a claim about the code and the annotation edit that writes it in standard
typing (ADR-023). It is no report: it has no rule code, severity, suppression, baseline entry,
or exit code, and `heki check` never prints one. Edits valid only together are one group: a
parameter and the parameters it is handed to, and the same parameter of every definition of an
override family. The JSON object lists them under `suggestions`.
The kind `readonly-parameter` suggests `Sequence`, `Mapping`, or `AbstractSet` for a parameter
annotated `list`, `dict`, or `set` that the function, and every function it hands it to, only
reads. What a suggestion states:
- **Only read here**, **Does not leave**, **Every call resolves and only reads**: the claim, from
the facts `MUT110` reads, so the suggestion and its guard cannot disagree. When one is open,
nothing is listed. A method called on a parameter annotated `Sequence`, `Mapping`, or
`AbstractSet` reads as the same method of the builtin. An operator or a comparison can hand the
object to the other operand's special method (`other == p` may run `other.__eq__(p)`, and which
side Python tries first depends on the classes): only a builtin's keeps nothing, so the other operand is a value built in the function or of a
builtin class no project class derives from. An item read of a `defaultdict` changes it.
- **The builtin's own reads**: the claim's last part (R2, read for the type the suggestion writes).
A `Mapping` may be an instance of a project class deriving from `dict`, from a standard-library
class of its family (`OrderedDict`, `defaultdict`, `Counter`, `UserDict`, `ChainMap`, ...), or
from `Mapping` itself, or of a project class registered with one; a `Sequence` or an
`AbstractSet` likewise. A `register` call heki cannot resolve, or a `__subclasshook__` in such
a class, admits any class and leaves every parameter of the family out. The function's reads of the object, and those of the
functions it hands it to, run that class's code if the class binds the method they run: item
access (with `__missing__`), iteration (with the length hint `[*v]`, `f(*v)`, and `xs += v` take;
`a, b = v` iterates too), size and truth, membership, comparison, conversion to text, operators,
`keys()` and the items for `**v`, the length `case []` and `case {"k": v}` test and the `get` of
the latter, the methods called by name (and `__getattribute__` for those), and what the catalog's
`[[invokes]]` entry of a library call reading it names. A read with no such list (a library call
without an entry, such as `bytes(v)`, or a method the builtin lacks) may run any member of the
class. Such a class, or one a metaclass heki does not know creates, leaves the parameter out,
counted by cause: `class Cache(dict)` with its own `__contains__` leaves out `k in m` on a `dict`
parameter, not `m.get(k)`. So does a class deriving from `defaultdict` for an item read: the
`__missing__` it inherits inserts the key. A class outside the project is taken to run what the
builtin runs.
- **Literal container annotation**: a builtin `list`, `dict`, or `set`, or its `typing` form,
after `Optional`, `| None`, and quotes; not `Annotated[...]`, a `Mutable*` ABC, or an alias.
Its names are the module's: a name a function or class body around the `def` binds (`class
list` in the enclosing function, a method `set` above it in the class) names that binding.
- **Abstract use**: every use exists on the read-only type; a set gives no iteration order.
- **Name bound once**, **Callees take it**, **Whole family** (no `Protocol` member, no
`@overload`, a body that does something, the whole override family in the group), **Not
replaced**, **Annotations stay unread** (every decorator in heki's table, of a `cached_property`
the `functools` one only, no class machinery or base the catalog does not know, no use of the
function as a value, no `dataclass` without a docstring for a constructor: it writes one from
the constructor's signature), **A name for the type** (an import of the module is reused when
it runs before the annotation is evaluated: above the `def`, or anywhere under `from __future__
import annotations`; on a Python 3.14 target, whose annotations are deferred without it, an
import below the `def` still leaves the premise open).
- **No fact lost**: the annotation trial. Each file of the groups is analyzed again with their
edits applied in memory, as the JSON prints them; a group whose edits change the facts of a
function they edit or the file's reports, every rule selected, is withheld, and `withheld` says
what changed (`trial-limit`: heki stopped trying the file, after four analyses with other edits
or two checks of its reports). With an `import-boundaries` contract that walks imports, the
reports of the modules it judges are checked too: an import an edit adds may be reached from
them. A heuristic group is tried by its facts only, so this premise is never established for
one.
- **A file to edit**: no generated file (a leading comment with `generated` or `DO NOT EDIT`),
no function a stub declares; these, and test code, are counted under `left_out`.
When the claim holds and only a premise of the edit is open, the group is heuristic, listed with
`--all` with the open premise and its place. A `list[str]` parameter is heuristic too: a
`Sequence[str]` also admits a plain `str`. heki looks for a type checker's configuration
(`[tool.ty]`, `ty.toml`, `[tool.mypy]`, `mypy.ini`, `[tool.pyright]`, `pyrightconfig.json`,
`[tool.pyrefly]`): half of each guard is the type checker's, the other half `MUT110`.
## JSON output
`--output-format json` prints one object, described by the JSON Schema at
[schemas/recommend-3.json](https://heki.koxudaxi.dev/schemas/recommend-3.json), the URL its `$schema` field names, which
`heki recommend --output-format-json-schema` prints. Version 3 lists contracts as blocks, with
`targets` in place of one `target`.
Within a `version`, fields are only added; the `version` changes when a field is removed or
changes meaning.
| Field | Content |
| ----- | ------- |
| `kind`, `version`, `heki` | `heki-recommend`, the version of the object, and the version of heki |
| `root`, `config_file`, `table_prefix` | the project root, the configuration file (`null` without one), and the table its keys are under (`tool.heki`, or empty) |
| `analyzed` | the files and functions analyzed, the files that could not be read or parsed, the paths given, and the Python files below the root they leave out |
| `runs` | the analyses the report was computed from: `discovery`, then `annotation-trial` (the files of the suggestions analyzed again with their edits) when there was a suggestion to try, `source-roots` (the source-root trial) and `hypothetical-catalog` (the trial of library names) when they ran, `contract-trial` when it tried a contract candidate (none when the block sets `src`, or when every candidate is past the places of its kind), `pattern-trial` when a block shown has a class pattern to try, and `verification` when the block adds rules or contracts and does not set `src` |
| `reports_now` | the counts of "Reports now", and `failing`: the reports shown (with a baseline, the regressions) that make `heki check` fail at the configuration's `fail-on` |
| `open_premises` | the counts of "What keeps reports heuristic": by code; by premise or condition and cause, with what the cause states, what closes it, the reports, the reports it is the only open cause of, and the first 50 reports; the sets of causes that reports leave open together |
| `blind_spots` | the counts of "What heki cannot see": the calls of library names without a catalog entry, by package and name, with what the trial run found; the names heki's catalog lacks in packages it covers; the calls heki does not resolve, by function and reason; the source-root candidates and their trials; the functions with an A1 hazard; the totals |
| `rules` | each rule of "Rules worth enabling here": its metadata, the reports it would add, its published measurement, whether the block enables it, and why |
| `contracts` | each block the configuration block declares, the first 3 of each kind (`--all`: every one): its kind, its targets (or the packages and modules of its scopes), the candidates it stands for, its entry, confidence, evidence, what the trial reported for its candidates, the class patterns tried with what the pattern trial reported and whether the block names them, and caveats |
| `contracts_not_shown` | per kind, the blocks past the first 3 and the candidates they stand for |
| `contract_blockers` | the sites of accesses heki cannot tie to a class that keep blocks at `unresolved = "ignore"`: how many, the first 5 (`--all`: 50) with the rule, path, line, function, the report as `heki check` writes it, and the candidates and blocks each holds back, and whether the list is cut |
| `suggestions` | the standard types the code already keeps (ADR-023): per kind, the exact and heuristic groups; the type checker the project configures (`found`, `config`, or `null`); the groups, the exact ones by rank, the first 50 (`--all`: every one, the heuristic ones after them), each with its `id` (kind, module, qualified name, parameter; no line), `certainty`, `message`, `items` (path, line, column, the byte span of the annotation's head, qualified name, parameter, the annotation now and as proposed), byte-span `edits` with a path each (applied together; spans are offsets in the file's text as UTF-8, the file's own bytes unless a PEP 263 declaration names Latin-1), `premises` and whether each is established, the `open` ones with their cause and place, `related` places, `guards`, `leverage` (the calls binding it, and those passing an attribute), and `labels` (`public`, `list[str]`, `family`); `truncated`; the groups the annotation trial withheld, by `reason` (`fact-would-change`, `report-would-change`, `trial-limit`), with what changed for the first 50; the parameters left out as test code, in generated files, or declared by a stub; per premise, the parameters it leaves out, the first 10 causes of those, and those it keeps heuristic; and where the project reads annotations at run time (`reader_sites`) |
| `rejected_contracts` | the candidates a run reported for, each alone, with the run and its reports |
| `contracts_not_tried` | per kind, the candidates past the trial's places (32 of each kind, the configuration's own `write-owners` contracts taking `write-owners` places), which no trial declared |
| `unmatched_entries` | each entry of "Contract entries that match nothing": the contracts' kind, the key, the entry, the contracts holding it (a name, or `#` and its position), what it names none of, the existing names like it, and `named_at_run_time` when its class family gets attributes named at run time (only with `unmatched-contract-entries = "error"`) |
| `notes` | the notes |
| `config`, `config_toml` | the keys to add or change, as keys and values and as TOML |
| `content` | the report as the text output prints it |
Exit codes: `0` the report was printed; `2` configuration, I/O, or syntax errors (the report
of the other files is still printed, as `heki check` does). It never exits with `1`: it checks
nothing.
---
Source: https://heki.koxudaxi.dev/cli-reference/
# CLI Reference
Exit codes: `0` no diagnostic that fails the run (warnings and heuristic reports are reported without failing it), `1` an exact `error` diagnostic, or any diagnostic with `--fail-on warning` (`lint.fail-on`), among the Ratchet regressions when a baseline is used (or a refused `--update-baseline`, or pending `--diff` changes), `2` configuration / I/O / syntax errors.
A file that cannot be read or does not parse does not stop the run: `heki check` reports its error, checks and reports the other files, and exits with `2`, also when it reports diagnostics. A run over given files (file PATHS, or `--touched`) reports and fails on only the errors of those files, as it does with diagnostics, and names the other files it could not analyze in a note. A file that does not parse cannot run either, so nothing it would do is assumed; the names under its module resolve to nothing. SARIF output lists such files as `error` notifications of a run that did not execute successfully (`invocations[0].toolExecutionNotifications`, `executionSuccessful: false`); JSON output holds the diagnostics only.
## `heki`
```text
heki (壁, "wall") is a static checker for Python. It tracks side effects and mutations across function calls, and checks imports and the contracts you declare.
Usage: heki
Commands:
check Check Python files or directories for blocking calls, mutations, imports, and broken contracts
server Start the incremental Language Server Protocol (LSP) server [alias: lsp]
rule Explain a rule, its Proof Obligations, and counterexamples (`ruff rule` style) [alias: explain]
snapshot Manage interprocedural effect summary snapshots (`MUT103`)
assumptions List Assumption A1 hazards (`eval`, `exec`, `locals()`, frame introspection, functions too large to model) in a project
inspect Experimental: what heki knows about one function (its effects, what it changes, keeps, and returns, whether it is pure, its callers, reports, and contracts)
recommend Experimental: advice on the configuration of a project, with counts from its analysis, and the keys to add (it writes no file)
skill Experimental: install heki's Agent Skill where a coding agent reads skills
version Print the version of this heki, and with `--changelog` what this release changed
help Print this message or the help of the given subcommand(s)
Options:
-h, --help
Print help (see a summary with '-h')
-V, --version
Print version
Documentation:
Documentation https://heki.koxudaxi.dev/
Getting started https://heki.koxudaxi.dev/getting-started/
Configuration https://heki.koxudaxi.dev/configuration/
Rules https://heki.koxudaxi.dev/rules/
Coding agents https://heki.koxudaxi.dev/coding-agents/
llms.txt https://heki.koxudaxi.dev/llms.txt
Agent Skill https://heki.koxudaxi.dev/coding-agents/#agent-skill-experimental
Exit codes:
0 no diagnostic fails the run
1 a diagnostic at the `fail-on` severity (an exact `error` by default; a heuristic one counts as a `warning`), a refused `--update-baseline`, or pending `--diff` changes
2 a configuration, path, read, or syntax error; the error says what to do and links the documentation
Examples:
heki check
check the project in the working directory
heki check src tests --select EFF,MUT
check two directories with two rule families
heki check --fix
apply the fixes heki proves safe
heki rule EFF101
the documentation of one rule
heki skill install --agent claude-code
install the Agent Skill for Claude Code (experimental)
Output for programs:
heki check --output-format json
the diagnostics; when the configuration or a path stops the run, {"error": {"message", "help", "docs", ...}}
heki rule --output-format json
one rule's metadata
heki inspect --output-format json
what heki knows about one function (experimental)
```
## `heki check`
```text
Check Python files or directories for blocking calls, mutations, imports, and broken contracts
Usage: heki check [OPTIONS] [PATHS]...
Arguments:
[PATHS]...
Directories to analyze, and files to report on: a file is checked in its project, as `--touched` does from the project root (with directories, the directories are analyzed). A file outside any project is analyzed alone
[default: .]
Options:
--fix
Apply `safe` + `unconditional` fixes (`OPT101`/`OPT102`)
--include-size-dependent
Also run the opt-in rules with a `size-dependent` rewrite (`OPT110`, `OPT111`, `OPT120`, `OPT121`, `OPT130`), as if `--extend-select` named them, and with `--fix` or `--diff` apply their proven-safe rewrites, in every function
--unsafe-fixes
With `--fix` or `--diff`, also apply the unsafe fixes, which change what the program does in a way the rule's page states (`MUT118`)
--diff
Preview fixes as a unified diff without writing files
--touched ...
Show and fail on only the diagnostics in one of these files or with a hop of their call chain (`related`) in one, such as the files a commit or a pull request changed, and let `--fix` and `--diff` rewrite only these files; the analysis still covers PATHS (put PATHS before the option). With a baseline, every Ratchet regression is shown, wherever it is; without one, a note counts the diagnostics that would fail the run and are not shown. A configuration file (`pyproject.toml`, `heki.toml`, the baseline) shows every diagnostic. Another path that is not an analyzed file is named in a warning
--select