Answer architecture round 1: make cognitive complexity a pure recursion, share a tied top-k cut evenly, count unresolved places, skip a run whose commit is gone, fail on a file that does not parse, link the history's format and its reader both ways, reword item 85's order, and record the worse ruling

This commit is contained in:
2026-10-08 21:48:05 +02:00
parent 8a2dbd70f1
commit 7d440c6ee1
10 changed files with 143 additions and 123 deletions
+16 -9
View File
@@ -38,18 +38,20 @@ def co_changed(log: str) -> dict[str, int]:
return {path: len(others) for path, others in partners.items()}
def bench(units: list[Unit], places: list[Place], spread: dict[str, int]) -> RunScores | None:
"""How well each metric ranks the units the seats named above the rest; None when no named place is a measured unit."""
def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[str, int]) -> RunScores | None:
"""How well each metric ranks the units the seats named above the rest; None when the named units are none or all of them. unresolved counts the places that named no tracked file."""
names = {(place.path, place.name) for place in places}
named = [unit for unit in units if (unit.path, unit.name) in names]
if not named or len(named) == len(units):
return None
rest = [unit for unit in units if (unit.path, unit.name) not in names]
measured = {(unit.path, unit.name) for unit in named}
unmeasured = len({place for place in places if (place.path, place.name) not in measured})
found = {(unit.path, unit.name) for unit in named}
unmeasured = unresolved + len({place for place in places if (place.path, place.name) not in found})
scores = {}
for metric, value in METRICS.items():
scores[metric] = Score(auc([value(unit, spread) for unit in named], [value(unit, spread) for unit in rest]), top_k(units, named, lambda unit: value(unit, spread)))
named_values = [value(unit, spread) for unit in named]
rest_values = [value(unit, spread) for unit in rest]
scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values))
return RunScores(len(units), len(named), unmeasured, scores)
@@ -59,10 +61,15 @@ def auc(named: list[int], rest: list[int]) -> float:
return wins / (len(named) * len(rest))
def top_k(units: list[Unit], named: list[Unit], value: Callable[[Unit], int]) -> float:
"""The share of the metric's top k units the seats named, k being how many they named; a tie at the cut counts in order of the units."""
top = sorted(units, key=value, reverse=True)[:len(named)]
return sum(unit in named for unit in top) / len(named)
def top_k(named: list[int], rest: list[int]) -> float:
"""The share of the metric's k highest units the seats named, k being how many they named. Units tied at the cut share its remaining seats evenly, as a random order of them would."""
k = len(named)
cut = sorted(named + rest, reverse=True)[k - 1]
above = sum(value > cut for value in named)
seats = k - above - sum(value > cut for value in rest)
tied_named = sum(value == cut for value in named)
tied = tied_named + sum(value == cut for value in rest)
return (above + seats * tied_named / tied) / k
def medians(runs: list[RunScores]) -> dict[str, Score]:
+18 -7
View File
@@ -15,7 +15,9 @@ medians. Places that name no Python function or method, such as a section of a m
counted as unmeasured.
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
history cannot be read, a run's commit is missing, or no scoring run names a measured unit.
history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A
run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the
table.
"""
import pathlib
import subprocess
@@ -23,7 +25,7 @@ import sys
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score
from failure import Failure
from metric_bench.python_units import measured, python_units
from metric_bench.python_units import measured, python_units, Unit
from metric_bench.places import resolved, scoring_runs, ScoringRun
@@ -45,15 +47,20 @@ def main(argv: list[str]) -> int:
except (OSError, UnicodeDecodeError) as failure:
return failed(Failure(f"could not read {history}: {failure}"))
rows = []
gone = []
for run in scoring_runs(text):
if isinstance(git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
gone.append(run.heading)
continue
scores = run_scores(run, top)
if isinstance(scores, Failure):
return failed(scores)
if scores:
rows.append((run.heading, scores))
skipped = "".join(f"\nSkipped, its commit is not in {top}: {heading}" for heading in gone)
if not rows:
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures"))
print(table(rows))
return failed(Failure(f"no scoring run in {history} names a Python function or method the bench measures; its format: ~/.claude/skills/larv-review/SKILL.md → \"History\"{skipped}"))
print(table(rows) + ("\n" + skipped if skipped else ""))
return 0
@@ -62,16 +69,20 @@ def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure:
if isinstance(listed, Failure):
return listed
tracked = listed.split("\n")
units = []
units: list[Unit] = []
for path in filter(measured, tracked):
source = git(["show", f"{run.commit}:{path}"], top)
if isinstance(source, Failure):
return source
units += python_units(path, source)
found = python_units(path, source)
if isinstance(found, Failure):
return found
units += found
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top)
if isinstance(log, Failure):
return log
return bench(units, resolved(run.places, tracked), co_changed(log))
places = resolved(run.places, tracked)
return bench(units, places, len(run.places) - len(places), co_changed(log))
def table(rows: list[tuple[str, RunScores]]) -> str:
+1
View File
@@ -4,6 +4,7 @@ import re
from markdown_sections import sections
# The format: skills/larv-review/SKILL.md §3 → "History", which names this reader.
RUN = re.compile(r"^(.+), (.+) at ([0-9a-f]{7,40})$")
SEAT_PLACES = re.compile(r"^.+, (hardest first|would restructure first):$")
# `path:line` or `:line`, then the unit's name where one follows.
+36 -93
View File
@@ -1,6 +1,9 @@
import ast
import collections
import dataclasses
import sys
from failure import Failure
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
@@ -20,12 +23,12 @@ def measured(path: str) -> bool:
return name.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in folders.split("/")
def python_units(path: str, source: str) -> list[Unit]:
"""Each module-level function and each method in source, with its metrics; a source that does not parse has none."""
def python_units(path: str, source: str) -> list[Unit] | Failure:
"""Each module-level function and each method in source, with its metrics."""
try:
tree = ast.parse(source)
except (SyntaxError, ValueError):
return []
except (SyntaxError, ValueError) as failure:
return Failure(f"could not parse {path} on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}")
units = []
for node in tree.body:
if isinstance(node, FUNCTION):
@@ -61,97 +64,37 @@ def written(node: ast.AST) -> list[ast.expr]:
# SonarSource's "Cognitive Complexity" white paper (G. Ann Campbell, 2017), read for Python: a comprehension counts as a loop and each of its `if` clauses as a condition.
def cognitive(function: ast.FunctionDef | ast.AsyncFunctionDef) -> int:
counter = Cognitive(function.name)
counter.within(function.body, 0)
return counter.score
return sum(score(node, 0, function.name) for node in function.body)
class Cognitive(ast.NodeVisitor):
def __init__(self, name: str) -> None:
self.name = name
self.nesting = 0
self.score = 0
def score(node: ast.AST, nesting: int, name: str) -> int:
"""The cognitive complexity node adds at nesting depth nesting, its children included; name is the function's own, a call to it counting as recursion."""
def inside(nodes: list, depth: int = nesting + 1) -> int:
return sum(score(child, depth, name) for child in nodes)
def within(self, nodes: list, deeper: int = 1) -> None:
self.nesting += deeper
for node in nodes:
self.visit(node)
self.nesting -= deeper
if isinstance(node, ast.If):
return 1 + nesting + branches(node, nesting, name)
if isinstance(node, ast.For | ast.AsyncFor | ast.While):
head = node.test if isinstance(node, ast.While) else node.iter
return 1 + nesting + score(head, nesting, name) + inside(node.body) + (1 + inside(node.orelse) if node.orelse else 0)
if isinstance(node, ast.Try | ast.TryStar):
handlers = sum(1 + nesting + inside(handler.body) for handler in node.handlers)
return inside(node.body, nesting) + handlers + inside(node.orelse, nesting) + inside(node.finalbody, nesting)
if isinstance(node, ast.Match):
return 1 + nesting + score(node.subject, nesting, name) + sum(inside(case.body) for case in node.cases)
if isinstance(node, ast.IfExp):
return 1 + nesting + inside([node.test, node.body, node.orelse])
if isinstance(node, ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp):
return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)))
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
return inside(node.body if isinstance(node.body, list) else [node.body])
own = 1 if isinstance(node, ast.BoolOp) or isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name else 0
return own + inside(list(ast.iter_child_nodes(node)), nesting)
def structure(self) -> None:
self.score += 1 + self.nesting
def visit_If(self, node: ast.If) -> None:
self.structure()
self.branch(node)
def branch(self, node: ast.If) -> None:
self.visit(node.test)
self.within(node.body)
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
self.score += 1
self.branch(node.orelse[0])
elif node.orelse:
self.score += 1
self.within(node.orelse)
def loop(self, node: ast.For | ast.AsyncFor | ast.While, head: ast.expr) -> None:
self.structure()
self.visit(head)
self.within(node.body)
if node.orelse:
self.score += 1
self.within(node.orelse)
def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
self.loop(node, node.iter)
visit_AsyncFor = visit_For
def visit_While(self, node: ast.While) -> None:
self.loop(node, node.test)
def visit_Try(self, node: ast.Try | ast.TryStar) -> None:
self.within(node.body, 0)
for handler in node.handlers:
self.structure()
self.within(handler.body)
self.within(node.orelse, 0)
self.within(node.finalbody, 0)
visit_TryStar = visit_Try
def visit_Match(self, node: ast.Match) -> None:
self.structure()
self.visit(node.subject)
for case in node.cases:
self.within(case.body)
def visit_IfExp(self, node: ast.IfExp) -> None:
self.structure()
self.within([node.test, node.body, node.orelse])
def visit_BoolOp(self, node: ast.BoolOp) -> None:
self.score += 1
self.generic_visit(node)
def comprehension(self, node: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp) -> None:
for generator in node.generators:
self.structure()
self.score += len(generator.ifs)
self.within(list(ast.iter_child_nodes(node)))
visit_DictComp = visit_GeneratorExp = visit_ListComp = visit_SetComp = comprehension
def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
self.within(node.body)
visit_AsyncFunctionDef = visit_FunctionDef
def visit_Lambda(self, node: ast.Lambda) -> None:
self.within([node.body])
def visit_Call(self, node: ast.Call) -> None:
if isinstance(node.func, ast.Name) and node.func.id == self.name:
self.score += 1
self.generic_visit(node)
def branches(node: ast.If, nesting: int, name: str) -> int:
"""An if's test and bodies; an elif or else adds 1 at no extra depth."""
total = score(node.test, nesting, name) + sum(score(child, nesting + 1, name) for child in node.body)
if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
return total + 1 + branches(node.orelse[0], nesting, name)
return total + (1 + sum(score(child, nesting + 1, name) for child in node.orelse) if node.orelse else 0)
+38 -9
View File
@@ -9,8 +9,9 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from metric_bench.bench import auc, bench, co_changed
from metric_bench.bench import auc, bench, co_changed, top_k
from metric_bench.python_units import cognitive, measured, python_units, Unit
from failure import Failure
from test_loop_claude_black_box import host_env
from metric_bench.places import Place, resolved, scoring_runs
@@ -59,6 +60,16 @@ class Cognitive(unittest.TestCase):
pass
"""), 1 + 2 + 2 + 1 + 1)
def test_nests_a_while_a_lambda_and_an_inner_function(self):
self.assertEqual(scored("""
def f(a):
while a:
g = lambda b: 1 if b else 2
def h():
if a:
pass
"""), 1 + 3 + 3)
def test_counts_a_comprehension_as_a_loop_and_its_conditions(self):
self.assertEqual(scored("""
def f(rows):
@@ -88,8 +99,10 @@ class Units(unittest.TestCase):
def test_measures_python_files_outside_the_tests(self):
self.assertEqual([path for path in ["a.py", "bin/test_a.py", "a_test.py", "tests/b.py", "e2e-tests/c.py", "README.md"] if measured(path)], ["a.py", "e2e-tests/c.py"])
def test_a_source_that_does_not_parse_has_no_units(self):
self.assertEqual(python_units("a.py", "def ("), [])
def test_a_source_that_does_not_parse_is_a_failure_naming_it(self):
failure = python_units("a.py", "def (")
assert isinstance(failure, Failure)
self.assertIn("could not parse a.py", failure.reason)
class Places(unittest.TestCase):
@@ -107,6 +120,10 @@ class Places(unittest.TestCase):
- `skills/x/SKILL.md:77` "Architecture"
- `bin/tool/cycle/states.py:69` `transition`, with `cycle/run.py:55` `step` and `:90` `close`
Inherited architect, would restructure first:
- `bin/tool/cycle/judge.py:31` `run_judge`
## 2026-10-08T18:37:21Z, PR #228 at 2682668, against 8c9bf09
Mid A, decided by:
@@ -117,7 +134,7 @@ class Places(unittest.TestCase):
def test_reads_each_scoring_runs_places_and_leaves_paired_rulings_out(self):
runs = scoring_runs(self.HISTORY)
self.assertEqual([(run.heading, run.commit) for run in runs], [("2026-10-08T12:50:49Z, PR #224 at a58a0a8", "a58a0a8")])
self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close")])
self.assertEqual(runs[0].places, [Place("skills/x/SKILL.md", None), Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("cycle/run.py", "close"), Place("bin/tool/cycle/judge.py", "run_judge")])
def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self):
tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"]
@@ -136,16 +153,21 @@ class Bench(unittest.TestCase):
def test_co_changed_counts_each_files_distinct_partners(self):
self.assertEqual(co_changed("@@\na.py\nb.py\n@@\na.py\nc.py\n@@\na.py"), {"a.py": 2, "b.py": 1, "c.py": 1})
def test_top_k_shares_the_seats_at_a_tied_cut_evenly(self):
self.assertEqual(top_k([0, 0], [0, 0, 0, 0]), 1 / 3)
self.assertEqual(top_k([5, 1], [1, 1]), 2 / 3)
def test_scores_the_named_units_and_counts_places_no_unit_measures(self):
units = [Unit("a.py", "hard", 9, 40, 0), Unit("a.py", "easy", 1, 5, 0), Unit("b.py", "plain", 2, 6, 0)]
run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], {"a.py": 1})
run = bench(units, [Place("a.py", "hard"), Place("doc.md", None)], 2, {"a.py": 1})
assert run is not None
self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 1))
self.assertEqual((run.units, run.named, run.unmeasured), (3, 1, 3))
self.assertEqual((run.scores["cognitive complexity"].auc, run.scores["cognitive complexity"].top_k), (1.0, 1.0))
self.assertEqual(run.scores["shared state"].auc, 0.5)
self.assertEqual((run.scores["shared state"].auc, run.scores["shared state"].top_k), (0.5, 1 / 3))
def test_a_run_naming_no_measured_unit_is_not_scored(self):
self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], {}))
def test_a_run_naming_no_unit_or_every_unit_is_not_scored(self):
self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("doc.md", None)], 0, {}))
self.assertIsNone(bench([Unit("a.py", "f", 1, 1, 0)], [Place("a.py", "f")], 0, {}))
class BlackBox(unittest.TestCase):
@@ -187,6 +209,13 @@ class BlackBox(unittest.TestCase):
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
self.assertEqual(self.run_tool(top, "--x").returncode, 1)
def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self):
top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at 0123456\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
ran = self.run_tool(top)
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("Skipped, its commit is not in", ran.stdout)
self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1])
def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self):
top = self.project("# Comprehension history\n\n## 2026-10-08T12:50:49Z, PR #1 at COMMIT\n\nJunior A, hardest first:\n\n- `a.py:1` `hard`\n")
ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md")))
+1 -1
View File
@@ -11,5 +11,5 @@ class Types(unittest.TestCase):
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
if shutil.which("uv") is None:
self.fail("uv on PATH fetches mypy; see README.md's Test line")
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True)
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude", "-p", "metric_bench", "-m", "rank_todo", "-p", "reading_cost", "-m", "statusline"], capture_output=True, cwd=ROOT / "bin", text=True)
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)