"""Replay documented defensive review budgets over disjoint KEV date windows.""" import argparse from datetime import timedelta import json from math import ceil from pathlib import Path import sys RESEARCH = Path(__file__).resolve().parents[2] sys.path.insert(0, str(RESEARCH / "draft-0.4" / "exposure")) from kev_backtest import BUDGETS, HORIZON_DAYS, coverage, rank from exposure_eda import read_catalog, read_scores, sha256, utc ROLES = {"fresh", "stale", "before", "after"} DATE_BUCKETS = ((1, 7), (8, 14), (15, HORIZON_DAYS)) def load_sources(spec, directory): if set(spec) != ROLES: raise ValueError("Each window requires fresh and stale scores and two KEV snapshots") sources = {} for role in sorted(ROLES): item = spec[role] name = Path(item["file"]) if name.name != item["file"] or name.name in ("", ".", ".."): raise ValueError(f"Invalid snapshot filename for {role}") path = directory / name if sha256(path) != item["sha256"]: raise ValueError(f"Snapshot SHA-256 mismatch for {role}") reader = read_scores if role in {"fresh", "stale"} else read_catalog observations, version, published = reader(path) provenance = { **item, "version": version, "published_at_utc": published.isoformat(), "records": len(observations), } sources[role] = (observations, version, published, provenance) return sources def observed_matrix(total, queued, outcome_count, queued_with_outcome): if not (0 <= queued <= total and 0 <= outcome_count <= total): raise ValueError("Invalid cohort or queue size") if not max(0, queued + outcome_count - total) <= queued_with_outcome <= min(queued, outcome_count): raise ValueError("Queue overlap inconsistent with cohort marginals") missed = outcome_count - queued_with_outcome return { "queued": { "added_to_kev": queued_with_outcome, "not_observed_in_kev_in_window": queued - queued_with_outcome, }, "not_queued": { "added_to_kev": missed, "not_observed_in_kev_in_window": total - queued - missed, }, } def timeline(outcomes, queued, score_day): buckets = [] for low, high in DATE_BUCKETS: matching = { key for key, added_on in outcomes.items() if low <= (added_on - score_day).days <= high } hits = len(matching & queued) buckets.append({ "days_after_score": [low, high], "added_in_queue": hits, "added_outside_queue": len(matching) - hits, }) return buckets def compare(scores, ranked, outcomes, cap, score_day): outcome_keys = set(outcomes) performance = coverage(scores, ranked, outcome_keys, cap) queue = set(ranked[:cap]) return { **performance, "outcome_matrix": observed_matrix(len(ranked), cap, len(outcomes), performance["hits"]), "addition_timing": timeline(outcomes, queue, score_day), } def paired_presence(outcomes, fresh_queue, stale_queue): keys = set(outcomes) both = keys & fresh_queue & stale_queue only_fresh = (keys & fresh_queue) - stale_queue only_stale = (keys & stale_queue) - fresh_queue return { "both_queues": len(both), "only_fresh_queue": len(only_fresh), "only_stale_queue": len(only_stale), "outside_both_queues": len(keys - fresh_queue - stale_queue), } def run_window(spec, directory): sources = load_sources(spec, directory) fresh, fresh_version, scored_at, _ = sources["fresh"] stale, stale_version, stale_at, _ = sources["stale"] before, _, before_at, _ = sources["before"] after, _, after_at, _ = sources["after"] score_day = scored_at.date() first_day = score_day + timedelta(days=1) last_day = score_day + timedelta(days=HORIZON_DAYS) if stale_version != fresh_version or (score_day - stale_at.date()).days != HORIZON_DAYS: raise ValueError("Score versions or age differ from the comparison contract") if not before_at <= scored_at < after_at or after_at.date() <= last_day: raise ValueError("KEV releases must bracket the decision and complete window") if utc(spec["before"]["mirror_commit_time_utc"]) > scored_at: raise ValueError("The fixed mirror archive postdates the decision") if utc(spec["after"]["mirror_commit_time_utc"]).date() <= last_day: raise ValueError("The fixed later mirror archive predates the end of the window") prior = before.keys() all_fresh = fresh.keys() - prior common = all_fresh & stale.keys() if not common: raise ValueError("No entries have both scores") outcomes = { key: day for key, day in after.items() if first_day <= day <= last_day and key not in prior } observed_common = {key: outcomes[key] for key in common & outcomes.keys()} observed_all_fresh = {key: outcomes[key] for key in all_fresh & outcomes.keys()} rank_common_fresh = rank(fresh, common) rank_common_stale = rank(stale, common) rank_all_fresh = rank(fresh, all_fresh) comparisons = [] for share in BUDGETS: cap = ceil(share * len(common)) fresh_full = compare(fresh, rank_all_fresh, observed_all_fresh, cap, score_day) full_queue = set(rank_all_fresh[:cap]) fresh_full["added_in_queue_with_only_fresh_score"] = len( full_queue & (observed_all_fresh.keys() - common) ) comparisons.append({ "common_budget_share": str(share), "list_size": cap, "fresh_in_shared_cohort": compare( fresh, rank_common_fresh, observed_common, cap, score_day ), "stale_in_shared_cohort": compare( stale, rank_common_stale, observed_common, cap, score_day ), "paired_presence_of_new_kev_entries": paired_presence( observed_common, set(rank_common_fresh[:cap]), set(rank_common_stale[:cap]) ), "fresh_across_all_scored_at_decision_same_cap": fresh_full, "uniform_expected_shared_hits": cap * len(observed_common) / len(common), }) fresh_coverage = len(observed_all_fresh) return { "score_day_utc": score_day.isoformat(), "window_inclusive": [first_day.isoformat(), last_day.isoformat()], "sources": {role: parts[3] for role, parts in sorted(sources.items())}, "catalog_integrity_between_endpoints": { "known_at_decision": len(prior), "prior_keys_removed": len(prior - after.keys()), "prior_keys_with_changed_addition_date": sum( before[key] != after[key] for key in prior & after.keys() ), "later_keys_with_backdated_addition": sum( day < score_day for key, day in after.items() if key not in prior ), "additions_on_score_day_excluded_from_outcome": sum( day == score_day for key, day in after.items() if key not in prior ), }, "cohort": { "candidates_with_both_scores": len(common), "candidates_with_only_fresh_score": len(all_fresh - common), "all_candidates_with_fresh_score": len(all_fresh), "kev_additions_in_window": len(outcomes), "added_with_both_scores": len(observed_common), "added_with_only_fresh_score": fresh_coverage - len(observed_common), "added_without_fresh_score": len(outcomes) - fresh_coverage, "added_with_fresh_score_share": fresh_coverage / len(outcomes) if outcomes else None, }, "equal_budget_comparisons": comparisons, } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("manifest", type=Path) parser.add_argument("input_directory", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() manifest = json.loads(args.manifest.read_text(encoding="utf-8")) if manifest.get("schema_version") != 1 or not isinstance(manifest.get("windows"), list): raise ValueError("Unsupported research manifest version") if not manifest["windows"]: raise ValueError("The manifest must contain at least one window") windows = sorted( (run_window(spec, args.input_directory) for spec in manifest["windows"]), key=lambda row: row["score_day_utc"], ) if any( left["window_inclusive"][1] >= right["window_inclusive"][0] for left, right in zip(windows, windows[1:]) ): raise ValueError("Outcome windows overlap") if len({row["sources"]["fresh"]["version"] for row in windows}) != 1: raise ValueError("Windows cross EPSS version regimes") result = { "outcome_proxy": "Date added to the later archived CISA KEV catalog within the following 30 calendar days", "score_unit": "public vulnerability", "interpretation": "Unrecorded outcome is not a verified negative; no organisation inventory, exposure or losses observed", "windows": windows, } args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") if __name__ == "__main__": main()