call-owner-violation (MUT204)¶
Family: Mutation & State (MUT) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix
Calling a guarded function or method, or constructing a guarded class (directly, via a bound method, getattr, or a helper), outside declared call-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 calls of functions and methods, and constructions of classes, that a
[[tool.heki.call-owners]] contract reserves for a set of allowed callers: the call side of
MUT201 (who may write) and MUT203 (who may read). A call is reported when it happens outside
the allowed callers and resolves to a target:
- a method called on an instance of the target's class or of a subclass, including an override of
the method in a subclass (
data_type.replace_reference(ref)); - the same method through a bound-method alias (
replace = data_type.replace_reference, thenreplace(ref)) orgetattr(data_type, "replace_reference")(...)with a constant name; - a module-level function (
pkg.util.reset_cache()); - a class: constructing it or a subclass (
FinalFacts(...),pkg.facts.FinalFacts(...),cls(...)in a class method, a value typedtype[FinalFacts]ortyping.Type[FinalFacts],type(facts)(...)), also for a dataclass or another class without an__init__of its own, through afunctools.partialobject holding the class (make = partial(FinalFacts), thenmake(), reported atmake()), and through a library method building an instance of its receiver's class without its__init__(a pydantic model'sFinalFacts.model_construct(...),FinalFacts.model_validate({...})of a dict,facts.model_copy(...)); withsubclasses = false, constructing exactly the class; - what a property returns, called (
self.data_type(is_dict=True)with a propertydata_typereturningtype[DataType]constructsDataType): the value the getter's return annotation names is called, and the getter runs as reading the property does; - what a name bound to the target holds, called: a class attribute bound once to it
(
factory = FinalFactsorrun = staticmethod(reset_cache), thenself.factory(),cls.factory(), orParser.factory()), an entry of a module-level table of functions (HANDLERS["reset"]()), and a module a function returns (_ops().reset_cache()of a function returning the module it imports); - a private method by the name Python's name mangling gives it (
parser._Parser__run()withparser: Parser,Parser._Parser__run(p),self._Parser__run()in a subclass): a target names itParser.__runorParser._Parser__run. A subclass's own__runis another method (_JsonParser__run), no override of the target; - a function or class outside the project a target names by its full dotted name
(
sys._getframe), or every private member outside the project (<external>._*, leaving out the names that are public API though they start with an underscore: dunder and sunder names and thecollections.namedtupleAPI): a call heki resolves to the symbol, also throughfrom sys import _getframe, an alias, or a project module re-exporting it (configuration). A reference handing such a symbol on is no call of it; aread-ownerstarget counts it as a read.
A target ending in an argument list names only the calls passing those constants:
DataType(is_dict=True) is DataType(is_dict=True), not DataType(is_list=True), and
container_flags(kind="dict") is container_flags(dt, "dict"), not container_flags(dt, "list").
A call passes a constant when heki establishes it: the argument is a literal, a string constant
bound once (a module's Final name), or a module's number or boolean bound once (LIMIT = 0),
read by name, through an import (also a function's own), or as an attribute of the module
(settings.LIMIT), and unless the importing module binds the name again (a global store or
del in a function, another module-level store, a star import); passed by keyword, 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 True, False, None, 0, or "" and the value. A keyword
binds as Python binds it: never a positional-only parameter, and one naming no parameter passes its
value under its name into **kwargs; the receiver is the 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 (DataType(**{"is_dict": True}),
flags = {"is_dict": True} then DataType(**flags)); a merge ({**a, **b}, dict(a, k=v),
a | b of 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 one built on several paths
(flags = a if c else b), which passes a key where every path passes the same constant for it.
Calling a functools.partial object the function makes passes what the object holds first (its
positions, and its keywords, which a keyword of the call replaces), then the call's arguments; a
call unpacking a mapping over keywords the object holds is not followed. A pydantic model's
model_construct passes its keywords to the fields, model_validate the entries of the dict it
is passed, and model_copy those of update. A call that
raises TypeError instead of running the function (two keywords of one name, a parameter bound by a
position, or the receiver, and a keyword, a keyword without **kwargs to land in, a position past
the parameters without *args, a parameter without a default left unbound where no * unpacking or
** unpacking of another mapping may bind it) passes nothing. A variable, a call result, *
unpacking, ** unpacking of another mapping, or a position of a class without a project __init__
establishes nothing, and the call is not reported. A reference passes nothing, so it never matches
such a target.
With references = "calls" (or "calls-and-bases" or "reads"), a reference handing a target on to be
called later counts as a call of it, reported where the target is named ("f hands on pkg.core.decide"; a name an import or
the module body binds is read in the scope binding it without a position of its own, so it is
reported there at the statement handing it on): passed to a call
(partial(decide), register(self.decide), field(default_factory=Rule)), stored in an
attribute, an item, or a global, returned, yielded, raised, or held by a display that is
([decide], {"a": decide}), also through an import alias (from pkg.core import decide as
chosen), a module alias (run = core.decide), or a module attribute (core.decide). A use that
only names a class is no reference: an argument of isinstance, issubclass, another builtin that
only inspects its arguments (print, getattr, type), super, typing.TypeVar,
typing.NewType, or contextlib.suppress, and the type a typing.cast names (the value it hands
back is the value itself: register(cast(Callable[[int], int], decide)) hands decide on); an except clause, a class's bases and keywords, a
function's defaults and annotations; a subscript (Optional[Rule]), a comparison (f is decide), a
receiver (Rule.of(...)), and a module binding another name to it. A callable a builtin calls once
per item (sorted(xs, key=decide), map(decide, xs)) is a call already, and so is the
functools.partial object handed to one. A call or a reference in a class body (a class
attribute's value, a method's decorator or default argument) counts for the function running the
class statement (<module> for a class at module level, a nested class's included); a method's own
body is the method's. A class body, a function, a
lambda, or a comprehension nested in a function names what the function binds to a name it reads
(a local import), at the name.
With references = "calls-and-bases", a class statement naming a class target among its bases
counts too ("<module> subclasses pkg.core.Base"): the class it makes holds the base, and
constructing it runs the base's initialization unless it overrides it. A base is a positional
argument of the class statement whose value is the class where the statement runs (Base,
core.Base, Base[int], also through an import alias, a local alias, or a closure cell holding
it; a parameter, a local, or a class-body name of the imported class's name is another value),
matched as a construction is, so a base that is a subclass of the target counts unless
subclasses = false; a keyword (metaclass=Base) is no base. It is reported at the base where
the statement loads it, and at the class statement for a name an import or the module body
binds, for the function running the class statement (a nested class: the function running the
outer one).
With references = "reads", everything "calls-and-bases" counts is reported as before, and every
other use of a target's value counts too ("build reads pkg.core.Keys"), reported where it is
named as a hand-on is: the object of an attribute access 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)), a subscript or its index (tuple[Keys, int]), an
operand (f is decide), a tested condition, an iterated, awaited, formatted, or with value, a
dict display's key, the class of a class pattern (case Keys():), the types of an except clause
an exception may reach, a decorator, a default of a function or lambda, a keyword of a class
statement, and the cause of raise ... from, also through copies and the displays holding it.
No read: a call, an annotation, evaluated or not (list[Keys]), the values Python evaluates only
when asked (a type statement's value, the bounds and defaults of type parameters), an import, a
name bound to the target by itself (Alias = Keys), whose own uses count, and a value nothing
uses. A load handing a target on is reported as a hand-on only, and a read is matched as a
construction is.
A call through a value typed with a project Protocol that declares the method is judged by the
protocol's declaration (h._helper() with h: Host calls Host._helper), not by the
implementations it runs, and what an implementation's private method calls inside stays with it
(also when other callers call the method through the class and take its calls over).
A target's last segment names the function, method, or class: a glob there matches within that
name only (pkg.*._* is every private member in pkg, not every function of a private module,
and pkg.api_* is pkg.api_commit, not pkg.api_helpers.api_reset), and the report names the
function the call reaches.
A call is reported only when every function it may call is a target: when the receiver's class
hierarchy also offers a method that is no target (a receiver typed with a base class whose own
replace_reference is not guarded), the call is not reported. The functions it may call can be
targets of different entries of one contract: with A.reset and B.reset both listed, obj.reset()
on obj: Base, whose subclasses A and B implement reset, is one report for
A.reset|B.reset. A call every function of which several targets of one contract name
(A.reset and reset for a.reset() on a: A) is one report too, under the target configured
first, naming the others ((alsoreset)). A call on a receiver whose class heki does not know (an unannotated
parameter, Any) is not seen; with unresolved = "report",
MUT207 reports it.
A private helper (_name, or a comprehension, generator expression, or lambda scope) with project
callers hands its calls to its callers (with unresolved = "report", not one that some code also
hands on as a value, which has callers heki does not see): the call is reported at the call sites of the first
non-private callers, with the chain of calls down to the call as related information. A call runs
where the body holding it runs, as for MUT201: a generator's calls where it is iterated (a
generator an allowed caller creates and returns calls outside it when its caller iterates it), a
coroutine's where it is awaited. Not reported either:
- a function that only runs inside allowed callers: it has project callers, and every path of
callers above it starts in an allowed caller, an exempt method, or a class's own
initialization (as for
MUT201); - a class's own initialization: an initializer (
__init__,__post_init__, ...) of a class of the target's family calling a guarded method on its ownself, or handing it on withreferences = "calls", directly or through a private helper (for a target naming no class,reset, the family is the classes defining the methods it names and their subclasses); - a target calling a target of the same contract (
remove_referencecallingself.replace_reference(None), an override callingsuper().replace_reference(...)): the guarded operation is checked where it is called, so what it does inside is part of it. Withtargets-call-each-other = "report"a target is allowed to call itself only, and a call of another target is judged as a one-target contract would judge it.
With attribution = "lexical", a call is judged in the function whose code holds it instead: a
private helper reports its calls itself, and a function that only runs inside allowed callers
is reported too. A lambda, comprehension, or generator expression is part of the function it is
written in (any(decide() for x in xs) in an allowed function is allowed), and a nested def
is a function of its own. A class's own initialization, 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), and the targets calling each other stay allowed.
With own-receiver = "allow", a call through the receiver of the method it is judged in is
allowed: the function reported (with attribution = "lexical", the function holding the call) is
a method that is no static method, and the object the called method is looked up on may be its
first parameter (self._label(), cls._kind(), super()._label(), self._norm(x) of a static
method, Resolver._label(self)), also for a method the class inherits. A static method called
through its class (Resolver._norm(x)), a call on another parameter, and a nested def, lambda,
or comprehension calling through the enclosing method's self stay reported.
With allowed-protocols, a call through a value typed with a project protocol the key names that
declares the method, itself or through its protocol bases, is allowed wherever it is judged, and so
is a reference handing the method on through such a value (return h._helper with references);
a call 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 callers that
make the call the report names themselves: public functions and methods an allowed-callers
pattern names (with forbidden-callers, every function outside them), by fully qualified name
(allowed callers of `DataType.replace_reference`: `pkg.store.GenerationStore.replace_ref`).
A reference handing a target on, the targets calling each other, 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 calls a function or method, or constructs a class, that a
call-owners contract reserves, outside the contract's call owners; with references = "calls",
that it hands one on; with references = "calls-and-bases", also that it subclasses one; with
references = "reads", also that it reads one.
Its premises:
- Target: the receiver or the callee 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). A subclass derives from the class through bases named where their class statements run: a parameter, a local, or a closure cell of the class's name is another class. 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 call is not allowed, nor runs only inside a class's own initialization; withown-receiver = "allow", the receiver is not the one 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. - Hands on (
references = "calls"): the value named is the target, and it reaches, through copies and displays, an argument, a store, areturn, ayield, or araise. Open: a value merged from several paths is enough. Whether the code it is handed to calls it is not part of the claim. - Subclasses (
references = "calls-and-bases"): the value the class statement passes as a base is the target class, typed where the statement runs. Established: a base heki cannot type (a parameter, a call's result, a value merged from paths that disagree) is no match. Whether the subclass is constructed is not part of the claim. - Reads (
references = "reads"): the value named is the target, and it reaches, through copies and displays, a use other than a call, a hand-on, a binding of another name, or an annotation. Open: a value merged from several paths is enough. What the use does with the target (whether a test of a display holding it looks at it) is not part of the claim. - Arguments (a target with an argument list): the call binds each parameter the list names to
its constant, as Python binds the call. Established: an argument heki cannot tell is no match,
a mapping built on several paths passes a key only where every path passes the same constant
(as every function the call may run must agree), and a call that raises
TypeErrorinstead of running the function binds nothing. Not followed: a mapping or afunctools.partialobject the function does not build itself through copies (a parameter, an attribute, a call's result, one chosen on several paths), a mapping something changes in place, a key computed at run time, and a pydantic model'smodel_validateof a value not established to be a dict.
Why is this bad?¶
Some operations keep invariants only when one component runs them: a store that updates its
indexes after redirecting a reference, a factory that builds a sealed object exactly once. A
direct call from elsewhere skips the bookkeeping, and nothing fails until an input exercises the
stale state. A linter cannot tell data_type.replace_reference(ref) from text.replace("a", "b")
without the receiver's class, and an import rule cannot forbid a method of an object the caller
legitimately imports. The contract states the ownership once in configuration.
Example¶
[[tool.heki.call-owners]]
name = "reference-mutators"
targets = ["DataType.replace_reference", "FinalFacts"]
allowed-callers = ["pkg.store.GenerationStore.*"]
message = "use a GenerationStore operation instead"
# pkg/store.py
class GenerationStore:
def replace_data_type_ref(self, data_type: DataType, ref: Reference) -> None:
data_type.replace_reference(ref) # allowed caller
def swap(data_type: DataType, ref: Reference) -> None:
data_type.replace_reference(ref) # MUT204: outside `pkg.store.GenerationStore.*`
def rename(text: str) -> str:
return text.replace("a", "b") # not reported: a `str`, not a `DataType`
Use instead:
def swap(store: GenerationStore, data_type: DataType, ref: Reference) -> None:
store.replace_data_type_ref(data_type, ref)
Fix safety¶
No automatic fix.
Options¶
[[tool.heki.call-owners]]:name: the contract name, shown in messages.targets: functions, methods, or classes, as dotted names or globs matched against the fully qualified name and any dotted suffix (DataType.replace_reference,pkg.util.reset_cache,FinalFacts,Parser._*). AClass.methodtarget covers the method's overrides in subclasses; a class target covers constructing the class and its subclasses; a target naming no class (reset) covers every project function and method of that name. A target may end in an argument list ofparameter=valueentries (DataType(is_dict=True)), each valueTrue,False,None, an integer, or a quoted string. A target can also name functions and classes outside the project by their full name (sys._getframe,os._*), or<external>.<name>for the members of every module and class outside the project.allowed-callers: functions allowed to call the targets, as dotted names or globs matched against the function's qualified name and itsClass.methodqualname (pkg.store.*). A module part names one module without its submodules:pkg:*allows whatpkg/__init__.pydefines, notpkg.sub.user.sub_user.forbidden-callers: when set, only calls by these functions are reported (matched likeallowed-callers);allowed-callersandexempt-methodsstay exceptions inside them. A call is in scope when the reporting function or one of the private helpers it hands the call through is forbidden (forbidden-callers = ["pkg.parser.*"]: the parser layer must not call the targets).exempt-methods: methods allowed to call the targets (__deepcopy__); a plain name matches any function or method of that name, an entry with a dot or a glob is matched likeallowed-callers.message: the help of every report of the contract.unresolved:"ignore"(default) or"report": also report the calls the contract cannot tie to a class, underMUT207. 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 calls itself, as if it had no callers.references:"ignore"(default),"calls","calls-and-bases", or"reads": a reference handing a target on to be called later counts as a call of it, with"calls-and-bases"a class statement naming a class target among its bases too, and with"reads"every other use of a target's value as well.attribution:"call-graph"(default) or"lexical": whether a private helper hands its calls to its callers and a function that only runs inside allowed callers is allowed, or each call is judged in the function holding it.own-receiver:"report"(default) or"allow": whether a call through the receiver of the method it is judged in (self,cls,super()) is allowed.targets-call-each-other:"allow"(default) or"report": whether a target may call the other targets of the contract. With"report", each target is judged like the one target of a contract with the same keys, so a 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()onobj: BasewithA.resetandB.resetlisted) is judged once for each target it may reach, with only that target guarded, and is reported when any of those judgements reports it.allowed-protocols: project protocols (class patterns, their subclasses included): a call through a value typed with one that declares the method, itself or through its protocol bases, is allowed, also through a class object typedtype[P]of one (MUT207).protocol-subclasses:true(default) orfalse: whether anallowed-protocolspattern names the subprotocols of the protocols it matches, or those protocols only.