readonly-return-mutation (MUT202)¶
Family: Mutation & State (MUT) · Heuristic · Runs when its contract is declared · Severity error (a bug) · No automatic fix
Mutating a shared object returned by a declared readonly-returns producer, directly or through the functions that return it.
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. Of 20 sampled reports (round 3, 2026-11-21), 70% were right about the code. See Rule Precision.
What it does¶
Checks mutations of objects returned by a shared producer declared in
[[tool.heki.readonly-returns]], and by the functions that return a producer's value, or a part
of it, on some path: a wrapper is a producer itself, without configuration, through any number
of wrappers, property getters, and recursion. The rule runs when such a contract is declared.
The results of functools.lru_cache / functools.cache functions are checked without
configuration by MUT114 (cached-result-mutation).
Mutations through attributes, subscripts, container methods, in-place operators, and helpers
that mutate their argument (also run on a worker thread: asyncio.to_thread(clear, shared)) are
followed, also on the call result itself
(schema_of(raw).items.append(x)); a generator function mutates its argument only where the
generator that call returns is iterated. Copies end the protection: copy.deepcopy(...),
model.model_copy(deep=True) (without update=, whose values Pydantic assigns to the copy by
reference), and the deep copy sanitizers of the ecosystem knowledge base clear it, shallow copies
(copy.copy, .copy(), dataclasses.replace(...), dict(...), list(...), tuple(...),
set(...), frozenset(...), displays that only unpack the value ({**shared}, [*rows]), a
sanitizer declared copy-sanitizer = "shallow", and slices of builtin lists, other builtin
sequences, and values whose class heki cannot infer, rows()[:]) free the top level only: the
values below stay shared, so a helper rebinding an attribute of the copy (b.name = "new")
changes nothing shared, and one changing the object an attribute or an item holds
(b.tags.append(x), b["tags"].append(x), for row in b: row.clear(), also on its own
shallow copy of the argument) does, unless it gave that item a new object first. A producer
that is not deep shares only the object itself: a helper changing what it holds as items does
not change it. A slice of an object of another known class may
be a view of it (numpy) and stays shared. A copy() method of a project class copies as
deeply as its body does: its result is shared only when the method returns a shared value. A
wrapper that returns a copy on one path and the shared value on another still returns a shared
value.
Filling a memo of the shared object, directly or in a method or helper it is handed to, is no
mutation: an in-place change of an attribute named as a cache or memo (self._style_cache[k] =
v, also through the methods of a cache object held there), a store under a test finding the
key missing (if k not in self._decoders:, the else of if k in ...:, a None or falsy
self._index.get(k), the key computed again by the same expression, id(raw)) or through
setdefault, a fill of a container a helper has as its default (def fill(key, _seen={})), and
a lazy initialization leave what the object computes as it was. A lazy initialization stores
an attribute (self._x = v, setattr, object.__setattr__) where a test found it unset: if
self._runtime is None:, if not hasattr(self, "_runtime"):, a None test of getattr(self,
"_runtime", None), or the except AttributeError: clause of a try that reads it.
What a report states¶
A report states that the function changes in place an object that a shared producer returned: a
producer declared in readonly-returns, or a function returning a producer's value.
Its premises:
- Producer: the declaration. Established.
- Returned through wrappers: a function returning a producer's value on some path is a producer. Open: one path is enough.
- Same object: the changed object is the returned one, or an object below it, not a copy. Open: a value that is the shared one on one path counts.
- Changed in place: a store, a mutator, an in-place operator, or a helper changing its argument. The memo fills listed above are left out; a memo fill heki does not recognize does change the object.
Why is this bad?¶
A shared return value is seen by every caller. Mutating it corrupts it for everyone else, usually long after the mutation happened.
Example¶
from registry import schema
def schema_of(name: str) -> dict[str, list[str]]:
return schema(name)
def extend(name: str) -> None:
s = schema_of(name)
s["fields"].append("extra") # MUT202: mutates the shared object
Use instead:
import copy
def extend(name: str) -> dict[str, list[str]]:
s = copy.deepcopy(schema_of(name))
s["fields"].append("extra")
return s
Known limitations¶
- A shared value stored in an attribute (
self.kept = schema(...)) and changed in another method is not followed. - A generator's values and a coroutine's result (
await) are not followed. - A method call on a shared value whose class heki cannot resolve (a producer returning a type variable) is not followed; a wrapper with a concrete return annotation resolves it.
- A dict that also holds values of its own (
{**shared, "extra": []},dict(shared, extra=[])) or unpacks another mapping ({**shared, **overrides}) is not followed. - A project method returning a part of a shared receiver (
return self._items[key]) is not followed, nor is acopy()method of a project class that shares the receiver's values (return Post(self.tags)).
Fix safety¶
No automatic fix.
Options¶
[[tool.heki.readonly-returns]]:name,producers(function names or globs),deep(protect nested values too).