From 5eaf1d0887ac68870449f5b004f7940501eb5abc Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 19 Sep 2026 17:37:20 +1000 Subject: [PATCH] feat(tools): surface half-wired symbols inside shipped packages in reachaudit reachaudit classified whole unreachable packages but explicitly skipped findings inside packages already in the cmd closure ("reported separately as live-package findings" -- never implemented). That's the more common half-built-feature shape: the package ships, one symbol at its call site doesn't (crondelivery.ChatCourier, eda/playbook.Store.Dispatch, gatewayrpc.StoreClient). Add a second in-package-* report section using the same tracked/untracked/dynamic classification. Also wires the --md flag, which was accepted but never written. --- Taskfile.yml | 15 ++++- tools/reachaudit/reachaudit.py | 110 +++++++++++++++++++++++---------- 2 files changed, 89 insertions(+), 36 deletions(-) diff --git a/Taskfile.yml b/Taskfile.yml index f6497f410..1fb93c58f 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -124,9 +124,20 @@ tasks: is a known gap, a forgotten one, or an artifact of runtime loading (yaegi, reflection) that must never be deleted. + Two report sections, because a dead whole package and a dead symbol + inside a live one are different failure modes: "unreachable-*" is a + package no shipped binary imports at all; "in-package-*" is a symbol + dead inside a package that IS shipped -- the ChatCourier/Dispatch + shape, where the feature is wired everywhere except its own call site. + Both carry the same tracked/untracked/dynamic classification. + --refresh re-runs the analysis. Without it the tool reuses - /tmp/reachaudit-deadcode.txt with no staleness check, which will - happily report last week's tree against today's code. + /tmp/reachaudit-deadcode-.txt with no staleness check beyond HEAD + and a dirty-tree check, which will happily report last week's tree + against today's code if HEAD hasn't moved. + + --json PATH and --md PATH write the same findings as structured data or + a Markdown report, in addition to the terminal summary. cmds: - python3 tools/reachaudit/reachaudit.py --repo . {{.CLI_ARGS}} docs:site: diff --git a/tools/reachaudit/reachaudit.py b/tools/reachaudit/reachaudit.py index 222df0c08..01f3cdd40 100755 --- a/tools/reachaudit/reachaudit.py +++ b/tools/reachaudit/reachaudit.py @@ -97,11 +97,7 @@ def dynamic_packages(repo: Path) -> set[str]: """Packages that reference runtime-loaded code.""" out = run(["grep", "-rl", "-E", "|".join(DYNAMIC_MARKERS), "--include=*.go", "internal/", "cmd/"], repo) - pkgs = set() - for f in out.splitlines(): - p = f.rsplit("/", 1)[0] if Path(f).name != f else f - pkgs.add(f.rsplit("/", 1)[0] if "/" in f else f) - return pkgs + return {f.rsplit("/", 1)[0] if "/" in f else f for f in out.splitlines()} def tracked_terms(short_pkg: str) -> list[str]: @@ -138,6 +134,21 @@ def consumers(repo: Path, pkg: str) -> tuple[int, int]: return len(nt), len(files) - len(nt) +def classify(repo: Path, pkg: str, titles: list[str], dyn: set[str]) -> tuple[str, list[str]]: + """Shared classification: tracked / untracked / dynamic, plus the tracker + titles that matched. Used for both whole-package and in-package findings + so a symbol inside a live package is judged by the same evidence as a + whole dead one.""" + terms = tracked_terms(pkg) + hits = [t for t in titles if any(term.lower() in t.lower() for term in terms)] + is_dynamic = any(pkg.startswith(d) or d.startswith(pkg) for d in dyn) + if is_dynamic: + return "dynamic", hits + if hits: + return "tracked", hits + return "untracked", hits + + def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--repo", default=str(Path(__file__).resolve().parents[2])) @@ -158,60 +169,91 @@ def main() -> int: titles = open_tracker_titles(repo) dyn = dynamic_packages(repo) - by_pkg: dict[str, int] = defaultdict(int) + by_pkg_syms: dict[str, list[str]] = defaultdict(list) for line in findings: - m = re.match(r"^(.+?):\d+:\d+: unreachable func:", line) + m = re.match(r"^(.+?):\d+:\d+: unreachable func: (.+)$", line) if m: - by_pkg[str(Path(m.group(1)).parent)] += 1 - if not by_pkg: + by_pkg_syms[str(Path(m.group(1)).parent)].append(m.group(2)) + if not by_pkg_syms: print("WARNING: no findings parsed; deadcode output format may have changed", file=sys.stderr) + # Whole packages absent from the cmd closure: the package cannot execute + # at all, whatever deadcode says about individual functions inside it. rows = [] - for pkg, n in sorted(by_pkg.items(), key=lambda kv: -kv[1]): - in_closure = pkg in closure - if in_closure: - continue # reported separately as live-package findings - terms = tracked_terms(pkg) - hits = [t for t in titles if any(term.lower() in t.lower() for term in terms)] + for pkg, syms in sorted(by_pkg_syms.items(), key=lambda kv: -len(kv[1])): + if pkg in closure: + continue + category, hits = classify(repo, pkg, titles, dyn) nt, tt = consumers(repo, pkg) - is_dynamic = any(pkg.startswith(d) or d.startswith(pkg) for d in dyn) - if is_dynamic: - category = "unreachable-dynamic" - elif hits: - category = "unreachable-tracked" - else: - category = "unreachable-untracked" rows.append({ - "package": pkg, "findings": n, "loc": loc(repo, pkg), - "category": category, + "package": pkg, "findings": len(syms), "loc": loc(repo, pkg), + "category": f"unreachable-{category}", "non_test_importers": nt, "test_importers": tt, "tracker_hits": hits[:3], **provenance(repo, pkg), }) + # Functions unreachable INSIDE a package that IS in the closure: the + # package ships, but this symbol is the unwired tail of a feature -- + # the ChatCourier/Dispatch shape, not a dead whole package. This is the + # half-built-feature case the whole-package report structurally cannot + # see, since the package itself looks perfectly live. + in_pkg_rows = [] + for pkg, syms in sorted(by_pkg_syms.items(), key=lambda kv: -len(kv[1])): + if pkg not in closure: + continue + category, hits = classify(repo, pkg, titles, dyn) + in_pkg_rows.append({ + "package": pkg, "symbols": sorted(syms), + "category": f"in-package-{category}", + "tracker_hits": hits[:3], + }) + order = {"unreachable-untracked": 0, "unreachable-dynamic": 1, "unreachable-tracked": 2} rows.sort(key=lambda r: (order.get(r["category"], 9), -r["loc"])) + in_pkg_order = {"in-package-untracked": 0, "in-package-dynamic": 1, "in-package-tracked": 2} + in_pkg_rows.sort(key=lambda r: (in_pkg_order.get(r["category"], 9), -len(r["symbols"]))) - print(f"packages reachable from shipped binaries: {len(closure)}") - print(f"deadcode findings total: {len(findings)}") - print(f"unreachable packages: {len(rows)}") total = sum(r["loc"] for r in rows) - print(f"unreachable LOC: {total}") - print() + lines = [] + lines.append(f"packages reachable from shipped binaries: {len(closure)}") + lines.append(f"deadcode findings total: {len(findings)}") + lines.append(f"unreachable packages: {len(rows)}") + lines.append(f"unreachable LOC: {total}") + lines.append("") for cat in ("unreachable-untracked", "unreachable-dynamic", "unreachable-tracked"): group = [r for r in rows if r["category"] == cat] if not group: continue - print(f"== {cat} ({len(group)}) ==") + lines.append(f"== {cat} ({len(group)}) ==") for r in group: tr = "; ".join(r["tracker_hits"]) or "NONE" - print(f" {r['loc']:>6} LOC {r['package']:<48} {tr[:56]}") - print() + lines.append(f" {r['loc']:>6} LOC {r['package']:<48} {tr[:56]}") + lines.append("") + for cat in ("in-package-untracked", "in-package-dynamic", "in-package-tracked"): + group = [r for r in in_pkg_rows if r["category"] == cat] + if not group: + continue + lines.append(f"== {cat} ({len(group)}) -- package ships, these symbols do not ==") + for r in group: + tr = "; ".join(r["tracker_hits"]) or "NONE" + lines.append(f" {r['package']} ({tr})") + for sym in r["symbols"]: + lines.append(f" {sym}") + lines.append("") + print("\n".join(lines)) if args.json: - Path(args.json).write_text(json.dumps({"rows": rows, "total_loc": total, - "closure_size": len(closure)}, indent=2)) + Path(args.json).write_text(json.dumps({ + "rows": rows, "in_package_rows": in_pkg_rows, + "total_loc": total, "closure_size": len(closure), + }, indent=2)) print(f"wrote {args.json}") + + if args.md: + md = ["# reachaudit", "", "```", *lines, "```", ""] + Path(args.md).write_text("\n".join(md)) + print(f"wrote {args.md}") return 0