Audit, Detection, and Incident Response › Detection: turning events into signal
Language AI HandbookAll chapters If the audit trail is the "what happened" layer, detection is the process of interrogating it live and at rest to find events that shouldn't be there. Detection is fundamentally a classification problem with a severe base-rate problem, and understanding the base rate is the difference between a detector that works and one that buries analysts in noise.
Batch detectors examine records after collection, for example to compare changes in granted permissions over a month. Streaming detectors consume observations shortly after they occur. A streaming alert can prompt a responder to check a permission decision quickly. Whether it can stop an action depends on when enforcement runs and what control the responder can invoke.
The base-rate trap
Suppose 1 in 100,000 actions in a fictional deployment is positive. Among 10 million actions that leaves 100 positives and 9,999,900 negatives. At a 1% false-positive rate, expect 99,999 false alerts. If the detector finds all 100 positives, precision is about 0.10%.
At 90% recall, the same detector would find 90 positives and precision would fall to about 0.090%. These are expected counts under the stated rates. A deployed alert policy also needs an estimate of the investigation workload at those rates.
The practical consequences are structural:
- Prefer high-precision signals even at low recall. A detector that fires on a narrow, structural signature (for example, an egress event whose destination was not pre-approved) may yield high precision if the narrow condition rarely occurs among benign events. Statistical anomaly detectors with high recall are used to generate leads for triage, not to page humans directly.
- Layer detectors. A cheap, high-recall anomaly scorer feeds a triage step; only triage outputs page a human. This is the "detection engineering" model from mature security operations.
- Calibrate against your own base rate. A generic benchmark of anomaly-detection AUC tells you almost nothing about precision at your prevalence. You must estimate the base rate in your deployment (even crudely) and compute the achieved precision.
Track all three quantities separately. The arrival rate sets how many alerts a team might receive, precision estimates how many flagged events are true positives, and recall estimates the share of all positive cases the system catches.
Families of detectors
There is no single "anomaly detection." Four families recur, and they trade off in characteristic ways.
Signature / rule detectors match structural patterns: "tool call to a destination not in the approved allowlist," "credential used outside business hours," "retrieval from a document whose provenance is untrusted followed by an egress tool." These are high-precision and cheap, but they only catch what you anticipated: they encode your threat model, not the unknown. They are the backbone, not the whole solution.
A narrow rule makes its trigger easy to inspect. Its precision still depends on whether benign activity can produce the same pattern and on the share of positive events in the population.
Threshold detectors on a single scalar page when some measured quantity crosses a limit: tokens of context consumed per minute (a cost/denial signal), number of external endpoints touched per session (a lateral-movement signal), count of denied policy decisions per actor per hour (a probing signal). Simple and explainable, but brittle at the boundary and blind to combinations.
A responder can compare a measured value with its cutoff. A legitimate workload can cross that cutoff, while incomplete records can leave concerning activity outside the observed population. Test thresholds on benign traffic and check which events and time windows the detector sees.
Statistical and distance anomaly detectors model "normal" and flag deviations. A classic, interpretable choice is the robust z-score using median and median-absolute-deviation (MAD), which is far less sensitive to outliers than mean and standard deviation. For multivariate behavior you use nearest-neighbor distance, isolation forests, or a learned density model. These catch the unanticipated, but their scores are hard to calibrate and they inherit the base-rate problem.
A statistical detector can flag a deviation without an existing signature for that behavior. The robust score estimates location with the median and scale with the median absolute deviation. The ordinary z-score uses the mean for location and the standard deviation for scale. A single extreme observation can move both the sample mean and sample standard deviation significantly, while the median and median absolute deviation use ranks and are less sensitive to a small number of extreme observations. Estimate the false-positive rate on benign cases, including unusual but valid activity.
Sequence / provenance detectors look for a specified order of event categories within one trace. For example, inspection can flag an external action that follows retrieval from a source labeled untrusted. The records establish the order of observed events. Additional evidence is needed to establish why the action was proposed or whether it complied with policy.
Check a rule's precision against legitimate traces, including normal workflows that produce its event sequence. Missing or inaccurate source labels also reduce what the rule can infer. The toy classifier below uses synthetic labels so we can inspect those conditions directly.
We will implement the robust-z threshold detector and a sequence/provenance detector below, because together they illustrate the two extremes: statistical breadth and structural precision.
Worked example: robust-z anomaly scoring on invented metrics
We generate a batch of invented per-session metrics (all benign, synthetic) and inject a few obvious outliers to stand in for anomalous sessions. Then we score every session with a robust z-score and apply a threshold. The point is to watch precision behave as we move the threshold, illustrating the base-rate math in code.
The choice of a robust z-score rather than a standard z-score is driven by the shape of the data. Egress volume per session is typically heavy-tailed: most sessions transfer small amounts, a few transfer large amounts legitimately, and the rare malicious session transfers an extreme amount. Under that distribution the standard z-score, which uses the mean and standard deviation, is dragged upward by the heavy tail, so the baseline is inflated and the extreme session no longer looks so extreme. The median and MAD, by contrast, are determined by the bulk of the distribution and only weakly influenced by the tail, so the extreme session stands out. Robust scoring is what makes the threshold meaningful when the data has the heavy-tailed shape that most security metrics have.
The median absolute deviation is:
where:
- : the -th observed value of the metric
- : the median of all observed values
- : the absolute deviation of each value from the median
- over those deviations: the robust estimate of spread,
A z-score built from it is:
where:
- : the robust z-score for observation
- : the -th observed value of the metric (for example, egress volume for one session)
- : the median of all observed values, a robust estimate of the typical value
- : the absolute deviation of each value from the median
- : the median of those absolute deviations, a robust estimate of spread
- : a scaling constant so that, for normally distributed data, the -based scale corresponds to the standard deviation
We do not assume normality for correctness, since MAD just gives a robust spread estimate, but the 0.6745 constant keeps magnitudes comparable to familiar z-scores. Without it, the same spread would be reported on a different scale, making threshold choices harder to reason about.
For a normal population, the median absolute deviation is about times its standard deviation. Dividing the sample MAD by , or multiplying it by approximately , gives the scale in the denominator of the example. The synthetic data are skewed, so a score of 8 means eight scaled-MAD units above the median. It carries no Gaussian tail-probability interpretation in this example.
PythonIn [9]Expand
import numpy as np
rng = np.random.default_rng(7)
# 4,000 benign sessions: mostly typical, log-ish egress volume in KB
n_benign = 4000
egress_benign = np.clip(
rng.lognormal(mean=2.0, sigma=0.5, size=n_benign), 0, None
)
# 12 anomalous sessions with far larger egress
n_anom = 12
egress_anom = rng.uniform(1500, 5000, size=n_anom)
egress = np.concatenate([egress_benign, egress_anom])
is_anom = np.concatenate([np.zeros(n_benign, bool), np.ones(n_anom, bool)])
def robust_z(x):
med = np.median(x)
mad = np.median(np.abs(x - med))
scale = 1.4826 * mad # 1/0.6745, avoid division by the constant
return (x - med) / (scale if scale > 0 else 1.0)
scores = robust_z(egress)The synthetic data mirrors the realistic shape: 4,000 benign sessions drawn from a lognormal (heavy-tailed) distribution and 12 anomalous sessions drawn from a uniform distribution far to the right. The is_anom boolean array records the ground truth, which is what lets us measure precision and recall below; in a real deployment you do not have this array, which is precisely the problem the base-rate section discusses.
ConsoleOut [10]Expand
Median egress (KB): 7.3 Anomaly score range: -1.72 to 1290.75 threshold z> 5: flagged= 43 precision= 0.28 recall= 1.00 threshold z> 8: flagged= 15 precision= 0.80 recall= 1.00 threshold z>12: flagged= 12 precision= 1.00 recall= 1.00
At a threshold of 5 the detector finds all 12 anomalies and flags 31 benign sessions. That is 12 true positives among 43 alerts, or about 28% precision. The threshold of 8 yields 12 true and three false positives. All three thresholds happened to catch every anomaly because the fixture’s positives are far above the benign bulk.
PythonIn [11]Expand
def precision_at_prevalence(tpr, fpr, prevalence):
# Bayes: P(anom | flagged) = tpr*prev / (tpr*prev + fpr*(1-prev))
denom = tpr * prevalence + fpr * (1 - prevalence)
return (tpr * prevalence / denom) if denom else float("nan")
# Use the z>8 operating point; measure its rates on our synthetic batch
thr = 8
flagged = scores > thr
tpr = (flagged & is_anom).sum() / is_anom.sum()
fpr = (flagged & ~is_anom).sum() / (~is_anom).sum()ConsoleOut [12]Expand
Measured TPR=1.000 FPR=0.0008 prevalence=1e-02: precision=0.931 prevalence=1e-03: precision=0.572 prevalence=1e-04: precision=0.118 prevalence=1e-05: precision=0.013
Holding the fixture rates fixed, precision is about 11.8% at prevalence and about 1.3% at . These are hypothetical deployments. If production traffic changes which events are flagged, estimate the conditional rates again before applying this calculation.
A single curve holds the fixture’s false-positive and true-positive rates fixed. The marker shows the fixture's own prevalence, about 0.003, and its 80% precision at the chosen threshold.
PythonIn [13]Expand
prevalence_grid = np.geomspace(1e-6, 1e-1, 100)
measured_curve = [
precision_at_prevalence(tpr, fpr, prior) for prior in prevalence_grid
]
measured_fixture_prevalence = is_anom.mean()
measured_fixture_precision = precision_at_prevalence(
tpr, fpr, measured_fixture_prevalence
)VisualizationOut [14]Expand

