Ownership contracts¶
An owner contract protects its targets and lists who may write, read, or call them.
readonly-returns protects the results every caller shares, and invalidation names the writes
that must be announced. Contracts lists every kind and the keys they share.
write-owners¶
[[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, Class.attr["key"] for one entry of the container an attribute holds, or Class[*] / Class["key"] for the items of the instances of a class deriving from a builtin dict, list, or set (below). An entry can also name the names of a module's namespace (pkg.api:run, below) and attributes of modules and classes outside the project (sys.stdin, sys.modules["pkg.*"], pathlib.Path.*, below). |
allowed-writers |
[] |
Functions allowed to write the targets. |
allowed-writers-marked-by |
[] |
Function patterns, as allowed-writers takes them. With this or allowed-writers-decorated-by, heki check over the whole project reports an allowed-writers entry that names no function one of them marks, with the entries that match nothing: only store operations can be allowed writers. See Restricting the allowed writers. |
allowed-writers-decorated-by |
[] |
Decorators that mark the functions allowed-writers may name, written as exempt-decorators entries are (the object the decorator is bound to, pkg.store.store_operation). See Restricting the allowed writers. |
forbidden-writers |
[] |
When set, only writes by these functions are reported: see 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. |
fail |
false |
true: the reports of this contract make heki check (and --watch) exit with code 1, whatever their tier and severity; see Failing on a contract. |
baseline |
"allow" |
"never": a baseline holds none of the reports of this contract; see Keeping a contract out of the baseline. |
allowance-reasons |
"optional" |
"required": every entry of allowed-writers, exempt-methods, and allowed-protocols comes from a group with a reason; see Reasons for allowances. |
unused-allowances |
"ignore" |
"warning" or "error": heki check over the whole project reports each entry of allowed-writers, exempt-methods, allowed-protocols, and exempt-decorators that allowed no write; see Unused allowances. |
exempt-decorators |
[] |
Decorators ({ name = "pytest.mark.allow_fail", reasons = "required" }) that exempt the functions they mark when they state a reason; see Exempting decorators. |
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. |
attribution |
"call-graph" |
"call-graph" or "lexical": which function a write is judged in. See 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. |
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. |
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). |
include-overrides |
false |
true: an entry naming a method (Class.method, module:Class.method) in allowed-writers, forbidden-writers, and the exempt-methods patterns also names the methods of that name in the project subclasses of Class. See Allowed and forbidden functions. |
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). |
unlisted-attributes |
"ignore" |
"ignore", "report", or "inventory": whether an attribute of a target's class that no write-owners target names is reported when it is written (any write but a __dict__ key, which is unlisted-dict-keys's); with unresolved = "report", also on an object of unknown class (MUT205). "inventory" also reports the attributes the class body declares and the class's own initializers set. |
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)writingfield.extras[key]or changing it in place, 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.
Items of a container class¶
A target Class[*] names the items of the instances of a project class deriving from a builtin
dict, list, or set (or from a standard-library class deriving from one, such as
collections.defaultdict), and Class["key"] the entry of one constant key. Class["key"] is an
items target when Class has no dot or names a project class; otherwise it is Class.attr["key"].
[[tool.heki.write-owners]]
name = "imports"
targets = ["pkg.imports.Imports[*]"]
allowed-writers = ["pkg.imports.Imports.*"]
They match an item store or deletion (imports["typing"] = s, del imports["sys"]), a mutating
method the class inherits (imports.setdefault("os", set()), pop, update, clear, add,
append, ...), and a change in place of an item (imports["typing"].add("Any"), also of the
entry setdefault returns), as for the entries of an attribute's container. An instance an
attribute holds counts too: model.imports["k"] = v writes Model.imports and the items of
Imports. A helper handed the instance writes them at the call, also when it is handed the
attribute (fill(model.imports) writes Model.imports and the items). The class's own methods
are writers like any other. When a project __setitem__ or __delitem__ along the class's MRO
replaces the store or the deletion, the caller's imports["k"] = v runs that method, whose own
writes (super().__setitem__(key, value)) are judged in it. Reading an item is no write, also
when the read of a missing key inserts one (the default of a defaultdict): a __missing__ the
class defines is a method like the others, so the stores in its body are judged in it. A change
An in-place operator the class inherits from its builtin base changes the items too
(imports |= other, names += more, -=, &=, ^= on a set), also when the instance is
stored back to an attribute (model.imports |= other); a class defining the in-place method runs
it, as for __setitem__. An item stored or deleted with the subscript syntax on a value heki
cannot type (box["k"] = v, del box["k"], box["k"] += v, also holder.imports["k"] = v) may
be one of the items: with unresolved = "report" it is MUT205 and a boundary's
unresolved-writes, unless every caller hands the value as an instance of a known class, where
MUT201 reports the call. A method named like a container's on such a value (box.update(x),
box["k"].add(v), session.add(obj)) is not tied to the items. A change of an item a loop over
the instance itself steps to (for row in rows: row.append(x)) is not followed.
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. An attribute write on an entry of a project class
(model.fields[0].name = v with fields: list[Field]) is a write of that class's attribute
(Field.name), judged by its own contracts, also in a helper handed the container
(rename_all(model.fields)); on an entry heki ties to no project class, a helper handed the
container writes the target.
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; calling the class runs its__init__, which may keep the object (below); - nothing can hold it yet: no store,
yield, closure, or call that may keep it ran before the write, except a store into another new object that links the two (below).
New objects stored in one another stay new: an attribute store of a new object into another
object the function made, of a class whose attribute write runs no code (no __setattr__,
property, or other descriptor of the name, no metaclass other than type or abc.ABCMeta, and
no mapping of class keywords heki cannot read, which may pass one; for a pydantic model, no
model_config, Config, or class keyword on any class the object may be, since
validate_assignment runs the model's validators), links the holder to the object it stores
(copied, part = Node(), Node(); part.parent = copied; copied.flag = True constructs copied).
Links are directed: keeping an object keeps what it holds, through any number of links, but not
the objects that hold it. With only part.parent = copied, storing part anywhere else,
yielding it, capturing it, or handing it to a call that may keep it ends the freshness of both,
while storing copied ends only copied's. Keeping a value read out of an object keeps what
that object holds, as the value may be one of them: an attribute, an item, an iteration step,
what a call over it returns, what a lookup with it as the key returns unless the lookup is a
builtin type's own (a project __getitem__ may return its key), and what an operator over it
returns unless the result holds nothing: a bool, number, or string that object's or a
builtin type's own special methods give (-part.count, part.count < 3, not part.flag,
f"{part.parent!r}"). -part may run a Node.__neg__ returning self.parent, and
(part,) + () is a tuple holding part, so old.append(part.parent), old.append(-part),
and old.append((part,) + ()) end copied's freshness, as does a helper handed part, which
may store what it reads out of it. A project function's result that holds itself through the
objects it links (made.part = part; part.parent = made) is new at a call until a value read
out of it is stored. A store into an object the function did not make, or into one of its own
that was kept before, still ends the freshness of what it stores.
Calling a project class keeps of the new object what the __init__ the call runs keeps of
self: that of the first class along the MRO defining one, and each one it reaches through
super().__init__(), in any module. One storing self anywhere but in an attribute of self
(REGISTRY.append(self)), or handing it to a helper that keeps it, makes an object another part
of the program holds, as the same store in the function would; one handing it to a helper that
only stores attributes on it keeps nothing. An __init__ of a class outside the project (a
pydantic model's, a dataclass's) keeps nothing of the object itself; two things it runs are not
followed yet: a property setter run by an attribute store, and a project __post_init__ or
model_post_init a generated initializer calls (#601). No construction gives a new object when the
class may return an existing instance (an Enum, a __new__), has a metaclass other than
type or abc.ABCMeta or a base heki names no class for, or runs an __init__ a decorator
replaces or the project rebinds outside the class body (Base.__init__ = other in any module).
A container a class's constructor makes for each instance is held by that instance, so storing a new
object into it links the two the same way: copied = Node(); copied.children.append(part) leaves
part new while copied is (append, appendleft, insert, add, setdefault, and item
stores other than slice stores, which iterate what they store, on a list, set, or dict, when they
run no project code on what they store). The constructor
is the project __init__ the class runs, its own or a base's (no class decorator,
__init_subclass__, dataclass_transform, or metaclass other than type or abc.ABCMeta along
the MRO, and no code that reading the attribute runs), and it binds the attribute once, on every
path to its return, to a list, dict, or set display or list(), dict(), set(), or
bytearray() (no star import of its module may bind the name, nor super). It uses self only to store attributes (none of __dict__ and __class__) and to
call super().__init__(...), whose __init__ along the MRO does the same or is object's, and
no store in them runs code (a property's setter, a descriptor, __setattr__): a call handed
self or a member of it, such as self.setup(), may hand the container anywhere. The object must
be one the function made by calling the class on every path.
Rebinding the attribute before an object is stored into the list (copied.children = node.children
on some path, setattr(copied, name, v), a write through copied.__dict__, vars(copied),
getattr(copied, "__dict__"), or object.__getattribute__(copied, "__dict__"), or a helper handed
copied), or keeping the list, ends the freshness of what is stored into it. A project function
returning such an object does not carry the fact to its callers.
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:
[[tool.heki.write-owners]]
name = "bookkeeping"
targets = ["pkg.model.Field._derived_from", "pkg.model.Field._seen_*"]
allowed-writers = ["*"]
With unlisted-attributes = "report", MUT201 likewise reports an attribute of an object of a
class a target covers that no target covering the class names, in any write-owners contract:
rebinding or deleting it (field.alias = v, del field.alias), setattr with a constant name,
and changing its container in place (field.tags.append(v)). The contract's allowance, the
class's own initialization, and fresh-objects apply as to a target write. A __dict__ key is
unlisted-dict-keys's, and the items of an instance are no attribute.
With unlisted-attributes = "inventory", a project that keeps one table of every attribute of
its contract classes can check the table is complete: MUT201 also reports
- an attribute the body of a class a target covers declares, with a value or without
(
seed: int = 0,seed = 0,seed: int), at the declaration, as a write of the class body judged by the contract's allowance (a class body belongs to the function running the class statement, so the module's functions are not allowed writers by being in the module); - an attribute the class's own initializers (
__init__,__post_init__,__new__, ...) set onself, also through a helper they handselfto, which"report"and a target write leave out as the class's own initialization.
A class covered by the targets includes its subclasses, whose own declarations count; a base
class the targets do not cover is not inventoried. Methods and nested classes, dunder names
(__slots__), an attribute some target of any contract names, and writes by allowed writers are
not reported. Writes of an object the writer just built (fresh-objects) stay allowed.
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 naming an attribute (writing an attribute stores no item, so noClass[*]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 passesselfto; - with
unlisted-attributes = "report", likewise an attribute written on an object of unknown class that no target names for some class the contract's targets cover.
read-owners¶
[[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"), hasattr(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 read-targets, 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, and a private method of an implementation called through the protocol keeps what it
reads and calls. It is also an access of a target C.m when heki lists the project classes
implementing the protocol, there is at least one, and every one of them is C or a subclass of
C: with Impl the one class implementing Host, h._m reads Impl._m. A call through the
protocol also needs every method it may run to be a target, as a call through a base class
does. A protocol that a class outside the target's family implements too gives no report, as a
value typed with a base class of the family gives none, and neither does a protocol no project
class implements. A protocol whose implementations heki cannot list (more than eight) leaves the
access to unresolved = "report" (MUT206, MUT207). An access matching Impl._m and a
Host._m target of the same contract is one report, named by the target configured first, and
allowed-callees naming every method a call through the protocol may run allows it, as naming
the declaration does. A static or class method the protocol declares, called through such a
value (h.build()), is judged the same way as an instance method: the receiver tells the
protocol. 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, type(h) of a value
typed with it included (see How contracts report).
| Key | Default | Meaning |
|---|---|---|
name |
"" |
The contract's name in reports. |
targets |
[] |
Class.attr attributes. A container entry (Class.attr["key"]) and the items of a class (Class[*]) are write targets only, and a configuration error here. An entry can also name the names of a module's namespace (pkg.api:LIMIT, below) and attributes of modules outside the project (below). |
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. |
fail |
false |
true: the reports of this contract make heki check (and --watch) exit with code 1, whatever their tier and severity; see Failing on a contract. |
baseline |
"allow" |
"never": a baseline holds none of the reports of this contract; see Keeping a contract out of the baseline. |
allowance-reasons |
"optional" |
"required": every entry of allowed-readers, exempt-methods, and allowed-protocols comes from a group with a reason; see Reasons for allowances. |
unused-allowances |
"ignore" |
"warning" or "error": heki check over the whole project reports each entry of allowed-readers, exempt-methods, allowed-protocols, and exempt-decorators that allowed no read; see Unused allowances. |
exempt-decorators |
[] |
Decorators ({ name = "pytest.mark.allow_fail", reasons = "required" }) that exempt the functions they mark when they state a reason; see Exempting decorators. |
unresolved |
"ignore" |
"ignore" or "report": whether the reads of a target's attribute name on an object of unknown class are reported under MUT206. A target ending in a glob (Context._*) matches only the names a class it names, or a project subclass, has from project code (below). |
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. |
include-overrides |
false |
As in write-owners, for allowed-readers, forbidden-readers, and the exempt-methods patterns. |
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¶
[[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 by raising it (raise Error, and the cause of raise ... from Error, which Python calls with no arguments), 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), builtins.str.split("#"), below), and * with an argument list names every call passing its constants, whatever it calls (*(module="pkg.backend.*"), *(0="#")). <any>.split("#") names the calls written as calls of the attribute split on any receiver (below). A target with a module part (pkg:Kind, pkg:*) also names the names the module imports, read or called through the module object (pkg.Kind.A, below). An entry can also name functions and classes outside the project (below). |
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. |
fail |
false |
true: the reports of this contract make heki check (and --watch) exit with code 1, whatever their tier and severity; see Failing on a contract. |
baseline |
"allow" |
"never": a baseline holds none of the reports of this contract; see Keeping a contract out of the baseline. |
allowance-reasons |
"optional" |
"required": every entry of allowed-callers, exempt-methods, and allowed-protocols comes from a group with a reason; see Reasons for allowances. |
unused-allowances |
"ignore" |
"warning" or "error": heki check over the whole project reports each entry of allowed-callers, exempt-methods, allowed-protocols, and exempt-decorators that allowed no call; see Unused allowances. |
exempt-decorators |
[] |
Decorators ({ name = "pytest.mark.allow_fail", reasons = "required" }) that exempt the functions they mark when they state a reason; see Exempting decorators. |
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. A target ending in a glob matches only the names a class it names, or a project subclass, has from project code (below). |
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. |
include-overrides |
false |
As in write-owners, for allowed-callers, forbidden-callers, and the exempt-methods patterns (the targets cover the overrides of a Class.method target always). |
- A call is reported only when every function it may call (each candidate in the class
hierarchy) is a target:
text.replace(...)on astris never a call ofDataType.replace_reference. - Bound-method aliases (
replace = dt.replace_reference) andgetattr(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 ofpkg.core.aby the targetpkg.core.cis reported unlessallowed-callersnamesc). - With
references = "calls", a target handed on is reported where it is named ("fhands onpkg.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. Raising a class, or naming it as the cause ofraise ... from, constructs it: a call, not a reference. A use that only names it is no reference: an argument ofisinstance,issubclass, another builtin that only inspects its arguments (print,getattr,type),super,typing.cast,typing.TypeVar,typing.NewType, orcontextlib.suppress; anexceptclause, 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 ofnamethat pass each value:"DataType(is_dict=True)",'container_flags(kind="dict")'. An entry can name a position instead of a parameter,position=value(0="#", the receiver of a method not counted), or be a bare value, which names the next position ('builtins.str.split("#")'is'builtins.str.split(0="#")'); bare values come first, as in a call. A position is the parameter the callee's signature has there where heki knows it (a project function, or a library function whose typeshed stubs declare its positional parameters), so a constant passed by position and one passed by keyword to that parameter match the same target:'builtins.str.split("#")'and'builtins.str.split(sep="#")'both matchtext.split("#"),text.split(sep="#"), andstr.split(text, "#")withtext: str. Where heki knows no signature, a position is the one written; positions past the named parameters count on into*args(print("#")passes"#"at position 0). A value isTrue,False,None, an integer, or a string in single or double quotes (no escapes). A string holding*,?,[, or{is a glob matched against the whole string constant passed, dots included:'make(module="pkg.backend.*")'matches"pkg.backend.dataclass". Write one of these characters in brackets to match it literally ([*],[?],[[],[{]):'make(module="pkg[*]")'matches"pkg*"only. 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'sFinalname, or a module's number or boolean bound once, asEFF101evaluates 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 itglobal, in another module-level store, or withdel, 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 onlyTrue,False,None,0, or""(heki keeps defaults by class and truthiness). A keyword binds as Python binds it: never a positional-only parameter (withdef f(kind=False, /, **kwargs),f(kind=True)leaveskindfalse), 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 | bof 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 afunctools.partialobject 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: aftermake = partial(DataType, is_dict=True),make()constructsDataType(is_dict=True), reported atmake(), where the class is constructed (a call unpacking a mapping with**over keywords the object holds is not followed). Afunctools.partialobject read from a table, a module global, or a class attribute passes the constants it holds the same way. A pydantic model'smodel_constructpasses its keywords to the fields,model_validatethe entries of the dict it is passed, andmodel_copythose ofupdate. A call that raisesTypeErrorinstead 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. An entry can also name values beyond one constant:key=<dynamic>matches a value heki cannot bound (a variable, a call such asmax(depth, 3),depth + 2, or constants that differ between the paths building a**mapping or between the functions the call may run),key>n,key>=n,key<n, andkey<=nan integer constant on that side ofn, andkey!=a,bevery constant but these (constants or string globs, up to the next keyed entry):targets = ["*(stacklevel>2)", "*(stacklevel=<dynamic>)"]reportswarnings.warn("x", stacklevel=3),stacklevel=max(depth, 3), andstacklevel=depth + 2. An integer expression the code fixes (LEVEL + 1of literals and the module's integer constants, with+,-,*) is its value for every entry. A comparison or an exclusion judges constants only, and none of these matches a call passing nothing for the key, a default heki cannot decide, or a constant of another kind (a float). A target with an argument list naming a function outside the project binds its arguments as the stubs declare the function's positional parameters (a keyword naming a positional-only one binds nothing, and a method called through its class takes its receiver first); without such a declaration, by keyword and by the position written.unresolved = "report"matches its last name before the list, whatever the arguments of a call on an object of unknown class. *followed by an argument list names every call passing its constants, whatever it calls:targets = ['*(module="pkg.backend.*")']reportsfactory(module=BACKEND)for a parameterfactory,loader.build(module=BACKEND)on an object of unknown class, anddict(module=BACKEND), withBACKEND = "pkg.backend.dataclass", whateverunresolvedsays, andMUT207leaves the target out. A call of project code passes its constants as above. A call heki binds to no project function or class (a function or class outside the project, or a value of unknown class) passes the constants it writes as keywords, or as entries of a**mapping the function builds (factory(**{"module": BACKEND})), and at the positions it writes them; a library function whose stubs declare its positional parameters binds them as above (*(sep="#")and*(0="#")matchtext.split("#")). heki cannot tell which parameter a default binds there. No function is part of the operation such a target guards, so the functions making the calls may not make them unlessallowed-callersnames them.<any>.followed by one attribute name, with or without an argument list, names the calls written as calls of that attribute (obj.split(...)), whatever the receiver is:targets = ['<any>.split("#")']reportsreference.split("#")for areferencetypedstr, untyped, typedAny, an attribute of anAnyvalue, an instance of a project class with or without asplitmethod, and a module object (tools.split("#")afterfrom pkg import tools), whateverunresolvedsays, andMUT207leaves the target out. The match is made at the call, with no resolution of the receiver; the constants are bound as for*above (by the project function or the stubs where heki binds the call, else as written:sepofstr.partitionis positional-only, so<any>.partition(sep="#")matches only a keyword on a receiver heki cannot type). A call not written as a call of the attribute is no match: a function called by its name (split("#")),getattr(obj, "split")("#"), or a name bound to the method (cut = obj.split; cut("#")).<any>.splitwithout a list names every call ofsplit. As for*, no function is part of the operation such a target guards.<any>names calls only: in the targets ofread-ownersorwrite-owners, or in any other form (<any>.a.b, a glob after it), it is a configuration error.- An argument list naming a parameter that no function or class the target names takes (no
parameter of the name and no
**kwargs; a class may take a name it declares, and one whose initializer is not project code any keyword) matches no call, since the call raisesTypeError:lint.unmatched-contract-entrieswarns about it ("names no function, method, or class takingkind"). - A target with a module part also names the names that module binds to definitions of other
modules (
from pkg.enums import Kindinpkg), read or called through the module object, judged at the access, not at the definition the name resolves to:targets = ["pkg:Kind"]withreferences = "reads"reportspkg.Kind.Aafterimport pkg.fmt(which bindspkg) androot.Kind(1)afterimport pkg as root, andpkg:*every such name ofpkg. An import of the name (from pkg import Kind,from pkg.enums import Kind) and its uses are judged at the definition, which the target does not name, and so is a submodule read through its package (pkg.fmt.X). A target without a module part (pkg.Kind) names only definitions. - With
references = "calls-and-bases", a class statement passing a class target as a base is reported too ("<module>subclassespkg.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 (withsubclasses = false, the class itself only); a keyword (metaclass=Base) is no base. A class target outside the project counts as a base too: a class statement naming it (class T(unittest.TestCase)), or, unlesssubclasses = false, a project class deriving from it in any module (class T(Base)withclass Base(unittest.TestCase)). A base heki cannot name (a parameter) stays open. - With
references = "reads", everything"calls-and-bases"counts is reported as before, and every other use of a target's value is reported too ("freadspkg.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, orwithvalue, a dict display's key, the class of a class pattern (case Keys():), the types of anexceptclause an exception may reach, a decorator, a default of a function or lambda, a keyword of a class statement, and the cause ofraise ... fromthat heki does not tie to a class, 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 (atypestatement's value, the bounds and defaults of type parameters), an import, a name bound to the target by itself in a function (a local, anonlocalcell), whose own uses count, and a value nothing uses (Keysas an expression statement). A class body or a module binding a name to the target is a read of it (model_type = Keys,Alias = Keys), because the uses of a class attribute or a global are not all followed back to the target. 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 unlesssubclasses = false; an instance of the class is no read of it.
Names of a module's namespace¶
A read-owners or write-owners target module:name, whose name has no dot, names a name the
module's namespace binds: a global, a function, a class, an imported name, or a submodule bound
on its package. pkg.api:* names every name of pkg.api, and the module part may be a glob
(pkg.*:LIMIT).
[[tool.heki.read-owners]]
name = "limit"
targets = ["pkg.api:LIMIT"]
forbidden-readers = ["tests.*"]
[[tool.heki.write-owners]]
name = "no-patching"
targets = ["pkg.api:run"]
forbidden-writers = ["tests.*"]
- A read is
pkg.api.LIMIT,getattr(module, "LIMIT"),hasattr,vars(module)["LIMIT"], ormodule.__dict__["LIMIT"], through any value heki knows holds the module (import pkg.api,import pkg.api as api,from pkg import api), judged at that module. An import of the name (from pkg.api import LIMIT, at the import, in the function or the module body running it) and each load of the name the import binds in the importing module are reads too, judged at the module defining the name, which the import's re-exports lead to, ascall-ownersjudges an imported name. A name loaded only to be called there (run(),pkg.api.run()) is a call, not a read, and the module's own code using its names reads none. - A write is an assignment,
del,setattr,delattr, or a store or deletion through the module's namespace (vars(module)["run"] = f) through such a value, and a store ordelin a function that declares the nameglobal. The module body binding its own names defines them and writes none, as a class's own initialization does. - A store through an object heki cannot type (
def patch(m): m.run = g) isMUT205withunresolved = "report", and a readMUT206, as for attributes: a written-out name (run) counts there, and a glob (pkg.api:*) names no member of an object of unknown class. - A report names the target as configured (
pkg.api:run), or for a glob the name accessed (pkg.api.run). The rest of the contract applies as for attributes: the allowed and forbidden functions, the exempt methods,attribution, and the reports of private helpers at their callers.own-receiverandfresh-objectsallow none of these accesses. - A target naming no name the analyzed modules bind is an unmatched entry (Entries that match nothing).
Patch calls¶
A call that replaces an attribute or an item for a test writes what it replaces, as the
assignment it stands for does, for write-owners and an effect boundary's writes-targets:
def test_run(monkeypatch, mocker):
monkeypatch.setattr(api, "run", fake) # writes pkg.api:run
monkeypatch.setattr("pkg.api.run", fake) # the same
mocker.patch.object(api.Client, "send") # writes pkg.api.Client.send
monkeypatch.setitem(sys.modules, "pkg.api", m) # writes sys.modules["pkg.api"]
monkeypatch.setenv("DEBUG", "1") # writes os.environ["DEBUG"]
@mock.patch("pkg.api.run") # writes pkg.api:run in test_other
def test_other(run): ...
- The calls are pytest's
monkeypatch.setattr,delattr,setitem,delitem,setenv, anddelenv,unittest.mock.patch,patch.object,patch.dict, andpatch.multiple, and pytest-mock'smocker.patch,mocker.patch.object,mocker.patch.dict,mocker.patch.multiple, andmocker.spy.delattr,delitem, anddelenvare deletions,patch.dictchanges the container's items in place, andsetenvanddelenvwrite the entry ofos.environthey name, assetitem(os.environ, ...)anddelitem(os.environ, ...)do. - An argument passed by keyword counts as the one in its position
(
mock.patch(target="pkg.api.run"),monkeypatch.setattr(pkg.api, name="run", value=f),monkeypatch.setenv(name="DEBUG", value="1")). patch.dict(d, values)stores items intodas a subscript store does: into a namespace (vars(obj),obj.__dict__,vars(module)), the names the keys ofvaluesand the keywords give; into a container of unknown class, items heki cannot tie (an unresolved write).- A dotted string names its object by the longest prefix that is a module of the project, then
attributes, as pytest and
mockresolve it:"pkg.api.run"is therunofpkg.api, and"pkg.api.Client.send"the class attributesendofpkg.api.Client. A string whose prefixes are no project module names an object outside the project as written ("requests.sessions.Session.request"). mockeris typed where the project declares thepytest-mockdistribution (or annotates the parameterpytest_mock.MockerFixture); without either,mocker.patch.object(obj, "name")has no known receiver and writes nothing.- A patcher of
unittest.mockused in awithwrites where thewithruns; one used as a decorator writes in the function it decorates.mocker.patch*writes where it is called. - A patch heki cannot tie to a target (an object of unknown class, a computed name, a string
with a part heki cannot read) is an unresolved write:
MUT205withunresolved = "report". - The allowed and forbidden writers,
fresh-objects, and the exemptions apply as for every write. Contracts read patch calls; the inferred types do not yet, so a report in production code that depends on a name a test patches stays, where an assignment of the name in the test makes it unprovable.
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. The targets of write-owners name the
attributes of modules and classes outside the project by full name too:
[[tool.heki.call-owners]]
name = "no-private-calls"
targets = ["pkg.*._*", "<external>._*"]
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._getframematches a call ofsys._getframe, also throughfrom 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._*), and an argument list the calls passing its constants ('os.getenv("HOME")'). A dotted suffix (_getframe), a leading glob (*._getframe), or a module part names project code only. A leading glob names project definitions by their qualified names (*.splitnamespkg.refs.splitandpkg.refs.Cutter.split), and<any>.splitthe attributesplitcalled on any receiver (call targets). <external>.<name>names the members of every module and class outside the project whose last name<name>matches:<external>._*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_replaceofcollections.namedtuple, the names ruff'sflake8-selfdoes not report either. A name written out (<external>._replace) matches as written.<external>takes one name after it; any other spelling is a configuration error.- A
write-ownerstarget counts an assignment,del,setattr, anddelattrof the attribute through the module or class object (sys.stdin = f,pathlib.Path.home = g;pathlib.Path.*names every attribute of the class), not through an instance of the class. An entry target (sys.modules["pkg.*"],os.environ["DEBUG"]) counts a change of an entry under a constant key its key glob matches: a store or deletion (sys.modules["pkg.api"] = m,del sys.modules[KEY]), andpop,setdefault, and the patch calls naming the key (monkeypatch.setenv("DEBUG", "1")). A target without a key (sys.modules,os.environ) counts every change of the container in place, as aClass.attrtarget counts the changes of the container the attribute holds: these, a store under a computed key, and the container's in-place methods (os.environ.update(...),pop,setdefault,clear,popitem,|=,sys.path.append(d)), through the module attribute, an alias of it, or a name imported from it (from os import environ). A copy (os.environ.copy()) is another container. - A
call-ownerstarget counts the calls of the symbol, aread-ownerstarget 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, assys._getframe(1)is. A name a library object serves through__getattr__(heki's catalog,[[getattr_objects]]:pytest.mark, whoseMarkGeneratormakes a mark for any name not starting with an underscore) is read wherever it is loaded, also where it is called:@pytest.mark.skip(reason="x")and@mark.skipif(...)(from pytest import mark) readpytest.mark.skipandpytest.mark.skipif, which the hook makes, and the decorator call is a call of them too. A reference handing an outside symbol on is no call of it, whateverreferencessays; with"calls-and-bases"or"reads", a class statement naming a class outside the project among its bases, directly or through a project class, subclasses it, as for project targets. - A library name the catalog knows as another name of a class is that class:
pytest.fail.Exceptionis_pytest.outcomes.Failed(alsopytest.skip.Exception,pytest.xfail.Exception,pytest.exit.Exception), so a target names the class, andraise pytest.fail.Exception("x")calls_pytest.outcomes.Failed. - 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. Withunresolved = "report", an<external>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 andown-receiverallow 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 thecall-ownerstargets) 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 writesMUT205counts: 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:
[[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 |
- Which keys need a function's nested scopes named:
scopesandallowed-calleesof an effect boundary name a function, class, or module and everything nested in it:pkg.run:outercoversouter.<locals>.inner, andouter{,.*}adds nothing.allowed-writers,allowed-readers,allowed-callers,forbidden-*,exempt-methods, and theinvalidationfunctions name the functions they match and no others. Withattribution = "call-graph"(the default) a lambda, a comprehension, a generator expression, and a nesteddefthat only runs inside the function are judged where the function is, soallowed-*namingoutercovers them; a nesteddefthat is handed on (returned, stored, passed) is a function of its own and needs its own entry, andforbidden-*names only the functions it matches. Withattribution = "lexical"a lambda, comprehension, or generator expression still belongs to its function, and every nesteddefis judged by itself.targetsname the function, method, or class they match; a nested function is a target only where an entry names it.
So outer{,.*} is needed in allowed-* and forbidden-* only for nested defs that
attribution does not attribute to outer, and in targets for nested definitions.
- With include-overrides = true on a contract (or in its defaults table),
an entry naming a method, Class.method or module:Class.method, in the keys that name places
or callees (allowed-*, forbidden-*, the exempt-methods patterns, an effect boundary's
scopes and allowed-callees, and the invalidators and exempt-writers of invalidation)
also names the methods of that name in the project subclasses of Class, in any module: the
family a call-owners target Class.method covers. Where the key covers nested scopes
(scopes, allowed-callees, or an entry ending in {,.*}), the overrides' nested scopes count too. A private
name (Base.__run) names the method of Base only: a subclass's __run is its own. The
reports are those of the same contract listing every override by hand, so the key is off by
default: it widens what a contract allows, and a new subclass's override is allowed without a
change of the configuration, which a project using the configuration as a review wall should
know. An entry still has to name a method of Class itself, and is judged as before (Entries that
match nothing): an allowed-callees entry only when its first name
is a module of the project, as that section says.
[[tool.heki.call-owners]]
name = "hook"
targets = ["pkg.store:Store.op"]
allowed-callers = ["pkg.hooks:Base.hook{,.*}"] # and every override of `hook`, nested scopes included
include-overrides = true
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.
- A whole module is allowed with module:*: in allowed-writers, allowed-readers, and
allowed-callers it names every function of the module and its body (<module>). An
import-boundaries contract takes modules in exempt-importers, and
per-file-ignores turns a rule off for files across every
contract.
readonly-returns¶
[[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. |
fail |
false |
true: the reports of this contract make heki check (and --watch) exit with code 1, whatever their tier and severity; see Failing on a contract. |
baseline |
"allow" |
"never": a baseline holds none of the reports of this contract; see Keeping a contract out of the baseline. |
- Functions decorated with
@lru_cache/@cacheare protected without configuration, also through an import alias, but not acachedecorator 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¶
[[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. |
include-overrides |
false |
true: an invalidators or exempt-writers entry naming a method (Class.method, module:Class.method) also names the methods of that name in the project subclasses of Class. See Allowed and forbidden functions. |
message |
none | The help of every report of the contract. |
fail |
false |
true: the reports of this contract make heki check (and --watch) exit with code 1, whatever their tier and severity; see Failing on a contract. |
baseline |
"allow" |
"never": a baseline holds none of the reports of this contract; see Keeping a contract out of the baseline. |
unused-allowances |
"ignore" |
"warning" or "error": heki check over the whole project reports each entry of exempt-writers and exempt-decorators that let no write go unannounced; see Unused allowances. |
exempt-decorators |
[] |
Decorators ({ name = "pytest.mark.allow_fail", reasons = "required" }) that exempt the functions they mark when they state a reason: they are exempt writers; see Exempting decorators. |
allowance-reasons |
"optional" |
"required": every entry of exempt-writers comes from a group with a reason; see Reasons for allowances. |
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.
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 ownself: directly, throughsuper().__init__(), or through helpers it passesselfto. - A nested scope uses the parameters of the functions enclosing it. A comprehension,
generator expression, lambda, or nested
defreading 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__writingself.importsis 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. - An operation calls the special method it runs. On an instance of a project class, an
operation that looks one method up on the operand's class calls it: a truth test (
if x:,not x,bool(x)) calls__bool__, or__len__when the class has no__bool__;len(x)calls__len__;incalls the container's__contains__when its class defines one; a comparison calls the left operand's method (a < b:a.__lt__;!=calls__eq__when the class has no__ne__); a subscript calls__getitem__,__setitem__, or__delitem__; andwithcalls__enter__and__exit__. A value that may be one of several classes makes one call of the methods they run. A value stored on the instance calls nothing, and neither does an operation on a class object (its metaclass's method) or on a value of unknown class. Effect boundaries follow these calls too. Not followed: iteration (for, comprehensions, unpacking,list(x), andinon a class without__contains__), the reflected method of a comparison's right operand, operators, f-strings, andasync with. - 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 (<module>for a class at module level), and a nesteddefa function of its own; the parameters of the function a lambda, comprehension, or generator expression reads are the function's, wherever it runs. Forwrite-owners, a call handing a typed object to a helper that changes it without knowing its class is the caller's write. Withunresolved = "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 passesselfto included when every path of project callers above the helper starts in such an initialization; so doexempt-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 withattribution = "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 itsself(_count(self)) is judged at the method, and is allowed with it, and so are a comprehension, generator expression, lambda, or private nesteddefthe method runs that uses itsself; a public nesteddefreports itself, as a public helper does. Withattribution = "lexical", a lambda, comprehension, or generator expression using the method'sselfis allowed wherever it runs, and a nesteddefis judged by itself, as any helper is.allowed-protocolsallows 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 thatreferencescounts (return h._helper). So is one through a class object typedtype[P]of such a protocol (a parameter, a local, or an attribute annotated so:cls._items_constraints(obj)withcls: type[KeywordsHost]; ortype(h)of a valuehtyped with the protocol, whichever class implementing it heki takes it for), and one through a protocol whose implementations heki cannot list, also where heki cannot tie the object to a class (MUT205,MUT206,MUT207):allowed-protocols = ["*Host"]allowsparser._flagwithparser: RenderHostandclass RenderHost(RuntimeFlags, Protocol)whenRuntimeFlagsdeclares_flag, while the same read throughflags: RuntimeFlagsstays reported. Withprotocol-subclasses = false, a pattern names the protocols it matches only, not their subprotocols: withclass RuntimeExpressionFlags(GraphBuilderHost, Protocol),allowed-protocols = ["*Host"]allows the accesses throughGraphBuilderHost, and those throughRuntimeExpressionFlagsstay judged, also of the members it inherits fromGraphBuilderHost. 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 ownselfto 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 (anallowed-*pattern names them, or theforbidden-*patterns leave them out; forinvalidation, the functions announcing every write of the target on every path and theexempt-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 asallowed_examples(fqn,path).
Restricting the allowed writers¶
An allowed-writers entry that names a function or method that exists passes whatever the
function is. A project whose writers must be its store operations says so with
allowed-writers-marked-by (function patterns) and allowed-writers-decorated-by (decorators):
[[tool.heki.write-owners]]
name = "generation-store"
targets = ["pkg.model.DataModel.fields"]
allowed-writers = ["pkg.store.GenerationStore.set_fields", "pkg.store.GenerationStore.model_key"]
allowed-writers-marked-by = ["pkg.store.GenerationStore.set_*"]
allowed-writers-decorated-by = ["pkg.store.store_operation"]
heki check over the whole project then reports each entry that names no marked function
(names no function or method marked by ...), with the entries that match nothing, at the severity of
unmatched-contract-entries. An entry naming several functions passes when one of them is marked, and
an entry that names a class or a glob is judged by the functions it matches. A decorator is
resolved as in exempt-decorators: the object it is bound to, which a project function
imported where it is used gives (pkg.store.store_operation). A decorator defined in the
module of the functions it marks marks nothing there, as for exempt-decorators: put it in a
module of its own. The keys judge the entries only; the writes are judged by allowed-writers
as before.