A statute in the form of a rule: what you gain and what you lose
The data protection officer tells you: "erasure requests must be handled within the deadlines". An automated compliance system turns this sentence into a rule that the software can evaluate on every event, producing an alert when the deadlines are exceeded. The gain is continuity of control: you do not discover the violation at the year-end audit. The cost is the translation: in the passage from statute to code something is always lost, and the hardest part of the project is deciding what.
This article builds a small rules engine with three ideas that make it usable in a regulated context: the rules are versioned data and not code, they are applied with the version in force at the date of the facts, and every evaluation leaves a trace that cannot be silently rewritten. The two listings were run; the example rules cite provisions I read in the official text, and they must still be validated by whoever answers for compliance. If you first want to understand where the custody trail lives, read the previous article on the e-Discovery platform.
Rules as data: three examples, three translation traps
The YAML file below contains three rules. Each declares its source, the date it came into force, its version and a list of conditions on fields of the event. I chose three different provisions on purpose, because each one hides a modelling difficulty.
- rule_id: GDPR-DSR-DEADLINE
name: Data subject request past the deadline, with no extension notified
source: "Regulation (EU) 2016/679, Article 12(3)"
effective_date: 2018-05-25
version: "1.0.0"
severity: HIGH
match: all
conditions:
- {field: event.type, op: eq, value: DSR_OPEN}
- {field: event.days_overdue, op: gt, value: 0}
- {field: event.extension_notified, op: ne, value: true}
- rule_id: GDPR-BREACH-72H
name: Data breach not notified within 72 hours
source: "Regulation (EU) 2016/679, Article 33(1)"
effective_date: 2018-05-25
version: "1.0.0"
severity: CRITICAL
match: all
conditions:
- {field: event.type, op: eq, value: BREACH_OPEN}
- {field: event.hours_since_awareness, op: gt, value: 72}
- {field: event.risk_unlikely, op: ne, value: true}
- {field: event.authority_notified, op: ne, value: true}
- rule_id: AML-OCCASIONAL-15K
name: Occasional transaction of 15,000 EUR or more without customer due diligence
source: "Directive (EU) 2015/849, Article 11(b) (national transposition to be verified)"
effective_date: 2017-06-26
version: "1.0.0"
severity: HIGH
match: all
conditions:
- {field: event.type, op: eq, value: OCCASIONAL_TRANSACTION}
- {field: event.amount_eur, op: gte, value: 15000}
- {field: customer.cdd_completed, op: ne, value: true}
# Sample data, loaded by the next listing.
The first rule concerns the deadline for answering the data subject. Article 12(3) of the GDPR
speaks of "without undue delay" and "in any event within one month of receipt of the request", extendable by two
further months where necessary, with notice to the data subject within the first month. A deadline of "30 days"
is not what the provision says: the month is a calendar month, so the computation of the overdue days
(days_overdue) must live in the system that manages the case, and the rule only checks that it is
positive and that the extension was not notified. The second concerns the notification of a data breach: Article
33(1) provides for notification to the supervisory authority within 72 hours of becoming aware of the breach,
"where feasible", unless the breach is unlikely to result in a risk to individuals; that is why the rule has the
risk_unlikely field.
The third rule shows the limit of modelling by directive: Article 11 of Directive (EU) 2015/849
requires customer due diligence for occasional transactions of an amount equal to or above 15,000 EUR, even if
split into linked transactions. Splitting is not captured by a condition on a single event (you need an
aggregation), and a directive binds the Member States: the obligation for an Italian entity derives from the
national transposition, which the source field declares as to be verified on Normattiva (the
official database of Italian legislation). A warning about the text of this source: the directive has been
amended several times, so the version to cite in production is the consolidated one in force.
The engine: validation, date of the facts and a flaw to know about
The engine uses Pydantic
to validate the rules on loading and yaml.safe_load to read them. Three choices deserve naming. The
models are frozen (ConfigDict(frozen=True)), so a loaded rule no longer changes. The
operator is a Literal: a wrong operator in the file makes loading fail instead of going unnoticed.
And ricarica (reload) reads and validates everything before taking the lock and replacing the tuple
of rules: if the new file is wrong the old version stays in operation, and this is the practical meaning of
"update without downtime".
import operator
from datetime import date
from pathlib import Path
from threading import Lock
from typing import Any, Literal
import yaml
from pydantic import BaseModel, ConfigDict
OPERATORI = {"eq": operator.eq, "ne": operator.ne, "gt": operator.gt, "gte": operator.ge,
"lt": operator.lt, "lte": operator.le, "in": lambda v, soglia: v in soglia}
class Condizione(BaseModel):
model_config = ConfigDict(frozen=True)
field: str
op: Literal["eq", "ne", "gt", "gte", "lt", "lte", "in"] # unknown operator: error on loading
value: Any
class Regola(BaseModel):
model_config = ConfigDict(frozen=True)
rule_id: str
name: str
source: str
effective_date: date
expiry_date: date | None = None
version: str
severity: Literal["CRITICAL", "HIGH", "MEDIUM", "LOW"]
match: Literal["all", "any"] = "all"
conditions: tuple[Condizione, ...]
def leggi(evento: dict, percorso: str) -> Any:
valore = evento
for chiave in percorso.split("."):
valore = valore[chiave]
return valore
def condizione_vera(c: Condizione, evento: dict) -> bool:
try:
return OPERATORI[c.op](leggi(evento, c.field), c.value)
except (KeyError, TypeError):
return False # missing field: the condition is NOT satisfied (a choice to be aware of)
class Motore:
def __init__(self, percorso: str):
self._percorso = Path(percorso)
self._lock = Lock()
self._regole: tuple[Regola, ...] = ()
self.ricarica()
def ricarica(self) -> None:
"""Reads and validates everything BEFORE replacing: if the file is wrong the old version stays."""
nuove = tuple(Regola(**r) for r in yaml.safe_load(self._percorso.read_text(encoding="utf-8")))
with self._lock:
self._regole = nuove
def valuta(self, evento: dict, alla_data: date) -> list[tuple[str, str]]:
with self._lock:
regole = self._regole
violazioni = []
for r in regole:
if alla_data < r.effective_date or (r.expiry_date and alla_data >= r.expiry_date):
continue # a rule applies with the version in force at the date of the facts
esiti = [condizione_vera(c, evento) for c in r.conditions]
if (all(esiti) if r.match == "all" else any(esiti)):
violazioni.append((r.rule_id, r.severity))
return violazioni
if __name__ == "__main__":
motore = Motore("regole.yaml")
richiesta = {"event": {"type": "DSR_OPEN", "days_overdue": 12, "extension_notified": False}}
violazione = {"event": {"type": "BREACH_OPEN", "hours_since_awareness": 80,
"risk_unlikely": False, "authority_notified": False}}
senza_campo = {"event": {"type": "OCCASIONAL_TRANSACTION", "amount_eur": 20000}}
print("1", motore.valuta(richiesta, date(2026, 11, 12)))
print("2", motore.valuta(richiesta, date(2018, 3, 1)))
print("3", motore.valuta(violazione, date(2026, 11, 12)))
print("4", motore.valuta(senza_campo, date(2026, 11, 12)))
print("5", motore.valuta({**senza_campo, "customer": {"cdd_completed": True}}, date(2026, 11, 12)))
# Output (run):
# 1 [('GDPR-DSR-DEADLINE', 'HIGH')]
# 2 []
# 3 [('GDPR-BREACH-72H', 'CRITICAL')]
# 4 []
# 5 []
Run with the three rules, the listing gives five answers, and two deserve attention. In case 2 the same event as
case 1 is evaluated at the date of 1 March 2018 and produces no violations: the GDPR applies from 25 May 2018
(Article 99(2)), so the rule does not yet exist at the date of the facts. To demonstrate compliance at a given
date you need to know which version was in force then, which is why effective_date,
expiry_date and version are mandatory fields and not decoration.
Case 4 is the flaw. The event describes a transaction of 20,000 EUR but does not contain the field
customer.cdd_completed: the read fails, condizione_vera returns
False and the rule does not fire. A missing datum is equivalent to "no violation", that is,
the system fails silently in favour of the operator. It is a choice to be made explicit: in a compliance system
it pays to distinguish three outcomes (violation, compliant, insufficient data) and to send the third to a
person. In case 5 the field is there, it is true, and the rule correctly stays silent.
What is not included, and why
A real engine receives events from a bus (Kafka or equivalent) and commits the offset only after persisting the outcome: this way an event is not lost and, if the job fails, it is processed again; the price is that the same event may be evaluated twice, so the evaluation and the writing of the outcome must be idempotent. I do not include the consumer code because I did not run it, and I do not replace it with a schema that looks complete. In the same way I left out risk scoring with machine-learning models: it requires labelled historical data and a validation that are not available here, and for a regulatory rule a score you can explain to an inspector, for example the severity of the violated rule, is preferable before adding an opaque model.
For market figures (size of the RegTech sector, growth rates) I did not find a verifiable primary source and I removed them: they are not needed to design the system.
The audit trail: why HMAC and not a plain hash
A rule applied without a trace cannot be defended. The second listing builds an append-only register in which
every entry contains the signature of the previous one and its own HMAC-SHA256 signature.
Unlike a plain hash, HMAC requires a secret key: whoever modifies an entry cannot recompute a valid signature
without having it. The comparison of signatures uses hmac.compare_digest, which does not reveal
through response times how many characters match, as the
documentation of the hmac module describes.
import hashlib
import hmac
import json
class RegistroAudit:
"""Append-only register: every entry is signed with HMAC-SHA256 and embeds the signature of the previous one."""
def __init__(self, chiave: bytes):
self._chiave = chiave
self._voci: list[dict] = []
def _firma(self, corpo: dict) -> str:
dati = json.dumps(corpo, sort_keys=True, ensure_ascii=False).encode()
return hmac.new(self._chiave, dati, hashlib.sha256).hexdigest()
def aggiungi(self, tipo: str, dati: dict) -> None:
precedente = self._voci[-1]["firma"] if self._voci else "0" * 64
corpo = {"n": len(self._voci) + 1, "tipo": tipo, "dati": dati, "precedente": precedente}
self._voci.append({**corpo, "firma": self._firma(corpo)})
def verifica(self, voci: list[dict] | None = None) -> int | None:
precedente = "0" * 64
for voce in (self._voci if voci is None else voci):
corpo = {k: v for k, v in voce.items() if k != "firma"}
if corpo["precedente"] != precedente or not hmac.compare_digest(self._firma(corpo), voce["firma"]):
return voce["n"]
precedente = voce["firma"]
return None
def copia_voci(self) -> list[dict]:
return json.loads(json.dumps(self._voci))
if __name__ == "__main__":
registro = RegistroAudit(chiave=b"test-key-to-be-kept-in-a-secrets-manager")
registro.aggiungi("EVALUATION", {"regola": "GDPR-BREACH-72H", "esito": "violation"})
registro.aggiungi("ACTION", {"azione": "notify the Garante", "utente": "dpo"})
registro.aggiungi("CLOSURE", {"stato": "RESOLVED"})
print("intact:", registro.verifica() is None)
manomesso = registro.copia_voci()
manomesso[1]["dati"]["azione"] = "none"
print("data modified, first inconsistent entry:", registro.verifica(manomesso))
# Whoever does NOT have the key cannot recompute the signature; whoever has a plain hash can.
manomesso[1]["firma"] = hashlib.sha256(json.dumps(
{k: v for k, v in manomesso[1].items() if k != "firma"}, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
print("modified with signature recomputed without the key:", registro.verifica(manomesso))
# Output (run):
# intact: True
# data modified, first inconsistent entry: 2
# modified with signature recomputed without the key: 2
The output shows two tamperings detected: the modification of the data of entry 2 and the modification with a signature "recomputed" as a plain SHA-256, because without the key the HMAC cannot be produced. The limit is the key itself: whoever holds it (a system administrator) can rewrite the whole chain, so the key must be kept in a separate secrets manager and the head of the chain must be anchored outside the system, as seen in the register of the article on the e-Discovery platform. A signature does not encrypt the data: if the payload contains personal data, the register is itself subject to the GDPR, with its own retention periods (this is discussed in GDPR and privacy by design).
The mistakes that make a compliance system useless
- The rules are written in the code and every regulatory change requires a release.
- The rules have no version and no application date, and nobody knows what applied at a given date.
- A missing datum is treated as compliance.
- Nobody is responsible for the content of each rule.
The four items are read together: the engine and the test data are the easy part. The first two are solved with the structure you have seen (rules as versioned files with an application date), the third with a third outcome, "insufficient data", the fourth with an owner for each rule, for example the data protection officer for the GDPR rules. There is no order of importance, but the third is the most insidious because the system keeps looking compliant.
What you can do now
You can represent a statute as data with a source, a version and an application date, evaluate it with an engine that applies the version in force at the date of the facts and updates without stopping, recognise where the translation from statute to code loses information, and record the evaluations in a register signed with a key. For integrating these events with the other systems of the organisation, continue with the data integration patterns. The system is an aid for whoever answers for compliance, not legal advice.
Frequently asked questions
Why should regulatory rules be kept as data and not as code?
Because a regulatory change alters the content of the rule, not the logic of the engine. If the rule is a file with a source, a version and an application date, it is updated without releasing the software and you can reconstruct which rule applied at a given date.
Within what time must a data erasure request be handled?
Without undue delay and, at the latest, within one month of receipt of the request; the deadline may be extended by two further months where necessary, informing the data subject within the first month (Article 12(3), GDPR). It is not a fixed count of 30 days.
What happens if a datum of the event is missing for a rule?
It depends on how you designed it. In the engine of this article the condition turns out false and the rule does not fire, so a missing datum passes for compliance. In a real system a third outcome, "insufficient data", is preferable, to be brought to a person.
Next in the series: Smart Contracts for Legal Agreements: Solidity and Vyper.
Sources
- Regulation (EU) 2016/679 (GDPR), English text on EUR-Lex - Art. 12(3) (one month, extension of two), Art. 33(1) (72 hours) and Art. 99(2) (application from 25 May 2018), text read on 2026-11-12
- Directive (EU) 2015/849 on EUR-Lex - Art. 11(b): customer due diligence for occasional transactions of an amount equal to or above 15,000 EUR, text read on 2026-11-12 in the base version; the consolidated version in force and the Italian transposition were not verified
- Pydantic: Models - immutable models with
frozenand validation on loading, consulted on 2026-11-12 - PyYAML Documentation -
safe_loadfor reading untrusted YAML files, consulted on 2026-11-12 - Python: hmac module - HMAC signing and comparison with
compare_digest, consulted on 2026-11-12
The rules engine and the audit register were run with Python 3 (Pydantic 2.13 and PyYAML 6.0 for the engine); the outputs shown are the real ones. The Kafka consumer and the machine-learning risk scoring are not shown because they were not run. The three rules are teaching examples and not a compliance checklist: their validation is up to whoever answers for compliance.
Commenti
Caricamento commenti...
Sign in to comment