Coverage for src/rhiza_task/tasks/python.py: 100%

127 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-11-30 09:28 +0000

1"""The Python language layer: python.mk, as tasks. 

2 

3python.mk is 312 lines, over half of the synced make. Most of it converts to the 

4declarative form in :mod:`rhiza_task.spec`; ``test`` is the one recipe that does not, and 

5it is written out in full below. 

6 

7``complexity`` is the one task here with no make ancestor. It lives in this module because 

8radon is a Python tool and the gate is therefore Python-layer, even though its section is 

9``Quality`` alongside the neutral gates it reads like. 

10""" 

11 

12from __future__ import annotations 

13 

14import json 

15import shutil 

16 

17from ..config import Config 

18from ..spec import REGISTRY, Failed, Guard, Skip, task 

19from ..uv import uv, uv_run, uvx 

20from .quality import install_hooks 

21 

22PYTEST_WITHS = ( 

23 "pytest>=9.1.0", 

24 "pytest-cov>=5.0.0", 

25 "pytest-xdist>=3.5.0", 

26 "pytest-html>=4.1.0", 

27 "pytest-timeout>=2.2.0", 

28 "pytest-mock>=3.12.0", 

29) 

30"""What ``test`` injects. 

31 

32A named tuple of packages rather than a literal in the call, so CI and this package's own 

33tests can assert on it. The make recipe's six ``--with`` flags are invisible to anything 

34but a human reading the recipe. 

35 

36**The floors change nothing under the default resolution** -- uv takes the newest of each 

37either way -- and they are not there for it. ``test-lowest`` runs these same six through 

38``--resolution lowest-direct``, which applies to every *direct* requirement including the 

39injected ones, and a bare ``pytest`` there resolves to the oldest release uv can see -- 

40``pytest 2.0.0``, whose sdist does not build -- so the gate fails on its own instrumentation 

41without ever reaching the floors it was asked about. Each name therefore carries the oldest version this package is 

42willing to run a suite with. 

43 

44They bound the *instrumentation* and nothing else, which is the boundary to know before 

45reading a failure: ``--with`` is an overlay uv resolves separately from the project, so a 

46floor here cannot rescue a bare name in the manifest under test -- and should not. A 

47requirement a repository declares without a lower bound has no floor for this gate to read 

48back, and saying so is the gate working. 

49 

50The pytest floor is set by the template's ``pytest.ini``, not by this package: since rhiza 

51v1.14.2 it carries ``strict_markers`` / ``strict_config`` as ini keys under 

52``--strict-config``, and pytest 8 rejects both as unknown, so every ``test-lowest`` run at 

53``pytest 8.0.0`` failed before collecting a test. 9.1 rather than 9.0 because 9.0.0-9.0.2 

54also ignore ``--strict-markers`` / ``--strict-config`` when they arrive through ``addopts``. 

55 

56That makes them a claim, and the claim is read back rather than asserted: ``ci.yml``'s 

57``python-layer`` runs ``test-lowest`` against a real project on Linux and Windows, which is 

58where a floor that cannot actually run ``-n auto`` shows up. 

59""" 

60 

61PYTEST_INTERNAL_ERROR = 3 

62"""pytest's INTERNALERROR. 

63 

64Distinct from test failure (1), interruption (2) and usage error (4), which is what makes 

65retrying on it safe: it means the *runner* broke during worker or session teardown -- the 

66xdist ``worker_workerfinished`` KeyError, or a pytest-html report-write race -- not that a 

67test failed. 

68""" 

69 

70MAX_ATTEMPTS = 2 

71 

72LOWEST_DIRECT = ("--isolated", "--resolution", "lowest-direct") 

73"""How ``test-lowest`` asks uv for the floors, and why it asks in an ephemeral environment. 

74 

75``--resolution lowest-direct`` is the gate itself: every direct requirement resolves to the 

76oldest version its specifier allows and every transitive one to the newest, so what fails is 

77a floor that was never true rather than a dependency somebody else moved. 

78 

79``--isolated`` is what keeps the answer free of charge. Without it uv re-resolves the 

80*project* environment in place -- it says so, ``Ignoring existing lockfile due to change in 

81resolution mode`` -- and leaves both ``.venv`` and ``uv.lock`` downgraded when the gate 

82finishes. On a runner that is invisible; on a developer's machine it is a gate that rewrites 

83a tracked file and silently changes what every later task runs against. An ephemeral 

84environment costs one resolve per invocation and leaves nothing behind. 

85""" 

