---
title: "Reproducibility"
subtitle: "How to rerun Multi-Stage Attack Graph Simulation Via Markov Chains"
---
```{r load}
#| include: false
source("R/00_setup.R")
source("R/01_model.R")
source("R/02_robustness.R")
```
Every number on this site is computed at render time from the parameters in `params.yaml`. No data are downloaded or read from elsewhere, every random draw is seeded, and package versions are pinned with `renv`, so rendering the same commit gives the same results. This page explains how to rerun the analysis, how the scripts fit together, what the tests check, and records the software environment.
## Quick start {#quick-start}
1. The code and data are in the GitHub repository [patrick-lefler/attack-graph-simulation-via-markov-chains](https://github.com/patrick-lefler/attack-graph-simulation-via-markov-chains). 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:
2. Restore the packages with `renv::restore()` (see [Software environment](#environment)).
3. Rebuild everything from the project root:
``` bash
Rscript run_all.R
```
`run_all.R` checks that the installed packages match `renv.lock`, runs the [tests](#tests), and then re-executes and renders every page into `docs/`. It stops at the first problem. To run the analysis in an R console without rendering, source the scripts in order from the project root:
``` r
source("R/00_setup.R")
source("R/01_model.R")
source("R/02_robustness.R")
```
Each script depends on objects and packages from the one before it, so sourcing a later script on its own in a fresh session fails. The full analysis takes about 20 seconds.
## Pipeline {#pipeline}
| File | What it does | Main outputs |
|:-----------------|:-----------------------------------|:-----------------------|
| `params.yaml` | Holds every parameter: the two transition matrices, the step length, the Dirichlet settings, perturbation sizes, simulation sizes and the seed | `params` |
| `R/00_setup.R` | Loads packages and `params.yaml`, sources `R/functions.R`, sets the plot theme and the global seed, defines percentage-formatting helpers | `params`, `pct1()`, `pp1()` |
| `R/functions.R` | Defines every function: the closed-form solver, the jump chain, the outcome distribution by step, the one-row perturbations, the Dirichlet and paired draws, and the simulated walk | `solve_absorbing_markov()`, `draw_P()` and others |
| `R/01_model.R` | Builds the stages and both matrices from `params.yaml`, solves the chain in closed form, checks the jump-chain invariance, computes the time-to-outcome distributions | `P_baseline_raw`, `P_hardened_raw`, `base_solution`, `hard_solution`, `res`, `pmf_b`, `floor_cat_h` |
| `R/02_robustness.R` | One-row sensitivity and its identity check, Dirichlet parameter uncertainty (concentration sweep, correlated detection, paired comparison, ranking robustness) and the Monte Carlo check of the solver | `sens_df`, `identity_df`, `unc_summary`, `alpha_sweep`, `paired_summary`, `sim_check` |
| `tests/testthat/` | Unit tests for the functions and the model (see [Tests](#tests)) | Test results |
| `run_all.R` | Checks packages, runs the tests, renders every page | The site in `docs/` |
Each page sources the three numbered scripts in a hidden first chunk, so every page works from the same objects. The Model and Robustness pages display each function next to the code that uses it. The scripts also contain `stopifnot()` checks: every probability row must sum to 1, the closed form must match the jump chain and the Monte Carlo run, and numbers quoted as fixed text must match the model. A failed check stops the render.
## Data {#data}
The model uses no external data. Both transition matrices are expert-elicited, illustrative values in `params.yaml`; they are not calibrated to any benchmark (see [Parameterization and Assumptions](model.qmd#parameterization-and-assumptions)). The figures from published reports quoted in the text (Mandiant M-Trends, Sophos, CrowdStrike) are cited for comparison only and do not enter any calculation.
Because the inputs are the parameter file and the code, the checksums below identify the exact files used in this render. A different checksum means a different model or analysis.
```{r data-checksums}
input_files <- c(
"params.yaml",
"R/00_setup.R",
"R/functions.R",
"R/01_model.R",
"R/02_robustness.R"
)
tibble(
File = input_files,
`Size (KB)` = file.size(input_files) / 1e3,
MD5 = unname(tools::md5sum(input_files))
) |>
gt() |>
tab_header(
title = md("**Parameter and script files used in this render**"),
subtitle = paste0("Rendered ", Sys.Date())
) |>
fmt_number(columns = `Size (KB)`, decimals = 1) |>
cols_align(align = "left", columns = c(File, MD5))
```
**How to read the table.** Each row is one of the files that define the model and run every analysis on this site: the parameter file and the four R scripts. The size is in kilobytes, and the MD5 column is a checksum: a short fingerprint computed from the file's exact contents. Changing even one character, such as a single transition probability, produces 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 checksums on their copies of these files. If every fingerprint matches, they are running the identical model, with the same transition probabilities and seeds, and with the package versions pinned in `renv.lock` they should get identical results. A mismatch means a file has changed, so any difference in the results should be traced to that file first.
## Parameters and seeds {#parameters}
All parameters live in `params.yaml`. Each is labelled as an **assumption** (an illustrative or elicited value with no empirical source) or a **design** choice (a simulation or perturbation size that affects precision or framing, not the model), with the range the analysis explores. Several numbers derived from these values are quoted as fixed text on the site, and `stopifnot()` guards in `R/01_model.R` stop the render if a parameter change breaks one, so the text must be updated along with the value.
Every random stream is seeded explicitly with the `seed` value (`r params$seed$value`): once in `R/00_setup.R` and again at the start of each random section of `R/02_robustness.R`. Each section therefore gives the same draws regardless of which sections run before it. The closed-form solver itself is deterministic. The full file:
```{r params-file}
#| echo: false
#| class-output: yaml
cat(readLines("params.yaml"), sep = "\n")
```
## Tests {#tests}
Unit tests in `tests/testthat/` cover the functions and the model. They load only the parameters, the functions and the closed-form model, so they run in a few seconds. Run them with `Rscript -e "testthat::test_dir('tests/testthat')"`; `run_all.R` runs them before rendering. The table below shows the results of running the tests during this render.
```{r test-results}
test_results <- testthat::test_dir("tests/testthat", reporter = "silent", stop_on_failure = FALSE) |>
as_tibble()
test_results |>
transmute(
File = str_remove(file, "^test-") |> str_remove("\\.R$"),
Test = test,
Checks = nb,
Result = if_else(failed == 0 & !error & skipped == FALSE, "Pass", "Fail")
) |>
gt(groupname_col = "File") |>
tab_header(
title = md("**Unit test results for this render**"),
subtitle = sprintf("%d tests, %d individual checks", nrow(test_results), sum(test_results$nb))
) |>
cols_align(align = "left", columns = Test) |>
tab_options(table.font.size = 11, row_group.font.weight = "bold")
```
**How to read the table.** Each row is one test, grouped by the file it lives in: parameters, solver, model, and the functions used in the robustness analysis. The Checks column counts the individual comparisons inside the test, and Result shows whether every one of them passed. The solver tests compare the code against a two-stage chain small enough to solve by hand, so they check the arithmetic against an independent answer.
**What the table tells you.** `r if (all(test_results$failed == 0 & !test_results$error)) "Every test passed in this render" else "At least one test failed in this render, so the results on this site should not be relied on until it is fixed"`. That means the solver reproduces hand-calculated answers, the matrices have the documented structure, and the headline numbers quoted in the text are what the model produces. The tests check that the code does what it describes. They cannot check whether the illustrative transition probabilities are realistic. If a later change breaks one of these properties, `run_all.R` stops before rendering any page, and the failing row names the test.
## Caching {#caching}
- **No results cache.** The full analysis runs in about 20 seconds, so every page recomputes it when rendered.
- **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. Edits to `params.yaml` or the `R/` scripts do not count as a change. After editing either, run `Rscript run_all.R`, which renders each page explicitly, because Quarto always executes a page that is rendered on its own.
## Licenses {#licenses}
The code on this site is released under the [MIT License](license.qmd). The site contains no third-party data. Figures quoted from published reports are cited with links to their sources, and those reports keep their own terms.
## Software environment {#environment}
The site was built with R and Quarto. The analysis loads `tidyverse`, `scales`, `patchwork` and `gt`, and also calls `yaml`, `knitr`, `testthat`, `withr`, `renv` and `sessioninfo`. Package versions are pinned in `renv.lock`; run `renv::restore()` to install them.
::: {.callout-note icon=false collapse="true"}
## Full R session information
```{r}
#| label: session-information
#| echo: false
sessioninfo::session_info()
```
:::