| #!/usr/bin/env python3 | |
| """Stream method_change rows of a CVEfixes-schema dump straight into staged code_sample rows (no full DB on disk). | |
| CVEfixes: SQLite text dump (INSERT INTO method_change VALUES(...)) inside the Zenodo zip | |
| MoreFixes: PostgreSQL plain dump (COPY method_change (...) FROM stdin) | |
| Metadata (fixes / commits / file_change without code blobs) comes from a small SQLite DB built beforehand | |
| (cvefixes: salvaged from load_cvefixes_sqlite.py; morefixes: load_morefixes_pg.py with method_change skipped). | |
| Label rules: before_change='True' -> pre-fix function (is_vulnerable, pair_role=vuln); 'False' -> post-fix (pair_role=fix); paired | |
| by signature within a file_change. label_source=nvd_patch_commit, conf 0.65/0.60, -0.30 test/vendor/minified, MoreFixes -0.25 if | |
| fixes.score < 65; the +0.05 single-function-commit bonus is applied in build_code_tier.py (needs the whole commit). | |
| Usage: ingest_fixdb_stream.py <source> <meta.db> <tag> <license> sqlinsert <zip> <member> | pgcopy <dump.sql.gz>""" | |
| import sys, os, re, io, json, gzip, zipfile, sqlite3, collections, multiprocessing as mp, time | |
| sys.path.insert(0, os.path.dirname(__file__)); import codecommon as C | |
| SRC, META, TAG, LIC, FMT = sys.argv[1:6]; ARGS = sys.argv[6:] | |
| def lookups(): | |
| con = sqlite3.connect(META) | |
| fcols = [r[1] for r in con.execute("PRAGMA table_info(fixes)")] | |
| fx = collections.defaultdict(lambda: {"cves": set(), "repos": set(), "score": None}) | |
| for row in con.execute(f"SELECT hash, cve_id, repo_url{', score' if 'score' in fcols else ''} FROM fixes"): | |
| d = fx[row[0]]; d["cves"].add(row[1]); d["repos"].add(row[2]) | |
| if len(row) > 3 and row[3] not in (None, ""): | |
| try: d["score"] = max(float(row[3]), d["score"] if d["score"] is not None else -1e9) | |
| except ValueError: pass | |
| fx = {k: {"cves": sorted(c for c in v["cves"] if c), "repos": sorted(x for x in v["repos"] if x), "score": v["score"]} for k, v in fx.items()} | |
| ccols = [r[1] for r in con.execute("PRAGMA table_info(commits)")] | |
| dcol = "author_date" if "author_date" in ccols else "committer_date" | |
| cdate = {h: (str(d)[:10] if d else None) for h, d in con.execute(f"SELECT hash, {dcol} FROM commits")} | |
| fc = {} | |
| for r in con.execute("SELECT file_change_id, hash, filename, old_path, new_path, programming_language FROM file_change_slim"): | |
| fc[str(r[0])] = r[1:] | |
| cwe = collections.defaultdict(set) | |
| if con.execute("select count(*) from sqlite_master where name='cwe_classification'").fetchone()[0]: | |
| for cve, cw in con.execute("SELECT cve_id, cwe_id FROM cwe_classification"): cwe[cve].add(cw) | |
| return fx, cdate, fc, {k: sorted(v) for k, v in cwe.items()} | |
| def init(): | |
| global LK; LK = lookups() | |
| def work(wi, rows): | |
| fx, cdate, fcm, cwe = LK | |
| w = C.StageWriter(SRC, worker=wi, clear=False, chunk=10000) | |
| by_fc = collections.defaultdict(list) | |
| for r in rows: by_fc[str(r["file_change_id"])].append(r) | |
| for fcid, rs in by_fc.items(): | |
| f = fcm.get(fcid) | |
| if not f: continue | |
| h, filename, old, new, plang = f | |
| meta = fx.get(h, {"cves": [], "repos": [], "score": None}) | |
| path = new if new not in (None, "None", "") else (old if old not in (None, "None", "") else filename) | |
| lang, detail, _ = C.lang_from_path(path or "") | |
| if lang == "other": lang = C.lang_from_name(plang) | |
| repo = meta["repos"][0] if meta["repos"] else None | |
| cw = sorted({c for cve in meta["cves"] for c in cwe.get(cve, [])}) | |
| groups = collections.defaultdict(dict) | |
| for r in rs: | |
| kind = "before" if str(r["before_change"]).lower() in ("true", "1", "t") else "after" | |
| groups[r.get("signature") or r.get("name")][kind] = r | |
| for key, g in groups.items(): | |
| pid = C.sha256(f"{TAG}:{fcid}:{key}")[:32] | |
| for kind, r in g.items(): | |
| vul = kind == "before"; role = "vuln" if vul else "fix" | |
| conf = C.confidence("nvd_patch_commit", role, path, morefixes_score=meta["score"] if SRC == "morefixes" else None) | |
| def ival(x): | |
| try: return int(x) | |
| except (TypeError, ValueError): return None | |
| w.add(language=lang, language_detail=detail, code=r.get("code"), project=C.project_from_repo(repo), repo_url=repo, commit_sha=h, | |
| commit_date=cdate.get(h), file_path=path, func_name=r.get("name"), start_line=ival(r.get("start_line")), end_line=ival(r.get("end_line")), | |
| is_vulnerable=vul, pair_id=pid, pair_role=role, cve_ids=meta["cves"], cwe_ids=C.cwes(cw), label_source="nvd_patch_commit", | |
| label_confidence=conf, origin={"dataset": TAG, "original_id": f"method_change:{r.get('method_change_id')}", "original_label": f"before_change={r.get('before_change')}"}, | |
| source_dataset=SRC, source_license=LIC, publishable_code=True, source_split=None, | |
| extra=json.dumps({"fix_score": meta["score"]}) if meta["score"] is not None else None) | |
| return w.close() | |
| def stream_sqlinsert(zp, member): | |
| f = io.TextIOWrapper(gzip.GzipFile(fileobj=zipfile.ZipFile(zp).open(member)), encoding="utf-8", errors="replace") | |
| mem = sqlite3.connect(":memory:"); cols = None; buf = []; pend = 0; started = False; blen = 0; skipped = 0; resync = False; pbytes = 0 | |
| for line in f: | |
| if not started: | |
| if line.startswith('CREATE TABLE IF NOT EXISTS "method_change"') or line.startswith("CREATE TABLE method_change"): started = "create" | |
| elif not line.startswith("INSERT INTO method_change"): continue | |
| buf.append(line); blen += len(line) | |
| if blen > 600_000: # a single >1.5 MB method row (code > MAX_CODE_CHARS anyway): drop it, resync on the next INSERT line | |
| skipped += 1; buf = []; blen = 0; resync = True; continue | |
| if resync: | |
| if line.startswith("INSERT INTO method_change"): resync = False; buf = [line]; blen = len(line) | |
| else: buf = []; blen = 0; continue | |
| if not line.rstrip().endswith(";"): continue | |
| stmt = "".join(buf) | |
| if not sqlite3.complete_statement(stmt): continue | |
| buf = []; blen = 0 | |
| s = stmt.lstrip() | |
| if s.startswith("CREATE TABLE"): | |
| mem.execute(s.replace("IF NOT EXISTS ", "")); cols = [r[1] for r in mem.execute("PRAGMA table_info(method_change)")]; started = True; continue | |
| if not s.startswith("INSERT INTO method_change"): | |
| if pend: yield from drain(mem, cols); pend = 0 | |
| if s.startswith("INSERT INTO") or s.startswith("CREATE"): break # method_change block finished | |
| continue | |
| mem.execute(s); pend += 1; pbytes += len(s) | |
| if pend >= 3000 or pbytes > 40_000_000: yield from drain(mem, cols); pend = 0; pbytes = 0 | |
| if pend: yield from drain(mem, cols) | |
| print("giant statements skipped:", skipped, flush=True) | |
| def drain(mem, cols): | |
| rows = [dict(zip(cols, r)) for r in mem.execute(f"SELECT * FROM method_change WHERE length(code) <= {C.MAX_CODE_CHARS}")] | |
| mem.execute("DELETE FROM method_change"); yield from rows | |
| ESC = re.compile(r"\\(?:([btnrfv\\])|([0-7]{1,3})|x([0-9a-fA-F]{1,2}))") | |
| MAP = {"b": "\b", "t": "\t", "n": "\n", "r": "\r", "f": "\f", "v": "\v", "\\": "\\"} | |
| def unesc(s): | |
| if s == r"\N": return None | |
| if "\\" not in s: return s | |
| return ESC.sub(lambda m: MAP[m.group(1)] if m.group(1) else chr(int(m.group(2), 8)) if m.group(2) else chr(int(m.group(3), 16)), s) | |
| def stream_pgcopy(path): | |
| cols = None | |
| with gzip.open(path, "rt", encoding="utf-8", errors="replace", newline="\n") as f: | |
| for line in f: | |
| if cols is None: | |
| m = re.match(r"^COPY (?:public\.)?\"?method_change\"? \((.*)\) FROM stdin;", line) | |
| if m: cols = [c.strip().strip('"') for c in m.group(1).split(",")] | |
| continue | |
| if line.rstrip("\r\n") == "\\.": return | |
| if len(line) > 2 * C.MAX_CODE_CHARS: continue | |
| yield dict(zip(cols, (unesc(p) for p in line.rstrip("\r\n").split("\t")))) | |
| def batches(it, n=4000): | |
| """group consecutive rows; never split a file_change across batches""" | |
| b = []; last = None; size = 0 | |
| for r in it: | |
| fc = str(r["file_change_id"]) | |
| if (len(b) >= n or size > 25_000_000) and fc != last: yield b; b = []; size = 0 | |
| b.append(r); last = fc; size += len(r.get("code") or "") | |
| if b: yield b | |
| if __name__ == "__main__": | |
| t0 = time.time(); C.clear_stage(SRC) | |
| it = stream_sqlinsert(*ARGS) if FMT == "sqlinsert" else stream_pgcopy(*ARGS) | |
| n = 0 | |
| with mp.Pool(4, initializer=init) as p: | |
| pending = collections.deque() | |
| for i, b in enumerate(batches(it)): | |
| pending.append(p.apply_async(work, (i, b))) | |
| while len(pending) > 6: n += pending.popleft().get() # backpressure: <= 10 batches in flight | |
| if i % 20 == 0: | |
| import resource | |
| print(f"batch {i} rows_done {n} {time.time()-t0:.0f}s maxrss={resource.getrusage(resource.RUSAGE_SELF).ru_maxrss//1024}MB", flush=True) | |
| while pending: n += pending.popleft().get() | |
| print(f"[{SRC}] total rows {n} in {time.time()-t0:.0f}s", flush=True) | |
Xet Storage Details
- Size:
- 9.26 kB
- Xet hash:
- b79dc3d860b5335d360f98b4b22660a2f0afa10050ca6a0ea7ff2e048a424d9c
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.