read-owner-violation (MUT203)¶
Family: Mutation & State (MUT) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix
Reading a guarded attribute (directly, via alias, getattr, or __dict__) outside declared read-owners.
Heuristic
This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs when its contract is declared. It has not been measured yet. See Rule Precision.
What it does¶
Checks reads of attributes that a [[tool.heki.read-owners]] contract reserves for a set of
allowed reader functions: the read side of MUT201. A read is reported when it happens outside
the allowed readers:
- directly (
ref.children), also onselfand through local aliases; - through a class object, which reads the class attribute: the class itself
(
Reference.children),clsin a class method,type(ref), or a value typedtype[Reference]/typing.Type[Reference]; - through
getattr(ref, "children"[, default])orobject.__getattribute__(ref, "children")with a constant name: a string literal or a string constant, as forMUT201; - through
ref.__dict__["children"]orref.__dict__.get("children")(also onvars(ref)), also with a string constant for the key.
A target can also name an attribute of a module outside the project by its full dotted name
(sys._getframe), or every private member outside the project (<external>._*, which leaves
out the names that are public API though they start with an underscore: dunder and sunder names
and the collections.namedtuple API). Every load of the symbol heki resolves is a read of it
(return sys._getframe, getframe = sys._getframe, from sys import _getframe at the import),
also through a project module re-exporting it, except a name loaded only to be called there,
which is a call (MUT204)
(configuration).
A target names a class and an attribute; it covers the class's subclasses too. A private
attribute (self.__secret in class Vault) is the member _Vault__secret, which a target names
Vault.__secret or Vault._Vault__secret, read inside the class as self.__secret and outside
as vault._Vault__secret. A container
entry (Class.attr["key"]) is a write target only: reading an entry reads the attribute, so a
read target names Class.attr (an entry is a configuration error).
The read object's class is the one heki infers for it, with annotations as hints: a
parameter, local, attribute, or return annotation, including the items of list[...],
Sequence[...], Iterable[...], Iterator[...], Generator[...], dict[...],
Mapping[...], tuple[...], and set[...], and a type alias naming one (Models: TypeAlias =
list[Model]); a constructor call; and what the object comes
from: a loop over such a container (for model in models), a subscript (models[0],
by_name["a"]), unpacking (model, _ = pair), dict views and get / pop, enumerate,
zip, reversed, sorted, iter, next, list / tuple / set, itertools.chain, a
display, the items appended to a local list, or a comprehension or generator expression. A
method call or a @property / cached_property read has the return annotation of the
definition the receiver's class finds first along its MRO, as for a type checker (typing.Self
is the receiver's class); a copy (copy.copy, copy.deepcopy, dataclasses.replace,
model_copy) has its original's class, calling a functools.partial object returns what the
wrapped function returns, and typing.cast names the class of its value, its type read as
an annotation (cast(list[Model], x) as cast("list[Model]", x)): a cast to a subclass narrows
a value known as its base, and a cast to Any or to a base class keeps the class the value is
known to have, as an annotated local does. A variable rebound in a loop
(node = node.parent) or assigned on some paths only (a walrus inside and / or) has the
classes of the values reaching it; a value of two or three classes (Model | Node, from an
annotation or from different assignments) is each of them, and an isinstance check narrows it
in the code it guards (if isinstance(x, Model): ..., if not isinstance(x, Model): return,
also inside and / or). A value typed with a project Protocol is an instance of the project
classes that implement it structurally (having every member it defines; at most eight, counting
a class and not its subclasses), but a read of a member the protocol declares is judged by the
protocol, the type the code reads it through: it reads the protocol's member, not the
implementations' (def f(h: Host): h._m reads Host._m when Host declares _m), and a
private method of an implementation called through the protocol keeps its own reads instead of
handing them to the caller (also when other callers call it through the class and take them
over). An object whose class heki cannot see (an unannotated parameter or return, Any, a
value of more than three classes) is not tied to the target.
A private helper (_name, or a comprehension, generator expression, or lambda scope) with
project callers hands the responsibility to its callers: the read is reported at every call
site of the first non-private callers above it, with the chain of calls as related
information. Reading a @property or functools.cached_property attribute calls its getter,
so a private getter (ref._kids returning self.children) hands its read to the functions
reading it. Reads in a class's own initializer on its own self are allowed, and so are reads
in a function that only runs inside allowed contexts (every path of callers above it starts in
an allowed reader or an exempt method), as for MUT201. One report stands for every read behind
its call (sites in JSON), as for MUT201, and a read matching several targets of one contract
is one report, under the target configured first, naming the others. A read runs where the body holding it runs, as for
MUT201: a generator's reads where it is iterated, a coroutine's where it is awaited.
With attribution = "lexical", a read is judged in the function whose code holds it instead: a
private helper reports its reads itself, and a function that only runs inside allowed readers is
reported too. A lambda, comprehension, or generator expression is part of the function it is
written in. A class's own initialization still allows a read, through the helpers it passes
self to too (a helper whose every path of project callers starts in an initializer handing it
its own self).
With own-receiver = "allow", a read through the receiver of the method it is judged in is
allowed: the function reported (with attribution = "lexical", the function holding the read)
is a method that is no static method, and the object the member is looked up on may be its first
parameter (self._seen, cls._kind, obj._seen with obj = self if flag else peer), also for
a member the class inherits. Another parameter, an attribute of the receiver, and a nested
def, lambda, or comprehension using the enclosing method's self stay reported.
With allowed-protocols, a read through a value typed with a project protocol the key names that
declares the attribute, itself or through its protocol bases, is allowed wherever it is judged; a
read through another protocol or the implementation's class stays reported. A pattern names the
subprotocols of the protocols it matches too, unless protocol-subclasses = false.
The help starts with the contract's message and then names up to three allowed readers that
read the member the report names themselves: public functions and methods an allowed-readers
pattern names (with forbidden-readers, every function outside them), by fully qualified name
(allowed readers of `Reference.children`: `pkg.index.GenerationIndex.children_of`). Private
functions (_name), special methods, and the exempt methods do not count. JSON output gives them
with their files as allowed_examples (fqn, path).
What a report states¶
A report states that the function reads a target of a read-owners contract outside the contract's
read owners, directly, through an alias, getattr, or __dict__, or through the helpers shown.
Its premises:
- Target: the object is an instance of a class the contract names, or of a subclass, or the class object of one, by construction or annotation (assumption R2). Open: an alias bound on one path is enough.
- Outside the owners: the function is not in the allowed modules and classes, nor runs only
inside allowed contexts (with
attribution = "lexical": the function holding the read is not allowed, nor runs only inside a class's own initialization; withown-receiver = "allow", the read object is not the receiver of the method judging it). Established from the contract. - Through helpers: a helper's write, read, or call counts at its caller (never with
attribution = "lexical"). Open: one path of the helper is enough.
Why is this bad?¶
Some state is only meaningful through the component that maintains it: an index that keeps a derived view consistent, a store that resolves references lazily. Reading the raw attribute elsewhere sees stale or partial data, and the bug only shows up for some inputs. The contract states which functions may read it once in configuration, with no runtime cost.
Example¶
[[tool.heki.read-owners]]
name = "reference-children"
targets = ["Reference.children"]
allowed-readers = ["*GenerationIndex*"]
message = "read children through GenerationIndex instead"
class Reference:
def __init__(self) -> None:
self.children: list["Reference"] = []
class GenerationIndex:
def children_of(self, ref: Reference) -> list[Reference]:
return list(ref.children) # allowed reader
def _kids(ref: Reference) -> list[Reference]:
return ref.children
def render(ref: Reference) -> str:
return ", ".join(map(str, _kids(ref))) # MUT203: reads `Reference.children` via `_kids`
Use instead:
def render(ref: Reference, index: GenerationIndex) -> str:
return ", ".join(map(str, index.children_of(ref)))
Fix safety¶
No automatic fix.
Options¶
[[tool.heki.read-owners]]:name: the contract name, shown in messages.targets:Class.attrentries; globs and dotted suffixes match. An entry can also name attributes of modules outside the project by their full name (sys._getframe), or<external>.<name>for the members of every module and class outside the project.allowed-readers: functions allowed to read the targets, as dotted names or globs matched against the function's qualified name and itsClass.methodqualname.forbidden-readers: when set, only reads by these functions are reported (matched likeallowed-readers;forbidden-readers = ["pkg.parser.*"]: the parser layer must not read the targets);allowed-readersandexempt-methodsstay exceptions inside them. A read is in scope when the reporting function or a private helper it hands the read through is forbidden.exempt-methods: methods allowed to read the targets (__repr__,__deepcopy__); a plain name matches any function or method of that name, an entry with a dot or a glob is matched likeallowed-readers.message: the help of every report of the contract.unresolved:"ignore"(default) or"report": also report the reads the contract cannot tie to a class, underMUT206. A function some code hands on as a value (a display, a class attribute, an argument, a return:HANDLERS = [helper],REQUIRE = staticmethod(helper)) has callers heki does not see: with"report", it judges its reads itself, as if it had no callers.attribution:"call-graph"(default) or"lexical": whether a private helper hands its reads to its callers and a function that only runs inside allowed readers is allowed, or each read is judged in the function holding it.own-receiver:"report"(default) or"allow": whether a read through the receiver of the method it is judged in (self,cls,super()) is allowed.allowed-protocols: project protocols (class patterns, their subclasses included): a read through a value typed with one that declares the attribute, itself or through its protocol bases, is allowed, also through a class object typedtype[P]of one (MUT206).protocol-subclasses:true(default) orfalse: whether anallowed-protocolspattern names the subprotocols of the protocols it matches, or those protocols only.
Known limitation: a read through a parameter without a project-class annotation
(def helper(ref): return ref.children) is not seen, since the read object's class is unknown
there; unlike a write, a read is not handed to the caller that knows it. With
unresolved = "report", MUT206 reports it.