Skip to content

Effect and path boundaries

effect-boundaries lists the I/O, writes, reads, and calls the code its scopes name must not reach, and path-boundaries the files below a directory that code must not read, copy, or list. Contracts lists every kind and the keys they share.

effect-boundaries

[[tool.heki.effect-boundaries]]
name = "pure-render"
scopes = ["*.render", "*.render_module_code", "pkg.domain.*"]
forbid = ["writes-targets", "blocking"]
write-targets = ["DataModel.*", "DataType.*"]
allowed-callees = ["pkg.logging.*"]
message = "render entry points must not mutate model state"

[[tool.heki.effect-boundaries]]
name = "decisions-read-final-facts"
scopes = ["pkg.model._decisions.*"]
forbid = ["reads-targets", "calls"]
read-targets = ["DataType.is_optional", "DataModel._additional_imports"]
call-targets = ["GenerationStore.*"]

[[tool.heki.effect-boundaries]]
name = "pass-sort-base-classes"
scopes = ["pkg.parser.passes.sort_base_classes"]
allow-writes = ["DataModel.base_classes"]
write-universe = ["DataModel.*", "DataModelFieldBase.*", "DataType.*"]

[[tool.heki.effect-boundaries]]
name = "portable-generation"
scopes = ["pkg.generate.*"]
forbid = ["reads-environment"]
import-probes = "report"
Key Default Meaning
name "" The boundary's name in reports.
scopes [] Modules, classes, or functions whose functions must stay inside the boundary; nested functions are included. A module body is included only where a pattern names <module> (pkg.gen:<module>, below). Lambdas are named with <lambda> (Lambda scopes).
forbid [] What the scope functions must not reach (tokens below).
self-type none The class of the first parameter of the lambdas the lambda scopes select, as their module names it (Parser) or by its full dotted name (Lambda scopes).
lambda-parameters [] The classes of the parameters of the lambdas the lambda scopes select, by position: a class or protocol as their module names it or by its full dotted name, or a pattern of the classes of a module (pkg.state.*); _ or "" leaves a position as it is (Lambda scopes).
write-targets [] Class.attr targets of writes-targets, required with it. Class.attr["key"] names one entry, and Class[*] / Class["key"] the items of a container class, as in write-owners.
read-targets [] Class.attr targets of reads-targets, required with it: reads as read-owners sees them, also inside property getters. A container entry or items target is a configuration error. An entry can also name an attribute of a module outside the project by its full name (sys.platform, os.environ, below), or a name of a project module (below).
call-targets [] Functions, methods, or classes of calls, required with it, matched as the targets of call-owners (also with an argument list). An entry can also name a function or class outside the project by its full name (os.getenv, platform.*, below).
write-universe [] Class.attr entries (and Class[*] items): a reached write of one that allow-writes does not name is reported, once per written Class.attr. An attribute pattern (Class.*) does not name the items.
allow-writes [] Class.attr writes (and Class[*] items) the boundary allows, exempt from write-targets too. Needs write-universe.
read-universe [] Class.attr entries, or names of a project module (below): a reached read of one that allow-reads does not name is reported, once per read Class.attr or name, in every form reads-targets follows.
allow-reads [] Class.attr reads, or names of a project module, the boundary allows, exempt from read-targets too. Needs read-universe.
allowed-callees [] Functions, classes, modules, or ecosystem symbols whose effects are allowed: paths through them are not followed, and calls of them are no calls violation.
exempt-decorators [] Decorators ({ name = "pytest.mark.allow_fail", reasons = "required" }) that exempt the functions they mark when they state a reason: they are allowed callees, and a scope function carrying one is not searched; see Exempting decorators.
fresh-objects "allow" "allow" or "report": whether a write that constructs the object it writes (as in write-owners) counts as a write of the boundary.
references "ignore" "ignore", "calls", "calls-and-bases", or "reads", as for call-owners: whether a reference handing a call-targets entry on (and a class statement naming one among its bases, and any other use of its value) counts for calls.
import-probes "allow" "allow" or "report": whether reads-environment also forbids an import probe, an import inside a try with an except clause naming ImportError or ModuleNotFoundError. "report" without reads-environment is a configuration error.
include-overrides false true: a scopes or allowed-callees entry naming a method (Class.method, module:Class.method) also names the methods of that name in the project subclasses of Class, with the scopes nested in them. See Allowed and forbidden functions.
unresolved "ignore" "ignore" or "report": whether the boundary also reports, under EFF201, what it cannot judge in its scopes' reach: a call heki resolves to no function (also a function a worker or a builtin is handed to run), a function it does not model (eval, a body too large) or whose body only a stub declares, 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, and a read of one read-targets or read-universe names on an object of unknown class, or under a name computed at run time (getattr(x, name), a __dict__ key heki cannot read, the __dict__ used whole) on an object that may be of one of their classes. An access that allow-writes or allow-reads names for every class it may be of is allowed (*.updated_at). A call that may run more functions than heki follows (eight) is judged when allowed-callees names every one of them. Each kind is one report per scope function, at the first one with its chain; the JSON output lists every site of a call or write report (Output Formats).
message none The help of every report of the boundary.
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 allowed-callees, allow-writes, allow-reads, and exempt-decorators that allowed no effect the boundary forbids; see Unused allowances.
allowance-reasons "optional" "required": every entry of allow-writes and allowed-callees comes from a group with a reason; see Reasons for allowances.
forbid token Forbids
blocking-net, blocking-db, blocking-fs, blocking-subprocess, blocking-sync, sleep that blocking effect
blocking all six blocking effects
mutates-params changing a parameter in place (for a method, self is a parameter)
writes-targets writing a write-targets attribute
reads-targets reading a read-targets attribute
calls calling a call-targets function or class
reads-environment reading the environment the program runs in: calling or reading what the ecosystem catalog tags environment (below), and import probes with import-probes = "report"
writes-environment changing the environment variables of the process: calling os.putenv or os.unsetenv, and changing an entry of os.environ or os.environb (below)

