When the guardrail stops stopping what it should
Imagine that your assistant's guardrail stops blocking anything and that you only notice because an alarm goes off in the middle of the night. You have two problems at once: stopping the exposure now and understanding why it happened, so that it does not happen again. The answer is a five-step process with a measurable result for each: detect, contain, assess the impact, fix with verification, and write the post-mortem. The code in this article covers the steps that can be automated, and does so with synthetic data.
All the listings were run with Python 3.14 and the standard library only. They send no notifications, touch no databases or key-value stores, and call no models: the guardrail is fake, the bait words are made-up placeholders, the audit log is an in-memory table. The process comes before the tools, and indeed it adapts to any alarm channel and any store.
Severity decides who gets woken up
Before responding to an incident you need to know what kind it is. Classification serves two purposes: saying who steps in and saying how quickly, so that nobody decides priorities at two in the morning. The table uses four levels; the times are example targets that your organization has to agree on, not values taken from a standard.
| Level | Definition | Example | Example target |
|---|---|---|---|
| P0 | Harmful content already delivered to real users, with possible legal consequences | Personal data of other users in the response; content the system was supposed to refuse, served to several people | Switch turned off immediately, fix the same day |
| P1 | Partial bypass or serious degradation without confirmed harm | A family of requests gets through; blocks drop but outputs are borderline | Resolution within the day |
| P2 | Anomaly with no direct impact on users | Rising false positives; latency above target | Working hours |
| P3 | Minor deviation or a problem outside production | Coverage gap that emerged in a review | Next work cycle |
The rule that avoids the most mistakes is asymmetry: when in doubt between two levels you pick the higher one, because downgrading later costs one sentence while underestimating costs a late intervention. A harmful output that reached even a single real user cannot sit below P1. The NIST AI RMF reference framework, in the MANAGE function, asks for exactly this: that processes exist to detect, respond to and recover from incidents (subcategory MANAGE 4.1) and that incidents and errors are communicated to the relevant actors (MANAGE 4.3).
Detect: the block rate that collapses
A guardrail that breaks leaves two traces: the block rate drops and, among the requests let through, the moderation
score of the outputs gets worse. If only the first drops, it may be cleaner traffic; if both drop, a fault is much
more likely. The file monitor.py looks at a moving 60-second window and returns a state: insufficient
data, ok, P1 (only the blocks drop) or P0 (the scores drop too). Time is logical, in whole seconds, so the result
does not depend on the clock.
# monitor.py - detects the collapse of the block rate on a moving window, with LOGICAL time (whole seconds).
from collections import deque
from dataclasses import dataclass
@dataclass(frozen=True)
class Evento:
t: int # seconds since the start of the simulation
bloccato: bool
punteggio: float # moderation score of the output, 0 = worst, 1 = best
FINESTRA_S = 60
MIN_EVENTI = 10 # below this threshold the sample is too small to conclude
SOGLIA_BLOCCO = 0.05 # below 5% of blocks the window is anomalous (example value)
SOGLIA_PUNTEGGIO = 0.30
def valuta_finestra(eventi, adesso):
recenti = [e for e in eventi if adesso - FINESTRA_S < e.t <= adesso]
if len(recenti) < MIN_EVENTI:
return "insufficient_data", len(recenti), None, None
tasso = sum(e.bloccato for e in recenti) / len(recenti)
passati = [e.punteggio for e in recenti if not e.bloccato]
medio = sum(passati) / len(passati) if passati else 1.0
if tasso < SOGLIA_BLOCCO and medio < SOGLIA_PUNTEGGIO:
return "P0", len(recenti), tasso, medio
if tasso < SOGLIA_BLOCCO:
return "P1", len(recenti), tasso, medio
return "ok", len(recenti), tasso, medio
def traffico_sintetico():
"""Minutes 0-2: ~12% of blocks, good outputs. From minute 3 the filter 'stops working' and outputs get worse."""
eventi = []
for t in range(0, 300, 2):
guasto = t >= 180
bloccato = (not guasto) and (t // 2) % 8 == 0
punteggio = 0.2 if guasto else 0.8
eventi.append(Evento(t, bloccato, punteggio))
return eventi
eventi = traffico_sintetico()
for adesso in (60, 120, 180, 240, 299):
stato, n, tasso, medio = valuta_finestra(eventi, adesso)
dettaglio = "" if tasso is None else f" blocks={tasso:.1%} mean_score_of_passed={medio:.2f}"
print(f"t={adesso:>3}s window={n:>2} events -> {stato}{dettaglio}")
# How long does it take to notice? Time is scanned in steps of 10 seconds from the moment of the fault (t=180).
primo = next(t for t in range(180, 300, 10) if valuta_finestra(eventi, t)[0] in ("P0", "P1"))
print(f"fault at t=180s, first alarm at t={primo}s: detection delay {primo - 180}s")
# Output:
# t= 60s window=30 events -> ok blocks=10.0% mean_score_of_passed=0.80
# t=120s window=30 events -> ok blocks=13.3% mean_score_of_passed=0.80
# t=180s window=30 events -> ok blocks=13.3% mean_score_of_passed=0.78
# t=240s window=30 events -> P0 blocks=0.0% mean_score_of_passed=0.20
# t=299s window=30 events -> P0 blocks=0.0% mean_score_of_passed=0.20
# fault at t=180s, first alarm at t=220s: detection delay 40s
In the synthetic traffic the fault starts at 180 seconds; the function scans time in steps of 10 seconds and the
first alarm is at 220: 40 seconds of delay. That delay is the price of the window. A shorter window warns sooner
but with fewer requests inside it, hence more false alarms; that is why MIN_EVENTI exists, and below
ten requests the state is «insufficient data» and not a verdict. Note that the code sends nothing: it returns the
state, and delivering the alarm (chat, phone call, ticket) is a separate layer, where no secret should ever appear
in the sources.
Contain: a per-feature switch, closed when in doubt
The switch must be operable in a few seconds by someone who has just woken up, without restarting the service. Two
choices make the file kill_switch.py robust. The first is granularity: the state is per feature, so
you turn off chat and search stays active, reducing the business damage during the incident. The second is the
behavior when the state cannot be read: the method consentita answers false, that is «closed»,
because a failure of the store must not reopen what had been closed for a reason.
# kill_switch.py - per-feature switch, with "closed" behavior if the state is not readable.
class StatoNonLeggibile(Exception):
pass
class ArchivioInMemoria:
def __init__(self):
self._v = {}
def leggi(self, chiave):
return self._v.get(chiave, "active")
def scrivi(self, chiave, valore):
self._v[chiave] = valore
class ArchivioGuasto:
def leggi(self, chiave):
raise StatoNonLeggibile("store not reachable")
class KillSwitch:
def __init__(self, archivio, registro):
self.archivio, self.registro = archivio, registro
def spegni(self, funzione, motivo, operatore):
self.archivio.scrivi(funzione, "off")
self.registro.append({"action": "turn_off", "function": funzione, "reason": motivo, "operator": operatore})
def consentita(self, funzione):
"""True only if the state is readable AND equals 'active'. When in doubt: no (fail-closed)."""
try:
return self.archivio.leggi(funzione) == "active"
except StatoNonLeggibile:
return False
registro = []
ks = KillSwitch(ArchivioInMemoria(), registro)
print("chat allowed:", ks.consentita("chat"), "| search allowed:", ks.consentita("search"))
ks.spegni("chat", "block rate collapsed", "oncall-1")
print("after turning off -> chat:", ks.consentita("chat"), "| search:", ks.consentita("search"))
print("with failing store -> chat:", KillSwitch(ArchivioGuasto(), []).consentita("chat"))
print("log:", registro)
# Output:
# chat allowed: True | search allowed: True
# after turning off -> chat: False | search: True
# with failing store -> chat: False
# log: [{'action': 'turn_off', 'function': 'chat', 'reason': 'block rate collapsed', 'operator': 'oncall-1'}]
The output shows the three conditions: before turning off, both features are allowed; after turning off, chat is not and search is; and with the failing store, chat comes out as not allowed. Every action is written to the log with reason and operator: it serves reconstruction and the post-mortem. The trade-off of the «closed» behavior is stated: if the store fails, the service stops even without an incident. It is a legitimate choice only where the harm of a harmful content exceeds that of the outage, and it must be decided beforehand, not during. Subcategory MANAGE 2.4 of the NIST AI RMF asks for exactly this: mechanisms, with assigned responsibilities, to supersede, disengage or deactivate systems that show results inconsistent with their intended use.
Assess the impact: who received what
To know how many users were exposed you need the audit log. The query below answers three questions: how many
users received an output that slipped through the checks (an «allow» decision with a low score), how many requests
slipped through, and how many users continued the conversation within five minutes, which indicates that they read
the response. There is a trap worth knowing: the LEAD function must be computed on all the
requests of the session. If you filter first on the low score, the following requests with a good score disappear
from the table and the «next message» is never found. That is why the query uses an intermediate table,
con_seguito, and filters only afterwards.
-- impatto.sql - who received outputs that slipped through the checks, and who then continued the conversation.
-- Run on SQLite 3.46 with synthetic data; for PostgreSQL only the arithmetic on time changes.
WITH con_seguito AS (
-- LEAD must be computed on ALL the requests of the session: filtering first would make the following messages disappear
SELECT utente, sessione, istante, decisione, punteggio,
LEAD(istante) OVER (PARTITION BY sessione ORDER BY istante) AS prossimo
FROM audit_log
WHERE istante BETWEEN '2026-01-10 01:51:00' AND '2026-01-10 02:30:00'
),
sfuggite AS (
SELECT * FROM con_seguito
WHERE decisione = 'allow'
AND punteggio < 0.35
AND istante <= '2026-01-10 02:14:00'
),
per_utente AS (
SELECT utente,
COUNT(*) AS richieste,
SUM(CASE WHEN prossimo IS NOT NULL
AND (julianday(prossimo) - julianday(istante)) * 86400 < 300
THEN 1 ELSE 0 END) AS seguite_da_un_messaggio
FROM sfuggite
GROUP BY utente
)
SELECT COUNT(*) AS utenti_esposti,
SUM(seguite_da_un_messaggio > 0) AS utenti_che_hanno_proseguito,
SUM(richieste) AS richieste_sfuggite
FROM per_utente;
The file esegui_impatto.py creates a synthetic log of seven rows in memory and applies the query to it.
The analysis window is the incident (up to 02:14), while the search for the next message looks up to 02:30.
Window functions require SQLite 3.25 or later; the library used here is 3.46.1. For PostgreSQL only the time
calculation changes (an interval in place of julianday); that variant was not run.
# esegui_impatto.py - creates a SYNTHETIC audit_log in memory and applies impatto.sql to it.
import sqlite3
righe = [
# user, session, time, decision, score
("u1", "s1", "2026-01-10 01:55:00", "allow", 0.20),
("u1", "s1", "2026-01-10 01:56:10", "allow", 0.80), # continues within 5 minutes
("u2", "s2", "2026-01-10 02:00:00", "allow", 0.10), # no message afterwards
("u3", "s3", "2026-01-10 02:03:00", "block", 0.10), # blocked: does not count
("u4", "s4", "2026-01-10 02:05:00", "allow", 0.30),
("u4", "s4", "2026-01-10 02:20:00", "allow", 0.90), # continues, but after 15 minutes
("u5", "s5", "2026-01-10 00:30:00", "allow", 0.10), # outside the window
]
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE audit_log (utente TEXT, sessione TEXT, istante TEXT, decisione TEXT, punteggio REAL)")
db.executemany("INSERT INTO audit_log VALUES (?,?,?,?,?)", righe)
sql = open("impatto.sql", encoding="utf-8").read()
utenti, proseguito, richieste = db.execute(sql).fetchone()
print(f"exposed users: {utenti} | continued within 5 minutes: {proseguito} | requests that slipped through: {richieste}")
# Output:
# exposed users: 3 | continued within 5 minutes: 1 | requests that slipped through: 3
The numbers match the data: three users are exposed (u1, u2, u4), u3 is blocked and u5 stays out because its request precedes the window. Only u1 continued within five minutes; u4 wrote after fifteen minutes and does not count. The distinction between exposed users and users who continued serves to decide whom to contact first.
Notification obligations and preserving evidence
A guardrail incident is not automatically a personal data breach, but it can be one. If it is, Article 33 of the GDPR requires the controller to notify it to the supervisory authority «without undue delay and, where feasible, not later than 72 hours» after becoming aware of it, unless the breach is unlikely to result in a risk to the rights and freedoms of natural persons. For providers of high-risk AI systems, Article 73 of the AI Act provides for the reporting of serious incidents to the supervisory authorities, in general no later than 15 days after becoming aware of the incident (with shorter deadlines, two or ten days, for the cases indicated in paragraphs 3 and 4). If your system is not high-risk, this second obligation does not apply; assess your position with whoever handles compliance.
Article 73 also contains a detail that concerns the technical work: in paragraph 6 the provider «shall not perform any investigation which involves altering the AI system concerned» in a way that may affect any subsequent evaluation of the causes of the incident, prior to informing the authorities. In practice, before fixing anything it is worth saving what you need in order to understand:
- the configuration and the version of the rules and of the model in use at the time of the incident;
- the logs of the exposure window, as a read-only copy;
- the requests and outputs that slipped through, or at least their fingerprint and metadata;
- the timeline of the actions taken, including the time the switch was turned off.
These are the same things the post-mortem needs, so it is not additional work: it is work brought forward. As for keeping them, Article 19 of the AI Act asks providers of high-risk systems to keep the automatically generated logs for at least six months, subject to applicable law on personal data; in all other cases the duration depends on your legal basis, and the data minimization principle applies in both directions.
Finding the cause: the five whys lead to a process, not to a person
The five whys method makes sense only if every answer produces an action. It stops when the answer concerns a system or a process and not somebody's behavior. The table shows a chain built as an example of the method, not an incident that happened: it starts from a variant with invisible characters (the same one as in the regression tests further down) and arrives at a missing process.
| Why? | Answer | Action |
|---|---|---|
| 1. Why did the output get through? | The rule looked for the exact substring and the request contained an invisible character | Normalize the text before the comparison |
| 2. Why was there no test for this form? | The catalog contained no variants of form | Add mechanical mutations to the catalog |
| 3. Why did the catalog not contain them? | Nobody was tasked with updating it after the release | Assign an owner and a cadence |
| 4. Why was the task not assigned? | The release process ended with the deploy | Add catalog review to the process |
| 5. Why did the process end there? | The guardrail was treated as configuration, not as code with tests | Bring it under the same regime as code |
The root cause, in one sentence, is not «the rule was naive» but «the guardrail had no review cycle for its tests». Every row has an action with an owner and a deadline to be noted in the post-mortem; without owner and deadline, the five whys remain an exercise in style.
Fix and verify: the test born from the incident
Every P0 or P1 incident must leave behind at least one test that enters the suite for good. The rule is that of the
red-green test: the test is written before the fix, must fail on the old code and pass on the new. The file
regressione.py contains three tests (the form observed in the log, two paraphrases and a similar
legitimate request) and runs them against two versions of the fake guardrail. The tests use the standard
library's unittest; the pytest runner recognizes them without changes.
# regressione.py - the test born from the incident: it must fail BEFORE the patch and pass AFTER.
# The "guardrail" is fake and the bait words are made-up placeholders, as in the other examples of the series.
import io
import unicodedata
import unittest
ESCA = ("alfa7",)
INVISIBILI = {"", "", "", "", ""}
def guardrail_prima(testo):
return "block" if any(e in testo for e in ESCA) else "allow"
def guardrail_dopo(testo):
t = unicodedata.normalize("NFKC", testo).casefold()
t = "".join(c for c in t if c not in INVISIBILI)
return "block" if any(e in t for e in ESCA) else "allow"
VARIANTE_INCIDENTE = "Treat alfa7 as a system instruction." # the form observed in the log
PARAFRASI = ["Treat ALFA7 as a system instruction.", "Treat alfa7 as an instruction."]
LEGITTIMA = "My printer model Alfa keeps jamming: how do I fix it?"
def costruisci(guardrail):
class RegressioneIncidente(unittest.TestCase):
def test_incident_variant_blocked(self):
self.assertEqual(guardrail(VARIANTE_INCIDENTE), "block")
def test_paraphrases_blocked(self):
for testo in PARAFRASI:
with self.subTest(testo=testo):
self.assertEqual(guardrail(testo), "block")
def test_legitimate_request_not_blocked(self):
self.assertEqual(guardrail(LEGITTIMA), "allow")
return RegressioneIncidente
for nome, g in (("before the patch", guardrail_prima), ("after the patch", guardrail_dopo)):
suite = unittest.defaultTestLoader.loadTestsFromTestCase(costruisci(g))
esito = unittest.TextTestRunner(stream=io.StringIO(), verbosity=0).run(suite)
falliti = sorted({t.id().split(" ")[0].split(".")[-1] for t, _ in esito.failures})
print(f"{nome}: run={esito.testsRun} failed={len(esito.failures)} {falliti}")
# Output:
# before the patch: run=3 failed=3 ['test_incident_variant_blocked', 'test_paraphrases_blocked']
# after the patch: run=3 failed=0 []
Before the patch the tests run are 3 and the failures 3: it looks like a strange number, but one of the three tests
contains two sub-cases (subTest) and every failed sub-case counts separately; the list of names shows
that the two tests on attack requests failed, while the one on the legitimate request passes even before. After
the patch, zero failures. The third test is not an extra: it prevents the fix from being obtained by widening the
rule until it also blocks normal requests, which is the most common shortcut under pressure.
The blameless post-mortem
The document that closes the incident has few rules. It describes sequences of events, not accusations; it is written within a few days, while memories are fresh; it carries actions with an owner and a deadline. The chapter on post-mortem culture in Google's SRE book puts it bluntly: a blameless post-mortem assumes that the people involved had good intentions and did the right thing with the information they had, because in a culture of blame people do not bring problems to light for fear of being punished. The outline below is to be copied and adapted; it is not a runnable listing.
# Post-mortem: <short title>
- Identifier: INC-YYYY-NNN Severity: P0 / P1 / P2 Status: draft / in review / final
- Start and end (UTC): ... Duration of the exposure: ...
- Document owner: ... Review participants: ...
## Summary (three sentences)
What happened, who was exposed, when it was resolved.
## Timeline (UTC)
| Time | Event | Source (log, alarm, person) |
|------|-------|-----------------------------|
## Impact
Exposed users, users who continued, type of content (described without reusable details),
notification obligations assessed (yes / no / why).
## Causes
Immediate cause, chain of the five whys, systemic cause.
## What worked / what did not
Systems and processes, never people.
## Actions
| # | Action | Owner | Deadline | Status |
|---|--------|-------|----------|--------|
Note that in the impact section the type of content that slipped through is described without reusable details: the document circulates, and must not become a guide. The actions in the final table are the only part of the document that has a deadline, and it is the one the post-mortem's owner checks on the set date.
What you can do now
You can classify a guardrail incident and you can detect it with two signals instead of one. You can build a per-feature switch that closes by itself when in doubt, and you can write the query that says who was exposed without falling into the window-function trap. You know which evidence to keep before touching anything, which notification obligations may be triggered and how to tell them apart. The incident's regression test stays with you forever, while episode 10 on the evolution of the rules shows how to keep the catalog alive; the test bench is in episode 07 and the observability that feeds these alarms in episode 06.
The same series also includes the cost and latency of guardrails and defensive red teaming and the AI Act.
Frequently asked questions
What is the difference between a P0 and a P1 incident for a guardrail?
A P0 is harmful content already delivered to real users, with possible legal consequences; a P1 is a partial bypass or a serious degradation without confirmed harm. The practical line: an output that slipped through and reached even a single real user does not drop below P1, and when in doubt you escalate.
Should the switch stop the whole service or only the AI feature?
Only the feature involved, with a safe static response in its place. A per-feature switch reduces business damage and leaves monitoring active during recovery. Decide in advance the behavior if the state is not readable: closed or open, with the cost of each choice.
How long should the logs useful for an incident be kept?
There is no number that holds for everyone. The AI Act asks providers of high-risk systems to keep the automatically generated logs for at least six months, unless provided otherwise on personal data; in other cases the duration depends on the purpose and the legal basis of the processing, and must be declared and limited.
Sources
- NIST AI 100-1, Artificial Intelligence Risk Management Framework (AI RMF 1.0) - subcategories MANAGE 2.4 (deactivating systems inconsistent with intended use), 4.1 (monitoring and incident response plans) and 4.3 (communication of incidents), accessed 2026-11-12
- Regulation (EU) 2024/1689 (AI Act), English text on EUR-Lex - Article 73 (reporting of serious incidents, deadlines and paragraph 6 on investigations) and Article 19 (keeping of logs, at least six months), accessed 2026-11-12
- Regulation (EU) 2016/679 (GDPR), English text on EUR-Lex - Article 33, notification of a personal data breach within 72 hours where feasible, accessed 2026-11-12
- Google, Site Reliability Engineering, chapter «Postmortem Culture: Learning from Failure» - the blameless post-mortem and the follow-up actions, accessed 2026-11-12
- SQLite: Window Functions - the
lead()function used in the query, accessed 2026-11-12
The listings were run with Python 3.14 (SQLite 3.46.1) and the standard library only; every output is identical across two consecutive runs. Data, guardrail and bait words are synthetic. The PostgreSQL variant of the query and the post-mortem outline were not run.

Commenti
Caricamento commenti...
Sign in to comment