Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions scripts/make_fixture_bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
220 changes: 220 additions & 0 deletions src/codexray/analyze/drift.py
Original file line number Diff line number Diff line change
@@ -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
28 changes: 19 additions & 9 deletions src/codexray/report/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<blob_sha>.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=<id>` copies it into the web app.
"""
Expand All @@ -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"
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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()
Expand All @@ -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()}
Expand Down Expand Up @@ -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)
14 changes: 7 additions & 7 deletions src/codexray/report/assemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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
Expand Down
Loading