Skip to content

unresolved-guarded-write (MUT205)

Family: Mutation & State (MUT) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix

Strict mode of a write-owners contract (unresolved = "report"): writing an attribute named like a target on an object of unknown class, or a computed attribute name on a guarded class.

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

The strict mode of a [[tool.heki.write-owners]] contract that sets unresolved = "report": reports the writes outside the write owners that MUT201 cannot tie to a target class, so a clean MUT201 run says how much it did not check. Four kinds of writes are reported, each once, at the write:

  • an attribute named like a target attribute (fields for Model.fields, any name for Model.*: a write may add the member) written on an object of unknown class: an unannotated parameter that no project caller binds to an instance of a known class, a loop variable, the result of a call heki does not resolve, a value annotated Any or object (unless an isinstance test around the write narrows it to a class: if isinstance(obj, Field): ...), a protocol whose implementations heki cannot list (one without members, or implemented by more than eight classes), or a variable of an enclosing function that a nested scope rebinds (nonlocal). Rebinding (obj.fields = []), deleting, setattr with a constant name, and changing the container the attribute holds (obj.fields.append(x), obj.meta["k"][name] = v, also through an alias, in the function or in a scope nested in it) count;
  • an attribute name computed at run time written on an instance of a target class: setattr(model, name, v), model.__dict__[name] = v, model.__dict__.update(...), model.__dict__ |= other (also through vars(model) or a local alias of the namespace), and a __dict__ key in a name that is no constant: a module-level name bound twice, in a loop, or before a star import, rebound by another module, or that a change through globals() may bind (in a module whose __getattr__ caches what it serves, one the module body binds on some paths only), a class attribute without ClassVar or Final (an instance may hold its own), one a subclass defines again or inherits first from another base, a Final field of a dataclass read on an instance (or on a class object with slots=True along the way), and one stored on its class, a subclass, or an instance outside the class body (Model.KEY = "x");
  • an attribute name computed at run time written on an object of unknown class (an unannotated target in setattr(target, name, v) or target.__dict__[key] = v), which may be any target;
  • with unlisted-dict-keys = "report", a constant __dict__ key written on an object of unknown class (field.__dict__["_name_cache"] = v, field.__dict__.setdefault(KEY, v), del vars(field)["k"]) that no target of any write-owners contract names for some class this contract's targets cover: it may be a new key of that class, which MUT201 reports on a typed object.

The rules of MUT201 for what is allowed apply: allowed writers, exempt methods, a class's own initialization (setattr(self, name, v) in __init__), functions that only run inside allowed writers, forbidden-writers, allowed-protocols (also for an object of unknown class typed with a named protocol declaring the attribute: a class object typed type[P], or an instance of a protocol whose implementations heki cannot list), and, with fresh-objects = "allow", writes that construct the object they write. A parameter that every caller path binds to an object of a project class is not reported: MUT201 reports the write at those callers. For a computed name on a parameter, a caller binding an object of a target class leaves the write to MUT205 (MUT201 has no name to report at that caller), unless it is that class's own initialization handing over its self, and one binding an object of another class ties it there. The same holds for a __dict__ key no target names: a caller binding an object of a class the key would be new to leaves the write to MUT205 (MUT201 sees no __dict__ write at a caller handing the object to a helper that does not type it). With attribution = "lexical", a function that only runs inside allowed writers is not allowed, and a caller path through an allowed writer counts like any other, while a helper that only a class's own initialization runs on its own self (self._assign(name) in __init__) stays allowed. With own-receiver = "allow", a computed name written on the receiver of the method judging it (setattr(self, name, v)) is allowed.

The help names up to three allowed writers that write a target of the attribute's name themselves, as for MUT201, after the contract's message: allowed writers of `fields`: ....

What a report states

A report states that, outside the write owners, the function writes an attribute named like a target of the write-owners contract on an object whose class heki does not know, a computed attribute name on a guarded class or on an object whose class heki does not know, or, with unlisted-dict-keys = "report", a __dict__ key no target names on an object whose class heki does not know.

Its premises:

  • Named like a target: the attribute's name matches a target's, or is computed at run time (with unlisted-dict-keys = "report", or is a __dict__ key no target names for a class the targets cover). Established.
  • Unknown class: heki did not resolve the class of the object. Established: the claim is about heki's own resolution.
  • 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 access is not allowed, nor runs only inside a class's own initialization). Established from the contract.

Why is this bad?

MUT201 reports what it can back with a class: a write through an object it cannot type is not followed, so a contract that passes says nothing about those writes. Name-based checkers report them all; heki reports them separately, under their own code, so they can be counted, ratcheted with a baseline, and reduced by annotating the objects or naming the attributes with constants, without mixing them with the violations MUT201 proves.

Example

[[tool.heki.write-owners]]
name = "model-store"
targets = ["Model.fields"]
allowed-writers = ["Store.*"]
unresolved = "report"
def touch(model) -> None:  # no annotation: heki cannot tell what `model` is
    model.fields = []  # MUT205


def fill(model: Model, name: str) -> None:
    setattr(model, name, [])  # MUT205: the attribute is computed at run time


def fill_any(target, name: str) -> None:
    setattr(target, name, [])  # MUT205: neither the class nor the attribute is known


def read_only(model: Model) -> int:
    return len(model.fields)  # not reported: a read

With unlisted-dict-keys = "report" as well:

def remember(model) -> None:
    model.__dict__["_seen"] = True  # MUT205: a key no target names, on an object of unknown class

Use instead:

def touch(model: Model) -> None:
    model.fields = []  # now `MUT201`, outside `Store.*`

Fix safety

No automatic fix.

Options

  • [[tool.heki.write-owners]]:
  • unresolved: "ignore" (default) or "report".
  • unlisted-dict-keys: "ignore" (default) or "report": also report a constant __dict__ key no write-owners target names, written on an object of unknown class.
  • targets, allowed-writers, forbidden-writers, exempt-methods, fresh-objects, attribution, message: as for MUT201.