File size: 9,262 Bytes
8510f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
"""Export CCRB into a Hugging Face Hub / MTEB-compatible dataset repository in `hf_dist/`."""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
import sys
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.pipeline_utils import TRACKS, load_jsonl, load_qrels


def _sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(65536), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _build_hf_readme(stats: dict[str, dict[str, int]]) -> str:
    config_blocks: list[str] = []
    for track in TRACKS:
        config_blocks.append(
            f"""  - config_name: {track}-corpus
    data_files:
      - split: corpus
        path: data/{track}/corpus.jsonl
  - config_name: {track}-queries
    data_files:
      - split: dev
        path: data/{track}/queries_dev.jsonl
      - split: test
        path: data/{track}/queries_test.jsonl
  - config_name: {track}-qrels
    data_files:
      - split: dev
        path: data/{track}/qrels_dev.jsonl
      - split: test
        path: data/{track}/qrels_test.jsonl"""
        )

    configs_yaml = "\n".join(config_blocks)
    total_q = sum(s["queries"] for s in stats.values())
    total_d = sum(s["documents"] for s in stats.values())
    total_r = sum(s["qrels"] for s in stats.values())

    table_rows = "\n".join(
        f"| `{t}` | {stats[t]['dev']} / {stats[t]['test']} | {stats[t]['documents']:,} | {stats[t]['qrels']:,} |"
        for t in TRACKS
    )

    return f"""---
license: apache-2.0
language:
  - en
task_categories:
  - text-retrieval
  - feature-extraction
tags:
  - cybersecurity
  - embedding-benchmark
  - retrieval
  - mteb
  - cve
  - cwe
  - mitre-attack
  - code-retrieval
pretty_name: Continuum Cyber Retrieval Benchmark (CCRB)
size_categories:
  - 100K<n<1M
configs:
{configs_yaml}
---

# Continuum Cyber Retrieval Benchmark (CCRB)

The **Continuum Cyber Retrieval Benchmark (CCRB)** evaluates embedding models and semantic retrieval systems on cybersecurity knowledge, vulnerability intelligence, defensive guidance, and security-relevant code.

> **Status:** `v0.2-dev` — Pre-release benchmark with validated splits, cross-source graph qrels, BM25 hard-negative pooling, and baseline results.

## Dataset Summary

| Track | Queries (`dev` / `test`) | Documents | Graded Qrel Pairs |
| --- | ---: | ---: | ---: |
{table_rows}
| **Total** | **{total_q:,}** | **{total_d:,}** | **{total_r:,}** |

## Loading with `datasets`

Each track provides three BEIR/MTEB-compatible configs (`<track>-corpus`, `<track>-queries`, `<track>-qrels`):

```python
from datasets import load_dataset

corpus = load_dataset("continuum-oss/ccrb", "cwe-corpus", split="corpus")
queries = load_dataset("continuum-oss/ccrb", "cwe-queries", split="test")
qrels = load_dataset("continuum-oss/ccrb", "cwe-qrels", split="test")
```

## Evaluation Protocol

* **Primary Metric:** `nDCG@10` (exponential gain $2^{{rel}}-1$ over graded relevance `0, 1, 2, 3`)
* **Secondary Metrics:** `MRR@10`, `Recall@10`, `Recall@100`
* **Overall Score:** Equally weighted macro-average across all six tracks (`cve`, `cwe`, `attack`, `advisories`, `remediation`, `code`).
* **Baseline:** Okapi BM25 achieves `0.4393` macro `nDCG@10` on the `test` split (see `results/bm25_test.json`).

## Licensing & Attribution

Original CCRB materials are licensed under **Apache-2.0** (see `LICENSE`). Third-party sources (NVD, CISA KEV, MITRE CWE/CAPEC/ATT&CK, OSV/GHSA, OWASP CheatSheetSeries, SigmaHQ) remain subject to their respective upstream licenses and attribution terms.

## Citation

```bibtex
@misc{{continuum_ccrb,
  title        = {{Continuum Cyber Retrieval Benchmark (CCRB)}},
  author       = {{{{Continuum}}}},
  year         = {{2026}},
  howpublished = {{\\url{{https://huggingface.co/datasets/continuum-oss/ccrb}}}},
  note         = {{Benchmark v0.2-dev}}
}}
```
"""


