153 lines
9.1 KiB
Python
153 lines
9.1 KiB
Python
import dataclasses
|
|
import statistics
|
|
import typing
|
|
|
|
from round_titles import Findings, round_counts, round_findings
|
|
from comprehension_history import HISTORY
|
|
from todo_table import Item, items
|
|
from markdown_text import listed
|
|
from reading_cost.figures import RECORD
|
|
|
|
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
|
|
ENOUGH = 10
|
|
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
|
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
|
|
|
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
|
|
Landing = typing.Literal["merge", "rebase", "push"]
|
|
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
|
|
Chunk = tuple[str, str, int, Landing]
|
|
|
|
|
|
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Result:
|
|
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
|
|
item: Item
|
|
merge: str
|
|
merged: str
|
|
shipped_with: tuple[int, ...]
|
|
lines: int
|
|
files: int
|
|
rounds_past_first: int
|
|
findings: Findings | None
|
|
landed: Landing
|
|
|
|
|
|
# A measure's name and how to read it from a Result, None where the chunk did not record it.
|
|
Measure = tuple[str, typing.Callable[[Result], int | None]]
|
|
# The scores whose median result the report gives at each guessed value.
|
|
MEDIANS: dict[str, Measure] = {"R": ("🔴 findings", lambda result: result.findings.red if result.findings else None), "S": ("lines changed", lambda result: result.lines)}
|
|
# The levels R is built from; for each, the report gives how well it orders chunks by review rounds and by 🔴 findings.
|
|
ORDERED = ("L", "E", "I")
|
|
# The scores render shows, in this order; C only on an item scored before L, E and I replaced it.
|
|
SHOWN = ("L", "E", "I", "R", "S", "C")
|
|
|
|
|
|
def shipped(before: str, after: str) -> list[Item]:
|
|
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
|
planned, left = items(before), items(after)
|
|
if not isinstance(planned, list) or not isinstance(left, list):
|
|
return []
|
|
kept = {item.id for item in left}
|
|
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
|
|
|
|
|
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
|
|
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
|
|
changed = [row.split("\t", 2) for row in numstat.splitlines()]
|
|
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
|
|
if not work:
|
|
return []
|
|
# Git counts a binary file's lines as "-".
|
|
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
|
|
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
|
|
ids = [item.id for item in shipped]
|
|
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
|
|
|
|
|
|
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
|
|
"""The results whose guesses sit closest to the given scores: the least mean squared difference over the scores both hold, the newest first among equals."""
|
|
def distance(result: Result) -> float:
|
|
shared = [name for name in given if name in result.item.scores]
|
|
return sum((given[name] - result.item.scores[name]) ** 2 for name in shared) / len(shared)
|
|
newest_first = sorted(results, key=lambda result: result.merged, reverse=True)
|
|
return sorted(newest_first, key=distance)[:count]
|
|
|
|
|
|
def report(results: list[Result]) -> list[str]:
|
|
"""Among chunks that shipped one item, since a chunk measures all its items at once, and that were merged or replayed, since a never-replayed one may hold only part of a pull request: for each score in MEDIANS, the median result at each value it was guessed at; for each level in ORDERED, how well it orders chunks by review rounds and by 🔴 findings."""
|
|
single = [result for result in results if not result.shipped_with and result.landed != "push"]
|
|
lines = []
|
|
for name, (what, measure) in MEDIANS.items():
|
|
held = [(result.item.scores[name], value) for result in single if name in result.item.scores and (value := measure(result)) is not None]
|
|
if len(held) < ENOUGH:
|
|
lines.append(f"- {name}, {what}: {too_few(len(held), name, 'its outcome')}")
|
|
continue
|
|
medians = [(guess, [value for at, value in held if at == guess]) for guess in sorted({guess for guess, _ in held})]
|
|
lines.append(f"- {name}, {what}: " + ", ".join(f"{guess} → {statistics.median(found):g} ({plural(len(found), 'chunk')})" for guess, found in medians))
|
|
for name in ORDERED:
|
|
# Each pass takes a first round whatever the change, so only the rounds after it measure how hard the change was to get right.
|
|
rows = [(result.item.scores[name], result.rounds_past_first, result.findings.red) for result in single if name in result.item.scores and result.findings is not None]
|
|
opening = f"- {name}, by review rounds past each pass's first and 🔴 findings: "
|
|
if len(rows) < ENOUGH:
|
|
lines.append(opening + too_few(len(rows), name, "both outcomes"))
|
|
continue
|
|
guesses, rounds, red = ([row[column] for row in rows] for column in range(3))
|
|
found = [rank_correlation(guesses, rounds), rank_correlation(guesses, red)]
|
|
undefined = ", since every chunk held one value" if None in found else ""
|
|
lines.append(opening + f"rank correlation {listed(['none' if value is None else f'{value:+.2f}' for value in found], 'and')}{undefined} ({plural(len(rows), 'chunk')})")
|
|
return lines
|
|
|
|
|
|
def misreads(results: list[Result]) -> list[str]:
|
|
"""Newest first, each chunk's 🔴 and 🟡 findings with how many of them a reviewer marked `[misread]`, for each chunk whose round titles count those."""
|
|
# A chunk that shipped several items has a Result for each, so one line per chunk.
|
|
chunks = {result.merge: result for result in results}
|
|
newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
|
|
lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in newest_first if result.findings is not None and result.findings.misread is not None]
|
|
return lines or ["- None: no chunk's round titles count them."]
|
|
|
|
|
|
def too_few(held: int, name: str, what: str) -> str:
|
|
chunks = "such chunk records" if held == 1 else "such chunks record"
|
|
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
|
|
|
|
|
|
def rank_correlation(guesses: list[int], results: list[int]) -> float | None:
|
|
"""Spearman's rank correlation, tied values sharing their mean rank; None where either side holds one value, which no order can rank."""
|
|
if len(set(guesses)) < 2 or len(set(results)) < 2:
|
|
return None
|
|
return statistics.correlation(ranks(guesses), ranks(results))
|
|
|
|
|
|
def ranks(values: list[int]) -> list[float]:
|
|
"""Each value's rank from 1, tied values sharing their mean rank."""
|
|
ordered = sorted(values)
|
|
return [ordered.index(value) + (ordered.count(value) + 1) / 2 for value in values]
|
|
|
|
|
|
def render(result: Result) -> str:
|
|
scores = ", ".join(f"{name} {result.item.scores[name]}" for name in SHOWN if name in result.item.scores)
|
|
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landed]
|
|
others = result.shipped_with
|
|
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
|
|
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}; {merged}{together}. {result.item.tagline}"
|
|
|
|
|
|
def at_least(result: Result) -> str:
|
|
"""The words that mark a chunk's rounds and findings as lower bounds: rebase drops a round's commit that changed no file, so history shows a chunk that left no merge commit short."""
|
|
return "" if result.landed == "merge" else "at least "
|
|
|
|
|
|
def counted(result: Result) -> str:
|
|
"""A chunk's findings as its round titles spell them: `1 🔴, 2 🟡 (1 misread)`, the misread count left out where they lack it."""
|
|
if result.findings is None:
|
|
return "findings unknown"
|
|
misread = "" if result.findings.misread is None else f" ({result.findings.misread} misread)"
|
|
return f"{at_least(result)}{result.findings.red} 🔴, {result.findings.yellow} 🟡{misread}"
|
|
|
|
|
|
def plural(count: int, noun: str) -> str:
|
|
return f"{count} {noun}{'' if count == 1 else 's'}"
|