"""Generate CCRB v1.0 queries (3,600 total) and graded qrels from normalized corpora and graph.""" from __future__ import annotations import argparse import json import random import re import sys from collections import Counter, defaultdict from pathlib import Path from typing import Any _REPO_ROOT = Path(__file__).resolve().parent.parent if str(_REPO_ROOT) not in sys.path: sys.path.insert(0, str(_REPO_ROOT)) from scripts.baselines.bm25 import BM25Index, tokenize from scripts.pipeline_utils import TRACKS, load_jsonl # Scrub all benchmark shortcut identifiers and advisory IDs from queries. SCRUB_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = ( (re.compile(r"\bCVE-\d{4}-\d{4,7}\b", re.IGNORECASE), "this vulnerability"), (re.compile(r"\bCWE-\d{1,4}\b", re.IGNORECASE), "this weakness"), (re.compile(r"\bCAPEC-\d{1,4}\b", re.IGNORECASE), "this attack pattern"), (re.compile(r"\bGHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}\b", re.IGNORECASE), "this advisory"), (re.compile(r"\b(?:PYSEC|RUSTSEC|GO)-\d{4}-\d{3,6}\b", re.IGNORECASE), "this advisory"), (re.compile(r"\bT\d{4}(?:\.\d{3})?\b"), "this technique"), (re.compile(r"\bTA\d{4}\b"), "this tactic"), (re.compile(r"\bM\d{4}\b"), "this mitigation"), ) def _norm_ws(text: str) -> str: return re.sub(r"\s+", " ", text.strip().lower()) def _token_jaccard(a: str, b: str) -> float: ta = set(tokenize(a)) tb = set(tokenize(b)) if not ta or not tb: return 0.0 return len(ta & tb) / len(ta | tb) def scrub_query( text: str, forbidden_titles: list[str] | None = None, *, extra_literals: list[str] | None = None, ) -> str: """Remove direct IDs, URLs, package slugs, and verbatim target titles from query text.""" cleaned = re.sub(r"https?://\S+", "", text) cleaned = re.sub(r"(?im)^Affected packages:.*$", "", cleaned) cleaned = re.sub(r"(?im)^Associated weaknesses:.*$", "", cleaned) cleaned = re.sub(r"(?m)^#{1,4}\s+", "", cleaned) cleaned = re.sub(r"\b[0-9a-f]{40}\b", "[commit]", cleaned) for pattern, repl in SCRUB_PATTERNS: cleaned = pattern.sub(repl, cleaned) if forbidden_titles: for title in forbidden_titles: t_body = re.sub( r"^(?:CWE-\d+|CVE-\d{4}-\d+|CAPEC-\d+|T\d{4}(?:\.\d{3})?|M\d{4}|GHSA-[a-z0-9-]+)[:\s—-]+", "", title, flags=re.IGNORECASE, ).strip() # Only strip full-word title matches (avoid truncated 110-char NVD title snippets!) if len(t_body) >= 12 and len(t_body) < 105: cleaned = re.sub( rf"(?= 4: cleaned = re.sub( rf"(? bool: langs = [str(l).lower() for l in seed.get("language_tags", [])] if langs and all(l in {"other", "pseudocode"} for l in langs): return False txt = str(seed.get("text", "")) return any(ch in txt for ch in ("(", "{", "=", ";", "=>", "def ", "SELECT ", "<")) def _has_enough_substance(text: str, min_unique_tokens: int = 10) -> bool: tokens = {t for t in tokenize(text) if t not in {"the", "component", "affected", "package", "this", "vulnerability", "advisory", "weakness"}} return len(tokens) >= min_unique_tokens def _assign_splits( queries: list[dict[str, Any]], dev_count: int = 120, seed: int = 20261129, ) -> list[dict[str, Any]]: """Assign `dev` and `test` splits proportionally across `query_type` strata.""" if not queries: return queries rng = random.Random(seed) by_type: dict[str, list[dict[str, Any]]] = defaultdict(list) for qobj in queries: by_type[str(qobj.get("query_type", "nl"))].append(qobj) total = len(queries) dev_ids: set[str] = set() for qtype, group in sorted(by_type.items()): shuffled = group[:] rng.shuffle(shuffled) n_dev = round(dev_count * (len(group) / total)) for qobj in shuffled[:n_dev]: dev_ids.add(str(qobj["query_id"])) # Adjust rounding drift to match exact `dev_count` all_ids = [str(q["query_id"]) for q in queries] for qid in all_ids: if len(dev_ids) >= dev_count: break dev_ids.add(qid) while len(dev_ids) > dev_count: dev_ids.pop() for qobj in queries: qobj["split"] = "dev" if str(qobj["query_id"]) in dev_ids else "test" return queries def _build_bm25_for_docs(docs: list[dict[str, Any]]) -> BM25Index: doc_ids = [str(d["document_id"]) for d in docs] texts = [f"{d.get('title', '')}\n{d.get('text', '')}" for d in docs] return BM25Index(doc_ids, texts) def _mine_hard_negatives( index: BM25Index, query_text: str, positive_ids: set[str], *, num_negatives: int = 15, ) -> list[str]: hits = index.search(query_text, top_k=num_negatives + len(positive_ids) + 10) negs: list[str] = [] for doc_id, _score in hits: if doc_id not in positive_ids: negs.append(doc_id) if len(negs) >= num_negatives: break return negs def _load_docs_by_track(data_dir: Path) -> dict[str, list[dict[str, Any]]]: return { track: [obj for _ln, obj in load_jsonl(data_dir / "documents" / f"{track}.jsonl")] for track in TRACKS } def _load_graph(data_dir: Path) -> dict[str, Any]: return json.loads((data_dir / "graph" / "adjacency.json").read_text(encoding="utf-8")) def _extract_package_tokens(adv_doc: dict[str, Any]) -> list[str]: """Extract package names from advisory text (`Affected packages: Eco:pkg, ...`).""" m = re.search(r"Affected packages:\s*(.+)$", str(adv_doc.get("text", "")), re.MULTILINE) if not m: return [] tokens: list[str] = [] for item in m.group(1).split(","): item = item.strip() if ":" in item: _, pkg = item.split(":", 1) tokens.append(pkg.strip()) if "/" in pkg: tokens.append(pkg.split("/")[-1].strip()) elif item: tokens.append(item) return [t for t in tokens if len(t) >= 4] def _collect_disjoint_cross_pairs( docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], rng: random.Random, ) -> list[tuple[dict[str, Any], dict[str, Any], float]]: """Collect unique (adv_doc, cve_doc, jaccard) pairs sorted/filtered for semantic diversity.""" cve_by_source = { d["source_id"]: d for d in docs_by_track["cve"] if d.get("source_id") } fwd = graph["forward"] pairs: list[tuple[dict[str, Any], dict[str, Any], float]] = [] seen_cves: set[str] = set() adv_docs = docs_by_track["advisories"][:] rng.shuffle(adv_docs) for adv in adv_docs: adv_id = str(adv.get("source_id", "")) cve_aliases = fwd.get(adv_id, {}).get("alias_cve", []) matching = [c for c in cve_aliases if c in cve_by_source and c not in seen_cves] if not matching: continue cve_id = matching[0] cve_doc = cve_by_source[cve_id] jac = _token_jaccard(str(adv.get("text", "")), str(cve_doc.get("text", ""))) if jac <= 0.65: # Verify both sides have enough scrubbed substance before partitioning pkg_tokens = _extract_package_tokens(adv) adv_q = scrub_query(str(adv.get("text", "")), [cve_doc["title"], adv["title"]], extra_literals=pkg_tokens)[:900] cve_q = scrub_query(str(cve_doc.get("text", "")), [cve_doc["title"], adv["title"]], extra_literals=pkg_tokens)[:900] if len(adv_q) >= 60 and len(cve_q) >= 60 and _has_enough_substance(adv_q, 10) and _has_enough_substance(cve_q, 10): seen_cves.add(cve_id) pairs.append((adv, cve_doc, jac)) pairs.sort(key=lambda item: item[2]) return pairs def _build_cve_track( docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], cve_pairs: list[tuple[dict[str, Any], dict[str, Any], float]], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: fwd = graph["forward"] queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() # Use independent OSV/GHSA advisory descriptions (low lexical overlap + scrubbed package literals) # to retrieve the target NVD CVE record. rng.shuffle(cve_pairs) for adv_doc, cve_doc, _jac in cve_pairs: if len(queries) >= target_count: break pkg_tokens = _extract_package_tokens(adv_doc) q_body = scrub_query( str(adv_doc.get("text", "")), [cve_doc["title"], adv_doc["title"]], extra_literals=pkg_tokens, )[:900] if len(q_body) < 60 or not _has_enough_substance(q_body, 10): continue q_text = f"Identify the vulnerability record corresponding to this security flaw:\n{q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) qid = f"cve_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "cve", "query_type": "nl"}) pos_map: dict[str, int] = {cve_doc["document_id"]: 3} # Include any additional aliased CVEs if present adv_id = str(adv_doc.get("source_id", "")) cve_by_source = {d["source_id"]: d["document_id"] for d in docs_by_track["cve"] if d.get("source_id")} for alias_cve in fwd.get(adv_id, {}).get("alias_cve", []): if alias_cve in cve_by_source and cve_by_source[alias_cve] != cve_doc["document_id"]: pos_map.setdefault(cve_by_source[alias_cve], 2) qrels[qid] = pos_map return _assign_splits(queries, dev_count=120), qrels def _build_advisories_track( docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], adv_pairs: list[tuple[dict[str, Any], dict[str, Any], float]], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: adv_by_id = {d["source_id"]: d["document_id"] for d in docs_by_track["advisories"] if d.get("source_id")} rev = graph["reverse"] queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() rng.shuffle(adv_pairs) for adv_doc, cve_doc, _jac in adv_pairs: if len(queries) >= target_count: break pkg_tokens = _extract_package_tokens(adv_doc) q_body = scrub_query( str(cve_doc.get("text", "")), [cve_doc["title"], adv_doc["title"]], extra_literals=pkg_tokens, )[:900] if len(q_body) < 60 or not _has_enough_substance(q_body, 10): continue q_text = f"Find the ecosystem security advisory describing this issue:\n{q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) qid = f"advisories_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "advisories", "query_type": "nl"}) pos_map: dict[str, int] = {adv_doc["document_id"]: 3} cve_id = str(cve_doc.get("source_id", "")) for sib_adv in rev.get(cve_id, {}).get("alias_cve", []): if sib_adv in adv_by_id and adv_by_id[sib_adv] != adv_doc["document_id"]: pos_map.setdefault(adv_by_id[sib_adv], 2) qrels[qid] = pos_map return _assign_splits(queries, dev_count=120), qrels def _build_cwe_track( data_dir: Path, docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: cwe_docs = docs_by_track["cwe"] cwe_by_id = {d["source_id"]: d for d in cwe_docs if d.get("source_id")} fwd = graph["forward"] rev = graph["reverse"] bad_seeds = [obj for _ln, obj in load_jsonl(data_dir / "graph" / "code_query_seeds.jsonl")] rng.shuffle(bad_seeds) queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() cwe_usage: Counter[str] = Counter() def add_cwe_qrels(qid: str, cwe_id: str) -> None: doc = cwe_by_id[cwe_id] pos_map: dict[str, int] = {doc["document_id"]: 3} for rel_name, grade in (("cwe_childof", 2), ("cwe_peerof", 2), ("cwe_canalsobe", 1)): for target_cwe in fwd.get(cwe_id, {}).get(rel_name, []): if target_cwe in cwe_by_id: pos_map.setdefault(cwe_by_id[target_cwe]["document_id"], grade) for parent_child in rev.get(cwe_id, {}).get(rel_name, []): if parent_child in cwe_by_id: pos_map.setdefault(cwe_by_id[parent_child]["document_id"], grade) qrels[qid] = pos_map for seed in bad_seeds: if len(queries) >= target_count // 2: break if not _looks_like_code(seed): continue cwe_id = str(seed.get("cwe_id", "")) if cwe_id not in cwe_by_id or cwe_usage[cwe_id] >= 3: continue code_body = scrub_query(str(seed.get("text", "")), [cwe_by_id[cwe_id]["title"]])[:1200] if len(code_body) < 35: continue q_text = f"Which software weakness classification applies to this vulnerable code snippet?\n{code_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) cwe_usage[cwe_id] += 1 qid = f"cwe_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "cwe", "query_type": "code"}) add_cwe_qrels(qid, cwe_id) attack_capecs = [d for d in docs_by_track["attack"] if str(d.get("source_id", "")).startswith("CAPEC-")] rng.shuffle(attack_capecs) for capec in attack_capecs: if len(queries) >= target_count: break capec_id = str(capec["source_id"]) linked_cwes = [c for c in fwd.get(capec_id, {}).get("exploits_cwe", []) if c in cwe_by_id] if not linked_cwes: continue cwe_id = min(linked_cwes, key=lambda c: cwe_usage[c]) if cwe_usage[cwe_id] >= 4: continue q_body = scrub_query(str(capec["text"]), [capec["title"], cwe_by_id[cwe_id]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Identify the underlying software weakness exploited by this attack behavior: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) cwe_usage[cwe_id] += 1 qid = f"cwe_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "cwe", "query_type": "nl"}) add_cwe_qrels(qid, cwe_id) cve_and_adv = docs_by_track["cve"] + docs_by_track["advisories"][:10000] rng.shuffle(cve_and_adv) for src_doc in cve_and_adv: if len(queries) >= target_count: break src_id = str(src_doc.get("source_id", "")) linked_cwes = [c for c in fwd.get(src_id, {}).get("has_cwe", []) if c in cwe_by_id] if not linked_cwes: continue cwe_id = min(linked_cwes, key=lambda c: cwe_usage[c]) if cwe_usage[cwe_id] >= 5: continue q_body = scrub_query(str(src_doc["text"]), [src_doc["title"], cwe_by_id[cwe_id]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Map this vulnerability report to its corresponding weakness classification: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) cwe_usage[cwe_id] += 1 qid = f"cwe_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "cwe", "query_type": "nl"}) add_cwe_qrels(qid, cwe_id) return _assign_splits(queries, dev_count=120), qrels def _build_attack_track( docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: attack_docs = docs_by_track["attack"] att_by_id = {d["source_id"]: d for d in attack_docs if str(d.get("source_id", "")).startswith("T")} capec_by_id = {d["source_id"]: d for d in attack_docs if str(d.get("source_id", "")).startswith("CAPEC-")} sigma_docs = [d for d in docs_by_track["code"] if d.get("source") == "SigmaHQ"] rem_attack_docs = [d for d in docs_by_track["remediation"] if d.get("source") == "MITRE ATT&CK Mitigations"] fwd = graph["forward"] rev = graph["reverse"] queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() tech_usage: Counter[str] = Counter() def add_attack_qrels(qid: str, tech_id: str) -> None: pos_map: dict[str, int] = {att_by_id[tech_id]["document_id"]: 3} for parent in fwd.get(tech_id, {}).get("subtechnique_of", []): if parent in att_by_id: pos_map.setdefault(att_by_id[parent]["document_id"], 2) for child in rev.get(tech_id, {}).get("subtechnique_of", []): if child in att_by_id: pos_map.setdefault(att_by_id[child]["document_id"], 2) for capec_id in rev.get(tech_id, {}).get("maps_attack", []): if capec_id in capec_by_id: pos_map.setdefault(capec_by_id[capec_id]["document_id"], 1) qrels[qid] = pos_map rng.shuffle(sigma_docs) for sig in sigma_docs: if len(queries) >= 350: break tech_ids = [t for t in sig.get("attack_ids", []) if t in att_by_id] if not tech_ids: continue tech_id = min(tech_ids, key=lambda t: tech_usage[t]) if tech_usage[tech_id] >= 4: continue yaml_match = re.search(r"```yaml\s*\n(.*?)```", str(sig["text"]), re.DOTALL) if not yaml_match: continue yaml_code = scrub_query(yaml_match.group(1), [att_by_id[tech_id]["title"]])[:1100] if len(yaml_code) < 40: continue q_text = f"Which adversary technique does this detection logic identify?\n```yaml\n{yaml_code}\n```" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) tech_usage[tech_id] += 1 qid = f"attack_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "attack", "query_type": "code"}) add_attack_qrels(qid, tech_id) capecs = list(capec_by_id.values()) rng.shuffle(capecs) for capec in capecs: if len(queries) >= target_count: break tech_ids = [t for t in fwd.get(capec["source_id"], {}).get("maps_attack", []) if t in att_by_id] if not tech_ids: continue tech_id = min(tech_ids, key=lambda t: tech_usage[t]) if tech_usage[tech_id] >= 5: continue q_body = scrub_query(str(capec["text"]), [capec["title"], att_by_id[tech_id]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Retrieve the adversary technique corresponding to this attack pattern: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) tech_usage[tech_id] += 1 qid = f"attack_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "attack", "query_type": "nl"}) add_attack_qrels(qid, tech_id) rng.shuffle(sigma_docs) for sig in sigma_docs: if len(queries) >= target_count: break tech_ids = [t for t in sig.get("attack_ids", []) if t in att_by_id] if not tech_ids: continue tech_id = min(tech_ids, key=lambda t: tech_usage[t]) if tech_usage[tech_id] >= 5: continue desc_only = re.sub(r"```yaml.*?```", "", str(sig["text"]), flags=re.DOTALL).strip() q_body = scrub_query(desc_only, [sig["title"], att_by_id[tech_id]["title"]])[:700] if len(q_body) < 40: continue q_text = f"Find the adversary behavior or technique described by this telemetry alert: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) tech_usage[tech_id] += 1 qid = f"attack_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "attack", "query_type": "nl"}) add_attack_qrels(qid, tech_id) rng.shuffle(rem_attack_docs) for rem in rem_attack_docs: if len(queries) >= target_count: break targets = [t for t in fwd.get(rem["document_id"], {}).get("mitigates", []) if t in att_by_id] if not targets: continue tech_id = min(targets, key=lambda t: tech_usage[t]) q_body = scrub_query(str(rem["text"]), [rem["title"], att_by_id[tech_id]["title"]])[:700] if len(q_body) < 40: continue q_text = f"Which adversary technique is countered by this defensive control? {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) tech_usage[tech_id] += 1 qid = f"attack_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "attack", "query_type": "nl"}) add_attack_qrels(qid, tech_id) return _assign_splits(queries, dev_count=120), qrels def _build_remediation_track( data_dir: Path, docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: rem_docs = docs_by_track["remediation"] rem_by_id = {d["document_id"]: d for d in rem_docs} att_by_id = {d["source_id"]: d for d in docs_by_track["attack"] if str(d.get("source_id", "")).startswith("T")} bad_seeds = [obj for _ln, obj in load_jsonl(data_dir / "graph" / "code_query_seeds.jsonl")] fwd = graph["forward"] rev = graph["reverse"] queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() rem_usage: Counter[str] = Counter() rng.shuffle(bad_seeds) for seed in bad_seeds: if len(queries) >= 200: break if not _looks_like_code(seed): continue cwe_id = str(seed.get("cwe_id", "")) mit_ids = [m for m in fwd.get(cwe_id, {}).get("mitigated_by", []) if m in rem_by_id] if not mit_ids: continue primary_mit = min(mit_ids, key=lambda m: rem_usage[m]) if rem_usage[primary_mit] >= 3: continue code_body = scrub_query(str(seed["text"]), [rem_by_id[primary_mit]["title"]])[:1100] if len(code_body) < 35: continue q_text = f"What defensive remediation mitigates the security flaw in this code?\n{code_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) for m in mit_ids: rem_usage[m] += 1 qid = f"remediation_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "remediation", "query_type": "code"}) qrels[qid] = {m: (3 if idx == 0 else 2) for idx, m in enumerate(mit_ids[:4])} att_list = list(att_by_id.values()) rng.shuffle(att_list) for att_doc in att_list: if len(queries) >= 400: break tech_id = str(att_doc["source_id"]) mit_ids = [m for m in rev.get(tech_id, {}).get("mitigates", []) if m in rem_by_id] if not mit_ids: continue primary_mit = min(mit_ids, key=lambda m: rem_usage[m]) if rem_usage[primary_mit] >= 4: continue q_body = scrub_query(str(att_doc["text"]), [att_doc["title"], rem_by_id[primary_mit]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Recommend defensive controls to mitigate this adversary behavior: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) for m in mit_ids: rem_usage[m] += 1 qid = f"remediation_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "remediation", "query_type": "nl"}) qrels[qid] = {m: (3 if idx == 0 else 2) for idx, m in enumerate(mit_ids[:4])} cve_list = docs_by_track["cve"][:] rng.shuffle(cve_list) for cve_doc in cve_list: if len(queries) >= target_count: break cve_id = str(cve_doc.get("source_id", "")) cwes = fwd.get(cve_id, {}).get("has_cwe", []) mit_ids: list[str] = [] for cwe in cwes: mit_ids.extend(m for m in fwd.get(cwe, {}).get("mitigated_by", []) if m in rem_by_id) mit_ids = list(dict.fromkeys(mit_ids)) if not mit_ids: continue primary_mit = min(mit_ids, key=lambda m: rem_usage[m]) if rem_usage[primary_mit] >= 4: continue q_body = scrub_query(str(cve_doc["text"]), [cve_doc["title"], rem_by_id[primary_mit]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Find remediation guidance for resolving this vulnerability class: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) for m in mit_ids: rem_usage[m] += 1 qid = f"remediation_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "remediation", "query_type": "nl"}) qrels[qid] = {m: (3 if idx == 0 else 2) for idx, m in enumerate(mit_ids[:4])} return _assign_splits(queries, dev_count=120), qrels def _build_code_track( data_dir: Path, docs_by_track: dict[str, list[dict[str, Any]]], graph: dict[str, Any], rng: random.Random, target_count: int = 600, ) -> tuple[list[dict[str, Any]], dict[str, dict[str, int]]]: code_docs = docs_by_track["code"] code_by_id = {d["document_id"]: d for d in code_docs} att_by_id = {d["source_id"]: d for d in docs_by_track["attack"] if str(d.get("source_id", "")).startswith("T")} rem_owasp = [d for d in docs_by_track["remediation"] if d.get("source") == "OWASP CheatSheetSeries"] bad_seeds = [obj for _ln, obj in load_jsonl(data_dir / "graph" / "code_query_seeds.jsonl")] fwd = graph["forward"] rev = graph["reverse"] owasp_code_by_slug: dict[str, list[dict[str, Any]]] = defaultdict(list) for cdoc in code_docs: if cdoc.get("source") == "OWASP CheatSheetSeries": sid = str(cdoc.get("source_id", "")) slug = sid.replace("OWASP-CODE-", "").rsplit("-", 1)[0] owasp_code_by_slug[slug].append(cdoc) queries: list[dict[str, Any]] = [] qrels: dict[str, dict[str, int]] = {} seen_q: set[str] = set() target_usage: Counter[str] = Counter() rng.shuffle(bad_seeds) # Prioritize seeds with an exact paired Good example from the same Demonstrative_Example bad_seeds.sort( key=lambda s: 1 if fwd.get(str(s.get("document_id", "")), {}).get("paired_good_code") else 0, reverse=True, ) for seed in bad_seeds: if len(queries) >= 200: break if not _looks_like_code(seed): continue cwe_id = str(seed.get("cwe_id", "")) paired = [gid for gid in fwd.get(str(seed.get("document_id", "")), {}).get("paired_good_code", []) if gid in code_by_id] other_good = [gid for gid in fwd.get(cwe_id, {}).get("has_good_code", []) if gid in code_by_id and gid not in paired] good_ids = paired + other_good if not good_ids: continue primary = paired[0] if paired else min(other_good, key=lambda g: target_usage[g]) if target_usage[primary] >= 3: continue code_body = scrub_query(str(seed["text"]), [code_by_id[primary]["title"]])[:1100] if len(code_body) < 35: continue q_text = f"Find a secure defensive implementation to replace this vulnerable code:\n{code_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) for g in good_ids: target_usage[g] += 1 qid = f"code_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "code", "query_type": "code"}) if paired: pos_map = {paired[0]: 3} for g in other_good[:3]: pos_map[g] = 2 qrels[qid] = pos_map else: qrels[qid] = {g: (3 if idx == 0 else 2) for idx, g in enumerate(good_ids[:4])} att_list = list(att_by_id.values()) rng.shuffle(att_list) for att_doc in att_list: if len(queries) >= 400: break tech_id = str(att_doc["source_id"]) sig_ids = [s for s in rev.get(tech_id, {}).get("detects_attack", []) if s in code_by_id] if not sig_ids: continue primary = min(sig_ids, key=lambda s: target_usage[s]) if target_usage[primary] >= 3: continue q_body = scrub_query(str(att_doc["text"]), [att_doc["title"], code_by_id[primary]["title"]])[:800] if len(q_body) < 50: continue q_text = f"Retrieve a detection rule that identifies this adversary behavior: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) for s in sig_ids[:4]: target_usage[s] += 1 qid = f"code_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "code", "query_type": "nl"}) qrels[qid] = {s: (3 if idx == 0 else 2) for idx, s in enumerate(sig_ids[:5])} rng.shuffle(rem_owasp) for rem in rem_owasp: if len(queries) >= target_count: break sid = str(rem.get("source_id", "")) slug = sid.replace("OWASP-", "").rsplit("-", 1)[0] cand_codes = owasp_code_by_slug.get(slug, []) if not cand_codes: continue rem_heading = rem["title"].split("—")[-1].strip().lower() scored_cands = sorted( cand_codes, key=lambda c: ( 1 if rem_heading and rem_heading in c["title"].lower() else 0, -target_usage[c["document_id"]], ), reverse=True, ) primary_doc = scored_cands[0] if target_usage[primary_doc["document_id"]] >= 3: continue q_body = scrub_query(str(rem["text"]), [rem["title"], primary_doc["title"]])[:700] if len(q_body) < 60: continue q_text = f"Find a secure code implementation example satisfying this security guidance: {q_body}" norm = _norm_ws(q_text) if norm in seen_q: continue seen_q.add(norm) target_usage[primary_doc["document_id"]] += 1 qid = f"code_q_{len(queries) + 1:06d}" queries.append({"query_id": qid, "query": q_text, "track": "code", "query_type": "nl"}) pos_map = {primary_doc["document_id"]: 3} for sib in scored_cands[1:4]: pos_map.setdefault(sib["document_id"], 2) qrels[qid] = pos_map return _assign_splits(queries, dev_count=120), qrels def build_all_queries_and_qrels( data_dir: Path, *, per_track: int = 600, seed: int = 20261129, ) -> dict[str, Any]: """Generate queries and BM25-hard-negative-pooled graded qrels across all 6 tracks.""" rng = random.Random(seed) docs_by_track = _load_docs_by_track(data_dir) graph = _load_graph(data_dir) cross_pairs = _collect_disjoint_cross_pairs(docs_by_track, graph, rng) # Partition lowest-overlap cross-source pairs evenly between `cve` and `advisories` cve_pairs = cross_pairs[0::2] adv_pairs = cross_pairs[1::2] builders = { "cve": lambda: _build_cve_track(docs_by_track, graph, cve_pairs, rng, per_track), "cwe": lambda: _build_cwe_track(data_dir, docs_by_track, graph, rng, per_track), "attack": lambda: _build_attack_track(docs_by_track, graph, rng, per_track), "advisories": lambda: _build_advisories_track(docs_by_track, graph, adv_pairs, rng, per_track), "remediation": lambda: _build_remediation_track(data_dir, docs_by_track, graph, rng, per_track), "code": lambda: _build_code_track(data_dir, docs_by_track, graph, rng, per_track), } summary: dict[str, Any] = {} for track in TRACKS: print(f"[build] generating queries + mining BM25 hard negatives for {track}...") queries, qrels = builders[track]() bm25 = _build_bm25_for_docs(docs_by_track[track]) for qobj in queries: qid = qobj["query_id"] pos_ids = {did for did, rel in qrels[qid].items() if rel >= 1} for neg_id in _mine_hard_negatives(bm25, qobj["query"], pos_ids, num_negatives=12): qrels[qid].setdefault(neg_id, 0) q_path = data_dir / "queries" / f"{track}.jsonl" with q_path.open("w", encoding="utf-8") as handle: for qobj in queries: handle.write(json.dumps(qobj, ensure_ascii=False) + "\n") qrel_path = data_dir / "qrels" / f"{track}.tsv" with qrel_path.open("w", encoding="utf-8") as handle: for qobj in queries: qid = qobj["query_id"] for did, rel in sorted(qrels[qid].items(), key=lambda x: (-x[1], x[0])): handle.write(f"{qid}\t{did}\t{rel}\n") summary[track] = { "queries": len(queries), "dev": sum(1 for q in queries if q.get("split") == "dev"), "test": sum(1 for q in queries if q.get("split") == "test"), "qrel_pairs": sum(len(v) for v in qrels.values()), } print(f"[done] {track}: {summary[track]}") return summary def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Build CCRB queries and graded qrels.") parser.add_argument("--data-dir", type=Path, default=Path("data")) parser.add_argument("--per-track", type=int, default=600) parser.add_argument("--seed", type=int, default=20261129) args = parser.parse_args(argv) summary = build_all_queries_and_qrels(args.data_dir, per_track=args.per_track, seed=args.seed) print(json.dumps(summary, indent=2)) return 0 if __name__ == "__main__": sys.exit(main())