Add SPSS-ready exports for DeepSeek comparison

- Add export_spss.py to generate long, wide, summary, and paired CSVs
- Add codebook, SPSS import syntax, and paired-analysis syntax
- Include generated SPSS files for the original and obfuscated runs
This commit is contained in:
Joren committed 2026-11-10 19:21:35 +01:00
1 parent c70239af0c
commit 7f047030c6
13 files changed
+1940 -4

No files matched your search

+834
View File
@@ -0,0 +1,834 @@
#!/usr/bin/env python3
"""Export the two DeepSeek runs to SPSS-friendly CSV files.
Outputs:
sast_long.csv one row per sample x condition (400 rows)
sast_wide.csv one row per sample with original/obfuscated columns
sast_summary.csv aggregate metrics by condition
sast_paired.csv paired McNemar counts and exact p-value
codebook.csv variable/value codebook
sast_import.sps SPSS import syntax for the long file
sast_wide.sps SPSS paired-analysis syntax for the wide file
Usage:
python3 validation/export_spss.py
python3 validation/export_spss.py \
--db results/sast_runs.sqlite3 \
--output-dir validation/spss
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import re
import sqlite3
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parents[1]
DEFAULT_DB = BASE_DIR / "results" / "sast_runs.sqlite3"
DEFAULT_OUTPUT = BASE_DIR / "validation" / "spss"
DEFAULT_ORIGINAL = "deepseek-original"
DEFAULT_OBFUSCATED = "deepseek-v4.1-flash"
CATEGORY_CODES = {
"None": 0,
"pathtraver": 1,
"sqli": 2,
"xpathi": 3,
"xxe": 4,
"cmdi": 5,
"deserialization": 6,
"xss": 7,
"weakrand": 8,
"trustbound": 9,
"hash": 10,
"codeinj": 11,
"securecookie": 12,
"redirect": 13,
"ldapi": 14,
}
OTHER_CATEGORY_CODE = 99
def flag_num(value: str | None) -> int:
return 1 if value == "Yes" else 0
def category_code(value: str | None) -> int:
if value is None:
return 0
return CATEGORY_CODES.get(value, OTHER_CATEGORY_CODE)
def cwe_num(value: str | None) -> int:
match = re.search(r"(\d+)", value or "")
return int(match.group(1)) if match else 0
def latest_rows(connection: sqlite3.Connection, run_id: 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 = ?
GROUP BY sample_path
) latest
ON latest.sample_path = a.sample_path
AND latest.max_index = a.call_index
WHERE a.run_id = ?
ORDER BY a.sample_name
""",
(run_id, run_id),
).fetchall()
return {row["sample_name"]: row for row in rows}
def run_meta(connection: sqlite3.Connection, run_id: str) -> sqlite3.Row:
row = connection.execute(
"SELECT * FROM run_meta WHERE run_id = ?", (run_id,)
).fetchone()
if row is None:
raise SystemExit(f"Run not found: {run_id}")
return row
def outcome_flags(row: sqlite3.Row) -> dict[str, int]:
expected = flag_num(row["expected_vulnerable"])
predicted = flag_num(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)
category_correct = int(
tp
and category_code(row["category"]) == category_code(row["expected_category"])
)
cwe_correct = int(tp and cwe_num(row["cwe"]) == cwe_num(row["expected_cwe"]))
return {
"expected_vuln": expected,
"predicted_vuln": predicted,
"correct_flag": correct,
"tp": tp,
"fp": fp,
"tn": tn,
"fn": fn,
"category_correct": category_correct,
"cwe_correct": cwe_correct,
}
def write_csv(path: Path, rows: list[dict[str, object]], fieldnames: list[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
def build_long(
original: dict[str, sqlite3.Row],
obfuscated: dict[str, sqlite3.Row],
original_meta: sqlite3.Row,
obfuscated_meta: sqlite3.Row,
) -> list[dict[str, object]]:
rows: list[dict[str, object]] = []
for sample_id in sorted(set(original) | set(obfuscated)):
for condition, condition_label, source, meta in (
(0, "original", original, original_meta),
(1, "obfuscated_v2", obfuscated, obfuscated_meta),
):
row = source.get(sample_id)
if row is None:
continue
flags = outcome_flags(row)
rows.append(
{
"sample_id": sample_id,
"condition": condition,
"condition_label": condition_label,
"model": meta["model"],
"in_scope": int(row["in_target_scope"] or 0),
**flags,
"expected_category": row["expected_category"] or "None",
"expected_category_code": category_code(row["expected_category"]),
"predicted_category": row["category"] or "None",
"predicted_category_code": category_code(row["category"]),
"expected_cwe": row["expected_cwe"] or "None",
"expected_cwe_num": cwe_num(row["expected_cwe"]),
"predicted_cwe": row["cwe"] or "None",
"predicted_cwe_num": cwe_num(row["cwe"]),
"parse_ok": int(row["parse_ok"] or 0),
"prompt_tokens": row["prompt_tokens"] or 0,
"completion_tokens": row["completion_tokens"] or 0,
"total_tokens": row["total_tokens"] or 0,
"latency_ms": row["latency_ms"] or 0,
"calls": row["call_index"] or 0,
"run_id": meta["run_id"],
"prompt_hash": meta["prompt_hash"],
}
)
return rows
def build_wide(
original: dict[str, sqlite3.Row],
obfuscated: dict[str, sqlite3.Row],
) -> list[dict[str, object]]:
rows: list[dict[str, object]] = []
for sample_id in sorted(set(original) | set(obfuscated)):
o = original.get(sample_id)
b = obfuscated.get(sample_id)
if o is None or b is None:
continue
of = outcome_flags(o)
bf = outcome_flags(b)
rows.append(
{
"sample_id": sample_id,
"in_scope": int(o["in_target_scope"] or 0),
"expected_vuln": of["expected_vuln"],
"expected_category": o["expected_category"] or "None",
"expected_category_code": category_code(o["expected_category"]),
"expected_cwe": o["expected_cwe"] or "None",
"expected_cwe_num": cwe_num(o["expected_cwe"]),
"orig_predicted_vuln": of["predicted_vuln"],
"orig_category": o["category"] or "None",
"orig_category_code": category_code(o["category"]),
"orig_correct": of["correct_flag"],
"orig_tp": of["tp"],
"orig_fp": of["fp"],
"orig_tn": of["tn"],
"orig_fn": of["fn"],
"orig_category_correct": of["category_correct"],
"orig_cwe_correct": of["cwe_correct"],
"orig_total_tokens": o["total_tokens"] or 0,
"orig_latency_ms": o["latency_ms"] or 0,
"obf_predicted_vuln": bf["predicted_vuln"],
"obf_category": b["category"] or "None",
"obf_category_code": category_code(b["category"]),
"obf_correct": bf["correct_flag"],
"obf_tp": bf["tp"],
"obf_fp": bf["fp"],
"obf_tn": bf["tn"],
"obf_fn": bf["fn"],
"obf_category_correct": bf["category_correct"],
"obf_cwe_correct": bf["cwe_correct"],
"obf_total_tokens": b["total_tokens"] or 0,
"obf_latency_ms": b["latency_ms"] or 0,
"both_correct": int(of["correct_flag"] and bf["correct_flag"]),
"orig_only_correct": int(of["correct_flag"] and not bf["correct_flag"]),
"obf_only_correct": int(not of["correct_flag"] and bf["correct_flag"]),
"both_wrong": int(not of["correct_flag"] and not bf["correct_flag"]),
}
)
return rows
def summarize(
rows: list[dict[str, object]],
condition: int,
label: str,
run_totals: dict[str, int],
) -> dict[str, object]:
all_selected = [row for row in rows if row["condition"] == condition]
selected = [row for row in all_selected if row["in_scope"] == 1]
tp = sum(int(row["tp"]) for row in selected)
fp = sum(int(row["fp"]) for row in selected)
tn = sum(int(row["tn"]) for row in selected)
fn = sum(int(row["fn"]) for row in selected)
n = tp + fp + tn + fn
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
)
cat_correct = sum(int(row["category_correct"]) for row in selected)
cwe_correct = sum(int(row["cwe_correct"]) for row in selected)
in_scope_tokens = sum(int(row["total_tokens"]) for row in selected)
final_tokens = sum(int(row["total_tokens"]) for row in all_selected)
mean_tokens = in_scope_tokens / n if n else 0.0
mean_latency = (
sum(int(row["latency_ms"]) for row in selected) / n if n else 0.0
)
model = str(all_selected[0]["model"]) if all_selected else ""
run_id = str(all_selected[0]["run_id"]) if all_selected else ""
return {
"condition": condition,
"condition_label": label,
"model": model,
"run_id": run_id,
"n_all": len(all_selected),
"n_in_scope": 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),
"category_accuracy_tp": round(cat_correct / tp, 6) if tp else 0.0,
"cwe_accuracy_tp": round(cwe_correct / tp, 6) if tp else 0.0,
"total_tokens_in_scope_final": in_scope_tokens,
"total_tokens_all_final": final_tokens,
"total_tokens_all_attempts": run_totals["total_tokens"],
"mean_tokens_in_scope": round(mean_tokens, 2),
"mean_latency_ms_in_scope": round(mean_latency, 2),
"api_calls_all_attempts": run_totals["calls"],
}
def mcnemar_exact(orig_only: int, obf_only: int) -> float:
n = orig_only + obf_only
if n == 0:
return 1.0
tail = sum(
math.comb(n, k) * (0.5**n)
for k in range(0, min(orig_only, obf_only) + 1)
)
return min(1.0, 2 * tail)
def write_codebook(path: Path) -> None:
entries = [
("sample_id", "Benchmark test identifier", "string", "BenchmarkTestNNNNN"),
("condition", "Dataset condition", "numeric", "0=original; 1=obfuscated_v2"),
("condition_label", "Dataset condition label", "string", "original / obfuscated_v2"),
("model", "Model identifier", "string", "deepseek-v4.1-flash"),
("in_scope", "Expected category is in the prompt target list", "numeric", "0=out; 1=in"),
("expected_vuln", "Ground-truth vulnerability flag", "numeric", "0=No; 1=Yes"),
("predicted_vuln", "Model 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; 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"),
("predicted_category", "Predicted category label", "string", "see category codes"),
("predicted_category_code", "Predicted category code", "numeric", "same as expected_category_code"),
("category_correct", "Predicted category matches ground truth among TP", "numeric", "0=no; 1=yes"),
("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"),
("cwe_correct", "Predicted CWE matches ground truth among TP", "numeric", "0=no; 1=yes"),
("parse_ok", "Response parsed as valid JSON", "numeric", "0=no; 1=yes"),
("prompt_tokens", "Prompt tokens", "numeric", "count"),
("completion_tokens", "Completion tokens", "numeric", "count"),
("total_tokens", "Total tokens", "numeric", "count"),
("latency_ms", "Request latency in milliseconds", "numeric", "milliseconds"),
("calls", "API calls used for this sample (retries/repair included)", "numeric", "count"),
("run_id", "Run identifier", "string", "text"),
("prompt_hash", "SHA-256 of the system prompt", "string", "hex"),
]
with path.open("w", encoding="utf-8", newline="") as handle:
writer = csv.writer(handle, lineterminator="\n")
writer.writerow(["variable", "label", "type", "values"])
writer.writerows(entries)
def write_codebook_md(path: Path) -> None:
text = """# SPSS codebook
## Files
- `sast_long.csv` — one row per sample × condition (400 rows)
- `sast_wide.csv` — one row per sample, original and obfuscated columns side by side (200 rows)
- `sast_summary.csv` — aggregate metrics by condition
- `sast_paired.csv` — paired McNemar counts and exact p-value
- `codebook.csv` — machine-readable variable/value codebook
- `sast_import.sps` — SPSS syntax to import and describe the long file
- `sast_wide.sps` — SPSS syntax for paired McNemar/token analyses
## 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
- `in_scope = 1` restricts analyses to the nine categories targeted by the prompt.
- `correct_flag` is the agreement between `predicted_vuln` and `expected_vuln`.
- `category_correct` and `cwe_correct` are only meaningful for true positives
(`expected_vuln = 1` and `predicted_vuln = 1`).
- The long file is the right shape for mixed models or condition-by-category
descriptives.
- The wide file is the right shape for paired tests such as McNemar and paired
token/latency comparisons.
## Summary file columns
`sast_summary.csv` contains one row per condition:
- `n_all` / `n_in_scope`
- `tp`, `fp`, `tn`, `fn`
- `accuracy`, `precision`, `recall`, `f1`
- `category_accuracy_tp`, `cwe_accuracy_tp`
- `total_tokens_in_scope_final` — final-attempt tokens for in-scope samples
- `total_tokens_all_final` — final-attempt tokens for all samples
- `total_tokens_all_attempts` — includes retries and repair calls
- `mean_tokens_in_scope`, `mean_latency_ms_in_scope`
- `api_calls_all_attempts`
`sast_paired.csv` contains the paired McNemar counts and exact p-value for the
in-scope samples.
"""
path.write_text(text, encoding="utf-8")
def spss_import_syntax(long_fields: list[tuple[str, str]]) -> str:
var_lines = "\n".join(f" {name} {fmt}" for name, fmt in long_fields)
labels = {
"sample_id": "Benchmark test identifier",
"condition": "Dataset condition",
"condition_label": "Dataset condition label",
"model": "Model identifier",
"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",
"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",
}
label_lines = "\n".join(
f" {name} '{label}'" for name, label in labels.items()
)
return f"""* Import long-format SAST results.
* Set the SPSS working directory to this folder before running.
GET DATA
/TYPE=TXT
/FILE='sast_long.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
{var_lines}
.
DATASET NAME sast_long WINDOW=FRONT.
VARIABLE LABELS
{label_lines}
.
VALUE LABELS
condition 0 'Original' 1 'Obfuscated v2'
in_scope 0 'Out of scope' 1 'In scope'
expected_vuln predicted_vuln correct_flag parse_ok 0 'No' 1 'Yes'
tp fp tn fn category_correct cwe_correct 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=condition in_scope expected_vuln predicted_vuln correct_flag.
SORT CASES BY condition.
SPLIT FILE LAYERED BY condition.
CROSSTABS
/TABLES=predicted_vuln BY expected_vuln
/STATISTICS=CHISQ
/CELLS=COUNT ROW COLUMN.
SPLIT FILE OFF.
MEANS TABLES=total_tokens latency_ms BY condition
/CELLS=MEAN COUNT STDDEV.
"""
def spss_wide_syntax(wide_fields: list[tuple[str, str]]) -> str:
var_lines = "\n".join(f" {name} {fmt}" for name, fmt in wide_fields)
return f"""* Import wide paired SAST results.
* Set the SPSS working directory to this folder before running.
GET DATA
/TYPE=TXT
/FILE='sast_wide.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
{var_lines}
.
DATASET NAME sast_wide WINDOW=FRONT.
VARIABLE 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'
orig_predicted_vuln 'Original predicted vulnerability'
orig_category 'Original predicted category'
orig_category_code 'Original category code'
orig_correct 'Original prediction correct'
orig_tp 'Original TP' orig_fp 'Original FP' orig_tn 'Original TN' orig_fn 'Original FN'
orig_category_correct 'Original category correct among TP'
orig_cwe_correct 'Original CWE correct among TP'
orig_total_tokens 'Original total tokens'
orig_latency_ms 'Original latency (ms)'
obf_predicted_vuln 'Obfuscated predicted vulnerability'
obf_category 'Obfuscated predicted category'
obf_category_code 'Obfuscated category code'
obf_correct 'Obfuscated prediction correct'
obf_tp 'Obfuscated TP' obf_fp 'Obfuscated FP' obf_tn 'Obfuscated TN' obf_fn 'Obfuscated FN'
obf_category_correct 'Obfuscated category correct among TP'
obf_cwe_correct 'Obfuscated CWE correct among TP'
obf_total_tokens 'Obfuscated total tokens'
obf_latency_ms 'Obfuscated latency (ms)'
both_correct 'Both correct'
orig_only_correct 'Original only correct'
obf_only_correct 'Obfuscated only correct'
both_wrong 'Both wrong'
.
VALUE LABELS
in_scope expected_vuln orig_predicted_vuln obf_predicted_vuln
orig_correct obf_correct orig_tp orig_fp orig_tn orig_fn
obf_tp obf_fp obf_tn obf_fn
orig_category_correct obf_category_correct
orig_cwe_correct obf_cwe_correct
both_correct orig_only_correct obf_only_correct both_wrong
0 'No' 1 'Yes'
expected_category_code orig_category_code obf_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.
* Restrict paired analyses to the 157 in-scope samples.
SELECT IF (in_scope = 1).
EXECUTE.
* McNemar test on paired correctness.
NPAR TESTS
/MCNEMAR=orig_correct WITH obf_correct
/STATISTICS DESCRIPTIVES.
* Paired correctness crosstab.
CROSSTABS
/TABLES=orig_correct BY obf_correct
/STATISTICS=CHISQ
/CELLS=COUNT.
* Token/latency difference descriptives.
COMPUTE delta_tokens = obf_total_tokens - orig_total_tokens.
COMPUTE delta_latency_ms = obf_latency_ms - orig_latency_ms.
EXECUTE.
DESCRIPTIVES VARIABLES=orig_total_tokens obf_total_tokens delta_tokens
orig_latency_ms obf_latency_ms delta_latency_ms.
"""
def spss_summary_syntax() -> str:
return """* Import aggregate SAST summary.
* Set the SPSS working directory to this folder before running.
GET DATA
/TYPE=TXT
/FILE='sast_summary.csv'
/ENCODING='UTF8'
/DELIMITERS=","
/QUALIFIER='"'
/ARRANGEMENT=DELIMITED
/FIRSTCASE=2
/VARIABLES=
condition F1.0
condition_label A20
model A40
run_id A40
n_all F5.0
n_in_scope 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
category_accuracy_tp F8.6
cwe_accuracy_tp F8.6
total_tokens_in_scope_final F10.0
total_tokens_all_final F10.0
total_tokens_all_attempts F10.0
mean_tokens_in_scope F10.2
mean_latency_ms_in_scope F12.2
api_calls_all_attempts F5.0
.
DATASET NAME sast_summary WINDOW=FRONT.
VARIABLE LABELS
condition 'Dataset condition'
condition_label 'Dataset condition label'
model 'Model identifier'
run_id 'Run ID'
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' precision 'Precision' recall 'Recall' f1 'F1'
category_accuracy_tp 'Category accuracy among TP'
cwe_accuracy_tp 'CWE accuracy among TP'
total_tokens_in_scope_final 'Final-attempt tokens, in-scope'
total_tokens_all_final 'Final-attempt tokens, all samples'
total_tokens_all_attempts 'Tokens across all attempts'
mean_tokens_in_scope 'Mean tokens per in-scope sample'
mean_latency_ms_in_scope 'Mean latency (ms), in-scope'
api_calls_all_attempts 'API calls across all attempts'
.
VALUE LABELS
condition 0 'Original' 1 'Obfuscated v2'
.
EXECUTE.
LIST ALL.
"""
def main() -> int:
parser = argparse.ArgumentParser(description="Export SAST results for SPSS.")
parser.add_argument("--db", default=str(DEFAULT_DB))
parser.add_argument("--original-run", default=DEFAULT_ORIGINAL)
parser.add_argument("--obfuscated-run", default=DEFAULT_OBFUSCATED)
parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT))
args = parser.parse_args()
db_path = Path(args.db).expanduser()
if not db_path.is_file():
raise SystemExit(f"Database not found: {db_path}")
output_dir = Path(args.output_dir).expanduser()
output_dir.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect(db_path)
connection.row_factory = sqlite3.Row
try:
original_meta = run_meta(connection, args.original_run)
obfuscated_meta = run_meta(connection, args.obfuscated_run)
original = latest_rows(connection, args.original_run)
obfuscated = latest_rows(connection, args.obfuscated_run)
original_totals = connection.execute(
"""
SELECT COUNT(*) AS calls,
COALESCE(SUM(total_tokens), 0) AS total_tokens
FROM attempts WHERE run_id = ?
""",
(args.original_run,),
).fetchone()
obfuscated_totals = connection.execute(
"""
SELECT COUNT(*) AS calls,
COALESCE(SUM(total_tokens), 0) AS total_tokens
FROM attempts WHERE run_id = ?
""",
(args.obfuscated_run,),
).fetchone()
finally:
connection.close()
long_rows = build_long(original, obfuscated, original_meta, obfuscated_meta)
wide_rows = build_wide(original, obfuscated)
long_fields = [
("sample_id", "A20"),
("condition", "F1.0"),
("condition_label", "A20"),
("model", "A40"),
("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"),
("parse_ok", "F1.0"),
("prompt_tokens", "F8.0"),
("completion_tokens", "F8.0"),
("total_tokens", "F8.0"),
("latency_ms", "F10.0"),
("calls", "F3.0"),
("run_id", "A40"),
("prompt_hash", "A64"),
]
write_csv(
output_dir / "sast_long.csv",
long_rows,
[name for name, _ in long_fields],
)
wide_fields = [
("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"),
("orig_predicted_vuln", "F1.0"),
("orig_category", "A20"),
("orig_category_code", "F3.0"),
("orig_correct", "F1.0"),
("orig_tp", "F1.0"),
("orig_fp", "F1.0"),
("orig_tn", "F1.0"),
("orig_fn", "F1.0"),
("orig_category_correct", "F1.0"),
("orig_cwe_correct", "F1.0"),
("orig_total_tokens", "F8.0"),
("orig_latency_ms", "F10.0"),
("obf_predicted_vuln", "F1.0"),
("obf_category", "A20"),
("obf_category_code", "F3.0"),
("obf_correct", "F1.0"),
("obf_tp", "F1.0"),
("obf_fp", "F1.0"),
("obf_tn", "F1.0"),
("obf_fn", "F1.0"),
("obf_category_correct", "F1.0"),
("obf_cwe_correct", "F1.0"),
("obf_total_tokens", "F8.0"),
("obf_latency_ms", "F10.0"),
("both_correct", "F1.0"),
("orig_only_correct", "F1.0"),
("obf_only_correct", "F1.0"),
("both_wrong", "F1.0"),
]
write_csv(
output_dir / "sast_wide.csv",
wide_rows,
[name for name, _ in wide_fields],
)
summary_rows = [
summarize(long_rows, 0, "original", dict(original_totals)),
summarize(long_rows, 1, "obfuscated_v2", dict(obfuscated_totals)),
]
write_csv(
output_dir / "sast_summary.csv",
summary_rows,
list(summary_rows[0].keys()),
)
in_scope_wide = [row for row in wide_rows if row["in_scope"] == 1]
orig_only = sum(int(row["orig_only_correct"]) for row in in_scope_wide)
obf_only = sum(int(row["obf_only_correct"]) for row in in_scope_wide)
both_correct = sum(int(row["both_correct"]) for row in in_scope_wide)
both_wrong = sum(int(row["both_wrong"]) for row in in_scope_wide)
paired_rows = [
{
"n_in_scope": len(in_scope_wide),
"both_correct": both_correct,
"orig_only_correct": orig_only,
"obf_only_correct": obf_only,
"both_wrong": both_wrong,
"mcnemar_exact_p": round(mcnemar_exact(orig_only, obf_only), 6),
}
]
write_csv(
output_dir / "sast_paired.csv",
paired_rows,
list(paired_rows[0].keys()),
)
write_codebook(output_dir / "codebook.csv")
write_codebook_md(output_dir / "codebook.md")
(output_dir / "sast_import.sps").write_text(
spss_import_syntax(long_fields), encoding="utf-8"
)
(output_dir / "sast_wide.sps").write_text(
spss_wide_syntax(wide_fields), encoding="utf-8"
)
(output_dir / "sast_summary.sps").write_text(
spss_summary_syntax(), encoding="utf-8"
)
print(f"Wrote SPSS exports to {output_dir}")
for name in (
"sast_long.csv",
"sast_wide.csv",
"sast_summary.csv",
"sast_paired.csv",
"codebook.csv",
"codebook.md",
"sast_import.sps",
"sast_wide.sps",
"sast_summary.sps",
):
print(f" {name}")
print(json.dumps(paired_rows[0], indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())