---
title: "Reproducibility"
subtitle: "Where Will the Attacker Strike? How to rerun the analysis"
knitr:
opts_chunk:
comment: "#>"
---
```{r load}
#| include: false
source("R/00_params.R"); source("R/01_utils.R"); source("R/90_theme.R")
source("R/repro_env.R")
library(dplyr); library(ggplot2); library(gt)
diag <- read_result("diagnostics")
si <- read_result("session_info")
n_pass <- sum(diag$result == "pass")
params <- yaml::read_yaml(file.path(PROJECT_ROOT, "params.yaml"))
frontier <- read_result("frontier")$frontier
loss_rat <- \(s) frontier$loss_rational[frontier$budget == BUDGET_BASE & frontier$strategy == s]
```
Every number on this site comes from synthetic inputs in `params.yaml` and `data/`, and from results computed by the scripts in `R/`. Nothing is downloaded, and every random draw is seeded, so running the same commit with the same package versions gives the same results. The pages never solve anything themselves: they read cached results from `data/results/`. This page explains how to rebuild those results, lists the inputs with their checksums, shows the tests and checks, and records the software environment.
## Quick start {#quick-start}
The code and data are in the GitHub repository [patrick-lefler/defender-attacker-game-theory](https://github.com/patrick-lefler/defender-attacker-game-theory). You need R 4.3 or later and Quarto 1.5 or later. To rebuild the results, run the tests and render the site from a clean copy:
``` bash
git clone https://github.com/patrick-lefler/defender-attacker-game-theory
cd defender-attacker-game-theory
Rscript -e 'renv::restore()' # once: install the package versions pinned in renv.lock
Rscript R/run_all.R
Rscript -e 'testthat::test_dir("tests/testthat")'
quarto render
```
The rendered site is written to `docs/`. Run `R/run_all.R` with `Rscript` from a terminal, not with `source()` in an R console: it ends with `quit()`, which would close your session. It exits with an error status if any diagnostic fails.
## Environment {#environment}
```{r}
#| label: tbl-env
#| tbl-cap: "Software used to render this page."
repro_env_table(packages = c("highs", "nloptr", "dplyr", "gt", "testthat")) |>
gt() |>
gt_se() |>
cols_align(align = "left")
```
::: {.reader-note}
**How to read the table.** Each row is one piece of software this page was rendered with and its version: R, the operating system, Quarto, and the packages the results depend on most (the two solvers, the data tools, the table package and the test framework). The "Packages" row says whether the installed R packages match the versions pinned in `renv.lock`.
**What the table tells you.** If your versions match these and the packages are in sync, rebuilding the project should give the same numbers. If they differ, small differences in the results may come from the software rather than the analysis. The versions that built the cached results are recorded separately under [Caching](#caching).
:::
## Pipeline {#pipeline}
`R/run_all.R` sources the scripts below in order, calls each script's `main_*()` function, runs the [diagnostics](#tests) and saves every result to `data/results/`. Later scripts depend on functions from earlier ones, so sourcing one script on its own in a fresh session fails.
| Script | What it does | Main outputs |
|:-----------------|:-----------------------------------|:-----------------------|
| `R/00_params.R` | Reads `params.yaml` into constants and sets the project paths | `SEED`, `BUDGET_BASE`, `RESULTS_DIR` and other constants |
| `R/01_utils.R` | Payoffs, the crew's best response, quantal-response loss and gradient, formatters, result read/write helpers | Shared functions |
| `R/20_solve_sse.R` | Textbook (Stackelberg) equilibrium as a set of linear programs solved with `highs`; the two-asset example | `two_asset.rds` |
| `R/21_baselines.R` | Risk-ranked, proportional and uniform allocations | Shared functions |
| `R/30_robust.R` | Robust (quantal-response) equilibrium with `nloptr` (SLSQP, analytic gradient, multistart) | `strategies_base.rds` |
| `R/31_qre_sweep.R` | Sweep over the crew's rationality (lambda) and the out-of-sample choice of lambda | `qre_sweep.rds`, `lambda_choice.rds` |
| `R/32_misestimation.R` | Monte Carlo test of each strategy against misjudged crews | `misest_draws.rds`, `misest_summary.rds`, `evpi.rds` |
| `R/33_frontier.R` | All strategies across the budget grid; data for the budget slider | `frontier.rds`, `slider_data.rds` |
| `R/34_alignment_check.R` | Rerun with crew values proportional to our losses | `alignment.rds` |
| `R/35_sensitivity.R` | One-at-a-time sensitivity and the lateral-movement scenario | `sensitivity.rds` |
| `R/run_all.R` | Runs all of the above, then the diagnostics | `diagnostics.rds`, `session_info.rds` |
Every page sources `R/00_params.R`, `R/01_utils.R` and `R/90_theme.R` (names, colors and the plot and table styles) in a hidden first chunk, then reads the results it needs. `R/99_wordcount.R` is an internal prose-length check; its result is printed to the terminal only.
## Data {#data}
All inputs are synthetic and illustrative, written for this project. `data/assets.csv` holds the six assets: our loss if each is hit, the crew's value, the cost of coverage and the coverage cap. `data/assumptions_register.csv` is the register shown on the [Governance](04-governance.qmd) page. `params.yaml` holds every other setting (see [Parameters and seeds](#parameters)). The files in `data/results/` are generated by `R/run_all.R` and committed, so the site renders without rerunning the analysis.
The checksums below identify the exact files used in this render. A different checksum means a different file.
```{r}
#| label: tbl-checksums
#| tbl-cap: "Input files and cached results used in this render."
input_files <- c("params.yaml", "data/assets.csv", "data/assumptions_register.csv")
result_files <- file.path("data", "results", c(
"two_asset.rds", "strategies_base.rds", "qre_sweep.rds", "lambda_choice.rds",
"misest_draws.rds", "misest_summary.rds", "evpi.rds", "frontier.rds", "slider_data.rds",
"alignment.rds", "sensitivity.rds", "diagnostics.rds", "session_info.rds"
))
checksums <- tibble(
Kind = c(rep("Input", length(input_files)), rep("Cached result", length(result_files))),
File = c(input_files, result_files)
) |>
mutate(
`Size (KB)` = file.size(file.path(PROJECT_ROOT, File)) / 1e3,
MD5 = unname(tools::md5sum(file.path(PROJECT_ROOT, File)))
)
checksums |>
gt() |>
tab_header(
title = md("**Files used in this render**"),
subtitle = paste0("Rendered ", Sys.Date())
) |>
fmt_number(columns = `Size (KB)`, decimals = 1) |>
gt_se() |>
cols_align(align = "left", columns = c(Kind, File, MD5))
```
::: {.reader-note}
**How to read the table.** Each row is one file the site depends on: `r length(input_files)` hand-written inputs and `r length(result_files)` cached results produced by the scripts. The size is in kilobytes. The MD5 column is a checksum, a short fingerprint computed from the file's exact contents; changing even one character gives a completely different fingerprint. The subtitle gives the date this page was rendered.
**What the table tells you.** Anyone rerunning the analysis can compute the same fingerprints on their copies. Matching input fingerprints mean identical starting points. The results should then match too, except `session_info.rds`, which records the build time and so changes on every run. If a result fingerprint differs while the inputs match, check the package versions first.
:::
## Parameters and seeds {#parameters}
Every setting lives in `params.yaml`, each labeled as an assumption, most with a tested range. Every random stream is seeded explicitly from `seed` (`r params$seed$value`): the misjudgment Monte Carlo in `R/32_misestimation.R`, the multistart points in `R/30_robust.R` and the gradient check in `R/run_all.R`. Lambda is chosen on separate draws seeded with `seed + 100`, so the choice is not tuned to the reported results, and the stability diagnostic reruns the Monte Carlo with `seed + 1`.
```{r}
#| label: tbl-params
#| tbl-cap: "Settings in params.yaml."
fmt_value <- \(p) {
v <- if (!is.null(p$value)) p$value else c(p$from, p$to, p$by)
if (!is.null(p$from)) sprintf("%g to %g by %g", p$from, p$to, p$by) else paste(format(unlist(v)), collapse = ", ")
}
tibble(
Name = names(params),
Value = purrr::map_chr(params, fmt_value),
Range = purrr::map_chr(params, \(p) if (is.null(p$range)) "" else paste(unlist(p$range), collapse = " to ")),
Status = purrr::map_chr(params, "status")
) |>
gt() |>
gt_se() |>
cols_align(align = "left")
```
::: {.reader-note}
**How to read the table.** Each row is one setting from `params.yaml`, the single file that controls the analysis. The value is what this site uses. The range, where given, is the span of values that would still be plausible. The status explains what the setting means and marks it as an assumption, since every value here is illustrative rather than taken from a published source.
**What the table tells you.** To test a different assumption, change its value in `params.yaml` and rerun the pipeline; no code needs editing. The seed fixes every random draw, so two people with the same file get the same numbers. The [Governance](04-governance.qmd#sensitivity) page shows how much the ranking moves when the most important settings change.
:::
::: {.callout-note icon="false" collapse="true"}
## params.yaml
```{r params-yaml}
#| echo: false
#| results: asis
cat("```yaml\n", paste(readLines(file.path(PROJECT_ROOT, "params.yaml")), collapse = "\n"), "\n```\n", sep = "")
```
:::
## Tests {#tests}
Two layers of checks guard the results. Unit tests in `tests/testthat/` check the core functions against reference values from an independent Python prototype (`reference_prototype.py`). They run again each time this page is executed, and the table below shows the results.
```{r}
#| label: tbl-tests
#| tbl-cap: "Unit test results from rendering this page."
tests <- testthat::test_dir(
file.path(PROJECT_ROOT, "tests", "testthat"),
reporter = "silent", stop_on_failure = FALSE
) |>
as.data.frame() |>
transmute(
File = file, Test = test, Expectations = nb,
Result = if_else(failed == 0 & !error & !skipped, "pass", "FAIL")
)
n_tests_pass <- sum(tests$Result == "pass")
tests |>
gt() |>
gt_se() |>
cols_align(align = "left", columns = c(File, Test, Result))
```
::: {.reader-note}
**How to read the table.** Each row is one unit test, grouped by the file it lives in. The expectations column counts the individual comparisons inside the test, such as one computed coverage against its reference value. "Pass" means every comparison in the test held. Here `r n_tests_pass` of `r nrow(tests)` tests passed, covering `r sum(tests$Expectations)` comparisons in total.
**What the table tells you.** The building blocks give the expected answers: the solvers, the baseline strategies, the Monte Carlo and the robust optimizer all reproduce values computed separately in Python. A failing row would point to the function that broke. Because of the page cache, this table updates only when this page is rendered on its own (see [Caching](#caching)).
:::
The second layer is `r nrow(diag)` diagnostics that `R/run_all.R` runs on the full results each time it builds them; `r n_pass` passed in the last build.
```{r}
#| label: tbl-diagnostics
#| tbl-cap: "Automated checks run when the results were built."
diag |>
gt() |>
cols_label(check = "Check", result = "Result", detail = "Detail") |>
gt_se() |>
cols_align(align = "left")
```
::: {.reader-note}
**How to read the table.** Each row is a check on the finished results rather than on a single function. "Pass" means the check met its standard. The detail column states what was checked and, where useful, by how much it passed, such as the largest gradient error or the change in average loss under a new seed.
**What the table tells you.** The solvers converged, every strategy respects the budget, the optimizer's slope calculation is correct, and the Monte Carlo results barely move when the random draws change: average losses shift by at most a few percent and the ranking holds. The last row explains the one exception on the budget frontier: at $5.5M, the risk-ranked plan has a slightly lower average loss than robust when we misjudge the crew. Robust still gives the lowest loss under its own noisy-crew model at every budget, so the optimizer found the right answer; the exception comes from the misjudgment test, not from a solver failure.
:::
## Caching {#caching}
- **Cached results (`data/results/*.rds`).** Written by `R/run_all.R` (or by a single script's `main_*()` function) and read by the pages. They are committed to git. Rerun `Rscript R/run_all.R` after changing `params.yaml`, `data/` or any analysis script. A page fails to render if a result file it reads is missing, so run the pipeline before rendering after adding a script.
- **Quarto freeze (`_freeze/`).** `_quarto.yml` sets `freeze: auto`, so a full `quarto render` re-executes a page only when that page's `.qmd` file changes. New cached results do not count as a change, so after rerunning `R/run_all.R`, render each page explicitly (for example `quarto render index.qmd`) or delete `_freeze/` first. Otherwise a page can show stale numbers. `_freeze/` is not committed.
The cached results on this site were built on `r si$built` with the versions below.
```{r}
#| label: tbl-build
#| tbl-cap: "R version, seed and key package versions used to build the cached results."
tibble(
Item = c("R", "Seed", names(si$packages)),
Value = c(si$r_version, as.character(si$seed), unname(si$packages))
) |>
gt() |>
gt_se() |>
cols_align(align = "left")
```
::: {.reader-note}
**How to read the table.** The first row is the version of R that built the cached results, the second is the random seed, and the rest are the packages that most affect the numbers: the two solvers, the data and plotting tools, and the test framework. These were recorded when `R/run_all.R` last ran, which can be earlier than the date this page was rendered.
**What the table tells you.** Anyone using these versions and this seed should reproduce every number on the site exactly. A different seed changes the Monte Carlo results slightly; the stability diagnostic above shows by how much. A different solver version could change results in the last decimal places.
:::
## Known limitations {#limitations}
### Limits of reproducibility {#repro-limits}
- Bit-for-bit equality is expected only on the same platform and package versions. Floating-point and BLAS differences across machines can change low-order digits. The optimizers (`highs` for the linear programs, `nloptr` for the robust strategy) can stop at slightly different points on different machines or versions, which can move results in the last decimal places.
- Nothing is downloaded during a build, so the analysis does not depend on any external data source. Rebuilding does depend on the pinned package versions staying available from CRAN, through `renv::restore()`.
- The unit-test reference values come from `reference_prototype.py`, which needs Python to rerun. The R tests use the stored values and do not call Python.
- Quarto versions affect rendering, not the numbers.
### Model limitations {#sec-limitations}
The model is a deliberately simple stylized game. Its main limitations, most of which are also listed in the [assumptions register](04-governance.qmd#assumptions-register):
1. **No repeated play.** One campaign, one decision. Real crews return, learn from failed attempts and share what they find. Loss figures are per campaign and the model assumes one campaign per year (A1).
2. **One attacker type.** Every strategy is built around one ransomware crew's payoffs. Insiders and state actors want different assets and are out of scope (A2).
3. **No deception.** The model has no honeypots or decoys, which can change what the crew sees and so where it attacks. The crew is assumed to see our coverage before choosing a target (A3); the noisy-crew sweep on the [Robustness](03-robustness.qmd) page tests this only in part.
4. **Assets fail independently.** A breach of identity or corporate IT does not spread to other systems, although real ransomware crews often move laterally (A11). The sensitivity table on the [Governance](04-governance.qmd#sensitivity) page tests a simple version of this by raising those two assets' losses.
5. **Static budget and simple controls.** The budget does not respond to new intelligence during the year. Coverage costs rise in a straight line (A4) and coverage is treated as the probability an attack is stopped, with controls failing independently (A5). Neither assumption is tested.
6. **Synthetic calibration.** Every asset value, cost and setting is illustrative (A8). The misjudgment test stresses only the crew's payoffs, not our own loss estimates or costs.
Natural follow-ons are repeated play, mixtures of attacker types, and the attack-graph Markov chain project.
#### What would change the conclusions
| Change | Likely effect | Tested here? |
|:-----------------------|:-----------------------------------------|:-----------------------|
| We know the crew's payoffs exactly | The textbook plan wins: at the base budget it loses `r fmt_m(loss_rat("textbook"))` against a perfectly predicted crew, against `r fmt_m(loss_rat("robust"))` for robust. Robust's advantage comes entirely from protecting against misjudgment. | Yes, frontier and two-asset example |
| Misjudgment larger than tested, or biased in one direction | Every strategy loses more. Robust led across sigma 0.20 to 0.50, but a consistent bias (for example always underrating one asset) was not simulated. | Partly (sigma 0.20 to 0.50, unbiased) |
| Several attacker types, or repeated campaigns | Could reorder the strategies, because the best plan against a mixture need not be the best against any single crew. | No |
| Strong lateral movement | Raises the value of covering identity and corporate IT. Robust still led in the one scenario tested. | One scenario |
| Diminishing returns or correlated control failures | Changes how much each extra dollar of coverage buys, and so the shape of every allocation. | No |
::: {.reader-note}
**How to read the table.** Each row is a change to the world the model assumes. The middle column says what that change would probably do to the comparison of strategies; the last column says whether this site tests it.
**What the table tells you.** The headline result, that robust beats the alternatives when we misjudge the crew, holds for every change the site tests. The first row is the trade-off: robust gives up some performance against a perfectly predicted crew in exchange for much smaller losses when the prediction is wrong. The untested rows are where the conclusion is least secure.
:::
#### What real data would replace
| Assumption | Real data that would replace it |
|:-----------------------|:-----------------------------------------|
| Our loss if each asset is hit (`L` in `data/assets.csv`) | The firm's own business-impact and scenario analysis, cross-checked against incident and insurance-claim history |
| The crew's value of each asset (`V`) | Threat intelligence on which systems ransomware crews target and what they extract or demand from them |
| Coverage cost and cap (`k`, `c_max`) | Control costs from the security budget and vendor quotes, and the realistic maximum effectiveness of each control set |
| Coverage as the probability an attack is stopped (A5) | Control-effectiveness evidence from red-team exercises, penetration tests and past incidents |
| Size of misjudgment (`misest_sigma`, A10) | A record of how well past threat-intelligence forecasts matched the attacks that followed |
| Loss when an attack is stopped (`def_covered_share`, A6) | Response and recovery costs of contained incidents |
| One campaign per year (A1) | The firm's own attack frequency and industry incident data |
::: {.reader-note}
**How to read the table.** Each row pairs a synthetic input or assumption with the kind of evidence a real firm would use in its place. Column names in parentheses refer to `data/assets.csv` and `params.yaml`.
**What the table tells you.** The method carries over to a real firm, but the numbers do not. The crew's values and the size of our misjudgment matter most here, because they decide which asset the crew prefers and how much robustness is worth. They are also the hardest inputs to estimate.
:::
#### How to use these results
Use the analysis as a challenge to a security budget, not as an allocation engine. What carries over is the logic: attackers respond to what we defend, and a plan should be tested against an attacker who differs from the one we expect. Do not use the dollar figures, coverage levels or asset rankings as estimates for any real firm; they come from illustrative inputs.
## Licenses {#licenses}
The code on this site is released under the [MIT License](license.qmd). There are no third-party data: every input is synthetic and was written for this project, so the same license covers it. Three packages the results depend on carry copyleft licenses, as stated in each package's DESCRIPTION file; using them to produce results does not change the license of this project's code.
| Source | Terms |
|:----------------------|:--------------------------------------------------------|
| Code in `R/` and `tests/` | [MIT License](license.qmd) |
| Synthetic inputs (`params.yaml`, `data/`) | [MIT License](license.qmd) |
| [`highs`](https://cran.r-project.org/package=highs) (linear-program solver) | GPL (>= 2) |
| [`nloptr`](https://cran.r-project.org/package=nloptr) (robust optimizer) | LGPL (>= 3) |
| [`ggrepel`](https://cran.r-project.org/package=ggrepel) (plot labels) | GPL-3 |
## Session information {#session-info}
The site was built with R and Quarto. The analysis loads `dplyr`, `ggplot2` and `gt`, and also calls `ggrepel`, `highs`, `nloptr`, `purrr`, `readr`, `renv`, `scales`, `sessioninfo`, `testthat`, `tibble`, `tidyr`, `tidyselect` and `yaml`. Package versions are pinned in `renv.lock`; run `renv::restore()` to install them.
::: {.callout-note icon="false" collapse="true"}
## Full R session information
```{r session-information}
#| echo: false
sessioninfo::session_info()
```
:::