Sub topic 12
Record-keeping and automatic logging in practice
This chapter turns the Act's logging duty into engineering decisions. It assumes you know what a high-risk system is (see the earlier chapters on risk tiers and high-risk requirements). It also assumes you have read the chapters on audit event design and hash-chained logs, and that you can read basic Python.
What the Act asks for
Article 12 of Regulation (EU) 2024/1689 says a high-risk AI system must technically allow automatic recording of events (logs) over the system's lifetime. Two points matter for design.
- The logging must be automatic. A runbook that tells people to write things down does not satisfy it.
- The logs must support three purposes: identifying situations where the system may present a risk or undergo a substantial modification, supporting post-market monitoring, and letting deployers monitor operation.
The Act does not give a schema. For most systems you decide which events are relevant. The exception is remote biometric identification systems, where Article 12 sets a minimum: the period of each use, the reference database checked, the input data that led to a match, and the people who verified the result.
Retention is set in two places. Providers keep the logs under their control, and deployers keep the logs of their systems. Both must keep them for a period appropriate to the intended purpose, and for at least six months unless other EU or national law says otherwise. Data protection law is the main example of such other law. Technical documentation is a separate record, with a ten-year retention rule.
This is engineering guidance, not legal advice. Confirm the retention period for your sector with counsel.
Two kinds of records
Teams often mix up two record types. Keep them apart.
| Record type | Answers | Example events | Typical writer |
|---|---|---|---|
| Governance audit trail | Who changed what about the model? | Training run, approval, promotion, rollback | Pipeline, registry |
| Operational log | What did the system do in use? | Inference, override by a human, input out of range | Serving layer |
The governance trail is covered in earlier chapters. Article 12 mainly concerns the operational log, but regulators and auditors will want to join the two. The join key is the model version. Every operational event must carry the exact version that produced it, so you can trace a decision back to a release record, its approvals and its lineage.
What to put in each operational event
Aim for events that let someone reconstruct a decision without storing more personal data than needed.
- Timestamp in UTC, from a trusted clock.
- Model name and version, plus a reference to the dataset snapshot and code commit if cheap to carry.
- A reference to the input, such as a request ID or a hash, rather than the raw input.
- The output and any confidence value.
- Flags for risk-relevant situations: input outside the training distribution, a low confidence score, a fallback path taken.
- Human involvement: who reviewed the output and whether they accepted or overrode it.
Raw inputs often contain personal data. Storing a hash plus a pointer to a separately governed store lets you apply GDPR deletion without breaking the log.
Implementation: a hash-chained operational log
The code below reuses the chain from the earlier chapter and applies it to inference events. Each event stores the previous event's hash, so editing or deleting an earlier entry makes verify() return False.
import hashlib
import json
from datetime import datetime, timezone
GENESIS = "0" * 64
def _digest(body: dict) -> str:
payload = json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def append_event(log: list, actor: str, action: str, model: str, version: str, details: dict) -> dict:
body = {
"ts": datetime.now(timezone.utc).isoformat(),
"actor": actor,
"action": action,
"model": model,
"version": version,
"details": details,
"prev_hash": log[-1]["hash"] if log else GENESIS,
}
event = {**body, "hash": _digest(body)}
log.append(event)
return event
def verify(log: list) -> bool:
prev = GENESIS
for event in log:
body = {k: v for k, v in event.items() if k != "hash"}
if body["prev_hash"] != prev or _digest(body) != event["hash"]:
return False
prev = event["hash"]
return True
log = []
request = b'{"applicant_id": 1842, "income": 52000}'
append_event(
log,
actor="svc-scoring",
action="inference",
model="credit-scoring",
version="2.4.0",
details={
"input_sha256": hashlib.sha256(request).hexdigest(),
"score": 0.71,
"out_of_distribution": False,
},
)
append_event(
log,
actor="officer-17",
action="human_review",
model="credit-scoring",
version="2.4.0",
details={"decision": "accepted", "override": False},
)
print(verify(log)) # True
log[0]["details"]["score"] = 0.95
print(verify(log)) # FalseThe second event records the human review as its own entry. That gives you evidence for the oversight requirement as well as the logging one.
Limits of the hash chain
A hash chain detects edits, but it has gaps you should plan for.
- Whole-chain rewrite. Someone with write access can edit an entry and recompute every later hash. Defend against this by publishing the latest hash to a separate system on a schedule, such as a write-once bucket or a different team's store.
- Dropped events at the end. Deleting the newest entries leaves a valid chain. The external anchor catches this too, because the anchored head no longer matches.
- Events never written. The chain proves nothing about what was not logged. Write the log from the serving path itself, and alert when the count of logged inferences diverges from the count of requests served.
- Concurrency. The simple list above is single-writer. With several serving replicas, write to a per-replica chain or to a database with a sequence number, then chain within each stream.
Retention in practice
Set retention per log type and write down the reasoning.
- Start from the legal floor of six months for logs under your control.
- Extend it if your sector law requires more. Financial institutions, for example, may fold these logs into records kept under financial services rules.
- Weigh the data protection cost of keeping personal data longer than needed. If the logs hold only references and hashes, longer retention costs less.
- Decide how expiry works with a chain. Deleting old entries from the front breaks verification of what remains. Store a signed checkpoint holding the last deleted hash, and start verification from it.
Also decide who can read the logs. Deployers need access to the logs of their own use. Regulators may request them. Define the export format and the response process before a request arrives.
Common errors
- Logging only the prediction and not the model version, which makes the entry impossible to tie to a release.
- Using local server time, so events from different replicas cannot be ordered.
- Letting the application's own service account delete log storage.
- Treating application debug logs as the Article 12 log. Debug logs rotate, change format and are rarely access controlled.
- Skipping a restore test, so nobody knows whether the retained logs can be read a year later.
Exercise
Your serving layer logs each prediction with a timestamp and the score, then deletes entries after 30 days to save storage. Name two problems with this design against the Act's record-keeping duty and say how to fix each.
Show answer
First, 30 days is below the six-month minimum for logs under your control, so retention must rise to at least six months, or longer if sector law requires. Second, entries carry no model version, so a decision cannot be traced to a release, its approvals or its lineage. Add model name and version, and a reference to the input, to every event. A good answer may also add a hash chain with an external anchor so edits and deletions are detectable.
Exercise
After running the code above, an engineer edits the "score" in the first event and then recomputes the hash of every event after it. Does verify() return True, and what control would still catch the change?
Show answer
verify() returns True, because the chain is internally consistent after the recomputation. An external anchor would catch it. If the latest hash was previously published to a separate write-once system, the recomputed head hash would not match the anchored one.