STRA-338: limits gate gets the params metric (max 5 parameters, self counted): scanner, diff gate, census baseline, tests, doc

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-07 23:54:40 +01:00
co-authored by Claude Sonnet 5.5
parent e4993d1516
commit 4b04c24981
9 changed files with 257 additions and 28 deletions
+13 -7
View File
@@ -1,13 +1,13 @@
# Limits gate (STRA-367)
Lawbook chapter 301 limits the size of code: a function has at most 30 lines, cyclomatic complexity at most 10 and
nesting at most 4, and a line is at most 120 columns wide. The workspace does not meet them today (see the census
nesting at most 4, a function has at most 5 parameters (`self` counted) and a line is at most 120 columns wide. The workspace does not meet them today (see the census
below), so the gate is erroring for **new and changed code** and a **falling ratchet for legacy**. It is offline tooling
(stdlib Python, no cargo needed for the diff part, no network, no GPU); the production build does not depend on it.
```
scripts/check-limits.py diff gate + allowlist ratchet + census ratchet (what check-local.sh --product runs)
scripts/check_limits_test.py the self-tests (56 tests)
scripts/check_limits_test.py the self-tests (64 tests)
scripts/check-limits.py --report census per crate and the worst functions
scripts/check-limits.py --base REF diff against REF instead of the default base (env LIMITS_BASE does the same)
scripts/check-limits.py --update-baseline rewrite limits-baseline.json (never raises a total) and tighten the allowlist
@@ -19,7 +19,7 @@ scripts/check-clippy-limits.sh opt-in Clippy ratchet (check-local.
Files: `limits.json` (the policy), `limits-allowlist.json`, `limits-baseline.json`, `clippy-limits-baseline.json`,
`clippy.toml`, `scripts/limits/` (the tool). The tool holds itself to the limits: `scripts/limits/`,
`scripts/check-limits.py`, `scripts/check_limits_test.py` and the architecture gate scripts are in `python_include`,
so they are measured with the same four measures (Python measures below) and the gate runs on its own commits.
so they are measured with the same five measures (Python measures below) and the gate runs on its own commits.
## What is enforced
@@ -58,6 +58,12 @@ A function is found from the Rust tokens (the lexer of `scripts/dev/rustsplit`,
* **nesting**: the deepest chain of blocks inside the body (the body is depth 0). The block of `if`, `else`, `while`,
`for`, `loop`, `match`, `unsafe`, `async`, a closure `{ }` and a bare block each add one. A match arm block `=> { }`, a
struct literal or pattern `Foo { .. }` and a macro `name! { .. }` add nothing.
* **params**: the number of parameters in the signature, `self` (any form: `self`, `&self`, `&mut self`, `self: Box<Self>`)
counted like the others. Only the top-level, non-empty comma-separated parts of the list count, so commas inside
generics, tuples, arrays, patterns (`Foo { x, y }: Foo`) and `impl Fn(A, B)` types do not; a trailing comma is free;
generics before the list are skipped. `extern "C" fn` with a body and test functions count like any other function
(a declaration without a body, such as the ones in an `extern "C" { }` block, is not a function and is not counted).
In Python it is the number of positional, keyword-only, `*args` and `**kwargs` parameters, `self` and `cls` included.
* **width**: the columns of a line; a tab is 4, the line ending is not counted, 120 is allowed, 121 is not. For a
function `width` is the number of its lines wider than 120.
@@ -79,12 +85,12 @@ inside `macro_rules!` bodies are not modelled. It errs by a point or two, never
`limits-allowlist.json` lists functions that may miss a limit, with the numbers they have today:
```json
{"path": "crates/x/src/a.rs", "name": "Type::method", "fn_lines": 120, "complexity": 31, "nesting": 5, "width": 2,
{"path": "crates/x/src/a.rs", "name": "Type::method", "fn_lines": 120, "complexity": 31, "nesting": 5, "width": 2, "params": 7,
"reason": "moved verbatim from backend.rs by S19", "owner": "STRA-367"}
```
* `reason` and `owner` (the work item that removes the debt) are mandatory; an entry without them is an error.
* A recorded number may only fall. The function growing in any of the four measures is an error, touched or not; the
* A recorded number may only fall. The function growing in any of the five measures is an error, touched or not; the
entry also covers the wide lines inside the function.
* The entry named `<file>` covers the wide lines that are in no function (consts, attributes, imports); only `width`.
* An entry whose function is within the limits (or gone) is **stale**: the gate says so and
@@ -102,7 +108,7 @@ once; it is not committed here, because the entries would only describe code tha
## The census (legacy)
`limits-baseline.json` counts, per scope and crate, the functions over each limit (`fn_lines`, `complexity`, `nesting`)
`limits-baseline.json` counts, per scope and crate, the functions over each limit (`fn_lines`, `complexity`, `nesting`, `params`)
and the lines over the width. Only the **total over all crates** is ratcheted (code that moves between crates keeps its
total, like the source ratchets of the architecture gate), and `--update-baseline` refuses to raise a total unless
`--allow-increase` is given and justified in review. The tool reads the package list from `cargo metadata`; a file belongs
@@ -196,7 +202,7 @@ open branch. The 120-column rule is enforced by the diff gate on added and chang
Owner order of 2026-11-06: encode the chapter 301 limits as machine-enforced gates, without asking.
* **Erroring for new and changed code.** A function that is added or touched, and a line that is added or changed, must
be within 30 lines, complexity 10, nesting 4 and 120 columns. Legacy that is moved verbatim is exempt only through an
be within 30 lines, complexity 10, nesting 4, 5 parameters and 120 columns. Legacy that is moved verbatim is exempt only through an
allowlist entry with a reason and an owner, and the entry can only shrink.
* **Ratchet for legacy.** The census of what already misses the limits is recorded and its totals may only fall.
* **No workspace reformat.** No `rustfmt.toml` with `max_width = 120`; the width rule applies to changed lines only.
+126 -3
View File
@@ -4,10 +4,133 @@
"fn_lines": 30,
"complexity": 10,
"nesting": 4,
"width": 120
"width": 120,
"params": 5
},
"census": {
"prod": {},
"test": {}
"prod": {
"leleka-context": {
"params": 2
},
"leleka-cpu-kernels": {
"params": 4
},
"leleka-cpu-sys": {
"params": 18
},
"leleka-cpu-worker": {
"params": 1
},
"leleka-cuda-driver": {
"params": 337
},
"leleka-cuda-model": {
"params": 7
},
"leleka-deploy": {
"params": 4
},
"leleka-engine-core": {
"params": 16
},
"leleka-engine-qwen35-cuda": {
"params": 600
},
"leleka-experimental-ref": {
"params": 14
},
"leleka-gateway-domain": {
"params": 2
},
"leleka-gateway-text": {
"params": 1
},
"leleka-gptoss": {
"params": 4
},
"leleka-gptoss-igpu": {
"params": 3
},
"leleka-gptoss-npu": {
"params": 8
},
"leleka-gpu-npu-worker": {
"params": 2
},
"leleka-igpu": {
"params": 10
},
"leleka-kar-codec": {
"params": 2
},
"leleka-libc-shim": {
"params": 1
},
"leleka-model-format": {
"params": 11
},
"leleka-native-cpu-expert": {
"params": 28
},
"leleka-obs": {
"params": 1
},
"leleka-quant-core": {
"params": 1
},
"leleka-sampler-ref": {
"params": 2
},
"leleka-tokenizer": {
"params": 1
},
"leleka-worker-protocol": {
"params": 1
},
"strata-control": {
"params": 32
},
"strata-desktop-core": {
"params": 6
}
},
"test": {
"leleka-cpu-sys": {
"params": 1
},
"leleka-cuda-driver": {
"params": 5
},
"leleka-deploy": {
"params": 1
},
"leleka-engine-core": {
"params": 1
},
"leleka-engine-qwen35-cuda": {
"params": 5
},
"leleka-experimental-ref": {
"params": 3
},
"leleka-gptoss": {
"params": 1
},
"leleka-igpu": {
"params": 2
},
"leleka-model-format": {
"params": 8
},
"leleka-native-cpu-expert": {
"params": 1
},
"leleka-npu-service": {
"params": 1
},
"leleka-sampler-ref": {
"params": 1
}
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"_comment": "Policy of scripts/check-limits.py (STRA-367, lawbook chapter 301). The limits apply to new and changed code (diff gate) and to the whole tree as a falling census. See docs/architecture/limits-gate.md.",
"limits": {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120},
"limits": {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5},
"tab_width": 4,
"exclude": ["engine/strata/", "target/", ".git/"],
"python_include": [
+50 -2
View File
@@ -18,7 +18,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from limits import allow, baseline, census, cli, clippy_ratchet, diffs, files, gate # noqa: E402
from limits import model, policy, pyscan, rscan # noqa: E402
POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120}, 4, ("engine/strata/",),
POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, 4,
("engine/strata/",),
("scripts/limits/",), ("claude/hexagonal-integ", "main"))
LIMITS = POLICY.limits
@@ -441,10 +442,57 @@ class ClippyConfig(unittest.TestCase):
self.assertEqual(opt_in["too-many-arguments-threshold"], "5")
class Parameters(unittest.TestCase):
"""Lawbook 301: at most 5 parameters, `self` counted; FFI and test functions count like the rest."""
def count(self, signature):
return one(signature + " {}").params
def test_counts_every_parameter_and_self(self):
self.assertEqual(self.count("fn a()"), 0)
self.assertEqual(self.count("fn a(&self)"), 1)
self.assertEqual(self.count("fn a(&mut self, x: u8, y: u8)"), 3)
self.assertEqual(self.count("fn a(self: Box<Self>, x: u8)"), 2)
def test_a_trailing_comma_and_multiline_lists_are_free(self):
self.assertEqual(self.count("fn a(\n x: u8,\n y: u8,\n)"), 2)
def test_commas_inside_types_patterns_and_closures_do_not_count(self):
self.assertEqual(self.count("fn a(m: HashMap<K, V>, t: (u8, u8), s: [u8; 4])"), 3)
self.assertEqual(self.count("fn a(f: impl Fn(u8, u8) -> Result<u8, E>, g: &dyn Fn(A, B))"), 2)
self.assertEqual(self.count("fn a(Foo { x, y }: Foo, (p, q): (u8, u8))"), 2)
def test_generics_before_the_list_are_skipped(self):
self.assertEqual(self.count("fn a<T: Into<u8>, U>(x: T, y: U) -> Option<(u8, u8)>"), 2)
def test_ffi_and_test_functions_count_like_any_other(self):
ffi = 'pub unsafe extern "C" fn a(a: *mut u8, b: i32, c: i32, d: i32, e: i32, f: i32)'
self.assertEqual(self.count(ffi), 6)
text = "#[cfg(test)]\nmod t {\n fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n}\n"
(fn,) = rscan.scan(text, set())
self.assertEqual((fn.params, fn.test), (6, True))
def test_python_counts_self_keyword_only_and_star_arguments(self):
(fn,) = pyscan.scan("def f(self, a, /, b, *args, c, **kw):\n pass\n", set())
self.assertEqual(fn.params, 6)
def test_the_diff_gate_rejects_a_changed_function_with_six_parameters(self):
six = "fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n"
errors = gate.check_changed([state("a.rs", six, added=[1])], {}, LIMITS, 4).errors
self.assertEqual(errors, ["a.rs:1: a: parameters 6 > 5"])
five = "fn a(a: u8, b: u8, c: u8, d: u8, e: u8) {}\n"
self.assertEqual(gate.check_changed([state("a.rs", five, added=[1])], {}, LIMITS, 4).errors, [])
def test_the_census_counts_functions_over_the_limit(self):
(fn,) = rscan.scan("fn a(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8) {}\n", set())
self.assertEqual(census.tally("src/a.rs", [fn], set(), LIMITS), [("prod", "params", 1)])
class PolicyFile(unittest.TestCase):
def test_the_committed_policy_matches_lawbook_301(self):
root = pathlib.Path(__file__).resolve().parent.parent
self.assertEqual(policy.load(root).limits, {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120})
want = {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}
self.assertEqual(policy.load(root).limits, want)
if __name__ == "__main__":
+7 -5
View File
@@ -2,7 +2,7 @@
"""List the production functions over the lawbook 301 limits, longest first (STRA-338 helper for the size work).
Usage: scripts/limits-offenders.py [--top N] [--min-lines 31] PATH_PREFIX...
Each line: lines complexity nesting wide-lines file:start function-key
Each line: lines complexity nesting wide-lines params file:start function-key
"""
import argparse
import pathlib
@@ -14,7 +14,7 @@ from limits import files, policy # noqa: E402
def over_any(fn):
return fn.fn_lines > 30 or fn.complexity > 10 or fn.nesting > 4 or fn.width > 0
return fn.fn_lines > 30 or fn.complexity > 10 or fn.nesting > 4 or fn.width > 0 or fn.params > 5
def main(argv):
@@ -22,7 +22,8 @@ def main(argv):
parser.add_argument("prefixes", nargs="+")
parser.add_argument("--top", type=int, default=0)
parser.add_argument("--min-lines", type=int, default=31)
parser.add_argument("--over", action="store_true", help="every function over ANY limit (lines, complexity, nesting, width)")
parser.add_argument("--over", action="store_true", help="every function over ANY limit (lines, complexity, nesting, width, params)")
parser.add_argument("--params", action="store_true", help="only the functions with more than 5 parameters, most first")
args = parser.parse_args(argv)
root = pathlib.Path(__file__).resolve().parent.parent
pol = policy.load(root)
@@ -34,10 +35,11 @@ def main(argv):
continue
fns, _ = files.scan_file(root, pol, rel)
keep = over_any if args.over else (lambda fn: fn.fn_lines >= args.min_lines)
keep = (lambda fn: fn.params > 5) if args.params else keep
rows += [(fn, rel) for fn in fns if not fn.test and keep(fn)]
rows.sort(key=lambda row: -row[0].fn_lines)
rows.sort(key=(lambda row: -row[0].params) if args.params else (lambda row: -row[0].fn_lines))
for fn, rel in rows[: args.top or None]:
print(f"{fn.fn_lines:5} {fn.complexity:4} {fn.nesting:3} {fn.width:4} {rel}:{fn.start} {fn.key}")
print(f"{fn.fn_lines:5} {fn.complexity:4} {fn.nesting:3} {fn.width:4} {fn.params:3} {rel}:{fn.start} {fn.key}")
print(f"# {len(rows)} functions", file=sys.stderr)
+2 -1
View File
@@ -8,7 +8,8 @@ from dataclasses import dataclass, field
from . import allow, model
from .diffs import Changes
LABELS = (("fn_lines", "lines"), ("complexity", "complexity"), ("nesting", "nesting"))
LABELS = (("fn_lines", "lines"), ("complexity", "complexity"), ("nesting", "nesting"),
("params", "parameters"))
@dataclass
+3 -2
View File
@@ -1,12 +1,12 @@
"""What is measured, and the dispatch from a file to its language scanner."""
from dataclasses import dataclass
KINDS = ("fn_lines", "complexity", "nesting", "width")
KINDS = ("fn_lines", "complexity", "nesting", "width", "params")
@dataclass(frozen=True)
class Fn:
"""One function: its qualified key, its span (1-based, inclusive) and its four measures."""
"""One function: its qualified key, its span (1-based, inclusive) and its five measures."""
key: str
start: int
end: int
@@ -15,6 +15,7 @@ class Fn:
nesting: int
width: int # lines wider than the limit inside the span
test: bool
params: int = 0 # parameters in the signature, `self` included
def measures(self):
return {kind: getattr(self, kind) for kind in KINDS}
+9 -2
View File
@@ -1,4 +1,4 @@
"""Python functions of a source text, measured with the same four measures as the Rust ones (see rmetrics).
"""Python functions of a source text, measured with the same five measures as the Rust ones (see rmetrics).
complexity = 1 + `if`, conditional expression, `for`, `while`, `except`, `match` case, comprehension (and each of its
`if`s) and every extra operand of `and`/`or`. nesting = the deepest chain of compound statements (`if`, loops, `try`,
@@ -58,6 +58,13 @@ def nesting(stmts, depth=0):
inner = [nesting(block, depth + extra) for stmt in compound for block, extra in _blocks(stmt)]
return max([depth] + inner)
def param_count(fn):
"""Parameters of a def: positional, keyword-only, `*args` and `**kwargs`; `self` and `cls` count."""
args = fn.args
named = len(args.posonlyargs) + len(args.args) + len(args.kwonlyargs)
return named + (args.vararg is not None) + (args.kwarg is not None)
def _collect(body, chain, test, found):
for node in body:
if isinstance(node, SCOPES):
@@ -76,5 +83,5 @@ def scan(text, wide, test=False):
key = name + (f"#{seen[name]}" if seen[name] > 1 else "")
end = node.end_lineno
result.append(Fn(key, node.lineno, end, end - node.lineno + 1, complexity(node), nesting(node.body),
count_wide(wide, node.lineno, end), is_test))
count_wide(wide, node.lineno, end), is_test, param_count(node)))
return result
+46 -5
View File
@@ -1,4 +1,4 @@
"""Rust functions of a source text: qualified key, span and the four measures (see rmetrics for the rules).
"""Rust functions of a source text: qualified key, span and the five measures (see rmetrics for the rules).
A function runs from its `fn` keyword to the closing brace of its body, so its line count is signature plus body. Its
key is the chain of enclosing `impl`/`trait`/`mod`/`fn` names and its own name (`Type::method`, `Trait for
@@ -130,6 +130,43 @@ def _open_bracket(toks, j):
return -1
def _list_start(toks, j):
"""Index of the `(` that opens the parameter list after the fn name (past generics `<...>`); None without one."""
depth = 0
for k in range(j, len(toks)):
depth += _angle(toks, k)
if depth == 0 and _punct(toks[k]) == "(":
return k
if depth == 0 and _punct(toks[k]) in ("{", ";"):
return None
return None
def _depth_step(toks, k):
"""+1 for an opening `( [ { <`, -1 for the closing one (not the `>` of `->`), else 0."""
text = _punct(toks[k])
if text and text in "([{":
return 1
return -1 if text and text in ")]}" else _angle(toks, k)
def param_count(toks, j):
"""Parameters of the fn whose name is before `j`, `self` included: the non-empty comma-separated parts."""
start = _list_start(toks, j)
if start is None:
return 0
depth, count, part = 1, 0, False
for k in range(start + 1, len(toks)):
depth += _depth_step(toks, k)
if depth == 0:
break
if depth == 1 and _punct(toks[k]) == ",":
count, part = count + part, False
else:
part = True
return count + part
def _is_test_attr(attr):
return "cfg(" in attr and re.search(r"\btest\b", attr) is not None and "not(test" not in attr
@@ -150,8 +187,9 @@ def has_test_cfg(toks, i):
class _Rec:
def __init__(self, name, key, start, body, test):
self.name, self.key, self.start, self.body, self.test = name, key, start, body, test
def __init__(self, name, key, start, body):
self.name, self.key, self.start, self.body = name, key, start, body
self.test, self.params = False, 0
self.end = -1
self.children = []
@@ -192,7 +230,10 @@ class _Scanner:
key = "::".join([f.label for f in self.stack if f.label] + [name])
self.counts[key] = self.counts.get(key, 0) + 1
key += f"#{self.counts[key]}" if self.counts[key] > 1 else ""
self.fn_at[body] = _Rec(name, key, i, body, any(f.test for f in self.stack))
rec = _Rec(name, key, i, body)
rec.test = any(f.test for f in self.stack)
rec.params = param_count(self.toks, i + 2)
self.fn_at[body] = rec
def on_item(self, i):
header = item_header(self.toks, i)
@@ -226,5 +267,5 @@ def scan(text, wide):
complexity, nesting = rmetrics.metrics(toks, rec.body + 1, rec.end, rec.children)
first, last = toks[rec.start].line, toks[rec.end].line
result.append(model.Fn(rec.key, first, last, last - first + 1, complexity, nesting,
model.count_wide(wide, first, last), rec.test))
model.count_wide(wide, first, last), rec.test, rec.params))
return sorted(result, key=lambda fn: fn.start)