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
*-ownerscontract protects itstargetsand lists who may touch them. A*-boundariescontract 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.cachefunctions, and of functions that keep their results in a memo they fill themselves, are checked without one byMUT114(cached-result-mutation). - Declaring a contract selects its rule, whatever its certainty.
- Their reports are heuristic, so they count as warnings for
fail-onand do not fail the run by default: to make a broken contract failheki check, the pre-commit hook, and CI, setfail = truein 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.fieldsmatchespkg.model.DataModel.fields, notpkg.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{,.*}namesouterand every scope nested in it (outer.<locals>.inner, a class defined in it, their methods), wherepkg.run:outernamesouteralone. It works wherever a configured text is a glob, module patterns,exclude, andper-file-ignoresincluded. - A
{...}group may hold dotted alternatives, in the holder of aClass.attrtarget too:pkg.{a.Base,a.Sub}.only_subispkg.a.Base.only_subandpkg.a.Sub.only_sub, andheki checkjudges each of them (Entries that match nothing). - A glob's
*spans dots (pkg.parser.*covers the functions of every module underpkg.parser), except in the last segment of a target, which names the attribute, function, method, or class:pkg.*._*names the private members of everything inpkg, and no function of a private module whose own name is public;pkg.api_*namespkg.api_commit, notpkg.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 everythingpkg/__init__.pydefines (its functions, classes, methods, nested functions, and module body<module>), wherepkg.*also coverspkg.sub.user.sub_user;pkg.sub:Store.*names the methods ofStoreinpkg.sub. In aClass.attrtarget 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 ofpkg). Such a name never matches an external symbol, andunresolved = "report"counts its last name (decideofpkg:decide). A module part that names no project module is no error: the name matches nothing, whichheki checkwarns about (Entries that match nothing). Awrite-ownersorread-ownerstarget 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.attrtarget 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__cachein classParser), and a name may spell it either way:pkg.Parser.__runandpkg.Parser._Parser__run(orpkg.Parser._Parser__*) name the same method. An access is matched as Python runs it: insideParser,self.__runreaches_Parser__run; outside, a receiver typedParser, a subclass'sself, ortype[Parser]reaches it as_Parser__run. A subclass's own private name (self.__runinJsonParser, the member_JsonParser__run) is another member, and overrides nothing of its base. Withunresolved = "report", the last name of such a target counts in both spellings (__run, and_Parser__runfor a class the target names); a target without a class (__run) names the member of any class (other.__run()in classDrivercalls_Driver__run). - A contract heki cannot use is a configuration error: a target that is not
Class.attr(ormodule:nameinwrite-ownersandread-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 inallowed-protocols, an unknown group, a group inrelative-imports, or anignored-importsentry without->inimport-boundaries, or an unknown value offorbid,fresh-objects,unresolved,references,attribution,own-receiver,unlisted-dict-keys,unlisted-attributes,type-checking, orreach. - With
unresolved = "report", a contract also reports the accesses it cannot tie to a class, each under its own rule (MUT205writes,MUT206reads,MUT207calls): 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"andsubclasses = false, androllbackkeeps its ownreferences.heki check,heki inspect, andheki recommendread 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. nameandtargetsname one contract, andsourceandentry-sourcessay where one is defined, so they are errors in a defaults table. Any other key of the kind may be defaulted,failamong them:fail = truein[tool.heki.call-owners-defaults]makes the reports of everycall-ownerstable fail the run, and a table withfail = falsekeeps 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.tomlit is written without thetool.hekiprefix ([call-owners-defaults]). - A table you add to the file from
heki recommendtakes 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, andentry-sourcesmaps 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 anentry-sourcesentry 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 = truedoes not changefail-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: anerrorreport of a contract is anerrorannotation withfail = trueand awarningone 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. AMUT202report is of thereadonly-returnstables naming a producer the changed value may come from: all of them when the change reaches the producer's result itself, and only those withdeep = truewhen 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 = truein a<kind>-defaultstable applies to every table of the kind that does not setfailitself.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 inlint.fail.