86 

87 

88# `setup` first, and in all three layers: a native library needed to *build* a wheel has to 

89# be on the machine before `uv sync`, not after it. See tasks/setup.py for why the hook is 

90# anchored on `install` rather than run by the workflows. 

91@task("install", "create the venv and sync dependencies", section="Python", layer="python", needs=("setup",)) 

92def install(cfg: Config) -> None: 

93 """Create ``.venv`` if absent, sync from the lock file, install the git hooks. 

94 

95 Args: 

96 cfg: The resolved config. 

97 

98 Raises: 

99 Skip: When the project has no ``pyproject.toml``. 

100 Failed: When the lock file is out of sync, or a step exits non-zero. 

101 """ 

102 venv = cfg.root / ".venv" 

103 if not venv.is_dir(): 

104 uv("venv", "--python", cfg.python_version, str(venv), cwd=cfg.root) 

105 else: 

106 print(f"[INFO] using existing virtual environment at {venv}") 

107 

108 if not (cfg.root / "pyproject.toml").is_file(): 

109 raise Skip("no pyproject.toml") 

110 

111 frozen: tuple[str, ...] = () 

112 if (cfg.root / "uv.lock").is_file(): 

113 # python.mk runs this check, swallows its output and prints three lines of 

114 # guidance on failure. The check is worth keeping; the guidance belongs with it 

115 # rather than in a shell heredoc. 

116 if uv("lock", "--check", cwd=cfg.root, check=False): 

117 raise Failed(1, "uv.lock is out of sync with pyproject.toml -- run `uv lock`") 

118 frozen = ("--frozen",) 

119 

120 # --inexact: leave packages uv did not manage in place instead of pruning them on 

121 # every run, so repeated task invocations do not churn the environment. Per-task 

122 # tooling is provisioned on the fly by uv.py, so there is no separate step for it. 

123 uv("sync", *cfg.uv_sync_args, "--inexact", *frozen, cwd=cfg.root) 

124 

125 install_hooks(cfg) 

126 

127 

128@task( 

129 "test", 

130 "run all tests", 

131 section="Python", 

132 layer="python", 

133 needs=("install",), 

134 guards=(Guard("tests_folder", glob="test_*.py", reason="no test files found"),), 

135) 

136def test(cfg: Config) -> None: 

137 """Run the suite with coverage, retrying once on a pytest-internal teardown error. 

138 

139 This is the recipe that justifies a real language. In python.mk it is a 40-line shell 

140 ``while :; do ... done`` inside a make recipe, with ``$$`` escaping on every variable, 

141 ``set --`` used to build the argument list because make cannot hold an array, and the 

142 retry condition spelled ``if [ $$status -ne 3 ]; then exit $$status; fi``. 

143 

144 Args: 

145 cfg: The resolved config. 

146 

147 Raises: 

148 Failed: When pytest reports test failures, or reports an internal error twice. 

149 """ 

150 reports = cfg.root / "_tests" 

151 shutil.rmtree(reports, ignore_errors=True) 

152 

153 args = [*_pytest_args(cfg)] 

154 if cfg.path("source_folder").is_dir(): 

155 args += coverage_args(cfg) 

156 else: 

157 # Not a Skip: the tests exist and must run. Only coverage is unavailable. 

158 print(f"[WARN] source folder '{cfg.source_folder}' not found; running without coverage") 

159 args.append("--html=_tests/html-report/report.html") 

160 

161 for attempt in range(1, MAX_ATTEMPTS + 1): 

162 # Stale data first: a crashed run can leave a corrupt .coverage file, which then 

163 # reports a false 0% on the next run. 

164 for stale in cfg.root.glob(".coverage*"): 

165 stale.unlink(missing_ok=True) 

166 (reports / "html-coverage").mkdir(parents=True, exist_ok=True) 

167 (reports / "html-report").mkdir(parents=True, exist_ok=True) 

168 

169 code = uv_run("pytest", *args, cwd=cfg.root, withs=PYTEST_WITHS, check=False) 