Names of a project module in read entries

A read-targets, read-universe, or allow-reads entry can name a name a project module binds, such as a registry or a ContextVar that holds run state, as a read-owners target does (Names of a module's namespace): pkg.tables:REGISTRY, and pkg.tables:* for every name of pkg.tables. A dotted entry without a glob (pkg.tables.REGISTRY) names the same when pkg.tables is a project module that binds the name and no project class matches pkg.tables; otherwise it is a Class.attr entry, and one naming no class is an entry that matches nothing as before.

[[tool.heki.effect-boundaries]]
name = "gate"
scopes = ["pkg.tables:GATES:<lambda>"]
read-universe = ["pkg.tables:*"]
allow-reads = ["pkg.tables.LIMIT"]
# pkg/tables.py
REGISTRY: dict[str, int] = {}
LIMIT = 3

GATES = (
    ("registry", lambda self, _: bool(REGISTRY)),  # EFF201
    ("limit", lambda self, _: LIMIT > 1),
)
  • A read is one read-owners counts: pkg.tables.REGISTRY or getattr(tables, "REGISTRY") through the module object, and an import of the name with each load of what it binds. A load of the name in a function or lambda of the module binding it reads it too, which read-owners does not count: the boundary keeps its scope from the module's state wherever the scope is. A name loaded only to be called there (run_pass(name)) is a call, and a local of the same name is no read.
  • A report names the entry as configured, or for a glob the name read (gate:reads:pkg.tables.REGISTRY for pkg.tables:*).

Outside the project, call-targets and read-targets entries name symbols by their full dotted name, starting with the top-level module: os.getenv matches a call of os.getenv (also from os import getenv, import os as o), platform.* every function of platform, and sys.platform a read of sys.platform (also from sys import platform, or import sys as s and s.platform). A dotted suffix (getenv), a leading glob (*.getenv), or a module part (os:getenv) never names a symbol outside the project, so an entry for project functions keeps its meaning. <external>._* names the private members of every module and class outside the project, as for the owner contracts, whose rules for calls and reads these entries follow. Only a call or a read heki resolves counts: an attribute read by name (getattr(sys, name)) or on an object of unknown origin is not reported.

reads-environment needs no targets. The ecosystem catalog tags these calls: os.getenv, os.getenvb, the functions of platform that describe the machine or the interpreter (platform.system, platform.machine, platform.python_version, ...), importlib.util.find_spec, importlib.import_module, importlib.metadata.version, importlib.metadata.distribution, shutil.which, and sysconfig.get_config_var; and these reads: os.environ, os.environb, os.name, sys.platform, sys.version, sys.version_info, sys.hexversion, sys.implementation, and sys.flags. An entry set excluded = true ([[tool.heki.ecosystem]], below) is never reported. A call on os.environ (os.environ.get("X")) is a read of os.environ. One report per scope function names the first read it reaches and counts every one.

importlib.import_module(name, package) and importlib.util.find_spec(name, package) read the environment unless the module they import is established to be the project's own:

  • every text name may hold names a module of the project ("pkg.config", a module constant, either of two such texts) that the import finds in the project, or starts with a package of the project and a dot (f"pkg.parser.{name}", "pkg.parser." + name, "pkg.%s" % name) under which it finds only modules of the project (below);
  • a relative name (".config", f"..parser.{name}") is anchored at package: a text the code fixes, or the module's own __package__ or __name__;
  • the call is not inside a try with an except clause naming ImportError or ModuleNotFoundError: the code expects the import to fail.

Python finds the modules under a package on its __path__, the package's own directory unless code changes it. heki follows what the modules of the project do to the __path__ of a package, its own in its __init__.py or another's through an import (plugins.__path__, from plugins import __path__):

  • adding directories after the package's own (__path__.append(d), __path__.extend(ds), __path__ += ds, __path__ = __path__ + ds, __path__ = pkgutil.extend_path(__path__, __name__), also on __import__("pkgutil"), and pkg_resources.declare_namespace) leaves the package's own modules found first, but any other name under the package may be an installed module;
  • any other change (__path__ = [d], __path__.insert(0, d), a slice store, del __path__), or a use heki does not follow (the list handed to a function other than a builtin that only reads it and pkgutil.iter_modules, walk_packages, or extend_path, returned, or stored elsewhere), may take any name under the package elsewhere, its own modules included. So may a package whose __init__.py heki cannot read.

Reading the path (iterating it, __path__[0], len(__path__), pkgutil.iter_modules(__path__)) changes nothing. A module is found in the project when each package along its name leads the import there first: heki takes the project's top-level packages to be found in the project, a regular package of the project is found before the directories added after its parent's own, and a directory without __init__.py is a namespace package with a portion in each directory of its parent's path, in that order. A name under a package holds only modules of the project when the packages along it lead to the project's directories alone and no package under it changes its path: f"pkg.{name}" reads the environment once a package anywhere under pkg changes its __path__, while a change in another package does not affect it.

A name heki cannot tell (a parameter, "pkg" + name, a namespace package without __init__.py) stays a read of the environment, and so does an import of a module the project does not have. A call-targets entry naming importlib.import_module matches every call of it.

writes-environment needs no targets either. A variable the process sets for itself is inherited by every child process it starts later, and a change through os.environ is also what every later os.getenv reads (os.putenv changes the process environment only, not os.environ), so a library function that sets one changes what code far from it does, depending on the order the calls ran in. Binding another mapping to the name (os.environ = {}) changes no variable and is not reported. The ecosystem catalog tags the calls os.putenv and os.unsetenv, and the mappings os.environ and os.environb, whose entries a function changes by an item store or del, by an in-place method (update, pop, setdefault, clear, popitem, |=), or by a patch call of a test (monkeypatch.setenv, monkeypatch.delenv, monkeypatch.setitem(os.environ, ...), mock.patch.dict(os.environ, ...)). A copy (os.environ.copy(), {**os.environ, "K": v}) passed to a child process as env= writes nothing. allowed-callees names the callees that may set the environment (a project function outside the scopes, or os.putenv itself); a function the scopes select is checked itself, whatever allowed-callees says. One report per scope function names the first write it reaches and counts every one.

[[tool.heki.effect-boundaries]]
name = "library-sets-no-env"
scopes = ["app.core.*"]
forbid = ["writes-environment"]
allowed-callees = ["app.proc:run_child"]
  • Each scope function is checked through any number of calls.
  • A module body, what runs when the module is imported, is checked only where a scope names <module> itself: pkg.gen:<module> (the body of pkg.gen), pkg.*:<module> (of every module under pkg), pkg.gen.<module>, or <module> (of every module). pkg.* and pkg.gen:* keep naming the functions only. The body is checked as a scope function is (its module-level reads, calls, import probes, and writes), and the bodies of its classes, which run with it, count for what they take from outside the project (environment reads and writes, import probes, and the external call-targets and read-targets), not for their other effects. Reports name it <module>.
  • A violation inside another scope function is reported there only, once.
  • One report per scope function and forbidden kind (or target) stands for every distinct site of it that the function reaches.

Lambda scopes

A scopes entry ending in :<lambda> names lambdas: pkg.gates:<lambda> every lambda of the module pkg.gates (in its functions and class bodies too), and pkg.gates:GATES:<lambda> the lambdas the module-level value GATES holds in its tuple, list, set, or dict display, nested displays included. The boundary judges their bodies as it judges a function's. A lambda's first parameter is typed by the boundary's self-type, or else by the annotation of the value holding it, which gives the lambda's place a Callable[[Parser, ...], R]:

[[tool.heki.effect-boundaries]]
name = "gate"
scopes = ["pkg.gates:GATES:<lambda>"]
self-type = "Parser"
read-universe = ["Parser.*"]
allow-reads = ["Parser.config"]
GATES = (
    ("option", lambda self, _: self.config.flag),
    ("fact", lambda self, _: bool(self.results)),  # EFF201: reads `Parser.results`
)

Without self-type, GATES: tuple[tuple[str, Callable[[Parser, object], bool]], ...] types self the same way: a tuple by position (or tuple[X, ...] by its item), a list, set, or sequence by its item, and a dict or mapping by its key or value, also inside Final. Only the lambdas a lambda scope selects are typed, and when two boundaries type one lambda, the first in the configuration wins. The lambdas of one function are one function to the reports, so a read repeated in several of them is one report with more sites, and what the lambdas no scope selects do (their calls, reads, writes, and changes of their parameters) counts for none. An entry whose module has no lambda, or whose value holds none, matches nothing (Entries that match nothing).

pkg.passes:PassSpec(when)<lambda> names the lambdas written in the module pkg.passes, the module whose code holds the lambdas and the calls, passed to the parameter when of the callable PassSpec, by keyword or at the position the callable's signature gives when, wherever in that module the call is (in a display, a module constant, a function). PassSpec itself may be defined in another module. PassSpec is named as the module names it (PassSpec, specs.PassSpec) or by its full dotted name, and the call names it directly; a lambda bound to a local first counts when the call passes that local. The parentheses tell this form from MODULE:VALUE:<lambda>, so no entry of that form changes meaning. Other lambdas of the call (run below) are not in the scope:

[[tool.heki.effect-boundaries]]
name = "gate"
scopes = ["pkg.passes:PassSpec(when)<lambda>"]
read-universe = ["Parser.*", "State.*"]
allow-reads = ["Parser.config", "State.with_import"]
@dataclass(frozen=True)
class PassSpec:
    name: str
    run: Callable[[Parser, State], object]
    when: Callable[[Parser, State], bool] | None = None


PASSES = (
    PassSpec("option", lambda self, s: run_pass(self, s), when=lambda self, _: self.config.flag),
    PassSpec("fact", lambda self, s: run_pass(self, s), when=lambda self, _: bool(self.results)),  # EFF201
    PassSpec("state_fact", lambda self, s: run_pass(self, s), when=lambda _, state: bool(state.models)),  # EFF201
)

Every parameter of a lambda passed to a parameter of a project callable annotated Callable[[A, B], R] takes its class from the annotation by position, scope or not: a module function's parameter, a dataclass or NamedTuple field (as the generated constructor binds it, a subclass's annotation of a field winning), and an __init__ parameter; X | None and Optional[X] count as X, and Callable[..., R] types nothing. A lambda that its function also calls, returns, or passes on elsewhere keeps a class only where every use gives it the same one. self-type, when set, types the first parameter instead.