Use broad anomalies as leads and test which structural checks or triage steps improve alert quality on your own traffic.
The curves in the next figure hold recall constant and vary the false-positive rate. Each curve applies the same Bayes calculation to a different hypothetical deployment prevalence. The measured point belongs to the synthetic fixture.
VisualizationOut [16]Expand

The numerator in precision_at_prevalence is the true-positive rate multiplied by prevalence. The denominator also includes the contribution from false positives. In this figure, lowering the false-positive rate improves precision wherever prevalence and recall are held fixed and both positive and negative cases are present. In deployment, a stricter rule can also lower recall. Measure both rates and the prevalence of the cases evaluated.
Worked example: a provenance/sequence detector
The sequence detector flags an invented trace in which external action follows a retrieval labeled untrusted. The application can also legitimately produce that sequence. Treat a match as a lead, and check the recorded authorization and outcome before declaring an incident.
The trace identifier limits the demonstration to one run. Production investigators may also need authenticated principal, timestamps, exact execution outcomes, and links to related runs to assess whether two events belong to the same incident.
PythonIn [17]Expand
from dataclasses import dataclass, field
@dataclass
class Trace:
trace_id: str
events: list = field(default_factory=list)
def classify(trace):
# inert, invented provenance and effect labels only
got_untrusted = False
for ev in trace.events:
if (
ev["action_type"] == "retrieval"
and ev.get("provenance") == "untrusted"
):
got_untrusted = True
if (
got_untrusted
and ev["action_type"] == "tool_call"
and ev.get("side_effect") == "write"
and ev.get("dest") == "external"
):
return "flag:untrusted_to_egress"
return "clear"
# Invented traces; no payloads, just structural labels
traces = [
Trace(
"t-100",
[
{"action_type": "retrieval", "provenance": "trusted"},
{
"action_type": "tool_call",
"side_effect": "write",
"dest": "external",
},
],
),
Trace(
"t-101",
[
{"action_type": "retrieval", "provenance": "untrusted"},
{
"action_type": "tool_call",
"side_effect": "read",
"dest": "internal",
},
],
),
Trace(
"t-102",
[
{"action_type": "retrieval", "provenance": "untrusted"},
{"action_type": "model_completion"},
{
"action_type": "tool_call",
"side_effect": "write",
"dest": "external",
},
],
),
]The classify function walks the ordered fixture and tracks whether it has seen a retrieval labeled untrusted. It stops at the first matching sequence and returns a fixed category label. This return value gives neither a matching event index nor an alert time.
ConsoleOut [18]Expand
t-100: clear t-101: clear t-102: flag:untrusted_to_egress
Fixtures t-100 and t-101 each contain one part of the sequence and therefore return clear. Fixture t-102 contains both in the specified order and returns the category label. A clear result means the supplied records did not match this rule.
For a deployment test, include normal workflows with the same observed sequence and traces with incomplete provenance. A match provides a lead for investigation. Use event records and the applicable policy to determine whether the action was authorized and whether it completed.
From detectors to alert policy
Raw detector scores are not alerts. An alert policy decides when a combination of signals warrants human attention, and it must be designed for the triage workflow:
- Correlate before paging. Aggregate per trace and per actor. Twelve robust-z hit events in one trace is one alert, not twelve.
- Require corroboration for statistical signals. Test whether corroboration from another source reduces unnecessary pages at an acceptable recall. Use labeled observations to estimate the joint rates.
- Encode severity. Check the policy in force at the time and corroborate the recorded destination and execution result. A verified policy-disallowed effect merits investigation at the severity defined for that effect.
- Version the policy. Alerts must record the detector and policy version that produced them, exactly as Evaluation Harnesses and Reproducibility argues for evaluation, or you cannot later explain why a real incident produced no page.
If two detectors are conditionally independent among benign events, false-positive rates of 1% and 0.1% give a joint rate of 0.001% when both must fire. For precision, also measure the joint true-positive rate. Shared inputs can correlate the signals, so estimate both joint rates on labeled data before turning an AND rule into a page.
Recognize that "is my detector good?" is the same question as "is my benchmark good?" from Benchmark Design and Evaluation Challenges. You need labeled incident data to measure precision and recall, and that data is rare, adversarial, and distribution-shifting. Detector metrics measured on last year's incidents understate next year's attacks. Treat detector quality as a live, drifting quantity, not a one-time certification.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!