Skip to content

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.

  • scopes select 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, so render also selects a module named render. 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 external call-targets and read-targets); their other effects (calls of project functions, blocking calls, writes and reads of target attributes) do not count.
  • forbid lists the forbidden effects:
  • blocking-net, blocking-db, blocking-fs, blocking-subprocess, blocking-sync, sleep, or blocking for all six: blocking calls of the ecosystem knowledge base (requests.get, sqlite3, open, subprocess.run, time.sleep, ...);
  • writes-targets: writes to the Class.attr entries of write-targets (and their subclasses), or to one entry of the container an attribute holds (Class.attr["key"]), in every form MUT201 follows, through the receivers whose class MUT201 sees (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 own self, itself or through the helpers it passes self to (_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 for MUT201;
  • reads-targets: reads of the Class.attr entries of read-targets (and their subclasses), in every form MUT203 follows (obj.attr, getattr(obj, "attr"), obj.__dict__["attr"] or vars(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 as sys.platform or through from sys import platform;
  • calls: calls of the call-targets entries, matched as the targets of MUT204: a function, a method (with its overrides in subclasses, through bound-method aliases and getattr with 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 for MUT204. 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 for MUT204); a dotted suffix, a leading glob, a module part, or an argument list does not. With references = "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 for MUT204 ("render hands on pkg.core.decide"), with "calls-and-bases" a class statement naming a class target among its bases ("render subclasses pkg.core.Rule"), and with "reads" every other use of a target's value ("render reads pkg.core.Keys");
  • reads-environment: reading the environment the program runs in: a call or a module attribute read the ecosystem catalog tags environment (os.getenv, platform.system, importlib.util.find_spec, os.environ, sys.platform, sys.version_info, ...), and, with import-probes = "report", an import inside a try with an except clause naming ImportError or ModuleNotFoundError. A call of importlib.import_module or importlib.util.find_spec that 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 at package (a text, or the module's own __package__ or __name__). Inside a try that takes an ImportError, 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 is self, so a method writing self.x mutates a parameter.
  • write-universe with allow-writes states the writes a scope may make positively: a reached write of a write-universe entry that no allow-writes entry names is reported, in every form writes-targets follows. allow-writes also exempts writes from write-targets in the same boundary. Without allow-writes, the boundary allows no write of the universe.
  • An entry target (Class.attr["key"], in write-targets, write-universe, or allow-writes) also matches the writes a store operation makes with the key a call passes it: set_extra(field, "init", v), where set_extra writes field.extras[key], writes Field.extras["init"], through any number of functions passing the key on, also as a Final constant. 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 of Field.extras under 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 like scopes): their effects are allowed, also when a helper hands them a field it was given (helper(model.fields) writes nothing when helper only passes fields to an allowed callee that changes it). A method changing its own self in place, called on a field's value (model.bag.add(x)), changes the field at the call, as MUT201 counts 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 def functions called without await (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 for EFF101, 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 forbid lists, as the ecosystem catalog or the boundary's own entries describe it; or the last function makes the call, the read, or the import probe forbid lists. Established for a read and an import probe: the module attribute is named through the module's imports, and the except clause names the import error. For a call importing a module, open: the module is not established to be the project's. With references = "calls", a target handed on is one for calls: 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 for MUT204; 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.fields for 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.attr entries for writes-targets (required with it).
  • read-targets: Class.attr entries for reads-targets (required with it), or attributes of modules outside the project by their full name.
  • call-targets: functions, methods, or classes for calls (required with it), as for the targets of [[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.attr entries whose reached writes are reported unless allow-writes names them; the diagnostic target is the entry, with a glob attribute replaced by the written one (pass:DataModel.fields for DataModel.*).
  • allow-writes: Class.attr writes the boundary allows (needs write-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 targets checks:unresolved-calls, checks:unresolved-writes:required).
  • references: "ignore" (default), "calls", "calls-and-bases", or "reads": whether a reference handing a call-targets entry on, with "calls-and-bases" a class statement naming one among its bases, and with "reads" any other use of its value, counts for calls, as for [[tool.heki.call-owners]].
  • import-probes: "allow" (default) or "report": whether reads-environment also forbids import probes (needs reads-environment).
  • allowed-callees: functions, classes, modules, or ecosystem symbols whose effects are allowed.
  • message: the help of every report of the boundary.