lambda-parameters gives the classes of the selected lambdas' parameters by position, for an annotation that gives them none, such as the type variables of a generic class (Callable[[P, S], bool] in a PassSpec(Generic[P, S])). Each entry is a class or protocol, as the lambdas' module names it or by its full dotted name, or MODULE.GLOB, every class the module MODULE declares whose name the glob matches (pkg.state.*, pkg.state.*State); _ or "" leaves its position as it is. A parameter is typed as an annotation of that class, or of the union of the classes a pattern matches, would type it, so the read, call, and write rules see through it; a pattern of more than eight classes types nothing, as such a union does. The entries win over the annotation, and self-type = "Parser" is the same as lambda-parameters = ["Parser"] (setting both is a configuration error, as is the key on a boundary without a lambda scope, or an entry naming no class of the lambdas' module):

[[tool.heki.effect-boundaries]]
name = "gate"
scopes = ["pkg.tables:PassSpec(when)<lambda>"]
lambda-parameters = ["Parser", "pkg.state.*"]
read-universe = ["Parser.*", "pkg.state.State.*"]
allow-reads = ["Parser.config", "pkg.state.State.with_import"]
PASSES: tuple[PassSpec[Parser, State], ...] = (
    PassSpec("option", run_pass, when=lambda self, _: self.config.flag),
    PassSpec("fact", run_pass, when=lambda self, _: bool(self.results)),  # EFF201
)
EXPLICIT = (PassSpec[Parser, State]("explicit", run_pass, when=lambda self, _: bool(self.results)),)  # EFF201

A call through a subscripted project class (PassSpec[Parser, State](...)) passes its lambdas to the class as PassSpec(...) does, unless the project defines the subscript (a __class_getitem__ of the class, or a metaclass), which may return another class; a subscript of anything else (HANDLERS[kind](...)) calls an item, which names no callable.

path-boundaries

[[tool.heki.path-boundaries]]
name = "expected-outputs"
roots = ["tests/data/expected"]
scopes = ["tests.*"]
exempt-scopes = ["tests.conftest.*"]
forbid = ["read", "copy", "list"]
sanitizers = ["tests.conftest.stored_expected"]

Which files and directories below roots the functions of scopes must not read, copy, or list, checked by EFF202 (experimental: the table's keys and what it counts can still change). A call is reported when heki builds its path from a constant path at or below a root: __file__, module constants (also imported ones), locals, /, joinpath, os.path.join, .parent, a loop over a tuple or list display.

Key Default Meaning
roots [] directories relative to the project root, with / between their names
scopes [] the functions checked (dotted patterns, as for effect-boundaries)
exempt-scopes [] the functions of scopes that are not checked
forbid [] the operations reported: read, copy, list
sanitizers [] project functions whose result may be read or copied, though it names a file below a root; listing it is reported
unresolved "ignore" "report": also report a call on a path heki cannot place (a parameter, another call's result, a path relative to the working directory)
message none the help of every report
fail false as for the other contracts (below)
baseline "allow" as for the other contracts (below)