Skip to content

set-order-output (EFF112)

Family: Execution Effects (EFF) · Heuristic · Opt-in · Experimental · Severity error (a bug) · No automatic fix

Opt-in: the iteration order of a set of strings, which changes between runs, reaches a file, a stream, a serializer, or a raised exception's message across a call.

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 only when select or extend-select names its code or name. It has not been measured yet. See Rule Precision.

Experimental

Its precision is measured on a sample of reports of one corpus only, and its premises are not yet certified. Experimental features can still change in behavior or precision, or be removed, in any release, and each change is listed in the release notes. An opt-in rule that is not experimental is stable and only off by default. See Experimental Features.

What it does

Checks for the iteration order of a set of strings reaching an output across a call: a function builds a value in the order it iterates a set (or picks an element of one) and returns it, and its caller writes it; or a function hands such a value to a call that writes it. The rule is opt-in: enable it with --extend-select EFF112 or extend-select = ["EFF112"].

The set is a set or frozenset of str or bytes values (or tuples of them), by construction (a display, a comprehension, set(), frozenset(), a set operator such as a & b.keys(), a module constant bound once to one) or by annotation (set[str], a callee's declared return type). Python randomizes the hashes of strings per process, so such a set iterates in a different order from run to run.

The order is taken where the code iterates the set (a loop, a comprehension, a generator expression), copies it into a sequence or text (list(), tuple(), str.join(), formatting), or picks an element of it (set.pop(), next(iter(...)), the first element a loop returns). It follows the value through assignments, displays, formatting, string concatenation (text built element by element in a loop included), the containers it is appended to or stored in, returns, and the calls of the project.

The outputs are:

  • files and streams: pathlib.Path.write_text / write_bytes, print, sys.stdout.write, and write on a file the function opens;
  • serializers: json.dumps / json.dump unless sort_keys=True, yaml.dump / yaml.safe_dump with sort_keys=False, pprint.pprint / pprint.pformat with sort_dicts=False, and pprint.pp;
  • the message of a raised builtin exception built from the whole value (ValueError("unknown: " + ", ".join(names))).

Add your own writers with writes-in-order in [[tool.heki.ecosystem]]. The report is placed where the ordered value meets the output: the call whose result is written, or the place the order is taken when it is handed to a call that writes it. The place the order is taken and the calls on the way are related locations.

It does not report:

  • a flow inside one function (", ".join(names) written in the same function): one expression and its type decide it, which is a linter's check;
  • a set of other values (set[int] iterates in the same order in every run), or of values whose type heki does not know;
  • a value sorted on the way (sorted(...)), turned back into a set, measured (len), compared, or only tested for membership;
  • a set holding at most one element on every path to where its order is taken (if len(s) > 1: return None, then s.pop(), also as one operand of or / and: if len(s) != 1 or not ok: return None), or a sequence copied from it holding at most one where an item is read from it (if len(rest) > 1: ..., then rest[0]);
  • one element at a time written to its own file ((root / name).write_text(...) in a loop over the set): only an output that appends, such as a stream, writes the set's order;
  • an exception raised for one element at a time (for name in names: check(f"pkg.{name}"), raising with its argument): it names the first element that fails, which depends on the order only when two fail;
  • a mapping read back by key (summary[path] for each path of sorted(summary)), and a key read from the mapping before and stored again (fields[k] = fields[k].strip()), which keeps its place;
  • a set filled with the elements (seen.update(...)): a set has an order of its own, and iterating it is a take of its own; insert, update, and setdefault on a value heki does not know as a list or a mapping;
  • a writer whose sorting switch heki cannot evaluate (json.dumps(data, sort_keys=flag)), and logging and warnings.warn;
  • a value passed through code heki does not follow: a template engine, a call it cannot resolve.

What a report states

A report states that a value whose order (or whose element, for a pick) comes from iterating a set of strings reaches the output call shown in that order, across a call, so the written text changes from run to run.

Its premises:

  • Set order: the iterated value is a set or frozenset, by construction or annotation (assumption R2). Open through an annotation.
  • Run-dependent hashes: its elements are str or bytes, or tuples of them, by construction or annotation. Open through an annotation.
  • Order taken: the code iterates, copies, formats, or picks from the set, with no sorted() after it on the way, and the set may hold two elements there. Established.
  • Reaches output: the value, or a value built from it in order, is the argument of the output call, through assignments, returns, and calls. Open: one path is enough.
  • Writes in order: the output call writes its argument in the value's order, as the catalog describes it (assumption R3), with its sorting switch established off. Established.

Why is this bad?

A program whose output depends on the iteration order of a set of strings writes different files on different runs: generated code and configuration change without a change to their input, --check modes fail at random, caches and snapshots miss, and two runs of a test disagree. The order is fixed only within one process, so the difference shows on another machine or in CI, rarely where the code was written.

Example

import json
from pathlib import Path


def referenced(schema: dict[str, dict]) -> set[str]:
    return {value["$ref"] for value in schema.values() if "$ref" in value}


def components(schema: dict[str, dict], schemas: dict[str, dict]) -> dict[str, dict]:
    return {name: schemas[name] for name in referenced(schema)}


def write_components(schema: dict[str, dict], schemas: dict[str, dict], path: Path) -> None:
    path.write_text(json.dumps(components(schema, schemas)))  # EFF112

Use instead:

def components(schema: dict[str, dict], schemas: dict[str, dict]) -> dict[str, dict]:
    return {name: schemas[name] for name in sorted(referenced(schema))}

Fix safety

No automatic fix.

Options

  • lint.extend-select = ["EFF112"] (or --extend-select EFF112) enables the rule. It is opt-in: selecting the EFF prefix does not enable it.
  • [[tool.heki.ecosystem]] entries with writes-in-order add writers.