170 if code != PYTEST_INTERNAL_ERROR: 

171 if code: 

172 raise Failed(code, "tests failed") 

173 return 

174 if attempt == MAX_ATTEMPTS: 

175 raise Failed(code, f"pytest reported an internal (teardown) error {attempt}x") 

176 print(f"[WARN] pytest exited {code} (xdist teardown race); retrying {attempt + 1}/{MAX_ATTEMPTS}") 

177 

178 

179@task( 

180 "coverage", 

181 "measure coverage and write _tests/coverage.xml", 

182 section="Python", 

183 layer="python", 

184 needs=("install",), 

185 guards=( 

186 Guard("tests_folder", glob="test_*.py", reason="no test files found"), 

187 Guard("source_folder"), 

188 ), 

189) 

190def coverage(cfg: Config) -> None: 

191 """Run the suite for its coverage reports. 

192 

193 python.mk has no ``coverage`` target: its ``test`` recipe carries the ``--cov`` flags, 

194 so the Cobertura file CI uploads and ``book`` badges is a side effect of the test gate. 

195 rust.mk and go.mk both name ``coverage`` separately, and the gate-parity contract lists 

196 it for all three layers -- so the Python layer grows the name it was missing rather than 

197 the other two losing it. 

198 

199 It is not a second test run in any meaningful sense: same suite, same floor, same 

200 output path. What it buys is a caller that wants the report without asserting anything 

201 about the HTML test report, and one name that means the same thing in all three layers. 

202 

203 Args: 

204 cfg: The resolved config. 

205 """ 

206 (cfg.root / "_tests" / "html-coverage").mkdir(parents=True, exist_ok=True) 

207 for stale in cfg.root.glob(".coverage*"): 

208 stale.unlink(missing_ok=True) 

209 uv_run("pytest", *_pytest_args(cfg), *coverage_args(cfg), cwd=cfg.root, withs=PYTEST_WITHS) 

210 

211 

212@task( 

213 "test-lowest", 

214 "run the tests against the oldest dependencies the manifest allows", 

215 section="Python", 

216 layer="python", 

217 needs=("install",), 

218 guards=(Guard("tests_folder", glob="test_*.py", reason="no test files found"),), 

219) 

220def test_lowest(cfg: Config) -> None: 

221 """Run the suite with every direct dependency resolved to its declared floor. 

222 

223 A declared floor is a claim -- ``typer>=0.15`` says the package works with typer 0.15 -- 

224 and ``--frozen`` everywhere else means nothing reads it back: the lock file resolves 

225 whatever is newest, so a floor can be years stale while every gate stays green. 

226 

227 **It is a task rather than a workflow step, and that is the whole of #169.** rhiza's 

228 ``lowest-deps`` job called plain ``uv`` because there was nothing here to call, and a 

229 caller that bypasses the task graph bypasses ``setup`` with it -- so a repository whose 

230 ``local-setup.sh`` provisions a native binary got a green ``test`` and a red 

231 ``lowest-deps`` on identical code, reporting a resolution problem that was really a 

232 missing ``dot`` on the runner. Arriving through ``install`` puts this gate back inside 

233 the single insertion point :mod:`rhiza_task.tasks.setup` documents, which is the whole 

234 argument for anchoring the hook there. 

235 

236 Three things it shares rather than restates, because the job it replaces restated all 

237 three by hand and the copy had already drifted by one flag: 

238 

239 * ``_pytest_args``, so the suite is selected the way ``test`` and ``coverage`` select it. 

240 * :data:`PYTEST_WITHS`, so ``-n auto`` has an xdist to run under -- see that constant for 

241 why its floors exist and why they are invisible anywhere else. 

242 * :attr:`~rhiza_task.config.Config.uv_sync_args`, because "which of the manifest's 

243 optional pieces count" is the same question ``install`` asks, and a repository that 

244 answered it once has answered it here. 

245 

246 No coverage flags, deliberately. The subject is whether the suite *runs* at the floors, 

247 and a coverage floor here would either report what ``test`` already reported or give this 

248 gate a second way to go red that has nothing to do with resolution. 

249 

250 Args: 

251 cfg: The resolved config. 

252 

253 Raises: 

254 Failed: When pytest reports test failures. 

255 """ 

