sidik-ml 0.5.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sidik_ml/__init__.py ADDED
@@ -0,0 +1,82 @@
1
+ """SIDIK-ML: Explainable Non-Neural ML Extension for SIDIK Static Security Analysis."""
2
+
3
+ from sidik_ml.schemas import MLPrediction, HybridFinding, TriagePolicy
4
+ from sidik_ml.features import FEATURE_SCHEMA_VERSION, FEATURE_NAMES, extract_feature_dict, extract_feature_vector
5
+ from sidik_ml.models import SUPPORTED_MODELS, FORBIDDEN_NEURAL_KEYWORDS, validate_non_ann_model_name, create_non_ann_model
6
+ from sidik_ml.dataset import (
7
+ LabeledCandidateRecord,
8
+ load_jsonl_dataset,
9
+ save_jsonl_dataset,
10
+ deduplicate_records,
11
+ resolve_cross_repo_value_duplicates,
12
+ assert_no_leakage,
13
+ repository_grouped_split,
14
+ stratified_repository_split,
15
+ iter_repository_group_folds,
16
+ records_to_matrix,
17
+ )
18
+ from sidik_ml.evaluation import (
19
+ FEATURE_GROUPS,
20
+ compute_classification_metrics,
21
+ bootstrap_metric_ci,
22
+ mcnemar_paired_test,
23
+ profile_inference_overhead,
24
+ run_feature_group_ablation,
25
+ )
26
+ from sidik_ml.explainability import extract_global_explanations, explain_single_candidate
27
+ from sidik_ml.serialization import (
28
+ SAFE_SKOPS_TYPE_PREFIXES,
29
+ compute_file_sha256,
30
+ verify_artifact_sha256,
31
+ save_verified_skops_model,
32
+ load_verified_skops_model,
33
+ )
34
+ from sidik_ml.training import collect_provenance, train_and_compare_models
35
+ from sidik_ml.integration import HybridTriagePipeline
36
+ from sidik_ml.plugin import SidikMLPlugin, create_plugin, resolve_model_and_sha256
37
+
38
+ __version__ = "0.5.2"
39
+
40
+ __all__ = [
41
+ "__version__",
42
+ "SidikMLPlugin",
43
+ "create_plugin",
44
+ "resolve_model_and_sha256",
45
+ "MLPrediction",
46
+ "HybridFinding",
47
+ "TriagePolicy",
48
+ "FEATURE_SCHEMA_VERSION",
49
+ "FEATURE_NAMES",
50
+ "FEATURE_GROUPS",
51
+ "extract_feature_dict",
52
+ "extract_feature_vector",
53
+ "SUPPORTED_MODELS",
54
+ "FORBIDDEN_NEURAL_KEYWORDS",
55
+ "validate_non_ann_model_name",
56
+ "create_non_ann_model",
57
+ "LabeledCandidateRecord",
58
+ "load_jsonl_dataset",
59
+ "save_jsonl_dataset",
60
+ "deduplicate_records",
61
+ "resolve_cross_repo_value_duplicates",
62
+ "assert_no_leakage",
63
+ "repository_grouped_split",
64
+ "stratified_repository_split",
65
+ "iter_repository_group_folds",
66
+ "records_to_matrix",
67
+ "compute_classification_metrics",
68
+ "bootstrap_metric_ci",
69
+ "mcnemar_paired_test",
70
+ "profile_inference_overhead",
71
+ "run_feature_group_ablation",
72
+ "extract_global_explanations",
73
+ "explain_single_candidate",
74
+ "SAFE_SKOPS_TYPE_PREFIXES",
75
+ "compute_file_sha256",
76
+ "verify_artifact_sha256",
77
+ "save_verified_skops_model",
78
+ "load_verified_skops_model",
79
+ "collect_provenance",
80
+ "train_and_compare_models",
81
+ "HybridTriagePipeline",
82
+ ]
sidik_ml/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Module entry point for running SIDIK-ML directly via `python -m sidik_ml`."""
2
+
3
+ import sys
4
+
5
+ from sidik_ml.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
sidik_ml/cli.py ADDED
@@ -0,0 +1,333 @@
1
+ """Command-line interface, interactive console launcher, and GUI launcher for SIDIK-ML."""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from sidik import SecurityScanner, __version__ as SIDIK_VERSION
10
+ from sidik.reporting.formatter import ReportFormatter
11
+ from sidik_ml import __version__ as ML_VERSION
12
+ from sidik_ml.dataset import load_jsonl_dataset
13
+ from sidik_ml.features import extract_feature_dict
14
+ from sidik_ml.integration import HybridTriagePipeline
15
+ from sidik_ml.plugin import SidikMLPlugin, resolve_model_and_sha256
16
+ from sidik_ml.schemas import TriagePolicy
17
+ from sidik_ml.serialization import load_verified_skops_model, verify_artifact_sha256
18
+ from sidik_ml.training import train_and_compare_models
19
+
20
+
21
+ KNOWN_SUBCOMMANDS = {
22
+ "scan",
23
+ "interactive",
24
+ "cli",
25
+ "tui",
26
+ "gui",
27
+ "extract-features",
28
+ "verify-model",
29
+ "train",
30
+ }
31
+
32
+
33
+ def _normalize_argv(raw_argv: List[str]) -> List[str]:
34
+ """Normalizes symmetric SIDIK-style shorthands (`-i`, `--gui`, `.`, `-t`) into subcommands."""
35
+ if not raw_argv:
36
+ return []
37
+ head = raw_argv[0]
38
+ if head in KNOWN_SUBCOMMANDS or head in ("-v", "--version"):
39
+ return list(raw_argv)
40
+
41
+ interactive_flags = {"-i", "--interactive", "--cli"}
42
+ if any(tok in interactive_flags for tok in raw_argv):
43
+ rest = [tok for tok in raw_argv if tok not in interactive_flags]
44
+ return ["interactive", *rest]
45
+
46
+ if "--gui" in raw_argv:
47
+ rest = [tok for tok in raw_argv if tok != "--gui"]
48
+ return ["gui", *rest]
49
+
50
+ if head in ("-h", "--help"):
51
+ return list(raw_argv)
52
+
53
+ if (not head.startswith("-")) or ("-t" in raw_argv or "--target" in raw_argv):
54
+ return ["scan", *raw_argv]
55
+
56
+ return list(raw_argv)
57
+
58
+
59
+ def _add_shared_ml_args(subparser: argparse.ArgumentParser) -> None:
60
+ """Registers symmetric `--model/--ml-model`, `--sha256/--ml-sha256`, `--threshold`, and `--suppress-fp` flags."""
61
+ subparser.add_argument(
62
+ "--model", "--ml-model",
63
+ dest="model",
64
+ default=None,
65
+ help="Optional path to verified .skops model artifact",
66
+ )
67
+ subparser.add_argument(
68
+ "--sha256", "--ml-sha256",
69
+ dest="sha256",
70
+ default=None,
71
+ help="Optional expected SHA-256 checksum (auto-reads <model>.manifest.json if omitted)",
72
+ )
73
+ subparser.add_argument(
74
+ "--threshold", "--ml-threshold",
75
+ dest="threshold",
76
+ type=float,
77
+ default=0.5,
78
+ help="Probability threshold for ML triage (default: 0.5)",
79
+ )
80
+ subparser.add_argument(
81
+ "--suppress-fp", "--ml-suppress-fp",
82
+ dest="suppress_fp",
83
+ action="store_true",
84
+ help="Suppress non-CRITICAL findings classified as false positives",
85
+ )
86
+
87
+
88
+ def build_parser() -> argparse.ArgumentParser:
89
+ parser = argparse.ArgumentParser(
90
+ prog="sidik-ml",
91
+ description="SIDIK-ML: Explainable Non-ANN ML Extension for SIDIK Static Security Analysis",
92
+ epilog=(
93
+ "Examples (symmetric with SIDIK):\n"
94
+ " sidik-ml -i # Launch Amber-Orange Interactive Console (TUI)\n"
95
+ " sidik-ml --gui # Launch SIDIK-ML Desktop GUI (alias: sidik-ml gui)\n"
96
+ " sidik-ml . # Scan current directory with ML triage\n"
97
+ " sidik-ml --target . --include-deps --format html # Full Secret + SCA HTML dashboard\n"
98
+ " sidik-ml train data.jsonl -o artifacts/ --stratified"
99
+ ),
100
+ formatter_class=argparse.RawDescriptionHelpFormatter,
101
+ )
102
+ parser.add_argument(
103
+ "--interactive", "-i", "--cli",
104
+ action="store_true",
105
+ help="Launch interactive CLI console window (TUI) with SIDIK-ML active",
106
+ )
107
+ parser.add_argument(
108
+ "--gui",
109
+ action="store_true",
110
+ help="Launch SIDIK-ML Desktop GUI",
111
+ )
112
+ parser.add_argument(
113
+ "--version",
114
+ "-v",
115
+ action="version",
116
+ version=f"SIDIK-ML v{ML_VERSION} (Explainable Non-ANN ML Extension | Core SIDIK v{SIDIK_VERSION})",
117
+ )
118
+ sub = parser.add_subparsers(dest="command", required=False)
119
+
120
+ p_scan = sub.add_parser("scan", help="Scan a path via SIDIK and apply verified ML triage & optional SCA")
121
+ p_scan.add_argument("target", nargs="?", default=None, help="File or directory path to scan")
122
+ p_scan.add_argument("--target", "-t", dest="target_opt", default=None, help="File or directory path to scan")
123
+ _add_shared_ml_args(p_scan)
124
+ p_scan.add_argument(
125
+ "--include-deps",
126
+ action="store_true",
127
+ help="Also inspect Python dependency manifests against offline OSV advisories",
128
+ )
129
+ p_scan.add_argument(
130
+ "--format", "-f",
131
+ choices=["compact", "console", "json", "markdown", "csv", "html", "sarif", "github"],
132
+ default="compact",
133
+ help="Report format (compact preserves single-line ML triage; others use SIDIK ReportFormatter)",
134
+ )
135
+ p_scan.add_argument("--output", "-o", default=None, help="Optional output file path for report")
136
+ p_scan.add_argument("--lang", choices=["id", "en"], default="id", help="Report language (default: id)")
137
+ p_scan.add_argument("--json", action="store_true", help="Emit JSON output (equivalent to --format json in compact mode)")
138
+
139
+ p_tui = sub.add_parser("interactive", aliases=["cli", "tui"], help="Launch SIDIK Interactive CLI Console with SIDIK-ML plugin active")
140
+ p_tui.add_argument("--lang", choices=["id", "en"], default="id", help="Initial console language (default: id)")
141
+ _add_shared_ml_args(p_tui)
142
+
143
+ p_gui = sub.add_parser("gui", help="Launch SIDIK Desktop GUI with SIDIK-ML plugin pre-enabled")
144
+ _add_shared_ml_args(p_gui)
145
+
146
+ p_feat = sub.add_parser("extract-features", help="Export leakage-free feature JSONL from target candidates")
147
+ p_feat.add_argument("target", help="File or directory path to inspect")
148
+ p_feat.add_argument("--output", "-o", required=True, help="Output JSONL file path")
149
+ p_feat.add_argument("--repo-id", default="local_target", help="Repository identifier tag for exported records")
150
+
151
+ p_ver = sub.add_parser("verify-model", help="Verify SHA-256 checksum of an offline .skops artifact")
152
+ p_ver.add_argument("model_path", help="Path to .skops artifact")
153
+ p_ver.add_argument("--sha256", required=True, help="Expected SHA-256 hex digest")
154
+
155
+ p_train = sub.add_parser("train", help="Train and evaluate classical Non-ANN models on a labeled JSONL dataset")
156
+ p_train.add_argument("dataset", help="Path to labeled JSONL dataset")
157
+ p_train.add_argument("--output-dir", "-o", required=True, help="Directory for model artifact, manifest, and report")
158
+ p_train.add_argument("--stratified", action="store_true", help="Use StratifiedGroupKFold split and CV selection")
159
+ p_train.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)")
160
+ p_train.add_argument("--bootstrap", type=int, default=300, help="Bootstrap resamples for 95%% CI (default: 300)")
161
+
162
+ return parser
163
+
164
+
165
+ def _render_report_text(report, fmt: str, lang: str) -> str:
166
+ if fmt == "json":
167
+ return ReportFormatter.to_json(report)
168
+ if fmt == "markdown":
169
+ return ReportFormatter.to_markdown(report, lang=lang)
170
+ if fmt == "csv":
171
+ return ReportFormatter.to_csv(report)
172
+ if fmt == "html":
173
+ return ReportFormatter.to_html(report, lang=lang)
174
+ if fmt == "sarif":
175
+ return ReportFormatter.to_sarif(report)
176
+ if fmt == "github":
177
+ return ReportFormatter.to_github_annotations(report, lang=lang)
178
+ return ReportFormatter.to_console_summary(report, lang=lang)
179
+
180
+
181
+ def main(argv: Optional[List[str]] = None) -> int:
182
+ raw_argv = list(sys.argv[1:]) if argv is None else list(argv)
183
+ if not raw_argv and argv is None and sys.stdin.isatty() and sys.stdout.isatty():
184
+ raw_argv = ["interactive"]
185
+
186
+ parser = build_parser()
187
+ args = parser.parse_args(_normalize_argv(raw_argv))
188
+
189
+ if args.command in ("interactive", "cli", "tui") or (args.command is None and args.interactive):
190
+ from sidik.cli import run_interactive_cli
191
+ return run_interactive_cli(
192
+ initial_lang=getattr(args, "lang", "id"),
193
+ enable_ml_plugin=True,
194
+ ml_model_path=getattr(args, "model", None),
195
+ ml_sha256=getattr(args, "sha256", None),
196
+ ml_threshold=getattr(args, "threshold", 0.5),
197
+ ml_suppress_fp=getattr(args, "suppress_fp", False),
198
+ banner_title="SIDIK-ML",
199
+ )
200
+
201
+ if args.command == "gui" or (args.command is None and args.gui):
202
+ from sidik.gui import main as sidik_gui_main
203
+ sidik_gui_main(
204
+ enable_ml=True,
205
+ ml_model_path=getattr(args, "model", None),
206
+ ml_sha256=getattr(args, "sha256", None),
207
+ ml_threshold=getattr(args, "threshold", 0.5),
208
+ ml_suppress_fp=getattr(args, "suppress_fp", False),
209
+ app_brand="SIDIK-ML",
210
+ )
211
+ return 0
212
+
213
+ if args.command is None:
214
+ parser.print_help()
215
+ return 2
216
+
217
+ if args.command == "train":
218
+ records = load_jsonl_dataset(args.dataset)
219
+ report = train_and_compare_models(
220
+ records,
221
+ random_state=args.seed,
222
+ output_dir=args.output_dir,
223
+ dataset_path=args.dataset,
224
+ use_stratified_split=args.stratified,
225
+ n_bootstrap=args.bootstrap,
226
+ )
227
+ print(json.dumps({"best_model": report["best_model"], "saved_artifact": report["saved_artifact"]}, indent=2))
228
+ return 0
229
+
230
+ if args.command == "verify-model":
231
+ ok = verify_artifact_sha256(args.model_path, args.sha256)
232
+ print("VERIFIED" if ok else "CHECKSUM_MISMATCH")
233
+ return 0 if ok else 1
234
+
235
+ if args.command == "extract-features":
236
+ scanner = SecurityScanner(enable_dependency_scan=False, measure_memory=False)
237
+ cands = scanner.extract_secret_candidates(args.target, include_filtered=True)
238
+ with open(args.output, "w", encoding="utf-8") as f:
239
+ for c in cands:
240
+ rec = {
241
+ "candidate_id": c.candidate_id,
242
+ "repo_id": args.repo_id,
243
+ "file_path": c.file_path,
244
+ "value_sha256": c.value_sha256,
245
+ "masked_context": c.code_context.get("masked_line", c.masked_value),
246
+ "deterministic_passed": bool(c.deterministic_decision.get("passed_deterministic_filter")),
247
+ "severity": c.severity.value if hasattr(c.severity, "value") else str(c.severity),
248
+ "features": extract_feature_dict(c),
249
+ }
250
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
251
+ print(f"Exported {len(cands)} candidate feature rows to {args.output}")
252
+ return 0
253
+
254
+ scan_target = args.target_opt or args.target
255
+ if not scan_target:
256
+ parser.error("Target path is required (e.g., 'sidik-ml .' or 'sidik-ml scan <path>' or 'sidik-ml -i')")
257
+
258
+ resolved_sha: Optional[str] = args.sha256
259
+ if args.model:
260
+ try:
261
+ _, resolved_sha = resolve_model_and_sha256(args.model, args.sha256)
262
+ except ValueError as exc:
263
+ print(f"Error: {exc}", file=sys.stderr)
264
+ return 2
265
+
266
+ use_full_formatter = (args.format != "compact") or bool(args.include_deps) or bool(args.output)
267
+ if use_full_formatter:
268
+ fmt = "json" if (args.format == "compact" and args.json) else ("console" if args.format == "compact" else args.format)
269
+ plugin = SidikMLPlugin()
270
+ scanner = SecurityScanner(
271
+ enable_secret_scan=True,
272
+ enable_dependency_scan=bool(args.include_deps),
273
+ measure_memory=True,
274
+ post_scan_plugins=[plugin],
275
+ plugin_options={
276
+ "model_path": args.model,
277
+ "sha256": resolved_sha,
278
+ "threshold": args.threshold,
279
+ "suppress_false_positives": args.suppress_fp,
280
+ },
281
+ )
282
+ scan_report = scanner.scan_path(scan_target)
283
+ out_text = _render_report_text(scan_report, fmt=fmt, lang=args.lang)
284
+ if args.output:
285
+ out_dir = os.path.dirname(os.path.abspath(args.output))
286
+ if out_dir:
287
+ os.makedirs(out_dir, exist_ok=True)
288
+ with open(args.output, "w", encoding="utf-8") as f:
289
+ f.write(out_text)
290
+ print(f"Report written to {args.output}")
291
+ else:
292
+ print(out_text)
293
+ return 0
294
+
295
+ classifier = None
296
+ model_name = "deterministic_pass_through"
297
+ if args.model and resolved_sha:
298
+ classifier = load_verified_skops_model(args.model, resolved_sha)
299
+ model_name = args.model
300
+
301
+ pipeline = HybridTriagePipeline(
302
+ classifier=classifier,
303
+ model_name=model_name,
304
+ policy=TriagePolicy(
305
+ decision_threshold=args.threshold,
306
+ suppress_false_positives=args.suppress_fp,
307
+ ),
308
+ )
309
+ findings = pipeline.scan_path(scan_target, include_filtered=True)
310
+ if args.json:
311
+ print(json.dumps([f.to_dict() for f in findings], indent=2))
312
+ else:
313
+ for f in findings:
314
+ print(f"[{f.severity}] {f.final_action} p={f.ml_prediction.secret_probability:.2f} {f.file_path}:{f.line_number} {f.masked_value}")
315
+ return 0
316
+
317
+
318
+ def launch_gui(argv: Optional[List[str]] = None) -> int:
319
+ """Dedicated entry point for ``sidik-ml-gui`` wrapping SIDIK's desktop GUI."""
320
+ parser = argparse.ArgumentParser(prog="sidik-ml-gui", description="Launch SIDIK-ML Desktop GUI")
321
+ _add_shared_ml_args(parser)
322
+ args = parser.parse_args(argv)
323
+ return main([
324
+ "gui",
325
+ *(["--model", args.model] if args.model else []),
326
+ *(["--sha256", args.sha256] if args.sha256 else []),
327
+ "--threshold", str(args.threshold),
328
+ *(["--suppress-fp"] if args.suppress_fp else []),
329
+ ])
330
+
331
+
332
+ if __name__ == "__main__":
333
+ sys.exit(main())
sidik_ml/dataset.py ADDED
@@ -0,0 +1,230 @@
1
+ """Dataset loading, deduplication, and repository-grouped leakage-free splitting."""
2
+
3
+ from dataclasses import asdict, dataclass
4
+ import json
5
+ import os
6
+ import re
7
+ from typing import Dict, Iterator, List, Tuple
8
+
9
+ from sklearn.model_selection import GroupShuffleSplit, StratifiedGroupKFold
10
+
11
+ from sidik_ml.features import FEATURE_NAMES
12
+
13
+
14
+ @dataclass
15
+ class LabeledCandidateRecord:
16
+ """Represents a labeled secret candidate ready for leakage-free classical ML workflows."""
17
+ candidate_id: str
18
+ repo_id: str
19
+ file_path: str
20
+ value_sha256: str
21
+ masked_context: str
22
+ label: int
23
+ features: Dict[str, float]
24
+ deterministic_passed: bool = True
25
+ severity: str = "MEDIUM"
26
+
27
+ def to_dict(self) -> Dict[str, object]:
28
+ return asdict(self)
29
+
30
+ @classmethod
31
+ def from_dict(cls, data: Dict[str, object]) -> "LabeledCandidateRecord":
32
+ raw_feats = data.get("features")
33
+ feat_dict: Dict[str, float] = {}
34
+ if isinstance(raw_feats, dict):
35
+ feat_dict = {str(k): float(v) for k, v in raw_feats.items()}
36
+ raw_label = data.get("label", 0)
37
+ label_val = int(raw_label) if isinstance(raw_label, (int, float, str, bool)) else 0
38
+ return cls(
39
+ candidate_id=str(data.get("candidate_id", "")),
40
+ repo_id=str(data.get("repo_id", "")),
41
+ file_path=str(data.get("file_path", "")),
42
+ value_sha256=str(data.get("value_sha256", "")),
43
+ masked_context=str(data.get("masked_context", "")),
44
+ label=label_val,
45
+ features=feat_dict,
46
+ deterministic_passed=bool(data.get("deterministic_passed", True)),
47
+ severity=str(data.get("severity", "MEDIUM")),
48
+ )
49
+
50
+
51
+ def _normalize_context(text: str) -> str:
52
+ return re.sub(r"\s+", " ", text.strip().lower())
53
+
54
+
55
+ def load_jsonl_dataset(path: str) -> List[LabeledCandidateRecord]:
56
+ """Loads labeled candidate records from a UTF-8 JSONL file."""
57
+ records: List[LabeledCandidateRecord] = []
58
+ with open(path, "r", encoding="utf-8") as f:
59
+ for line in f:
60
+ stripped = line.strip()
61
+ if not stripped:
62
+ continue
63
+ obj = json.loads(stripped)
64
+ records.append(LabeledCandidateRecord.from_dict(obj))
65
+ return records
66
+
67
+
68
+ def save_jsonl_dataset(records: List[LabeledCandidateRecord], path: str) -> None:
69
+ """Saves labeled candidate records to a UTF-8 JSONL file."""
70
+ parent = os.path.dirname(os.path.abspath(path))
71
+ if parent:
72
+ os.makedirs(parent, exist_ok=True)
73
+ with open(path, "w", encoding="utf-8") as f:
74
+ for rec in records:
75
+ f.write(json.dumps(rec.to_dict(), ensure_ascii=False) + "\n")
76
+
77
+
78
+ def deduplicate_records(
79
+ records: List[LabeledCandidateRecord],
80
+ ) -> Tuple[List[LabeledCandidateRecord], int]:
81
+ """Removes exact and context-equivalent duplicate samples prior to dataset splitting."""
82
+ seen: set[Tuple[str, str]] = set()
83
+ unique: List[LabeledCandidateRecord] = []
84
+ removed = 0
85
+ for rec in records:
86
+ key = (rec.value_sha256.strip().lower(), _normalize_context(rec.masked_context))
87
+ if key in seen:
88
+ removed += 1
89
+ continue
90
+ seen.add(key)
91
+ unique.append(rec)
92
+ return unique, removed
93
+
94
+
95
+ def resolve_cross_repo_value_duplicates(
96
+ records: List[LabeledCandidateRecord],
97
+ ) -> Tuple[List[LabeledCandidateRecord], Dict[str, int]]:
98
+ """Enforces zero cross-repository value_sha256 overlap and drops conflicting-label hashes."""
99
+ ordered = sorted(records, key=lambda r: (r.repo_id, r.file_path, r.candidate_id))
100
+ grouped: Dict[str, List[LabeledCandidateRecord]] = {}
101
+ nohash_records: List[LabeledCandidateRecord] = []
102
+
103
+ for rec in ordered:
104
+ h = rec.value_sha256.strip().lower()
105
+ if not h:
106
+ nohash_records.append(rec)
107
+ continue
108
+ grouped.setdefault(h, []).append(rec)
109
+
110
+ resolved: List[LabeledCandidateRecord] = list(nohash_records)
111
+ cross_repo_deduped = 0
112
+ conflicting_dropped = 0
113
+
114
+ for h in sorted(grouped):
115
+ grp = grouped[h]
116
+ distinct_labels = {int(r.label) for r in grp}
117
+ if len(distinct_labels) > 1:
118
+ conflicting_dropped += len(grp)
119
+ continue
120
+ resolved.append(grp[0])
121
+ cross_repo_deduped += len(grp) - 1
122
+
123
+ stats = {
124
+ "input_records": len(records),
125
+ "output_records": len(resolved),
126
+ "cross_repo_value_deduped": cross_repo_deduped,
127
+ "conflicting_label_dropped": conflicting_dropped,
128
+ }
129
+ return resolved, stats
130
+
131
+
132
+ def assert_no_leakage(
133
+ train_records: List[LabeledCandidateRecord],
134
+ test_records: List[LabeledCandidateRecord],
135
+ ) -> None:
136
+ """Raises ValueError if repository IDs or candidate value hashes overlap between train and test."""
137
+ train_repos = {r.repo_id for r in train_records if r.repo_id}
138
+ test_repos = {r.repo_id for r in test_records if r.repo_id}
139
+ overlap_repos = train_repos.intersection(test_repos)
140
+ if overlap_repos:
141
+ raise ValueError(f"Repository leakage detected across splits: {sorted(overlap_repos)[:5]}")
142
+
143
+ train_hashes = {r.value_sha256 for r in train_records if r.value_sha256}
144
+ test_hashes = {r.value_sha256 for r in test_records if r.value_sha256}
145
+ overlap_hashes = train_hashes.intersection(test_hashes)
146
+ if overlap_hashes:
147
+ raise ValueError(
148
+ f"Candidate string hash leakage detected across splits ({len(overlap_hashes)} overlapping hashes)"
149
+ )
150
+
151
+
152
+ def repository_grouped_split(
153
+ records: List[LabeledCandidateRecord],
154
+ test_size: float = 0.2,
155
+ random_state: int = 42,
156
+ ) -> Tuple[List[LabeledCandidateRecord], List[LabeledCandidateRecord]]:
157
+ """Splits records into train and held-out test sets strictly grouped by repo_id."""
158
+ if len(records) < 2:
159
+ raise ValueError("At least 2 records are required for a grouped train/test split.")
160
+ groups = [r.repo_id or r.candidate_id for r in records]
161
+ unique_groups = set(groups)
162
+ if len(unique_groups) < 2:
163
+ raise ValueError("At least 2 distinct repo_id groups are required for repository-grouped splitting.")
164
+
165
+ splitter = GroupShuffleSplit(n_splits=1, test_size=test_size, random_state=random_state)
166
+ labels = [r.label for r in records]
167
+ train_idx, test_idx = next(splitter.split(records, labels, groups=groups))
168
+
169
+ train_records = [records[int(i)] for i in train_idx]
170
+ test_records = [records[int(i)] for i in test_idx]
171
+ assert_no_leakage(train_records, test_records)
172
+ return train_records, test_records
173
+
174
+
175
+ def stratified_repository_split(
176
+ records: List[LabeledCandidateRecord],
177
+ n_splits: int = 5,
178
+ test_fold: int = 0,
179
+ ) -> Tuple[List[LabeledCandidateRecord], List[LabeledCandidateRecord]]:
180
+ """Splits records into stratified train and held-out test folds grouped strictly by repo_id."""
181
+ if n_splits < 2:
182
+ raise ValueError("n_splits must be at least 2.")
183
+ if not (0 <= test_fold < n_splits):
184
+ raise ValueError(f"test_fold must satisfy 0 <= test_fold < {n_splits}.")
185
+ groups = [r.repo_id or r.candidate_id for r in records]
186
+ unique_groups = set(groups)
187
+ if len(unique_groups) < n_splits:
188
+ raise ValueError(
189
+ f"At least {n_splits} distinct repo_id groups are required for {n_splits}-fold stratified repo split."
190
+ )
191
+
192
+ labels = [r.label for r in records]
193
+ cv = StratifiedGroupKFold(n_splits=n_splits)
194
+ for fold_idx, (tr_idx, te_idx) in enumerate(cv.split(records, labels, groups=groups)):
195
+ if fold_idx == test_fold:
196
+ train_records = [records[int(i)] for i in tr_idx]
197
+ test_records = [records[int(i)] for i in te_idx]
198
+ assert_no_leakage(train_records, test_records)
199
+ return train_records, test_records
200
+
201
+ raise ValueError(f"Unable to select fold {test_fold} from {n_splits}-fold StratifiedGroupKFold.")
202
+
203
+
204
+ def iter_repository_group_folds(
205
+ records: List[LabeledCandidateRecord],
206
+ n_splits: int = 5,
207
+ ) -> Iterator[Tuple[int, List[LabeledCandidateRecord], List[LabeledCandidateRecord]]]:
208
+ """Yields leakage-verified StratifiedGroupKFold splits grouped by repo_id."""
209
+ groups = [r.repo_id or r.candidate_id for r in records]
210
+ labels = [r.label for r in records]
211
+ cv = StratifiedGroupKFold(n_splits=n_splits)
212
+ for fold_idx, (tr_idx, va_idx) in enumerate(cv.split(records, labels, groups=groups)):
213
+ tr_recs = [records[int(i)] for i in tr_idx]
214
+ va_recs = [records[int(i)] for i in va_idx]
215
+ assert_no_leakage(tr_recs, va_recs)
216
+ yield fold_idx, tr_recs, va_recs
217
+
218
+
219
+ def records_to_matrix(
220
+ records: List[LabeledCandidateRecord],
221
+ selected_features: List[str] | None = None,
222
+ ) -> Tuple[List[List[float]], List[int], List[str]]:
223
+ """Converts labeled records into aligned feature matrix X, labels y, and feature name list."""
224
+ cols = list(selected_features) if selected_features is not None else list(FEATURE_NAMES)
225
+ X: List[List[float]] = []
226
+ y: List[int] = []
227
+ for rec in records:
228
+ X.append([float(rec.features.get(col, 0.0)) for col in cols])
229
+ y.append(int(rec.label))
230
+ return X, y, cols