effect-boundary-violation (EFF201)¶
Family: Execution Effects (EFF) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix
Reaching a forbidden effect (directly or through calls) from a declared effect-boundaries scope.
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 the functions of a declared effect boundary ([[tool.heki.effect-boundaries]]): they
must not reach a forbidden effect, directly or through the functions they call. Reading a
@property or functools.cached_property attribute of a project class calls its getter; a
property that also defines a setter or deleter is not followed, so its setter's writes never
count for a read.
scopesselect the checked functions. A pattern names a module (pkg.domain,pkg.domain.*), a class (pkg.Renderer), or a function (*.render); every function defined inside a matched name is in scope, nested functions included. Patterns are matched against the function's qualified name, its qualname, and every dotted prefix of them, sorenderalso selects a module namedrender. A module body (<module>, what runs when the module is imported) is checked only where a pattern names<module>itself:pkg.gen:<module>,pkg.*:<module>,pkg.gen.<module>, or<module>for every module. A pattern naming the module (pkg.*,pkg.gen:*) does not cover its body. The body is searched as a function is, and the bodies of its classes, which run with it, count for what they take from outside the project (reads-environment, and the externalcall-targetsandread-targets); their other effects (calls of project functions, blocking calls, writes and reads of target attributes) do not count.forbidlists the forbidden effects:blocking-net,blocking-db,blocking-fs,blocking-subprocess,blocking-sync,sleep, orblockingfor all six: blocking calls of the ecosystem knowledge base (requests.get,sqlite3,open,subprocess.run,time.sleep, ...);writes-targets: writes to theClass.attrentries ofwrite-targets(and their subclasses), or to one entry of the container an attribute holds (Class.attr["key"]), in every formMUT201follows, through the receivers whose classMUT201sees (the items of annotated containers included); a class's own initialization is no write (constructing a fresh object runs its__init__): what an initializer writes on its ownself, itself or through the helpers it passesselfto (_link(self),self._init_fields(),super().__init__()), while the same helper writing another object, or called after__init__returned, writes an existing one; neither is a write that constructs the object it writes (fresh-objects = "allow", the default: a write the reached function makes to an object it allocated, or to the object a parameter holds when every call reaching it hands it a new object nothing kept yet), as forMUT201;reads-targets: reads of theClass.attrentries ofread-targets(and their subclasses), in every formMUT203follows (obj.attr,getattr(obj, "attr"),obj.__dict__["attr"]orvars(obj)["attr"], a property getter that reads it); a class's own initialization reading its instance, itself or through such a helper, is no read. An entry also names an attribute of a module outside the project by its full dotted name (sys.platform), read assys.platformor throughfrom sys import platform;calls: calls of thecall-targetsentries, matched as the targets ofMUT204: a function, a method (with its overrides in subclasses, through bound-method aliases andgetattrwith a constant name), or a class (constructing it); a call is one only when every function it may call is a target. An entry with an argument list names only the calls passing its constants, as forMUT204. An entry also names a function or class outside the project by its full dotted name (os.getenv,platform.*), or every private member outside the project (<external>._*, as forMUT204); a dotted suffix, a leading glob, a module part, or an argument list does not. Withreferences = "calls", a reached function handing a target on to be called later (passed, stored, returned, yielded, raised, or held by such a display) counts too, as forMUT204("renderhands onpkg.core.decide"), with"calls-and-bases"a class statement naming a class target among its bases ("rendersubclassespkg.core.Rule"), and with"reads"every other use of a target's value ("renderreadspkg.core.Keys");reads-environment: reading the environment the program runs in: a call or a module attribute read the ecosystem catalog tagsenvironment(os.getenv,platform.system,importlib.util.find_spec,os.environ,sys.platform,sys.version_info, ...), and, withimport-probes = "report", animportinside atrywith anexceptclause namingImportErrororModuleNotFoundError. A call ofimportlib.import_moduleorimportlib.util.find_specthat imports a module of the project reads no environment: every text its name may hold names a project module ("pkg.config", a module constant), or starts with a project package and a dot (f"pkg.parser.{name}","pkg.parser." + name), and the packages along the name lead the import to the project's module, or under the package to the project's directories alone: a package whose__path__a module of the project changes (__path__.append(d),pkgutil.extend_path,__path__ = [d]), or whose__init__heki cannot read, may lead it to an installed module. A relative name is anchored atpackage(a text, or the module's own__package__or__name__). Inside atrythat takes anImportError, such a call still counts;mutates-params: mutating a parameter, its attributes, or its contents, also an object it holds as an item or an element (p["k"].append(x),for row in p: row.clear()), directly or through a shallow copy of it (dict(p)["k"].append(x)), unless the function gave that item a new object first. For a method, parameter 0 isself, so a method writingself.xmutates a parameter.write-universewithallow-writesstates the writes a scope may make positively: a reached write of awrite-universeentry that noallow-writesentry names is reported, in every formwrites-targetsfollows.allow-writesalso exempts writes fromwrite-targetsin the same boundary. Withoutallow-writes, the boundary allows no write of the universe.- An entry target (
Class.attr["key"], inwrite-targets,write-universe, orallow-writes) also matches the writes a store operation makes with the key a call passes it:set_extra(field, "init", v), whereset_extrawritesfield.extras[key], writesField.extras["init"], through any number of functions passing the key on, also as aFinalconstant. An item write whose key heki cannot tell (a key the function computes, a parameter of the scope function, or an argument that is neither) is reported where the boundary names an entry of the attribute and allows no write of the whole container (allow-writes = ["Field.extras"]): "writes an entry ofField.extrasunder a key heki cannot tell".
Each scope function is searched breadth first over the project call graph, so the reported chain is a shortest one. The search does not enter:
allowed-callees(project functions or ecosystem symbols, matched likescopes): their effects are allowed, also when a helper hands them a field it was given (helper(model.fields)writes nothing whenhelperonly passesfieldsto an allowed callee that changes it). A method changing its ownselfin place, called on a field's value (model.bag.add(x)), changes the field at the call, asMUT201counts it, also when it is an allowed callee;- other functions of the scopes: each reports its own violations, so a violation is reported once, at the boundary, not again by every scope function above it;
async deffunctions called withoutawait(calling one only creates a coroutine), and generators that are not iterated (calling a generator function only creates the generator; its body is searched where it is iterated, as forEFF101, and a generator a function returns where the object it returns is iterated);- functions an offloading decorator or API runs on another thread (
@sync_to_async,asyncio.to_thread(f), ...).
A call or a read outside the project counts only when heki resolves it to the name: through imports and aliases of the module, never by an attribute name computed at run time or on an object of unknown origin.
Unlike EFF101, the search does not read the callees' guards: a reached function's effects
count whatever its arguments are, so __repr__ calling save(text, io.StringIO()) reaches the
open that save runs only for a path.
A violation is reported once per scope function and forbidden effect (or write, read, or call
target; a write-universe write once per written Class.attr; every environment read of
reads-environment together), at the call in the scope function that starts the shortest chain
(or at the blocking call, write, read, call, or import itself),
with the chain as related information; mutates-params is reported at the function's
definition. The report counts every distinct site of that kind the scope function reaches
(sites in JSON; for mutates-params, every change of a parameter, in the body making it), so
a Ratchet baseline sees a second blocking call, write, or parameter change below a recorded
report.
With unresolved = "report", the boundary also reports what it cannot judge in the reach: a call
heki resolves to no function (HANDLERS[kind](...) on a table something changes, a parameter
called), a function it does not model (eval, a body too large) or whose body only a stub
declares, and a write of an attribute write-targets or write-universe names on an object of
unknown class or under a name computed at run time (thing.required = True of an unannotated
thing, setattr(thing, name, v)); a class's own initialization is none, so constructing an
object whose initializer runs setattr(self, name, v), itself or in a helper it hands self to,
is not reported. Each kind is reported once per scope function, at the call
in the scope function starting the shortest chain to the first one, with the chain; calls and
writes inside allowed-callees are not followed. Without it, the boundary is silent where heki
cannot see, so no report does not mean the scope stays inside the boundary.
allow-writes is only as precise as heki's view of which object each write changes. A write
heki cannot tell apart from a write of the pass's input is reported: state that a property
getter writes while rendering, or a store operation whose writes depend on its arguments. A
write that constructs the object it writes is not (fresh-objects = "allow"). Treat its
reports as candidates to review, or narrow the universe, rather than gating on it.
What a report states¶
A report states that a function of a declared effect boundary reaches a forbidden effect, directly or through the calls shown.
Its premises:
- In scope: the function matches the boundary's
scopes, or a scope names the module body as<module>. Established. - Resolves: each call on the chain is to the function shown, through the calls heki resolves. Open through a method call: one candidate implementation that leads on is enough.
- Reaches: each function on the chain reaches the next call. Open: one path is enough, and the rule reads no branch at all: a call under any test counts.
- Forbidden effect: the last call has an effect
forbidlists, as the ecosystem catalog or the boundary's own entries describe it; or the last function makes the call, the read, or the import probeforbidlists. Established for a read and an import probe: the module attribute is named through the module's imports, and theexceptclause names the import error. For a call importing a module, open: the module is not established to be the project's. Withreferences = "calls", a target handed on is one forcalls: the value is the target, and it reaches a use handing it on. Established; whether the code it is handed to calls it is not part of the claim. With"calls-and-bases", so is a class statement passing a class target as a base, typed where the statement runs; whether the subclass is constructed is not part of the claim. With"reads", so is any other use of the target's value, as forMUT204; what the use does with it is not part of the claim. For an item write, the entry is the one the key names: a constant in the function, or the constant a call on the chain passes for the key. Established. A write under a key heki cannot tell may change another entry. Open.
Why is this bad?¶
Some parts of a code base promise to be pure: rendering a model must not mutate it, domain code must not do network I/O, a hot path must not sleep. The promise usually breaks several calls away from the function that makes it, where a reviewer does not look. The boundary states it once in configuration and checks every path.
Example¶
[[tool.heki.effect-boundaries]]
name = "pure-render"
scopes = ["*.render"]
forbid = ["blocking", "writes-targets"]
write-targets = ["DataModel.fields"]
allowed-callees = ["pkg.cache.*"]
message = "render entry points must not mutate model state"
import requests
def get_json(url: str) -> dict:
return requests.get(url).json()
class Model:
def render(self) -> str:
data = get_json("https://example.com") # EFF201: reaches `requests.get`
return str(data)
Use instead:
class Model:
def render(self, data: dict) -> str:
return str(data) # the caller fetches `data` before rendering
Fix safety¶
No automatic fix.
Options¶
[[tool.heki.effect-boundaries]]:name: the boundary name, used in messages and in the diagnostic target (pure-render:blocking_net,pure-render:DataModel.fieldsfor a write,pure-render:reads:DataModel.fields,pure-render:calls:GenerationStore.*,pure-render:reads-environment,pure-render:mutates-params), so a read and a write of one field are two reports.scopes: modules, classes, or functions (dotted names or globs).forbid:blocking-net,blocking-db,blocking-fs,blocking-subprocess,blocking-sync,sleep,blocking,mutates-params,writes-targets,reads-targets,calls,reads-environment.write-targets:Class.attrentries forwrites-targets(required with it).read-targets:Class.attrentries forreads-targets(required with it), or attributes of modules outside the project by their full name.call-targets: functions, methods, or classes forcalls(required with it), as for thetargetsof[[tool.heki.call-owners]](also with an argument list,DataType(is_dict=True)), or functions and classes outside the project by their full name.write-universe:Class.attrentries whose reached writes are reported unlessallow-writesnames them; the diagnostic target is the entry, with a glob attribute replaced by the written one (pass:DataModel.fieldsforDataModel.*).allow-writes:Class.attrwrites the boundary allows (needswrite-universe).fresh-objects:"allow"(default) or"report": whether writes that construct the object they write count, as for[[tool.heki.write-owners]].unresolved:"ignore"(default) or"report": whether what the boundary cannot judge in the reach is reported (diagnostic targetschecks:unresolved-calls,checks:unresolved-writes:required).references:"ignore"(default),"calls","calls-and-bases", or"reads": whether a reference handing acall-targetsentry on, with"calls-and-bases"a class statement naming one among its bases, and with"reads"any other use of its value, counts forcalls, as for[[tool.heki.call-owners]].import-probes:"allow"(default) or"report": whetherreads-environmentalso forbids import probes (needsreads-environment).allowed-callees: functions, classes, modules, or ecosystem symbols whose effects are allowed.message: the help of every report of the boundary.