256 uv_run( 

257 "pytest", 

258 *_pytest_args(cfg), 

259 cwd=cfg.root, 

260 withs=PYTEST_WITHS, 

261 uv_args=(*LOWEST_DIRECT, *cfg.uv_sync_args), 

262 ) 

263 

264 

265def _pytest_args(cfg: Config) -> list[str]: 

266 """Return the arguments both pytest-running gates share. 

267 

268 Args: 

269 cfg: The resolved config. 

270 

271 Returns: 

272 Parallelism, the per-test timeout, and the two folders the testing extras own. 

273 """ 

274 return [ 

275 "-n", 

276 "auto", 

277 # Here rather than in pytest.ini, because these are the runs that provision 

278 # pytest-timeout (PYTEST_WITHS) -- see ``test_timeout`` in config.py. 

279 f"--timeout={cfg.test_timeout}", 

280 f"--ignore={cfg.tests_folder}/benchmarks", 

281 f"--ignore={cfg.tests_folder}/stress", 

282 ] 

283 

284 

285def coverage_args(cfg: Config) -> list[str]: 

286 """Return the ``--cov`` flags, including the Cobertura path the other layers write to. 

287 

288 Shared by ``test`` and ``coverage`` so the two cannot drift: ``_tests/coverage.xml`` is 

289 the file book.mk's badge step reads and CI uploads, and rust.mk and go.mk go out of 

290 their way to write it at exactly that path. 

291 

292 Args: 

293 cfg: The resolved config. 

294 

295 Returns: 

296 The coverage flags. 

297 """ 

298 return [ 

299 f"--cov={cfg.source_folder}", 

300 "--cov-report=term", 

301 "--cov-report=html:_tests/html-coverage", 

302 "--cov-report=json:_tests/coverage.json", 

303 "--cov-report=xml:_tests/coverage.xml", 

304 f"--cov-fail-under={cfg.coverage_fail_under}", 

305 ] 

306 

307 

308@task( 

309 "typecheck", 

310 "run ty and/or mypy (typechecker = ty | mypy | both)", 

311 section="Python", 

312 layer="python", 

313 needs=("install",), 

314 guards=(Guard("source_folder"),), 

315) 

316def typecheck(cfg: Config) -> None: 

317 """Run the configured type checker(s) over the source folder. 

318 

319 The make recipe is a shell ``case`` with four branches, the fourth of which validates 

320 the setting and errors. Validation moved to :meth:`Config.__post_init__`, so an 

321 invalid value fails before a tool is provisioned, and what is left is a loop. 

322 

323 **What each checker is provisioned *as* is a setting, and it has to be.** The ``--with`` 

324 here used to carry the bare name, so the gate ran whatever was newest at the moment it 

325 ran -- and for a 0.0.x checker that is not a detail: one consumer saw a single warning 

326 locally, where ``--with ty`` reused the ty their lock file supplied, and twenty-four 

327 errors on a runner that had none to reuse, on the same commit. An unchanged repository 

328 could go from green to red overnight, and two machines could disagree about it on the 

329 same day. See #170, and ``ty_version`` in :mod:`rhiza_task.config` for why ty is pinned 

330 by default and mypy is not. 

331 

332 Args: 

333 cfg: The resolved config. 

334 """ 

335 checkers = ("ty", "mypy") if cfg.typechecker == "both" else (cfg.typechecker,) 

336 for checker in checkers: 

337 # The asymmetry is preserved from python.mk: mypy runs --strict, ty does not. 

338 # `--error-on-warning` is ty's current default, spelled out because `ty_version` is a 

339 # setting: ty has changed what a warning-only run exits with before, and a consumer on 

340 # another version would otherwise get a gate that shows warnings and passes. The flag 

341 # pins the meaning to "any diagnostic fails", whichever ty runs (jebel-quant/rhiza#1833). 

342 ty_args = ("check", "--error-on-warning", cfg.source_folder) 

343 args = ty_args if checker == "ty" else ("--strict", cfg.source_folder) 

344 # The second asymmetry, and this one is not python.mk's: `ty` is provisioned at an 

345 # exact version and mypy is not. See `ty_version` in config.py for why -- both are 

346 # settings, so a consumer needing the other answer changes it rather than the task. 

