Async and Execution Effects¶
heki finds blocking calls in async code, database queries and clients in loops, and lock and task hazards, keeps scopes free of an effect with effect-boundaries and away from the files below a directory with path-boundaries (experimental), and reports functions that gained an effect with heki snapshot.
An effect is what a call does besides returning a value: it waits on the network, sends a query, takes a lock, writes a field. heki follows effects through helper calls and across files, so a report names the function that does the work and the chain of calls that leads to it. Rules has one page per rule, and Contracts has every contract key.
🔍 What runs without configuration¶
Three rules are exact and run by default, and two more are exact by default and are described with the problems they belong to. Their reports show the call chain, and an error fails heki check.
| Rule | Reports | Tier |
|---|---|---|
EFF101 |
a call in an async def that always runs a network, database, subprocess, or sleep call that waits on the event loop, however many helpers below |
exact, default |
EFF102 |
a loop over data whose every iteration makes an HTTP, database, or RPC client, or a sessionless request | exact, default |
EFF103 |
a loop over data whose every iteration sends a database statement | exact, default |
EFF102 and EFF103 also have heuristic reports, where a premise of the claim is open (a loop that can make a client or run a query on every iteration). They appear with --heuristic.
EFF103 knows Django's model managers from the ecosystem catalog. Model.objects, read on a model class or on cls, is the Manager Django adds, or the manager the model's body declares (objects = StreamManager(), a project subclass of models.Manager). Its query methods (get, count, create, get_or_create, update, ...) send a statement on every call, so calling one per item of a loop over data is an exact, default EFF103 report; filter, exclude, and all only build a QuerySet. A method the manager adds is followed as project code. Some managers keep the report heuristic (with --heuristic) or unknown:
- a manager that binds a name its query methods use (
get_queryset,_queryset_class,__init__) runs its own code under them: heuristic. So is a model's defaultobjectswhile the project defines such a manager, since heki takes aManagerto be possibly an instance of any project subclass; - a project
QuerySetsubclass (models.QuerySetis the catalog'sQuerySet) that binds a name a query method looks up on the queryset (get'sfilterand_fetch_all,acount'scount) runs its own code under that method: a call of it on aQuerySetis heuristic, since heki takes aQuerySetto be possibly an instance of any project subclass. A subclass that only adds methods keeps every row, on its own instances too; createandacreatesave a new instance of the model: while a project model bindssave(or a methodsavereaches,save_base,_save_table, ...) otherwise than as a method callingsuper().save(...)on every path, they are heuristic.get_or_createandupdate_or_createquery bygetfirst on every call, andQuerySet.deletenever calls the model'sdelete, so a model's overrides leave them exact;- a manager
from_queryset()oras_manager()builds, one of a class outside the project, and related managers (question.choice_set, a many-to-many field read on an instance) are unknown: they add no effect.
EFF109 (a lock taken again while it is held) is under Exclusive use and lock safety, and EFF116 (a generator that nothing iterates) is on State Ownership and Mutation. Both are exact and run by default.
Two rules run by default only when you pass --heuristic (or set lint.heuristic = true), because they can be wrong about the code. They are about locks and cancellation: EFF117 is under Exclusive use and lock safety, and EFF118 under Resource and cancellation lifetimes.
The knowledge base names the calls that wait. Besides requests and httpx.Client, it lists the synchronous clients of Xinference (xinference_client.RESTfulClient and the handles of its models) and of Supabase and PostgREST (supabase.Client, postgrest.SyncPostgrestClient): building a table query, including through .not_, sends nothing, and execute() waits for the server, so EFF101 and EFF103 report it there. Tier: exact, default (EFF101, EFF103).
A call through a module object resolves as the same call through an import of the module: importlib.import_module("time") and __import__("time") with a constant name (a relative one anchored at a constant package or at __package__), sys.modules["time"] with a constant key, and getattr(m, "sleep") on such a module. __import__("a.b") gives the package a, and the module a.b when it takes names: a tuple, or a list nothing changes before the call, fixes that. So importlib.import_module("time").sleep(1) in an async def is reported as time.sleep(1) is. A name, a package, or names to take that heki cannot fix leave the call unresolved, and sys.modules["m"] is taken to hold the module m. Tier: exact, default (EFF101 and the other effect rules).
A module variable of the standard library is an instance of the class its stub annotation declares, so a call through it resolves: sys.stdout.write(...), logging.root.getChild(...), sys.modules[name].__name__, and the names from sys import stderr binds. Passed on as it is, the variable has that class where a catalog row tests an argument's class: logger.add(sys.stderr) adds a stream sink, which opens no file. A catalog row for the variable's own member answers first (os.environ.copy, unittest.mock.patch.dict), a project module that stores the variable's name (sys.stdout = Tee()) keeps it unresolved, and the stubs give types only, never an effect: a method of the declared class gets one from a catalog row under its exact name, or from a [[tool.heki.ecosystem]] entry for it (typing.TextIO.write). An effect boundary with unresolved = "report" no longer reports such a call. Tier: exact, default (EFF101 and the other effect rules).
The typeshed stubs of dateutil, docutils, jsonschema, openpyxl, pexpect, reportlab, setuptools, six and tensorflow are bundled, so a call on what these libraries return resolves with no stubs installed: parser.isoparse(text).isoformat(), six.ensure_str(value).upper(), load_workbook(path).copy_worksheet(sheet).title, and an attribute of a value annotated with a library class (ValidationError.message). The types are those of the release range the stubs describe (assumption R10 in ARCHITECTURE.md). They give types and signatures only, never an effect: a catalog row or a [[tool.heki.ecosystem]] entry answers first, a project module of the same name is the project's, and a library class with a lowercase name (pexpect.spawn(...)) stays untyped. An effect boundary with unresolved = "report" no longer reports such a call. Tier: exact, default (EFF101 and the other effect rules).
A method call on a standard-library value takes the overloads its positional arguments select, so match.group() and match.group(1) give a str and match.group(1, 2) a tuple; a call with keyword or unpacked arguments still joins every overload, and so does a module function. A library class written with type arguments keeps them (re.Match[str], os._Environ[str]), an operator on two operands of one builtin class, or with a str on the right, gives the result the stubs declare (("A" + s).lower(), (n + 1).bit_length()), and an item of a TypedDict at a constant key its class declares has the key's annotated type (payload["name"].upper()). Operands of different classes (s * 2), an undeclared or computed key and a union of library classes (str | bytes) stay unknown. An effect boundary with unresolved = "report" no longer reports such a call. Tier: exact, default (EFF101 and the other effect rules).
DATA101 (exact, default, loop-carried-concat) also reports an array grown through numpy.r_[...] or numpy.c_[...] on every iteration (arr = np.r_[arr, chunk]), also when a helper returns that concatenation (arr = grow(arr, chunk)), as it does for numpy.hstack.
A function handed to a thread or process pool runs once per item for these rules:
executor.submit(f, ...) in a loop counts as a call of f on every iteration, and
executor.map(f, items) as one call of f per item, for the concurrent.futures executors;
loop.run_in_executor(executor, f, ...) in a loop is the same. EFF102 then reports a client f
makes per item, and EFF103 a query f sends per item. Through a pool both reports are heuristic
(with --heuristic), since the pool runs f after submit returns. A worker in another process
(ProcessPoolExecutor, anyio.to_process.run_sync) runs on copies of its arguments, so what it
changes in them does not reach the caller, and rules that follow changes to the caller's objects
do not follow it there.
A function handed to a project helper runs where the helper calls it. heki follows a helper that
calls its parameter (each(items, visit) calling visit(item)), directly, in a nested function,
or by handing the parameter on to another project function: by name, as an attribute of an import
(helpers.each(items, visit)), or as a method of its own receiver (self.each(items, visit),
where every project implementation of the method may run). A module handed as an argument is
followed too: a helper that calls a member of a parameter with no annotation or one annotated
types.ModuleType (c.save(item)) runs the module's function of that name when the caller
passes a project module, also one that a function returns on every path. A tuple display handed
to a helper that calls an item of its parameter at a constant position (checks[0](node), or
first(node) after first, second = checks), or hands it on as itself to a function that does,
runs the element at that position, when no * element comes before it. Where the helper calls
its parameter itself, or hands it on as itself to project functions, the function runs on the helper's paths of that call, and through a hand-on on
the second helper's paths, mapped across the call handing it on: a call whose arguments fail the
helper's test around it (maybe(fetch, False) with if enabled: return fn(), or
maybe_on(fetch, False) with def maybe_on(fn, enabled): return maybe(fn, enabled)) runs nothing
there, and a helper that calls it on every normal return (def call(fn): return fn(), or
def hand_on(fn): return call(fn)) gives the exact EFF101 report the direct call gives, when
that call can be no other value (a helper that may replace it first, if not enabled: fn = noop,
keeps the heuristic report, and so does a hand-on within a recursion or into a nested function).
Otherwise
EFF101 reports a blocking call reached this way as heuristic (with --heuristic). Nothing runs on the caller's thread through
a generator function, an async def the call does not await, or a function an offloading
decorator runs on a worker (@sync_to_async, @database_sync_to_async), whether it is the
helper, a function the helper hands the value on to, or the function handed over.
In an effect boundary (EFF201, heuristic, contract), a
call of such a parameter is judged by what every followed call binds it to: the functions, or
the modules' functions of the member's name, and their effects. With unresolved = "report",
the call stays a call heki cannot resolve when the parameter is the scope function's own, an
argument is unpacked with *, the parameter is rebound before the call, a nested function runs
away from the function that defines it, or the member is a class (constructing it is not
followed). Only modules are followed for members: an instance passed in place of the module, a
method's receiver (self), and a parameter annotated with a class are not.
The first page of the docs shows EFF101 two helpers below an async def and EFF103 one helper below a loop, with their output.
The chain a blocking-call report shows (EFF101, both tiers, and EFF105) is one real path to the call, chosen in this order: a path the call's arguments allow (a helper that dispatches on isinstance(item, Response) shows the branch an argument of known class takes), then a path on the normal flow before one through cleanup code (an except handler or a finally body), then the shortest. Which path is shown never decides whether the report exists or its tier. Output folds many reports into one ((+N more)) only when they reach the same blocking call through the same helper: sites that call one API directly still fold together, and sites that reach different blocking calls through different helpers stay separate groups.
The async rules EFF101, EFF105, and EFF106 skip test code as pytest finds it (relax-async-in-tests, on by default): test_* functions, test_*.py and *_test.py files, conftest.py, files under test/ or tests/, an app's tests.py (Django's test runner), and the files the python_files setting of the pytest settings file in use names (pytest.toml, .pytest.toml, pytest.ini, .pytest.ini, pyproject.toml, tox.ini, setup.cfg, the first one pytest takes). When testpaths is set, a configured name counts only below those directories, so python_files = *.py with testpaths = tests leaves app/models.py production code. Tier: unchanged; only which files are skipped changes.
🔧 Rules to switch on¶
These rules are off by default. Name one in extend-select or with --extend-select EFF105. A prefix such as EFF or ALL never enables them.
| Rule | Reports | Tier |
|---|---|---|
EFF105 |
a call in an async def that always runs blocking local file I/O on the event loop |
exact, opt-in |
EFF107 |
an asyncio.create_task result bound to a local variable that is never awaited, returned, or stored; a call whose result is discarded is not reported |
heuristic, opt-in |
EFF112 |
the iteration order of a set of strings, which changes between runs, reaching a file, a stream, or a serializer | heuristic, experimental, opt-in |
EFF114 |
an except around a recursion that takes the RecursionError and goes on, so the result depends on the stack depth |
heuristic, experimental, opt-in |
EFF115 |
an async def handed to a library call that does not await it (a thread target, an executor function, a signal handler), so the body never runs |
heuristic, experimental, opt-in |
Experimental rules can change or go away between releases. Experimental Features says why each one is marked.
🔒 Exclusive use and lock safety¶
Some objects allow one user at a time: a lock, a stream reader, a database connection. These rules report code that breaks that. The opt-in ones (EFF106 and EFF110) are off until you name them in extend-select, for example --extend-select EFF106. A prefix such as EFF or ALL never enables them.
An exclusive object used by tasks started together¶
A stream reader, an asyncpg connection, or a WebSocket runs one operation at a time. EFF110 reports tasks started together (asyncio.gather, a task group) that all use the same one, so the second call raises. Tier: heuristic, experimental, opt-in (EFF110).
import asyncio
class FrameClient:
def __init__(self, reader: asyncio.StreamReader) -> None:
self._reader = reader
async def read_frame(self) -> bytes:
return await self._reader.readexactly(4)
async def read_frames(self, count: int) -> list[bytes]:
return await asyncio.gather(*(self.read_frame() for _ in range(count))) # EFF110
heki reports: FrameClient.read_frames starts a task for every item, each using self._reader (asyncio.gather); asyncio.StreamReader allows one operation at a time, so the second task's call raises. Read the frames one after another instead.
A lock taken again while it is held¶
threading.Lock and asyncio.Lock are not reentrant. A method that holds the lock and calls another method that takes it waits for itself. EFF109 reports the second take, directly or through a call. Tier: exact, default; its heuristic reports, where a helper takes the lock on some paths only, appear with --heuristic (EFF109).
# app/m.py
import threading
class Registry:
def __init__(self) -> None:
self._lock = threading.Lock()
self._items: dict[str, int] = {}
def size(self) -> int:
with self._lock:
return len(self._items)
def add(self, key: str) -> int:
with self._lock:
self._items[key] = 1
return self.size() # EFF109
heki reports: Registry.add calls app.m.Registry.size, which takes self._lock while Registry.add holds it (taken at line 14); threading.Lock is not reentrant, so this waits forever. Move the body of size into a helper that does not take the lock, and call that one.
A write without the lock its other writes hold¶
When one method changes a field holding a lock, every method that changes it needs the same lock. EFF117 reports a write that holds none while another write of the same state holds a thread lock, and a thread heki resolves can run one of them. An update can be lost. Tier: heuristic, runs with --heuristic (EFF117).
import threading
class Stats:
def __init__(self) -> None:
self._lock = threading.Lock()
self.received = 0
def start(self) -> None:
threading.Thread(target=self._read).start()
def _read(self) -> None:
with self._lock:
self.received += 1
def reset(self) -> None:
self.received = 0 # EFF117
heki reports: Stats.reset assigns self.received where heki finds no lock held, while Stats._read assigns it holding self._lock; Stats._read can run on another thread, so the two writes can interleave and one can lose the other's update. Take the lock in reset too.
I/O while holding a lock¶
A lock held across a network call or an await makes every other user of the lock wait for the slow call. EFF106 reports an await or blocking network I/O while a threading lock or a database transaction is held. Tier: heuristic, opt-in (EFF106).
# app/sync.py
import threading
import requests
_lock = threading.Lock()
def refresh(url: str) -> str:
with _lock:
return requests.get(url, timeout=5).text
$ heki check
app/sync.py:10:16: EFF106 (lock-or-tx-held-across-io) [error, heuristic] `refresh` calls `requests.get` (blocking network I/O) while holding the synchronous `threading.Lock` taken at line 9
|
10 | return requests.get(url, timeout=5).text
| ^
= related: app/sync.py:10:16: `refresh` calls `requests.get`
= help: make the request before taking the lock and hold it only for the update
Found 1 diagnostic(s) in 2 file(s).
...
Make the request before taking the lock and hold it only for the update.
⏳ Resource and cancellation lifetimes¶
Work around a resource can end early. A cancelled task stops at its next checkpoint, and cleanup that runs after the cancellation can be stopped the same way, so the resource is never released. Each rule in this part reports one way the end of a scope leaves a resource in the wrong state. The rules are listed as entries of their own, so a new one is one more entry.
Cleanup that stops at a cancellation checkpoint¶
A finally body, an except that takes the cancellation, or an __aexit__ that awaits a call reaching an AnyIO or Trio cancellation checkpoint is cut short in a cancelled scope: the await raises the cancellation again and the rest of the cleanup does not run. EFF118 reports it when no shield is on the way. A shield is a CancelScope with shield=True by the public name (anyio.CancelScope) or by the path that defines it (anyio._core._tasks.CancelScope). Tier: heuristic, runs with --heuristic (EFF118).
# app/m.py
import anyio
async def delete_group(name: str) -> None:
await anyio.to_thread.run_sync(delete_container_group, name)
async def run(name: str) -> None:
try:
await watch(name)
finally:
await delete_group(name) # EFF118
log_deleted(name)
heki reports: run awaits app.m.delete_group in a finally body, which reaches the cancellation checkpoint anyio.to_thread.run_sync 2 calls down with no shield on the way: in a cancelled scope the await raises the cancellation and the rest of the cleanup does not run. Shield the cleanup:
📜 Contracts for execution effects¶
effect-boundaries marks code that must stay free of an effect: a render function that makes no blocking call, a decision pass that writes no model state, a generator that does not read the environment. Any function in scope that reaches the effect, directly or through calls, is reported as EFF201 (heuristic, contract).
# heki.toml
[[effect-boundaries]]
name = "pure-render"
scopes = ["app.render.*"]
forbid = ["blocking"]
message = "render from data the caller already loaded"
fail = true
A scope can name only the lambdas passed to one parameter of a callable, scopes = ["app.passes:PassSpec(when)<lambda>"]: the when= gates of a table of PassSpec(...) calls are judged and the run lambdas beside them are not (heuristic, contract). Every parameter of such a lambda takes its class from the Callable[[A, B], R] annotation of the parameter it is passed to, in any module; each parameter keeps its class only where every use of the lambda gives it the same one, so a use that gives a position another class, or a use with no annotation (the lambda also called or returned), leaves that position without one. Where the annotation gives a position no class (the type variables of a generic class, Callable[[P, S], bool]), the boundary's lambda-parameters gives the classes by position, lambda-parameters = ["app.host.Parser", "app.state.*"] (a class, a protocol, or the classes of a module by a pattern), and the read, call, and write rules see through them as through an annotation. A call through a subscripted class, PassSpec[Parser, State](...), is selected like PassSpec(...), unless the project defines the subscript (a __class_getitem__ of the class, or a metaclass). See Configuration: effect-boundaries.
A effect-boundaries contract that lists every allowed site itself can keep its reports out of a Ratchet baseline with baseline = "never".
render_page in app/render.py calls load_title, which calls requests.get:
$ heki check
app/render.py:5:19: EFF201 (effect-boundary-violation) [error, heuristic] `render_page` reaches blocking_net (`requests.get` via `app.loader.load_title`), which effect boundary `pure-render` forbids
|
5 | return f"<h1>{load_title(page_id)}</h1>"
| ^
= related: app/render.py:5:19: `render_page` calls `app.loader.load_title`
= related: app/loader.py:5:12: `load_title` calls `requests.get`
= help: render from data the caller already loaded
Found 1 diagnostic(s) in 3 file(s).
The run exits with code 1. forbid takes tokens such as blocking, blocking-net, blocking-db, sleep, mutates-params, writes-targets, reads-targets, calls, reads-environment, and writes-environment (calling os.putenv, or changing an entry of os.environ, directly, through a callee, or with monkeypatch.setenv). effect-boundaries lists them all with their extra keys.
write-targets, write-universe, and allow-writes take the targets write-owners takes, also the items of a project class that derives from a builtin dict, list, or set (Imports[*], Imports["typing"]). An attribute pattern such as Model.* never names the items, so a boundary that guards them lists them on their own.
call-targets entries take the argument lists of call-owners targets, also on functions outside the project: call-targets = ['os.getenv("HOME")'] with calls reports a reached os.getenv("HOME") or os.getenv(key="HOME") and no other os.getenv call, and 'builtins.str.split("#")' matches the constant passed at position 0 or as sep (EFF201, heuristic, contract).
A value that an annotation declares as a union of up to eight classes is each of them, so a call on it reaches the method of each class; a union that different assignments join keeps three. A loop over a TypedDict's keys or items that calls setattr(obj, name, value) writes the keys the class declares only for a closed TypedDict (closed=True, or a base that is closed). For an open one the write stays an attribute named at run time (unresolved-writes), because a subclass value may carry more keys.
A call-targets entry may name a class outside the project. With references = "calls-and-bases" or "reads" in the boundary, a class statement in scope naming it among its bases (class T(unittest.TestCase)) reaches it, and so does one naming a project class deriving from it in any module, as for call-owners (EFF201, heuristic, contract, opt-in through references).
A scopes or allowed-callees entry naming a method (Class.method) names that method only. With include-overrides = true in the boundary (or in its defaults table) it also names the overrides in the project subclasses of Class, nested scopes included, so a subclass written later is in scope or allowed with no change of the configuration. The key is off by default for that reason.
read-universe and allow-reads keep a scope's reads to a list, the way write-universe and allow-writes do for writes (opt-in, contract). A reached read of a Class.attr entry of read-universe that no allow-reads entry names is reported under EFF201, in every form reads-targets follows. An entry can also name a name of a project module, such as a registry a pass fills (pkg.tables:REGISTRY, pkg.tables.REGISTRY, or pkg.tables:*): its reads through the module object or an import and its loads in the module's own functions and lambdas count (Names of a project module in read entries). With unresolved = "report" the boundary also reports a read it cannot tell: an attribute of an object of unknown class, or one under a name computed at run time (getattr(x, name), obj.__dict__[key], vars(obj).pop(key), obj.__dict__.popitem()).
With unresolved = "report", a write or a read on an object of unknown class, or under a name computed at run time, is allowed when the allowances name it for every class it may be of, since it is then no forbidden access whatever the object is: allow-writes = ["*.updated_at"] allows thing.updated_at = now of an unannotated thing for every class, and allow-writes = ["Model.updated_at"] allows it where only Model entries name updated_at (write-universe = ["Model.*"]), not where Other.* names it too. Several allowances may cover the classes together. A name computed at run time (setattr(model, name, v), getattr(x, name)) needs an allowance naming every attribute of each class (Model.*); allow-reads covers reads the same way (heuristic, contract).
A write under a name that is a parameter of the function writing (setattr(self, key, v), self.__dict__[key] = v, del self.__dict__[key]) writes the attribute each string constant the followed calls pass for it names, by position or keyword, also through helpers that hand the name on: on self of a method, that attribute of the class; on an object of unknown class, that attribute by name. A parameter annotated with a Literal of strings names those attributes. A name heki cannot read stays a write under a name computed at run time, and the report names the class when the object is an instance of a project class. A module read from sys.modules is a ModuleType, so a write on it under a constant or Literal name writes no project attribute; a store anywhere in the project under a name heki cannot read on an object of unknown class may rebind sys.modules itself, and then the modules read from it are of unknown class. A store through a project class object (Client.send = f, setattr(Client, "send", f), del Client.send) is a write of the class attribute (EFF201, heuristic, contract).
The boundary follows a function a worker runs like a call of it, since what the function does still happens, on another thread or process: pool.submit(step.execute, x), executor.map(f, xs), loop.run_in_executor(None, f), asyncio.to_thread(f), anyio.to_thread.run_sync(f), and a call of a function @sync_to_async decorates (heuristic, contract). What the function writes, changes of its arguments, reads, calls, and its I/O count for the scope. Its blocking calls (blocking, blocking-net, sleep, ...) do not: they make the worker's thread wait, not the scope's. A process worker (ProcessPoolExecutor, anyio.to_process.run_sync) works on copies of its arguments and on module state of its own process, so what it writes and changes stays there and does not count either; what it runs (its reads, calls, I/O, and environment reads) does. asyncio.to_thread(f), the run_sync APIs, and a call of a decorated function return a coroutine that starts the worker only once it runs: a scope that builds it without awaiting it, or only returns it, starts no worker, so f is not searched there, while one awaited, gathered (asyncio.gather), or made a task is. A pool's submit and map and loop.run_in_executor start the worker at the call. With unresolved = "report", a function handed to a worker or to a builtin that calls it (map(f, xs), xs.sort(key=f)) that heki resolves to no function is a call the boundary cannot judge, and allowed-callees naming the worker function stops the search there.
exempt-decorators makes a function that carries a listed decorator stating a reason an allowed callee of the boundary: a scope function carrying it is not searched, and a search does not go into a callee carrying it.
A call that heki resolves to many functions, such as one through a table of more than eight entries, is judged by allowed-callees when the list names every function it may reach. The call no longer stays unresolved past the candidate limit.
An allowed-callees, allow-writes, or allow-reads entry can say why it is allowed: list it in a group with a reason, and set allowance-reasons = "required" on the boundary or its defaults table so that an entry without one is a configuration error. With unused-allowances on the boundary, heki check over the whole project reports each of these entries, and each exempt-decorators entry, that allowed no effect the boundary would report without them.
path-boundaries (experimental) keeps scopes from reading, copying, or listing the files below a directory: tests that must not read the expected outputs they are compared with, except through the helper that stores them. A call that reads, copies, or lists a path heki builds from a constant path at or below a root (__file__, module constants, also imported ones, locals, /, joinpath, os.path.join, .parent) is reported as EFF202 (heuristic, contract, experimental). The result of a sanitizers function may be read or copied, not listed, and a path heki cannot place (a parameter, another call's result) is reported only with unresolved = "report".
# heki.toml
[[path-boundaries]]
name = "expected-outputs"
roots = ["tests/data/expected"]
scopes = ["tests.*"]
exempt-scopes = ["tests.conftest.*"]
forbid = ["read", "copy", "list"]
sanitizers = ["tests.conftest.stored_expected"]
📸 Public API effect changes across pull requests¶
A change in what a public function does is worth a review even when no rule fires: it starts changing an argument, or doing network I/O. heki snapshot saves the effect summaries of the project, and MUT103 (summary-effect-regression, heuristic, opt-in) reports each function that gained an effect since.
Commit the file. Later, total starts to sort its argument, and so does checkout, which calls it:
$ heki check --select MUT103 --fail-on warning
app/billing.py:1:1: MUT103 (summary-effect-regression) [error, heuristic] `total` gained side effects since the summary snapshot: mutates parameter `prices`
|
1 | def total(prices: list[int]) -> int:
| ^
= help: if the change is intended, refresh the snapshot with `heki snapshot --write`
app/billing.py:6:1: MUT103 (summary-effect-regression) [error, heuristic] `checkout` gained side effects since the summary snapshot: mutates parameter `prices`
|
6 | def checkout(prices: list[int]) -> int:
| ^
= help: if the change is intended, refresh the snapshot with `heki snapshot --write`
Found 2 diagnostic(s) in 2 file(s).
The run exits with code 1. When the new effect is intended, refresh the snapshot in the same pull request, so the diff of the JSON file shows reviewers what changed. A pull request can also be compared with a snapshot of its base branch, with heki check --snapshot PATH. Effect snapshots has both workflows.
👉 Next steps¶
- Configuration: effect-boundaries lists every key and
forbidtoken, and path-boundaries the keys of a path boundary. - Adopting heki in a code base shows how to start with a baseline, and has the blocking and database-write contracts of a web service to copy.
heki inspect app.render.render_page(experimental) shows what one function reaches, with the call chains. See Coding agents.- State Ownership and Mutation covers the contracts about who may change, read, or call a thing, and the rules for borrowed, shared, and single-use values.