Governance and baselines¶
Named groups, reasons for allowances, unused allowances, exempt decorators, included files, and baseline exclusions apply across contracts. Contracts lists every kind and the keys they share.
Named groups¶
A list that several contracts repeat can be named once in [tool.heki.groups] ([groups] in a
heki.toml). An entry @name in a list of a contract table, of a defaults table, or of another
group stands for the entries of the group, in order, at its place:
[tool.heki.groups]
parser = ["pkg.parser.*", "pkg.cli:parse"]
writers = ["@parser", "pkg.store.*"]
[[tool.heki.write-owners]]
name = "fields"
targets = ["pkg.model:Model.fields"]
allowed-writers = ["@writers"]
[[tool.heki.call-owners]]
name = "parse"
targets = ["pkg.parser:Parser.parse"]
allowed-callers = ["@parser", "tests.*"]
- The entries are written out before the tables are read, as the defaults are, so each key reads
them in its own grammar (module patterns in
import-boundaries, dotted patterns elsewhere). The configuration reports, and keys a baseline, exactly as the lists written out do:allowed-writersabove is["pkg.parser.*", "pkg.cli:parse", "pkg.store.*"]. - A group is a list of strings, or a table of them with the reason they are listed
(
{ reason = "...", entries = [...] }, below). Its entries are neither sorted nor merged: an entry listed twice stays twice. - Only a whole entry that starts with
@names a group. An@anywhere else is part of the entry, as in the item key of'pkg.model:Model.fields["[email protected]"]'. - The groups of one list write at most 10,000 entries into it. A group that names another twice doubles it, so a few lines could otherwise write out more entries than memory holds.
- Group names are shared by the main configuration file and the files it includes.
- A group that no contract uses is reported as an entry that matches nothing is.
- Errors (exit code 2), each at its file and line: an
@namethat names no group, with the chain of groups that leads to it (@a->@b->@missing); a cycle between groups (@ainband@bina, or a group that names itself), with the chain of names; an empty group, which would empty every key that uses it (and an emptyforbidden-*key means every function); groups that write more than 10,000 entries into one list; and a group name defined twice.
Reasons for allowances¶
A group written as a table holds a reason beside its entries: why the code it names may do
what the contracts using it would report.
[tool.heki.groups]
fixtures-as-user-code = { reason = "Modules that stand in for user code inside a fixture.", entries = ["tests.data.plugin:*", "tests.fixtures.loader"] }
[tool.heki.groups.legacy-writers]
reason = "Writers from before the store; remove with the old loader."
entries = ["pkg.old.load", "@fixtures-as-user-code"]
[tool.heki.write-owners-defaults]
allowance-reasons = "required"
[[tool.heki.write-owners]]
name = "fields"
targets = ["pkg.model:Model.fields"]
allowed-writers = ["@legacy-writers", "pkg.store.*"] # an error: `pkg.store.*` has no reason
- An entry's reason is the reason of the innermost group it comes through that has one: the
group that lists it, else the group that names that group, and so on. In the example,
tests.fixtures.loaderhas the reason offixtures-as-user-code, and an entry of a group without a reason thatlegacy-writersnames would have the reason oflegacy-writers. An entry written in a contract or a defaults table has none. - Every report of an entry shows its reason after its group:
entries that match nothing (
from group `legacy-writers` at pyproject.toml:6, reason "Writers from before the store; remove with the old loader."), the place a contract report points at (from group `g`, reason "..."), and the JSON ofheki recommend(reasonbesidegroupinwritten_atandentry_at). A reason of several lines is shown on one, escaped. allowance-reasons = "required"on a contract, or in its defaults table, makes every entry of its allowing keys come from a group with a reason:allowed-writers,allowed-readers,allowed-callers,allowed-imports,allowed-protocols,allowed-callees,exempt-methods,exempt-importers,ignored-imports,allow-writes,allow-reads, andexempt-writers. The other keys (targets,forbidden-*,scopes, ...) allow nothing and are written as before. The default,"optional", asks for no reason. A tableheki recommendsuggests lists its entries in the table, so under"required"move them into a group with a reason when you add it.- A reason is metadata: it changes no match, no report, and no baseline key.
- Errors (exit code 2), each at its file and line: an entry of an allowing key that comes from
no group with a reason, under
"required", at the table, defaults table, or group that writes it; a reason that is empty or only blanks; a group table with a key other thanreasonandentries. A group table withoutentriesis an empty group.
Unused allowances¶
An entry of an allowing key stays after the code it allowed is gone: a function that no longer
writes the target keeps its place in allowed-writers, and a later write there is allowed
unseen. unused-allowances on a write-owners, read-owners, call-owners,
import-boundaries, invalidation, or effect-boundaries contract, or in its
defaults table, reports each entry of its allowing keys
(allowed-writers, allowed-readers, allowed-callers, exempt-methods, allowed-protocols,
exempt-decorators, allowed-imports, exempt-importers, ignored-imports, exempt-writers,
allowed-callees, allow-writes, allow-reads) that allowed no access the contract would
report without them:
[[tool.heki.write-owners]]
name = "config-writes"
targets = ["app.Config.*"]
allowed-writers = ["app.setup.load", "app.old.migrate"] # app.old.migrate writes nothing now
unused-allowances = "error"
error: `allowed-writers` entry `app.old.migrate` of write-owners `config-writes` (from pyproject.toml:4; contract at pyproject.toml:1) allowed no access in the analyzed files
"warning"reports each entry,"error"also makes the run fail (exit code 1), and"ignore", the default, reports nothing.- An entry allowed an access when the contract stopped at it for an access of a target: the
entry names the function the access is judged in, a helper the access is handed through,
or an allowed caller of a function that only runs inside allowed functions; an
exempt-methodsentry, the method; anallowed-protocolsentry, the protocol the access goes through; anexempt-decoratorsentry, a function it exempts, as anallowed-*entry would. A caller of a function that is reported anyway allowed nothing. - An
import-boundariesentry allowed an import the contract would report with its allowing keys empty: anallowed-importsentry, a module it allows thatforbidden-importsnames or that the contract would not allow otherwise (an open import only withunresolved = "report"); anignored-importspair, an import it accepts, or a step of a walk it stops (reach), whatever lies past it; anexempt-importersentry, a module the contract would report an import of, with its allowing keys empty, if the module were not exempt. A walk that runs out of its budget counts everyallowed-importsandignored-importsentry of its contract as used. Theexempt-importersentries are judged by their own probe of each exempt importer, with a budget of its own, so a walk that ran out does not mark them: an entry is used when its probe finds something to report or runs out of its own budget, and an entry that matched nothing is still reported. - An
exempt-writersentry allowed a write that a function it names leaves unannounced on some path, or the call of an exempt writer that announces a write for a function it calls. A private helper counts whether or not its callers announce the change. - An
effect-boundariesentry allowed an effect the boundary would report with its allowing keys empty: anallow-writesorallow-readsentry, a reached write or read of the universe or the targets it names (also on an object of unknown class, withunresolved = "report"); anallowed-calleesentry, a call of the call targets, an ecosystem symbol with a forbidden effect, or a project function the search stops at that reaches anything the boundary forbids when searched with its allowing keys empty; anexempt-decoratorsentry, the same for the functions it exempts, also a scope function it exempts. A function searched that way is judged without the arguments the scope passes it, so an entry can count as used for an effect the scope's own calls never cause. - Each contract is judged by itself: a group several contracts use is judged in each that opts in, and its entry is reported for each contract it allowed nothing in.
- The report names the entry's place, its group and reason, and the contract's table, as for entries that match nothing.
- Only a run over the whole project judges: a file the paths leave out may hold the access an
entry allows. A run over some paths that cannot tell (the count of the files below the root
stops at 10,000 entries, or at one it cannot read) does not judge.
--touchedanalyzes the whole project, so an entry used outside the touched files counts as used. A contract whose rule does not run (MUT201,MUT203,MUT204,IMP201,MUT208, orEFF201left out of the selection) is not judged.--watchand the language server do not report them.
Exempting decorators¶
A decorator the project writes on its functions can exempt them from a contract
(write-owners, read-owners, call-owners, effect-boundaries, import-boundaries,
invalidation) when it states why. heki ships no decorator: the contract names the decorators
that exempt, here a pytest marker:
[[tool.heki.call-owners]]
name = "no-pytest-fail"
targets = ["pytest.fail"]
forbidden-callers = ["tests.*"]
exempt-decorators = [{ name = "pytest.mark.allow_fail", reasons = "required" }]
import pytest
@pytest.mark.allow_fail("the plugin under test calls fail")
def test_ok():
pytest.fail("x") # exempt
@pytest.mark.allow_fail
def test_bad():
pytest.fail("x") # reported; the decorator is reported too: it states no reason
- Each entry is a table:
name, the decorator as the module that defines it names it, andreasons,"required"(the default) or"optional". Under"required"a decorator states a reason when it is a call with exactly one argument, a string literal that is not blank, and no keyword. One without a reason exempts nothing from that contract and is reported (exemption-without-reason, an error, at the decorator). Under"optional"the bare decorator exempts too. - A function carries the decorator when pytest applies the marker to it: written on the
function, on a class around it (pytest applies a class's marks to its methods), or through a
pytestmark = ...of its class or module (one value, or a list or tuple of them). Only the value the body ends with counts: apytestmarkassigned under a condition, in a loop or atry, or changed after its assignment (+=) exempts nothing. A function nested in another function's body carries only its own decorators. A mark on one case (pytest.param(..., marks=...)) exempts nothing. - The decorator is resolved as any name is:
import pytest,from pytest import mark, ormark = pytest.markfollowed by@mark.allow_fail("...")all namepytest.mark.allow_fail. A decorator heki cannot resolve exempts nothing, and a name no decorator resolves to matches nothing. - The function counts as an allowed function of the contract, with the same path rules as
allowed-*: a nested scope that only runs inside it is judged with it, and a helper that only runs inside exempt functions is allowed, in another module too. - For an
effect-boundariescontract the function is an allowed callee (allowed-callees): a scope function carrying the decorator, and the scopes nested in it, are not searched, and a search does not go into a callee carrying it. Forimport-boundaries, the imports in the function's body and in the scopes nested in it are accepted. Forinvalidation, the function is an exempt writer (exempt-writers). heki check --report-suppressedlists each report a decorator hid, withdirective.kind = "decorator"at the decorator: the one on the report's function, or on the nearest function whose exemption reaches it (the exempt caller of a helper, the exempt callee of an effect boundary's scope function). The reports are found by a second analysis with everyexempt-decoratorsemptied, made only when a contract lists one.- With
lint.report-unused-suppressions,heki checkover the whole project reports each exempting decorator that hid no report of a contract listing it, and fails:
error: `pytest.mark.allow_fail` at tests/test_x.py:13:2 exempted no report of a contract that lists it (`lint.report-unused-suppressions`)
A decorator counts as used when a hidden report is in a function carrying it, in a scope
nested in one, or in a function one runs (for an effect boundary, a function running one).
--watch and the language server do not report it.
- The report of a decorator without a reason is made whatever rules run, wherever a contract
lists it under "required". Like suppression-without-code, a suppression comment cannot hide
it and a baseline can record it.
- heki inspect shows the role exempt-by-decorator of a function a contract's decorators
exempt.
- The key can be set in a defaults table, and
unused-allowances reports an entry that exempted no access.
Several configuration files¶
include in the main configuration file ([tool.heki] of a pyproject.toml, the top level of
a heki.toml) lists further TOML files of contracts, read in order:
# contracts/store.toml
[groups]
store = ["pkg.store.*"]
[write-owners-defaults]
message = "write it through the store"
[[write-owners]]
name = "fields"
targets = ["pkg.model:Model.fields"]
allowed-writers = ["@store"]
- A path is relative to the file that holds
include. It is a plain path, not a glob, so adding a file is an edit of the main file, and not a rooted or drive-prefixed one (/etc/c.toml,C:\c.toml), so the configuration reads the same in every checkout. - An included file holds contract tables, their
<kind>-defaultstables, and[groups], at its top level. Every other setting (lint,src,baseline,required-version, ...) stays in the main file, and an included file includes nothing. - The tables of a kind are the main file's, then each included file's, in the order of
include. The configuration reports, and keys a baseline, as one file holding the tables in that order. A table takes its own key, else the defaults table of its file, else the main file's. - An included file is part of the configuration:
heki check,heki inspect,heki recommend,--watch, and the language server read it, and a change to it reloads them as a change to the main file does. The pre-commit hook passes it when it is staged, and naming it in--touchedshows every report. Protect it in review as you protect the main file, for example with its ownCODEOWNERSline: a contract it drops or an entry it adds changes what heki allows. - Errors (exit code 2), each at its file and line: a file that cannot be read, a glob, a path
that is not relative, a file listed twice, the main file listed,
includein an included file, and any setting but the tables above in an included file. An error in the TOML or a value of an included file names that file.
Keeping a contract out of the baseline¶
baseline = "never" in a contract table keeps the reports of that contract out of a
baseline, for a contract that lists every allowed site in its
own allowance lists. A contract without the key, or with baseline = "allow", keeps the default:
a baseline records its reports like any other. Every kind of contract has the key.
[[tool.heki.write-owners]]
name = "generation-store"
targets = ["pkg.model.DataModel.fields"]
allowed-writers = ["Store.*"]
baseline = "never"
heki check --update-baselinewrites no entry for the reports of the contract, and says how many it left out. Without an entry, the pooled count of a baseline entry cannot let a removed, unrelated site pay for a new report of the contract.- A baseline entry that holds only reports of the contract is a configuration error:
heki check(and--update-baseline) exits with code 2 and names the entry, and the file is not changed. An entry that also holds reports of another contract is fine, and counts only those. - The reports are reported, and fail the run as they do without a baseline, whatever the baseline
holds.
--watch, the language server, andheki check --generate-promptread the baseline the same way. - A report that several contracts find stays out of the baseline when one of them has
baseline = "never". baseline = "never"in a<kind>-defaultstable applies to every table of the kind that does not setbaselineitself. Any other value is a configuration error.
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 lists them:
$ heki check
warning: `targets` entry `pkg.model.Field._gone_cache` of write-owners `field-caches` (from pyproject.toml:9; contract at pyproject.toml:7) 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, andforbid-cached-property-onofwrite-owners,read-owners, andcall-owners; thescopes,write-targets,write-universe, andallow-writesofeffect-boundaries; and thetargets,invalidators, andexempt-writersofinvalidation. - The
read-targets,call-targets, andallowed-calleesof an effect boundary, theproducersofreadonly-returns, and the keys ofimport-boundaries(importers,exempt-importers,allowed-imports,forbidden-imports,relative-imports, and both sides of anignored-importspair) may name code outside the project by its full name (os.getenv,sys.platform,<stdlib>). Their entries are judged when the first name is a module of the project (pkgofpkg.store:runorpkg.db:Session), and are not judged otherwise (sys.platform,Store.save,<stdlib>,tests.*wheretestsis not analyzed). A producer names a function, a method, or an attribute of a class. A module pattern names a module of the analyzed files or a package holding one, a namespace package without__init__.pyincluded; with a name (pkg.db:Session) it needs the module. - A
call-ownersorread-ownerstarget 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<external>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. Aread-ownerstarget without a glob that the analyzed files only call (pytest.skip) can never match, since a call reads a name only where a library__getattr__serves it: withunmatched-contract-entries = "error"it is reported as naming "no read outside the project (only calls of it, and no library__getattr__heki knows serves it)". 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. - Braces are taken first. A
{...}group without an empty alternative lists names, each judged on its own:pkg.store:Base.{a,c}ispkg.store:Base.aandpkg.store:Base.c, and the warning lists those that name nothing (pkg.store:Base.cwhen the class has noc), in one line for each kind of name they name none of (no class, no attribute of a class). A group with an empty alternative is one name with its extensions, which names something when one of them does:pkg.run:outer{,.*}whenouteror a scope inside it does, andpkg.zz{,.*}:*whenpkg.zzor a module below it does, so a namespace package without__init__.pyis not reported. - 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 (or, with a module part, a name the module imports), and one with an argument list one that takes each parameter the list names; an exempt method a method's name; a scope a module, class, or function; a class pattern a class.
- A
Class.attrentry 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 aread-ownerstarget, 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 givesupdate(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 withunmatched-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 orvars(other), also throughlist,tuple,sorted, or a copy, andobj.__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'smodel_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 thenameof each ofdataclasses.fields(obj); an attrs class's__attrs_attrs__,attrs.fields(cls), andattrs.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, and an items target (Class[*],Class["key"]) names something when a class of its family derives from a builtindict,list, orset. - 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.storeofpkg.store:*, the class ofField._*, the function ofrun.*). A holder that is a glob itself is judged by the parts written out before it:pkg.zz.*:*needs a modulepkg.zzor one below it, andpkg.*.run_*needspkg. A glob with no part written out before it (*_helper,__*__,*.run_*) 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.
- With
inherited-contract-entries = true, aClass.attrentry thatClassitself declares nothing namedattrfor (no class-body name, no attribute its methods or module set), while a project base does, is reported too, with the base:names no attribute, method, or `__dict__` key declared on `pkg.Child` in the analyzed files (declared on `Base`). A table that names the declaring class of each attribute can then check it. An entry on the declaring class, a glob, and a class that gets attributes named at run time are not reported. - A target naming a module of a namespace package (
pkg:api, with nopkg/__init__.py) names it: the package's modules are the names it holds. - 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, and a run over some paths that cannot tell (the count of the files below the root stops at 10,000 entries, or at one it cannot read) does not judge either. A file given is checked in its project, so its run judges. With the key set, every run judges the files it analyzes. - An entry written in a file
includelists, or in a group, is judged as one written in the contract (braces first, a glob holder by its written-out prefix). Each warning names where the entry is written, in a table, an included file, or a group, and where its contracts are, or the places theirsourceandentry-sourcesname:warning: `allowed-writers` entry `pkg.store.gone` of write-owners `fields` (from group `store` at contracts/store.toml:3; contract at pyproject.toml:12) names no function or method in the analyzed files. JSON output ofheki recommendgives them asentry_atandcontracts_at, and the places in the filesincludelists and in groups also aswritten_at. A group that no contract uses is reported under the same setting:warning: the group `old` (pyproject.toml:12) is used by no contract. --watchand the language server do not report them.