In this section
- Units storage · cosmic / tools/explore/clean/units.py lines 1–403
Units
A Python command-line tool in the clean folder of Cosmic that reads unit shares, using SHA-256. It makes key (`make_key`), parses key (`parse_key`) and loads rules (`load_rules`).
storagecosmic / tools/explore/clean/units.py · lines 1–403 of 403 · Entry point · pattern cluster_units (shared by 2 files)
- What it does
- It loads unit shares. Defines 23 functions or classes, including make_key, parse_key, est_jaccard, UnionFind, __init__. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file units.json; JSON file unit-shares.json; command-line arguments.
- Downstream impact
- Used directly by 3 files: CI (cosmic); Test Apply (cosmic); Test Units (cosmic). Reached from 1 other entry point, including Test CI (cosmic).
- What it achieves
- Propose function-level duplicates for Explore Code cleaning (clean-proposals-v1). It accepts `--graph`, `--units` and `--src`.
- Why it matters
- Run by CI. Checked by 2 tests, including Test Apply.
- Application
- cosmic · tools/explore/clean · Python CLI
- Uses
- __future__, argparse, hashlib, json, os, sys, collections, pathlib
- Used by
- run by CI (script call), run by Test Apply (script call), imported by Test Units (import)
- Produces
- make_key, parse_key, est_jaccard, UnionFind, load_rules, load_units, TextSource, select_units, cluster_units, canonical_rank, relation, run
- Defines here
- make_key, parse_key, est_jaccard, UnionFind, __init__, find, union, load_rules, load_units, TextSource, __init__, lines, text, select_units, cluster_units, canonical_rank, relation, run, file_jaccard, covered, sha256_file, write_json, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/clean/units.py:1-403 · blob 8f478c9e01a3d102d112de0fe4e5285600d3e590 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""units.py: propose function-level duplicates for Explore Code cleaning (clean-proposals-v1).
Proposals only. Nothing is deleted or rewritten anywhere. This script reads the build graph and the VEDIC
fingerprint units and writes two JSON files.
Inputs (all read-only):
--graph build_graph.json (schema explore-build-graph-v1): file ids, repo commits, canonical_status, reachable
--units units.parquet from vedic-/fingerprints/extract.py (schema vedic-fingerprint-units-v1): one row per
function, method or class, with exact_hash, struct_hash and a 64-value MinHash
--src folder of clones (optional): used only to check whether two units are byte-identical
--rules vedic-/fingerprints/rules.json (optional): cluster.min_tokens, near_jaccard, lsh_bands, lsh_rows,
lsh_max_bucket. Built-in defaults equal rules v6.
Outputs:
--out clean-proposals-v1 (clean/CONTRACT.md): one `unit-duplicate-of <target key>` record per duplicated
unit, with file id, line range and the key of the canonical unit that stays
--shares clean-unit-shares-v1: for every build-graph file, the share of its lines that duplicate a function
kept elsewhere (display only)
Method:
1. Keep units whose (repo, path) is a build-graph file, with at least min_tokens tokens and a declared name.
2. Group units by struct_hash. Struct groups whose representative MinHash signatures are at least near_jaccard
alike (LSH bands, each pair verified) join one cluster (union-find). Clusters inside a single file are dropped.
3. In each cluster one canonical unit stays. It is the best by: canonical_status (production_core, supporting_data,
unknown, unreached_review, duplicate_candidate), then core repository, then reachable, then entry, then the
smallest key. Every unit in another file is proposed as a duplicate of it.
4. Confidence comes from how the unit relates to the canonical: 1.0 byte-identical text; 0.9 equal exact_hash
(identical apart from whitespace and comments); 0.55 equal struct_hash (same shape, different names or
literals); 0.4 near (estimated Jaccard >= near_jaccard). With apply.py's default --min-confidence of 0.6, a
structure-only or near match can never set a file aside, even when the unit covers the whole file.
5. "Otherwise different" files only. A pair of files whose unit exact_hash sets have Jaccard >= --near-copy-files
(default 0.8) is a whole-file near copy, which families.py handles, so its units are not proposed here. Such
pairs are still counted.
6. Nested units: when a unit lies inside another unit proposed in the same file, only the outer one is kept.
7. Share per file = union of the kept proposed line ranges / file lines (also given for confidence >= 0.9 only).
Key (clean/CONTRACT.md section 1): `<repo>@<commit> <path>:<first>-<last> <blob>`.
Run:
python tools/explore/clean/units.py --graph /tmp/site7/explore-code/build_graph.json \
--units /tmp/vk/12/out/units.parquet --src /home/claude/src \
--rules /home/claude/vedic-/fingerprints/rules.json
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from collections import defaultdict
from pathlib import Path
PROPOSER = "units.py"
SCHEMA = "clean-proposals-v1"
SHARES_SCHEMA = "clean-unit-shares-v1"
STATUS_RANK = {"production_core": 0, "supporting_data": 1, "unknown": 2, "unreached_review": 3,
"duplicate_candidate": 4}
DEFAULT_RULES = {"min_tokens": 25, "near_jaccard": 0.8, "lsh_bands": 16, "lsh_rows": 4, "lsh_max_bucket": 400}
CONF = {"byte-identical": 1.0, "exact": 0.9, "struct": 0.55, "near": 0.4}
RELATION_TEXT = {
"byte-identical": "is byte-for-byte the same code as",
"exact": "is the same code, apart from spacing and comments, as",
"struct": "has the same structure, with different names or values, as",
"near": "is a close variant of",
}
UNIT_COLUMNS = ["unit_id", "repo", "commit", "path", "blob", "kind", "name", "line_from", "line_to",
"n_tokens", "exact_hash", "struct_hash", "minhash"]
# ---------------------------------------------------------------- small helpers
def make_key(repo, commit, path, first, last, blob):
return f"{repo}@{commit} {path}:{first}-{last} {blob or '-'}"
def parse_key(key):
"""Split a key per CONTRACT.md: first '@', first space after it, last ':' and last space."""
repo, rest = key.split("@", 1)
commit, rest = rest.split(" ", 1)
body, blob = rest.rsplit(" ", 1)
path, rng = body.rsplit(":", 1)
first, last = rng.split("-", 1)
return {"repo": repo, "commit": commit, "path": path, "first": int(first), "last": int(last), "blob": blob}
def est_jaccard(a, b):
return sum(1 for x, y in zip(a, b) if x == y) / max(len(a), 1)
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
def find(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]
x = self.p[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.p[max(ra, rb)] = min(ra, rb)
def load_rules(path):
rules = dict(DEFAULT_RULES)
if path:
cl = json.loads(Path(path).read_text(encoding="utf-8")).get("cluster", {})
for k in DEFAULT_RULES:
if k in cl:
rules[k] = cl[k]
return rules
def load_units(path):
import pyarrow.parquet as pq
return pq.read_table(path, columns=UNIT_COLUMNS).to_pylist()
class TextSource:
"""Reads unit text from the clones for the byte-identical check; returns None when unavailable."""
def __init__(self, src):
self.src = Path(src) if src else None
self.cache = {}
def lines(self, repo, path):
if self.src is None:
return None
k = (repo, path)
if k not in self.cache:
try:
self.cache[k] = (self.src / repo / path).read_bytes().split(b"\n")
except OSError:
self.cache[k] = None
return self.cache[k]
def text(self, u):
ls = self.lines(u["repo"], u["path"])
if ls is None or u["line_to"] > len(ls):
return None
return b"\n".join(ls[u["line_from"] - 1:u["line_to"]])
# ---------------------------------------------------------------- core
def select_units(graph, units, rules):
files = {(f["repo"], f["path"]): f for f in graph["files"]}
commits = {r["repo"]: r["commit"] for r in graph["repos"]}
kept, dropped = [], defaultdict(int)
for u in units:
f = files.get((u["repo"], u["path"]))
if f is None:
dropped["not_in_build_graph"] += 1
continue
if commits.get(u["repo"]) and u["commit"] != commits[u["repo"]]:
dropped["commit_differs_from_graph"] += 1
continue
if (u["n_tokens"] or 0) < rules["min_tokens"]:
dropped["below_min_tokens"] += 1
continue
if not u["name"] or u["name"] == "<anonymous>":
dropped["anonymous"] += 1
continue
u = dict(u)
u["file_id"] = f["id"]
u["key"] = make_key(u["repo"], u["commit"], u["path"], u["line_from"], u["line_to"], u["blob"])
kept.append(u)
kept.sort(key=lambda x: x["key"])
return kept, dict(dropped)
def cluster_units(units, rules):
"""Struct groups, merged by verified MinHash LSH. Returns a list of clusters (lists of units)."""
groups = defaultdict(list)
for u in units:
groups[u["struct_hash"]].append(u)
hashes = sorted(groups)
reps = [groups[h][0]["minhash"] for h in hashes]
uf = UnionFind(len(hashes))
bands, rows, cap = rules["lsh_bands"], rules["lsh_rows"], rules["lsh_max_bucket"]
for b in range(bands):
buckets = defaultdict(list)
for i, mh in enumerate(reps):
if mh is None or len(mh) < (b + 1) * rows:
continue
buckets[tuple(mh[b * rows:(b + 1) * rows])].append(i)
for members in buckets.values():
if len(members) < 2:
continue
pairs = ([(members[0], m) for m in members[1:]] if len(members) > cap
else [(a, c) for k, a in enumerate(members) for c in members[k + 1:]])
for a, c in pairs:
if uf.find(a) != uf.find(c) and est_jaccard(reps[a], reps[c]) >= rules["near_jaccard"]:
uf.union(a, c)
comps = defaultdict(list)
for i, h in enumerate(hashes):
comps[uf.find(i)].extend(groups[h])
clusters = [sorted(c, key=lambda x: x["key"]) for c in comps.values()
if len({u["file_id"] for u in c}) >= 2]
clusters.sort(key=lambda c: c[0]["key"])
return clusters
def canonical_rank(u, fmeta, core):
f = fmeta[u["file_id"]]
return (STATUS_RANK.get(f.get("canonical_status"), 9), 0 if u["repo"] in core else 1,
0 if f.get("reachable") else 1, 0 if f.get("entry") else 1, u["key"])
def relation(u, c, text, rules):
if u["exact_hash"] == c["exact_hash"]:
tu, tc = text.text(u), text.text(c)
if tu is not None and tu == tc:
return "byte-identical", None
return "exact", None
if u["struct_hash"] == c["struct_hash"]:
return "struct", None
j = est_jaccard(u["minhash"], c["minhash"])
return ("near", j) if j >= rules["near_jaccard"] else (None, j)
def run(graph, units, rules, src=None, near_copy_files=0.8):
fmeta = {f["id"]: f for f in graph["files"]}
core = {r["repo"] for r in graph["repos"] if r.get("core")}
text = TextSource(src)
sel, dropped = select_units(graph, units, rules)
file_exact = defaultdict(set)
for u in sel:
file_exact[u["file_id"]].add(u["exact_hash"])
def file_jaccard(a, b):
sa, sb = file_exact[a], file_exact[b]
return len(sa & sb) / max(len(sa | sb), 1)
clusters = cluster_units(sel, rules)
raw, stats = [], defaultdict(int)
near_copy_pairs = set()
cluster_info = []
for ci, cl in enumerate(clusters):
canon = min(cl, key=lambda u: canonical_rank(u, fmeta, core))
f = fmeta[canon["file_id"]]
why = [f"canonical_status {f.get('canonical_status')}",
"core repository" if canon["repo"] in core else "not a core repository",
"reachable" if f.get("reachable") else "not reached"]
n_files = len({u["file_id"] for u in cl})
n_repos = len({u["repo"] for u in cl})
members = 0
for u in cl:
if u["file_id"] == canon["file_id"]:
continue
rel, j = relation(u, canon, text, rules)
if rel is None:
stats["near_below_threshold_to_canonical"] += 1
continue
fj = file_jaccard(u["file_id"], canon["file_id"])
if fj >= near_copy_files:
near_copy_pairs.add(tuple(sorted((u["file_id"], canon["file_id"]))))
stats["skipped_whole_file_near_copy"] += 1
continue
ev = [f"{'exact_hash' if rel in ('byte-identical', 'exact') else 'struct_hash' if rel == 'struct' else 'MinHash'}"
f" {'equal: ' + (u['exact_hash'] if rel in ('byte-identical', 'exact') else u['struct_hash'])[:16] if rel != 'near' else 'estimated Jaccard ' + format(j, '.3f') + ' of 64 values'}"
f" (target {canon['key']})"]
if rel == "byte-identical":
ev.append("unit text byte-identical to the target's lines in the clone")
ev.append(f"cluster of {len(cl)} units in {n_files} files across {n_repos} repositories")
ev.append(f"files otherwise different: unit exact_hash Jaccard between the two files {fj:.2f} "
f"(< {near_copy_files})")
ev.append("target chosen by " + ", ".join(why))
first, last = u["line_from"], u["line_to"]
whole = first == 1 and last == (fmeta[u["file_id"]].get("lines") or -1)
reason = (f"The {u['kind']} `{u['name']}` (lines {first}-{last}) {RELATION_TEXT[rel]} "
f"`{canon['name']}` kept in {canon['repo']} {canon['path']} "
f"(lines {canon['line_from']}-{canon['line_to']})"
+ ("; it is the whole file." if whole else "; the rest of this file is different."))
raw.append({
"file_id": u["file_id"], "key": u["key"], "category": f"unit-duplicate-of {canon['key']}",
"reason": reason, "evidence": ev, "confidence": CONF[rel], "proposer": PROPOSER,
"unit_name": u["name"], "unit_kind": u["kind"], "relation": rel,
"target_file_id": canon["file_id"], "target_name": canon["name"], "cluster": ci,
"covers_whole_file": whole,
"_lines": (first, last),
})
members += 1
cluster_info.append({"cluster": ci, "canonical": canon, "units": len(cl), "files": n_files,
"repos": n_repos, "proposed": 0})
# nested units: keep the outermost proposal in each file
by_file = defaultdict(list)
for r in raw:
by_file[r["file_id"]].append(r)
records = []
for fid in sorted(by_file):
kept = []
for r in sorted(by_file[fid], key=lambda r: (r["_lines"][0], -r["_lines"][1], r["key"])):
if any(k["_lines"][0] <= r["_lines"][0] and r["_lines"][1] <= k["_lines"][1] for k in kept):
stats["nested_dropped"] += 1
continue
kept.append(r)
records.extend(kept)
for r in records:
cluster_info[r["cluster"]]["proposed"] += 1
shares = []
for f in sorted(graph["files"], key=lambda f: f["id"]):
rs = [r for r in by_file.get(f["id"], []) if r in records] if f["id"] in by_file else []
lines = f.get("lines") or 0
def covered(min_conf):
spans = sorted(r["_lines"] for r in rs if r["confidence"] >= min_conf)
total, end = 0, 0
for a, b in spans:
a = max(a, end + 1)
if b >= a:
total += b - a + 1
end = b
return min(total, lines) if lines else total
dup, dup_exact = covered(0.0), covered(0.9)
shares.append({"file_id": f["id"], "repo": f["repo"], "path": f["path"], "lines": lines,
"duplicated_lines": dup, "share": round(dup / lines, 4) if lines else 0.0,
"duplicated_lines_exact": dup_exact,
"share_exact": round(dup_exact / lines, 4) if lines else 0.0,
"units": len(rs)})
for r in records:
del r["_lines"]
records.sort(key=lambda r: (r["file_id"], r["key"]))
top = sorted((c for c in cluster_info if c["proposed"]),
key=lambda c: (-c["files"], -c["proposed"], c["canonical"]["key"]))[:10]
by_rel = defaultdict(int)
for r in records:
by_rel[r["relation"]] += 1
counts = {
"units_read": len(units), "units_considered": len(sel), "units_dropped": dropped,
"clusters_multi_file": len(clusters), "clusters_with_proposals": sum(1 for c in cluster_info if c["proposed"]),
"proposals": len(records), "by_relation": dict(sorted(by_rel.items())),
"proposals_confidence_ge_0_6": sum(1 for r in records if r["confidence"] >= 0.6),
"whole_file_proposals": sum(1 for r in records if r["covers_whole_file"]),
"whole_file_proposals_confidence_ge_0_6": sum(1 for r in records if r["covers_whole_file"]
and r["confidence"] >= 0.6),
"files_with_proposals": len({r["file_id"] for r in records}),
"files_share_ge_0_5": sum(1 for s in shares if s["share"] >= 0.5),
"duplicated_lines": sum(s["duplicated_lines"] for s in shares),
"skipped_whole_file_near_copy_pairs": len(near_copy_pairs),
**{k: v for k, v in sorted(stats.items())},
}
top_out = [{"name": c["canonical"]["name"], "files": c["files"], "repos": c["repos"], "units": c["units"],
"proposed": c["proposed"], "canonical_key": c["canonical"]["key"]} for c in top]
return records, shares, counts, top_out
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def write_json(path, obj):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
os.replace(tmp, path)
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--graph", required=True, type=Path)
ap.add_argument("--units", required=True, type=Path)
ap.add_argument("--src", type=Path, help="folder of clones (byte-identical check)")
ap.add_argument("--rules", type=Path, help="vedic- fingerprints rules.json")
ap.add_argument("--out", type=Path, default=Path("/tmp/vk/clean/proposals/units.json"))
ap.add_argument("--shares", type=Path, default=Path("/tmp/vk/clean/unit-shares.json"))
ap.add_argument("--near-copy-files", type=float, default=0.8)
a = ap.parse_args(argv)
graph = json.loads(a.graph.read_text(encoding="utf-8"))
if graph.get("schema") != "explore-build-graph-v1":
sys.exit(f"unexpected graph schema {graph.get('schema')!r}")
rules = load_rules(a.rules)
records, shares, counts, top = run(graph, load_units(a.units), rules, a.src, a.near_copy_files)
inputs = {"graph": str(a.graph), "graph_sha256": sha256_file(a.graph), "units": str(a.units),
"units_sha256": sha256_file(a.units), "rules": rules, "near_copy_files": a.near_copy_files}
write_json(a.out, {"schema": SCHEMA, "proposer": PROPOSER, "graph_cut": graph["cut"], "inputs": inputs,
"counts": counts, "proposals": records})
write_json(a.shares, {"schema": SHARES_SCHEMA, "proposer": PROPOSER, "graph_cut": graph["cut"],
"meaning": "Share of each file's lines inside a function, method or class that "
"duplicates one kept in another file (display only; nothing is removed). "
"share_exact counts only byte-identical or whitespace/comment-only copies.",
"inputs": inputs, "counts": counts, "most_duplicated": top, "files": shares})
print(json.dumps({"counts": counts, "most_duplicated": top[:5]}, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())