In this section
- Cosmic — Index Page render · cosmic / index.html lines 701–1018
- Belt Split storage · cosmic / tools/belt_split.py lines 1–130
- Clusters storage · cosmic / tools/clusters.py lines 1–200
Cosmic — Index Page
A web page that makes accumulator (`makeAccumulator`), loads rows (`loadRows`), finds ordinal (`findByOrdinal`) and calculates planar distances. Published at https://ventusltd.github.io/cosmic/.
rendercosmic / index.html · lines 701–1018 of 1018 (continued from section 1071) · Entry point · pattern stepTween (shared by 2 files)
- What it does
- It draws its content. Defines 31 functions or classes, including fmt, words, build, mk, makeAccumulator. Side effects: changes the web page (DOM); makes network requests.
- Inputs & outputs
- In: JSON file universe.json; form fields (user input). Out: web page; WebGL/WebGPU drawing.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/cosmic/.
- What it achieves
- It makes accumulator (`makeAccumulator`), loads rows (`loadRows`) and finds ordinal (`findByOrdinal`). Defines `fmt`, `words`, `build` and 26 more. It responds to webglcontextlost, resize and pointerdown events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · / · page
- Uses
- none found
- Used by
- none found
- Produces
- fmt, words, build, mk, makeAccumulator, whitePoint, U, restart, sizes, loadRows, requestChildren, ensureChildren
- Defines here
- overlay, toPx, pick, openGoto, closeGoto
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 index.html:701-1018 · blob 41a9007eb8480538552240829c5cf7a137e0445c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unknown
requestAnimationFrame(frame); return;
}
gl.deleteSync(fence); fence = null; retired = pass;
const took = performance.now() - fenceAt;
if (took < 10 && perFrame < 4096) perFrame = Math.min(4096, Math.ceil(perFrame * 1.6));
else if (took > 24 && perFrame > 1) perFrame = Math.max(1, Math.floor(perFrame / 1.6));
}
classify();
if (xray) {
gl.bindFramebuffer(gl.FRAMEBUFFER, accFB);
gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); // every thing adds one to its pixel
}
if (pass === 0) {
gl.clear(gl.COLOR_BUFFER_BIT);
started = performance.now();
if (discs.length) {
gl.useProgram(PB);
const arr = new Float32Array(MAXB * 4);
for (let i = 0; i < discs.length; i += MAXB) {
const n = Math.min(MAXB, discs.length - i);
arr.fill(0);
for (let j = 0; j < n; j++) {
arr[j*4] = discs[i+j].sx; arr[j*4+1] = discs[i+j].sy; arr[j*4+2] = discs[i+j].rpx;
}
gl.uniform4fv(uBody, arr);
gl.drawArrays(gl.POINTS, 0, n);
}
}
}
if (resolved.length && pass < maxStride) {
gl.useProgram(PL);
gl.uniform1f(lSca, scale);
gl.uniform2f(lPan, pan[0], pan[1]);
gl.uniform1f(lAsp, cv.width / cv.height);
for (let i = 0; i < perFrame && pass < maxStride; i++) {
for (const b of resolved) {
if (pass >= b.stride) continue;
gl.uniform2f(lC, b.x, b.y);
gl.uniform1f(lRho, b.rho);
gl.uniform1f(lInv, 1 / b.value);
gl.uniform1ui(lStr, b.stride);
gl.uniform1ui(lPas, pass);
gl.uniform1ui(lSeed, b.seed >>> 0);
gl.uniform1f(lShape, b.shape === 'rect' ? 1 : 0);
gl.uniform2f(lHalf, b.hw || 0, b.hh || 0);
gl.drawArrays(gl.POINTS, 0, Math.ceil(b.value / b.stride));
}
pass++;
}
fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
gl.flush(); fenceAt = performance.now();
} else if (!resolved.length) {
retired = pass = maxStride;
}
if (xray) {
// the counts are in. Turn them into shades, with the white point stated so the picture can be
// read backwards into the number that made it.
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.disable(gl.BLEND);
gl.useProgram(PT);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, acc);
gl.uniform1i(tTex, 0);
gl.uniform1f(tWhite, whitePoint());
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
// ---------------------------------------------------------------- the accounting invariant
// TRAVELLING MUST NOT LOSE THE WHOLE. Every unit in the cartridge is in exactly one of three
// states every frame, and the three must sum to the total. This is the check that makes the
// zoom safe to compute against: relevance without amnesia.
const accounted = drawn + held + outside;
const done = retired >= maxStride;
const shown = done ? drawn : Math.floor(drawn * (retired / maxStride));
const u = M.unit;
const lines = [];
lines.push('the whole · ' + words(TOTAL) + ' ' + u);
lines.push('resolved ' + words(shown) + (done ? '' : ' of ' + words(drawn))
+ ' · held ' + words(held) + ' in ' + fmt(heldN)
+ (heldN === 1 ? ' source' : ' sources')
+ ' · outside ' + words(outside));
// THE HUD CITES THE LAW THAT GOVERNS EACH STATE, so a refusal is never unexplained.
if (held) lines.push('L12 · what is held is past the confusion limit, not discarded');
if (accounted !== TOTAL) {
lines.push('L13 BROKEN · MISACCOUNTED by ' + fmt(TOTAL - accounted) + ' ' + u);
} else if (!done) {
lines.push('exposing ' + (retired / maxStride * 100).toFixed(0) + '% · '
+ ((performance.now() - started) / 1000).toFixed(1) + ' s');
} else {
lines.push('L13 · every ' + u.replace(/s$/, '') + ' accounted for');
}
if (target) lines.push('collapsed to ' + M.unit.replace(/s$/, '') + ' ' + fmt(target.k)
+ ' of ' + fmt(TOTAL) + ' · ' + target.path.length + ' levels, '
+ target.fetches + (target.fetches === 1 ? ' fetch' : ' fetches') + ', no traversal');
lines.push('distance is time · outward is older · levels are not to scale');
if (xray) {
lines.push('X-RAY · L20 · each pixel holds its exact count, drawn as a shade');
lines.push('black = none · white = ' + fmt(Math.round(whitePoint()))
+ ' or more in one pixel · logarithmic, so it reads backwards');
}
hud.textContent = lines.join('\n');
hud.className = (accounted !== TOTAL) ? 'warn' : '';
overlay();
requestAnimationFrame(frame);
}
// ------------------------------------------------ boundaries and names, without the clutter
// An unresolved source larger than the screen is drawn as its BOUNDARY with its count beside it.
// Filling it white would say "here are the things" when the things are precisely what has not
// been drawn. Only the object under the pointer is named unless names are asked for.
function overlay() {
o2.clearRect(0, 0, ov.width, ov.height);
if (!root) return;
const asp = ov.width / ov.height, R = ov.height / 2 * scale;
const toPx = n => [ (n.x * scale + pan[0]) / asp * ov.width/2 + ov.width/2,
ov.height/2 - (n.y * scale + pan[1]) * ov.height/2 ];
o2.font = '11px ui-monospace,Consolas,monospace';
// ---------------------------------------------------------------- the section, drawn as one
// THE SUBSTRATE IS PART OF THE DRAWING. A wafer map is the collision between a rectangular step
// and a round substrate, so the circle, the exclusion ring and the notch are not decoration:
// they are what make the partial fields at the rim mean anything.
if (M && M.extent_mm && LEVELS.some((l, i) => viewOf(i) === 'section')) {
const [zx, zy] = toPx({ x:0, y:0 });
o2.lineWidth = 1;
o2.strokeStyle = 'rgba(232,230,225,0.6)';
o2.beginPath(); o2.arc(zx, zy, R, 0, 6.2832); o2.stroke();
const ee = M.inputs && M.inputs.edge_exclusion_mm;
if (ee) {
o2.strokeStyle = 'rgba(139,145,156,0.55)'; o2.setLineDash([5, 5]);
o2.beginPath(); o2.arc(zx, zy, R * (1 - ee / M.extent_mm), 0, 6.2832); o2.stroke();
o2.setLineDash([]);
if (R > 120) {
o2.fillStyle = 'rgba(139,145,156,0.8)';
o2.fillText(ee + ' mm edge exclusion', zx + 8, zy - R * (1 - ee / M.extent_mm) - 6);
}
}
// the notch: crystal orientation, and the only thing that tells you which way the wafer is up
const nr = Math.max(3, R * (1.5 / M.extent_mm));
o2.strokeStyle = 'rgba(232,230,225,0.6)';
o2.beginPath(); o2.arc(zx, zy + R, nr, Math.PI, 0); o2.stroke();
}
// dies: outlines on the stepper grid. A full field is solid, a partial field is dashed, because
// a partial field is printed and discarded and must never be mistaken for yield.
if (rects.length) {
const wide = rects.length < 400;
for (const q of rects) {
const n = q.node;
const [x, y] = toPx(n);
const w = n.hw * R * 2, h = n.hh * R * 2;
if (w < 1.2 || x + w < -40 || x - w > ov.width + 40) continue;
const part = n.kind === 'partial';
o2.strokeStyle = part ? 'rgba(139,145,156,0.75)' : 'rgba(232,230,225,0.85)';
o2.lineWidth = 1;
if (part) o2.setLineDash([3, 3]);
o2.strokeRect(Math.round(x - w/2) + 0.5, Math.round(y - h/2) + 0.5, Math.round(w), Math.round(h));
o2.setLineDash([]);
if (wide && w > 46) {
o2.fillStyle = part ? 'rgba(139,145,156,0.7)' : 'rgba(232,230,225,0.6)';
o2.fillText(part ? 'partial' : n.label, x - w/2 + 4, y - h/2 + 13);
}
}
}
for (const r of rings) {
const [x, y] = toPx(r.node);
o2.strokeStyle = 'rgba(232,230,225,0.55)';
o2.setLineDash([2, 4]); o2.lineWidth = 1;
o2.beginPath(); o2.arc(x, y, r.rpx, 0, 6.2832); o2.stroke();
o2.setLineDash([]);
o2.fillStyle = 'rgba(232,230,225,0.8)';
o2.fillText(r.node.label + ' · ' + words(r.node.value) + ' ' + M.unit + ' · '
+ words(r.node.perPixel) + ' per pixel, beyond resolving'
+ (r.node.badChildren ? ' · ' + r.node.badChildren
: r.node.children ? '' : ' · keep travelling'),
x - r.rpx + 8, y - r.rpx - 6);
}
if (target) {
const [tx, ty] = [ (target.x * scale + pan[0]) / asp * ov.width/2 + ov.width/2,
ov.height/2 - (target.y * scale + pan[1]) * ov.height/2 ];
if (tx > -200 && tx < ov.width + 200 && ty > -200 && ty < ov.height + 200) {
o2.strokeStyle = 'rgba(232,179,106,0.9)'; o2.lineWidth = 1;
o2.beginPath();
o2.moveTo(tx - 14, ty); o2.lineTo(tx - 5, ty);
o2.moveTo(tx + 5, ty); o2.lineTo(tx + 14, ty);
o2.moveTo(tx, ty - 14); o2.lineTo(tx, ty - 5);
o2.moveTo(tx, ty + 5); o2.lineTo(tx, ty + 14);
o2.stroke();
o2.fillStyle = 'rgba(232,179,106,0.95)';
o2.fillText(target.address, tx + 18, ty - 6);
}
}
const show = names ? (root.children || []) : (hover ? [hover] : []);
for (const b of show) {
const [x, y] = toPx(b); const rpx = b.rho * R;
if (x < -300 || x > ov.width + 300 || y < -300 || y > ov.height + 300) continue;
const hot = b === hover;
o2.strokeStyle = hot ? 'rgba(232,230,225,0.85)' : 'rgba(139,145,156,0.30)';
o2.lineWidth = 1;
o2.beginPath(); o2.arc(x, y, Math.max(3, rpx) + 4, 0, 6.2832); o2.stroke();
o2.fillStyle = hot ? '#e8e6e1' : 'rgba(139,145,156,0.75)';
o2.fillText(hot
? b.label + ' ' + words(b.value) + ' ' + M.unit + ' ' + fmt(b.value) + ' exactly '
+ (b.commits !== undefined ? fmt(b.commits) + ' commits ' : '')
+ (b.value / TOTAL * 100).toFixed(2) + '%'
: b.label, x + Math.max(3, rpx) + 8, y - 4);
}
}
// the object under the pointer, read back through the placement law: screen gives world, world
// gives the object. The law is invertible, which is why nothing has to be stored to answer
// "what am I looking at".
function pick(px, py) {
if (!root) { hover = null; return; }
const asp = cv.width / cv.height;
const ndx = (px / innerWidth) * 2 - 1, ndy = 1 - (py / innerHeight) * 2;
const wx = (ndx * asp - pan[0]) / scale, wy = (ndy - pan[1]) / scale;
const grain = 7 / (cv.height / 2 * scale);
hover = null; let best = Infinity;
(function scan(node, depth) {
for (const c of (node.children || [])) {
const d = Math.hypot(wx - c.x, wy - c.y);
const hit = (c.shape === 'rect')
? (Math.abs(wx - c.x) <= Math.max(c.hw, grain) && Math.abs(wy - c.y) <= Math.max(c.hh, grain))
: d < Math.max(c.rho, grain);
if (hit && d < best) { best = d; hover = c; }
if (c.children && depth < 8) scan(c, depth + 1);
}
})(root, 0);
}
// -------------------------------------------------------------------------------- the controls
let drag = null, moved = 0;
cv.addEventListener('pointerdown', e => { drag = [e.clientX, e.clientY]; moved = 0; });
addEventListener('pointerup', e => {
if (drag && moved < 4) { pick(e.clientX, e.clientY); if (hover) travelTo(hover); }
drag = null;
});
addEventListener('pointermove', e => {
if (drag) {
moved += Math.abs(e.clientX - drag[0]) + Math.abs(e.clientY - drag[1]);
pan[0] += (e.clientX - drag[0]) / innerWidth * 2;
pan[1] -= (e.clientY - drag[1]) / innerHeight * 2;
drag = [e.clientX, e.clientY];
tween = null; restart();
}
pick(e.clientX, e.clientY);
});
addEventListener('wheel', e => {
scale *= e.deltaY < 0 ? 1.15 : 1 / 1.15;
scale = Math.max(0.05, Math.min(1e12, scale));
tween = null; restart();
}, { passive: true });
const gotoBox = document.getElementById('goto'), gotoIn = document.getElementById('gotoin');
function openGoto() { gotoBox.style.display = 'block'; gotoIn.value = ''; gotoIn.focus(); }
function closeGoto() { gotoBox.style.display = 'none'; gotoIn.blur(); }
gotoIn.addEventListener('keydown', e => {
e.stopPropagation();
if (e.key === 'Escape') { closeGoto(); return; }
if (e.key !== 'Enter') return;
const q = gotoIn.value.trim();
closeGoto();
if (!q || !root) return;
const digits = q.replace(/[ ,_]/g, '');
if (/^\d+$/.test(digits)) { collapseTo(Number(digits)); return; }
// an address by name: repository, or repository/commit. Resolved to its ordinal, then
// collapsed to exactly like any other ordinal, because there is only one way in.
const parts = q.split('/').map(t => t.trim()).filter(Boolean);
const repo = root.children.find(c => c.label.toLowerCase() === parts[0].toLowerCase())
|| root.children.find(c => c.label.toLowerCase().includes(parts[0].toLowerCase()));
if (!repo) { hud.textContent = 'no such address: ' + q; return; }
if (parts.length === 1) { collapseTo(repo.cum); return; }
ensureChildren(repo).then(kids => {
const c = (kids || []).find(x => String(x.label).startsWith(parts[1]));
collapseTo(repo.cum + (c ? c.cum : 0));
});
});
addEventListener('keydown', e => {
if (gotoBox.style.display === 'block') return;
// SHOW EVERYTHING. Not a claim, a run: it either reaches the total or it does not.
if (e.key === 'x') {
if (!FLOATOK) {
hud.textContent = 'This GPU has no float colour buffer, so counts past 255 cannot be held. '
+ 'Refusing to draw an x-ray that would count wrong.';
return;
}
xray = !xray; restart();
return;
}
if (e.key === 's') {
scanning = !scanning;
if (scanning) { scanK = 0; scanT0 = performance.now(); scanFrames = 0; }
else { restart(); }
return;
}
if (e.key === '/') { e.preventDefault(); openGoto(); }
// RANDOM NAVIGATION. A uniformly chosen point out of the whole, landed on directly. This is the
// test of the claim: if any of 37.93 billion can be reached for one fetch, the distance between
// you and the data is gone, and the size of the estate stops being a cost you pay to look.
else if (e.key === 'r') collapseTo(Math.floor(Math.random() * TOTAL));
else if (e.key === 'l') names = !names;
else if (e.key === 'Backspace') {
e.preventDefault();
tween = { t0:performance.now(), dur:750, s0:scale, s1:0.92, p0:pan.slice(), p1:[0,0] };
}
});
requestAnimationFrame(frame);
</script>
</body>
</html>Belt Split
A Python command-line tool in the tools folder of Cosmic that reads meta.
storagecosmic / tools/belt_split.py · lines 1–130 of 130 · Entry point · pattern find_repos (shared by 2 files)
- What it does
- It loads meta. Defines git, lines_of, batch_count, find_repos, main. Uses libraries argparse, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file -meta.json; command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It finds repos (`find_repos`) and is built from the git step (`git`) and the lines of helper (`lines_of`). Split the estate's line count by repository, exactly. It accepts `--roots` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools · Python CLI
- Uses
- argparse, json, os, subprocess, sys, time, datetime
- Used by
- none found
- Produces
- git, lines_of, batch_count, find_repos, main
- Defines here
- git, lines_of, batch_count, find_repos, 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/belt_split.py:1-130 · blob 737863ea5d243c9dfa880883e46403651b13c95d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""tools/belt_split.py - split the estate's line count by repository, exactly.
The telescope draws 37,796,045,093 particles from a single integer. To draw the BELT it needs to
know which repository each ordinal belongs to, and that needs one number per repository, measured
the same way the total was measured: every path in every commit's tree, copies counted each time.
python tools/belt_split.py --roots C:/Users/vikra/Documents/GitHub --out belt.tsv
Writes repo <TAB> entry_lines <TAB> entries <TAB> commits <TAB> head_lines <TAB> first_commit_unix
Sixty-six numbers, not 37.8 billion. The placement law stays computed; only the band boundaries
are shipped, and they sum to the published total or the script says so and exits non-zero.
"""
import argparse, json, os, subprocess, sys, time
from datetime import datetime, timezone
PUBLISHED_ENTRY_LINES = 37796045093
PUBLISHED_ENTRIES = 14998313
def git(d, args, binary=False):
r = subprocess.run(['git'] + args, cwd=d, capture_output=True,
text=not binary, encoding=None if binary else 'utf-8',
errors=None if binary else 'replace')
return r.stdout
def lines_of(body, size):
if b'\x00' in body[:8000]:
return -1
return body.count(b'\n') + (1 if size and not body.endswith(b'\n') else 0)
def batch_count(d, shas):
if not shas: return {}
p = subprocess.run(['git','cat-file','--batch'], cwd=d,
input=('\n'.join(shas)+'\n').encode(), capture_output=True)
out, i, res = p.stdout, 0, {}
for sha in shas:
nl = out.find(b'\n', i)
if nl < 0: break
hdr = out[i:nl].split()
if len(hdr) < 3: break
size = int(hdr[2])
res[sha] = lines_of(out[nl+1:nl+1+size], size)
i = nl + 1 + size + 1
return res
def find_repos(root):
out = []
for name in sorted(os.listdir(root)):
d = os.path.join(root, name)
if os.path.isdir(os.path.join(d, '.git')):
out.append((name, d))
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--roots', default='C:/Users/vikra/Documents/GitHub')
ap.add_argument('--out', default='belt.tsv')
a = ap.parse_args()
repos = []
for root in a.roots.split(','):
if os.path.isdir(root):
repos += find_repos(root)
if not repos:
print('FAIL: zero repositories. A check that examines nothing refuses.'); return 1
cache = {} # blob sha -> lines (-1 binary). shared across repos: content is content.
rows = []
t0 = time.time()
for name, d in repos:
entries = lines = 0
commits = git(d, ['rev-list','--all']).split()
for c in commits:
need, have = [], []
for line in git(d, ['ls-tree','-r',c]).splitlines():
p = line.split(None, 3)
if len(p) < 4 or p[1] != 'blob': continue
have.append(p[2])
if p[2] not in cache:
cache[p[2]] = None
need.append(p[2])
if need: cache.update(batch_count(d, need))
for sha in have:
entries += 1
v = cache.get(sha)
if v and v > 0: lines += v
head_lines = 0
seen_head = set()
for line in git(d, ['ls-tree','-r','-l','HEAD']).splitlines():
p = line.split(None, 4)
if len(p) < 5 or p[1] != 'blob' or p[2] in seen_head: continue
seen_head.add(p[2])
v = cache.get(p[2])
if v is None:
v = batch_count(d, [p[2]]).get(p[2]); cache[p[2]] = v
if v and v > 0: head_lines += v
first = git(d, ['log','--reverse','--all','--format=%ct']).split('\n')[0].strip() or '0'
rows.append((name, lines, entries, len(commits), head_lines, int(first or 0)))
print(' %-36s %16s lines %10s entries %5s commits %6.1f s'
% (name, format(lines,','), format(entries,','), len(commits), time.time()-t0),
file=sys.stderr, flush=True)
total_lines = sum(r[1] for r in rows)
total_entries = sum(r[2] for r in rows)
with open(a.out, 'w', encoding='utf-8', newline='\n') as f:
f.write('# repo\tentry_lines\tentries\tcommits\thead_lines\tfirst_commit_unix\n')
for r in sorted(rows, key=lambda r: (r[5], r[0])):
f.write('%s\t%d\t%d\t%d\t%d\t%d\n' % r)
meta = {'asof': datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds'),
'repositories': len(rows),
'entry_lines': total_lines, 'entries': total_entries,
'published_entry_lines': PUBLISHED_ENTRY_LINES,
'published_entries': PUBLISHED_ENTRIES,
'matches_published_lines': total_lines == PUBLISHED_ENTRY_LINES,
'matches_published_entries': total_entries == PUBLISHED_ENTRIES,
'seconds': round(time.time()-t0, 1),
'command': 'python tools/belt_split.py ' + ' '.join(sys.argv[1:])}
with open(os.path.splitext(a.out)[0] + '-meta.json','w',encoding='utf-8',newline='\n') as f:
json.dump(meta, f, indent=1, sort_keys=True)
print(json.dumps(meta, indent=1, sort_keys=True))
if total_lines != PUBLISHED_ENTRY_LINES:
print('MISMATCH: the bands do not sum to the published total. The belt must not be drawn '
'from these numbers until this is explained.', file=sys.stderr)
return 2
return 0
if __name__ == '__main__':
sys.exit(main())Clusters
A Python command-line tool in the tools folder of Cosmic that reads belt meta.
storagecosmic / tools/clusters.py · lines 1–200 of 200 · Entry point · pattern batch_count (shared by 3 files)
- What it does
- It loads belt meta. Defines git, lines_of, batch_count, main. Uses libraries argparse, json, os, subprocess, sys. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file belt-meta.json; command-line arguments. Out: JSON file.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the git step (`git`), the lines of helper (`lines_of`) and the batch count helper (`batch_count`). The estate as a hierarchy, measured at every level. It accepts `--roots` and `--out`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools · Python CLI
- Uses
- argparse, json, os, subprocess, sys, time, datetime
- Used by
- none found
- Produces
- git, lines_of, batch_count, main
- Defines here
- git, lines_of, batch_count, 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/clusters.py:1-200 · blob 1fb91de25e7fcc34f275e3dd54ffefad3deea03a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""tools/clusters.py - the estate as a hierarchy, measured at every level.
A flat disc of 37.9 billion identical points is white, because 37.9 billion over a million pixels
is forty thousand lines per pixel. The night sky is not white. What makes a sky is CLUSTERING:
things are bound to other things, and the black between them is as real as the light.
The estate was never a flat list. It is already a hierarchy:
estate -> repository -> commit -> line
So the telescope draws the level the field can resolve, and no deeper. At full field it draws the
repositories. Enter one and its commits resolve. Enter a commit and its lines resolve. The 37.9
billion are only drawn inside a sector small enough to hold them, which is what a telescope does:
it does not resolve the whole sky at once, and it never pretended to.
Writes:
belt.tsv repo entry_lines entries commits head_lines first_commit_unix
commits/NN.tsv unix entry_lines entries sha12 one file per repository, fetched only
when that sector is entered, exactly as
GridAtlas fetches a project on demand
belt-meta.json the totals, and whether they match what was published
Sharding the commits by repository is the point: the whole hierarchy is never downloaded, because
nobody looks at two sectors at once.
"""
import argparse
import json
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
PUBLISHED_ENTRY_LINES = 37796045093
PUBLISHED_ENTRIES = 14998313
def git(d, args):
return subprocess.run(['git'] + args, cwd=d, capture_output=True, text=True,
encoding='utf-8', errors='replace').stdout
def lines_of(body, size):
"""-1 means binary. Otherwise newlines, plus one if the file does not end in a newline."""
if b'\x00' in body[:8000]:
return -1
return body.count(b'\n') + (1 if size and not body.endswith(b'\n') else 0)
def batch_count(d, shas):
"""One git cat-file --batch pass. Returns {sha: lines, or -1 for binary}."""
if not shas:
return {}
p = subprocess.run(['git', 'cat-file', '--batch'], cwd=d,
input=('\n'.join(shas) + '\n').encode(), capture_output=True)
out, i, res = p.stdout, 0, {}
for sha in shas:
nl = out.find(b'\n', i)
if nl < 0:
break
h = out[i:nl].split()
if len(h) < 3:
break
size = int(h[2])
res[sha] = lines_of(out[nl + 1:nl + 1 + size], size)
i = nl + 1 + size + 1
return res
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--roots', default='C:/Users/vikra/Documents/GitHub')
ap.add_argument('--out', default='.')
a = ap.parse_args()
repos = []
for root in a.roots.split(','):
if not os.path.isdir(root):
continue
for n in sorted(os.listdir(root)):
d = os.path.join(root, n)
if os.path.isdir(os.path.join(d, '.git')):
repos.append((n, d))
if not repos:
print('FAIL: zero repositories. A check that examines nothing refuses.')
return 1
os.makedirs(os.path.join(a.out, 'commits'), exist_ok=True)
cache, rows, t0 = {}, [], time.time()
for name, d in repos:
times = {}
for line in git(d, ['log', '--all', '--format=%H %ct']).splitlines():
p = line.split()
if len(p) == 2:
times[p[0]] = int(p[1])
crows, entries, lines = [], 0, 0
for c in git(d, ['rev-list', '--all']).split():
ce = cl = 0
need, have = [], []
for line in git(d, ['ls-tree', '-r', c]).splitlines():
p = line.split(None, 3)
if len(p) < 4 or p[1] != 'blob':
continue
have.append(p[2])
if p[2] not in cache:
cache[p[2]] = None
need.append(p[2])
if need:
cache.update(batch_count(d, need))
for sha in have:
ce += 1
v = cache.get(sha)
if v and v > 0:
cl += v
crows.append((times.get(c, 0), cl, ce, c[:12]))
entries += ce
lines += cl
head, seen = 0, set()
for line in git(d, ['ls-tree', '-r', '-l', 'HEAD']).splitlines():
p = line.split(None, 4)
if len(p) < 5 or p[1] != 'blob' or p[2] in seen:
continue
seen.add(p[2])
v = cache.get(p[2])
if v is None:
v = batch_count(d, [p[2]]).get(p[2])
cache[p[2]] = v
if v and v > 0:
head += v
first = min([r[0] for r in crows if r[0]], default=0)
rows.append({'repo': name, 'lines': lines, 'entries': entries, 'commits': len(crows),
'head': head, 'first': first, 'crows': crows})
print(' %-34s %16s lines %10s entries %5s commits %6.1f s'
% (name, format(lines, ','), format(entries, ','), len(crows), time.time() - t0),
file=sys.stderr, flush=True)
# the belt's own order: newest repository at the centre, oldest at the rim, because distance
# is time. This is the same ordering the estate already uses, not a new one.
rows.sort(key=lambda r: (-r['first'], r['repo']))
# NAMES ARE DISCLOSURE. A repository that is not public must not have its name published in a
# public cartridge: the counts are the point, the name is somebody else's business. Anything
# not confirmed public is given one of our own words and a number, and the totals are
# untouched, so the accounting still holds and nothing is hidden except the name.
public = set()
try:
import subprocess as _sp
for line in _sp.run(['gh', 'repo', 'list', 'Ventusltd', '--limit', '300',
'--json', 'name,visibility', '--jq',
'.[] | select(.visibility=="PUBLIC") | .name'],
capture_output=True, text=True).stdout.split():
public.add(line.strip().lower())
except Exception:
public = None
if public:
k = 0
for r in rows:
if r['repo'].lower() not in public:
k += 1
r['repo'] = 'unnamed-%02d' % k
print(' redacted %d repositories that are not public' % k, file=sys.stderr)
else:
print(' WARNING: could not confirm which repositories are public. Names left as they are;'
' do not publish this without checking.', file=sys.stderr)
total = sum(r['lines'] for r in rows)
tot_e = sum(r['entries'] for r in rows)
with open(os.path.join(a.out, 'belt.tsv'), 'w', encoding='utf-8', newline='\n') as f:
f.write('# repo\tentry_lines\tentries\tcommits\thead_lines\tfirst_commit_unix\n')
for r in rows:
f.write('%s\t%d\t%d\t%d\t%d\t%d\n'
% (r['repo'], r['lines'], r['entries'], r['commits'], r['head'], r['first']))
for i, r in enumerate(rows):
with open(os.path.join(a.out, 'commits', '%02d.tsv' % i), 'w',
encoding='utf-8', newline='\n') as f:
f.write('# %s\tunix\tentry_lines\tentries\tsha12\n' % r['repo'])
for t, cl, ce, sha in sorted(r['crows'], key=lambda x: -x[0]):
f.write('%d\t%d\t%d\t%s\n' % (t, cl, ce, sha))
meta = {'asof': datetime.now(timezone.utc).astimezone().isoformat(timespec='seconds'),
'repositories': len(rows), 'entry_lines': total, 'entries': tot_e,
'commits': sum(r['commits'] for r in rows),
'published_entry_lines': PUBLISHED_ENTRY_LINES,
'published_entries': PUBLISHED_ENTRIES,
'matches_published_lines': total == PUBLISHED_ENTRY_LINES,
'matches_published_entries': tot_e == PUBLISHED_ENTRIES,
'delta_lines': total - PUBLISHED_ENTRY_LINES,
'seconds': round(time.time() - t0, 1),
'command': 'python tools/clusters.py ' + ' '.join(sys.argv[1:])}
with open(os.path.join(a.out, 'belt-meta.json'), 'w', encoding='utf-8', newline='\n') as f:
json.dump(meta, f, indent=1, sort_keys=True)
print(json.dumps(meta, indent=1, sort_keys=True))
return 0
if __name__ == '__main__':
sys.exit(main())