Sub topic 2
Designing audit trails for ML systems
This chapter assumes you know the basic ML lifecycle (train, evaluate, deploy, monitor), can read Python, and have used Git and CI/CD. It also assumes you know what a model registry does. You will learn what an audit event for an ML system should contain, which actions to record, and the mistakes that make a trail useless when someone needs it.
What an audit trail is for
An audit trail is an append-only record of who did what, to which asset, when, and with what result. It answers questions after the fact:
- Who promoted model version 2.4.0 to production?
- Which dataset snapshot was it trained on?
- Who approved the release, and did they approve before or after the evaluation report was produced?
- Who changed the decision threshold last month?
An application log is different. Application logs help engineers debug, and they can be rotated, sampled, or rewritten. An audit trail is evidence, so it must be complete for the actions it covers, hard to alter, and kept for a defined period.
ML needs more than ordinary change control because behavior depends on data and training runs, not only code. A Git history shows the code changed. It does not show that someone swapped the training snapshot, retrained with a new random seed, or lowered an approval threshold in a config store.
Choosing what to record
Start from decisions that change what the system does or who is responsible for it. Record these action categories:
- Data actions: dataset snapshot created, labeled, filtered, or deleted.
- Training actions: run started, run completed, hyperparameters or seed changed.
- Evaluation actions: evaluation report produced or waived.
- Registry actions: version registered, stage changed, version archived.
- Approval actions: approval requested, granted, rejected, or revoked.
- Configuration actions: thresholds, feature flags, or routing rules changed.
- Access actions: someone read sensitive artifacts or exported a model.
Do not try to log every prediction in this trail. Per-inference logging is a separate concern with its own volume and privacy trade-offs. A later chapter covers it under record-keeping.
Anatomy of an audit event
Each event is a small, flat, structured record. Every field answers one question.
| Field | Question it answers | Notes |
|---|---|---|
| `event_id` | Which event is this? | Unique, for example a UUID. |
| `ts` | When did it happen? | UTC, ISO 8601, set by the logging service. |
| `actor` | Who did it? | A person or service identity, never a shared account. |
| `actor_type` | Human or automated? | Pipelines act on behalf of someone. |
| `action` | What was done? | Value from a fixed vocabulary. |
| `model`, `version` | Which asset? | Use the registry's identifiers. |
| `lineage` | Built from what? | References to data snapshot, code commit, and run. |
| `outcome` | Did it succeed? | Record failures and denials too. |
| `details` | Anything else? | Small JSON object, no raw personal data. |
Three design choices matter most.
Use a fixed action vocabulary. If one team writes promote and another writes moved_to_prod, you cannot query reliably. Define the allowed values in code and reject others.
Store references, not copies. The event holds a dataset snapshot ID and a commit SHA. It does not hold the data. The referenced artifacts must be immutable, otherwise the reference proves nothing. The next chapter covers lineage.
Log denials. A rejected promotion attempt is often the most interesting event in the trail.
A minimal event writer
The following code defines the event, validates it, and appends it as one JSON line. It runs as shown.
import json
import uuid
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
ALLOWED_ACTIONS = {
"dataset.snapshot_created",
"training.run_completed",
"evaluation.report_produced",
"registry.version_registered",
"registry.stage_changed",
"approval.granted",
"approval.rejected",
"config.changed",
}
ALLOWED_OUTCOMES = {"success", "failure", "denied"}
@dataclass
class AuditEvent:
actor: str
actor_type: str # "human" or "service"
action: str
model: str
version: str
outcome: str = "success"
lineage: dict = field(default_factory=dict)
details: dict = field(default_factory=dict)
event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
ts: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
def __post_init__(self):
if self.action not in ALLOWED_ACTIONS:
raise ValueError(f"unknown action: {self.action}")
if self.outcome not in ALLOWED_OUTCOMES:
raise ValueError(f"unknown outcome: {self.outcome}")
if self.actor_type not in {"human", "service"}:
raise ValueError(f"unknown actor_type: {self.actor_type}")
def write_event(path: str, event: AuditEvent) -> None:
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(asdict(event), sort_keys=True) + "\n")
if __name__ == "__main__":
write_event("audit.jsonl", AuditEvent(
actor="ci-pipeline",
actor_type="service",
action="registry.stage_changed",
model="credit-scoring",
version="2.4.0",
lineage={"dataset": "dataset-snapshot-2026-03-01", "code_commit": "9f2c1ab"},
details={"from": "staging", "to": "production", "requested_by": "carol"},
))
print(open("audit.jsonl", encoding="utf-8").read())Notice that the pipeline is the actor, but requested_by names the person who asked for the change. Without that, every automated action looks like it was done by one service account, and you lose accountability.
Where events come from
The trail is only trustworthy if events are emitted by the system that performs the action, not by the person who performed it. A developer who writes their own audit line can forget it or edit it.
Emit events from the registry, the approval service, and the pipeline runner. These components should write to the store through a service identity that normal users cannot use for edits or deletes.
Common errors
- Clock problems. Let the writer set the timestamp in UTC. Client-supplied times drift and can be forged.
- Shared accounts. An
adminactor tells you nothing. Require individual identities, and map service accounts to an owner. - Logging secrets or personal data. Audit events are retained for years and read by many people. Put identifiers in
details, not feature values, credentials, or customer records. - Mutable references. A tag like
latestor a dataset path that gets overwritten breaks lineage. Use content hashes, commit SHAs, or snapshot IDs. - Missing failures. If only successes are logged, an attacker or careless user leaves no trace of attempts.
- Editable storage. A plain database table that an administrator can update is not an audit trail. Use append-only storage and, as the tamper-evidence chapter shows, chain the entries by hash.
Testing the design
Check the trail with a few concrete questions before you rely on it. Pick one production model and try to answer, using only the audit store: who approved the current version, what data it was trained on, and when it entered production. If any answer needs a Slack search or someone's memory, you have a gap. Then try to perform an action, such as a stage change, in a test environment and confirm an event appears even when the action is denied.
Exercise
A teammate proposes logging promotions as free text, such as "Bob moved the model to prod", written by the engineer's own script after the promotion. Name two problems with this and one fix for each.
Show answer
First, free text cannot be queried reliably, so use a fixed action vocabulary and structured fields (actor, action, model, version, outcome). Second, an event written by the engineer's own script can be forgotten, altered, or forged, so have the registry or approval service emit the event as part of performing the promotion, writing through a service identity that users cannot edit.