def export_huggingface_repo(
    data_dir: Path,
    out_dir: Path,
    *,
    repo_root: Path = _REPO_ROOT,
) -> dict[str, dict[str, int]]:
    """Export CCRB into `out_dir` formatted for Hugging Face Hub & Dataset Viewer."""
    if out_dir.exists():
        shutil.rmtree(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    stats: dict[str, dict[str, int]] = {}
    checksum_paths: list[Path] = []

    for track in TRACKS:
        track_out = out_dir / "data" / track
        track_out.mkdir(parents=True, exist_ok=True)

        # 1. Corpus (`_id`, `title`, `text`, plus clean provenance fields)
        corpus_out = track_out / "corpus.jsonl"
        doc_count = 0
        with corpus_out.open("w", encoding="utf-8") as handle:
            for _ln, doc in load_jsonl(data_dir / "documents" / f"{track}.jsonl"):
                row = {
                    "_id": str(doc["document_id"]),
                    "title": str(doc.get("title", "")),
                    "text": str(doc.get("text", "")),
                    "source": str(doc.get("source", "")),
                    "license": str(doc.get("license", "")),
                    "source_id": str(doc.get("source_id", "")),
                }
                handle.write(json.dumps(row, ensure_ascii=False) + "\n")
                doc_count += 1
        checksum_paths.append(corpus_out)

        # 2. Queries split into dev / test (`_id`, `text`, `query_type`)
        dev_qids: set[str] = set()
        test_qids: set[str] = set()
        q_dev_path = track_out / "queries_dev.jsonl"
        q_test_path = track_out / "queries_test.jsonl"
        with (
            q_dev_path.open("w", encoding="utf-8") as f_dev,
            q_test_path.open("w", encoding="utf-8") as f_test,
        ):
            for _ln, qobj in load_jsonl(data_dir / "queries" / f"{track}.jsonl"):
                qid = str(qobj["query_id"])
                split = str(qobj.get("split", "test"))
                row = {
                    "_id": qid,
                    "text": str(qobj["query"]),
                    "query_type": str(qobj.get("query_type", "nl")),
                }
                line = json.dumps(row, ensure_ascii=False) + "\n"
                if split == "dev":
                    f_dev.write(line)
                    dev_qids.add(qid)
                else:
                    f_test.write(line)
                    test_qids.add(qid)
        checksum_paths.extend([q_dev_path, q_test_path])

        # 3. Qrels split into dev / test (`query-id`, `corpus-id`, `score`)
        qrels = load_qrels(data_dir / "qrels" / f"{track}.tsv")
        r_dev_path = track_out / "qrels_dev.jsonl"
        r_test_path = track_out / "qrels_test.jsonl"
        qrel_count = 0
        with (
            r_dev_path.open("w", encoding="utf-8") as f_dev,
            r_test_path.open("w", encoding="utf-8") as f_test,
        ):
            for qid, doc_map in qrels.items():
                target = f_dev if qid in dev_qids else f_test
                for did, score in sorted(doc_map.items(), key=lambda x: (-x[1], x[0])):
                    target.write(
                        json.dumps({"query-id": qid, "corpus-id": did, "score": score}) + "\n"
                    )
                    qrel_count += 1
        checksum_paths.extend([r_dev_path, r_test_path])

        stats[track] = {
            "documents": doc_count,
            "dev": len(dev_qids),
            "test": len(test_qids),
            "queries": len(dev_qids) + len(test_qids),
            "qrels": qrel_count,
        }

    # Copy supporting benchmark files
    for rel_file in ("LICENSE", "CITATION.cff", "EXECUTION_PLAN.md", "pyproject.toml"):
        src = repo_root / rel_file
        if src.exists():
            shutil.copy2(src, out_dir / rel_file)

    for rel_dir in ("evaluation", "scripts"):
        src_dir = repo_root / rel_dir
        if src_dir.exists():
            shutil.copytree(
                src_dir,
                out_dir / rel_dir,
                ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),
            )

    res_out = out_dir / "results"
    res_out.mkdir(parents=True, exist_ok=True)
    for res_file in ("README.md", "bm25_dev.json", "bm25_test.json"):
        src = repo_root / "results" / res_file
        if src.exists():
            shutil.copy2(src, res_out / res_file)

    (out_dir / "README.md").write_text(_build_hf_readme(stats), encoding="utf-8")

    sha_lines = [
        f"{_sha256_file(p)}  {p.relative_to(out_dir).as_posix()}"
        for p in sorted(checksum_paths)
    ]
    (out_dir / "SHA256SUMS.txt").write_text("\n".join(sha_lines) + "\n", encoding="utf-8")
    return stats


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Export CCRB for Hugging Face Hub.")
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--out-dir", type=Path, default=Path("hf_dist"))
    args = parser.parse_args(argv)
    stats = export_huggingface_repo(args.data_dir, args.out_dir)
    print(json.dumps(stats, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())