---
title: "Cyber Anomaly Detection & Service Dependency Risk"
subtitle: "Markov transition matrices, PageRank, a shallow autoencoder, and Extreme Value Theory thresholds: a simulation study"
author: Patrick Lefler
date: "2026-08-13"
---
```{r}
#| label: setup
#| include: false
source("R/pages/setup.R")
gt_tab <- graph$table
tier1 <- gt_tab |> filter(criticality_tier == "Tier 1") |> pull(name)
fa999 <- rob_get("False alarms at 99.9%")
f3 <- \(x) f_num(x, 3)
```
## Introduction
Enterprise systems produce large volumes of authentication, network and host telemetry. Most monitoring still relies on fixed signatures and static thresholds, which miss attacks that stay inside normal ranges. Credential stuffing spread across many sources and slow data exfiltration are examples. An unsupervised detector learns what normal looks like and flags departures from it, so it can in principle catch attacks nobody has written a rule for.
Detection alone is not enough. The usual response to an alert is containment: isolate a host, revoke a token. If the affected service sits under much of the estate, the containment can cause a larger outage than the attack. This project therefore tests a two-layer design, built in R, on **simulated** enterprise telemetry. Together the layers answer two questions: *is this window abnormal?* and *how dangerous is it to act on that automatically?*
**The structural layer** models `r nrow(gt_tab)` services as a Markov transition matrix of call flows. It ranks them by PageRank, articulation points and a node-removal simulation, and turns the ranking into criticality tiers that decide which alerts may trigger automated containment.
**The detection layer** is a shallow autoencoder, written in base R with analytic gradients and Adam. It is trained on `r d_features` correlated, seasonal telemetry features. Alerts fire when reconstruction loss exceeds a threshold fitted to the loss tail with a Generalized Pareto Distribution on held-out hosts.
**Results.** Across `r n_seeds` independent seeds (mean [95% range]):
- The autoencoder separates attacks from normal windows with ROC AUC `r f_rob("ROC AUC (all attacks)", f = f3)`. Mahalanobis distance does better (`r f_rob("Mahalanobis distance", "ROC AUC by method", f3)`), so the network adds nothing over simpler statistics on this data.
- At the 99.9% threshold it catches `r f_rob("high", "Detection at 99.9% by intensity", f_pct)` of high-intensity attacks, `r f_rob("medium", "Detection at 99.9% by intensity", f_pct)` of medium and `r f_rob("low", "Detection at 99.9% by intensity", f_pct)` of low.
- It misses data exfiltration at every intensity.
- False alarms at 99.9% were `r f_rob("False alarms at 99.9%", f = \(x) f_num(x, 1))` per `r f_int(n_normal_test)` normal windows, against about `r f_num(n_normal_test * 0.001, 0)` expected. The threshold does not transfer cleanly to new hosts.
- The loss tail is heavy (shape ξ = `r f_rob("GPD shape xi")`), driven by rare benign count spikes.
The two-layer design is sound. The detector, as built, is not ready for automated response.
::: {.callout-warning}
## Read this first
Every number on this site comes from a simulation with assumed parameters (`params.yaml`) and injected attacks, not production telemetry. The results show how the methods behave under controlled conditions. They do not estimate how the system would perform on any real network.
:::
## Techniques
**Markov transition matrix.** Services are nodes, and an edge $i \to j$ means service $i$ calls service $j$. Normalizing call volumes by row gives $P_{ij} = \Pr(\text{next call goes to } j \mid \text{at } i)$, a row-stochastic matrix. It assumes the next hop depends only on the current service (first-order Markov). [Details →](dependency-graph.qmd)
**PageRank.** PageRank is the long-run share of request hops landing on each service, with random restarts weighted by a damping factor. It measures *dependency concentration*. It is not a single-point-of-failure detector, so it is cross-checked against articulation points and a node-removal simulation.
**Shallow autoencoder.** A `r d_features`-`r cfg$autoencoder$bottleneck`-`r d_features` network with a $\tanh$ bottleneck and a linear decoder, trained only on normal windows. Each window is scored by its mean squared reconstruction error $\ell(\mathbf{x}) = \tfrac{1}{d}\lVert \mathbf{x} - \hat{\mathbf{x}} \rVert^2$. With one hidden layer it is close to principal component analysis, and the results confirm this. [Details →](detector.qmd)
**Extreme Value Theory (peaks over threshold).** Losses above a high level are modelled with a Generalized Pareto Distribution. This gives quantile thresholds $\tau_q$ for exceedance probabilities too small to estimate directly from the data. The thresholds come with bootstrap intervals, diagnostics and a calibration test. [Details →](thresholds.qmd)
## Architecture
```{mermaid}
%%| fig-align: center
%%{init: {'themeVariables': { 'fontSize': '15px', 'fontFamily': 'sans-serif' }}}%%
flowchart LR
T["<b>Telemetry window</b><br>x ∈ ℝᵈ"] --> AE["<b>Shallow autoencoder</b><br>d → k → d"]
AE --> L["<b>Loss</b><br>ℓ(x) = (1/d)‖x − x̂‖²"]
L --> EVT["<b>EVT threshold</b><br>τ_q from held-out GPD fit"]
EVT --> A{"<b>Alert?</b><br>ℓ(x) > τ_q"}
G["<b>Service call graph</b>"] --> P["<b>Transition matrix P</b><br>PageRank, articulation,<br>removal impact"]
P --> C["<b>Criticality tier</b>"]
A --> R["<b>Containment routing</b>"]
C --> R
R --> H["Tier 1: human approval"]
R --> S["Tier 2–3: low-blast-radius<br>automated actions"]
classDef default fill:#f8f9fa,stroke:#0275d8,stroke-width:1.5px;
classDef human fill:#fce4e4,stroke:#d9534f,stroke-width:1.5px;
class H human;
```
## Headline results
It collects the numbers a decision-maker needs on one screen, each averaged over `r n_seeds` complete re-runs instead of one lucky draw.
```{r}
#| label: tbl-headline
pick <- tribble(
~group, ~metric, ~label, ~fmt,
"ROC AUC by method", ae_label, "ROC AUC, autoencoder", "num",
"ROC AUC by method", "Mahalanobis distance", "ROC AUC, Mahalanobis distance (baseline)", "num",
"ROC AUC by method", "Sum of squared z-scores", "ROC AUC, sum of squared z-scores (baseline)", "num",
"Detection at 99.9% by intensity", "high", "Detection at 99.9%, high-intensity attacks", "pct",
"Detection at 99.9% by intensity", "medium", "Detection at 99.9%, medium-intensity attacks", "pct",
"Detection at 99.9% by intensity", "low", "Detection at 99.9%, low-intensity attacks", "pct",
"Detection at 99.9% by attack", "Data Exfiltration", "Detection at 99.9%, data exfiltration", "pct",
"Model", "False alarms at 99.9%", "False alarms at 99.9% (count)", "int",
"Model", "GPD shape xi", "Tail shape ξ", "num",
"Model", "tau 0.999", "Threshold τ₀.₉₉₉", "num"
)
pick |>
left_join(rob, by = join_by(group, metric)) |>
mutate(across(c(mean, lo, hi), \(x) case_when(fmt == "pct" ~ f_pct(x), fmt == "int" ~ f_num(x, 1), .default = f_num(x, 3)))) |>
select(label, mean, lo, hi) |>
gt() |>
tab_header(title = sprintf("Headline Results across %d Seeds", n_seeds),
subtitle = sprintf("False alarms out of %s normal test windows; about %.0f expected at 99.9%%",
f_int(n_normal_test), n_normal_test * 0.001)) |>
cols_label(label = "Quantity", mean = "Mean", lo = "2.5%", hi = "97.5%") |>
tab_options(table.font.size = 12)
```
**How to read the table.** Each row is one result, averaged over `r n_seeds` complete re-runs of the study, each with fresh simulated data, a newly trained model and a newly fitted threshold. ROC AUC runs from 0.5, no better than a coin toss, to 1, complete separation of attacks from normal activity. Detection rates are the share of attack windows that raised an alert. The 2.5% and 97.5% columns bracket the middle 95% of re-runs.
**What the table tells you.** The detector reliably catches loud attacks and misses quiet ones: `r f_pct(rob_get("high", "Detection at 99.9% by intensity")$mean)` of high-intensity windows but `r f_pct(rob_get("low", "Detection at 99.9% by intensity")$mean)` of low-intensity ones, and almost no data exfiltration. It does no better than Mahalanobis distance, a classical statistic that needs no training. False alarms average `r f_num(fa999$mean, 1)` against about `r f_num(n_normal_test * 0.001, 0)` expected and vary several-fold between runs. The original AUC of 1.0 came from the simulation design, not the model.
## Recommendations
We recommend three governance practices:
1. **Human-in-the-loop containment, routed by criticality.** Alerts on Tier 1 services (`r paste(tier1, collapse = ", ")`) require human approval before isolation or credential revocation, because isolating them is itself an outage. Automate only low-blast-radius actions, such as step-up authentication or ending a single session, and only after the detector has been validated on production telemetry. At realistic attack rates most alerts at the 99.9% threshold would be false alarms (see the [base-rate table](evaluation.qmd#base-rates)), so automated isolation today would mostly hit healthy hosts.
2. **Explain every alert, and test the explanations.** Report the top three contributing features with each alert. Measure how often they point at the true cause, and compare them against plain z-scores, which did as well here. This aligns with the explainability and model-risk expectations in the [NIST AI Risk Management Framework](https://www.nist.gov/itl/ai-risk-management-framework/ai-risk-management-framework-faqs) (voluntary) and [OSFI Guideline E-23](https://www.osfi-bsif.gc.ca/en/guidance/guidance-library/guideline-e-23-model-risk-management-2027) (effective May 1, 2027 for federally regulated Canadian financial institutions). Neither one prescribes a specific detector.
3. **Monitor drift by effect size, not significance.** Replace weekly per-feature KS tests with Wasserstein distance per feature (in standard-deviation units, with an effect-size trigger). Track the live alert rate against its expected $1-q$, and refit and re-validate the threshold on a schedule. In the [drift test](evaluation.qmd#drift-monitoring), KS flagged harmless shifts every time, and PSI at standard cut-offs missed a material one.
## Limitations
All telemetry, attacks and the service graph are simulated, so the results show how the method behaves on data like the simulation, not how it would perform in a real environment. The threshold is fitted once to a heavy, discrete tail, and the test set has about `r f_pct(n_attack_test / (n_attack_test + n_normal_test), 0)` attacks, far more than real environments, which is why the [base-rate table](evaluation.qmd#base-rates) matters more than the ROC curve. The [Model limitations](reproducibility.qmd#sec-limitations) section lists each limitation, the real data that would replace each assumption, and how the results should and should not be used.
## Reproducibility
Every result can be regenerated from `params.yaml` with one script, `run_all.R`, and package versions are pinned with `renv`. The [Reproducibility](reproducibility.qmd) page has step-by-step instructions, result fingerprints for checking a rerun, unit-test results, and the full software environment. The code is on [GitHub](https://github.com/patrick-lefler/high-dimensional-cyber-anomaly-detection).