| """Shared helpers for the code tier (Stage 2-3): language detection, tree-sitter function splitting, | |
| normalisation + content hashing, MinHash signatures, label-confidence rules, and the staged `code_sample` writer.""" | |
| import hashlib, os, re, json, functools | |
| import numpy as np, pyarrow as pa, pyarrow.parquet as pq, xxhash | |
| ROOT = "/workspace/security-dataset" | |
| STAGE = f"{ROOT}/work/stage" # per-source staged rows (local) | |
| DATA = f"{ROOT}/data" # bucket mirror | |
| # ---------------------------------------------------------------- languages | |
| EXT = { # extension -> (partition language, language_detail, tree-sitter grammar) | |
| "c": ("c_cpp", "c", "c"), "h": ("c_cpp", "c_or_cpp_header", "cpp"), "cc": ("c_cpp", "cpp", "cpp"), "cpp": ("c_cpp", "cpp", "cpp"), | |
| "cxx": ("c_cpp", "cpp", "cpp"), "hpp": ("c_cpp", "cpp", "cpp"), "hh": ("c_cpp", "cpp", "cpp"), "hxx": ("c_cpp", "cpp", "cpp"), "c++": ("c_cpp", "cpp", "cpp"), | |
| "java": ("java", "java", "java"), "py": ("python", "python", "python"), "js": ("javascript", "javascript", "javascript"), | |
| "jsx": ("javascript", "javascript", "javascript"), "mjs": ("javascript", "javascript", "javascript"), "cjs": ("javascript", "javascript", "javascript"), | |
| "ts": ("typescript", "typescript", "typescript"), "tsx": ("typescript", "tsx", "tsx"), | |
| "php": ("php", "php", "php"), "phpt": ("php", "php", "php"), "inc": ("php", "php", "php"), "phtml": ("php", "php", "php"), | |
| "go": ("go", "go", "go"), "rb": ("ruby", "ruby", "ruby"), "cs": ("csharp", "csharp", "csharp"), "rs": ("rust", "rust", "rust"), | |
| "kt": ("kotlin", "kotlin", "kotlin"), "scala": ("scala", "scala", "scala"), "swift": ("swift", "swift", "swift"), | |
| "m": ("objc", "objc", "objc"), "mm": ("objc", "objcpp", "objc"), "pl": ("perl", "perl", None), "pm": ("perl", "perl", None), | |
| "lua": ("lua", "lua", "lua"), "sh": ("shell", "bash", "bash"), "erl": ("erlang", "erlang", None), "ex": ("elixir", "elixir", "elixir"), | |
| "exs": ("elixir", "elixir", "elixir"), "groovy": ("groovy", "groovy", None), "dart": ("dart", "dart", None), | |
| } | |
| LANG_NAME = { # dataset-provided language names -> partition language | |
| "c": "c_cpp", "c++": "c_cpp", "cpp": "c_cpp", "c/c++": "c_cpp", "java": "java", "python": "python", "javascript": "javascript", | |
| "typescript": "typescript", "php": "php", "go": "go", "ruby": "ruby", "c#": "csharp", "csharp": "csharp", "rust": "rust", | |
| "kotlin": "kotlin", "scala": "scala", "swift": "swift", "objective-c": "objc", "perl": "perl", "lua": "lua", "shell": "shell", | |
| "erlang": "erlang", "elixir": "elixir", "groovy": "groovy", "dart": "dart", "markdown": "other", "html": "other", | |
| } | |
| GRAMMAR = {"c_cpp": "cpp", "java": "java", "python": "python", "javascript": "javascript", "typescript": "typescript", "php": "php", | |
| "go": "go", "ruby": "ruby", "csharp": "csharp", "rust": "rust", "kotlin": "kotlin", "scala": "scala", "swift": "swift", | |
| "objc": "objc", "lua": "lua", "shell": "bash", "elixir": "elixir"} | |
| def lang_from_path(path): | |
| ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path or "") else "" | |
| return EXT.get(ext, ("other", ext or "unknown", None)) | |
| def lang_from_name(name): | |
| return LANG_NAME.get((name or "").strip().lower(), "other") | |
| def parser(grammar): | |
| from tree_sitter_language_pack import get_parser | |
| try: return get_parser(grammar) | |
| except Exception: return None | |
| # ---------------------------------------------------------------- function splitting (tree-sitter) | |
| FUNC_TYPES = { | |
| "cpp": {"function_definition"}, "c": {"function_definition"}, | |
| "java": {"method_declaration", "constructor_declaration"}, | |
| "python": {"function_definition"}, | |
| "javascript": {"function_declaration", "method_definition", "generator_function_declaration"}, | |
| "typescript": {"function_declaration", "method_definition", "generator_function_declaration"}, | |
| "tsx": {"function_declaration", "method_definition"}, | |
| "php": {"function_definition", "method_declaration"}, | |
| "go": {"function_declaration", "method_declaration"}, | |
| "ruby": {"method", "singleton_method"}, | |
| "csharp": {"method_declaration", "constructor_declaration", "local_function_statement"}, | |
| "rust": {"function_item"}, "kotlin": {"function_declaration"}, "scala": {"function_definition"}, | |
| "swift": {"function_declaration"}, "objc": {"function_definition", "method_definition"}, "lua": {"function_declaration"}, | |
| "bash": {"function_definition"}, "elixir": set(), | |
| } | |
| def _func_name(node, src): | |
| n = node.child_by_field_name("name") | |
| if n is None: | |
| d = node.child_by_field_name("declarator") | |
| while d is not None and d.type not in ("identifier", "field_identifier", "qualified_identifier", "operator_name", "destructor_name"): | |
| nd = d.child_by_field_name("declarator") | |
| if nd is None: | |
| ids = [c for c in d.children if c.type in ("identifier", "field_identifier", "qualified_identifier", "destructor_name", "operator_name")] | |
| d = ids[0] if ids else None; break | |
| d = nd | |
| n = d | |
| return src[n.start_byte:n.end_byte].decode("utf-8", "replace") if n is not None else None | |
| def split_functions(code, grammar, max_bytes=2_000_000): | |
| """Return [(func_name, start_line(1-based), end_line, code)] for top-level and nested function/method definitions.""" | |
| src = code.encode("utf-8", "replace") if isinstance(code, str) else code | |
| if len(src) > max_bytes: return [] | |
| p = parser(grammar) | |
| if p is None: return [] | |
| tree = p.parse(src) | |
| types = FUNC_TYPES.get(grammar, set()); out = [] | |
| stack = [tree.root_node] | |
| while stack: | |
| node = stack.pop() | |
| if node.type in types: | |
| out.append((_func_name(node, src), node.start_point[0] + 1, node.end_point[0] + 1, | |
| src[node.start_byte:node.end_byte].decode("utf-8", "replace"))) | |
| if grammar not in ("javascript", "typescript", "tsx", "rust", "go", "scala", "kotlin", "swift", "ruby"): | |
| continue # C/C++/Java/PHP/C#: don't descend into function bodies | |
| stack.extend(reversed(node.children)) | |
| out.sort(key=lambda r: r[1]) | |
| return out | |
| # ---------------------------------------------------------------- normalisation + hashing | |
| _C_COMMENT = re.compile(r'//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S) | |
| _HASH_COMMENT = re.compile(r'#[^\n]*|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'') | |
| _PY_DOC = re.compile(r'"""(?:.|\n)*?"""|\'\'\'(?:.|\n)*?\'\'\'') | |
| _WS = re.compile(r"\s+") | |
| HASH_STYLE = {"python": "hash", "ruby": "hash", "perl": "hash", "shell": "hash", "elixir": "hash"} | |
| def strip_comments(code, language): | |
| if language == "python": code = _PY_DOC.sub(" ", code) | |
| if language == "php": # PHP has //, /* */ and # | |
| code = _C_COMMENT.sub(lambda m: m.group(0) if m.group(0)[0] in "\"'" else " ", code) | |
| return re.sub(r'(?m)^\s*#[^\n]*', " ", code) | |
| rx = _HASH_COMMENT if HASH_STYLE.get(language) else _C_COMMENT | |
| return rx.sub(lambda m: m.group(0) if m.group(0)[0] in "\"'" else " ", code) | |
| def normalize(code, language): | |
| """Comments stripped (string-literal aware), all whitespace runs collapsed to one space, trimmed. | |
| Identifiers are NOT renamed (kept simple and reversible-free).""" | |
| return _WS.sub(" ", strip_comments(code or "", language)).strip() | |
| def sha256(s): return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest() | |
| # ---------------------------------------------------------------- MinHash (token 5-grams, 128 perms) | |
| NUM_PERM, SHINGLE = 128, 5 | |
| BANDS, ROWS = 16, 8 # P(candidate | J=0.8) ~= 0.9996 ; P(candidate | J=0.5) ~= 0.06 ; edges are then verified on full signatures | |
| # Hash family: h_i(x) = splitmix64(x XOR seed_i) (a strong 64-bit mixer; wrap-around uint64 arithmetic), low 32 bits kept. | |
| # (v1 used (a*x+b) mod 2^61-1 with a<2^29, x<2^32, which never wraps -> order-preserving -> degenerate signatures; fixed 2026-10-03.) | |
| _rng = np.random.RandomState(20261003) | |
| _SEED = _rng.randint(0, 1 << 62, size=NUM_PERM, dtype=np.int64).astype(np.uint64) | |
| _M1, _M2 = np.uint64(0xBF58476D1CE4E5B9), np.uint64(0x94D049BB133111EB) | |
| _S30, _S27, _S31 = np.uint64(30), np.uint64(27), np.uint64(31) | |
| _TOK = re.compile(r"\w+|[^\w\s]") | |
| _MAXSH = 20000 | |
| MINHASH_VERSION = 2 | |
| def _mix(v): | |
| v = v ^ (v >> _S30); v = v * _M1 | |
| v = v ^ (v >> _S27); v = v * _M2 | |
| return v ^ (v >> _S31) | |
| def minhash(norm): | |
| toks = _TOK.findall(norm[:400_000])[:60_000] | |
| if not toks: toks = [""] | |
| th = np.fromiter((xxhash.xxh32_intdigest(t.encode()) for t in toks), dtype=np.uint64, count=len(toks)) | |
| if len(th) >= SHINGLE: | |
| sh = np.zeros(len(th) - SHINGLE + 1, dtype=np.uint64) | |
| for k in range(SHINGLE): | |
| sh = sh * np.uint64(1000003) + th[k:len(th) - SHINGLE + 1 + k] # wraps mod 2^64 (intended) | |
| else: | |
| sh = np.array([xxhash.xxh64_intdigest(" ".join(toks).encode())], dtype=np.uint64) | |
| sh = _mix(np.unique(sh)) | |
| if len(sh) > _MAXSH: sh = np.sort(sh)[:_MAXSH] # bottom-k of the mixed values (unbiased, unlike first-k) | |
| with np.errstate(over="ignore"): | |
| v = _mix(sh[:, None] ^ _SEED[None, :]) | |
| return (v.min(axis=0) & np.uint64(0xFFFFFFFF)).astype(np.uint32) | |
| def bands(sig): | |
| b = sig.reshape(BANDS, ROWS) | |
| return [xxhash.xxh64_intdigest(b[i].tobytes()) - (1 << 63) for i in range(BANDS)] | |
| # ---------------------------------------------------------------- label-confidence rules (PLAN.md Stage 2.4) | |
| _TESTVENDOR = re.compile(r"(^|/)(tests?|testing|spec|__tests__|testdata|fixtures?|vendor|third[_-]?party|node_modules|external|deps)(/|$)|" | |
| r"(_test\.(go|py|c|cc|cpp)$)|(^|/)test_[^/]*\.py$|Test\.java$|\.min\.js$|\.min\.css$", re.I) | |
| def path_is_test_vendor_min(path): return bool(path and _TESTVENDOR.search(path)) | |
| CONF = { # (label_source, pair_role) -> confidence | |
| ("prime_vul", "vuln"): 0.90, ("prime_vul", "fix"): 0.85, ("prime_vul", "unrelated_in_commit"): 0.70, ("prime_vul", None): 0.70, | |
| ("nvd_patch_commit", "vuln"): 0.65, ("nvd_patch_commit", "fix"): 0.60, ("nvd_patch_commit", "unrelated_in_commit"): 0.50, | |
| ("diversevul_commit", "vuln"): 0.60, ("diversevul_commit", None): 0.50, | |
| ("static_analyzer", "vuln"): 0.35, ("static_analyzer", None): 0.30, | |
| ("synthetic", "vuln"): 1.0, ("synthetic", "fix"): 1.0, | |
| ("manual_commit_review", "vuln"): 0.80, ("manual_commit_review", None): 0.75, # Devign (manual labelling) | |
| ("llm_heuristic", "vuln"): 0.70, ("llm_heuristic", "fix"): 0.65, | |
| } | |
| def confidence(label_source, pair_role, path=None, single_func_commit=False, morefixes_score=None): | |
| c = CONF.get((label_source, pair_role), CONF.get((label_source, None), 0.5)) | |
| if label_source == "nvd_patch_commit": | |
| if single_func_commit and pair_role == "vuln": c += 0.05 # one-function fix (PrimeVul's strongest signal) | |
| if morefixes_score is not None and morefixes_score < 65: c -= 0.25 # MoreFixes says < 65 is noisy | |
| if path_is_test_vendor_min(path): c -= 0.30 # CleanVul-style test/vendor/minified down-weight | |
| return round(max(0.05, min(c, 1.0)), 3) | |
| # ---------------------------------------------------------------- staged schema | |
| ORIGIN_T = pa.struct([("dataset", pa.string()), ("original_id", pa.string()), ("original_label", pa.string())]) | |
| SCHEMA = pa.schema([ | |
| ("sample_id", pa.string()), ("language", pa.string()), ("language_detail", pa.string()), ("granularity", pa.string()), | |
| ("code", pa.string()), ("code_normalized_hash", pa.string()), ("code_sha256", pa.string()), | |
| ("project", pa.string()), ("repo_url", pa.string()), ("commit_sha", pa.string()), ("commit_date", pa.string()), | |
| ("file_path", pa.string()), ("func_name", pa.string()), ("start_line", pa.int32()), ("end_line", pa.int32()), | |
| ("is_vulnerable", pa.bool_()), ("vuln_lines", pa.list_(pa.int32())), | |
| ("pair_id", pa.string()), ("pair_role", pa.string()), | |
| ("cve_ids", pa.list_(pa.string())), ("cwe_ids", pa.list_(pa.string())), | |
| ("label_source", pa.string()), ("label_confidence", pa.float32()), | |
| ("origin", ORIGIN_T), ("source_dataset", pa.string()), ("source_license", pa.string()), ("publishable_code", pa.bool_()), | |
| ("source_split", pa.string()), ("extra", pa.string()), | |
| ]) | |
| MAX_CODE_CHARS = 100_000 | |
| BAND_SCHEMA = pa.schema([("sample_id", pa.string())] + [(f"b{i}", pa.int64()) for i in range(BANDS)]) | |
| CWE_RX = re.compile(r"CWE-?(\d+)", re.I); CVE_RX = re.compile(r"CVE-\d{4}-\d{4,}", re.I) | |
| def cwes(x): | |
| if x is None: return [] | |
| if isinstance(x, (list, tuple)): x = " ".join(map(str, x)) | |
| return sorted({f"CWE-{m}" for m in CWE_RX.findall(str(x))}) | |
| def cves(x): | |
| if x is None: return [] | |
| if isinstance(x, (list, tuple)): x = " ".join(map(str, x)) | |
| return sorted({m.upper() for m in CVE_RX.findall(str(x))}) | |
| def project_from_repo(url): | |
| if not url: return None | |
| u = url.lower().rstrip("/").removesuffix(".git") | |
| m = re.search(r"(github\.com|gitlab\.com|bitbucket\.org)/([^/]+/[^/]+)", u) | |
| return m.group(2) if m else u.split("://")[-1] | |
| class StageWriter: | |
| """Writes staged rows + MinHash band hashes + raw signatures for one source, in row groups.""" | |
| def __init__(self, source, chunk=20000, worker=None, clear=True): | |
| self.dir = f"{STAGE}/{source}"; os.makedirs(self.dir, exist_ok=True) | |
| if clear: | |
| for f in os.listdir(self.dir): os.remove(f"{self.dir}/{f}") | |
| self.tag = "" if worker is None else f"w{worker:02d}-" | |
| self.rows, self.chunk, self.part, self.n, self.too_big, self.bytes = [], chunk, 0, 0, 0, 0 | |
| self.sig_cache = {} | |
| def add(self, **r): | |
| lang = r["language"]; code = r["code"] or "" | |
| if len(code) > MAX_CODE_CHARS: self.too_big += 1; return False # generated / vendored blobs (>100k chars) are dropped | |
| if len(code) > 3000 and code.count("\n") * 400 < len(code): self.too_big += 1; return False # minified (avg line > 400 chars) | |
| norm = normalize(code, lang) | |
| if len(norm) < 10: return False # empty / trivial bodies are dropped | |
| r["sample_id"] = r["code_normalized_hash"] = sha256(norm) | |
| r["code_sha256"] = sha256(code) | |
| r.setdefault("granularity", "function") | |
| for k in SCHEMA.names: r.setdefault(k, None) | |
| for k in ("cve_ids", "cwe_ids", "vuln_lines"): r[k] = r[k] or [] | |
| r["_norm"] = norm | |
| if not r.get("publishable_code"): r["code"] = None # restricted sources: keep only hashes/IDs/labels (never stored) | |
| self.rows.append(r); self.n += 1; self.bytes += len(code) + len(norm) | |
| if len(self.rows) >= self.chunk or self.bytes > 150_000_000: self.flush() | |
| return True | |
| def flush(self): | |
| if not self.rows: return | |
| tbl = pa.Table.from_pylist([{k: r[k] for k in SCHEMA.names} for r in self.rows], schema=SCHEMA) | |
| pq.write_table(tbl, f"{self.dir}/part-{self.tag}{self.part:05d}.parquet", compression="zstd") | |
| seen = {}; bl = []; sigs = [] | |
| for r in self.rows: | |
| sid = r["sample_id"] | |
| if sid in seen or sid in self.sig_cache: continue | |
| sig = minhash(r["_norm"]); seen[sid] = 1; self.sig_cache[sid] = 1 | |
| bl.append([sid] + bands(sig)); sigs.append(sig) | |
| if bl: | |
| cols = list(zip(*bl)) | |
| pq.write_table(pa.table({n: pa.array(c, type=t.type) for n, c, t in zip(BAND_SCHEMA.names, cols, BAND_SCHEMA)}), | |
| f"{self.dir}/bands-{self.tag}{self.part:05d}.parquet", compression="zstd") | |
| np.save(f"{self.dir}/sigs-{self.tag}{self.part:05d}.npy", np.stack(sigs)) | |
| self.part += 1; self.rows = []; self.bytes = 0 | |
| def close(self): | |
| self.flush(); print(f"[stage] {self.dir}: {self.n} rows, {self.part} parts, {self.too_big} too-big dropped", flush=True); return self.n | |
| def clear_stage(source): | |
| d = f"{STAGE}/{source}"; os.makedirs(d, exist_ok=True) | |
| for f in os.listdir(d): os.remove(f"{d}/{f}") | |
| def run_pool(source, tasks, fn, procs=7): | |
| """tasks: list of picklable args; fn(worker_index, args) -> rows written. Clears the stage dir first.""" | |
| import multiprocessing as mp | |
| clear_stage(source) | |
| with mp.Pool(procs) as p: | |
| n = sum(p.starmap(fn, list(enumerate(tasks)), chunksize=1)) | |
| print(f"[{source}] total rows {n}", flush=True); return n | |
Xet Storage Details
- Size:
- 16.2 kB
- Xet hash:
- 6d23b91949503caa33fa6ceeef4d3fe2e05d8ce9bf70868b5fea4328bf7360b3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.