Measure what would lower review's token use: bench static metrics against the panel's hardest places, and rescore item 73 by its reports' measured cost
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import collections
|
||||
import dataclasses
|
||||
import statistics
|
||||
from typing import Callable
|
||||
|
||||
from metric_bench.places import Place
|
||||
from metric_bench.python_units import Unit
|
||||
|
||||
METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
|
||||
"cognitive complexity": lambda unit, spread: unit.cognitive,
|
||||
"length": lambda unit, spread: unit.length,
|
||||
"shared state": lambda unit, spread: unit.shared_state,
|
||||
"change spread": lambda unit, spread: spread.get(unit.path, 0),
|
||||
}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Score:
|
||||
auc: float
|
||||
top_k: float
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RunScores:
|
||||
units: int
|
||||
named: int
|
||||
unmeasured: int
|
||||
scores: dict[str, Score]
|
||||
|
||||
|
||||
def co_changed(log: str) -> dict[str, int]:
|
||||
"""For each file, how many other files changed in a commit with it; log is `git log --format=format:@@ --name-only`."""
|
||||
partners: dict[str, set[str]] = collections.defaultdict(set)
|
||||
for commit in log.split("@@"):
|
||||
files = set(commit.split())
|
||||
for path in files:
|
||||
partners[path] |= files - {path}
|
||||
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."""
|
||||
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})
|
||||
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)))
|
||||
return RunScores(len(units), len(named), unmeasured, scores)
|
||||
|
||||
|
||||
def auc(named: list[int], rest: list[int]) -> float:
|
||||
"""The chance a named unit outranks one not named, a tie counting half: 0.5 is a coin toss, 1.0 a perfect ranking."""
|
||||
wins = sum((a > b) + 0.5 * (a == b) for a in named for b in rest)
|
||||
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 medians(runs: list[RunScores]) -> dict[str, Score]:
|
||||
return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs)) for metric in METRICS}
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Bench cheap static metrics against the places a project's comprehension panel named as hardest.
|
||||
|
||||
usage: metric-bench [history]
|
||||
|
||||
Run it inside a project checkout. history defaults to docs/comprehension-history.md there. For each
|
||||
scoring run in it, at the commit the seats read, it measures every Python function and method git
|
||||
tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python),
|
||||
length in lines, shared state (attributes on self another method of the class also writes, plus
|
||||
names declared global or nonlocal), and change spread (how many other files changed in a commit with
|
||||
the unit's file, up to that commit). It then prints, for each metric, how well it ranks the units
|
||||
the seats named above the rest: AUC (0.5 is a coin toss, 1.0 a perfect ranking) and top k (the share
|
||||
of the metric's k highest units the seats named, k being how many they named). A last row gives the
|
||||
medians. Places that name no Python function or method, such as a section of a markdown file, are
|
||||
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.
|
||||
"""
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score
|
||||
from failure import Failure
|
||||
from metric_bench.places import resolved, scoring_runs
|
||||
from metric_bench.python_units import python_units, Unit
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1 or argv[:1] and argv[0].startswith("-"):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: metric-bench [history]", file=sys.stderr)
|
||||
return 1
|
||||
top = git(["rev-parse", "--show-toplevel"], None)
|
||||
if isinstance(top, Failure):
|
||||
return failed(top)
|
||||
history = pathlib.Path(argv[0]) if argv else pathlib.Path(top.strip(), "docs", "comprehension-history.md")
|
||||
try:
|
||||
text = history.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return failed(Failure(f"could not read {history}: {failure}"))
|
||||
rows = []
|
||||
for run in scoring_runs(text):
|
||||
tracked = git(["ls-tree", "-r", "--name-only", run.commit], top.strip())
|
||||
if isinstance(tracked, Failure):
|
||||
return failed(tracked)
|
||||
units = commit_units(run.commit, tracked.split("\n"), top.strip())
|
||||
if isinstance(units, Failure):
|
||||
return failed(units)
|
||||
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top.strip())
|
||||
if isinstance(log, Failure):
|
||||
return failed(log)
|
||||
if scores := bench(units, resolved(run.places, tracked.split("\n")), co_changed(log)):
|
||||
rows.append((run.heading, scores))
|
||||
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 0
|
||||
|
||||
|
||||
def commit_units(commit: str, tracked: list[str], top: str) -> list[Unit] | Failure:
|
||||
units = []
|
||||
for path in tracked:
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
if path.endswith(".py") and not name.startswith("test_") and not name.endswith("_test.py") and "tests" not in path.split("/")[:-1]:
|
||||
source = git(["show", f"{commit}:{path}"], top)
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
units += python_units(path, source)
|
||||
return units
|
||||
|
||||
|
||||
def table(rows: list[tuple[str, RunScores]]) -> str:
|
||||
head = ["Scoring run", "Units", "Named", "Unmeasured", *METRICS]
|
||||
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||||
for heading, run in rows:
|
||||
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), *(cell(run.scores[metric]) for metric in METRICS)]) + " |")
|
||||
medianed = medians([run for _, run in rows])
|
||||
lines.append("| " + " | ".join(["Median", "", "", "", *(cell(medianed[metric]) for metric in METRICS)]) + " |")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def cell(score: Score) -> str:
|
||||
return f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
|
||||
|
||||
|
||||
def git(args: list[str], cwd: str | None) -> str | Failure:
|
||||
try:
|
||||
ran = subprocess.run(["git", *args], capture_output=True, cwd=cwd, encoding="utf-8", errors="replace")
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start git: {failure.strerror}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
def failed(failure: Failure) -> int:
|
||||
print(failure.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -0,0 +1,70 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import re
|
||||
|
||||
from markdown_sections import sections
|
||||
|
||||
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.
|
||||
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Place:
|
||||
path: str
|
||||
name: str | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ScoringRun:
|
||||
heading: str
|
||||
commit: str
|
||||
places: list[Place]
|
||||
|
||||
|
||||
def scoring_runs(history: str) -> list[ScoringRun]:
|
||||
"""Each scoring run in a comprehension history, with the places its seats named, as they wrote them; paired rulings name what changed, not what is hard, and are left out."""
|
||||
runs = []
|
||||
for heading, bodies in sections(history).items():
|
||||
if (named := RUN.match(heading)) and ", against " not in heading:
|
||||
runs.append(ScoringRun(heading, named.group(3), [place for body in bodies for place in seat_places(body)]))
|
||||
return runs
|
||||
|
||||
|
||||
def seat_places(body: str) -> list[Place]:
|
||||
places = []
|
||||
listing = False
|
||||
for line in body.splitlines():
|
||||
if SEAT_PLACES.match(line):
|
||||
listing = True
|
||||
elif listing and line.startswith("- "):
|
||||
places += bullet_places(line)
|
||||
elif not line.startswith(" "):
|
||||
listing = False
|
||||
return places
|
||||
|
||||
|
||||
def bullet_places(bullet: str) -> list[Place]:
|
||||
"""A `:line` with no path is in the file named before it in the bullet."""
|
||||
places = []
|
||||
path = ""
|
||||
for match in PLACE.finditer(bullet):
|
||||
path = match.group(1) or path
|
||||
if path:
|
||||
places.append(Place(path, match.group(2)))
|
||||
return places
|
||||
|
||||
|
||||
def resolved(places: list[Place], tracked: list[str]) -> list[Place]:
|
||||
"""Seats shorten a path once they have named its folder: `cycle/run.py` after `bin/loop_claude/cycle/states.py`. Each place resolves to the one tracked file it names, or, where several match, the one sharing most of the path resolved before it; a place naming no tracked file is dropped."""
|
||||
found = []
|
||||
before = ""
|
||||
for place in places:
|
||||
candidates = [path for path in tracked if path == place.path or path.endswith("/" + place.path)]
|
||||
if len(candidates) > 1:
|
||||
candidates = [max(candidates, key=lambda path: len(os.path.commonprefix([path, before])))]
|
||||
if candidates:
|
||||
before = candidates[0]
|
||||
found.append(Place(before, place.name))
|
||||
return found
|
||||
@@ -0,0 +1,151 @@
|
||||
import ast
|
||||
import collections
|
||||
import dataclasses
|
||||
|
||||
FUNCTION = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unit:
|
||||
path: str
|
||||
name: str
|
||||
cognitive: int
|
||||
length: int
|
||||
shared_state: int
|
||||
|
||||
|
||||
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."""
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except (SyntaxError, ValueError):
|
||||
return []
|
||||
units = []
|
||||
for node in tree.body:
|
||||
if isinstance(node, FUNCTION):
|
||||
units.append(unit(path, node, 0))
|
||||
elif isinstance(node, ast.ClassDef):
|
||||
shared = shared_writes(node)
|
||||
units += [unit(path, method, shared[method.name]) for method in node.body if isinstance(method, FUNCTION)]
|
||||
return units
|
||||
|
||||
|
||||
def unit(path: str, node: ast.FunctionDef | ast.AsyncFunctionDef, shared: int) -> Unit:
|
||||
globals_written = sum(len(statement.names) for statement in ast.walk(node) if isinstance(statement, ast.Global | ast.Nonlocal))
|
||||
return Unit(path, node.name, cognitive(node), (node.end_lineno or node.lineno) - node.lineno + 1, shared + globals_written)
|
||||
|
||||
|
||||
def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]:
|
||||
"""For each method, how many of the attributes it writes on self another method of the class writes too."""
|
||||
writers = collections.defaultdict(set)
|
||||
for method in cls.body:
|
||||
if isinstance(method, FUNCTION):
|
||||
for node in ast.walk(method):
|
||||
for target in written(node):
|
||||
if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self":
|
||||
writers[target.attr].add(method.name)
|
||||
return collections.Counter(method for methods in writers.values() if len(methods) > 1 for method in methods)
|
||||
|
||||
|
||||
def written(node: ast.AST) -> list[ast.expr]:
|
||||
if isinstance(node, ast.Assign):
|
||||
return node.targets
|
||||
return [node.target] if isinstance(node, ast.AugAssign | ast.AnnAssign) else []
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
class Cognitive(ast.NodeVisitor):
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
self.nesting = 0
|
||||
self.score = 0
|
||||
|
||||
def within(self, nodes: list, deeper: int = 1) -> None:
|
||||
self.nesting += deeper
|
||||
for node in nodes:
|
||||
self.visit(node)
|
||||
self.nesting -= deeper
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user