A guardrail that blocks without leaving a trace of why is unusable: you cannot tune the rules, you cannot explain to a user why they were stopped, you cannot reconstruct an incident. Recording decisions, however, creates a second problem, because the log becomes a store of data. In this article you build four things that have different purposes and that are best not confused: a log per decision, an audit trail that cannot be modified without it showing, metrics and alerts to notice what is happening now, and a way to handle the personal data in the log. The listings are executed, with invented data.
What the texts ask for, and what they do not
Regulation (EU) 2024/1689 (the AI Act) says, in Article 12, that high-risk AI systems must technically allow for the automatic recording of events (logs) over the lifetime of the system, for the purpose of traceability: identifying situations that may present a risk, facilitating post-market monitoring, monitoring the operation of the system. Paragraph 3 lists minimum contents (the period of each use, the reference database, the input data for which the search led to a match, the persons involved in verifying the results), but only for the systems in Annex III, point 1(a), that is, remote biometric identification. The text contains no list of fifteen fields valid for every system, as one sometimes reads.
On retention, Articles 19 (providers) and 26(6) (deployers) require keeping the logs, to the extent they are under their control, for a period appropriate to the intended purpose and of at least six months, "unless provided otherwise in applicable Union or national law, in particular in Union law on the protection of personal data". That clause is the point of contact with the GDPR. Whether your system is high-risk depends on Article 6 and Annex III, that is, on its use.
A negative observation, to be checked with your adviser: I searched the texts of the NIS2 directive (EU 2022/2555) and of the DORA regulation (EU 2022/2554) for a fixed retention period for the audit trail, and I did not find one. The "5 years for NIS2" and "7 years for DORA" that you read in many guides do not appear as such in those texts; they may derive from technical standards, delegated acts or national rules that I did not consult here. I do not repeat them as facts.
The GDPR, finally, sets two markers that guide the design. The definition of pseudonymisation (Article 4, point 5) says the data can no longer be attributed to a specific person without additional information, kept separately and protected: pseudonymised data therefore remains personal data as long as a way to link it back exists. And Article 17(3)(b) excludes the right to erasure to the extent that the processing is necessary for compliance with a legal obligation. The rest is a legal assessment that is not for a technical article to make.
What to record, and what never
The table lists the fields that the log of a decision should contain and the reason each one is there. The last row is the most important: the user's text and the values of the personal data found do not go into the log.
| Field | What it is for | Caution |
|---|---|---|
request, session | Link the decision to the application logs and reconstruct a conversation | Random identifiers, not derived from the user's data |
user | Count repeated attempts by the same user | Internal reference or pseudonym, never email or name |
outcome, reason | Know what was decided and why | The reason is a value from a closed list, not free text |
path | Tell rules and judge apart: cost and reliability are different | It also helps to understand which blocks must be reviewed by hand |
policy_version | Know which rule was in force when the decision was made | Without it, the effect of a change cannot be assessed |
input_fingerprint | Verify, given the text, that it is the one behind the decision | Computed with a secret key (HMAC), not with a plain hash |
| Do not record | The text of the request, the values of personal data | You record the type found, not the data |
The common thread is a trade-off: more fields allow better analysis, but every field that identifies a person adds an obligation of protection, access and erasure. You start from the minimum that answers the questions someone will really ask you (an auditor, a user, you in six months) and add only with a written reason.
The log of every decision
The listing decisione_log.py uses structlog, whose JSON renderer produces one line per event that a log aggregator reads without regular expressions. Three choices deserve a line. Motivo is an enumeration, because free strings cannot be aggregated. Decisione.testo enters the function but not the log: only input_fingerprint comes out. And the fingerprint is an HMAC with a key, not a plain SHA-256: the hash of a short or structured text, such as a fiscal code, can be rebuilt by trying candidates, whereas without the key the HMAC cannot. The time is not read from the clock but passed as an argument, to make the output reproducible.
import hashlib
import hmac
from dataclasses import dataclass
from enum import Enum
import structlog
class Motivo(str, Enum): # fixed values: they can be aggregated, free strings cannot
DATI_PERSONALI = "PERSONAL_DATA"
TEMA_VIETATO = "FORBIDDEN_TOPIC"
INIEZIONE = "INJECTION"
FORMATO = "FORMAT"
FONTE_INVENTATA = "INVENTED_SOURCE"
LIMITE_CONSUMO = "RATE_LIMIT"
@dataclass(frozen=True)
class Decisione:
richiesta: str
sessione: str
utente: str # internal identifier, never the email or the name
esito: str # "BLOCK" | "ALLOW"
motivo: Motivo | None
percorso: str # "rules" | "judge"
versione_policy: str
testo: str # NOT logged: only its fingerprint remains
CHIAVE_DI_PROVA = b"test-key" # in a real system: a secret, read from the environment
def impronta(testo: str, chiave: bytes = CHIAVE_DI_PROVA) -> str:
# HMAC and not plain SHA-256: a short or structured text could be rebuilt by trying candidates
return hmac.new(chiave, testo.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
def configura():
structlog.configure(
processors=[structlog.processors.add_log_level, structlog.processors.JSONRenderer(sort_keys=True)],
logger_factory=structlog.PrintLoggerFactory(),
)
return structlog.get_logger("guardrail")
def registra(log, d: Decisione, ora_iso: str) -> None:
campi = dict(event="decision", time=ora_iso, request=d.richiesta, session=d.sessione, user=d.utente,
outcome=d.esito, reason=d.motivo.value if d.motivo else None, path=d.percorso,
policy_version=d.versione_policy, input_fingerprint=impronta(d.testo))
(log.warning if d.esito == "BLOCK" else log.info)(**campi)
if __name__ == "__main__":
log = configura()
registra(log, Decisione("r-001", "s-9", "u-17", "BLOCK", Motivo.DATI_PERSONALI, "rules", "1.2.0",
"My fiscal code is RSSMRA85T10A562S"), "2026-11-12T10:00:00Z")
registra(log, Decisione("r-002", "s-9", "u-17", "ALLOW", None, "rules", "1.2.0",
"How do I set a timeout?"), "2026-11-12T10:00:05Z")
# Output:
# {"event": "decision", "input_fingerprint": "7d4a6ffd63027371", "level": "warning", "outcome": "BLOCK", "path": "rules", "policy_version": "1.2.0", "reason": "PERSONAL_DATA", "request": "r-001", "session": "s-9", "time": "2026-11-12T10:00:00Z", "user": "u-17"}
# {"event": "decision", "input_fingerprint": "eaea12baac1ef482", "level": "info", "outcome": "ALLOW", "path": "rules", "policy_version": "1.2.0", "reason": null, "request": "r-002", "session": "s-9", "time": "2026-11-12T10:00:05Z", "user": "u-17"}
The two lines of the output are the same function with two outcomes: a block for personal data, emitted at warning level, and a pass at info level. Neither contains the fiscal code of the first message: only the fingerprint is there. The keys are sorted (sort_keys=True) to have comparable lines. The value of the key in the listing is a test key; in a real system it is a secret read from the environment and rotated with a procedure.
The audit trail: insert-only, and a chain that reveals tampering
The operational log is rotated and thrown away; the audit register is not, because it must be able to prove months later what happened. The property asked of it is that it cannot be modified without it showing. The listing audit_trail.py achieves it in two ways, both run on in-memory SQLite. The no_update and no_delete triggers reject ordinary modifications. But whoever has schema rights can drop a trigger, and that is why every row also contains the fingerprint of the previous one: a chain in which changing one row breaks all the following ones.
The listing includes the query on suspicious sessions, which takes the order of events into account: for each pass (ALLOW) it counts how many blocks precede it in the same session (b.seq < a.seq). A version that only counts the blocks and passes of the session, with no order, also flags someone who was accepted first and blocked afterwards, which is the opposite behavior.
import hashlib
import json
import sqlite3
SCHEMA = """
CREATE TABLE eventi(
seq INTEGER PRIMARY KEY AUTOINCREMENT,
ora TEXT NOT NULL, sessione TEXT NOT NULL, utente_ref TEXT NOT NULL,
esito TEXT NOT NULL CHECK (esito IN ('BLOCK','ALLOW')), motivo TEXT,
versione_policy TEXT NOT NULL, impronta_precedente TEXT NOT NULL, impronta TEXT NOT NULL);
CREATE TRIGGER no_update BEFORE UPDATE ON eventi BEGIN SELECT RAISE(ABORT, 'audit trail: insert-only'); END;
CREATE TRIGGER no_delete BEFORE DELETE ON eventi BEGIN SELECT RAISE(ABORT, 'audit trail: insert-only'); END;
"""
CAMPI = ("ora", "sessione", "utente_ref", "esito", "motivo", "versione_policy")
def impronta_riga(precedente: str, valori: dict) -> str:
canonico = json.dumps({k: valori[k] for k in CAMPI}, sort_keys=True, ensure_ascii=False)
return hashlib.sha256((precedente + canonico).encode("utf-8")).hexdigest()
def aggiungi(conn, **valori) -> None:
ultima = conn.execute("SELECT impronta FROM eventi ORDER BY seq DESC LIMIT 1").fetchone()
precedente = ultima[0] if ultima else "0" * 64
conn.execute("INSERT INTO eventi(ora,sessione,utente_ref,esito,motivo,versione_policy,impronta_precedente,impronta)"
" VALUES (:ora,:sessione,:utente_ref,:esito,:motivo,:versione_policy,:p,:h)",
{**valori, "p": precedente, "h": impronta_riga(precedente, valori)})
def verifica_catena(conn) -> int | None:
"""Returns the seq of the first inconsistent row, or None if the chain holds."""
precedente = "0" * 64
for riga in conn.execute("SELECT seq,ora,sessione,utente_ref,esito,motivo,versione_policy,"
"impronta_precedente,impronta FROM eventi ORDER BY seq"):
valori = dict(zip(CAMPI, riga[1:7]))
if riga[7] != precedente or riga[8] != impronta_riga(precedente, valori):
return riga[0]
precedente = riga[8]
return None
SESSIONI_SOSPETTE = """
SELECT a.sessione, COUNT(*) AS passaggi_dopo_3_blocchi FROM eventi a
WHERE a.esito='ALLOW' AND (SELECT COUNT(*) FROM eventi b
WHERE b.sessione=a.sessione AND b.esito='BLOCK' AND b.seq<a.seq) >= 3
GROUP BY a.sessione"""
if __name__ == "__main__":
conn = sqlite3.connect(":memory:")
conn.executescript(SCHEMA)
base = dict(versione_policy="1.2.0", utente_ref="p-001")
for i, (sess, esito, motivo) in enumerate([("s-1", "BLOCK", "INJECTION"), ("s-1", "BLOCK", "FORBIDDEN_TOPIC"),
("s-1", "BLOCK", "INJECTION"), ("s-1", "ALLOW", None),
("s-2", "ALLOW", None), ("s-3", "ALLOW", None), ("s-3", "BLOCK", "FORMAT")]):
aggiungi(conn, ora=f"2026-11-12T10:00:{i:02d}Z", sessione=sess, esito=esito, motivo=motivo, **base)
print("chain intact:", verifica_catena(conn) is None)
print("suspicious sessions:", conn.execute(SESSIONI_SOSPETTE).fetchall())
try:
conn.execute("UPDATE eventi SET esito='ALLOW' WHERE seq=1")
except sqlite3.DatabaseError as e:
print("UPDATE rejected:", e)
conn.execute("DROP TRIGGER no_update") # whoever has schema rights gets around the trigger...
conn.execute("UPDATE eventi SET esito='ALLOW' WHERE seq=2")
print("after the tampering, first inconsistent row:", verifica_catena(conn)) # ...but the chain reveals it
# Output:
# chain intact: True
# suspicious sessions: [('s-1', 1)]
# UPDATE rejected: audit trail: insert-only
# after the tampering, first inconsistent row: 2
The output retraces the reasoning. The chain is intact. The session s-1 (three blocks, then a pass) is the only one flagged: s-3 has a pass followed by a block and s-2 only a pass, and they stay out. The UPDATE is rejected by the trigger. After dropping the trigger and modifying row 2, the check points to row 2 itself as the first inconsistent one. The limit is just as clear: whoever can rewrite the whole chain from the tampered row onward recomputes the fingerprints and nobody notices. The countermeasure is to anchor the last fingerprint outside the system every so often (another service, a signed document), so as to have a point that the attacker does not control.
On PostgreSQL the same idea is obtained with triggers and permissions (removing UPDATE and DELETE from the application role). I did not use ClickHouse in this article and I do not guarantee its immutability properties: if you choose it, check in its documentation what the engine does at every data merge, because an engine designed to deduplicate rows with the same key is not, for that reason, an unmodifiable register.
Metrics: what is happening now
The audit trail answers "what happened". For "what is happening" you need metrics, which are read on a chart or in an alert rule. The listing metriche.py uses the Prometheus Python client with a dedicated registry, two counters (blocks and passes) and a histogram of durations. Two choices derive from the Prometheus guide on names and labels: every combination of label values is a time series of its own, so you do not put user IDs, emails or other unbounded sets of values in labels; and base units are used, so seconds and not milliseconds.
from prometheus_client import CollectorRegistry, Counter, Histogram, generate_latest
REGISTRO = CollectorRegistry()
BLOCCHI = Counter("guardrail_blocks", "BLOCK decisions of the guardrail",
["reason", "path", "policy_version"], registry=REGISTRO)
PASSAGGI = Counter("guardrail_passes", "ALLOW decisions of the guardrail",
["path", "policy_version"], registry=REGISTRO)
DURATA = Histogram("guardrail_duration_seconds", "Duration of the evaluation", ["path"],
buckets=(0.001, 0.005, 0.025, 0.1, 0.5, 2.5), registry=REGISTRO)
def registra(esito, motivo, percorso, versione, durata_s):
if esito == "BLOCK":
BLOCCHI.labels(reason=motivo, path=percorso, policy_version=versione).inc()
else:
PASSAGGI.labels(path=percorso, policy_version=versione).inc()
DURATA.labels(path=percorso).observe(durata_s) # no user, no session: bounded cardinality
if __name__ == "__main__":
for esito, motivo, percorso, durata in [("BLOCK", "INJECTION", "rules", 0.0002), ("BLOCK", "INJECTION", "rules", 0.0003),
("BLOCK", "PERSONAL_DATA", "rules", 0.0002), ("ALLOW", None, "rules", 0.0002),
("ALLOW", None, "judge", 0.35)]:
registra(esito, motivo, percorso, "1.2.0", durata)
for riga in generate_latest(REGISTRO).decode().splitlines():
if riga.startswith("guardrail_") and "_created" not in riga and "_bucket" not in riga:
print(riga)
# Output:
# guardrail_blocks_total{path="rules",policy_version="1.2.0",reason="INJECTION"} 2.0
# guardrail_blocks_total{path="rules",policy_version="1.2.0",reason="PERSONAL_DATA"} 1.0
# guardrail_passes_total{path="rules",policy_version="1.2.0"} 1.0
# guardrail_passes_total{path="judge",policy_version="1.2.0"} 1.0
# guardrail_duration_seconds_count{path="rules"} 4.0
# guardrail_duration_seconds_sum{path="rules"} 0.0009
# guardrail_duration_seconds_count{path="judge"} 1.0
# guardrail_duration_seconds_sum{path="judge"} 0.35
In the output, the two blocks for injection are a single counter with value 2, distinct from the block for personal data thanks to the reason label; counters receive the _total suffix; the histogram exposes the number and sum of observations per path (four evaluations for the rules, one for the judge, with a sum of 0.35 seconds). The bucket lines and the _created series are filtered out in the listing only for brevity. The single user trying to get around the system is not visible here: they are visible in the audit trail, where the identifier can live.
Alerts: thresholds to calibrate, not to copy
Three rules are enough to start: the blocks of the last five minutes above triple the average of the last hour, a high rate of blocks for injection, a duration of the path with the judge above a threshold. The listing is a schema to adapt: I verified that the YAML file loads (output at the bottom, PyYAML), but I did not validate the PromQL expressions because promtool is not available. The thresholds (0.2 per second, 2.5 seconds) are placeholders: a sensible value comes only from observing your own traffic for a few weeks.
# Schema to adapt: YAML syntax verified, PromQL expressions NOT validated (promtool not available).
# The thresholds are placeholders to calibrate on real traffic after a few weeks of observation.
groups:
- name: guardrail
rules:
- alert: GuardrailBlocksRising
# blocks in the last 5 minutes above three times the average of the last hour
expr: sum(rate(guardrail_blocks_total[5m])) > 3 * sum(rate(guardrail_blocks_total[1h]))
for: 5m
labels: {severity: warning}
annotations: {summary: "Guardrail blocks rising compared with the hourly average"}
- alert: GuardrailFrequentInjections
expr: sum(rate(guardrail_blocks_total{reason="INJECTION"}[10m])) > 0.2
for: 10m
labels: {severity: warning}
annotations: {summary: "Many blocks for attempted injection: check the sessions in the audit trail"}
- alert: GuardrailSlowJudge
expr: histogram_quantile(0.95, sum by (le) (rate(guardrail_duration_seconds_bucket{path="judge"}[10m]))) > 2.5
for: 10m
labels: {severity: warning}
annotations: {summary: "The path with the judge exceeds the duration threshold"}
# Output of verifica_regole.py (loads the file with PyYAML):
# GuardrailBlocksRising for=5m severity=warning
# GuardrailFrequentInjections for=10m severity=warning
# GuardrailSlowJudge for=10m severity=warning
The method for choosing a threshold is simple. Observe the value of the metric under normal conditions, choose a margin that forces you to look when something really changes, and use for: to avoid being woken by an isolated spike. Alerts must lead to a described action (what to look at, in which panel, in which query): an alert without a delivered action is noise, and soon becomes something that gets ignored.
Personal data in the log: separating identity from events
The listing pseudonimi.py shows a way to keep the events without keeping the link to the person. The events contain a random token, and the correspondence between user and token lives in a separate table, the one that must be protected the most. The token is random, not a function of the identifier, and for this reason it cannot be rebuilt by someone who does not have the table. A request for erasure deletes the correspondence row: the events stay, the link does not.
import secrets
import sqlite3
conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE pseudonimi(utente TEXT PRIMARY KEY, token TEXT NOT NULL); -- kept separate and protected
CREATE TABLE eventi(seq INTEGER PRIMARY KEY, token TEXT NOT NULL, esito TEXT NOT NULL);
""")
def token_per(utente: str) -> str:
riga = conn.execute("SELECT token FROM pseudonimi WHERE utente=?", (utente,)).fetchone()
if riga:
return riga[0]
nuovo = secrets.token_hex(8) # random: it cannot be derived from the user's identifier
conn.execute("INSERT INTO pseudonimi VALUES (?,?)", (utente, nuovo))
return nuovo
def richiesta_di_cancellazione(utente: str) -> int:
"""Removes the link between the person and their events; it does not delete the events."""
return conn.execute("DELETE FROM pseudonimi WHERE utente=?", (utente,)).rowcount
def eventi_riconducibili(utente: str) -> int:
return conn.execute("SELECT COUNT(*) FROM eventi e JOIN pseudonimi p ON p.token=e.token WHERE p.utente=?",
(utente,)).fetchone()[0]
if __name__ == "__main__":
for utente, esito in [("anna", "BLOCK"), ("anna", "ALLOW"), ("luca", "ALLOW"), ("anna", "BLOCK")]:
conn.execute("INSERT INTO eventi(token,esito) VALUES (?,?)", (token_per(utente), esito))
print("total events:", conn.execute("SELECT COUNT(*) FROM eventi").fetchone()[0])
print("traceable to anna before:", eventi_riconducibili("anna"))
richiesta_di_cancellazione("anna")
print("traceable to anna after :", eventi_riconducibili("anna"))
print("total events after :", conn.execute("SELECT COUNT(*) FROM eventi").fetchone()[0])
print("blocks kept :", conn.execute("SELECT COUNT(*) FROM eventi WHERE esito='BLOCK'").fetchone()[0])
# Output:
# total events: 4
# traceable to anna before: 3
# traceable to anna after : 0
# total events after : 4
# blocks kept : 2
The output shows the result: four events in total, three traceable to Anna before the request, zero after, four events still present and two blocks kept for analysis. The legal question remains open, and I cannot close it: whether, in a specific case, removing the link is enough to satisfy a request for erasure depends on whether other identifying elements remain in the data (an address, a reusable session identifier, a text) and on any legal obligation to retain. Before adopting the schema, discuss it with whoever handles data protection.
What you can do now
You can say what Article 12 of the AI Act really asks for (and that the minimum content of paragraph 3 concerns only one case), what minimum retention it proposes (six months, with the clause on personal-data law) and which widespread figures you have not verified. You can write a log per decision that does not contain the user's text, build a register that flags modifications, define metrics without high-cardinality labels, set up alerts to calibrate and separate identity from events. To verify that the checks work, see the article on testing; for what the register tells you when a check fails, incident response.
The same series also includes the three control points and guardrail architectures, guardrails with NeMo Guardrails and Colang, the defense against prompt injection and validating an LLM's output.
Frequently asked questions
What is the difference between an application log and an audit trail?
The application log serves to understand and repair how the system works, and it is rotated. The audit trail serves to prove after a long time what happened, and it must make modifications visible. They have different life cycles and requirements, so they do not coincide.
What does Article 12 of the AI Act say about logs?
That high-risk AI systems must allow the automatic recording of events over their whole lifetime, for traceability. The list of minimum contents in paragraph 3 applies only to the systems in Annex III, point 1(a). Whether your system is high-risk depends on Article 6 and Annex III.
How long must logs be kept?
For high-risk systems, Articles 19 and 26 of the AI Act indicate at least six months, unless provided otherwise by Union or national law, in particular on the protection of personal data. I did not find a fixed retention period in the texts of NIS2 and DORA: check with your legal adviser.
Can I record the text of the blocked request?
As a rule no: it contains personal data and creates a store you must protect and erase. Record the outcome, the reason, the type of data found and a fingerprint computed with a secret key, so that you can verify a request without keeping it.
Is pseudonymisation enough to satisfy a request for erasure?
Not automatically. Under the GDPR, pseudonymised data remains personal as long as a way to link it back exists, and erasure has exceptions, among them the legal obligation to retain. Whether removing the link is enough in a specific case is an assessment for whoever handles data protection.
Sources
- Regulation (EU) 2024/1689 (AI Act), Articles 12, 19 and 26 - the content of Article 12 (paragraphs 1-3), the retention of logs for at least six months (Articles 19 and 26(6)), consulted on 2026-11-12
- Regulation (EU) 2016/679 (GDPR), Articles 4 and 17 - the definition of pseudonymisation (Article 4, point 5) and the exceptions to erasure (Article 17(3)), consulted on 2026-11-12
- Directive (EU) 2022/2555 (NIS2) - search for a fixed retention period for the audit trail in the text: not found, consulted on 2026-11-12
- Regulation (EU) 2022/2554 (DORA) - search for a fixed retention period for the audit trail in the text: not found, consulted on 2026-11-12
- Prometheus: Metric and label naming - the warning on high-cardinality labels and base units, consulted on 2026-11-12
- structlog: Processors - the JSON renderer as a processor for log aggregators, consulted on 2026-11-12
The listings were run twice with identical output (Python 3.10 with structlog 26.1.0, prometheus-client 0.26.0 and PyYAML 6.0.3 for decisione_log.py, metriche.py and the rule check; Python 3.14 for audit_trail.py and pseudonimi.py). The alert rules are a schema to adapt, with YAML syntax verified and PromQL not validated. This article is not legal advice.

Commenti
Caricamento commenti...
Sign in to comment