diff --git a/scripts/make_fixture_bundle.py b/scripts/make_fixture_bundle.py index a73c1740..3c332078 100644 --- a/scripts/make_fixture_bundle.py +++ b/scripts/make_fixture_bundle.py @@ -2003,9 +2003,19 @@ def fail(message: str) -> None: module_ids = {n.id for n in the_map.nodes if n.level == "module"} finding_ids = {f.id for f in findings} - # Cells and cell changes name module nodes. - cell_lists = [("before_after.cells", before_after.cells)] - cell_lists += [ + # Cells and cell changes name module nodes. The before-and-after grid also holds the + # modules that exist only at the earlier date, so its cells name its own module order, + # which holds every module node once. + ba_order = set(before_after.module_order) + for cell in before_after.cells: + for end in (cell.src, cell.dst): + if end not in ba_order: + fail(f"before_after.cells names {end}, which is not in its module_order") + if len(ba_order) != len(before_after.module_order): + fail("before_after.module_order names a module more than once") + for module in sorted(module_ids - ba_order): + fail(f"before_after.module_order leaves out the module node {module}") + cell_lists = [ (f"{f.id} simulation.cell_changes", f.simulation.cell_changes) for f in findings if f.simulation @@ -2019,7 +2029,7 @@ def fail(message: str) -> None: for end in (cell.src, cell.dst): if end not in module_ids: fail(f"{where} names {end}, which is not a module node") - for module in [*the_map.module_order, *before_after.module_order]: + for module in the_map.module_order: if module not in module_ids: fail(f"module_order names {module}, which is not a module node") for edge in the_map.edges: diff --git a/src/codexray/analyze/drift.py b/src/codexray/analyze/drift.py new file mode 100644 index 00000000..ca7cc5b4 --- /dev/null +++ b/src/codexray/analyze/drift.py @@ -0,0 +1,220 @@ +"""Same code, old layout (spec.md §12.3, basis 1): a newer snapshot measured again with an +older snapshot's modules. + +If a change in a measure mostly disappears when the newer code is grouped the old way, the +change came from regrouping the code, not from new uses between parts: a reorganisation. + +Pure functions on `SnapshotMap`s and decisions. Nothing here reads or writes a table; the +report stage calls them for the before-and-after view. + +**The newer snapshot under the older layout** (`under_layout`). Each file takes a module +and a role from the older snapshot: + +1. a file whose id exists in the older snapshot takes its module and role there; +2. a file that did not exist then takes the module most common among the files that did + exist and sit in its folder at the newer snapshot. Files directly in the folder are + asked first, then every file below the folder, then below each folder above it. The + repository root is not asked: a file whose folders above it hold no older file is not + placed. Ties go to the first name. Its role is the folder directly under that module's + folder that holds it (spec.md §7.3), and, when it sits outside that folder, the role + most common among the asked files in that module; +3. a file that cannot be placed keeps its own module and role. + +**The measures** (`measure`) are those of the project yardsticks (spec.md §9.5): +exceptions to every checkable decision per 1,000 production lines, and the weight of +links between different modules. + +**A reorganisation** (`remeasure`): some measure changed under the new layout by more than +`min_change_share` of its older value (from an older value of 0, any move counts), and at +least `most_share` of that change disappears under the old layout: +1 - |old layout - older| / |new layout - older|. One such measure is enough: a change in +the other that stays under the old layout is real change in the code, which the decision +series shows, and does not make the regrouping any less a regrouping. +""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, replace +from posixpath import dirname +from typing import Any + +from codexray.analyze.checks import check_decision, per_kloc +from codexray.analyze.snapshot import FileInfo, SnapshotMap +from codexray.core.contracts import Decision + +MEASURES = ("exceptions_per_kloc", "cross_module_links") + + +@dataclass(frozen=True) +class Placement: + """How many files of the newer snapshot got their module by each rule.""" + + by_id: int + by_folder: int + kept: int + + +@dataclass(frozen=True) +class Measure: + exceptions_per_kloc: float + cross_module_links: int + + +@dataclass(frozen=True) +class Remeasure: + """One pair of snapshots, older and newer, measured three ways.""" + + older: Measure + new_layout: Measure + old_layout: Measure + placement: Placement + gone: dict[str, float | None] # per measure: share of the change that disappears + reorganisation: bool + + +def under_layout(newer: SnapshotMap, older: SnapshotMap) -> tuple[SnapshotMap, Placement]: + """A copy of `newer` whose files carry the modules and roles of `older`.""" + direct: dict[str, Counter[tuple[str, str]]] = {} + below: dict[str, Counter[tuple[str, str]]] = {} + for file in newer.files.values(): + old = older.files.get(file.id) + if old is None or old.module is None: + continue + vote = (old.module, old.role) + folder = dirname(file.path) + direct.setdefault(folder, Counter())[vote] += 1 + for level in _folders_up(folder): + below.setdefault(level, Counter())[vote] += 1 + + files: dict[str, FileInfo] = {} + by_id = by_folder = kept = 0 + for file_id, file in newer.files.items(): + old = older.files.get(file_id) + if old is not None: + files[file_id] = replace(file, module=old.module, role=old.role) + by_id += 1 + continue + votes = _votes_for(dirname(file.path), direct, below) + if votes is None: + files[file_id] = file + kept += 1 + continue + module, role = _majority(votes) + folder = older.modules.get(module) + if folder and file.path.startswith(folder.rstrip("/") + "/"): + role = _role_in(file.path, folder) # the folder kind it sits in, as in §7.3 + files[file_id] = replace(file, module=module, role=role) + by_folder += 1 + + modules = dict(older.modules) + for file in files.values(): + if file.module and file.module not in modules and file.module in newer.modules: + modules[file.module] = newer.modules[file.module] + relaid = replace(newer, files=files, modules=dict(sorted(modules.items()))) + return relaid, Placement(by_id=by_id, by_folder=by_folder, kept=kept) + + +def measure(smap: SnapshotMap, decisions: Sequence[Decision]) -> Measure: + """Exceptions per 1,000 production lines over every checkable decision, and the + weight of links between different modules.""" + exceptions = 0 + for decision in sorted(decisions, key=lambda d: d.id): + result = check_decision(decision, smap) + if result is not None: + exceptions += result.exceptions + return Measure( + exceptions_per_kloc=per_kloc(exceptions, smap.production_loc()), + cross_module_links=sum(smap.module_weights().values()), + ) + + +def changed(older: float, newer: float, min_change_share: float) -> bool: + """Whether a measure moved by more than the minimum share of its older value.""" + if older == 0: + return newer != 0 + return abs(newer - older) > min_change_share * abs(older) + + +def share_gone(older: float, new_layout: float, old_layout: float) -> float: + """The share of the change under the new layout that disappears under the old one. + + 1 when the old layout gives the older value back, 0 when it gives the same change, + below 0 when the old layout moves even further. + """ + return 1 - abs(old_layout - older) / abs(new_layout - older) + + +def remeasure( + older: SnapshotMap, + newer: SnapshotMap, + decisions: Sequence[Decision], + cfg: Mapping[str, Any], + *, + older_measure: Measure | None = None, +) -> tuple[Remeasure, SnapshotMap]: + """The three measurements of one pair, whether it is a reorganisation, and `newer` + under the older layout. `cfg` is `settings["report"]["before_after"]`.""" + relaid, placement = under_layout(newer, older) + before = older_measure or measure(older, decisions) + new_layout = measure(newer, decisions) + old_layout = measure(relaid, decisions) + gone: dict[str, float | None] = {} + for name in MEASURES: + a, b, c = getattr(before, name), getattr(new_layout, name), getattr(old_layout, name) + gone[name] = ( + round(share_gone(a, b, c), 6) if changed(a, b, float(cfg["min_change_share"])) else None + ) + moved = [value for value in gone.values() if value is not None] + reorganisation = any(value >= float(cfg["most_share"]) for value in moved) + return ( + Remeasure( + older=before, + new_layout=new_layout, + old_layout=old_layout, + placement=placement, + gone=gone, + reorganisation=reorganisation, + ), + relaid, + ) + + +def _folders_up(folder: str) -> list[str]: + """`folder` and every folder above it, nearest first, without the repository root.""" + out = [] + while folder: + out.append(folder) + folder = dirname(folder) + return out + + +def _votes_for( + folder: str, + direct: Mapping[str, Counter[tuple[str, str]]], + below: Mapping[str, Counter[tuple[str, str]]], +) -> Counter[tuple[str, str]] | None: + if direct.get(folder): + return direct[folder] + for level in _folders_up(folder): + if below.get(level): + return below[level] + return None + + +def _role_in(path: str, module_folder: str) -> str: + """The folder directly under the module folder that holds `path`, or "" (§7.3).""" + rest = path[len(module_folder.rstrip("/")) + 1 :].split("/") + return rest[0] if len(rest) > 1 else "" + + +def _majority(votes: Counter[tuple[str, str]]) -> tuple[str, str]: + """The most common module, then the most common role in it; ties to the first name.""" + modules: Counter[str] = Counter() + for (module, _role), n in votes.items(): + modules[module] += n + module = min(modules, key=lambda m: (-modules[m], m)) + roles = {role: n for (m, role), n in votes.items() if m == module} + role = min(roles, key=lambda r: (-roles[r], r)) + return module, role diff --git a/src/codexray/report/__init__.py b/src/codexray/report/__init__.py index f046fa3f..e33ad112 100644 --- a/src/codexray/report/__init__.py +++ b/src/codexray/report/__init__.py @@ -6,15 +6,19 @@ AI has no influence on order, and the result is complete with no AI call. Reads: candidate_findings, decision_checks, yardsticks, module_order (Stage 5); nodes, - edges (Stage 3); commits, file_changes (Stage 1); parse_coverage (Stage 2); - decisions.yaml; judgements/, usage.json and simulation_batch.json when present. + edges, links (Stage 3); commits, file_changes, structural_events, snapshot_files, + line_origin (Stage 1); parse_coverage + (Stage 2); decisions.yaml; judgements/, usage.json and simulation_batch.json when + present. Writes: findings.json in the run folder, and web/ holding index.json, findings.json, decisions.json, map.json, layouts.json, before_after.json, report.json and code/.json. Settings: settings/report.yaml. AI: none. -`assemble.py` builds the ranked findings, `bundle.py` the bundle files. The bundle is the +`assemble.py` builds the ranked findings, `bundle.py` the bundle files, +`before_after.py` the before-and-after file and its labelled changes, and +`line_shares.py` the shares of lines by origin that both show. The bundle is the contract with the web app: every file is a record from `core.contracts`. `make bundle REPO=` copies it into the web app. """ @@ -29,7 +33,7 @@ from codexray.core.runs import RunPaths from codexray.decisions import registry from codexray.model.rollup import load_tree -from codexray.report import assemble, bundle +from codexray.report import assemble, before_after, bundle, line_shares from codexray.repository import CLONES_DIR LANE = "report" @@ -74,9 +78,10 @@ def run(run: RunPaths, settings: dict[str, Any]) -> None: if end is None: raise CodeXrayError(f"the run has no END snapshot for {repo}") tree = load_tree(con, repo, end.sha) + origin = line_shares.load(con, manifest, end.sha, settings) findings, ranked = assemble.assemble( con, manifest, settings, by_id, tree, end, - assemble.load_ai_judgements(run.judgements), + assemble.load_ai_judgements(run.judgements), origin, ) # fmt: skip date_of = {s.sha: s.date for s in all_snapshots} @@ -108,12 +113,16 @@ def run(run: RunPaths, settings: dict[str, Any]) -> None: for evidence in finding.evidence: if evidence.kind == "lines": blob_paths.setdefault(evidence.blob_sha, evidence.path) - the_map = bundle.build_map(con, repo, end, tree, findings, cfg, blob_paths) + the_map = bundle.build_map(con, repo, end, tree, findings, cfg, blob_paths, origin) adoption = (manifest.coverage.get("adoption") or {}).get("detected_date") - before_after = bundle.build_before_after(con, repo, all_snapshots, end, the_map, adoption) - report = bundle.build_report(con, run, manifest, end, settings) + compared = before_after.build_before_after( + con, repo, all_snapshots, end, the_map, adoption, decisions, settings, + blob_paths, clone_dir, + ) # fmt: skip + report = bundle.build_report(con, run, manifest, end, settings, origin, compared.limits) cited = [e for f in findings for e in f.evidence] cited += [e for edge in the_map.edges for e in edge.refs] + cited += [e for change in compared.file.changes for e in change.evidence] code = bundle.code_files(con, repo, end, clone_dir, cited) finally: con.close() @@ -136,7 +145,7 @@ def run(run: RunPaths, settings: dict[str, Any]) -> None: bundle.FILES["decisions"]: contracts.DecisionsFile(decisions=decisions, checks=checks), bundle.FILES["map"]: the_map, bundle.FILES["layouts"]: bundle.build_layouts(findings, the_map, tree), - bundle.FILES["before_after"]: before_after, + bundle.FILES["before_after"]: compared.file, bundle.FILES["report"]: report, } records |= {f"code/{blob}.json": record for blob, record in code.items()} @@ -167,4 +176,5 @@ def run(run: RunPaths, settings: dict[str, Any]) -> None: f"{len(code)} cited files", flush=True, ) + print(before_after.summary(compared), flush=True) print(f"written to {run.web.relative_to(run.runs_dir)}", flush=True) diff --git a/src/codexray/report/assemble.py b/src/codexray/report/assemble.py index 7cbd2663..3d790218 100644 --- a/src/codexray/report/assemble.py +++ b/src/codexray/report/assemble.py @@ -20,13 +20,9 @@ from codexray.core.errors import CodeXrayError from codexray.model.rollup import Tree from codexray.report import templates +from codexray.report.line_shares import LineOrigin from codexray.report.ranking import Ranked, RankInput, rank -ORIGIN_NOTE = ( - "Explicit markers only, so a lower bound. Line-level origin is not collected in this " - "run yet, so both shares are shown as 0." -) - @dataclass(frozen=True) class Snapshot: @@ -161,8 +157,12 @@ def assemble( tree: Tree, end: Snapshot, judgements: Mapping[str, contracts.Judgement], + origin: LineOrigin, ) -> tuple[list[Finding], list[Ranked]]: - """Every finding of the END snapshot, in final order, with the ranking behind it.""" + """Every finding of the END snapshot, in final order, with the ranking behind it. + + `origin` gives each finding the shares of its evidence lines (`line_shares`). + """ repo = manifest.repo report, analyze = settings["report"], settings["analyze"] ranking = report["ranking"] @@ -260,7 +260,7 @@ def assemble( else [(end, breach)], sponsor_date, ), - origin=contracts.Origin(lines_after_2025_03=0.0, lines_ai_marked=0.0, note=ORIGIN_NOTE), + origin=origin.finding_origin(evidence, end.sha), link_quality=( contracts.LinkQuality(how="same-folder" if by_rule else "import-path") if linked diff --git a/src/codexray/report/before_after.py b/src/codexray/report/before_after.py new file mode 100644 index 00000000..04268af0 --- /dev/null +++ b/src/codexray/report/before_after.py @@ -0,0 +1,946 @@ +"""`before_after.json`: the sponsor date against END, and every structural change between +them with a label and its evidence (spec.md §10.2, §12). + +**The grid.** `module_order` holds every module that exists at either date once, in one +order computed from the link weights of both dates added together (spec.md §9.5, §10.4), +so switching dates changes colours only. `cells` holds every module pair with links at +either date; the `after` counts are those of the edges of `map.json`. + +**The changes**, in this order: one layout change per snapshot interval whose set of +modules differs (oldest first), each commit in `structural_events` after the sponsor date +(oldest first), modules added and modules removed (by the interval they appear or go in, +then by id), links added and links removed (most link lines first, at most +`max_link_changes` of each kind). A new link cites the link lines its tag rests on: those +that count toward "expected and found", or, when it is "found but not expected", those +that count against. + +**The labels** (spec.md §12.3). The bases are tried in order and the first that holds +wins; a change with none is "no stated intent", never anything worse: + +1. same code, old layout (`analyze.drift`): the interval is a reorganisation; for a + commit, its interval is one and it moved at least `min_files_moved` renamed files to + another module; for a module, at least `most_share` of its files at its first + snapshot existed at the snapshot before (for a removed module, of its files at its + last snapshot still exist at the next); for a new link, at least `most_share` of its + link lines join two files that both existed at the sponsor date by id and that, under + the sponsor date's layout, sit in one module or in two modules already linked then + ("expected and found"; a link line with an end file that did not exist then counts + against); for a removed link, link lines at END between two files that both existed + at the sponsor date by id still join the pair under that layout (renamed by a change + of layout, not removed). A file placed in an old module by its folder never counts + for a link label: its code did not exist at the earlier date, so nothing recorded + says it was expected; +2. a commit flagged by Stage 1 as planned restructuring: in the interval; for a commit, + the commit itself; for a module or a link, one that changed at least + `min_changed_share` of the module's files or of the files the link lines are in; +3. a decision document at END (`decision_documents` globs) added after the sponsor date + whose text names the full folder path of the module (for a link, of both modules; + for an interval, of a module added or removed in it), or the commit's pull-request + number or id; +4. the stated goal of the pull request is not evaluated here. +""" + +from __future__ import annotations + +import re +from collections import Counter, defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date, datetime +from fnmatch import fnmatchcase +from pathlib import Path +from typing import Any + +import duckdb + +from codexray.analyze import drift +from codexray.analyze.grain import module_order as order_modules +from codexray.analyze.snapshot import SnapshotMap, load_snapshot +from codexray.core import contracts as c +from codexray.core.contracts import Decision +from codexray.model.rollup import load_tree +from codexray.report.assemble import Snapshot, short_names +from codexray.report.bundle import module_counts +from codexray.repository import git + +Pair = tuple[str, str] +BASIS_ORDER = ("same_code_old_layout", "restructuring_commit", "decision_document") +MEASURE_NAMES = { + "exceptions_per_kloc": "exceptions per 1,000 lines", + "cross_module_links": "links between modules", +} +REMOVED_TAGS = ("renamed by a change of layout", "expected but missing", "code no longer there") + + +@dataclass(frozen=True) +class Interval: + older: Snapshot + newer: Snapshot + remeasure: drift.Remeasure + added: tuple[str, ...] # modules present at `newer` and not at `older` + removed: tuple[str, ...] + + +@dataclass(frozen=True) +class Commit: + sha: str + when: datetime + files: int + renames: int + subject: str + label: str | None # Stage 1 planned-restructuring label + pr: int | None + + +@dataclass(frozen=True) +class Document: + path: str + blob_sha: str + added_sha: str + added: str # date + lines: tuple[str, ...] + + +@dataclass +class BeforeAfter: + """The file, and what the report prints and states about it.""" + + file: c.BeforeAfterFile + limits: list[str] + intervals: list[Interval] + document_matches: int + documents: int + end_placement: drift.Placement | None = None + link_totals: dict[str, Counter[str]] = field(default_factory=dict) + listed: Counter[str] = field(default_factory=Counter) + + +def build_before_after( + con: duckdb.DuckDBPyConnection, + repo: str, + all_snapshots: Sequence[Snapshot], + end: Snapshot, + the_map: c.MapFile, + adoption_date: str | None, + decisions: Sequence[Decision], + settings: Mapping[str, Any], + blob_paths: dict[str, str], + clone_dir: Path, +) -> BeforeAfter: + """`before_after.json` for the sponsor date against END. + + `blob_paths` says under which path each cited blob is shown; evidence lines whose blob + another path already claims are left out, as in `map.json`. + """ + cfg = settings["report"]["before_after"] + before = next((s for s in all_snapshots if s.role == "sponsor_date"), all_snapshots[0]) + span = [s for s in all_snapshots if before.date <= s.date <= end.date] + maps = { + s.sha: load_snapshot(con, repo, s.sha, date.fromisoformat(s.date), s.role, + settings["analyze"]) + for s in span + } # fmt: skip + first, last = maps[before.sha], maps[end.sha] + + # The grid on one order for both dates. + now = {(e.src, e.dst): e.count for e in the_map.edges} + then = module_counts(con, repo, before.sha, load_tree(con, repo, before.sha)) + modules_after = {n.id for n in the_map.nodes if n.level == "module"} + modules_before = set(first.modules) + weights: dict[Pair, int] = defaultdict(int) + for counts in (then, now): + for pair, n in counts.items(): + weights[pair] += n + for module in modules_before | modules_after: + weights.setdefault((module, module), 0) # modules without links still get a place + order = order_modules(dict(weights)) + cells = [ + c.CellChange(src=a, dst=b, before=then.get((a, b), 0), after=now.get((a, b), 0)) + for a, b in sorted(set(now) | set(then)) + ] + every = set(order).union(*(smap.modules for smap in maps.values())) + names = short_names(sorted(every)) + + # Same code, old layout, for every interval; and END under the sponsor date's layout. + intervals: list[Interval] = [] + previous = None + for older, newer in zip(span, span[1:], strict=False): + result, _relaid = drift.remeasure( + maps[older.sha], maps[newer.sha], decisions, cfg, older_measure=previous + ) + previous = result.new_layout + a, b = set(maps[older.sha].modules), set(maps[newer.sha].modules) + intervals.append(Interval(older, newer, result, tuple(sorted(b - a)), tuple(sorted(a - b)))) + end_old, end_placement = drift.under_layout(last, first) + + when = _commit_dates(con, repo, [s.sha for s in span]) + events = _commits(con, repo, when[before.sha], when[end.sha], structural=True) + planned = _commits(con, repo, when[before.sha], when[end.sha], structural=False) + touched = _changed_files(con, repo, sorted({k.sha for k in events} | {k.sha for k in planned})) + renamed = _renamed_files(con, repo, sorted(k.sha for k in events)) + documents = _documents(con, repo, end, when[before.sha], cfg, clone_dir, blob_paths) + + def interval_of(moment: datetime) -> Interval | None: + for interval in intervals: + if when[interval.older.sha] < moment <= when[interval.newer.sha]: + return interval + return None + + def planned_in(interval: Interval) -> list[Commit]: + return [k for k in planned if interval_of(k.when) is interval] + + def planned_covering(files: set[str], scope: Sequence[Commit]) -> Commit | None: + """The first planned-restructuring commit that changed enough of `files`.""" + if not files: + return None + for commit in scope: + share = len(files & touched.get(commit.sha, set())) / len(files) + if share >= float(cfg["min_changed_share"]): + return commit + return None + + matches = 0 + out: list[tuple[tuple, c.StructuralChange]] = [] + + def add(key: tuple, change_id: str, kind: str, title: str, held: Mapping[str, bool], + evidence: Sequence[Mapping[str, Any]]) -> None: # fmt: skip + basis = next((b for b in BASIS_ORDER if held.get(b)), None) + records = [ + c.Evidence.model_validate({**record, "id": f"E{i}"}) + for i, record in enumerate(evidence, 1) + ] + out.append( + ( + key, + c.StructuralChange( + id=change_id, + title=title, + kind=kind, + label="planned" if basis else "no_stated_intent", + basis=basis, + source="computed", + evidence=records, + ), + ) + ) + + # 1. One layout change per interval whose set of modules differs. + for n, interval in enumerate(intervals): + if not interval.added and not interval.removed: + continue + older, newer = interval.older, interval.newer + commits_here = [k for k in events if interval_of(k.when) is interval] + flagged = planned_in(interval) + doc = _naming(documents, [_folder(m, maps) for m in (*interval.added, *interval.removed)], + any_of=True) # fmt: skip + matches += doc is not None + evidence = [ + _commit_record(repo, newer.sha, older.sha, + f"snapshot at {older.date}, {len(maps[older.sha].modules)} modules"), + _commit_record(repo, newer.sha, newer.sha, + f"snapshot at {newer.date}, {len(maps[newer.sha].modules)} modules"), + ] # fmt: skip + for commit in commits_here: + evidence.append(_commit_record(repo, newer.sha, commit.sha, _event_role(commit))) + for commit in flagged: + if commit.sha not in {k.sha for k in commits_here}: + evidence.append( + _commit_record(repo, newer.sha, commit.sha, + f"commit flagged as planned restructuring ({commit.label})") + ) # fmt: skip + evidence += _document_records(repo, end.sha, doc) + add( + (0, n), + f"layout/{older.date}..{newer.date}", + "restructuring", + _layout_title(interval, maps, cfg), + { + "same_code_old_layout": interval.remeasure.reorganisation, + "restructuring_commit": bool(flagged), + "decision_document": doc is not None, + }, + evidence, + ) + + # 2. Each structural-event commit after the sponsor date. + for n, commit in enumerate(events): + interval = interval_of(commit.when) + moved = 0 + if interval is not None: + older_files = maps[interval.older.sha].files + newer_files = maps[interval.newer.sha].files + for file_id in renamed.get(commit.sha, ()): + a, b = older_files.get(file_id), newer_files.get(file_id) + if a is not None and b is not None and a.module != b.module: + moved += 1 + doc = _naming_commit(documents, commit, int(cfg["commit_id_chars"])) + matches += doc is not None + title = f"{commit.subject}: {_count(commit.files, 'file')} changed, " + ( + f"{commit.renames:,} of them renamed, {moved:,} of those into another module" + if commit.renames + else "none renamed" + ) + if interval is not None: + title += f" (between the snapshots of {interval.older.date} and {interval.newer.date})" + title += "." + role = _event_role(commit) + add( + (1, n), + f"restructuring/{commit.sha}", + "restructuring", + title, + { + "same_code_old_layout": bool( + interval and interval.remeasure.reorganisation + and moved >= int(cfg["min_files_moved"]) + ), + "restructuring_commit": commit.label is not None, + "decision_document": doc is not None, + }, + [ + _commit_record(repo, (interval.newer if interval else end).sha, commit.sha, role), + *_document_records(repo, end.sha, doc), + ], + ) # fmt: skip + + # 3. Modules added and removed, in the interval they appear or go in. + most = float(cfg["most_share"]) + for module in sorted(modules_after - modules_before): + n, interval = _last(intervals, lambda i, m=module: m in i.added) + older, newer = maps[interval.older.sha], maps[interval.newer.sha] + files = {f.id for f in newer.files.values() if f.module == module} + known = [older.files[f].module for f in sorted(files) if f in older.files] + source = _most_common(known) + title = ( + f"{names[module]} appears between {interval.older.date} and {interval.newer.date} " + f"with {_count(len(files), 'file')}; " + + ( + f"{len(known):,} of them already existed at {interval.older.date}, " + f"{known.count(source):,} in {names.get(source, _plain(source))}." + if known + else f"none of them existed at {interval.older.date}." + ) + ) + commit = planned_covering(files, planned_in(interval)) + doc = _naming(documents, [_folder(module, maps)]) + matches += doc is not None + add( + (2, n, module), + f"module_added/{module}", + "module_added", + title, + { + "same_code_old_layout": bool(files) and len(known) / len(files) >= most, + "restructuring_commit": commit is not None, + "decision_document": doc is not None, + }, + _module_records(repo, interval, commit, f"{names[module]} is not there", + f"{names[module]} is there") + + _document_records(repo, end.sha, doc), + ) # fmt: skip + for module in sorted(modules_before - modules_after): + n, interval = _last(intervals, lambda i, m=module: m in i.removed) + older, newer = maps[interval.older.sha], maps[interval.newer.sha] + files = {f.id for f in older.files.values() if f.module == module} + kept = [newer.files[f].module for f in sorted(files) if f in newer.files] + target = _most_common(kept) + title = ( + f"{names[module]} is gone between {interval.older.date} and {interval.newer.date}. " + f"It had {_count(len(files), 'file')} at {interval.older.date}; " + + ( + f"{len(kept):,} of them still {'exists' if len(kept) == 1 else 'exist'} at " + f"{interval.newer.date}, " + f"{kept.count(target):,} in {names.get(target, _plain(target))}." + if kept + else f"none of them exist at {interval.newer.date}." + ) + ) + commit = planned_covering(files, planned_in(interval)) + doc = _naming(documents, [_folder(module, maps)]) + matches += doc is not None + add( + (3, n, module), + f"module_removed/{module}", + "module_removed", + title, + { + "same_code_old_layout": bool(files) and len(kept) / len(files) >= most, + "restructuring_commit": commit is not None, + "decision_document": doc is not None, + }, + _module_records(repo, interval, commit, f"{names[module]} is there", + f"{names[module]} is not there") + + _document_records(repo, end.sha, doc), + ) # fmt: skip + + # 4. Links added and removed between the two dates. Their labels count only link lines + # between files that existed at the sponsor date by id: a file placed by folder is code + # that did not exist then, so the older layout says nothing about what was expected. + end_links = _pair_links(last) + existed = set(first.files) + old_weights = { + pair: sum(k.count for k in ks if k.src in existed and k.dst in existed) + for pair, ks in _pair_links(end_old).items() + } + before_links = _pair_links(first) + old_modules_at_end = {f.module for f in end_old.files.values()} + edge_refs = {(e.src, e.dst): e.refs for e in the_map.edges} + keep_refs = int(cfg["max_link_evidence"]) + link_totals: dict[str, Counter[str]] = {"link_added": Counter(), "link_removed": Counter()} + candidates: dict[str, list[tuple[tuple, Any]]] = {"link_added": [], "link_removed": []} + + for cell in cells: + pair = (cell.src, cell.dst) + a, b = names[cell.src], names[cell.dst] + if cell.before == 0 and cell.after > 0: + links = end_links.get(pair, []) + total = sum(k.count for k in links) + toward: list[Any] = [] + against: list[Any] = [] + for k in links: + held_then = ( + k.src in existed + and k.dst in existed + and _expected(first.files[k.src].module, first.files[k.dst].module, then) + ) + (toward if held_then else against).append(k) + known = sum(k.count for k in toward) + share = known / total if total else 0.0 + expected = total > 0 and share >= most + tag = "expected and found" if expected else "found but not expected" + title = ( + f"{a} uses {b} at {end.date} through {_count(cell.after, 'link line')}, " + f"and did not at {before.date}. {tag.capitalize()}: {known:,} of " + f"{_count(total, 'link line')} join files that already existed at " + f"{before.date} and were already linked, or in one module, under that layout." + ) + commit = planned_covering({k.src for k in links}, planned) + doc = _naming(documents, [_folder(cell.src, maps), _folder(cell.dst, maps)]) + matches += doc is not None + # Cite the link lines the tag rests on: those that count toward it when + # expected, those that count against it otherwise. + evidence = ( + _link_refs(toward if expected else against, keep_refs, blob_paths, end.date) + or [ + {**ref.model_dump(mode="json"), "role": f"link line at {end.date}: {ref.role}"} + for ref in edge_refs.get(pair, [])[:keep_refs] + ] + or [_commit_record(repo, end.sha, end.sha, f"snapshot at {end.date}")] + ) + if commit is not None: + evidence.append(_commit_record(repo, end.sha, commit.sha, _event_role(commit))) + evidence += _document_records(repo, end.sha, doc) + held = { + "same_code_old_layout": expected, + "restructuring_commit": commit is not None, + "decision_document": doc is not None, + } + link_totals["link_added"][tag] += 1 + candidates["link_added"].append( + ((-cell.after, cell.src, cell.dst), (pair, title, held, evidence)) + ) + elif cell.before > 0 and cell.after == 0: + still = old_weights.get(pair, 0) + present = cell.src in old_modules_at_end and cell.dst in old_modules_at_end + if still: + tag = "renamed by a change of layout" + detail = ( + f"Not removed: under the {before.date} layout the code at {end.date} still " + f"links them through {_count(still, 'link line')} between files that " + f"already existed at {before.date}, so the change of layout renamed the link." + ) + elif present: + tag = "expected but missing" + detail = ( + f"Expected but missing: code of both modules is still there at {end.date}, " + f"and no link joins them at {end.date}, nor, under the {before.date} " + f"layout, between files that already existed at {before.date}." + ) + else: + tag = "code no longer there" + gone = [m for m in pair if m not in old_modules_at_end] + detail = ( + f"No file of {' or '.join(names[m] for m in gone)} at {before.date} is " + f"still there at {end.date}." + ) + title = ( + f"{a} used {b} at {before.date} through {_count(cell.before, 'link line')}, " + f"and does not at {end.date}. {detail}" + ) + links = before_links.get(pair, []) + commit = planned_covering({k.src for k in links}, planned) + doc = _naming(documents, [_folder(cell.src, maps), _folder(cell.dst, maps)]) + matches += doc is not None + evidence = _link_refs(links, keep_refs, blob_paths, before.date) + evidence += [ + _commit_record(repo, before.sha, before.sha, + f"snapshot at {before.date}, where {a} uses {b}"), + _commit_record(repo, end.sha, end.sha, + f"snapshot at {end.date}, where {a} does not use {b}"), + ] # fmt: skip + if commit is not None: + evidence.append(_commit_record(repo, end.sha, commit.sha, _event_role(commit))) + evidence += _document_records(repo, end.sha, doc) + held = { + "same_code_old_layout": bool(still), + "restructuring_commit": commit is not None, + "decision_document": doc is not None, + } + link_totals["link_removed"][tag] += 1 + candidates["link_removed"].append( + ((-cell.before, cell.src, cell.dst), (pair, title, held, evidence)) + ) + + listed: Counter[str] = Counter() + for rank, kind in enumerate(("link_added", "link_removed"), 4): + kept = sorted(candidates[kind], key=lambda item: item[0])[: int(cfg["max_link_changes"])] + for n, (_key, (pair, title, held, evidence)) in enumerate(kept): + add((rank, n), f"{kind}/{pair[0]}->{pair[1]}", kind, title, held, evidence) + listed[kind] = len(kept) + + changes = [change for _key, change in sorted(out, key=lambda item: item[0])] + + date_of = {s.sha: s.date for s in all_snapshots} + series: dict[str, dict[str, float]] = defaultdict(dict) + for sha, name, value in con.execute( + "SELECT snapshot_sha, name, value FROM yardsticks WHERE repo = ? ORDER BY name", [repo] + ).fetchall(): + if sha in date_of: + series[name][date_of[sha]] = float(value) + file = c.BeforeAfterFile( + before=c.SnapshotRef(date=before.date, sha=before.sha, role=before.role), + after=c.SnapshotRef(date=end.date, sha=end.sha, role=end.role), + adoption_date=adoption_date, + module_order=order, + cells=cells, + changes=changes, + yardsticks=[ + c.YardstickSeries( + name=name, + series=[c.TrendPoint(snapshot_date=d, value=v) for d, v in sorted(points.items())], + ) + for name, points in sorted(series.items()) + ], + ) + result = BeforeAfter( + file=file, + limits=[], + intervals=intervals, + document_matches=matches, + documents=len(documents), + end_placement=end_placement, + link_totals=link_totals, + listed=listed, + ) + result.limits = _limits(result, before, end, cfg) + return result + + +def summary(result: BeforeAfter) -> str: + """What the command prints: the changes by kind, label and basis, and the measurements.""" + counts = Counter((ch.kind, ch.label, ch.basis or "-") for ch in result.file.changes) + lines = [ + f"before and after: {len(result.file.changes)} changes listed, " + f"{len(result.file.module_order)} modules on one order, {len(result.file.cells)} cells; " + + ", ".join(f"{k} {lab} {b} {n}" for (k, lab, b), n in sorted(counts.items())) + ] + for kind, tags in sorted(result.link_totals.items()): + lines.append( + f" {kind}: " + + ", ".join(f"{t} {n}" for t, n in sorted(tags.items())) + + f"; {result.listed[kind]} listed" + ) + lines.append( + f" decision documents: {result.documents} dated after the sponsor date, " + f"{result.document_matches} changes matched" + ) + if result.end_placement: + p = result.end_placement + lines.append( + f" END under the sponsor-date layout: {p.by_id} files by id, {p.by_folder} by " + f"folder, {p.kept} kept" + ) + for i in result.intervals: + r, p = i.remeasure, i.remeasure.placement + lines.append( + f" {i.older.date}..{i.newer.date}: +{len(i.added)} -{len(i.removed)} modules; " + f"exceptions/kloc {r.older.exceptions_per_kloc:.6f} -> " + f"{r.new_layout.exceptions_per_kloc:.6f} (old layout " + f"{r.old_layout.exceptions_per_kloc:.6f}); cross-module links " + f"{r.older.cross_module_links} -> {r.new_layout.cross_module_links} (old layout " + f"{r.old_layout.cross_module_links}); gone {r.gone}; reorganisation " + f"{r.reorganisation}; placed {p.by_id} by id, {p.by_folder} by folder, {p.kept} kept" + ) + return "\n".join(lines) + + +# --- Reading the tables ------------------------------------------------------------ + + +def _commit_dates(con: duckdb.DuckDBPyConnection, repo: str, shas: Sequence[str]) -> dict: + rows = con.execute( + "SELECT sha, committer_date FROM commits WHERE repo = ? " + "AND sha IN (SELECT unnest(?::VARCHAR[]))", + [repo, list(shas)], + ).fetchall() + return {sha: moment for sha, moment in rows} + + +def _commits( + con: duckdb.DuckDBPyConnection, repo: str, after: datetime, upto: datetime, *, structural: bool +) -> list[Commit]: + """Structural-event commits, or commits flagged as planned restructuring, landed after + `after` and up to `upto`, oldest first.""" + if structural: + sql = ( + "SELECT s.sha, c.committer_date, s.files, s.renames, s.subject, " + "c.restructuring_label, c.pr_number FROM structural_events s " + "JOIN commits c ON c.repo = s.repo AND c.sha = s.sha " + "WHERE s.repo = ? AND c.committer_date > ? AND c.committer_date <= ? " + "ORDER BY c.committer_date, s.sha" + ) + else: + sql = ( + "SELECT c.sha, c.committer_date, c.files_changed, 0, '', c.restructuring_label, " + "c.pr_number FROM commits c WHERE c.repo = ? AND c.restructuring_label IS NOT NULL " + "AND c.committer_date > ? AND c.committer_date <= ? ORDER BY c.committer_date, c.sha" + ) + return [ + Commit(sha, moment, int(files), int(renames), subject, label, pr) + for sha, moment, files, renames, subject, label, pr in con.execute( + sql, [repo, after, upto] + ).fetchall() + ] + + +def _file_ids(path: str, old_path: str | None, canonical: str) -> set[str]: + """The file ids one changed path can have at a snapshot (spec.md §7.1: the path at END; + a file deleted before END keeps the path it had).""" + if canonical != "": + return {f"F:{canonical}"} + return {f"F:{p}" for p in (path, old_path) if p} + + +def _changed_files(con: duckdb.DuckDBPyConnection, repo: str, shas: Sequence[str]) -> dict: + out: dict[str, set[str]] = defaultdict(set) + for sha, path, old_path, canonical in con.execute( + "SELECT sha, path, old_path, canonical_path FROM file_changes WHERE repo = ? " + "AND sha IN (SELECT unnest(?::VARCHAR[])) ORDER BY sha, path", + [repo, list(shas)], + ).fetchall(): + out[sha] |= _file_ids(path, old_path, canonical) + return dict(out) + + +def _renamed_files(con: duckdb.DuckDBPyConnection, repo: str, shas: Sequence[str]) -> dict: + out: dict[str, list[str]] = defaultdict(list) + for sha, canonical in con.execute( + "SELECT sha, canonical_path FROM file_changes WHERE repo = ? " + "AND status LIKE 'R%' AND sha IN (SELECT unnest(?::VARCHAR[])) ORDER BY sha, path", + [repo, list(shas)], + ).fetchall(): + if canonical != "": + out[sha].append(f"F:{canonical}") + return dict(out) + + +def _documents( + con: duckdb.DuckDBPyConnection, + repo: str, + end: Snapshot, + after: datetime, + cfg: Mapping[str, Any], + clone_dir: Path, + blob_paths: dict[str, str], +) -> list[Document]: + """Decision documents at END added after `after`, oldest first, with their text.""" + globs = list(cfg["decision_documents"]) + files = { + path: blob + for path, blob in con.execute( + "SELECT path, blob_sha FROM snapshot_files WHERE repo = ? AND snapshot_sha = ? " + "ORDER BY path", + [repo, end.sha], + ).fetchall() + if any(fnmatchcase(path, glob) for glob in globs) + } + if not files: + return [] + added: dict[str, tuple[str, datetime]] = {} + for path, sha, moment in con.execute( + "SELECT f.canonical_path, c.sha, c.committer_date FROM file_changes f " + "JOIN commits c ON c.repo = f.repo AND c.sha = f.sha " + "WHERE f.repo = ? AND f.status = 'A' AND f.canonical_path IN (SELECT unnest(?::VARCHAR[])) " + "ORDER BY f.canonical_path, c.committer_date, c.sha", + [repo, sorted(files)], + ).fetchall(): + added.setdefault(path, (sha, moment)) + dated = {p: added[p] for p in sorted(files) if p in added and added[p][1] > after} + texts: dict[str, str] = {} + for item in git.cat_file(clone_dir, sorted({files[p] for p in dated})): + try: + texts[item.object_id] = (item.content or b"").decode("utf-8") + except UnicodeDecodeError: + continue + out = [] + for path, (sha, moment) in dated.items(): + blob = files[path] + if blob not in texts or blob_paths.setdefault(blob, path) != path: + continue # unreadable, or the blob is shown under another path + out.append(Document(path, blob, sha, moment.date().isoformat(), + tuple(texts[blob].splitlines()))) # fmt: skip + return sorted(out, key=lambda d: (d.added, d.path)) + + +# --- Matching decision documents --------------------------------------------------- + + +def _folder(module: str, maps: Mapping[str, SnapshotMap]) -> str | None: + """The full folder path of a module that is one folder, else None.""" + for smap in maps.values(): + path = smap.modules.get(module) + if path is not None: + return path if path and module == f"M:{path}" else None + return None + + +def _path_pattern(path: str) -> re.Pattern[str]: + # The whole folder path, ending at a folder boundary: not inside a longer name. + return re.compile( + r"(? int | None: + for number, line in enumerate(document.lines, 1): + if pattern.search(line): + return number + return None + + +def _naming( + documents: Sequence[Document], folders: Sequence[str | None], *, any_of: bool = False +) -> tuple[Document, list[tuple[str, int]]] | None: + """The first document that names every folder (with `any_of`, at least one), and the + first line naming each. A module that is not one folder cannot be named.""" + wanted = [f for f in folders if f] + if not wanted or (not any_of and len(wanted) < len(folders)): + return None + patterns = {folder: _path_pattern(folder) for folder in sorted(set(wanted))} + for document in documents: + found = {f: _find(document, p) for f, p in patterns.items()} + hits = [(f, line) for f, line in found.items() if line is not None] + if hits and (any_of or len(hits) == len(patterns)): + return document, hits + return None + + +def _naming_commit( + documents: Sequence[Document], commit: Commit, chars: int +) -> tuple[Document, list[tuple[str, int]]] | None: + patterns = [(f"commit {commit.sha[:chars]}", + re.compile(r"(? dict[str, Any]: + return {"repo": repo, "snapshot_sha": snapshot_sha, "kind": "commits", "commits": [sha], + "role": role} # fmt: skip + + +def _event_role(commit: Commit) -> str: + text = f"commit of {commit.when.date().isoformat()} that changed {_count(commit.files, 'file')}" + if commit.renames: + text += f", {commit.renames:,} renamed" + if commit.label: + text += f"; flagged as planned restructuring ({commit.label})" + return text + + +def _document_records( + repo: str, end_sha: str, match: tuple[Document, list[tuple[str, int]]] | None +) -> list[dict[str, Any]]: + if match is None: + return [] + document, hits = match + records: list[dict[str, Any]] = [ + { + "repo": repo, + "snapshot_sha": end_sha, + "kind": "lines", + "path": document.path, + "start_line": line, + "end_line": line, + "blob_sha": document.blob_sha, + "role": f"decision document added {document.added}, names {name}", + } + for name, line in hits + ] + records.append(_commit_record(repo, end_sha, document.added_sha, + "commit that added the decision document")) # fmt: skip + return records + + +def _module_records( + repo: str, interval: Interval, commit: Commit | None, at_older: str, at_newer: str +) -> list[dict[str, Any]]: + older, newer = interval.older, interval.newer + records = [ + _commit_record(repo, newer.sha, older.sha, f"snapshot at {older.date}, where {at_older}"), + _commit_record(repo, newer.sha, newer.sha, f"snapshot at {newer.date}, where {at_newer}"), + ] + if commit is not None: + records.append(_commit_record(repo, newer.sha, commit.sha, _event_role(commit))) + return records + + +def _link_refs( + links: Sequence[Any], keep: int, blob_paths: dict[str, str], when: str +) -> list[dict[str, Any]]: + """Up to `keep` link lines of `links` at the snapshot of `when`, skipping blobs shown + under another path.""" + out: list[dict[str, Any]] = [] + refs = [ + r for link in links for r in link.refs if r.get("kind") == "lines" and r.get("blob_sha") + ] + for ref in sorted(refs, key=lambda r: (r["path"], r["start_line"], r["end_line"])): + if len(out) >= keep: + break + if blob_paths.setdefault(ref["blob_sha"], ref["path"]) != ref["path"]: + continue + record = {k: v for k, v in ref.items() if k != "id"} + record["role"] = f"link line at {when}: {ref.get('role', 'link')}" + out.append(record) + return out + + +# --- Helpers ----------------------------------------------------------------------- + + +def _pair_links(smap: SnapshotMap) -> dict[Pair, list[Any]]: + """Production links of `smap` between different modules, by module pair.""" + out: dict[Pair, list[Any]] = defaultdict(list) + for link in smap.production_links(): + a, b = smap.files[link.src].module, smap.files[link.dst].module + if a and b and a != b: + out[(a, b)].append(link) + return dict(out) + + +def _expected(a: str | None, b: str | None, then: Mapping[Pair, int]) -> bool: + """Whether, under the older layout, a link from module a to module b joins one module + or two modules that were already linked then.""" + return a is not None and b is not None and (a == b or then.get((a, b), 0) > 0) + + +def _last(intervals: Sequence[Interval], test: Any) -> tuple[int, Interval]: + """The latest interval that passes `test`, with its index. A module that is at END and + not at the sponsor date appears in some interval, and one removed goes in one.""" + for n in range(len(intervals) - 1, -1, -1): + if test(intervals[n]): + return n, intervals[n] + raise ValueError("no interval holds the change") + + +def _most_common(values: Sequence[str | None]) -> str | None: + counts = Counter(v for v in values if v) + return min(counts, key=lambda v: (-counts[v], v)) if counts else None + + +def _count(n: int, word: str) -> str: + return f"{n:,} {word}" if n == 1 else f"{n:,} {word}s" + + +def _plain(module: str | None) -> str: + return (module or "no module").removeprefix("M:") + + +def _percent(older: float, newer: float) -> str: + if older == 0: + return "from 0" if newer else "no change" + return f"{(newer - older) / abs(older):+.1%}" + + +def _layout_title(interval: Interval, maps: Mapping[str, SnapshotMap], cfg: Mapping) -> str: + older, newer, r = interval.older, interval.newer, interval.remeasure + a, b = r.older, r.new_layout + o = r.old_layout + text = ( + f"From {older.date} to {newer.date} the modules went from " + f"{len(maps[older.sha].modules)} to {len(maps[newer.sha].modules)} " + f"({len(interval.added)} new, {len(interval.removed)} gone). " + f"Exceptions per 1,000 lines: {a.exceptions_per_kloc:.3f} at {older.date}; at " + f"{newer.date} {b.exceptions_per_kloc:.3f} under the new layout " + f"({_percent(a.exceptions_per_kloc, b.exceptions_per_kloc)}) and " + f"{o.exceptions_per_kloc:.3f} under the {older.date} layout " + f"({_percent(a.exceptions_per_kloc, o.exceptions_per_kloc)}). " + f"Links between modules: {a.cross_module_links:,} at {older.date}; at {newer.date} " + f"{b.cross_module_links:,} under the new layout " + f"({_percent(a.cross_module_links, b.cross_module_links)}) and " + f"{o.cross_module_links:,} under the {older.date} layout " + f"({_percent(a.cross_module_links, o.cross_module_links)}). " + ) + gone = {name: v for name, v in r.gone.items() if v is not None} + most = float(cfg["most_share"]) + if not gone: + return text + ( + f"Neither measure moved by more than {float(cfg['min_change_share']):.0%}, so " + "the old layout cannot show a reorganisation." + ) + parts = [ + f"{'none' if v <= 0 else f'{min(v, 1.0):.0%}'} of the change in {MEASURE_NAMES[name]}" + for name, v in gone.items() + ] + verb = "disappears" if len(parts) == 1 else "disappear" + text += f"Under the old layout, {' and '.join(parts)} {verb}, so the layout change " + rule = f"(the rule asks for at least {most:.0%} of one change)" + if r.reorganisation: + return text + f"is counted as a reorganisation {rule}." + return text + f"is not counted as a reorganisation {rule}." + + +def _limits(result: BeforeAfter, before: Snapshot, end: Snapshot, cfg: Mapping) -> list[str]: + added, removed = result.link_totals["link_added"], result.link_totals["link_removed"] + + def tally(counts: Counter[str], tags: Sequence[str]) -> str: + return ", ".join(f"{counts[t]:,} {t}" for t in tags) + + n_added = sum(added[t] for t in ("expected and found", "found but not expected")) + n_removed = sum(removed[t] for t in REMOVED_TAGS) + return [ + "Report: the before-and-after labels do not use the stated goal of the pull request " + "behind a change (spec.md §12.3, the fourth basis), which this run does not read; a " + "change labelled no stated intent may still have a stated goal in its pull request.", + f"Report: between {before.date} and {end.date}, {n_added:,} module pairs gained " + f"their first links ({tally(added, ('expected and found', 'found but not expected'))}) " + f"and {n_removed:,} lost all their links ({tally(removed, REMOVED_TAGS)}). " + f"The before-and-after view lists {result.listed['link_added']:,} of the first and " + f"{result.listed['link_removed']:,} of the second, those with the most link lines; " + "every pair is in the grid. A first link is expected and found when at least " + f"{float(cfg['most_share']):.0%} of its link lines join files that already existed " + f"at {before.date} and were already linked, or in one module, under the " + f"{before.date} layout; a link line with an end file that did not exist at " + f"{before.date} counts against, since nothing recorded says it was expected. A lost " + "link counts as renamed by a change of layout only through link lines between such " + "files.", + "Report: a layout change counts as a reorganisation when the newer snapshot, measured " + "again with the older snapshot's modules, loses at least " + f"{float(cfg['most_share']):.0%} of its change in exceptions per 1,000 lines or in " + "links between modules; for this re-measurement a file that is new since the older " + "snapshot takes the module most common among the older files in its folder, so new " + "code is counted as part of the modules around it.", + "Report: a decision document counts only when it was added after " + f"{before.date} and names the module's full folder path, or the commit's pull-request " + f"number or id; {result.document_matches:,} changes matched one of " + f"{result.documents:,} such documents.", + ] diff --git a/src/codexray/report/bundle.py b/src/codexray/report/bundle.py index c37d9763..b98496b8 100644 --- a/src/codexray/report/bundle.py +++ b/src/codexray/report/bundle.py @@ -6,7 +6,7 @@ Every file is a record from `core.contracts`, validated before it is written, and goes through `runs.write_json`, so a second run gives the same bytes. Every evidence record in the bundle is checked against the text of the blob it cites; evidence that does not -resolve to real lines fails the run. +resolve to real lines fails the run. `before_after.json` is built in `before_after.py`. `make bundle REPO=` calls `main` here to copy a run's bundle into the web app. """ @@ -27,8 +27,9 @@ from codexray.core import contracts as c from codexray.core import runs from codexray.core.errors import CodeXrayError -from codexray.model.rollup import Tree, load_tree +from codexray.model.rollup import Tree from codexray.report.assemble import Snapshot, module_of +from codexray.report.line_shares import LineOrigin, share from codexray.repository import git Pair = tuple[str, str] @@ -102,12 +103,17 @@ def build_map( findings: Sequence[c.Finding], cfg: Mapping[str, Any], blob_paths: dict[str, str], + origin: LineOrigin, ) -> c.MapFile: """`map.json`: the repo, its modules and files; links between modules; the numbers. `blob_paths` says under which path each cited blob is shown. Two files with the same content share one blob and one code file, so a cell keeps an evidence line only if it cites the blob under that path; the first path to cite a blob claims it. + + `share_after_2025_03` comes from line origin (`line_shares`): a file's lines with a + recorded origin, and for a module all such lines of its files. Only production files + have one, so other files show 0. """ rows = con.execute( "SELECT id, level, path, kind, loc FROM nodes WHERE repo = ? AND snapshot_sha = ? " @@ -181,9 +187,15 @@ def build_map( changes = _changes_12m(con, repo, end.sha) files_in: dict[str, int] = defaultdict(int) changes_in: dict[str, int] = defaultdict(int) + after_in: dict[str, int] = defaultdict(int) # lines after the sponsor date, by node + origin_in: dict[str, int] = defaultdict(int) # lines with a recorded origin, by node for file_id, module in module_of_file.items(): files_in[module] += 1 changes_in[module] += changes.get(path_of[file_id], 0) + after, known = origin.path_lines(path_of[file_id]) + for node_id in (file_id, module): + after_in[node_id] += after + origin_in[node_id] += known stats, descriptions = [], [] using: dict[str, set[str]] = defaultdict(set) used_by: dict[str, set[str]] = defaultdict(set) @@ -203,7 +215,7 @@ def build_map( links_out=links_out[node.id], changes_12m=changes_in[node.id] if is_module else changes.get(node.path, 0), exceptions=exceptions[node.id], - share_after_2025_03=0.0, + share_after_2025_03=share(after_in[node.id], origin_in[node.id]), ) ) if is_module: @@ -264,61 +276,18 @@ def build_layouts(findings: Sequence[c.Finding], the_map: c.MapFile, tree: Tree) return c.LayoutsFile(layouts=layouts) -def build_before_after( - con: duckdb.DuckDBPyConnection, - repo: str, - all_snapshots: Sequence[Snapshot], - end: Snapshot, - the_map: c.MapFile, - adoption_date: str | None, -) -> c.BeforeAfterFile: - """`before_after.json`: the sponsor date against END on END's module order. - - Only modules that exist at END have cells, so a module that was removed since is not - shown. The list of labelled structural changes is filled by the bonus stage. - """ - before = next((s for s in all_snapshots if s.role == "sponsor_date"), all_snapshots[0]) - modules = set(the_map.module_order) - now = {(e.src, e.dst): e.count for e in the_map.edges} - earlier = module_counts(con, repo, before.sha, load_tree(con, repo, before.sha)) - then = {pair: n for pair, n in earlier.items() if pair[0] in modules and pair[1] in modules} - cells = [ - c.CellChange(src=a, dst=b, before=then.get((a, b), 0), after=now.get((a, b), 0)) - for a, b in sorted(set(now) | set(then)) - ] - date_of = {s.sha: s.date for s in all_snapshots} - series: dict[str, dict[str, float]] = defaultdict(dict) - for sha, name, value in con.execute( - "SELECT snapshot_sha, name, value FROM yardsticks WHERE repo = ? ORDER BY name", [repo] - ).fetchall(): - if sha in date_of: - series[name][date_of[sha]] = float(value) - return c.BeforeAfterFile( - before=c.SnapshotRef(date=before.date, sha=before.sha, role=before.role), - after=c.SnapshotRef(date=end.date, sha=end.sha, role=end.role), - adoption_date=adoption_date, - module_order=the_map.module_order, - cells=cells, - changes=[], - yardsticks=[ - c.YardstickSeries( - name=name, - series=[c.TrendPoint(snapshot_date=d, value=v) for d, v in sorted(points.items())], - ) - for name, points in sorted(series.items()) - ], - ) - - def build_report( con: duckdb.DuckDBPyConnection, run: runs.RunPaths, manifest: c.Manifest, end: Snapshot, settings: Mapping[str, Any], + origin: LineOrigin, + before_after_limits: Sequence[str] = (), ) -> c.ReportFile: """`report.json`: yardsticks, weights, coverage, limits and the AI usage ledger. + `before_after_limits` are the limits of the before-and-after view (`before_after`). The stability table and the hotspot list are filled by later stages; they are empty here. """ repo, report = manifest.repo, settings["report"] @@ -361,11 +330,18 @@ def build_report( row["cached_calls"] += call.served_from_cache for key in ("input_tokens", "output_tokens", "cached_input_tokens", "cost_usd"): row[key] += getattr(call, key) - limits = list(manifest.limits) + [ + limits = [ + *manifest.limits, "Report: imports counted as outside the project include the language's own library.", - "Report: the share of lines that arrived after 2025-03-01 is not collected in this run " - "yet and is shown as 0; exceptions per file count the evidence lines kept.", + *origin.limits(), + "Report: exceptions per file count the evidence lines kept.", + *before_after_limits, ] + if not any("does not show cause" in limit for limit in limits): + limits.append( + "Report: with three repositories and no comparison group, the before-and-after " + "view describes what changed and does not show cause." + ) return c.ReportFile( yardsticks=yardsticks, weights={k: float(v) for k, v in report["ranking"]["weights"].items()}, diff --git a/src/codexray/report/line_shares.py b/src/codexray/report/line_shares.py new file mode 100644 index 00000000..12ab54ab --- /dev/null +++ b/src/codexray/report/line_shares.py @@ -0,0 +1,237 @@ +"""Line origin in the report: the shares of a finding's lines and of a map node's lines. + +Spec: spec.md §5.6, §12.2 (AI-generated risk), §12.4, §14. + +Stage 1 credits every line of a production file at END to its landed change and stores +the result in `line_origin`. Here: + +- a finding's lines are the distinct lines its evidence of kind `lines` cites at END (a + line cited twice counts once); its shares are taken over those of them that have a + recorded origin; +- a file node's share is taken over its lines with a recorded origin, and a module node's + over all such lines of its files. Only production files have a recorded origin, so a + test or generated file, and a module of them alone, shows 0. + +The AI-marked share counts lines whose landed change has a strong explicit marker. Lines +whose change has only a weak marker are counted apart and named in the note (spec.md +§5.4). A run made before line origin was collected gives 0 everywhere and says so. + +Shares are rounded to `SHARE_PLACES`, so a second run gives the same bytes. +""" + +from __future__ import annotations + +from bisect import bisect_right +from collections import defaultdict +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date +from typing import Any + +import duckdb + +from codexray.core import contracts as c +from codexray.core.errors import CodeXrayError +from codexray.repository.origin import era_names + +# The same places as the other shares the report writes. +SHARE_PLACES = 4 +COVERAGE_KEY = "line_origin" +STRONG, WEAK = "strong", "weak" + +NOT_COLLECTED = ( + "Line origin was not collected in this run, so both shares are shown as 0 and are not measured." +) + + +@dataclass +class _Ranges: + """The origin ranges of one path, sorted by first line.""" + + starts: list[int] = field(default_factory=list) + # (first line, last line, after the sponsor date, marker strength or "") + rows: list[tuple[int, int, bool, str]] = field(default_factory=list) + + +@dataclass +class LineOrigin: + """The `line_origin` rows of the END snapshot, read once for the whole report.""" + + collected: bool + sponsor_date: str + by_path: dict[str, _Ranges] + after_lines: dict[str, int] # per path: lines whose landed change is after the sponsor date + origin_lines: dict[str, int] # per path: lines with a recorded origin + + # --- Findings ------------------------------------------------------------------------ + + def finding_origin(self, evidence: Sequence[c.Evidence], end_sha: str) -> c.Origin: + """The shares of the distinct lines a finding's line evidence cites at END.""" + spans: dict[str, list[tuple[int, int]]] = defaultdict(list) + for record in evidence: + if record.kind == "lines" and record.snapshot_sha == end_sha: + # Line evidence always has a path and both lines (contracts.Evidence). + spans[record.path].append((record.start_line, record.end_line)) # type: ignore[index,arg-type] + merged = {path: _merge(found) for path, found in spans.items()} + cited = sum(last - first + 1 for runs in merged.values() for first, last in runs) + if not self.collected: + return c.Origin(lines_after_2025_03=0.0, lines_ai_marked=0.0, note=NOT_COLLECTED) + + based = after = strong = weak = 0 + for path in sorted(merged): + ranges = self.by_path.get(path) + if ranges is None: + continue + for first, last in merged[path]: + i = max(0, bisect_right(ranges.starts, first) - 1) + while i < len(ranges.rows) and ranges.rows[i][0] <= last: + start, end, is_after, marker = ranges.rows[i] + n = min(end, last) - max(start, first) + 1 + if n > 0: + based += n + after += n if is_after else 0 + strong += n if marker == STRONG else 0 + weak += n if marker == WEAK else 0 + i += 1 + + if not based: + return c.Origin( + lines_after_2025_03=0.0, + lines_ai_marked=0.0, + note=_no_origin_note(cited, evidence), + ) + return c.Origin( + lines_after_2025_03=share(after, based), + lines_ai_marked=share(strong, based), + note=_measured_note(based, cited, weak), + ) + + # --- Map nodes ----------------------------------------------------------------------- + + def path_lines(self, path: str) -> tuple[int, int]: + """(lines after the sponsor date, lines with a recorded origin) of one file.""" + return self.after_lines.get(path, 0), self.origin_lines.get(path, 0) + + # --- Limits -------------------------------------------------------------------------- + + def limits(self) -> list[str]: + if not self.collected: + return [ + "Report: line origin was not collected in this run, so the share of lines " + f"that arrived after {self.sponsor_date} and the AI-marked share of each " + "finding are shown as 0 and are not measured." + ] + return [ + f"Report: the share of lines that arrived after {self.sponsor_date} is measured " + "from line origin at END, for production files only: test and generated files " + "have no recorded origin and show 0, and a module counts only its files on the " + "map. A finding's shares count the distinct lines " + "its evidence cites that have a recorded origin.", + "Report: line origin is the last change to touch a line, which is not always the " + "change that first wrote it. The AI-marked share counts strong explicit markers " + "only, so it is a lower bound; lines with only a weak marker are kept apart and " + "named in the finding's note.", + ] + + +def share(part: int, whole: int) -> float: + """`part / whole` rounded to `SHARE_PLACES`, or 0.0 when `whole` is 0.""" + return round(part / whole, SHARE_PLACES) + 0.0 if whole else 0.0 + + +def load( + con: duckdb.DuckDBPyConnection, + manifest: c.Manifest, + end_sha: str, + settings: Mapping[str, Any], +) -> LineOrigin: + """Read `line_origin` at END, or an empty record for a run made before it existed.""" + sponsor = str(settings["repository"]["ai_evidence"]["sponsor_date"]) + collected = COVERAGE_KEY in manifest.coverage + origin = LineOrigin( + collected=collected, sponsor_date=sponsor, by_path={}, after_lines={}, origin_lines={} + ) + if not collected: + return origin + before_era, after_era = era_names(date.fromisoformat(sponsor)) + rows = con.execute( + """ + SELECT l.path, l.start_line, l.end_line, l.era, + CASE WHEN l.ai_label = 'ai_attributed' THEN coalesce(k.ai_strength, '') ELSE '' + END + FROM line_origin l + LEFT JOIN commits k ON k.repo = l.repo AND k.sha = l.commit_sha + WHERE l.repo = ? AND l.snapshot_sha = ? + ORDER BY l.path, l.start_line + """, + [manifest.repo, end_sha], + ).fetchall() + unknown = sorted({row[3] for row in rows} - {before_era, after_era}) + if unknown: + raise CodeXrayError( + f"line_origin holds era {unknown[0]}, which the sponsor date in settings " + f"({sponsor}) does not give; run `codexray ingest` again" + ) + for path, start, end, era, marker in rows: + ranges = origin.by_path.setdefault(path, _Ranges()) + is_after = era == after_era + ranges.starts.append(start) + ranges.rows.append((start, end, is_after, marker)) + size = end - start + 1 + origin.origin_lines[path] = origin.origin_lines.get(path, 0) + size + if is_after: + origin.after_lines[path] = origin.after_lines.get(path, 0) + size + return origin + + +def _merge(spans: Sequence[tuple[int, int]]) -> list[tuple[int, int]]: + """Overlapping or touching line spans joined, sorted.""" + out: list[tuple[int, int]] = [] + for first, last in sorted(spans): + if out and first <= out[-1][1] + 1: + out[-1] = (out[-1][0], max(out[-1][1], last)) + else: + out.append((first, last)) + return out + + +def _measured_note(based: int, cited: int, weak: int) -> str: + if based == cited == 1: + first = "Based on the finding's one evidence line" + elif based == cited: + first = f"Based on all {cited} of the finding's evidence lines" + else: + first = f"Based on {based} of the finding's {cited} evidence lines" + first += ", credited" if based == 1 else ", each credited" + first += ( + " to the last change that touched it, which is not always the change that first wrote it." + ) + second = "The AI share counts strong explicit markers only, so it is a lower bound" + if weak and based == 1: + second += "; the line has only a weak marker and is not counted in it." + elif weak == 1: + second += "; 1 of these lines has only a weak marker and is not counted in it." + elif weak: + second += f"; {weak} of these lines have only a weak marker and are not counted in it." + else: + second += "." + return f"{first} {second}" + + +def _no_origin_note(cited: int, evidence: Sequence[c.Evidence]) -> str: + if cited: + which = ( + "the finding's one evidence line has no recorded origin" + if cited == 1 + else f"none of the finding's {cited} evidence lines has a recorded origin" + ) + return ( + f"No line origin applies: {which}, and origin is recorded for production files at " + "END only. Both shares are 0." + ) + if evidence and all(record.kind == "commits" for record in evidence): + return ( + "No line origin applies: the finding's evidence is commits, not lines, so both " + "shares are 0." + ) + return "No line origin applies: the finding has no evidence lines at END, so both shares are 0." diff --git a/src/codexray/repository/__init__.py b/src/codexray/repository/__init__.py index 56491dd8..e6aa601b 100644 --- a/src/codexray/repository/__init__.py +++ b/src/codexray/repository/__init__.py @@ -26,7 +26,15 @@ - A run is complete when its `manifest.json` exists, is a valid manifest for the same END_SHA and `params_hash`, and the database file is there. The manifest is written last, so an interrupted run is never complete; the next run starts it again. -- `line_origin` and `prs` stay empty here (filled by later work). +- After the history pass and the snapshots, `ignore-revs.txt` is written to the run folder + and every production file at END is blamed with it (origin.write_line_origin). Each line + range is credited to its landed change (the first-parent commit that brought the blamed + commit into the mainline) and gets that change's era and AI label. +- Pull requests are fetched only for the changes in `structural_events`, up to the bound + in `prs` settings, from the configured host and only with a token + (origin.write_prs). They are cached in `pr-cache/` in the run folder, which the cleanup + of an interrupted run keeps, so a re-run needs no network. Without a token, on another + host or without network, `prs` is empty or partial and the run is still complete. """ from __future__ import annotations @@ -46,7 +54,7 @@ from codexray.core import contracts, db, runs from codexray.core.errors import CodeXrayError from codexray.core.runs import RunPaths -from codexray.repository import git, history, snapshots +from codexray.repository import git, history, origin, snapshots LANE = "repository" SPEC = "§5" @@ -207,7 +215,11 @@ def _row_counts(con: Any, repo: str) -> dict[str, int]: def _limits( - summary: history.HistorySummary, snap: snapshots.SnapshotSummary, pinned_by: str + summary: history.HistorySummary, + snap: snapshots.SnapshotSummary, + pinned_by: str, + lines: origin.LineOriginSummary, + pulls: origin.PrSummary, ) -> list[str]: out = [ f"END_SHA is {summary.end_sha}, taken from {pinned_by}; every table holds history up " @@ -246,9 +258,9 @@ def _limits( "and no comparison group, the before-and-after view describes and does not show " "cause.", "A file whose extension has no grammar gets history-only facts (no language).", - "Line-level origin and pull requests are not collected by this run: the line_origin " - "and prs tables are empty.", ] + out += lines.limits + out += pulls.limits return out @@ -300,6 +312,14 @@ def run(repo_url: str, repo_id: str, runs_dir: Path, settings: dict[str, Any]) - print("listing files at each snapshot", flush=True) snap = snapshots.write(con, clone_dir, repo, end_sha, settings) revs = history.ignore_revs(con, repo) + ignore_file = run_paths.root / IGNORE_REVS_FILE + runs.write_text_atomic(ignore_file, _ignore_revs_text(revs)) + print("blaming the production files at END", flush=True) + lines = origin.write_line_origin( + con, clone_dir, repo, end_sha, ignore_file, len(revs), settings + ) + print("reading pull requests", flush=True) + pulls = origin.write_prs(con, repo, repo_url, run_paths.root, settings) counts = _row_counts(con, repo) bots, strong = con.execute( "SELECT count(*) FILTER (WHERE is_bot), " @@ -311,7 +331,6 @@ def run(repo_url: str, repo_id: str, runs_dir: Path, settings: dict[str, Any]) - finally: con.close() - runs.write_text_atomic(run_paths.root / IGNORE_REVS_FILE, _ignore_revs_text(revs)) adoption = summary.adoption.as_dict() manifest = contracts.Manifest( repo_id=repo_id, @@ -341,9 +360,11 @@ def run(repo_url: str, repo_id: str, runs_dir: Path, settings: dict[str, Any]) - "adoption": adoption, "snapshots": snap.coverage(), "ignore_revs": {"file": IGNORE_REVS_FILE, "commits": len(revs)}, + "line_origin": lines.coverage(), + "prs": pulls.coverage(), "rows": counts, }, - limits=_limits(summary, snap, pinned_by), + limits=_limits(summary, snap, pinned_by, lines, pulls), ) runs.write_json(run_paths.manifest, contracts.to_plain(manifest)) runs.set_current(run_paths) @@ -361,6 +382,12 @@ def run(repo_url: str, repo_id: str, runs_dir: Path, settings: dict[str, Any]) - f"{end.line_count} lines", flush=True, ) + print( + f"line origin: {lines.files_blamed} files, {lines.ranges} ranges, {lines.lines} lines " + f"({lines.lines_left_out} left out)", + flush=True, + ) + print(f"pull requests: {pulls.asked} asked for, {pulls.stored} stored", flush=True) detected = adoption["detected_date"] or "none" print(f"adoption: sponsor date {adoption['sponsor_date']}, detected {detected}", flush=True) print(f"run written to {run_paths.root}", flush=True) diff --git a/src/codexray/repository/origin.py b/src/codexray/repository/origin.py new file mode 100644 index 00000000..560a9c3f --- /dev/null +++ b/src/codexray/repository/origin.py @@ -0,0 +1,472 @@ +"""The `line_origin` and `prs` tables of Stage 1 (spec.md §5.6, §5.7). + +`write_line_origin` blames every production file at END and credits each line to its +landed change: one first-parent commit is one landed change (spec.md §5.2), so a line last +touched by a side-branch commit is credited to the first-parent commit that brought that +commit into the mainline. The mapping comes from git's parent graph, read in one call. + +`write_prs` fetches the pull requests behind the changes in `structural_events` (the +changes the bonus labels, spec.md §12.3), cached in the run folder, so a re-run needs no +network. With no token, another host, or no network, the table is empty or partial and +the run is still complete; the summary says how many were asked for and stored. + +Both return a summary for the manifest. Neither holds clock time or local paths. +""" + +from __future__ import annotations + +import csv +import json +import os +import tempfile +from collections import Counter +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date, datetime +from pathlib import Path +from typing import Any +from urllib.parse import urlparse + +import duckdb + +from codexray.core.errors import CodeXrayError +from codexray.repository import git, line_origin, prs + +LINE_ORIGIN_COLUMNS = ( + ("repo", "VARCHAR"), + ("snapshot_sha", "VARCHAR"), + ("path", "VARCHAR"), + ("start_line", "INTEGER"), + ("end_line", "INTEGER"), + ("commit_sha", "VARCHAR"), + ("era", "VARCHAR"), + ("ai_label", "VARCHAR"), +) +PR_CACHE_DIR = "pr-cache" +SCOPE_STRUCTURAL = "structural_events" +SCOPE_NONE = "none" + + +# --- Bulk insert ------------------------------------------------------------------------- + + +def load_rows( + con: duckdb.DuckDBPyConnection, + table: str, + columns: Sequence[tuple[str, str]], + rows: Sequence[tuple], +) -> None: + """Bulk-insert rows through a temporary file: text quoted, numbers bare, None empty. + + The same as `load_rows` in the model stage. Kept here rather than imported, so this + stage does not depend on a later one, and a change to that copy cannot change what this + stage writes without changing this stage's source digest (and so its params_hash). + """ + if not rows: + return + names = ", ".join(name for name, _ in columns) + spec = ", ".join(f"'{name}': '{kind}'" for name, kind in columns) + with tempfile.TemporaryDirectory(prefix="codexray-repository-") as scratch: + path = Path(scratch) / f"{table}.csv" + with path.open("w", encoding="utf-8", newline="") as out: + csv.writer(out, quoting=csv.QUOTE_STRINGS, lineterminator="\n").writerows(rows) + con.execute( + f'INSERT INTO "{table}" ({names}) SELECT * FROM read_csv($1, header = false, ' + f"delim = ',', quote = '\"', escape = '\"', new_line = '\\n', auto_detect = false, " + f"strict_mode = true, allow_quoted_nulls = false, nullstr = '', " + f"columns = {{{spec}}})", + [str(path)], + ) + + +# --- Line origin ------------------------------------------------------------------------- + + +@dataclass +class LineOriginSummary: + """What `write_line_origin` did, for the manifest.""" + + files_blamed: int + files_without_lines: int # binary or empty: blame gives no line + files_line_count_mismatch: list[str] # blamed lines differ from snapshot_files.lines + ranges: int + lines: int + lines_by_era: dict[str, int] + lines_by_ai_label: dict[str, int] + blamed_commits: int + blamed_commits_on_mainline: int + blamed_commits_mapped: int # side-branch commits credited to their landed change + blamed_commits_unmapped: int + lines_left_out: int + sponsor_date: date + restructuring_commits_skipped: int + limits: list[str] = field(default_factory=list) + + def coverage(self) -> dict[str, Any]: + return { + "snapshot": "end", + "files_blamed": self.files_blamed, + "files_without_lines": self.files_without_lines, + "files_line_count_mismatch": self.files_line_count_mismatch, + "ranges": self.ranges, + "lines": self.lines, + "lines_by_era": self.lines_by_era, + "lines_by_ai_label": self.lines_by_ai_label, + "blamed_commits": self.blamed_commits, + "blamed_commits_on_mainline": self.blamed_commits_on_mainline, + "blamed_commits_mapped_to_landed_change": self.blamed_commits_mapped, + "blamed_commits_unmapped": self.blamed_commits_unmapped, + "lines_left_out": self.lines_left_out, + "era_boundary": f"{self.sponsor_date.isoformat()}T00:00:00Z", + "ignore_revs_commits": self.restructuring_commits_skipped, + } + + +def era_names(sponsor: date) -> tuple[str, str]: + """(before, after) labels for the sponsor date, such as `before_2025_03`.""" + suffix = f"{sponsor.year:04d}_{sponsor.month:02d}" + return f"before_{suffix}", f"after_{suffix}" + + +def landed_changes(clone_dir: Path, end_sha: str) -> dict[str, str]: + """Every commit reachable from END, mapped to the first-parent commit that brought it + into the mainline. A first-parent commit maps to itself. + + The mainline is walked oldest first. Each first-parent commit takes every commit + reachable through its other parents that no earlier mainline commit reaches, which is + exactly what its merge brought in. The result does not depend on the walk order inside + one merge, so two runs give the same map. + """ + out = git.run(clone_dir, ["rev-list", "--parents", git.require_sha(end_sha)]).stdout + parents: dict[str, list[str]] = {} + for line in out.decode("ascii").splitlines(): + ids = line.split() + if ids: + parents[ids[0]] = ids[1:] + if end_sha not in parents: + raise CodeXrayError(f"git rev-list did not list {end_sha}") + + mainline: list[str] = [] + current: str | None = end_sha + while current is not None: + mainline.append(current) + first = parents.get(current) or [] + current = first[0] if first else None + + landed: dict[str, str] = {} + for main in reversed(mainline): + landed[main] = main + stack = list(parents[main][1:]) + while stack: + commit = stack.pop() + if commit in landed: + continue + landed[commit] = main + stack.extend(parents.get(commit) or []) + return landed + + +def write_line_origin( + con: duckdb.DuckDBPyConnection, + clone_dir: Path, + repo: str, + end_sha: str, + ignore_revs_file: Path, + restructuring_commits: int, + settings: Mapping[str, Any], +) -> LineOriginSummary: + """Blame every production file at END and write `line_origin`, sorted by path and line. + + `ignore_revs_file` must already be written; it is passed to git as an absolute path, + because git runs inside the clone. Rows already stored for `repo` are replaced. + """ + repo_settings = settings["repository"] + workers = int(repo_settings["line_origin"]["workers"]) + sponsor = date.fromisoformat(str(repo_settings["ai_evidence"]["sponsor_date"])) + boundary = datetime(sponsor.year, sponsor.month, sponsor.day) + before, after = era_names(sponsor) + + files = con.execute( + "SELECT f.path, f.lines FROM snapshot_files f " + "JOIN snapshots s ON s.repo = f.repo AND s.snapshot_sha = f.snapshot_sha " + "WHERE f.repo = ? AND f.snapshot_sha = ? AND s.role = 'end' " + "AND f.path_class = 'production' AND f.lines IS NOT NULL ORDER BY f.path", + [repo, end_sha], + ).fetchall() + expected = {path: lines for path, lines in files} + commits = { + sha: (when, label) + for sha, when, label in con.execute( + "SELECT sha, committer_date, ai_label FROM commits WHERE repo = ?", [repo] + ).fetchall() + } + + blamed = line_origin.blame_files( + clone_dir, end_sha, sorted(expected), ignore_revs_file.resolve(), workers + ) + landed = landed_changes(clone_dir, end_sha) + + rows: list[tuple] = [] + blamed_lines: Counter[str] = Counter() + unmapped: set[str] = set() + left_out = 0 + for r in blamed: # sorted by (path, start_line) + size = r.end_line - r.start_line + 1 + blamed_lines[r.path] += size + change = landed.get(r.commit_sha) + if change is None or change not in commits: + unmapped.add(r.commit_sha) + left_out += size + continue + when, label = commits[change] + era = before if when < boundary else after + last = rows[-1] if rows else None + if last and last[2] == r.path and last[4] + 1 == r.start_line and last[5] == change: + rows[-1] = (*last[:4], r.end_line, *last[5:]) + continue + rows.append((repo, end_sha, r.path, r.start_line, r.end_line, change, era, label)) + + con.execute("BEGIN TRANSACTION") + try: + con.execute("DELETE FROM line_origin WHERE repo = ?", [repo]) + load_rows(con, "line_origin", LINE_ORIGIN_COLUMNS, rows) + con.execute("COMMIT") + except BaseException: + con.execute("ROLLBACK") + raise + + by_era: Counter[str] = Counter({before: 0, after: 0}) + by_label: Counter[str] = Counter() + for row in rows: + size = row[4] - row[3] + 1 + by_era[row[6]] += size + by_label[row[7]] += size + commit_ids = {r.commit_sha for r in blamed} + on_mainline = sum(1 for c in commit_ids if landed.get(c) == c and c in commits) + mismatch = sorted(p for p, n in expected.items() if blamed_lines.get(p, 0) != n) + summary = LineOriginSummary( + files_blamed=len(expected), + files_without_lines=sum(1 for p in expected if p not in blamed_lines), + files_line_count_mismatch=mismatch, + ranges=len(rows), + lines=sum(by_era.values()), + lines_by_era=dict(sorted(by_era.items())), + lines_by_ai_label=dict(sorted(by_label.items())), + blamed_commits=len(commit_ids), + blamed_commits_on_mainline=on_mainline, + blamed_commits_mapped=len(commit_ids) - on_mainline - len(unmapped), + blamed_commits_unmapped=len(unmapped), + lines_left_out=left_out, + sponsor_date=sponsor, + restructuring_commits_skipped=restructuring_commits, + ) + summary.limits = _line_origin_limits(summary) + return summary + + +def _line_origin_limits(s: LineOriginSummary) -> list[str]: + out = [ + "Line origin is the last change to touch each line of a production file at END " + f"(git blame, skipping the {s.restructuring_commits_skipped} planned-restructuring " + "commits in the ignore-revs file). That is not always the change that first wrote " + "the line.", + "A line last touched by a side-branch commit is credited to the first-parent commit " + f"that brought it into the mainline: {s.blamed_commits_mapped} of the " + f"{s.blamed_commits} blamed commits were credited this way.", + f"A line's era is before or after the sponsor date ({s.sponsor_date.isoformat()}, " + "00:00 UTC), by the committer date of its landed change; its AI label is that " + "change's label, and a change without an explicit marker is no AI signal.", + ] + if s.blamed_commits_unmapped: + out.append( + f"{s.blamed_commits_unmapped} blamed commits could not be credited to a landed " + f"change; their {s.lines_left_out} lines are left out of line_origin." + ) + if s.files_line_count_mismatch: + out.append( + f"For {len(s.files_line_count_mismatch)} files the blamed lines differ from the " + "line count in snapshot_files; they are listed in coverage.line_origin." + ) + return out + + +# --- Pull requests ----------------------------------------------------------------------- + + +@dataclass +class PrSummary: + """What `write_prs` did, for the manifest.""" + + scope: str + status: str # fetched | cache_only_no_token | host_not_supported | scope_none + candidates: int # numbers in scope, before the upper bound + max_fetched: int + asked: int + stored: int + unknown_to_host: int + not_fetched: int # refused, rate-limited, network failure, or no token + limits: list[str] = field(default_factory=list) + + def coverage(self) -> dict[str, Any]: + return { + "scope": self.scope, + "status": self.status, + "candidates": self.candidates, + "max_fetched": self.max_fetched, + "left_out_by_upper_bound": max(0, self.candidates - self.max_fetched), + "asked": self.asked, + "stored": self.stored, + "unknown_to_host": self.unknown_to_host, + "not_fetched": self.not_fetched, + "cache": PR_CACHE_DIR, + } + + +def url_host(repo_url: str) -> str | None: + """The host of a repository URL (`scheme://host/...` or `user@host:path`), lower case; + None for a local folder.""" + if "://" in repo_url: + return (urlparse(repo_url).hostname or "").lower() or None + if Path(repo_url).exists(): + return None + head, sep, _ = repo_url.partition(":") + if not sep: + return None + return head.rsplit("@", 1)[-1].lower() or None + + +def _footer_patterns(settings: Mapping[str, Any], groups: Sequence[str]) -> list[str]: + rules = settings.get("labels") or {} + strong = rules.get("strong_markers") or {} + return [entry["pattern"] for group in groups for entry in strong.get(group) or []] + + +def _offline(url: str, headers: dict) -> tuple[int, Any]: + """A fetch that never reaches the host, so only cached pull requests are read.""" + raise OSError("fetching is off for this run") + + +def write_prs( + con: duckdb.DuckDBPyConnection, + repo: str, + repo_url: str, + run_root: Path, + settings: Mapping[str, Any], +) -> PrSummary: + """Fetch (or read from the run's cache) the pull requests in scope and write `prs`.""" + config = settings["repository"]["prs"] + scope = str(config["scope"]) + max_fetched = int(config["max_fetched"]) + if scope not in (SCOPE_STRUCTURAL, SCOPE_NONE): + raise CodeXrayError( + f"settings repository.prs.scope is '{scope}'; use '{SCOPE_STRUCTURAL}' or " + f"'{SCOPE_NONE}'" + ) + + numbers: list[int] = [] + if scope == SCOPE_STRUCTURAL: + numbers = [ + row[0] + for row in con.execute( + "SELECT DISTINCT c.pr_number FROM structural_events s " + "JOIN commits c ON c.repo = s.repo AND c.sha = s.sha " + "WHERE s.repo = ? AND c.pr_number IS NOT NULL ORDER BY 1", + [repo], + ).fetchall() + ] + asked = numbers[:max_fetched] + + host = str(config["host"]).lower() + token = (os.environ.get(str(config["token_env"])) or "").strip() or None + if scope == SCOPE_NONE: + status = "scope_none" + elif url_host(repo_url) != host: + status = "host_not_supported" + else: + status = "fetched" if token else "cache_only_no_token" + if status in ("scope_none", "host_not_supported"): + asked = [] + + found: list[prs.PullRequest] = [] + cache_dir = run_root / PR_CACHE_DIR + if asked: + found = prs.fetch_prs( + repo, + asked, + cache_dir, + token=token, + footer_patterns=_footer_patterns(settings, config["footer_marker_groups"]), + fetch=None if token else _offline, + ) + unknown = sum(1 for n in asked if _cached_missing(cache_dir / f"{n}.json")) + rows = [ + (repo, p.number, p.title, p.description, p.linked_issues, p.review_count, p.checks, + p.ai_footer) + for p in sorted(found, key=lambda p: p.number) + ] # fmt: skip + + con.execute("BEGIN TRANSACTION") + try: + con.execute("DELETE FROM prs WHERE repo = ?", [repo]) + if rows: + con.executemany( + "INSERT INTO prs (repo, pr_number, title, description, linked_issues, " + "review_count, checks, ai_footer) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + rows, + ) + con.execute("COMMIT") + except BaseException: + con.execute("ROLLBACK") + raise + + summary = PrSummary( + scope=scope, + status=status, + candidates=len(numbers), + max_fetched=max_fetched, + asked=len(asked), + stored=len(rows), + unknown_to_host=unknown, + not_fetched=len(asked) - len(rows) - unknown, + ) + summary.limits = _pr_limits(summary) + return summary + + +def _cached_missing(path: Path) -> bool: + """True when the cache holds this number as unknown to the host (see prs.py).""" + if not path.is_file(): + return False + return bool(json.loads(path.read_text(encoding="utf-8")).get("missing")) + + +def _pr_limits(s: PrSummary) -> list[str]: + if s.status == "scope_none": + return ["Pull requests are not fetched (settings: repository.prs.scope is none)."] + if s.status == "host_not_supported": + return [ + "Pull requests are not fetched: the repository is not on the host the fetcher " + "supports (settings: repository.prs.host). The prs table is empty." + ] + out = [ + "Pull requests are fetched only for the landed changes in structural_events that " + f"carry a pull-request number ({s.candidates}), at most {s.max_fetched}: one pull " + "request costs three or more host requests, so fetching every pull request does not " + f"fit the host's rate limit. {s.asked} were asked for and {s.stored} stored." + ] + if s.candidates > s.asked: + out.append( + f"{s.candidates - s.asked} pull requests in scope were not asked for because of " + "the upper bound (settings: repository.prs.max_fetched); the lowest numbers " + "were kept." + ) + if s.unknown_to_host: + out.append(f"{s.unknown_to_host} pull-request numbers are unknown to the host.") + if s.not_fetched: + why = ( + "no token was set, so only cached pull requests were read" + if s.status == "cache_only_no_token" + else "the host refused or rate-limited the requests, or the network failed" + ) + out.append(f"{s.not_fetched} pull requests are missing: {why}.") + return out diff --git a/src/codexray/settings/report.yaml b/src/codexray/settings/report.yaml index 14b160d3..136dd022 100644 --- a/src/codexray/settings/report.yaml +++ b/src/codexray/settings/report.yaml @@ -61,6 +61,45 @@ bundle: decisions_slipping: "decisions" decisions_broken: "decisions" +# The before-and-after view and its labels (spec.md §12.3). Every value here is initial +# and will be tuned on all three repositories. +before_after: + # "Most" of something starts at this share. A layout change is a reorganisation when at + # least this share of its change disappears under the older layout; a new module is + # moved code when at least this share of its files existed at the snapshot before; a + # new link is expected when at least this share of its link lines join two files that + # both existed at the sponsor date and, under that date's layout, were already linked + # or in one module. Link lines in files that did not exist then count against. + most_share: 0.5 + # A measure that moves by at most this share of its older value has not changed, so it + # cannot show a reorganisation. From an older value of 0, any move counts as a change. + min_change_share: 0.05 + # A commit moved code between modules when at least this many of the files it renamed + # sit in a different module at the next snapshot than at the one before. + min_files_moved: 10 + # A planned-restructuring commit explains a module or a link when it changed at least + # this share of the module's files, or of the files the link lines are written in. + min_changed_share: 0.5 + # Decision documents: files at END whose path matches one of these globs (`*` crosses + # folders), dated by the commit that added them. + decision_documents: + - "adr/*.md" + - "*/adr/*.md" + - "adrs/*.md" + - "*/adrs/*.md" + - "decisions/*.md" + - "*/decisions/*.md" + - "decision-records/*.md" + - "*/decision-records/*.md" + # A document names a commit by its pull-request number written as #, or by at + # least this many leading characters of the commit id. + commit_id_chars: 10 + # Link changes listed per kind (added, removed), the most link lines first. The totals + # by kind and label are stated in the report's limits. + max_link_changes: 25 + # Evidence lines shown per link change. + max_link_evidence: 3 + post_processing: merge_when_shared_nodes_at_least: 0.5 top_n: 10 diff --git a/src/codexray/settings/repository.yaml b/src/codexray/settings/repository.yaml index 610d7cd5..292b50c6 100644 --- a/src/codexray/settings/repository.yaml +++ b/src/codexray/settings/repository.yaml @@ -59,6 +59,33 @@ snapshots: # for in this many first lines of each file. header_marker_lines: 10 +line_origin: + # Parallel `git blame` processes over the production files at END (spec.md §5.6). Does + # not change what is written. Measured on Artemis (8,954 files, 1.03 million lines, on a + # 10-core machine): 104 s with 8 workers, 164 s with 4. + workers: 8 + +prs: + # Pull requests are fetched from this host's API only when the repository URL is on this + # host. Any other host, or a local folder, gives an empty `prs` table and a complete run. + host: "github.com" + # The token is read from this environment variable; it is never written or logged. + # Without it nothing is fetched (pull requests already in the run's cache are read): + # the limit without a token is 60 requests an hour, about 20 pull requests. + token_env: "GITHUB_TOKEN" + # Which pull requests to fetch. One pull request costs three or more host requests, and + # these repositories have 6,000 to 13,600 landed changes with a pull-request number, so + # fetching all of them does not fit the host's rate limit. + # structural_events only those behind the commits in `structural_events`, the + # changes the bonus labels as planned or not (spec.md §12.3) + # none fetch nothing + scope: structural_events + # At most this many pull requests are asked for; above it the lowest numbers are kept. + max_fetched: 200 + # A description line is an AI footer when it matches a pattern in these groups of + # `strong_markers` in labels.yaml (co-author lines and agent trailers). + footer_marker_groups: ["coauthors", "trailers"] + run: # Installed packages whose versions can change what Stage 1 or Stage 2 writes. Their # versions go into params_hash and the manifest, with git's version, this package's