Skip to content

Contracts

This page lists the contract kinds, the keys they share, and the settings that change what they report. Contracts declare what no type can say. Each kind is an array of tables with its own rule:

Contract Declares Rule Certainty
write-owners who may write an attribute MUT201; MUT205 with unresolved = "report" heuristic
read-owners who may read an attribute MUT203; MUT206 with unresolved = "report" heuristic
call-owners who may call a function or construct a class MUT204; MUT207 with unresolved = "report" heuristic
effect-boundaries what a scope must not reach: I/O, writes, reads, or calls EFF201 heuristic
readonly-returns results every caller shares MUT202 heuristic
invalidation writes that must be announced MUT208 heuristic
import-boundaries which modules a module may import (experimental) IMP201; IMP202 with unresolved = "report" heuristic
path-boundaries which files below a directory a scope must not read, copy, or list (experimental) EFF202 heuristic

Settings to check first

These three settings change what a contract reports more than their names suggest.

Setting Default What it changes
attribution = "lexical" "call-graph" An access is judged in the function whose code holds it, whoever calls that function. A helper that only allowed functions call is no longer allowed through them, and a private helper reports its own accesses, not at its callers.
pkg.passes in pkg.passes:PassSpec(when)<lambda> none The module part of a lambda scope is the module whose code holds the lambdas and the calls. PassSpec itself may be defined in another module.
unresolved = "report" "ignore" The contract also reports what it cannot tie to a class or a module, such as an access on an object of unknown class, under the rule the table above names. With the default these accesses are not reported.

Keys the kinds share

Contract name message fail baseline unresolved
write-owners yes yes yes yes yes
read-owners yes yes yes yes yes
call-owners yes yes yes yes yes
effect-boundaries yes yes yes yes yes
readonly-returns yes no yes yes no
invalidation yes yes yes yes no
import-boundaries yes yes yes yes yes
path-boundaries yes yes yes yes yes

name is the contract's name in reports, and message the help of every report of the contract. fail = true makes the reports of the contract fail heki check (Failing on a contract), and baseline = "never" keeps them out of a baseline (Keeping a contract out of the baseline). A defaults table sets keys once for every table of its kind.

How contracts apply

  • 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, and of functions that keep their results in a memo they fill themselves, 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 and do not fail the run by default: to make a broken contract fail heki check, the pre-commit hook, and CI, set fail = true in its table (below).
  • Every name in a contract but import-boundaries, whose names are module patterns, 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}). An alternative may be empty, as in a shell's brace expansion: pkg.run:outer{,.*} names outer and every scope nested in it (outer.<locals>.inner, a class defined in it, their methods), where pkg.run:outer names outer alone. It works wherever a configured text is a glob, module patterns, exclude, and per-file-ignores included.
  • A {...} group may hold dotted alternatives, in the holder of a Class.attr target too: pkg.{a.Base,a.Sub}.only_sub is pkg.a.Base.only_sub and pkg.a.Sub.only_sub, and heki check judges each of them (Entries that match nothing).
  • 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 <module>), 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). A write-owners or read-owners target whose qualified name has no dot (pkg.api:LIMIT, pkg.api:*) names the names of the module's namespace (below).
  • A report of a glob target names the member it matched (readspkg.types.DataType._flag``, and through a protocol the member the protocol declares); 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 ((alsoA.items)).
  • A Class.attr target covers the subclasses of the class too, and a read or call through a value typed with a project protocol that only the class and its subclasses implement (below).
  • 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 (or module:name in write-owners and read-owners), 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, unlisted-attributes, 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.

Defaults for the tables of a kind

A configuration with many tables of one kind repeats the same values in each. A defaults table per kind, named <kind>-defaults ([tool.heki.call-owners-defaults], [tool.heki.effect-boundaries-defaults], and one for each of write-owners, read-owners, call-owners, effect-boundaries, readonly-returns, invalidation, import-boundaries, and path-boundaries), sets the keys that every table of its kind takes when it does not set them:

