import dataclasses import statistics import typing from branch_chunks.cut import BranchChunk, Landing, NOT_WORK from round_titles import Findings, round_findings, rounds_past_first from todo_table import Item from markdown_text import listed # 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 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. fixed_by names the later chunks that fixed code it shipped, newest first, as branch_chunks counts them.""" item: Item merge: str merged: str shipped_with: tuple[int, ...] lines: int files: int rounds_past_first: int findings: Findings | None landed: Landing fixed_by: tuple[str, ...] # 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 results_of(chunk: BranchChunk, numstat: str) -> list[Result]: """What one chunk measured for each item it shipped, from `git diff --numstat` of its change; 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()) titles = list(chunk.titles) ids = [item.id for item in chunk.shipped] return [Result(item, chunk.label, chunk.merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), rounds_past_first(titles), round_findings(titles), chunk.landed, chunk.fixed_by) for item in chunk.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.""" lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in one_per_chunk(results) 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 fixed_later(results: list[Result]) -> list[str]: """Newest first, each finished chunk whose code later chunks fixed, naming them, then how many finished chunks none fixed.""" chunks = one_per_chunk(results) lines = [f"- {result.merged} in {result.merge}: {later(result)}, by {listed(result.fixed_by, 'and')}" for result in chunks if result.fixed_by] if not lines: return ["- None: no later chunk fixed code a finished chunk shipped."] others = len(chunks) - len(lines) return lines + ([f"- The other {plural(others, 'finished chunk')}: none."] if others else []) def one_per_chunk(results: list[Result]) -> list[Result]: """One result for each chunk, newest first: a chunk that shipped several items has a Result for each, and the report gives each chunk one line.""" chunks = {result.merge: result for result in results} return sorted(chunks.values(), key=lambda result: result.merged, reverse=True) 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)}, {later(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 later(result: Result) -> str: count = len(result.fixed_by) return f"{count} later fix{'' if count == 1 else 'es'}" def plural(count: int, noun: str) -> str: return f"{count} {noun}{'' if count == 1 else 's'}"