ingot-zig / tools /package_pools.py
ego0op's picture
Ingot v1.2: human Zig pushed 2026-10-15..11-28 (verified 187M -> 437M tokens); decontam vs zig.valid; misses fixed (see changelog)
ae6a9ee verified
Raw History Blame Contribute Delete
10.5 kB
# Ingot `ore` and `slag` pools (Opus · Smelter, 2026-10-26). Run after package.py (needs the released ingot tiers).
# ore : files of failed-build repos the per-file gate could NOT verify (env / unchecked / dep / timeout).
# Mostly modern Zig that needs a build-graph module or imports an unverified file. Not proven correct.
# slag : files the gate PROVED do not compile on this Zig (verdict fail), each with the compiler error. Mostly code
# for older Zig; meant for migration work (old -> new), not for plain next-token training.
# Same license / provenance / vendoring / generated / benchmark rules as the ingot tiers, plus: no row may duplicate
# (exactly, whitespace-normalised, or >= 90% contained) an ingot row or a row of the other pool.
import json, os, re, sys, hashlib, collections, zlib, pyarrow as pa, pyarrow.parquet as pq
S = '/work'
I = os.path.join(S, 'ingot'); OUT = os.path.join(I, 'release')
_pk = open(os.path.join(I, 'tools', 'package.py')).read() # reuse the exact license helpers
exec(_pk[_pk.index("DROP_REPOS = {"):_pk.index("VERIFY = {")])
exec(_pk[_pk.index("IMP_RE = re.compile"):_pk.index("rows = collections.defaultdict(list)")])
exec(_pk[_pk.index("GEN_RE = re.compile"):_pk.index("def multi_license")])
exec(_pk[_pk.index("def multi_license"):_pk.index("for tt in ('tested', 'built', 'compiled'):\n kept = []\n for x in rows[tt]:\n if keep_host")])
import subprocess
ZIG = subprocess.run([os.environ.get('ZIG', os.path.join(S, 'zig', 'zig')), 'version'], capture_output=True, text=True).stdout.strip()
_norm = lambda s: re.sub(r'\s+', ' ', s).strip()
_LT = {}
def lic_text(d):
if d in _LT: return _LT[d]
_LT[d] = sys.intern(_lic_text(d)); return _LT[d]
def _lic_text(d):
root = os.path.join(I, 'harvest', d); t = []
for f in sorted(os.listdir(root)):
if f.upper().startswith(('LICENSE', 'LICENCE', 'COPYING', 'UNLICENSE')) and os.path.isfile(os.path.join(root, f)):
t.append(open(os.path.join(root, f), encoding='utf-8', errors='replace').read())
return '\n\n'.join(t)
def wins(s):
L = [l.strip() for l in s.splitlines() if l.strip()]
return {h for h in (zlib.crc32('\n'.join(L[i:i + 6]).encode()) for i in range(max(len(L) - 5, 0))) if h % 4 == 0}
# reference set: every released ingot row (tiers + std + langref)
ref_norm, _H, _R = set(), [], [] # v1.2: window index as sorted numpy arrays (the dict of sets OOM-killed the 8 GB VM at 2x Ingot)
for t in ('tested', 'built', 'compiled', 'std', 'langref'):
for k, x in enumerate(pq.read_table(os.path.join(OUT, 'data', t, 'train-00000-of-00001.parquet'), columns=['text']).column('text').to_pylist()):
ref_norm.add(hashlib.sha256(_norm(x).encode()).digest())
for h in wins(x): _H.append(h); _R.append(len(ref_norm)) # row id: position of this row's entry (unique per Ingot row up to identical texts)
import numpy as _np
_H = _np.array(_H, dtype=_np.uint32); _R = _np.array(_R, dtype=_np.int32); _o = _np.argsort(_H, kind='stable'); _H, _R = _H[_o], _R[_o]; del _o
def _cnt(w): # per Ingot row, how many of this file's windows it shares; windows shared by > 5,000 rows are idioms and skipped (speed)
hs = _np.fromiter(w, dtype=_np.uint32, count=len(w)); a = _np.searchsorted(_H, hs, 'left'); b = _np.searchsorted(_H, hs, 'right')
m = (b - a) <= 5000; a, b = a[m], b[m]
if not len(a): return collections.Counter()
ids = _np.concatenate([_np.unique(_R[i:j]) for i, j in zip(a.tolist(), b.tolist()) if j > i]) if (b > a).any() else _np.array([], dtype=_np.int32)
if not len(ids): return collections.Counter()
u, n = _np.unique(ids, return_counts=True); k = n.argmax()
return collections.Counter({int(u[k]): int(n[k])})
REASON = collections.Counter()
INGOT_KEYS = {(h, r, p) for t in ('tested', 'built', 'compiled') for h, r, p in zip(*[pq.read_table(os.path.join(OUT, 'data', t, 'train-00000-of-00001.parquet'), columns=[c]).column(0).to_pylist() for c in ('host', 'repo', 'path')])}
KEEP_CLEAN = {'ore': {'keep'}, 'slag': {'keep', 'gate:ast-check', 'B:stale-std-ref'}} # slag is broken by definition
DESC = {'ore': "not verified: whole-repo build failed and the per-file check could not analyse this file (%s)",
'slag': "does not compile on Zig %s: %s"}
class _Sink: # v1.2: rows stream to Parquet as they are accepted (a list of all ore rows OOM-killed the 8 GB VM)
def __init__(s, pool):
s.pool, s.w, s.buf, s.keys, s.n, s.nb, s.reps, s.lic, s.gate = pool, None, [], set(), 0, 0, set(), collections.Counter(), collections.Counter()
os.makedirs(os.path.join(OUT, 'data', pool), exist_ok=True); s.path = os.path.join(OUT, 'data', pool, 'train-00000-of-00001.parquet')
def add(s, x):
s.buf.append(x); s.keys.add((x['host'], x['repo'], x['path'])); s.n += 1; s.nb += x['bytes']; s.reps.add((x['host'], x['repo'])); s.lic[x['license']] += 1; s.gate[x['gate']] += 1
if len(s.buf) >= 1000: s.flush()
def flush(s):
if not s.buf: return
if s.w is None:
tab = pa.Table.from_pylist(s.buf)
sch = pa.schema([pa.field(f.name, pa.list_(pa.string())) if f.name == 'imports' else pa.field(f.name, pa.string()) if pa.types.is_null(f.type) else f for f in tab.schema])
s.w = pq.ParquetWriter(s.path, sch, compression='zstd', use_dictionary=['host', 'repo', 'license', 'license_text', 'tier', 'zig_version', 'commit', 'gate'])
s.w.write_table(pa.Table.from_pylist(s.buf, schema=s.w.schema)); s.buf = []
def close(s): s.flush(); s.w and s.w.close()
pool_rows = {}
for pool in ('ore', 'slag'):
repos = {r['repo']: r for r in map(json.loads, open(os.path.join(I, 'd3in_%s_repos.jsonl' % pool)))}
meta = {(f['dir'], f['path']): f for f in map(json.loads, open(os.path.join(I, 'd3in_%s_files.jsonl' % pool)))}
out = _Sink(pool)
for m in map(json.loads, open(os.path.join(I, 'd3out_%s' % pool, 'manifest.jsonl'))):
if m['verdict'] not in KEEP_CLEAN[pool]: REASON[(pool, m['verdict'])] += 1; continue
d, p = m['path'].split('/', 1); r = repos[d]; f = meta[(d, p)]
if r['full'] in DROP_REPOS: REASON[(pool, 'license-repo')] += 1; continue
if re.search(r'(^|/)compile_errors?[^/]*\.zig$', p) and pool == 'ore': REASON[(pool, 'compile-errors-file')] += 1; continue
lt = lic_text(d)
if not lt.strip(): REASON[(pool, 'no-license')] += 1; continue
if COPYLEFT_TEXT.search(lt) and 'Mozilla Public License' not in lt: REASON[(pool, 'license-text')] += 1; continue
spdx = SPDX.get((r['license'] or '').lower(), r['license'] or '')
if spdx == 'BSD-unspecified':
spdx = 'BSD-3-Clause' if 'endorse or promote' in lt else 'BSD-2-Clause' if 'Redistributions in binary form' in lt else spdx
spdx = LABEL_FIX.get(r['full'], spdx)
text = open(os.path.join(I, 'd3in_%s' % pool, d, p), encoding='utf-8', errors='replace').read()
if not text.strip(): REASON[(pool, 'empty')] += 1; continue
if file_copyleft(text): REASON[(pool, 'license-file')] += 1; continue
lab = file_license(text, spdx)
if lab is None: REASON[(pool, 'license-file')] += 1; continue
if not SPDX_RE.search('\n'.join(text.splitlines()[:40])): lab = multi_license(lt, lab)
if GEN_RE.search('\n'.join(text.splitlines()[:12])) or GEN_ANY.search(text) or GEN_PATHS.search(p): REASON[(pool, 'generated')] += 1; continue
hn = hashlib.sha256(_norm(text).encode()).digest()
if hn in ref_norm: REASON[(pool, 'dup-of-ingot')] += 1; continue
w = wins(text)
if len(w) >= 8:
c = _cnt(w)
if c and c.most_common(1)[0][1] / len(w) >= 0.9: REASON[(pool, 'copy-of-ingot')] += 1; continue
why = f.get('gate_error') or f.get('d2s') or ''
if pool == 'slag' and m['verdict'] != 'keep': why = (m['verdict'] + ': ' + (m.get('reason_detail') or '')).strip()
out.add(dict(text=text, host=r['host'], repo=r['full'], commit=r['commit'], path=p, license=lab, license_text=lt,
tier=pool, verify=(DESC['ore'] % f.get('d2s')) if pool == 'ore' else (DESC['slag'] % (ZIG, why[:200])),
gate=f.get('d2s') or '', gate_error=why[:300], zig_version=ZIG, min_zig_declared=r.get('min_zig') or '',
bytes=len(text.encode()), sha256=hashlib.sha256(text.encode()).hexdigest(), dropped_copies=0, **signals(text)))
ref_norm.add(hn) # also dedups slag against ore (ore is built first)
if os.environ.get('V11_DIR'): # v1.2: carry the v1.1 pool rows forward unless decontaminated, superseded or now verified
V11X = {tuple(m['path'].split('/', 1)) for m in map(json.loads, open(os.path.join(I, 'd3out_%s' % pool, 'manifest_full.jsonl')))
if m['repo'].startswith('v11~') and m['verdict'] == 'eval:overlap'}
NEWK = out.keys | INGOT_KEYS
for x in (y for bt in pq.ParquetFile(os.path.join(os.environ['V11_DIR'], pool + '.parquet')).iter_batches(batch_size=1000) for y in bt.to_pylist()): # streamed: 8 GB VM
if ('v11~%s__%s' % (x['host'], x['repo'].replace('/', '__')), x['path']) in V11X: REASON[(pool, 'v11-eval-overlap')] += 1; continue
if (x['host'], x['repo'], x['path']) in NEWK: REASON[(pool, 'v11-superseded')] += 1; continue
hn = hashlib.sha256(_norm(x['text']).encode()).digest()
if hn in ref_norm: REASON[(pool, 'v11-dup-of-ingot')] += 1; continue
w = wins(x['text'])
if len(w) >= 8:
c = _cnt(w)
if c and c.most_common(1)[0][1] / len(w) >= 0.9: REASON[(pool, 'v11-copy-of-ingot')] += 1; continue
for k_ in ('license_text', 'verify', 'license', 'host', 'repo', 'commit', 'zig_version', 'tier', 'gate'): x[k_] = sys.intern(x[k_] or '')
ref_norm.add(hn); out.add(x); REASON[(pool, 'v11-kept')] += 1
out.close(); pool_rows[pool] = out
stats = json.load(open(os.path.join(OUT, 'stats.json')))
for pool, R in pool_rows.items():
stats[pool] = dict(files=R.n, repos=len(R.reps), MB=round(R.nb / 1e6, 1), licenses=dict(R.lic.most_common()), gate=dict(R.gate.most_common()))
json.dump(stats, open(os.path.join(OUT, 'stats.json'), 'w'), indent=1)
print('dropped', {('%s %s' % k): v for k, v in sorted(REASON.items())})
print({p: {k: v for k, v in stats[p].items() if k not in ('licenses',)} for p in pool_rows})