347 requirement = f"ty{cfg.ty_version}" if checker == "ty" else f"mypy{cfg.mypy_version}" 

348 uv_run(checker, *args, cwd=cfg.root, withs=(requirement,)) 

349 

350 

351@task( 

352 "security", 

353 "run the bandit security scan", 

354 section="Python", 

355 layer="python", 

356 needs=("install",), 

357 guards=(Guard("source_folder"),), 

358) 

359def security(cfg: Config) -> None: 

360 """Scan the source folder with bandit. 

361 

362 The scan scope lives in ``.bandit`` rather than in this argument list, so that every 

363 runner -- this task, the pre-commit hook, CI -- sees the same one. ``--ini`` is passed 

364 only when that file exists: python.mk passes it unconditionally, and bandit treats a 

365 missing ini as a usage error, so a project without one gets a red gate reporting a 

366 configuration problem as if it were a security finding. 

367 

368 ``security`` does not mean the same thing in all three layers, and the asymmetry is 

369 inherited rather than introduced here. Rust runs ``cargo deny check advisories`` and Go 

370 runs ``govulncheck ./...`` -- both scan *dependencies* against an advisory database. 

371 Bandit is SAST: it lints the source this repository owns and never looks at what is 

372 installed. So Python, which has the largest advisory surface of the three, is the one 

373 layer whose ``security`` gate is not a dependency scan. 

374 

375 No ``pip-audit`` here is a decision taken upstream, not an omission: ``jebel-quant/rhiza`` 

376 dropped it in #1416 along with rhiza-tools, and pins its absence with a test 

377 (``tests/docs/test_doc_consistency.py`` -- "pip-audit is deliberately not wired up; 

378 this pins the fact the gate depends on"). This module is owned by this repository and 

379 nothing syncs it, so adding a scan here is *possible* -- but it would put a gate in 

380 consumers' CI that the template they also follow says is not there, and a transitive 

381 advisory with no fix available would then fail a run the template would have passed. 

382 Closing the gap belongs upstream, where both halves move together. Recorded here so 

383 the next reader does not have to rediscover which of the two it is. 

384 

385 What that argument covers is the *shipped task*, and it is worth being precise about the 

386 limit, because the paragraph above used to be the only note on the subject and so read as 

387 "nothing anywhere audits dependencies". This repository does audit its own: ``weekly.yml`` 

388 exports the committed lockfile and runs ``pip-audit`` over it on a schedule. Nothing about 

389 that reaches a consumer -- no task name, no prerequisite of ``all``, nothing a 

390 ``uvx rhiza-task`` invocation can find -- which is exactly why it is a workflow job and not 

391 the two lines it would take to add here. 

392 

393 So the honest summary is that the gap is closed for this repository and open for consumers, 

394 deliberately and in that order. If it is ever closed for consumers too, this is the place 

395 that changes, and the note above is the argument that has to be answered first. 

396 

397 Args: 

398 cfg: The resolved config. 

399 """ 

400 ini = ("--ini", ".bandit") if (cfg.root / ".bandit").is_file() else () 

401 uvx("bandit", "-r", cfg.source_folder, "-ll", "-q", *ini, cwd=cfg.root) 

402 

403 

404@task("deps", "run deptry over the contributed folders", section="Python", layer="python", needs=("install",)) 

405def deps(cfg: Config) -> None: 

406 """Check declared dependencies against actual imports. 

407 

408 ``DEPTRY_FOLDERS`` and ``DEPTRY_IGNORE`` were make accumulators that each bundle 

409 appended to, which worked only because of include order. Here the folder set is 

410 *derived*: the source folder when it exists, plus the marimo folder when the marimo 

411 tasks are registered and that folder exists. DEP004 (misplaced development dependency) 

412 is ignored for the same reason marimo.mk ignores it -- notebooks legitimately import 

413 development dependencies. 

414 

415 deptry runs in the project environment (``uv run --with deptry``), not via ``uvx``. It 

416 maps each declared distribution to its import name by reading *installed* metadata, so 

417 in an isolated env it guesses the distribution name and reports ``pyyaml``/``yaml`` or 

418 ``scikit-learn``/``sklearn`` as both missing (DEP001) and unused (DEP002) -- leaving every 

419 consumer to maintain ``[tool.deptry.package_module_name_map]`` by hand (#222). 

420 

421 Args: 

422 cfg: The resolved config. 

423 

424 Raises: 

425 Skip: When no contributed folder exists. 

426 """ 

