Answer stability, product-owner and architecture round 3: resolve every place in order and count the dropped ones once, let a full path win, name unparsed files and unscored runs below the table, show chance and constant metrics, leave sweeps of more than 30 files out of change spread, count tuple and loop writes and self recursion, and say what a missing history or folder means
This commit is contained in:
@@ -14,10 +14,15 @@ METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Code Maat's default --max-changeset-size: a sweep across the tree couples every file to every other.
|
||||||
|
LARGEST_CHANGESET = 30
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
class Score:
|
class Score:
|
||||||
auc: float
|
auc: float
|
||||||
top_k: float
|
top_k: float
|
||||||
|
constant: bool
|
||||||
|
|
||||||
|
|
||||||
@dataclasses.dataclass(frozen=True)
|
@dataclasses.dataclass(frozen=True)
|
||||||
@@ -29,10 +34,12 @@ class RunScores:
|
|||||||
|
|
||||||
|
|
||||||
def co_changed(log: str) -> dict[str, int]:
|
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`."""
|
"""For each file, how many other files changed in a commit with it, commits of more than LARGEST_CHANGESET files left out; log is `git log --format=format:@@ --name-only`."""
|
||||||
partners: dict[str, set[str]] = collections.defaultdict(set)
|
partners: dict[str, set[str]] = collections.defaultdict(set)
|
||||||
for commit in log.split("@@"):
|
for commit in log.split("@@\n"):
|
||||||
files = set(commit.split())
|
files = set(filter(None, commit.split("\n")))
|
||||||
|
if len(files) > LARGEST_CHANGESET:
|
||||||
|
continue
|
||||||
for path in files:
|
for path in files:
|
||||||
partners[path] |= files - {path}
|
partners[path] |= files - {path}
|
||||||
return {path: len(others) for path, others in partners.items()}
|
return {path: len(others) for path, others in partners.items()}
|
||||||
@@ -51,7 +58,7 @@ def bench(units: list[Unit], places: list[Place], unresolved: int, spread: dict[
|
|||||||
for metric, value in METRICS.items():
|
for metric, value in METRICS.items():
|
||||||
named_values = [value(unit, spread) for unit in named]
|
named_values = [value(unit, spread) for unit in named]
|
||||||
rest_values = [value(unit, spread) for unit in rest]
|
rest_values = [value(unit, spread) for unit in rest]
|
||||||
scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values))
|
scores[metric] = Score(auc(named_values, rest_values), top_k(named_values, rest_values), len(set(named_values + rest_values)) == 1)
|
||||||
return RunScores(len(units), len(named), unmeasured, scores)
|
return RunScores(len(units), len(named), unmeasured, scores)
|
||||||
|
|
||||||
|
|
||||||
@@ -73,4 +80,4 @@ def top_k(named: list[int], rest: list[int]) -> float:
|
|||||||
|
|
||||||
|
|
||||||
def medians(runs: list[RunScores]) -> dict[str, Score]:
|
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}
|
return {metric: Score(statistics.median(run.scores[metric].auc for run in runs), statistics.median(run.scores[metric].top_k for run in runs), all(run.scores[metric].constant for run in runs)) for metric in METRICS}
|
||||||
|
|||||||
+59
-39
@@ -4,22 +4,32 @@ usage: metric-bench [history]
|
|||||||
|
|
||||||
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
|
history defaults to docs/comprehension-history.md in the checkout it runs in, and the bench reads
|
||||||
the checkout that holds the history. For each scoring run in it, at the commit the seats read, it
|
the checkout that holds the history. For each scoring run in it, at the commit the seats read, it
|
||||||
measures every Python function and method git
|
measures each module-level function and each method of a module-level class in the Python files git
|
||||||
tracks, test files left out: cognitive complexity (SonarSource's white paper, read for Python),
|
tracks, leaving out test_*.py, *_test.py and anything under a tests/ folder:
|
||||||
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. Unmeasured counts the distinct places that name no Python function or method, such as a
|
|
||||||
section of a markdown file, or no single tracked file.
|
|
||||||
|
|
||||||
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the
|
- cognitive complexity: SonarSource's white paper, read for Python;
|
||||||
history cannot be read, a measured file does not parse, or no scoring run names a measured unit. A
|
- length: lines;
|
||||||
run whose commit the checkout lacks, such as a deleted branch's, is skipped and named below the
|
- shared state: attributes on self that another method of the class also writes, plus names
|
||||||
table.
|
declared global or nonlocal;
|
||||||
|
- change spread: how many other files changed in a commit with the unit's file, up to that commit,
|
||||||
|
leaving out commits of more than 30 files.
|
||||||
|
|
||||||
|
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; Chance is what top k scores at random). A metric that
|
||||||
|
gave every unit one value reads "constant". A last row gives the medians. Unmeasured counts the
|
||||||
|
distinct places that name no Python function or method, such as a section of a markdown file, or no
|
||||||
|
single tracked file.
|
||||||
|
|
||||||
|
Below the table it names each run it skipped, its commit not in the checkout, each run it could not
|
||||||
|
score, its places naming no measured unit or every one, and each file that does not parse on this
|
||||||
|
Python, left out of its run.
|
||||||
|
|
||||||
|
Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the history
|
||||||
|
cannot be read, or no scoring run names a measured unit.
|
||||||
"""
|
"""
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import statistics
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
@@ -43,19 +53,23 @@ def main(argv: list[str]) -> int:
|
|||||||
benched = bench_runs(text, top)
|
benched = bench_runs(text, top)
|
||||||
if isinstance(benched, Failure):
|
if isinstance(benched, Failure):
|
||||||
return failed(benched)
|
return failed(benched)
|
||||||
rows, gone = benched
|
rows, notes = benched
|
||||||
if not rows:
|
if not 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(gone, top)}"))
|
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\"{noted(notes)}"))
|
||||||
print(table(rows) + skipped(gone, top))
|
print(table(rows) + noted(notes))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure:
|
def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure:
|
||||||
"""The checkout that holds the history, the history's path and its text."""
|
"""The checkout that holds the history, the history's path and its text."""
|
||||||
|
if given and not given.parent.is_dir():
|
||||||
|
return Failure(f"could not read {given}: no folder {given.parent}")
|
||||||
found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None)
|
found = git(["rev-parse", "--show-toplevel"], str(given.parent) if given else None)
|
||||||
if isinstance(found, Failure):
|
if isinstance(found, Failure):
|
||||||
return found
|
return found
|
||||||
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
|
history = given or pathlib.Path(found.strip(), "docs", "comprehension-history.md")
|
||||||
|
if not history.exists():
|
||||||
|
return Failure(f"no comprehension history at {history}; larv-review writes one at a project's first paired ruling or scoring run")
|
||||||
try:
|
try:
|
||||||
return found.strip(), history, history.read_text(encoding="utf-8")
|
return found.strip(), history, history.read_text(encoding="utf-8")
|
||||||
except (OSError, UnicodeDecodeError) as failure:
|
except (OSError, UnicodeDecodeError) as failure:
|
||||||
@@ -63,60 +77,66 @@ def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] |
|
|||||||
|
|
||||||
|
|
||||||
def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure:
|
def bench_runs(text: str, top: str) -> tuple[list[tuple[str, RunScores]], list[str]] | Failure:
|
||||||
"""Each scored run's heading and scores, and the headings of the runs whose commit the checkout lacks."""
|
"""Each scored run's heading and scores, and a note for each run skipped or not scored and each file left out."""
|
||||||
rows = []
|
rows = []
|
||||||
gone = []
|
notes = []
|
||||||
for run in scoring_runs(text):
|
for run in scoring_runs(text):
|
||||||
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
|
if isinstance(missing := git(["cat-file", "-e", f"{run.commit}^{{commit}}"], top), Failure):
|
||||||
gone.append(f"{run.heading} ({missing.reason})")
|
notes.append(f"Skipped, its commit is not in {top}: {run.heading} ({missing.reason})")
|
||||||
continue
|
continue
|
||||||
scores = run_scores(run, top)
|
scored = run_scores(run, top)
|
||||||
if isinstance(scores, Failure):
|
if isinstance(scored, Failure):
|
||||||
return scores
|
return scored
|
||||||
|
scores, unparsed = scored
|
||||||
|
notes += [f"Left out of {run.heading}: {reason}" for reason in unparsed]
|
||||||
if scores:
|
if scores:
|
||||||
rows.append((run.heading, scores))
|
rows.append((run.heading, scores))
|
||||||
return rows, gone
|
else:
|
||||||
|
notes.append(f"Not scored, its places name no measured unit or every one: {run.heading}")
|
||||||
|
return rows, notes
|
||||||
|
|
||||||
|
|
||||||
def skipped(gone: list[str], top: str) -> str:
|
def noted(notes: list[str]) -> str:
|
||||||
lines = [f"Skipped, its commit is not in {top}: {run}" for run in gone]
|
return "\n\n" + "\n".join(notes) if notes else ""
|
||||||
return "\n\n" + "\n".join(lines) if lines else ""
|
|
||||||
|
|
||||||
|
|
||||||
def run_scores(run: ScoringRun, top: str) -> RunScores | None | Failure:
|
def run_scores(run: ScoringRun, top: str) -> tuple[RunScores | None, list[str]] | Failure:
|
||||||
listed = git(["ls-tree", "-r", "--name-only", run.commit], top)
|
"""The run's scores, and why each file that does not parse was left out."""
|
||||||
|
listed = git(["ls-tree", "-r", "-z", "--name-only", run.commit], top)
|
||||||
if isinstance(listed, Failure):
|
if isinstance(listed, Failure):
|
||||||
return listed
|
return listed
|
||||||
tracked = listed.split("\n")
|
tracked = list(filter(None, listed.split("\0")))
|
||||||
units: list[Unit] = []
|
units: list[Unit] = []
|
||||||
|
unparsed = []
|
||||||
for path in filter(measured, tracked):
|
for path in filter(measured, tracked):
|
||||||
source = git(["show", f"{run.commit}:{path}"], top)
|
source = git(["show", f"{run.commit}:{path}"], top)
|
||||||
if isinstance(source, Failure):
|
if isinstance(source, Failure):
|
||||||
return source
|
return source
|
||||||
found = python_units(path, source)
|
found = python_units(path, source)
|
||||||
if isinstance(found, Failure):
|
if isinstance(found, Failure):
|
||||||
return found
|
unparsed.append(found.reason)
|
||||||
units += found
|
else:
|
||||||
log = git(["log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top)
|
units += found
|
||||||
|
log = git(["-c", "core.quotePath=false", "log", "--no-merges", "--format=format:@@", "--name-only", run.commit], top)
|
||||||
if isinstance(log, Failure):
|
if isinstance(log, Failure):
|
||||||
return log
|
return log
|
||||||
named = list(dict.fromkeys(run.places))
|
places, dropped = resolved(run.places, tracked)
|
||||||
places = resolved(named, tracked)
|
return bench(units, places, len(set(dropped)), co_changed(log)), unparsed
|
||||||
return bench(units, places, len(named) - len(places), co_changed(log))
|
|
||||||
|
|
||||||
|
|
||||||
def table(rows: list[tuple[str, RunScores]]) -> str:
|
def table(rows: list[tuple[str, RunScores]]) -> str:
|
||||||
head = ["Scoring run", "Units", "Named", "Unmeasured", *METRICS]
|
head = ["Scoring run", "Units", "Named", "Unmeasured", "Chance", *METRICS]
|
||||||
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||||||
for heading, run in rows:
|
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)]) + " |")
|
lines.append("| " + " | ".join([heading, str(run.units), str(run.named), str(run.unmeasured), f"top k {run.named / run.units:.2f}", *(cell(run.scores[metric]) for metric in METRICS)]) + " |")
|
||||||
medianed = medians([run for _, run in rows])
|
medianed = medians([run for _, run in rows])
|
||||||
lines.append("| " + " | ".join(["Median", "", "", "", *(cell(medianed[metric]) for metric in METRICS)]) + " |")
|
chance = statistics.median(run.named / run.units for _, run in rows)
|
||||||
|
lines.append("| " + " | ".join(["Median", "", "", "", f"top k {chance:.2f}", *(cell(medianed[metric]) for metric in METRICS)]) + " |")
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def cell(score: Score) -> str:
|
def cell(score: Score) -> str:
|
||||||
return f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
|
return "constant" if score.constant else f"AUC {score.auc:.2f}, top k {score.top_k:.2f}"
|
||||||
|
|
||||||
|
|
||||||
def git(args: list[str], cwd: str | None) -> str | Failure:
|
def git(args: list[str], cwd: str | None) -> str | Failure:
|
||||||
|
|||||||
@@ -57,14 +57,17 @@ def bullet_places(bullet: str) -> list[Place]:
|
|||||||
return places
|
return places
|
||||||
|
|
||||||
|
|
||||||
def resolved(places: list[Place], tracked: list[str]) -> list[Place]:
|
def resolved(places: list[Place], tracked: list[str]) -> tuple[list[Place], 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 in the folder of the place resolved before it; a place naming no file, or several, is dropped."""
|
"""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 in the folder of the place resolved before it; a place naming no file, or several, is dropped. Returns the resolved places and the dropped ones."""
|
||||||
found = []
|
found = []
|
||||||
|
dropped = []
|
||||||
before = ""
|
before = ""
|
||||||
for place in places:
|
for place in places:
|
||||||
candidates = [path for path in tracked if path == place.path or path.endswith("/" + place.path)]
|
candidates = [place.path] if place.path in tracked else [path for path in tracked if path.endswith("/" + place.path)]
|
||||||
nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates
|
nearest = [path for path in candidates if path.startswith(os.path.dirname(before) + "/")] if len(candidates) > 1 else candidates
|
||||||
if len(nearest) == 1:
|
if len(nearest) == 1:
|
||||||
before = nearest[0]
|
before = nearest[0]
|
||||||
found.append(Place(before, place.name))
|
found.append(Place(before, place.name))
|
||||||
return found
|
else:
|
||||||
|
dropped.append(place)
|
||||||
|
return found, dropped
|
||||||
|
|||||||
@@ -24,11 +24,11 @@ def measured(path: str) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def python_units(path: str, source: str) -> list[Unit] | Failure:
|
def python_units(path: str, source: str) -> list[Unit] | Failure:
|
||||||
"""Each module-level function and each method in source, with its metrics."""
|
"""Each module-level function and each method of a module-level class in source, with its metrics."""
|
||||||
try:
|
try:
|
||||||
tree = ast.parse(source)
|
tree = ast.parse(source)
|
||||||
except (SyntaxError, ValueError) as failure:
|
except (SyntaxError, ValueError) as failure:
|
||||||
return Failure(f"could not parse {path} on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}")
|
return Failure(f"{path} does not parse on Python {sys.version_info[0]}.{sys.version_info[1]}: {failure}")
|
||||||
units = []
|
units = []
|
||||||
for node in tree.body:
|
for node in tree.body:
|
||||||
if isinstance(node, FUNCTION):
|
if isinstance(node, FUNCTION):
|
||||||
@@ -58,8 +58,14 @@ def shared_writes(cls: ast.ClassDef) -> collections.Counter[str]:
|
|||||||
|
|
||||||
def written(node: ast.AST) -> list[ast.expr]:
|
def written(node: ast.AST) -> list[ast.expr]:
|
||||||
if isinstance(node, ast.Assign):
|
if isinstance(node, ast.Assign):
|
||||||
return node.targets
|
targets = node.targets
|
||||||
return [node.target] if isinstance(node, ast.AugAssign | ast.AnnAssign) else []
|
elif isinstance(node, ast.AugAssign | ast.AnnAssign | ast.For | ast.AsyncFor | ast.comprehension):
|
||||||
|
targets = [node.target]
|
||||||
|
elif isinstance(node, ast.withitem) and node.optional_vars:
|
||||||
|
targets = [node.optional_vars]
|
||||||
|
else:
|
||||||
|
return []
|
||||||
|
return [leaf for target in targets for leaf in ast.walk(target) if isinstance(leaf, ast.Attribute)]
|
||||||
|
|
||||||
|
|
||||||
# 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.
|
# 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.
|
||||||
@@ -86,8 +92,18 @@ def score(node: ast.AST, nesting: int, name: str) -> int:
|
|||||||
return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)), nesting + 1, name)
|
return sum(1 + nesting + len(generator.ifs) for generator in node.generators) + inside(list(ast.iter_child_nodes(node)), nesting + 1, name)
|
||||||
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
|
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda):
|
||||||
return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name)
|
return inside(node.body if isinstance(node.body, list) else [node.body], nesting + 1, name)
|
||||||
recursion = isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == name
|
return (isinstance(node, ast.BoolOp) or called(node) == name) + inside(list(ast.iter_child_nodes(node)), nesting, name)
|
||||||
return (isinstance(node, ast.BoolOp) or recursion) + inside(list(ast.iter_child_nodes(node)), nesting, name)
|
|
||||||
|
|
||||||
|
def called(node: ast.AST) -> str | None:
|
||||||
|
"""The function a call names, or the method it calls on self."""
|
||||||
|
if not isinstance(node, ast.Call):
|
||||||
|
return None
|
||||||
|
if isinstance(node.func, ast.Name):
|
||||||
|
return node.func.id
|
||||||
|
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == "self":
|
||||||
|
return node.func.attr
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def inside(nodes: list, nesting: int, name: str) -> int:
|
def inside(nodes: list, nesting: int, name: str) -> int:
|
||||||
|
|||||||
@@ -70,6 +70,12 @@ class Cognitive(unittest.TestCase):
|
|||||||
pass
|
pass
|
||||||
"""), 1 + 3 + 3)
|
"""), 1 + 3 + 3)
|
||||||
|
|
||||||
|
def test_counts_a_call_to_itself_on_self_as_recursion(self):
|
||||||
|
self.assertEqual(scored("""
|
||||||
|
def walk(self, node):
|
||||||
|
return self.walk(node.child)
|
||||||
|
"""), 1)
|
||||||
|
|
||||||
def test_counts_a_comprehension_as_a_loop_and_its_conditions(self):
|
def test_counts_a_comprehension_as_a_loop_and_its_conditions(self):
|
||||||
self.assertEqual(scored("""
|
self.assertEqual(scored("""
|
||||||
def f(rows):
|
def f(rows):
|
||||||
@@ -93,8 +99,11 @@ class Units(unittest.TestCase):
|
|||||||
def grow(self):
|
def grow(self):
|
||||||
self.size += 1
|
self.size += 1
|
||||||
self.name = "x"
|
self.name = "x"
|
||||||
|
|
||||||
|
def rename(self):
|
||||||
|
self.name, self.other = "y", 1
|
||||||
"""))
|
"""))
|
||||||
self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 1)])
|
self.assertEqual(units, [Unit("a.py", "bump", 0, 3, 1), Unit("a.py", "__init__", 0, 2, 1), Unit("a.py", "grow", 0, 3, 2), Unit("a.py", "rename", 0, 2, 1)])
|
||||||
|
|
||||||
def test_measures_python_files_outside_the_tests(self):
|
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"])
|
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"])
|
||||||
@@ -102,7 +111,7 @@ class Units(unittest.TestCase):
|
|||||||
def test_a_source_that_does_not_parse_is_a_failure_naming_it(self):
|
def test_a_source_that_does_not_parse_is_a_failure_naming_it(self):
|
||||||
failure = python_units("a.py", "def (")
|
failure = python_units("a.py", "def (")
|
||||||
assert isinstance(failure, Failure)
|
assert isinstance(failure, Failure)
|
||||||
self.assertIn("could not parse a.py", failure.reason)
|
self.assertIn("a.py does not parse on Python", failure.reason)
|
||||||
|
|
||||||
|
|
||||||
class Places(unittest.TestCase):
|
class Places(unittest.TestCase):
|
||||||
@@ -139,10 +148,18 @@ class Places(unittest.TestCase):
|
|||||||
def test_resolves_a_shortened_path_to_the_file_nearest_the_one_before_it(self):
|
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"]
|
tracked = ["bin/tool/cycle/states.py", "bin/tool/cycle/run.py", "bin/other/cycle/run.py"]
|
||||||
places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")]
|
places = [Place("bin/tool/cycle/states.py", "transition"), Place("cycle/run.py", "step"), Place("gone.py", "x")]
|
||||||
self.assertEqual(resolved(places, tracked), [Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")])
|
self.assertEqual(resolved(places, tracked), ([Place("bin/tool/cycle/states.py", "transition"), Place("bin/tool/cycle/run.py", "step")], [Place("gone.py", "x")]))
|
||||||
|
|
||||||
|
def test_a_full_path_wins_over_a_file_in_the_folder_before_it(self):
|
||||||
|
self.assertEqual(resolved([Place("pkg/x.py", "a"), Place("main.py", "f")], ["pkg/x.py", "main.py", "pkg/main.py"])[0][-1], Place("main.py", "f"))
|
||||||
|
|
||||||
|
def test_resolves_a_shortened_path_after_a_repeated_place_by_the_repeat(self):
|
||||||
|
tracked = ["bin/a/main.py", "bin/b/main.py", "bin/b/bench.py"]
|
||||||
|
places = [Place("bin/a/main.py", "main"), Place("bin/b/bench.py", "bench"), Place("bin/a/main.py", "main"), Place("main.py", "figures")]
|
||||||
|
self.assertEqual(resolved(places, tracked)[0][-1], Place("bin/a/main.py", "figures"))
|
||||||
|
|
||||||
def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self):
|
def test_drops_a_shortened_path_two_files_match_with_no_place_before_it(self):
|
||||||
self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), [])
|
self.assertEqual(resolved([Place("cycle/run.py", "step")], ["bin/tool/cycle/run.py", "bin/other/cycle/run.py"]), ([], [Place("cycle/run.py", "step")]))
|
||||||
|
|
||||||
|
|
||||||
class Bench(unittest.TestCase):
|
class Bench(unittest.TestCase):
|
||||||
@@ -150,8 +167,9 @@ class Bench(unittest.TestCase):
|
|||||||
self.assertEqual(auc([5, 4], [1, 2]), 1.0)
|
self.assertEqual(auc([5, 4], [1, 2]), 1.0)
|
||||||
self.assertEqual(auc([3], [3]), 0.5)
|
self.assertEqual(auc([3], [3]), 0.5)
|
||||||
|
|
||||||
def test_co_changed_counts_each_files_distinct_partners(self):
|
def test_co_changed_counts_each_files_distinct_partners_past_a_sweep(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})
|
sweep = "".join(f"f{i}.py\n" for i in range(31))
|
||||||
|
self.assertEqual(co_changed(f"@@\na.py\nmy b.py\n@@\na.py\nc.py\n@@\na.py\n@@\n{sweep}"), {"a.py": 2, "my b.py": 1, "c.py": 1})
|
||||||
|
|
||||||
def test_top_k_shares_the_seats_at_a_tied_cut_evenly(self):
|
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([0, 0], [0, 0, 0, 0]), 1 / 3)
|
||||||
@@ -195,7 +213,7 @@ class BlackBox(unittest.TestCase):
|
|||||||
ran = self.run_tool(top)
|
ran = self.run_tool(top)
|
||||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||||
self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout)
|
self.assertIn("| 2026-10-08T12:50:49Z, PR #1 at ", ran.stdout)
|
||||||
self.assertIn("| 2 | 1 | 0 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | AUC 0.50,", ran.stdout)
|
self.assertIn("| 2 | 1 | 0 | top k 0.50 | AUC 1.00, top k 1.00 | AUC 1.00, top k 1.00 | constant | constant |", ran.stdout)
|
||||||
self.assertIn("| Median |", ran.stdout)
|
self.assertIn("| Median |", ran.stdout)
|
||||||
|
|
||||||
def test_exits_1_when_no_run_names_a_measured_unit(self):
|
def test_exits_1_when_no_run_names_a_measured_unit(self):
|
||||||
@@ -206,7 +224,8 @@ class BlackBox(unittest.TestCase):
|
|||||||
|
|
||||||
def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self):
|
def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self):
|
||||||
top = self.project("")
|
top = self.project("")
|
||||||
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
|
self.assertIn("no comprehension history at", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
|
||||||
|
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "gone", "x.md"))).stderr)
|
||||||
self.assertEqual(self.run_tool(top, "--x").returncode, 1)
|
self.assertEqual(self.run_tool(top, "--x").returncode, 1)
|
||||||
|
|
||||||
def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self):
|
def test_skips_and_names_a_run_whose_commit_the_checkout_lacks(self):
|
||||||
@@ -216,6 +235,11 @@ class BlackBox(unittest.TestCase):
|
|||||||
self.assertIn("Skipped, its commit is not in", ran.stdout)
|
self.assertIn("Skipped, its commit is not in", ran.stdout)
|
||||||
self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1])
|
self.assertIn("PR #0 at 0123456", ran.stdout.split("Skipped")[1])
|
||||||
|
|
||||||
|
def test_names_a_run_it_cannot_score_below_the_table(self):
|
||||||
|
top = self.project("# Comprehension history\n\n## 2026-10-07T12:00:00Z, PR #0 at COMMIT\n\nJunior A, hardest first:\n\n- `README.md:1` \"Install\"\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.assertIn("Not scored, its places name no measured unit or every one: 2026-10-07T12:00:00Z, PR #0", ran.stdout)
|
||||||
|
|
||||||
def test_reads_the_checkout_that_holds_a_history_named_from_elsewhere(self):
|
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")
|
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")))
|
ran = self.run_tool(tempfile.gettempdir(), str(pathlib.Path(top, "docs", "comprehension-history.md")))
|
||||||
|
|||||||
@@ -187,7 +187,7 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Cognitive complexity | 0.66 | 0.26 |
|
| Cognitive complexity | 0.66 | 0.26 |
|
||||||
| Length | 0.74 | 0.18 |
|
| Length | 0.74 | 0.18 |
|
||||||
| Shared state | 0.50 | 0.10 |
|
| Shared state | constant | constant |
|
||||||
| Change spread | 0.64 | 0.15 |
|
| Change spread | 0.67 | 0.18 |
|
||||||
|
|
||||||
AUC is 0.5 for a coin toss. Shared state cannot be judged here, since no unit in `bin/` writes state another method shares. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces.
|
AUC is 0.5 for a coin toss, and top k scores 0.10 by chance. Shared state cannot be judged here: every unit in `bin/` scores 0 on it. Before the rerun, set the AUC and top-k lift over chance that count as tracking, from a published threshold, so the rerun ends in a decision. Every run's first place was a section of `skills/larv-review/SKILL.md`, which no code metric sees. The rerun needs places from a project in Go or TypeScript, the languages most other projects use, so the bench first measures those languages, run through each project's own tooling. Function and file length stay warnings to look into, never limits: a plain long function can be simple, and a hard one may need five-line pieces.
|
||||||
|
|||||||
Reference in New Issue
Block a user