Files
ResearchMethods_Project/validation/export_spss_all.py
T
Joren 303cf016be Drop duplicate label columns from SPSS exports
tier_label, model_label, condition_label, and model_order duplicated the
numeric codes; SPSS value labels already carry the names. model is now a
numeric code (0=Bandit, 1=Semgrep, 2=DeepSeek V4.1 Flash, 3=Argon) with
value labels in the .sav files and .sps syntax. Long file drops from 38 to
34 variables, summary from 30 to 26.
2026-11-21 15:12:39 +01:00

1212 lines
45 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Export all detectors and conditions to SPSS-ready files.
Includes the traditional SAST baselines (Bandit, Semgrep), the open-weight
DeepSeek V4.1 Flash, and the frontier Gemini 4 Argon.
Outputs:
sast_all_long.csv one row per sample x detector x condition (2,400 rows)
sast_all_wide.csv one row per sample, paired columns for every detector
sast_all_summary.csv aggregate metrics by detector x condition
sast_all_category.csv per-category metrics by detector x condition
sast_all_paired.csv within-detector condition-pair McNemar tests
sast_all_between.csv between-detector McNemar tests by condition
codebook.csv variable/value codebook
codebook.md human-readable codebook
sast_all_import.sps import and describe the long file
sast_all_wide.sps import the wide file and run paired tests
sast_all_summary.sps import the aggregate summary
sast_all_category.sps import the per-category summary
Usage:
python3 validation/export_spss_all.py
"""
from __future__ import annotations
import argparse
import csv
import math
import sqlite3
from pathlib import Path
from export_spss import (
BASE_DIR,
CATEGORY_CODES,
OTHER_CATEGORY_CODE,
category_code,
cwe_num,
mcnemar_exact,
run_meta,
write_csv,
)
DEFAULT_OUTPUT = BASE_DIR / "validation" / "spss_all"
TOOLS_CSV = BASE_DIR / "validation" / "sast_tools" / "tools_long.csv"
CONDITIONS = [
(0, "original"),
(1, "obfuscated_v2"),
(2, "comments_removed"),
]
# (condition, wide-file suffix, display word)
CONDITION_SUFFIXES = [
(0, "orig", "Original"),
(1, "obf", "Obfuscated"),
(2, "comments", "Comments removed"),
]
# tier: 0 = traditional SAST, 1 = open-weight LLM, 2 = frontier LLM
DETECTORS = [
{
"kind": "sast",
"tool": "Bandit",
"model": "bandit",
"model_label": "Bandit",
"tier": 0,
"tier_label": "Traditional SAST",
"prefix": "bandit",
},
{
"kind": "sast",
"tool": "Semgrep",
"model": "semgrep",
"model_label": "Semgrep",
"tier": 0,
"tier_label": "Traditional SAST",
"prefix": "semgrep",
},
{
"kind": "llm",
"model": "deepseek-v4.1-flash",
"model_label": "DeepSeek V4.1 Flash",
"tier": 1,
"tier_label": "Open-weight",
"prefix": "deepseek",
"db": "results/sast_runs.sqlite3",
"original_run": "deepseek-v2-original",
"obfuscated_run": "deepseek-v2-obfuscated",
"comments_removed_run": "deepseek-comments-removed",
},
{
"kind": "llm",
"model": "gemini-4-argon",
"model_label": "Gemini 4 Argon",
"tier": 2,
"tier_label": "Frontier",
"prefix": "argon",
"db": "results/argon.sqlite3",
"original_run": "argon-original",
"obfuscated_run": "argon-obfuscated",
"comments_removed_run": "argon-comments-removed",
},
]
for index, detector in enumerate(DETECTORS):
detector["code"] = index
def as_int(value: object, default: int = 0) -> int:
try:
text = str(value).strip()
return int(float(text)) if text else default
except (TypeError, ValueError):
return default
def as_binary(value: object) -> int:
"""Accept Yes/No, true/false, and 1/0 database values."""
return 1 if str(value).strip().lower() in {"yes", "true", "1"} else 0
def latest_rows_for_condition(
connection: sqlite3.Connection, run_id: str, condition: str
) -> dict[str, sqlite3.Row]:
rows = connection.execute(
"""
SELECT a.*
FROM attempts a
JOIN (
SELECT sample_path, MAX(call_index) AS max_index
FROM attempts
WHERE run_id = ? AND condition = ?
GROUP BY sample_path
) latest
ON latest.sample_path = a.sample_path
AND latest.max_index = a.call_index
WHERE a.run_id = ? AND a.condition = ?
ORDER BY a.sample_name
""",
(run_id, condition, run_id, condition),
).fetchall()
return {row["sample_name"]: row for row in rows}
def attempt_totals(
db_path: Path, run_id: str, condition: str
) -> tuple[int, int, int]:
connection = sqlite3.connect(db_path)
connection.row_factory = sqlite3.Row
try:
row = connection.execute(
"""
SELECT COUNT(*) AS calls,
COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
COALESCE(SUM(completion_tokens), 0) AS completion_tokens
FROM attempts
WHERE run_id = ? AND condition = ?
""",
(run_id, condition),
).fetchone()
return int(row["calls"]), int(row["prompt_tokens"]), int(row["completion_tokens"])
finally:
connection.close()
def base_row(detector: dict[str, object], condition: int) -> dict:
return {
"tier": detector["tier"],
"model": detector["code"],
"condition": condition,
}
def load_llm_rows(detector: dict[str, object]) -> list[dict]:
db_path = BASE_DIR / str(detector["db"])
rows: list[dict] = []
connection = sqlite3.connect(db_path)
connection.row_factory = sqlite3.Row
try:
for condition, condition_label in CONDITIONS:
if condition == 0:
run_id = str(detector["original_run"])
elif condition == 1:
run_id = str(detector["obfuscated_run"])
else:
run_id = str(detector["comments_removed_run"])
meta = run_meta(connection, run_id)
source = latest_rows_for_condition(connection, run_id, condition_label)
calls, prompt_total, completion_total = attempt_totals(
db_path, run_id, condition_label
)
for sample_id, row in sorted(source.items()):
expected = as_binary(row["expected_vulnerable"])
predicted = as_binary(row["flagged"])
tp = int(expected == 1 and predicted == 1)
fp = int(expected == 0 and predicted == 1)
tn = int(expected == 0 and predicted == 0)
fn = int(expected == 1 and predicted == 0)
correct = int(expected == predicted)
expected_category = row["expected_category"] or "None"
predicted_category = row["category"] or "None"
expected_cwe = row["expected_cwe"] or "None"
predicted_cwe = row["cwe"] or "None"
category_correct = int(
tp and category_code(predicted_category) == category_code(expected_category)
)
cwe_correct = int(tp and cwe_num(predicted_cwe) == cwe_num(expected_cwe))
strict_correct = int(
correct and (expected == 0 or cwe_num(predicted_cwe) == cwe_num(expected_cwe))
)
item = {
"sample_id": sample_id,
**base_row(detector, condition),
"in_scope": as_int(row["in_target_scope"]),
"expected_vuln": expected,
"predicted_vuln": predicted,
"correct_flag": correct,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"expected_category": expected_category,
"expected_category_code": category_code(expected_category),
"predicted_category": predicted_category,
"predicted_category_code": category_code(predicted_category),
"expected_cwe": expected_cwe,
"expected_cwe_num": cwe_num(expected_cwe),
"predicted_cwe": predicted_cwe,
"predicted_cwe_num": cwe_num(predicted_cwe),
"category_correct": category_correct,
"cwe_correct": cwe_correct,
"strict_correct": strict_correct,
"wrong_category_tp": int(tp and not category_correct),
"parse_ok": as_int(row["parse_ok"]),
"prompt_tokens": as_int(row["prompt_tokens"]),
"completion_tokens": as_int(row["completion_tokens"]),
"total_tokens": as_int(row["total_tokens"]),
"latency_ms": as_int(row["latency_ms"]),
"calls": as_int(row["call_index"]),
"run_id": run_id,
"prompt_hash": str(meta["prompt_hash"]),
"findings": 0,
"token_data_available": 1,
"all_attempt_calls": calls,
"all_attempt_prompt_tokens": prompt_total,
"all_attempt_completion_tokens": completion_total,
}
rows.append(item)
finally:
connection.close()
return rows
def load_sast_rows(detector: dict[str, object]) -> list[dict]:
rows: list[dict] = []
with TOOLS_CSV.open(encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
for row in reader:
if row["tool_label"] != detector["tool"]:
continue
condition = as_int(row["condition"])
expected_category = row["expected_category"] or "None"
predicted_category = row["predicted_category"] or "None"
expected_cwe = row["expected_cwe"] or "None"
predicted_cwe = row["predicted_cwe"] or "None"
rows.append(
{
"sample_id": row["sample_id"],
**base_row(detector, condition),
"in_scope": as_int(row["in_scope"]),
"expected_vuln": as_binary(row["expected_vuln"]),
"predicted_vuln": as_binary(row["flagged"]),
"correct_flag": as_int(row["correct_flag"]),
"tp": as_int(row["tp"]),
"fp": as_int(row["fp"]),
"tn": as_int(row["tn"]),
"fn": as_int(row["fn"]),
"expected_category": expected_category,
"expected_category_code": category_code(expected_category),
"predicted_category": predicted_category,
"predicted_category_code": category_code(predicted_category),
"expected_cwe": expected_cwe,
"expected_cwe_num": cwe_num(expected_cwe),
"predicted_cwe": predicted_cwe,
"predicted_cwe_num": cwe_num(predicted_cwe),
"category_correct": as_int(row["category_correct"]),
"cwe_correct": as_int(row["cwe_correct"]),
"strict_correct": as_int(row["strict_correct"]),
"wrong_category_tp": as_int(row["wrong_category_tp"]),
"parse_ok": 1,
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
"latency_ms": 0,
"calls": 0,
"run_id": str(detector["model"]),
"prompt_hash": "NA",
"findings": as_int(row["target_finding_count"]),
"token_data_available": 0,
"all_attempt_calls": 0,
"all_attempt_prompt_tokens": 0,
"all_attempt_completion_tokens": 0,
}
)
return rows
def build_long(detectors: list[dict]) -> list[dict]:
rows: list[dict] = []
for detector in detectors:
if detector["kind"] == "sast":
rows.extend(load_sast_rows(detector))
else:
rows.extend(load_llm_rows(detector))
rows.sort(
key=lambda row: (
int(row["model"]),
int(row["condition"]),
str(row["sample_id"]),
)
)
return rows
LONG_FIELDS = [
("sample_id", "A20"),
("tier", "F1.0"),
("model", "F1.0"),
("condition", "F1.0"),
("in_scope", "F1.0"),
("expected_vuln", "F1.0"),
("predicted_vuln", "F1.0"),
("correct_flag", "F1.0"),
("tp", "F1.0"),
("fp", "F1.0"),
("tn", "F1.0"),
("fn", "F1.0"),
("expected_category", "A20"),
("expected_category_code", "F3.0"),
("predicted_category", "A20"),
("predicted_category_code", "F3.0"),
("expected_cwe", "A10"),
("expected_cwe_num", "F5.0"),
("predicted_cwe", "A10"),
("predicted_cwe_num", "F5.0"),
("category_correct", "F1.0"),
("cwe_correct", "F1.0"),
("strict_correct", "F1.0"),
("wrong_category_tp", "F1.0"),
("parse_ok", "F1.0"),
("prompt_tokens", "F10.0"),
("completion_tokens", "F10.0"),
("total_tokens", "F10.0"),
("latency_ms", "F10.0"),
("calls", "F5.0"),
("run_id", "A45"),
("prompt_hash", "A64"),
("findings", "F5.0"),
("token_data_available", "F1.0"),
]
def summarize(rows: list[dict]) -> dict:
n = len(rows)
tp = sum(int(row["tp"]) for row in rows)
fp = sum(int(row["fp"]) for row in rows)
tn = sum(int(row["tn"]) for row in rows)
fn = sum(int(row["fn"]) for row in rows)
in_scope = sum(int(row["in_scope"]) for row in rows)
accuracy = (tp + tn) / n if n else 0.0
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
fpr = fp / (fp + tn) if fp + tn else 0.0
tnr = tn / (tn + fp) if tn + fp else 0.0
balanced_accuracy = (recall + tnr) / 2
mcc_denominator = ((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) ** 0.5
mcc = (tp * tn - fp * fn) / mcc_denominator if mcc_denominator else 0.0
category_correct = sum(int(row["category_correct"]) for row in rows)
cwe_correct = sum(int(row["cwe_correct"]) for row in rows)
strict_correct = sum(int(row["strict_correct"]) for row in rows)
wrong_category_tp = sum(int(row["wrong_category_tp"]) for row in rows)
total_tokens = sum(int(row["total_tokens"]) for row in rows)
mean_latency = sum(int(row["latency_ms"]) for row in rows) / n if n else 0.0
first = rows[0]
all_attempt_calls = int(first["all_attempt_calls"])
all_attempt_prompt = int(first["all_attempt_prompt_tokens"])
all_attempt_completion = int(first["all_attempt_completion_tokens"])
return {
"tier": first["tier"],
"model": first["model"],
"condition": first["condition"],
"n_all": n,
"n_in_scope": in_scope,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"accuracy": round(accuracy, 6),
"strict_accuracy": round(strict_correct / n, 6) if n else 0.0,
"precision": round(precision, 6),
"recall": round(recall, 6),
"fpr": round(fpr, 6),
"tnr": round(tnr, 6),
"balanced_accuracy": round(balanced_accuracy, 6),
"f1": round(f1, 6),
"mcc": round(mcc, 6),
"category_accuracy_tp": round(category_correct / tp, 6) if tp else 0.0,
"cwe_accuracy_tp": round(cwe_correct / tp, 6) if tp else 0.0,
"wrong_category_tp": wrong_category_tp,
"total_tokens_final": total_tokens,
"total_tokens_all_attempts": all_attempt_prompt + all_attempt_completion,
"mean_latency_ms_in_scope": round(mean_latency, 2),
"api_calls_all_attempts": all_attempt_calls,
"token_data_available": first["token_data_available"],
}
def summarize_all(long_rows: list[dict]) -> list[dict]:
summaries: list[dict] = []
for detector in DETECTORS:
for condition, _ in CONDITIONS:
subset = [
row
for row in long_rows
if row["model"] == detector["code"] and row["condition"] == condition
]
if subset:
summaries.append(summarize(subset))
return summaries
def category_summaries(long_rows: list[dict]) -> list[dict]:
output: list[dict] = []
for detector in DETECTORS:
for condition, _ in CONDITIONS:
subset = [
row
for row in long_rows
if row["model"] == detector["code"] and row["condition"] == condition
]
categories = sorted({row["expected_category"] for row in subset})
for category in categories:
cat_rows = [row for row in subset if row["expected_category"] == category]
tp = sum(int(row["tp"]) for row in cat_rows)
fp = sum(int(row["fp"]) for row in cat_rows)
tn = sum(int(row["tn"]) for row in cat_rows)
fn = sum(int(row["fn"]) for row in cat_rows)
n = len(cat_rows)
accuracy = (tp + tn) / n if n else 0.0
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = (
2 * precision * recall / (precision + recall)
if precision + recall
else 0.0
)
output.append(
{
"tier": detector["tier"],
"model": detector["code"],
"condition": condition,
"expected_category": category,
"expected_category_code": category_code(category),
"n": n,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"accuracy": round(accuracy, 6),
"precision": round(precision, 6),
"recall": round(recall, 6),
"f1": round(f1, 6),
}
)
output.sort(
key=lambda row: (
int(row["model"]),
int(row["condition"]),
str(row["expected_category"]),
)
)
return output
def build_wide(long_rows: list[dict]) -> list[dict]:
sample_ids = sorted({row["sample_id"] for row in long_rows})
lookup = {
(row["model"], row["condition"], row["sample_id"]): row for row in long_rows
}
# Expected labels are identical across detectors; take them from Bandit (code 0) original.
expected_source = {
row["sample_id"]: row
for row in long_rows
if row["model"] == 0 and row["condition"] == 0
}
wide: list[dict] = []
for sample_id in sample_ids:
expected = expected_source[sample_id]
item: dict[str, object] = {
"sample_id": sample_id,
"in_scope": expected["in_scope"],
"expected_vuln": expected["expected_vuln"],
"expected_category": expected["expected_category"],
"expected_category_code": expected["expected_category_code"],
"expected_cwe": expected["expected_cwe"],
"expected_cwe_num": expected["expected_cwe_num"],
}
for detector in DETECTORS:
prefix = detector["prefix"]
for condition, suffix, _ in CONDITION_SUFFIXES:
row = lookup.get((detector["code"], condition, sample_id))
if row is None:
continue
item[f"{prefix}_{suffix}_predicted_vuln"] = row["predicted_vuln"]
item[f"{prefix}_{suffix}_correct"] = row["correct_flag"]
item[f"{prefix}_{suffix}_strict_correct"] = row["strict_correct"]
item[f"{prefix}_{suffix}_tp"] = row["tp"]
item[f"{prefix}_{suffix}_fp"] = row["fp"]
item[f"{prefix}_{suffix}_tn"] = row["tn"]
item[f"{prefix}_{suffix}_fn"] = row["fn"]
item[f"{prefix}_{suffix}_total_tokens"] = row["total_tokens"]
item[f"{prefix}_{suffix}_latency_ms"] = row["latency_ms"]
item[f"{prefix}_{suffix}_findings"] = row["findings"]
wide.append(item)
return wide
def wide_fields() -> list[tuple[str, str]]:
fields: list[tuple[str, str]] = [
("sample_id", "A20"),
("in_scope", "F1.0"),
("expected_vuln", "F1.0"),
("expected_category", "A20"),
("expected_category_code", "F3.0"),
("expected_cwe", "A10"),
("expected_cwe_num", "F5.0"),
]
for detector in DETECTORS:
prefix = detector["prefix"]
for _, suffix, _ in CONDITION_SUFFIXES:
fields.extend(
[
(f"{prefix}_{suffix}_predicted_vuln", "F1.0"),
(f"{prefix}_{suffix}_correct", "F1.0"),
(f"{prefix}_{suffix}_strict_correct", "F1.0"),
(f"{prefix}_{suffix}_tp", "F1.0"),
(f"{prefix}_{suffix}_fp", "F1.0"),
(f"{prefix}_{suffix}_tn", "F1.0"),
(f"{prefix}_{suffix}_fn", "F1.0"),
(f"{prefix}_{suffix}_total_tokens", "F10.0"),
(f"{prefix}_{suffix}_latency_ms", "F10.0"),
(f"{prefix}_{suffix}_findings", "F5.0"),
]
)
return fields
def paired_within(wide_rows: list[dict]) -> list[dict]:
output: list[dict] = []
labels = {condition: label for condition, _, label in CONDITION_SUFFIXES}
suffixes = {condition: suffix for condition, suffix, _ in CONDITION_SUFFIXES}
condition_pairs = [(0, 1), (0, 2), (1, 2)]
for detector in DETECTORS:
prefix = detector["prefix"]
for condition_a, condition_b in condition_pairs:
suffix_a = suffixes[condition_a]
suffix_b = suffixes[condition_b]
both = a_only = b_only = neither = 0
both_s = a_only_s = b_only_s = neither_s = 0
for row in wide_rows:
a = int(row.get(f"{prefix}_{suffix_a}_correct", 0))
b = int(row.get(f"{prefix}_{suffix_b}_correct", 0))
both += int(a == 1 and b == 1)
a_only += int(a == 1 and b == 0)
b_only += int(a == 0 and b == 1)
neither += int(a == 0 and b == 0)
a_s = int(row.get(f"{prefix}_{suffix_a}_strict_correct", 0))
b_s = int(row.get(f"{prefix}_{suffix_b}_strict_correct", 0))
both_s += int(a_s == 1 and b_s == 1)
a_only_s += int(a_s == 1 and b_s == 0)
b_only_s += int(a_s == 0 and b_s == 1)
neither_s += int(a_s == 0 and b_s == 0)
output.append(
{
"tier": detector["tier"],
"model": detector["code"],
"comparison": (
f"{labels[condition_a]}_vs_{labels[condition_b]}"
),
"condition_a": condition_a,
"condition_b": condition_b,
"n": both + a_only + b_only + neither,
"both_correct": both,
"a_only_correct": a_only,
"b_only_correct": b_only,
"both_wrong": neither,
"mcnemar_exact_p": round(mcnemar_exact(a_only, b_only), 6),
"both_strict_correct": both_s,
"a_only_strict_correct": a_only_s,
"b_only_strict_correct": b_only_s,
"both_strict_wrong": neither_s,
"strict_mcnemar_exact_p": round(
mcnemar_exact(a_only_s, b_only_s), 6
),
}
)
return output
def paired_between(wide_rows: list[dict]) -> list[dict]:
output: list[dict] = []
suffixes = {condition: suffix for condition, suffix, _ in CONDITION_SUFFIXES}
for condition, _ in CONDITIONS:
suffix = suffixes[condition]
for i, detector_a in enumerate(DETECTORS):
for detector_b in DETECTORS[i + 1 :]:
prefix_a = detector_a["prefix"]
prefix_b = detector_b["prefix"]
both = a_only = b_only = neither = 0
for row in wide_rows:
a = int(row.get(f"{prefix_a}_{suffix}_correct", 0))
b = int(row.get(f"{prefix_b}_{suffix}_correct", 0))
both += int(a == 1 and b == 1)
a_only += int(a == 1 and b == 0)
b_only += int(a == 0 and b == 1)
neither += int(a == 0 and b == 0)
output.append(
{
"condition": condition,
"model_a": detector_a["code"],
"model_b": detector_b["code"],
"n": both + a_only + b_only + neither,
"both_correct": both,
"a_only_correct": a_only,
"b_only_correct": b_only,
"both_wrong": neither,
"mcnemar_exact_p": round(mcnemar_exact(a_only, b_only), 6),
}
)
return output
def write_codebook_csv(path: Path) -> None:
entries = [
("sample_id", "Benchmark test identifier", "string", "BenchmarkTestNNNNN"),
("tier", "Capability tier", "numeric", "0=Traditional SAST; 1=Open-weight; 2=Frontier"),
("model", "Detector", "numeric", "0=Bandit; 1=Semgrep; 2=DeepSeek V4.1 Flash; 3=Argon"),
("condition", "Dataset condition", "numeric", "0=original; 1=obfuscated_v2; 2=comments_removed"),
("in_scope", "In prompt target scope", "numeric", "0=out; 1=in"),
("expected_vuln", "Ground-truth vulnerability flag", "numeric", "0=No; 1=Yes"),
("predicted_vuln", "Detector vulnerability flag", "numeric", "0=No; 1=Yes"),
("correct_flag", "Prediction matches ground truth", "numeric", "0=no; 1=yes"),
("tp", "True positive indicator", "numeric", "0/1"),
("fp", "False positive indicator", "numeric", "0/1"),
("tn", "True negative indicator", "numeric", "0/1"),
("fn", "False negative indicator", "numeric", "0/1"),
("expected_category", "Ground-truth category label", "string", "see category codes"),
("expected_category_code", "Ground-truth category code", "numeric", "0=None; 1=pathtraver; ...; 99=other"),
("predicted_category", "Predicted category label", "string", "see category codes"),
("predicted_category_code", "Predicted category code", "numeric", "same as expected_category_code"),
("expected_cwe", "Ground-truth CWE label", "string", "CWE-N or None"),
("expected_cwe_num", "Ground-truth CWE number", "numeric", "0=None"),
("predicted_cwe", "Predicted CWE label", "string", "CWE-N or None"),
("predicted_cwe_num", "Predicted CWE number", "numeric", "0=None"),
("category_correct", "Predicted category matches ground truth among TP", "numeric", "0=no; 1=yes"),
("cwe_correct", "Predicted CWE matches ground truth among TP", "numeric", "0=no; 1=yes"),
("strict_correct", "Flag and CWE both match ground truth", "numeric", "0=no; 1=yes"),
("wrong_category_tp", "Vulnerable sample flagged vulnerable but wrong category", "numeric", "0=no; 1=yes"),
("parse_ok", "Response parsed as valid JSON", "numeric", "0=no; 1=yes"),
("prompt_tokens", "Prompt tokens (final attempt)", "numeric", "count; 0 for SAST tools"),
("completion_tokens", "Completion tokens (final attempt)", "numeric", "count; 0 for SAST tools"),
("total_tokens", "Total tokens (final attempt)", "numeric", "count; 0 for SAST tools"),
("latency_ms", "Request latency", "numeric", "milliseconds; 0 for SAST tools"),
("calls", "Calls used for this sample", "numeric", "count; 0 for SAST tools"),
("run_id", "Run identifier", "string", "text"),
("prompt_hash", "SHA-256 of the system prompt", "string", "hex or NA"),
("findings", "Number of target-category SAST findings", "numeric", "0 for LLMs"),
("token_data_available", "Token/latency data available", "numeric", "0=SAST; 1=LLM"),
]
write_csv(path, [{"variable": a, "label": b, "type": c, "values": d} for a, b, c, d in entries], ["variable", "label", "type", "values"])
def write_codebook_md(path: Path) -> None:
text = """# SPSS export: all detectors
This folder contains one combined SPSS-ready dataset covering:
- **Traditional SAST:** Bandit, Semgrep
- **Open-weight LLM:** DeepSeek V4.1 Flash, evaluated through a hosted endpoint
- **Frontier LLM:** Gemini 4 Argon
## Files
| File | Shape | Use |
|---|---|---|
| `sast_all_long.csv` | 2,400 rows: 4 detectors × 3 conditions × 200 samples | Mixed models, descriptives, crosstabs |
| `sast_all_wide.csv` | 200 rows, paired columns for every detector | McNemar, paired tests, cross-model comparisons |
| `sast_all_summary.csv` | 12 rows: 4 detectors × 3 conditions | Aggregate metrics |
| `sast_all_category.csv` | 168 rows: 4 detectors × 3 conditions × 14 categories | Per-category accuracy/precision/recall |
| `sast_all_paired.csv` | 12 rows: within-detector condition pairs | McNemar tests |
| `sast_all_between.csv` | 18 rows: between-detector comparisons by condition | Pairwise McNemar tests |
| `sast_all_long.sav` | 2,400 rows | Native SPSS long file |
| `sast_all_wide.sav` | 200 rows | Native SPSS wide/paired file |
| `sast_all_summary.sav` | 12 rows | Native SPSS aggregate summary |
| `sast_all_category.sav` | 168 rows | Native SPSS per-category summary |
| `codebook.csv` / `codebook.md` | — | Variable documentation |
| `sast_all_import.sps` | — | Import/describe long CSV |
| `sast_all_wide.sps` | — | Import wide CSV and run paired tests |
| `sast_all_summary.sps` | — | Import aggregate CSV |
| `sast_all_category.sps` | — | Import category CSV |
## Importing into SPSS
The easiest route is to open the `.sav` files directly:
- `sast_all_long.sav` for most analyses
- `sast_all_wide.sav` for paired McNemar tests
- `sast_all_summary.sav` for the aggregate table
- `sast_all_category.sav` for per-category metrics
Alternatively, set the SPSS working directory to this folder (`validation/spss_all`)
and run:
1. `sast_all_import.sps` for the long CSV.
2. `sast_all_wide.sps` for paired McNemar tests.
3. `sast_all_summary.sps` and `sast_all_category.sps` for aggregate tables.
The `.sav` files are generated from the CSVs with `validation/export_sav.py`.
## Model configurations
| Model | Tier | Reasoning | Deployment |
|---|---|---|---|
| DeepSeek V4.1 Flash | Open-weight | Provider default; reasoning recorded | Evaluated through a hosted endpoint |
| Gemini 4 Argon | Frontier | Provider default; reasoning not exposed | Hosted |
## Limitations
DeepSeek is open-weight and locally hostable, but it was evaluated through a
hosted endpoint; the served checkpoint or quantization may differ from the
public weights, and latency/cost are not representative of local hardware.
Argon is a hosted frontier model. Both LLMs used provider-default reasoning.
Within-model condition comparisons hold model configuration constant and
remain valid.
## Codes
- `tier`: 0 = Traditional SAST, 1 = Open-weight, 2 = Frontier
- `model`: 0 = Bandit, 1 = Semgrep, 2 = DeepSeek V4.1 Flash, 3 = Argon
- `condition`: 0 = original, 1 = obfuscated_v2, 2 = comments_removed
- `expected_vuln` / `predicted_vuln`: 0 = No, 1 = Yes
- `correct_flag`: prediction matches ground truth
- `strict_correct`: flag correct and, for vulnerable samples, CWE correct
## Category codes
| Code | Category |
|---:|---|
| 0 | None |
| 1 | pathtraver |
| 2 | sqli |
| 3 | xpathi |
| 4 | xxe |
| 5 | cmdi |
| 6 | deserialization |
| 7 | xss |
| 8 | weakrand |
| 9 | trustbound |
| 10 | hash |
| 11 | codeinj |
| 12 | securecookie |
| 13 | redirect |
| 14 | ldapi |
| 99 | other |
## Notes
- The long file is the main analysis file.
- `tier`, `model`, and `condition` are numeric with SPSS value labels; there
are no separate string label columns.
- The wide file is for paired tests; each detector has `_orig_`, `_obf_`, and
`_comments_` columns.
- SAST tools have `token_data_available = 0`, with zero token/latency values.
- All LLM conditions parse 200/200.
- The comments-removed condition removes only comments and docstrings;
identifiers, strings, routes, and templates are unchanged from the original.
- DeepSeek recorded reasoning text on every sample; Argon used provider-default
reasoning but no reasoning text was recorded.
"""
path.write_text(text, encoding="utf-8")
def spss_import_syntax() -> str:
var_lines = "\n".join(f" {name} {fmt}" for name, fmt in LONG_FIELDS)
labels = {
"sample_id": "Benchmark test identifier",
"tier": "Capability tier",
"model": "Detector",
"condition": "Dataset condition",
"in_scope": "In prompt target scope",
"expected_vuln": "Ground-truth vulnerability",
"predicted_vuln": "Predicted vulnerability",
"correct_flag": "Prediction correct",
"tp": "True positive",
"fp": "False positive",
"tn": "True negative",
"fn": "False negative",
"expected_category": "Ground-truth category",
"expected_category_code": "Ground-truth category code",
"predicted_category": "Predicted category",
"predicted_category_code": "Predicted category code",
"expected_cwe": "Ground-truth CWE",
"expected_cwe_num": "Ground-truth CWE number",
"predicted_cwe": "Predicted CWE",
"predicted_cwe_num": "Predicted CWE number",
"category_correct": "Category correct among TP",
"cwe_correct": "CWE correct among TP",
"strict_correct": "Flag and CWE both correct",
"wrong_category_tp": "Vulnerable but wrong category (TP)",
"parse_ok": "Valid JSON response",
"prompt_tokens": "Prompt tokens",
"completion_tokens": "Completion tokens",
"total_tokens": "Total tokens",
"latency_ms": "Latency (ms)",
"calls": "API calls",
"run_id": "Run ID",
"prompt_hash": "Prompt SHA-256",
"findings": "Target-category SAST findings",
"token_data_available": "Token/latency data available",
}
label_lines = "\n".join(f" {name} '{label}'" for name, label in labels.items())
return f"""* Import long-format combined SAST + LLM results.
* Set the SPSS working directory to validation/spss_all before running.
GET DATA
/TYPE=TXT
/FILE='sast_all_long.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
{var_lines}
.
DATASET NAME sast_all_long WINDOW=FRONT.
VARIABLE LABELS
{label_lines}
.
VALUE LABELS
tier 0 'Traditional SAST' 1 'Open-weight' 2 'Frontier'
model 0 'Bandit' 1 'Semgrep' 2 'DeepSeek V4.1 Flash' 3 'Gemini 4 Argon'
condition 0 'Original' 1 'Obfuscated v2' 2 'Comments removed'
in_scope expected_vuln predicted_vuln correct_flag parse_ok
tp fp tn fn category_correct cwe_correct strict_correct
wrong_category_tp token_data_available
0 'No' 1 'Yes'
expected_category_code predicted_category_code
0 'None' 1 'pathtraver' 2 'sqli' 3 'xpathi' 4 'xxe' 5 'cmdi'
6 'deserialization' 7 'xss' 8 'weakrand' 9 'trustbound'
10 'hash' 11 'codeinj' 12 'securecookie' 13 'redirect'
14 'ldapi' 99 'other'
.
EXECUTE.
* Uncomment to restrict all following analyses to in-scope samples.
* SELECT IF (in_scope = 1).
* EXECUTE.
FREQUENCIES VARIABLES=tier model condition expected_vuln predicted_vuln
correct_flag strict_correct wrong_category_tp.
SORT CASES BY model condition.
SPLIT FILE LAYERED BY model condition.
CROSSTABS
/TABLES=predicted_vuln BY expected_vuln
/STATISTICS=CHISQ
/CELLS=COUNT ROW COLUMN.
SPLIT FILE OFF.
MEANS TABLES=total_tokens latency_ms BY model condition
/CELLS=MEAN COUNT STDDEV.
"""
def spss_wide_syntax(fields: list[tuple[str, str]]) -> str:
var_lines = "\n".join(f" {name} {fmt}" for name, fmt in fields)
labels = [
" sample_id 'Benchmark test identifier'",
" in_scope 'In prompt target scope'",
" expected_vuln 'Ground-truth vulnerability'",
" expected_category 'Ground-truth category'",
" expected_category_code 'Ground-truth category code'",
" expected_cwe 'Ground-truth CWE'",
" expected_cwe_num 'Ground-truth CWE number'",
]
for detector in DETECTORS:
prefix = detector["prefix"]
label = detector["model_label"]
for _, suffix, word in CONDITION_SUFFIXES:
labels.extend(
[
f" {prefix}_{suffix}_predicted_vuln '{word} {label} predicted vulnerability'",
f" {prefix}_{suffix}_correct '{word} {label} correct'",
f" {prefix}_{suffix}_strict_correct '{word} {label} strict correct'",
f" {prefix}_{suffix}_tp '{word} {label} TP'",
f" {prefix}_{suffix}_fp '{word} {label} FP'",
f" {prefix}_{suffix}_tn '{word} {label} TN'",
f" {prefix}_{suffix}_fn '{word} {label} FN'",
f" {prefix}_{suffix}_total_tokens '{word} {label} total tokens'",
f" {prefix}_{suffix}_latency_ms '{word} {label} latency'",
f" {prefix}_{suffix}_findings '{word} {label} findings'",
]
)
label_lines = "\n".join(labels)
tests = []
for detector in DETECTORS:
prefix = detector["prefix"]
for left, right in (("orig", "obf"), ("orig", "comments"), ("obf", "comments")):
tests.append(
f"NPAR TESTS /MCNEMAR={prefix}_{left}_correct "
f"WITH {prefix}_{right}_correct."
)
comparisons = [
("argon", "deepseek"),
("bandit", "semgrep"),
("argon", "bandit"),
("argon", "semgrep"),
("deepseek", "bandit"),
("deepseek", "semgrep"),
]
for left, right in comparisons:
for suffix in ("orig", "obf", "comments"):
tests.append(
f"NPAR TESTS /MCNEMAR={left}_{suffix}_correct "
f"WITH {right}_{suffix}_correct."
)
test_lines = "\n".join(tests)
return f"""* Import wide paired combined SAST + LLM results.
* Set the SPSS working directory to validation/spss_all before running.
GET DATA
/TYPE=TXT
/FILE='sast_all_wide.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
{var_lines}
.
DATASET NAME sast_all_wide WINDOW=FRONT.
VARIABLE LABELS
{label_lines}
.
VALUE LABELS
in_scope expected_vuln
bandit_orig_predicted_vuln bandit_obf_predicted_vuln
bandit_comments_predicted_vuln
semgrep_orig_predicted_vuln semgrep_obf_predicted_vuln
semgrep_comments_predicted_vuln
deepseek_orig_predicted_vuln deepseek_obf_predicted_vuln
deepseek_comments_predicted_vuln
argon_orig_predicted_vuln argon_obf_predicted_vuln
argon_comments_predicted_vuln
0 'No' 1 'Yes'
.
EXECUTE.
SELECT IF (in_scope = 1).
EXECUTE.
* Within-detector McNemar: all condition pairs.
{test_lines}
* Optional: paired token comparisons for LLM detectors.
* COMPUTE deepseek_delta_tokens = deepseek_obf_total_tokens - deepseek_orig_total_tokens.
* COMPUTE argon_delta_tokens = argon_obf_total_tokens - argon_orig_total_tokens.
* EXECUTE.
* DESCRIPTIVES VARIABLES=deepseek_delta_tokens argon_delta_tokens.
"""
def spss_summary_syntax() -> str:
return """* Import combined aggregate summary.
* Set the SPSS working directory to validation/spss_all before running.
GET DATA
/TYPE=TXT
/FILE='sast_all_summary.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
tier F1.0
model F1.0
condition F1.0
n_all F5.0
n_in_scope F5.0
tp F5.0
fp F5.0
tn F5.0
fn F5.0
accuracy F8.6
strict_accuracy F8.6
precision F8.6
recall F8.6
fpr F8.6
tnr F8.6
balanced_accuracy F8.6
f1 F8.6
mcc F8.6
category_accuracy_tp F8.6
cwe_accuracy_tp F8.6
wrong_category_tp F5.0
total_tokens_final F12.0
total_tokens_all_attempts F12.0
mean_latency_ms_in_scope F12.2
api_calls_all_attempts F6.0
token_data_available F1.0
.
DATASET NAME sast_all_summary WINDOW=FRONT.
VARIABLE LABELS
tier 'Capability tier'
model 'Detector'
condition 'Dataset condition'
n_all 'Samples in run' n_in_scope 'Samples in target scope'
tp 'True positives' fp 'False positives' tn 'True negatives' fn 'False negatives'
accuracy 'Flag accuracy' strict_accuracy 'Strict accuracy (flag + CWE)'
precision 'Precision' recall 'Recall'
fpr 'False-positive rate' tnr 'True-negative rate'
balanced_accuracy 'Balanced accuracy' f1 'F1' mcc 'Matthews correlation'
category_accuracy_tp 'Category accuracy among TP'
cwe_accuracy_tp 'CWE accuracy among TP'
wrong_category_tp 'Wrong-category true positives'
total_tokens_final 'Final-attempt tokens'
total_tokens_all_attempts 'Tokens across all attempts'
mean_latency_ms_in_scope 'Mean latency (ms), in-scope'
api_calls_all_attempts 'API calls across all attempts'
token_data_available 'Token/latency data available'
.
VALUE LABELS
tier 0 'Traditional SAST' 1 'Open-weight' 2 'Frontier'
model 0 'Bandit' 1 'Semgrep' 2 'DeepSeek V4.1 Flash' 3 'Gemini 4 Argon'
condition 0 'Original' 1 'Obfuscated v2' 2 'Comments removed'
token_data_available 0 'No' 1 'Yes'
.
EXECUTE.
SORT CASES BY model condition.
LIST ALL.
"""
def spss_category_syntax() -> str:
return """* Import combined per-category metrics.
* Set the SPSS working directory to validation/spss_all before running.
GET DATA
/TYPE=TXT
/FILE='sast_all_category.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
tier F1.0
model F1.0
condition F1.0
expected_category A20
expected_category_code F3.0
n F5.0
tp F5.0
fp F5.0
tn F5.0
fn F5.0
accuracy F8.6
precision F8.6
recall F8.6
f1 F8.6
.
DATASET NAME sast_all_category WINDOW=FRONT.
VARIABLE LABELS
tier 'Capability tier'
model 'Detector'
condition 'Dataset condition'
expected_category 'Ground-truth category'
expected_category_code 'Ground-truth category code'
n 'Samples' tp 'True positives' fp 'False positives'
tn 'True negatives' fn 'False negatives'
accuracy 'Accuracy' precision 'Precision' recall 'Recall' f1 'F1'
.
VALUE LABELS
tier 0 'Traditional SAST' 1 'Open-weight' 2 'Frontier'
model 0 'Bandit' 1 'Semgrep' 2 'DeepSeek V4.1 Flash' 3 'Gemini 4 Argon'
condition 0 'Original' 1 'Obfuscated v2' 2 'Comments removed'
expected_category_code
0 'None' 1 'pathtraver' 2 'sqli' 3 'xpathi' 4 'xxe' 5 'cmdi'
6 'deserialization' 7 'xss' 8 'weakrand' 9 'trustbound'
10 'hash' 11 'codeinj' 12 'securecookie' 13 'redirect'
14 'ldapi' 99 'other'
.
EXECUTE.
SORT CASES BY model condition expected_category_code.
SPLIT FILE LAYERED BY model condition.
MEANS TABLES=accuracy precision recall f1 BY expected_category
/CELLS=MEAN COUNT.
SPLIT FILE OFF.
"""
def main() -> int:
parser = argparse.ArgumentParser(description="Export all detectors for SPSS.")
parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT))
args = parser.parse_args()
output_dir = Path(args.output_dir).expanduser()
output_dir.mkdir(parents=True, exist_ok=True)
long_rows = build_long(DETECTORS)
wide_rows = build_wide(long_rows)
summary_rows = summarize_all(long_rows)
category_rows = category_summaries(long_rows)
paired_rows = paired_within(wide_rows)
between_rows = paired_between(wide_rows)
long_field_names = [name for name, _ in LONG_FIELDS]
write_csv(
output_dir / "sast_all_long.csv",
[{name: row[name] for name in long_field_names} for row in long_rows],
long_field_names,
)
_wide_fields = wide_fields()
write_csv(
output_dir / "sast_all_wide.csv",
wide_rows,
[name for name, _ in _wide_fields],
)
write_csv(
output_dir / "sast_all_summary.csv",
summary_rows,
list(summary_rows[0].keys()),
)
write_csv(
output_dir / "sast_all_category.csv",
category_rows,
list(category_rows[0].keys()),
)
write_csv(
output_dir / "sast_all_paired.csv",
paired_rows,
list(paired_rows[0].keys()),
)
write_csv(
output_dir / "sast_all_between.csv",
between_rows,
list(between_rows[0].keys()),
)
write_codebook_csv(output_dir / "codebook.csv")
write_codebook_md(output_dir / "codebook.md")
(output_dir / "sast_all_import.sps").write_text(
spss_import_syntax(), encoding="utf-8"
)
(output_dir / "sast_all_wide.sps").write_text(
spss_wide_syntax(_wide_fields), encoding="utf-8"
)
(output_dir / "sast_all_summary.sps").write_text(
spss_summary_syntax(), encoding="utf-8"
)
(output_dir / "sast_all_category.sps").write_text(
spss_category_syntax(), encoding="utf-8"
)
print(f"Wrote SPSS exports to {output_dir}")
print(f" long rows: {len(long_rows)}")
print(f" wide rows: {len(wide_rows)}")
print(f" summary rows: {len(summary_rows)}")
print(f" category rows: {len(category_rows)}")
print(f" paired rows: {len(paired_rows)}")
print(f" between rows: {len(between_rows)}")
for name in (
"sast_all_long.csv",
"sast_all_wide.csv",
"sast_all_summary.csv",
"sast_all_category.csv",
"sast_all_paired.csv",
"sast_all_between.csv",
"codebook.csv",
"codebook.md",
"sast_all_import.sps",
"sast_all_wide.sps",
"sast_all_summary.sps",
"sast_all_category.sps",
):
print(f" {name}")
return 0
if __name__ == "__main__":
raise SystemExit(main())