427 folders = [cfg.source_folder] if cfg.path("source_folder").is_dir() else [] 

428 ignores = list(cfg.deptry_ignore) 

429 if "marimo" in REGISTRY and cfg.path("marimo_folder").is_dir(): 

430 folders.append(cfg.marimo_folder) 

431 ignores += ["--ignore", "DEP004"] 

432 if not folders: 

433 raise Skip("no deptry folders") 

434 uv_run("deptry", *folders, *ignores, cwd=cfg.root, withs=("deptry",)) 

435 

436 

437@task("license", "scan for copyleft licences", section="Python", layer="python", needs=("install",)) 

438def license_(cfg: Config) -> None: 

439 """Fail on GPL/LGPL/AGPL among the installed distributions. 

440 

441 ``--partial-match`` is load-bearing: without it pip-licenses compares against the whole 

442 licence string, and ``GPL`` never equals a real classifier such as "GNU General Public 

443 License v2 or later (GPLv2+)", so the gate passed with a GPL package installed. 

444 

445 The docutils exemption is derived rather than accumulated. marimo depends on docutils, 

446 which is offered under a *choice* of licences and reports all of them as one string -- 

447 "BSD License; GNU General Public License (GPL); Public Domain". pip-licenses has no 

448 notion of *or*, so ``--partial-match`` fires on the copyleft option even where a 

449 permissive one is taken. 

450 

451 Args: 

452 cfg: The resolved config. 

453 """ 

454 ignored = list(cfg.license_ignore_packages) 

455 if "marimo" in REGISTRY and "docutils" not in ignored: 

456 ignored.append("docutils") 

457 args = [f"--fail-on={';'.join(cfg.license_fail_on)}", "--partial-match"] 

458 if ignored: 

459 # --ignore-packages errors on a bare flag, so it is omitted entirely when nothing 

460 # is exempted. 

461 args += ["--ignore-packages", *ignored] 

462 uv_run("pip-licenses", *args, cwd=cfg.root, withs=("pip-licenses",)) 

463 

464 

465@task( 

466 "docs-coverage", 

467 "check docstring coverage with interrogate", 

468 section="Python", 

469 layer="python", 

470 needs=("install",), 

471 guards=(Guard("source_folder"),), 

472) 

473def docs_coverage(cfg: Config) -> None: 

474 """Enforce :attr:`Config.docs_coverage_fail_under` over the source and test folders. 

475 

476 The floor was the literal ``100`` until it became a setting; it still *defaults* to 

477 100, so a repo that configures nothing is gated exactly as it was. The field's own 

478 comment carries why it is now askable. 

479 

480 Args: 

481 cfg: The resolved config. 

482 """ 

483 folders = [f for f in (cfg.source_folder, cfg.tests_folder) if (cfg.root / f).is_dir()] 

484 uv_run( 

485 "interrogate", 

486 "-vv", 

487 "--fail-under", 

488 str(cfg.docs_coverage_fail_under), 

489 "--ignore-init-method", 

490 "--ignore-magic", 

491 *folders, 

492 cwd=cfg.root, 

493 withs=("interrogate",), 

494 ) 

495 

496 

497@task( 

498 "complexity", 

499 "fail on a block above the cyclomatic-complexity ceiling", 

500 section="Quality", 

501 layer="python", 

502 guards=(Guard("source_folder"),), 

503) 

504def complexity(cfg: Config) -> None: 

505 """Fail when any block's cyclomatic complexity exceeds :attr:`Config.complexity_max`. 

506 

507 The one task here that is not a python.mk port. It exists because this repository's own 

508 convention -- a C-ranked block carries a comment arguing why the flat form is preferred 

509 -- committed to a *number* in ``config.py``, and nothing read it back. A stated ceiling 

510 that only a human checks is the same shape as a doctest no gate executes: correct today, 

511 stale-proof only by discipline, in the one place growth is expected. 

512 

513 Why the report goes through a file rather than a pipe: radon's verdict is a number per 

514 block, so the gate has to read its output, and ``-O`` is how radon hands output to 

515 something other than a terminal. That keeps the invocation a fixed argument vector with 

516 no shell and no capturing variant of :func:`~rhiza_task.uv.uvx` -- the same reason every 

517 other call in this package is one. 

518 

519 ``closures`` is deliberately not walked. radon only fills it under ``--show-closures``, 

520 which is not passed, so a nested function's complexity is already counted in its 

521 parent's -- walking the empty list would suggest a coverage this gate does not have. 

522 

523 Args: 

524 cfg: The resolved config. 

525 

526 Raises: 

527 Skip: When radon produced no report, so nothing was measured. 

528 Failed: When at least one block is above the ceiling. 

529 """ 

