In this section
- Explore — Lab storage · cosmic / tools/explore/lab/common.py lines 1–263
- Communities transform · cosmic / tools/explore/lab/communities.py lines 1–184
- Drift storage · cosmic / tools/explore/lab/drift.py lines 1–142
Explore — Lab
A Python module in the tools folder of Cosmic that reads build graph and units, using SHA-256. It splits ident (`split_ident`) and writes JSON (`write_json`).
storagecosmic / tools/explore/lab/common.py · lines 1–263 of 263 · pattern modularity (shared by 2 files)
- What it does
- It loads build graph and units. Defines 18 functions or classes, including split_ident, Graph, __init__, key, ref. Uses libraries hashlib, json, math, os, re. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file build_graph.json; JSON file graph.json; Parquet file units.parquet; Parquet file files.parquet; DuckDB queries. Out: JSON file.
- Downstream impact
- Used directly by 9 files: Pipeline (cosmic); Communities (cosmic); Drift (cosmic); Importance (cosmic); and 5 more. Reached from 5 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- Shared contract and helpers for the Explore Code intelligence lab.
- Why it matters
- Imported by 8 files, including Pipeline, Communities and Drift. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- hashlib, json, math, os, re, numpy, duckdb
- Used by
- imported by Pipeline (import), imported by Communities (import), imported by Drift (import), imported by Importance (import), imported by Links (import), imported by Explore — Lab (import), imported by Semantic (import), imported by Test Lab (import), and 1 more
- Produces
- split_ident, Graph, adjacency, load, synthetic, nmi, ari, modularity, top_words, file_words, digest, r4
- Defines here
- split_ident, Graph, __init__, key, ref, adjacency, load, synthetic, _contingency, nmi, ari, modularity, top_words, file_words, digest, r4, overlay, write_json
- 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/lab/common.py:1-263 · blob 2eea9998595dc39dc4866822e09152dcf9b1c7b3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: unknown · users: none · canonical: supporting_data
"""Shared contract and helpers for the Explore Code intelligence lab.
Every experiment module exposes:
NAME short id, also the overlay file name (/tmp/lab-out/<NAME>.json)
RULES rules/algorithm version string; bump on any change of rule or parameter
HYPOTHESIS one sentence that the metrics can refute
ALGORITHM one paragraph, what is computed (printed with every run: Kuiper's "a run whose rules
are not printed is not a run")
run(G) -> (overlay: dict, metrics: dict, findings: list[str])
`G` is a Graph (below). Overlays are compact, columnar and keyed by file id (= index in
build_graph.json `files` of the named cut); the keys file /tmp/lab-out/keys.json maps every id to its
permanent key `repo@commit:path` and blob SHA, so every claim can be recomputed (the first law).
Anything inferred rather than measured carries state "CANDIDATE".
Only numpy, pyarrow, duckdb and the standard library are used.
"""
import hashlib
import json
import math
import os
import re
import numpy as np
BUILD_GRAPH = '/tmp/site7/explore-code/build_graph.json'
DATA_DIR = '/tmp/site7/explore-code/data'
VISUAL_GRAPH = '/tmp/site7/explore-code/visual/graph.json'
VEDIC_UNITS = '/home/claude/vedic-/fingerprints/out/units.parquet'
OUT = '/tmp/lab-out'
OVERLAY_SCHEMA = 'explore-lab-overlay-v1'
SEED = 20261205
STOP = set('''a an and are as at be by for from in into is it of on or the to with this that file files index
main app src lib test tests js py html mjs css json md new old v1 v2 v3 v4 v5 v6 v7 v8 v9 get set make
data tmp util utils helper helpers mod module page pages public docs doc readme run script scripts'''.split())
# ------------------------------------------------------------------ words
_CAMEL = re.compile(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+')
def split_ident(s):
"""camelCase / snake_case / kebab-case -> lower-case words; digits and 1-letter words dropped."""
out = []
for part in re.split(r'[^A-Za-z0-9]+', s or ''):
for w in _CAMEL.findall(part):
w = w.lower()
if len(w) > 1 and not w.isdigit():
out.append(w)
return out
# ------------------------------------------------------------------ graph
class Graph:
"""The estate as arrays. Edges: resolved references excluding `comment-url` (a mention is not a load)."""
def __init__(self, g, blobs=None):
self.raw = g
self.files = g['files']
self.n = len(self.files)
self.cut = g.get('cut', '')
self.rules_version = g.get('rules_version', '')
self.repo_commit = {r['repo']: r.get('commit', '') for r in g.get('repos', [])}
self.core_repos = {r['repo'] for r in g.get('repos', []) if r.get('core')}
sec_topic = {s['section']: s.get('topic', '') for s in g.get('sections', [])}
self.topic = [f.get('topic') or sec_topic.get(f.get('section'), '') or '' for f in self.files]
self.repo = [f['repo'] for f in self.files]
self.path = [f['path'] for f in self.files]
self.blob = blobs or {}
ed = set()
for e in g.get('edges', []):
a, b, kind = int(e[0]), int(e[1]), e[2]
if kind == 'comment-url' or a == b or not (0 <= a < self.n and 0 <= b < self.n):
continue
ed.add((a, b))
if not g.get('edges'): # older cuts: imports only
for i, f in enumerate(self.files):
for j in f.get('imports') or []:
if isinstance(j, int) and j != i and 0 <= j < self.n:
ed.add((i, j))
self.edges = sorted(ed) # directed (importer, imported)
und = sorted({(min(a, b), max(a, b)) for a, b in self.edges})
self.uedges = und
self.out_adj = [[] for _ in range(self.n)]
self.in_adj = [[] for _ in range(self.n)]
for a, b in self.edges:
self.out_adj[a].append(b)
self.in_adj[b].append(a)
self.nbr = adjacency(self.n, und)
def key(self, i):
"""The permanent key of a file: repo@commit12:path (commit of the cut's clone)."""
r = self.repo[i]
return '%s@%s:%s' % (r, self.repo_commit.get(r, '')[:12], self.path[i])
def ref(self, i):
return 'file %d %s' % (i, self.key(i))
def adjacency(n, uedges):
nbr = [[] for _ in range(n)]
for a, b in uedges:
nbr[a].append(b)
nbr[b].append(a)
for l in nbr:
l.sort()
return nbr
_CACHE = {}
def load(path=BUILD_GRAPH, data_dir=DATA_DIR):
if path in _CACHE:
return _CACHE[path]
with open(path, 'rb') as fh:
raw = fh.read()
g = json.loads(raw)
blobs = {}
fp = os.path.join(data_dir, 'files.parquet')
if os.path.exists(fp):
import duckdb
for repo, p, b in duckdb.sql("select distinct repo, path, blob_sha from '%s'" % fp).fetchall():
blobs[(repo, p)] = b
G = Graph(g, {(f['repo'], f['path']): blobs.get((f['repo'], f['path']), '') for f in g['files']})
G.input_sha256 = hashlib.sha256(raw).hexdigest()
_CACHE[path] = G
return G
def synthetic(n, edges, **cols):
"""A tiny Graph for tests: files named f<i> in repo r, edges directed (a, b)."""
files = []
for i in range(n):
f = {'id': i, 'repo': cols.get('repo', ['r'] * n)[i], 'path': 'p/f%d.js' % i, 'stage': 'unknown',
'role': 'other', 'name_words': [], 'defines': [], 'entry': False, 'reachable': False,
'data_contracts': {'in': [], 'out': []}, 'imports': [], 'dependents': [], 'lines': 10}
for k, v in cols.items():
f[k] = v[i]
files.append(f)
g = {'files': files, 'edges': [[a, b, 'import', ''] for a, b in edges], 'repos': [], 'sections': [],
'cut': 'synthetic'}
G = Graph(g)
G.input_sha256 = 'synthetic'
return G
# ------------------------------------------------------------------ agreement metrics (by hand)
def _contingency(a, b):
a = np.asarray(a)
b = np.asarray(b)
_, ai = np.unique(a, return_inverse=True)
_, bi = np.unique(b, return_inverse=True)
m = np.zeros((ai.max() + 1, bi.max() + 1), dtype=np.float64)
np.add.at(m, (ai, bi), 1)
return m
def nmi(a, b):
"""Normalised mutual information, arithmetic-mean normalisation (sklearn default). 1 for equal partitions."""
m = _contingency(a, b)
n = m.sum()
if n == 0:
return 0.0
pa = m.sum(1) / n
pb = m.sum(0) / n
pij = m / n
nz = pij > 0
mi = float((pij[nz] * np.log(pij[nz] / np.outer(pa, pb)[nz])).sum())
ha = float(-(pa[pa > 0] * np.log(pa[pa > 0])).sum())
hb = float(-(pb[pb > 0] * np.log(pb[pb > 0])).sum())
if ha == 0 and hb == 0:
return 1.0
d = (ha + hb) / 2
return max(0.0, mi / d) if d > 0 else 0.0
def ari(a, b):
"""Adjusted Rand index (Hubert & Arabie). 1 for equal partitions, ~0 for random."""
m = _contingency(a, b)
n = m.sum()
c2 = lambda x: x * (x - 1) / 2
sij = c2(m).sum()
sa = c2(m.sum(1)).sum()
sb = c2(m.sum(0)).sum()
tot = c2(n)
if tot == 0:
return 1.0
exp = sa * sb / tot
mx = (sa + sb) / 2
if mx == exp:
return 1.0
return float((sij - exp) / (mx - exp))
def modularity(nbr, labels, weights=None):
"""Newman modularity of an undirected unweighted graph given as sorted neighbour lists."""
m2 = sum(len(l) for l in nbr)
if m2 == 0:
return 0.0
inside = {}
deg = {}
for i, l in enumerate(nbr):
c = labels[i]
deg[c] = deg.get(c, 0) + len(l)
for j in l:
if labels[j] == c:
inside[c] = inside.get(c, 0) + 1
return float(sum(inside.get(c, 0) / m2 - (d / m2) ** 2 for c, d in deg.items()))
def top_words(members, words_of, df_all, n_all, k=3):
"""Name a set of files by the words most over-represented in it (tf x idf over member counts)."""
cnt = {}
for i in members:
for w in set(words_of(i)):
cnt[w] = cnt.get(w, 0) + 1
sc = []
for w, c in cnt.items():
if c < 2 and len(members) > 2:
continue
sc.append((-(c / len(members)) * math.log((n_all + 1) / (df_all.get(w, 0) + 1)), w))
sc.sort()
return [w for _, w in sc[:k]]
def file_words(f):
ws = [w for w in (f.get('name_words') or []) if w not in STOP and len(w) > 2 and not w.isdigit()]
return ws
# ------------------------------------------------------------------ output
def digest(obj):
return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def r4(x):
return float(round(float(x), 4))
def overlay(G, name, rules, cols=None, edges=None, legend=None, state='measurement', extra=None):
o = {'schema': OVERLAY_SCHEMA, 'exp': name, 'rules': rules, 'cut': G.cut,
'input_sha256': getattr(G, 'input_sha256', ''), 'n': G.n, 'state': state,
'key': 'file id = index into build_graph.json files of this cut; keys.json maps id -> repo@commit:path',
'cols': cols or {}}
if edges is not None:
o['edges'] = edges
if legend is not None:
o['legend'] = legend
if extra:
o.update(extra)
return o
def write_json(path, obj, compact=True):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as fh:
if compact:
json.dump(obj, fh, separators=(',', ':'), ensure_ascii=False)
else:
json.dump(obj, fh, indent=1, ensure_ascii=False)Communities
A Python module in the lab folder of Cosmic that labels propagation (`label_propagation`), using Louvain.
transformcosmic / tools/explore/lab/communities.py · lines 1–184 of 184 · pattern label_propagation (shared by 2 files)
- What it does
- It calculates its inputs. Defines louvain, label_propagation, by_size, run. Uses libraries random, collections.
- Downstream impact
- Used directly by 2 files: Explore — Lab (cosmic); Test Lab (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- It is built from the louvain step (`louvain`), the by size helper (`by_size`) and the run step (`run`). Experiment 1: communities by modularity (Louvain) and label propagation.
- Why it matters
- Imported by Explore — Lab. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), random, collections
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import)
- Produces
- louvain, label_propagation, by_size, run
- Defines here
- louvain, label_propagation, by_size, run
- 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/lab/communities.py:1-184 · blob b11e75c955ec68d538243a5cab77fba1a3cb5c7a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Experiment 1: communities by modularity (Louvain) and label propagation."""
import random
from collections import Counter
from common import (SEED, ari, file_words, modularity, nmi, overlay, r4, top_words)
NAME = 'communities'
RULES = 'lab-communities-v1 (louvain resolution 1.0, seeded node order %d; label propagation async, ties -> smallest label, 60 sweeps max)' % SEED
HYPOTHESIS = ('Communities found from resolved references alone recover structure that repositories and topics '
'do not already give (cross-repository working sets), with modularity well above the repo partition.')
ALGORITHM = ('Undirected graph of resolved edges (comment-url excluded). Louvain: local moving by modularity gain '
'in a seeded order, then aggregation, repeated until no gain. Label propagation: each node takes the '
'most frequent neighbour label. Isolated files get no community (-1). Agreement with topic, repo and '
'role by NMI and ARI over files with at least one edge. Names: the three name words most '
'over-represented in the community (tf x idf).')
def louvain(n, uedges, seed=SEED, resolution=1.0, max_levels=12):
"""Return a list of community labels (0..k-1, numbered by first appearance in node order)."""
adj = [dict() for _ in range(n)]
for a, b in uedges:
if a == b:
continue
adj[a][b] = adj[a].get(b, 0.0) + 1.0
adj[b][a] = adj[b].get(a, 0.0) + 1.0
k = [sum(d.values()) for d in adj]
m2 = sum(k)
member = list(range(n)) # original node -> current super node
if m2 == 0:
return list(range(n))
rng = random.Random(seed)
for _level in range(max_levels):
nn = len(adj)
comm = list(range(nn))
tot = list(k)
order = list(range(nn))
rng.shuffle(order)
moved_any = False
improved = True
sweeps = 0
while improved and sweeps < 50:
improved = False
sweeps += 1
for i in order:
ci = comm[i]
ki = k[i]
links = {}
for j, w in adj[i].items():
if j != i:
links[comm[j]] = links.get(comm[j], 0.0) + w
tot[ci] -= ki
best_c = ci
best_gain = links.get(ci, 0.0) - resolution * tot[ci] * ki / m2
for c in sorted(links):
gain = links[c] - resolution * tot[c] * ki / m2
if gain > best_gain + 1e-12:
best_gain, best_c = gain, c
tot[best_c] += ki
if best_c != ci:
comm[i] = best_c
improved = True
moved_any = True
if not moved_any:
break
relabel = {}
for i in range(nn):
if comm[i] not in relabel:
relabel[comm[i]] = len(relabel)
new_n = len(relabel)
new_adj = [dict() for _ in range(new_n)]
new_k = [0.0] * new_n
for i in range(nn):
ci = relabel[comm[i]]
new_k[ci] += k[i]
for j, w in adj[i].items():
cj = relabel[comm[j]]
new_adj[ci][cj] = new_adj[ci].get(cj, 0.0) + w
member = [relabel[comm[s]] for s in member]
if new_n == nn:
break
adj, k = new_adj, new_k
relabel = {}
out = []
for s in member:
if s not in relabel:
relabel[s] = len(relabel)
out.append(relabel[s])
return out
def label_propagation(nbr, seed=SEED, sweeps=60):
n = len(nbr)
lab = list(range(n))
rng = random.Random(seed)
order = list(range(n))
for _ in range(sweeps):
rng.shuffle(order)
changed = 0
for i in order:
if not nbr[i]:
continue
c = Counter(lab[j] for j in nbr[i])
top = max(c.values())
best = min(l for l, v in c.items() if v == top)
if lab[i] in c and c[lab[i]] == top:
best = lab[i] # keep own label on ties: converges
if best != lab[i]:
lab[i] = best
changed += 1
if not changed:
break
return lab
def by_size(labels, active):
"""Renumber communities by size (largest 0); inactive (isolated) files get -1."""
cnt = Counter(labels[i] for i in range(len(labels)) if active[i])
order = sorted(cnt, key=lambda c: (-cnt[c], min(i for i in range(len(labels)) if labels[i] == c)))
ren = {c: r for r, c in enumerate(order)}
return [ren[labels[i]] if active[i] else -1 for i in range(len(labels))]
def run(G):
active = [len(l) > 0 for l in G.nbr]
lv = by_size(louvain(G.n, G.uedges), active)
lp = by_size(label_propagation(G.nbr), active)
idx = [i for i in range(G.n) if active[i]]
# isolated files count as their own singleton for modularity (they contribute nothing)
lv_full = [lv[i] if lv[i] >= 0 else 10 ** 6 + i for i in range(G.n)]
lp_full = [lp[i] if lp[i] >= 0 else 10 ** 6 + i for i in range(G.n)]
q_lv = modularity(G.nbr, lv_full)
q_lp = modularity(G.nbr, lp_full)
q_repo = modularity(G.nbr, G.repo)
q_topic = modularity(G.nbr, G.topic)
sub = lambda arr: [arr[i] for i in idx]
roles = [f.get('role', '') for f in G.files]
agree = {}
for nm, part in (('louvain', lv), ('label_propagation', lp)):
agree[nm] = {t: {'nmi': r4(nmi(sub(part), sub(ref))), 'ari': r4(ari(sub(part), sub(ref)))}
for t, ref in (('topic', G.topic), ('repo', G.repo), ('role', roles))}
agree['louvain_vs_label_propagation'] = {'nmi': r4(nmi(sub(lv), sub(lp))), 'ari': r4(ari(sub(lv), sub(lp)))}
sizes = Counter(c for c in lv if c >= 0)
sz = sorted(sizes.values(), reverse=True)
# names
df = Counter()
for f in G.files:
df.update(set(file_words(f)))
members = {}
for i, c in enumerate(lv):
if c >= 0:
members.setdefault(c, []).append(i)
legend = []
cross = 0
for c in sorted(members):
mem = members[c]
words = top_words(mem, lambda i: file_words(G.files[i]), df, G.n)
rc = Counter(G.repo[i] for i in mem)
top_repo, top_n = rc.most_common(1)[0]
if len(rc) > 1 and top_n / len(mem) < 0.8:
cross += 1
hub = max(mem, key=lambda i: (len(G.nbr[i]), -i))
legend.append([c, ' '.join(words) or top_repo, len(mem), top_repo, round(top_n / len(mem), 3), len(rc), hub])
cross_examples = [l for l in legend if l[5] > 1 and l[4] < 0.8 and l[2] >= 8][:8]
metrics = {
'files_with_edges': len(idx), 'isolated_files': G.n - len(idx),
'undirected_edges': len(G.uedges),
'modularity': {'louvain': r4(q_lv), 'label_propagation': r4(q_lp), 'repo_partition': r4(q_repo),
'topic_partition': r4(q_topic)},
'agreement': agree,
'louvain_communities': len(sizes), 'label_propagation_communities': len(set(c for c in lp if c >= 0)),
'size_distribution': {'largest': sz[:10], 'median': sz[len(sz) // 2] if sz else 0,
'singletons_or_pairs': sum(1 for s in sz if s <= 2),
'share_in_top10': r4(sum(sz[:10]) / max(1, sum(sz)))},
'cross_repo_communities_ge8_files': sum(1 for l in legend if l[5] > 1 and l[4] < 0.8 and l[2] >= 8),
'cross_repo_communities_any': cross,
}
findings = []
for l in cross_examples[:5]:
findings.append('community %d "%s": %d files across %d repos (top %s %.0f%%), hub %s' %
(l[0], l[1], l[2], l[5], l[3], 100 * l[4], G.ref(l[6])))
ov = overlay(G, NAME, RULES, cols={'c': lv, 'lp': lp},
legend={'c': ['id', 'label', 'size', 'top_repo', 'top_repo_share', 'repos', 'hub_file'],
'rows': legend})
return ov, metrics, findingsDrift
A Python module in the lab folder of Cosmic that loads units (`load_units`). It is built from the families step (`families`), the find step (`find`) and the canonical step (`canonical`).
storagecosmic / tools/explore/lab/drift.py · lines 1–142 of 142 · pattern load_units (shared by 3 files)
- What it does
- It loads data. Defines 7 functions or classes, including load_units, families, find, canonical, key. Uses libraries os, re, collections, duckdb. Side effects: uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: DuckDB queries.
- Downstream impact
- Used directly by 2 files: Explore — Lab (cosmic); Test Lab (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- Experiment 5: duplication and drift from Vedic structural fingerprints.
- Why it matters
- Imported by Explore — Lab. Checked by Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), os, re, collections, duckdb
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import)
- Produces
- load_units, families, canonical, run
- Defines here
- load_units, families, find, canonical, key, run, jab
- 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/lab/drift.py:1-142 · blob 7417a6f1446084da7ac7e5869a75c97ee0790b90 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: unknown · users: none · canonical: supporting_data
"""Experiment 5: duplication and drift from Vedic structural fingerprints."""
import os
import re
from collections import Counter
from common import VEDIC_UNITS, overlay, r4
NAME = 'drift'
RULES = ('lab-drift-v1 (units with >= 20 tokens; struct_hash in > 30 files dropped as boilerplate; near-copy = '
'Jaccard of struct_hash sets >= 0.5 with >= 3 shared units; family = connected component; canonical = '
'core repo > reachable > most dependents > newest path timestamp > lowest id)')
HYPOTHESIS = ('Structural fingerprints find families of near-identical files across repositories that blob identity '
'misses, and most unreached files in such families have a reachable copy, which makes them the '
'safest review candidates.')
ALGORITHM = ('Vedic units.parquet (one row per function/class: struct_hash = token stream with identifiers, numbers '
'and strings abstracted) joined to Explore Code files by repo + path. Each file becomes the set of its '
'struct hashes; an inverted index counts shared hashes per file pair; pairs above the threshold are '
'joined by union-find into families. In each family one canonical copy is chosen by a fixed order; '
'every other member gets a drift edge to it. All families are CANDIDATES for review, never deletions.')
TS = re.compile(r'(20\d{6}(?:\d{2,4})?)')
def load_units(path=VEDIC_UNITS):
if not os.path.exists(path):
return [], ''
import duckdb
rows = duckdb.sql("select repo, path, struct_hash, commit from '%s' where n_tokens >= 20 order by repo, path, line_from" % path).fetchall()
return rows, path
def families(sets, min_jac=0.5, min_shared=3, max_df=30):
"""sets: dict id -> set(hash). Returns (pairs {(a,b): (shared, jaccard)}, families [sorted member lists])."""
inv = {}
for i in sorted(sets):
for h in sets[i]:
inv.setdefault(h, []).append(i)
pc = Counter()
for h in sorted(inv):
mem = inv[h]
if len(mem) < 2 or len(mem) > max_df:
continue
for x in range(len(mem)):
for y in range(x + 1, len(mem)):
pc[(mem[x], mem[y])] += 1
pairs = {}
for (a, b), s in pc.items():
u = len(sets[a] | sets[b])
j = s / u if u else 0
if j >= min_jac and s >= min_shared:
pairs[(a, b)] = (s, j)
parent = {}
def find(x):
parent.setdefault(x, x)
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in sorted(pairs):
ra, rb = find(a), find(b)
if ra != rb:
parent[max(ra, rb)] = min(ra, rb)
fam = {}
for x in sorted(parent):
fam.setdefault(find(x), []).append(x)
return pairs, sorted((sorted(v) for v in fam.values()), key=lambda v: (-len(v), v[0]))
def canonical(G, members):
def key(i):
f = G.files[i]
ts = TS.findall(G.path[i])
return (G.repo[i] in G.core_repos, bool(f.get('reachable')), len(f.get('dependents') or []),
max(ts) if ts else '', -i)
return max(members, key=key)
def run(G):
rows, src = load_units()
ix = {(G.repo[i], G.path[i]): i for i in range(G.n)}
sets = {}
commits = {}
for repo, path, h, commit in rows:
i = ix.get((repo, path))
if i is not None:
sets.setdefault(i, set()).add(h)
commits[repo] = commit
pairs, fams = families(sets)
jac = {}
for (a, b), (s, j) in pairs.items():
jac[(a, b)] = j
def jab(a, b):
if (min(a, b), max(a, b)) in jac:
return jac[(min(a, b), max(a, b))]
u = len(sets[a] | sets[b])
return len(sets[a] & sets[b]) / u if u else 0.0
fam_id = [-1] * G.n
canon = [-1] * G.n
edges = []
legend = []
for fid, mem in enumerate(fams):
c = canonical(G, mem)
for i in mem:
fam_id[i] = fid
canon[i] = c
if i != c:
edges += [i, c, int(round(1000 * jab(i, c)))]
legend.append([fid, len(mem), len({G.repo[i] for i in mem}), c])
reach = [bool(f.get('reachable')) for f in G.files]
unreached_in_vedic = [i for i in sets if not reach[i]]
unreached = [i for i in range(G.n) if not reach[i]]
safe = sorted(i for i in unreached if fam_id[i] >= 0 and any(reach[j] for j in fams[fam_id[i]]))
known = {(i, f.get('duplicate_of')) for i, f in enumerate(G.files) if f.get('duplicate_of') is not None}
known_any = {i for i, _ in known}
in_fam = [i for i in range(G.n) if fam_id[i] >= 0]
cross = sum(1 for l in legend if l[2] > 1)
drifted = sum(1 for k in range(0, len(edges), 3) if edges[k + 2] < 1000)
metrics = {
'vedic_source': src, 'vedic_commits_seen': len(commits), 'files_with_fingerprints': len(sets),
'exact_blob_duplicates_in_cut': len(G.files) - len({G.blob.get((G.repo[i], G.path[i])) or i for i in range(G.n)}),
'near_copy_pairs': len(pairs), 'families': len(fams), 'files_in_families': len(in_fam),
'cross_repo_families': cross, 'largest_families': [l[1] for l in legend[:8]],
'drift_edges': len(edges) // 3, 'drifted_copies_jaccard_below_1': drifted,
'unreached_files': len(unreached), 'unreached_with_fingerprints': len(unreached_in_vedic),
'unreached_with_reachable_near_copy': len(safe),
'share_of_unreached_with_reachable_copy': r4(len(safe) / max(1, len(unreached))),
'share_of_fingerprinted_unreached_with_reachable_copy': r4(len(safe) / max(1, len(unreached_in_vedic))),
'build_duplicate_of_marked': len(known_any),
'family_members_not_marked_duplicate_by_build': sum(1 for i in in_fam if i != canon[i] and i not in known_any),
}
findings = []
for l in legend[:5]:
findings.append('family %d: %d files in %d repos, canonical CANDIDATE %s' % (l[0], l[1], l[2], G.ref(l[3])))
for i in safe[:5]:
findings.append('review CANDIDATE (unreached, reachable near-copy %s): %s' % (G.key(canon[i]), G.ref(i)))
ov = overlay(G, NAME, RULES, cols={'fam': fam_id, 'canon': canon}, edges=edges,
legend={'fam': ['id', 'size', 'repos', 'canonical_file'], 'rows': legend,
'edges': 'flat [copy, canonical, jaccard x1000, ...]'},
state='CANDIDATE', extra={'safe_review': safe})
return ov, metrics, findings