[tool.heki.call-owners-defaults]
attribution = "lexical"
references = "reads"
subclasses = false

[[tool.heki.call-owners]]
name = "commit"
targets = ["pkg.db.Session.commit"]
allowed-callers = ["pkg.db.*"]

[[tool.heki.call-owners]]
name = "rollback"
targets = ["pkg.db.Session.rollback"]
allowed-callers = ["pkg.db.*"]
references = "ignore"
  • The result is the configuration with every table written out: both tables above have attribution = "lexical" and subclasses = false, and rollback keeps its own references. heki check, heki inspect, and heki recommend read the effective values.
  • A table's own key overrides the default, an empty list too (allowed-callers = [] is a list of no callers). A list is replaced whole, never merged with the default's.
  • name and targets name one contract, and source and entry-sources say where one is defined, so they are errors in a defaults table. Any other key of the kind may be defaulted, fail among them: fail = true in [tool.heki.call-owners-defaults] makes the reports of every call-owners table fail the run, and a table with fail = false keeps its reports advisory.
  • A defaults table is one table, not an array of tables. With no table of its kind it changes nothing. In a file that is not a pyproject.toml it is written without the tool.heki prefix ([call-owners-defaults]).
  • A table you add to the file from heki recommend takes the defaults like any other, and the recommender tries it with them.
  • An error about a value of a defaults table is reported at the defaults table.

Where a contract is defined

Every contract report points at the contract it is of and at the entry its access matched (JSON contract_locations, SARIF related locations, and the language server's related information: Output formats), and every entry that matches nothing is warned about with its place and its contract's. The place is where the file writes it: the table's header, the entry in its list, in an included file, a defaults table, or a group. A table generated from another file can name the place of the rule there instead:

[[tool.heki.write-owners]]
name = "fields"
targets = ["pkg.model.Model.fields", "pkg.model.Model.extra"]
allowed-writers = ["pkg.store.*"]
source = "scripts/tables.py:120"
entry-sources = { "pkg.model.Model.extra" = "scripts/tables.py:131" }
  • source = "path:line" is shown for the table, and entry-sources maps an entry, as the lists write it out, to the place shown for it, for a table whose entries come from several places. The path is relative to the project root, and the line counts from 1. The file need not exist.
  • They are metadata: they change no match, no baseline key, and no judgment of an entry that matches nothing. Without them, the places in the configuration files are given.
  • Errors (exit code 2), each at its file and line: a value that is not path:line (no line, a line of 0, a rooted path), and an entry-sources entry that no list of the table holds.

Failing on a contract

fail = true in a contract table makes every report of that contract fail heki check (and --watch): exit code 1, whatever the report's tier and severity. A contract without the key, or with fail = false, keeps the default: its reports are warnings, and fail the run only as fail-on says. Every kind of contract has the key.

[[tool.heki.write-owners]]
name = "generation-store"
targets = ["pkg.model.DataModel.fields"]
allowed-writers = ["Store.*"]
fail = true
  • Other warnings and heuristic reports stay advisory: fail = true does not change fail-on, the rules' severities, or the tier of a report. The outputs (text, JSON, SARIF) are the same with and without it. Only the level of a GitHub annotation, which says whether its report fails the run, follows it: an error report of a contract is an error annotation with fail = true and a warning one without it (see Continuous integration).
  • A report that several contracts find stands for each of them, and fails the run when one of them has fail = true. A MUT202 report is of the readonly-returns tables naming a producer the changed value may come from: all of them when the change reaches the producer's result itself, and only those with deep = true when it changes a value below it.
  • A report that a baseline records, or that an inline suppression hides, does not fail the run. With --touched, the reports the run shows decide; the note about the ones it does not show says how many would fail it.
  • The closing note of a text run, which counts the reports that do not fail the run, leaves these reports out.
  • fail = true in a <kind>-defaults table applies to every table of the kind that does not set fail itself.
  • fail-on = "warning" is still there for a project that wants every warning and heuristic report to fail the run. To fail the run on the reports of single rules that belong to no contract (IMP101), list them in lint.fail.