530 report = cfg.root / "_tests" / "complexity.json" 

531 report.parent.mkdir(parents=True, exist_ok=True) 

532 # Stale data first, for the reason `test` unlinks `.coverage*`: a report left by an 

533 # earlier run would be read as this run's verdict if radon failed to write. 

534 report.unlink(missing_ok=True) 

535 

536 uvx("radon", "cc", cfg.source_folder, "--json", "--output-file", str(report), cwd=cfg.root) 

537 if not report.is_file(): 

538 raise Skip("radon wrote no report") 

539 

540 over = _over_ceiling(json.loads(report.read_text()), cfg.complexity_max) 

541 for label, score in over: 

542 print(f"{label}: {score}") 

543 if over: 

544 raise Failed(1, f"{len(over)} block(s) above the complexity ceiling of {cfg.complexity_max}") 

545 print(f"[INFO] no block above the complexity ceiling of {cfg.complexity_max}") 

546 

547 

548def _over_ceiling(measured: dict[str, object], ceiling: int) -> list[tuple[str, int]]: 

549 """Return the blocks above ``ceiling``, worst first. 

550 

551 radon keys its JSON by path, and the value is either a list of blocks or -- for a file 

552 it could not parse -- a dict carrying an ``error``. The dict is skipped rather than 

553 raised on: an unparseable file is ruff's finding to report, and failing the complexity 

554 gate for it would put one syntax error behind two red gates. 

555 

556 Args: 

557 measured: radon's parsed ``cc --json`` output. 

558 ceiling: The highest complexity a block may have. 

559 

560 Returns: 

561 ``(label, complexity)`` pairs, highest complexity first, then by label so the 

562 ordering is total and the output is diffable between runs. 

563 """ 

564 over: list[tuple[str, int]] = [] 

565 for path, blocks in measured.items(): 

566 if not isinstance(blocks, list): 

567 continue 

568 for block in blocks: 

569 score = int(block["complexity"]) 

570 if score <= ceiling: 

571 continue 

572 qualified = f"{block['classname']}.{block['name']}" if block.get("classname") else block["name"] 

573 over.append((f"{path}:{block['lineno']} {qualified}", score)) 

574 return sorted(over, key=lambda item: (-item[1], item[0])) 

575 

576 

577# `complexity` is deliberately *not* a prerequisite below, and the reason is semver rather 

578# than doubt about the gate. `all` is the aggregate every consumer's CI invokes, so adding a 

579# prerequisite to it fails builds in repositories that changed nothing -- a breaking change 

580# shipped as a feature. A consumer opts in by naming it, in `all`'s own `[tool.rhiza-task]` 

581# repo or in a workflow step, and this repository does the latter in ci.yml's `gates` job. 

582# 

583# Stated here for the reason ci.yml states the same thing about `semgrep`: a reader has to 

584# be able to tell "outside `all` on purpose" from "forgotten". 

585@task( 

586 "all", 

587 "run every gate, as CI does", 

588 section="Python", 

589 layer="python", 

590 needs=("fmt", "deps", "test", "docs-coverage", "security", "license", "typecheck", "rhiza-test"), 

591) 

592def all_(cfg: Config) -> None: 

593 """Aggregate. The body is empty because ``needs`` *is* the definition. 

594 

595 python.mk's ``all`` named four gates that lived in the optional ``tests`` bundle, so a 

596 project syncing ``core + python-core`` without it had an ``all`` that could not run. 

597 Here an unregistered prerequisite is skipped by the runner, so the failure mode does 

598 not exist. 

599 

600 Args: 

601 cfg: Unused; the prerequisites do the work. 

602 """