File size: 11,119 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Validate CCRB queries, document corpora, qrels, and anti-leakage invariants."""

from __future__ import annotations

import argparse
import json
import re
import sys
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path

_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,
    VALID_QUERY_TYPES,
    VALID_RELEVANCE_GRADES,
    VALID_SPLITS,
    load_jsonl,
    load_qrels,
)

# Identifiers that act as trivial lexical shortcuts when leaked verbatim into queries.
LEAKAGE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
    ("CVE_ID", re.compile(r"\bCVE-\d{4}-\d{4,7}\b", re.IGNORECASE)),
    ("CWE_ID", re.compile(r"\bCWE-\d{1,4}\b", re.IGNORECASE)),
    ("CAPEC_ID", re.compile(r"\bCAPEC-\d{1,4}\b", re.IGNORECASE)),
    ("GHSA_ID", re.compile(r"\bGHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}\b", re.IGNORECASE)),
    ("ATTACK_TECHNIQUE_ID", re.compile(r"\bT\d{4}(?:\.\d{3})?\b")),
    ("ATTACK_TACTIC_ID", re.compile(r"\bTA\d{4}\b")),
    ("ATTACK_MITIGATION_ID", re.compile(r"\bM\d{4}\b")),
)


@dataclass
class ValidationReport:
    """Structured validation outcome across all CCRB tracks."""

    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    track_stats: dict[str, dict[str, object]] = field(default_factory=dict)

    @property
    def ok(self) -> bool:
        return len(self.errors) == 0


def _normalize_text(text: str) -> str:
    return re.sub(r"\s+", " ", text.strip().lower())


def _require_non_empty_str(
    record: dict[str, object],
    key: str,
    location: str,
    errors: list[str],
) -> str | None:
    value = record.get(key)
    if not isinstance(value, str) or not value.strip():
        errors.append(f"{location}: field {key!r} must be a non-empty string")
        return None
    return value


def validate_track(
    data_dir: Path,
    track: str,
    *,
    allow_empty: bool = False,
    strict_leakage: bool = False,
    seen_query_ids: set[str] | None = None,
    seen_doc_ids: set[str] | None = None,
) -> tuple[list[str], list[str], dict[str, object]]:
    """Validate queries, documents, and qrels for a single CCRB track."""
    errors: list[str] = []
    warnings: list[str] = []

    queries_path = data_dir / "queries" / f"{track}.jsonl"
    docs_path = data_dir / "documents" / f"{track}.jsonl"
    qrels_path = data_dir / "qrels" / f"{track}.tsv"

    for required_path in (queries_path, docs_path, qrels_path):
        if not required_path.exists():
            errors.append(f"[{track}] missing required file: {required_path}")

    if errors:
        return errors, warnings, {}

    global_qids = seen_query_ids if seen_query_ids is not None else set()
    global_dids = seen_doc_ids if seen_doc_ids is not None else set()

    queries_by_id: dict[str, dict[str, object]] = {}
    docs_by_id: dict[str, dict[str, object]] = {}
    normalized_queries: dict[str, str] = {}
    split_counts: Counter[str] = Counter()
    grade_counts: Counter[int] = Counter()

    try:
        raw_queries = load_jsonl(queries_path)
    except (json.JSONDecodeError, ValueError) as exc:
        errors.append(f"[{track}] invalid queries JSONL: {exc}")
        raw_queries = []

    try:
        raw_docs = load_jsonl(docs_path)
    except (json.JSONDecodeError, ValueError) as exc:
        errors.append(f"[{track}] invalid documents JSONL: {exc}")
        raw_docs = []

    try:
        qrels = load_qrels(qrels_path)
    except ValueError as exc:
        errors.append(f"[{track}] invalid qrels TSV: {exc}")
        qrels = {}

    if not allow_empty and (not raw_queries or not raw_docs or not qrels):
        errors.append(
            f"[{track}] track files must be non-empty (queries={len(raw_queries)}, "
            f"docs={len(raw_docs)}, qrel_queries={len(qrels)})"
        )

    for line_no, obj in raw_queries:
        loc = f"{queries_path}:{line_no}"
        qid = _require_non_empty_str(obj, "query_id", loc, errors)
        qtext = _require_non_empty_str(obj, "query", loc, errors)
        qtrack = _require_non_empty_str(obj, "track", loc, errors)
        if qtrack is not None and qtrack != track:
            errors.append(f"{loc}: track={qtrack!r} does not match expected {track!r}")

        split = obj.get("split")
        if split is not None:
            if not isinstance(split, str) or split not in VALID_SPLITS:
                errors.append(f"{loc}: optional field 'split' must be one of {sorted(VALID_SPLITS)}")
            else:
                split_counts[split] += 1

        qtype = obj.get("query_type")
        if qtype is not None and (not isinstance(qtype, str) or qtype not in VALID_QUERY_TYPES):
            errors.append(
                f"{loc}: optional field 'query_type' must be one of {sorted(VALID_QUERY_TYPES)}"
            )

        if qid is not None:
            if qid in queries_by_id or qid in global_qids:
                errors.append(f"{loc}: duplicate query_id {qid!r}")
            else:
                queries_by_id[qid] = obj
                global_qids.add(qid)

        if qtext is not None:
            norm = _normalize_text(qtext)
            if norm in normalized_queries:
                warnings.append(
                    f"{loc}: duplicate normalized query text matches {normalized_queries[norm]!r}"
                )
            elif qid is not None:
                normalized_queries[norm] = qid

            for label, pattern in LEAKAGE_PATTERNS:
                match = pattern.search(qtext)
                if match:
                    msg = (
                        f"{loc}: potential identifier shortcut ({label}={match.group(0)!r}) "
                        f"in query_id={qid!r}"
                    )
                    if strict_leakage:
                        errors.append(msg)
                    else:
                        warnings.append(msg)

    for line_no, obj in raw_docs:
        loc = f"{docs_path}:{line_no}"
        did = _require_non_empty_str(obj, "document_id", loc, errors)
        _require_non_empty_str(obj, "title", loc, errors)
        _require_non_empty_str(obj, "text", loc, errors)
        _require_non_empty_str(obj, "source", loc, errors)
        dtrack = _require_non_empty_str(obj, "track", loc, errors)
        if dtrack is not None and dtrack != track:
            errors.append(f"{loc}: track={dtrack!r} does not match expected {track!r}")

        if did is not None:
            if did in docs_by_id or did in global_dids:
                errors.append(f"{loc}: duplicate document_id {did!r}")
            else:
                docs_by_id[did] = obj
                global_dids.add(did)

    for qid, doc_map in qrels.items():
        if qid not in queries_by_id:
            errors.append(f"[{track}] qrels references unknown query_id {qid!r}")
        positive_count = 0
        for did, rel in doc_map.items():
            if rel not in VALID_RELEVANCE_GRADES:
                errors.append(f"[{track}] invalid relevance grade {rel!r} for ({qid!r}, {did!r})")
            else:
                grade_counts[rel] += 1
            if did not in docs_by_id:
                errors.append(f"[{track}] qrels references unknown document_id {did!r}")
            elif rel >= 2 and qid in queries_by_id:
                q_norm = _normalize_text(str(queries_by_id[qid].get("query", "")))
                title_norm = _normalize_text(str(docs_by_id[did].get("title", "")))
                if len(title_norm) >= 20 and title_norm in q_norm:
                    msg = (
                        f"[{track}] query {qid!r} contains verbatim target title of {did!r}"
                    )
                    if strict_leakage:
                        errors.append(msg)
                    else:
                        warnings.append(msg)
            if rel >= 1:
                positive_count += 1
        if positive_count == 0:
            errors.append(f"[{track}] query {qid!r} has qrel entries but zero positives (rel >= 1)")

    for qid in queries_by_id:
        if qid not in qrels:
            errors.append(f"[{track}] query {qid!r} has no qrels entries")

    stats: dict[str, object] = {
        "queries": len(queries_by_id),
        "documents": len(docs_by_id),
        "qrel_pairs": sum(len(v) for v in qrels.values()),
        "grades": {str(g): grade_counts[g] for g in sorted(VALID_RELEVANCE_GRADES)},
        "splits": dict(split_counts),
    }
    return errors, warnings, stats


def validate_dataset(
    data_dir: Path,
    *,
    tracks: tuple[str, ...] = TRACKS,
    allow_empty: bool = False,
    strict_leakage: bool = False,
) -> ValidationReport:
    """Validate all tracks in a CCRB data directory."""
    report = ValidationReport()
    seen_query_ids: set[str] = set()
    seen_doc_ids: set[str] = set()

    for track in tracks:
        errs, warns, stats = validate_track(
            data_dir,
            track,
            allow_empty=allow_empty,
            strict_leakage=strict_leakage,
            seen_query_ids=seen_query_ids,
            seen_doc_ids=seen_doc_ids,
        )
        report.errors.extend(errs)
        report.warnings.extend(warns)
        report.track_stats[track] = stats

    return report


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Validate CCRB dataset files.")
    parser.add_argument(
        "--data-dir",
        type=Path,
        default=Path("data"),
        help="Path to the CCRB data directory (default: data).",
    )
    parser.add_argument(
        "--tracks",
        nargs="+",
        choices=TRACKS,
        default=list(TRACKS),
        help="Subset of tracks to validate (default: all 6 tracks).",
    )
    parser.add_argument(
        "--allow-empty",
        action="store_true",
        help="Allow empty placeholder files during early development.",
    )
    parser.add_argument(
        "--strict-leakage",
        action="store_true",
        help="Treat identifier/title leakage warnings as validation errors.",
    )
    args = parser.parse_args(argv)

    report = validate_dataset(
        args.data_dir,
        tracks=tuple(args.tracks),
        allow_empty=args.allow_empty,
        strict_leakage=args.strict_leakage,
    )

    print("CCRB Dataset Validation Summary")
    print("=" * 32)
    for track, stats in report.track_stats.items():
        print(
            f"- {track:12s} | queries={stats.get('queries', 0):5d} "
            f"| docs={stats.get('documents', 0):6d} "
            f"| qrels={stats.get('qrel_pairs', 0):6d}"
        )

    if report.warnings:
        print(f"\nWarnings ({len(report.warnings)}):")
        for warning in report.warnings:
            print(f"  [WARN] {warning}")

    if report.errors:
        print(f"\nErrors ({len(report.errors)}):")
        for err in report.errors:
            print(f"  [ERR]  {err}")
        return 1

    print("\nValidation passed.")
    return 0


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