# Ingot v1 packaging (Opus ยท Smelter, 2026-10-26): clean.py keepers -> Parquet configs tested / built / compiled, # plus std (Zig 0.17.0 standard library from the official ziglang.org tarball) and bench (Ingot-Bench v1). # One row per file. Every row carries its provenance and the exact gate it passed, so users can re-filter. import json, os, re, sys, hashlib, collections, posixpath, pyarrow as pa, pyarrow.parquet as pq S = '/work' I = os.path.join(S, 'ingot'); OUT = os.path.join(I, 'release') import subprocess ZIGBIN = os.environ.get('ZIG', os.path.join(S, 'zig', 'zig')) ZIG = subprocess.run([ZIGBIN, 'version'], capture_output=True, text=True).stdout.strip() # version comes from the toolchain used # license audit (2026-10-26): every repo's LICENSE text was re-classified independently of its scraped label DROP_REPOS = {'erenvly/plume', # GPL-3.0 text + GPL SPDX headers, label said MIT 'spiffyk/FruitsAndTails', # GPL text 'solenopsys/cruller', # Bun fork whose LICENSE defers to mixed upstream terms 'letoram/arcan', # mixed BSD/GPL/LGPL project, label said Zlib 'espra/espra'} # COPYING is a note, not a license (its UNLICENSE.md was not harvested) LABEL_FIX = {'ankane/dist-zig': 'MIT', 'nat3Github/zig-lib-audiocodec': 'BSD-3-Clause'} # text disagrees with label SPDX_RE = re.compile(r'SPDX-License-Identifier:\s*([^\n*]+)') def file_copyleft(text): """per-file drop: the header says the file is derived from / a port or transcription of GPL-family code (the two may sit on different lines, audit-2), or carries the Linux syscall-note (uapi transcriptions)""" head = '\n'.join(text.splitlines()[:120]) if 'Linux-syscall-note' in head: return True return bool(re.search(r'\b(port(ed)?|derived|based on|original(ly)?|translat(ed|ion)|adapt(ed|ation)|transcri\w*)\b.{0,300}?\b(A|L)?GPL', head, re.I | re.S) or re.search(r'\b(A|L)?GPL\b.{0,300}?\b(port(ed)?|derived|translat(ed|ion)|transcri\w*)\b', head, re.I | re.S)) PERMISSIVE_IDS = {'MIT', 'Apache-2.0', 'BSD-2-Clause', 'BSD-3-Clause', 'ISC', '0BSD', 'Zlib', 'Unlicense', 'CC0-1.0', 'MPL-2.0', 'UPL-1.0', 'BSL-1.0'} def file_license(text, repo_label): """the row's license from the file's own SPDX expression when it states one (more precise than the repo label). OR: keep the permissive alternatives ('MPL-2.0 OR GPL-2.0-only' -> 'MPL-2.0'); AND: an alternative is kept only if every part is permissive ('BSD-3-Clause AND MIT'). Returns None when the file states only non-permissive terms (GPL, CC-BY-SA, W3C, ...): the row is dropped.""" m = SPDX_RE.search('\n'.join(text.splitlines()[:40])) if not m: return repo_label expr = m.group(1).strip().rstrip('*/').strip() keep = [] for alt in re.split(r'\s+OR\s+', expr): parts = [x.strip(' ()') for x in re.split(r'\s+AND\s+', alt.strip(' ()'))] if parts and all(x in PERMISSIVE_IDS for x in parts): keep.append(' AND '.join(parts)) return ' OR '.join(keep) if keep else None COPYLEFT_TEXT = re.compile(r'GNU (LESSER |LIBRARY |AFFERO )?GENERAL PUBLIC LICENSE|Creative Commons Attribution-ShareAlike', re.I) SPDX = {'mit': 'MIT', 'apache-2.0': 'Apache-2.0', 'bsd-3-clause': 'BSD-3-Clause', 'bsd-2-clause': 'BSD-2-Clause', 'bsd': 'BSD-unspecified', 'unlicense': 'Unlicense', 'mpl-2.0': 'MPL-2.0', 'zlib': 'Zlib', 'isc': 'ISC', '0bsd': '0BSD', 'upl-1.0': 'UPL-1.0', 'cc0-1.0': 'CC0-1.0', 'isc-or-0bsd': 'ISC OR 0BSD'} VERIFY = {'tested': 'zig build && zig build test (repo root, Zig %s, x86_64-linux)' % ZIG, 'built': 'zig build (repo root, Zig %s, x86_64-linux)' % ZIG, 'compiled': 'zig test -lc -fno-emit-bin on a wrapper that references every pub decl of the file and of its nested container types (depth 3), with a canary error proving analysis ran; every repo file it imports must pass too (Zig %s, x86_64-linux; never executed)' % ZIG} repos = {r['repo']: r for r in map(json.loads, open(os.path.join(I, 'd3in_repos.jsonl')))} tier = {(f['dir'], f['path']): f['tier'] for f in map(json.loads, open(os.path.join(I, 'd3in_files.jsonl')))} lic_text = {} def license_of(d): if d not in lic_text: root = os.path.join(I, 'd3in', 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()) lic_text[d] = '\n\n'.join(t) return lic_text[d] IMP_RE = re.compile(r'@import\(\s*"([^"]+)"\s*,?\s*\)'); TEST_RE = re.compile(r'^\s*test\b[^\n{]*\{', re.M) def signals(text): """cheap per-file quality signals, so users can filter instead of trusting our thresholds""" L = text.splitlines() or ['']; code = [l for l in L if l.strip()] com = sum(1 for l in code if l.lstrip().startswith('//')) imps = set(IMP_RE.findall(text)) return dict(lines=len(L), max_line_len=max(len(l) for l in L), comment_frac=round(com / max(len(code), 1), 3), doc_comments=sum(1 for l in code if l.lstrip().startswith('///') or l.lstrip().startswith('//!')), n_tests=len(TEST_RE.findall(text)), pub_decls=len(re.findall(r'^\s*pub\s+(?:fn|const|var)\b', text, re.M)), imports=sorted(imps), std_only=not (imps - {'std', 'builtin', 'root'}) and not any(i.endswith('.zig') for i in imps)) rows = collections.defaultdict(list) for m in map(json.loads, open(os.path.join(I, 'd3out', 'manifest.jsonl'))): if m['verdict'] != 'keep': continue d, p = m['path'].split('/', 1); r = repos[d]; t = tier[(d, p)] if r['full'] in DROP_REPOS: continue if re.search(r'(^|/)compile_errors?[^/]*\.zig$', p): continue # files of code written to NOT compile (e.g. zefir tests/compile_errors.zig) lt = license_of(d) if not lt.strip(): continue # no license file in the tree: cannot prove the license, drop if COPYLEFT_TEXT.search(lt) and 'Mozilla Public License' not in lt: continue # audit-2: label said permissive, text is (L)GPL (andrewrk/ffmpeg) spdx = SPDX.get((r['license'] or '').lower(), r['license'] or '') if spdx == 'BSD-unspecified': # resolve from the license text itself 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', d, p), encoding='utf-8', errors='replace').read() if file_copyleft(text) or not text.strip(): continue spdx = file_license(text, spdx) if spdx is None: continue xc = sum(int(x) for x in re.findall(r'xrepo_(?:exact|near)_copies=(\d+)', m.get('reason_detail', ''))) rows[t].append(dict(text=text, host=r['host'], repo=r['full'], commit=r['commit'], path=p, license=spdx, license_text=lt, tier=t, verify=VERIFY[t], repo_tests=r.get('tests') or '', zig_version=ZIG, min_zig_declared=r.get('min_zig') or '', bytes=len(text.encode()), sha256=hashlib.sha256(text.encode()).hexdigest(), dropped_copies=xc, **signals(text))) # std: the standard library of the official Zig 0.17.0 release (MIT) zl = os.path.join(S, 'zig'); zlic = open(os.path.join(zl, 'LICENSE')).read() for a, _, fs in os.walk(os.path.join(zl, 'lib', 'std')): for f in sorted(fs): if not f.endswith('.zig'): continue p = os.path.join(a, f); b = open(p, 'rb').read() if not b.strip(): continue # 0-byte test stubs in the tarball rows['std'].append(dict(text=b.decode('utf-8', 'replace'), host='ziglang.org', repo='ziglang/zig', commit=ZIG, path=os.path.relpath(p, zl), license='MIT', license_text=zlic, tier='std', verify='official release tarball', repo_tests='', zig_version=ZIG, min_zig_declared='', bytes=len(b), sha256=hashlib.sha256(b).hexdigest(), dropped_copies=0, **signals(b.decode('utf-8', 'replace')))) # langref: the language reference examples, each re-checked against its own annotation (tools/langref_verify.py) LR = os.path.join(I, 'langref', 'langref.jsonl') if os.path.exists(LR): for x in map(json.loads, open(LR)): x.update(license_text=zlic, repo_tests='', min_zig_declared='', dropped_copies=0, **signals(x['text'])); rows['langref'].append(x) # whitespace-normalised copies of std / langref files inside repos are vendored copies (audit: 54 in compiled) _norm = lambda s: re.sub(r'\s+', ' ', s).strip() STDN = {_norm(x['text']) for x in rows['std'] + rows['langref']} REPO_CAP = 24_000_000 # bytes of text per repo per tier, so no single repo dominates a config (kept in path order) for tt in ('tested', 'built', 'compiled'): kept, used = [], collections.Counter() for x in sorted(rows[tt], key=lambda x: (x['host'], x['repo'], x['path'].count('/'), x['path'])): if _norm(x['text']) in STDN: continue if used[(x['host'], x['repo'])] + x['bytes'] > REPO_CAP: continue used[(x['host'], x['repo'])] += x['bytes']; kept.append(x) rows[tt] = kept seen_n = set() # final cross-tier dedup on whitespace-normalised text, priority tested > built > compiled for tt in ('tested', 'built', 'compiled'): kept = [] for x in rows[tt]: h = hashlib.sha256(_norm(x['text']).encode()).digest() if h in seen_n: continue seen_n.add(h); kept.append(x) rows[tt] = kept # ---- audit-3 rules (v1.3) ---- A3 = collections.Counter() # (5) one project mirrored on two hosts: keep the host contributing more rows (ties: tested > built > compiled, github) hosts = collections.defaultdict(collections.Counter) for tt in ('tested', 'built', 'compiled'): for x in rows[tt]: hosts[x['repo'].lower()][x['host']] += 1 keep_host = {k: max(c, key=lambda h: (c[h], h == 'github')) for k, c in hosts.items()} GEN_RE = re.compile(r'^\s*//[!/]*\s*(this (file|code|module) (is|was|has been) (automatically |auto-?)?generated|auto-?generated\b|code generated by|@generated\b|generated file\b)', re.I | re.M) GEN_ANY = re.compile(r'^\s*//[^\n]*auto-?generated[^\n]{0,60}(do not edit|modified at hand)', re.I | re.M) # a comment line, not a generator's string literal GEN_PATHS = re.compile(r'(^|/)(roc_platform_abi\.zig|zimplot\.zig|base58_vectors\.zig)$|ggml/quants/golden\.zig$|quant/tables\.zig$') # audit-3 hand list LIC_FAM = [('MIT', r'Permission is hereby granted, free of charge'), ('Apache-2.0', r'Apache License[\s\S]{0,40}Version 2\.0'), ('ISC', r'Permission to use, copy, modify, and(/or)? distribute this software for any purpose'), ('BSD-3-Clause', r'endorse or promote'), ('Zlib', r'altered source versions must be plainly marked')] def multi_license(lt, label): fams = [n for n, rx in LIC_FAM if re.search(rx, lt, re.I)] if 'BSD-3-Clause' in fams and 'ISC' in fams: fams.remove('ISC') return ' AND '.join(sorted(set(fams))) if len(set(fams)) > 1 and label in fams else label for tt in ('tested', 'built', 'compiled'): kept = [] for x in rows[tt]: if keep_host[x['repo'].lower()] != x['host']: A3['host-mirror'] += 1; continue if GEN_RE.search('\n'.join(x['text'].splitlines()[:12])) or GEN_ANY.search(x['text']) or GEN_PATHS.search(x['path']): A3['generated-marker'] += 1; continue # (2) a compiled file whose code imports a named build-graph module was never checked against that module if tt == 'compiled' and any(i not in ('std', 'builtin', 'root') and not i.endswith('.zig') and not i.endswith('.zon') for i in x['imports']): A3['named-module'] += 1; continue if not SPDX_RE.search('\n'.join(x['text'].splitlines()[:40])): x['license'] = multi_license(x['license_text'], x['license']) kept.append(x) rows[tt] = kept # (3) import closure again with the whitespace-tolerant regex, over the per-file gate's verdicts: every repo file a # compiled file imports (transitively) must have passed the gate itself (it may still be absent from the release, # e.g. deduplicated in favour of an identical copy elsewhere) import glob as _glob G = {} for f in _glob.glob(os.path.join(I, os.environ.get('D2S_DIR', 'd2s_v3'), '*.jsonl')): for l in open(f): v = json.loads(l); G[(v['dir'], v['path'])] = v['d2s'] def gate_ok(d, path, seen=None): seen = seen or set() if (d, path) in seen: return True seen.add((d, path)) if G.get((d, path)) != 'ok': return False try: txt = open(os.path.join(I, 'harvest', d, path), encoding='utf-8', errors='replace').read() except OSError: return False return all(gate_ok(d, posixpath.normpath(posixpath.join(posixpath.dirname(path), i)), seen) for i in IMP_RE.findall(txt) if i.endswith('.zig')) kept = [] for x in rows['compiled']: d = x['host'] + '__' + x['repo'].replace('/', '__') if gate_ok(d, x['path']): kept.append(x) else: A3['closure'] += 1 rows['compiled'] = kept # (4) vendored copies / forks across repos by content: sampled 6-line windows; a file >= 90% contained in a file of # another repo is dropped from the repo that vendors it (directory named like the other repo), else from the lower tier def wins(s): L = [l.strip() for l in s.splitlines() if l.strip()] import zlib # deterministic (Python's hash() is salted per run) 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} TIER_RANK = {'tested': 0, 'built': 1, 'compiled': 2} _M = json.load(open(os.path.join(I, 'repos_master.json'))) + (json.load(open(os.path.join(I, 'repos_round2.json'))) if os.path.exists(os.path.join(I, 'repos_round2.json')) else []) SRC_ORDER = {} for _i, _r in enumerate(_M): SRC_ORDER.setdefault((_r['host'], _r['repo']), _i) allx = [x for tt in ('tested', 'built', 'compiled') for x in rows[tt]] W_ = [wins(x['text']) for x in allx] inv = collections.defaultdict(list) for j, w in enumerate(W_): for h in w: inv[h].append(j) drop = set() for j, w in enumerate(W_): if len(w) < 8 or j in drop: continue c = collections.Counter(k for h in w for k in inv[h] if k != j and allx[k]['repo'] != allx[j]['repo']) for k, n in c.most_common(3): if n / len(w) < 0.9 or k in drop: continue a, b = allx[j], allx[k] def vendors(x, y): return any(seg.lower() in y['repo'].split('/')[-1].lower() or y['repo'].split('/')[-1].lower() in seg.lower() for seg in x['path'].split('/')[:-1] if len(seg) >= 4) # upstream heuristic: the vendoring repo loses; otherwise the repo that entered the source list later (curated # pools first, scouted forks/mirrors later) loses; then the lower tier loser = j if vendors(a, b) else k if vendors(b, a) else max((j, k), key=lambda q: (SRC_ORDER.get((allx[q]['host'], allx[q]['repo']), 10**6), TIER_RANK[allx[q]['tier']])) drop.add(loser); break A3['content-copy'] = len(drop) json.dump(sorted('%s %s %s' % (allx[q]['host'], allx[q]['repo'], allx[q]['path']) for q in drop), open(os.path.join(I, 'content_copy_drops.json'), 'w'), indent=0) dropped_ids = {id(allx[q]) for q in drop} for tt in ('tested', 'built', 'compiled'): rows[tt] = [x for x in rows[tt] if id(x) not in dropped_ids] del allx, W_, inv print('audit-3 drops', dict(A3)) # repo config: one document per repo, its kept files in dependency order (a file after the files it @imports), # each preceded by a path line, so cross-file context trains as it is read in the repo import posixpath def repo_docs(): by = collections.defaultdict(list) for tt in ('tested', 'built', 'compiled'): for x in rows[tt]: by[(x['host'], x['repo'])].append(x) for (h, rp), fs in sorted(by.items()): P = {x['path']: x for x in fs}; seen, order = set(), [] def visit(q, depth=0): if q in seen or depth > 200: return seen.add(q) for i in P[q]['imports']: if i.endswith('.zig'): d = posixpath.normpath(posixpath.join(posixpath.dirname(q), i)) if d in P: visit(d, depth + 1) order.append(q) for q in sorted(P): visit(q) body = ''.join('//@ingot-file %s\n%s%s' % (q, P[q]['text'], '' if P[q]['text'].endswith('\n') else '\n') for q in order) atoms = set() for q in order: l = P[q]['license'] atoms |= set(l.split(' AND ')) if ' OR ' not in l else {'(%s)' % l} doc_lic = ' AND '.join(sorted(atoms)) f0 = fs[0] yield dict(text=body, host=h, repo=rp, commit=f0['commit'], path='', license=doc_lic, license_text=f0['license_text'], tier='repo', verify='files from tiers ' + ','.join(sorted({x['tier'] for x in fs})), repo_tests=f0['repo_tests'], zig_version=ZIG, min_zig_declared=f0['min_zig_declared'], bytes=len(body.encode()), sha256=hashlib.sha256(body.encode()).hexdigest(), dropped_copies=0, files=order) stats = {} def write_config(t, it): """stream rows to Parquet in 2,000-row groups (the one-shot table OOM-killed the 7 GB VM)""" os.makedirs(os.path.join(OUT, 'data', t), exist_ok=True) path = os.path.join(OUT, 'data', t, 'train-00000-of-00001.parquet'); w = None; buf = [] n, nb, reps, lic = 0, 0, set(), collections.Counter() def flush(): nonlocal w, buf if not buf: return if w is not None: tab = pa.Table.from_pylist(buf, schema=w.schema) else: tab = pa.Table.from_pylist(buf) sch = pa.schema([pa.field(f.name, pa.list_(pa.string())) if f.name in ('imports', 'files') else pa.field(f.name, pa.string()) if pa.types.is_null(f.type) else f for f in tab.schema]) tab = tab.cast(sch) if w is None: w = pq.ParquetWriter(path, tab.schema, compression='zstd', use_dictionary=['host', 'repo', 'license', 'license_text', 'tier', 'verify', 'zig_version', 'commit']) w.write_table(tab); buf = [] for x in it: buf.append(x); n += 1; nb += x['bytes']; reps.add((x['host'], x['repo'])); lic[x['license']] += 1 if len(buf) >= 2000: flush() flush(); w and w.close() stats[t] = dict(files=n, repos=len(reps), MB=round(nb / 1e6, 1), licenses=dict(lic.most_common())) for t in [k for k in rows if k != 'repo']: rows[t].sort(key=lambda x: (x['host'], x['repo'], x['path'])); write_config(t, rows[t]) write_config('repo', repo_docs()) os.makedirs(os.path.join(OUT, 'bench'), exist_ok=True) with open(os.path.join(OUT, 'bench', 'ingot_bench_v1.jsonl'), 'w') as o: # same license rules as the training rows # audit 10-26 filters: tasks an empty body passes (bench/empty_graded.jsonl), trivial references (<30 non-space # chars), answers present verbatim in std/langref, and tasks whose source path the training-side rules exclude EMPTY_OK = {x['id'] for x in map(json.loads, open(os.path.join(I, 'bench', 'empty_graded.jsonl'))) if x['ok']} STDJ = '\n'.join(_norm(x['text']) for x in rows['std'] + rows['langref']) BAD_PATH = re.compile(r'(^|/)(compile_errors|test/cases|third_party|thirdparty|externals?|vendor)(/|$)') # as assemble_d3 (+vendor) GENERATED_TREES = {('github', 'cloudboss/aws-sdk-zig'): 'service/'} dropped = collections.Counter() UND = os.path.join(I, 'bench', 'undef_graded.jsonl') WEAK_UNDEF = {x['id'] for x in map(json.loads, open(UND)) if x['ok']} if os.path.exists(UND) else set() TEST_BLK = re.compile(r'^\s*test\s*("(?:[^"\\\n]|\\.)*"|\w+)?\s*\{', re.M) # audit-2: names may contain \" sys.path.insert(0, os.path.join(I, 'tools')); from bench_verify import match_brace import difflib FNB = re.compile(r'^\s*(?:pub\s+)?(?:inline\s+)?fn\s+\w+\s*\(', re.M) def bodies(s): out = [] for m in FNB.finditer(s): j = s.find('{', m.end()) k = match_brace(s, j) if j >= 0 else -1 if k > 0: out.append(s[j + 1:k]) return out def sibling_sim(b): ref = b['ref_body'] return max([difflib.SequenceMatcher(None, ref, x, autojunk=False).ratio() for x in bodies(b['prompt'] + b['suffix']) if abs(len(x) - len(ref)) < 0.5 * len(ref)] or [0.0]) def restrip(b): pre, suf = b['grader']['prefix'], b['grader']['suffix'] def strip(s): spans = [] for m in TEST_BLK.finditer(s): j = s.index('{', m.end() - 1); k = match_brace(s, j) if k > 0: spans.append((m.start(), k + 1)) o, i = [], 0 for x, y in spans: if x < i: continue o.append(s[i:x]); i = y o.append(s[i:]); return re.sub(r'\n{3,}', '\n\n', ''.join(o)) return strip(pre), strip(suf) for l in open(os.path.join(I, 'bench', 'ingot_bench_v1.jsonl')): b = json.loads(l); full = b['grader']['prefix'] + b['ref_body'] + b['grader']['suffix'] why = ('license' if b['repo'] in DROP_REPOS or file_copyleft(full) else 'empty-body-passes' if b['id'] in EMPTY_OK else 'trivial-ref' if len(re.sub(r'\s', '', b['ref_body'])) < 30 else 'answer-in-std' if len(_norm(b['ref_body'])) >= 60 and _norm(b['ref_body']) in STDJ else 'excluded-path' if BAD_PATH.search(b['path']) or (GENERATED_TREES.get((b['host'], b['repo'])) or '\0') and b['path'].startswith(GENERATED_TREES.get((b['host'], b['repo'])) or '\0') else None) if not why and b['id'] in WEAK_UNDEF: why = 'return-undefined-passes' if not why and sibling_sim(b) >= 0.90: why = 'near-copy-visible' if not why and file_license(full, 'x') is None: why = 'license' if why: dropped[why] += 1; continue b['prompt'], b['suffix'] = restrip(b) d = b['host'] + '__' + b['repo'].replace('/', '__') lab = LABEL_FIX.get(b['repo'], SPDX.get((b['license'] or '').lower(), b['license'])) b['license'] = file_license(full, lab); b['license_text'] = license_of(d) if os.path.isdir(os.path.join(I, 'd3in', d)) else '' o.write(json.dumps(b) + '\n') print('bench dropped', dict(dropped)) _B = [json.loads(l) for l in open(os.path.join(OUT, 'bench', 'ingot_bench_v1.jsonl'))] # Parquet copy for load_dataset(..., 'bench') pq.write_table(pa.Table.from_pylist(_B), os.path.join(OUT, 'bench', 'ingot_bench_v1.parquet'), compression='zstd') stats['bench'] = dict(tasks=len(_B)) json.dump(stats, open(os.path.join(OUT, 'stats.json'), 'w'), indent=1) print(json.dumps({k: {x: v[x] for x in v if x != 'licenses'} for k, v in stats.items()}, indent=1))