Sub topic 10
Keeping an audit trail
This chapter assumes you have read the earlier chapters on content states and approval gates. It also assumes you can read simple Python, including dataclasses and hashlib. The log list in the state-machine example is the starting point here. That list records what happened, but a real audit trail has to be harder to change and easier to question.
What an audit trail is for
An audit trail is a record of who did what to a content item, when, and to which version of the text. It answers questions that come up after the fact:
- Who approved the paragraph that contains the wrong price?
- Did the approver see the same text that went live?
- Which model and which brief produced the first draft?
- Why was the draft sent back twice?
Without a trail, the approval gate is a claim and not evidence. You can say a person approved the item, but you cannot show it. The trail is also how you debug the process. Metrics such as turnaround time, which a later chapter covers, are computed from it.
What to record
Record every event that changes the item's state, text, or responsibility. Each entry needs enough detail to be read on its own.
| Event | Actor | Details worth keeping |
|---|---|---|
| Draft created | The model, plus the person who ran it | Model name and version, brief ID, prompt digest, text digest |
| Edit | The editor | Digest of the new text, short change note |
| Submitted for review | Author or editor | Text digest at submission |
| Changes requested | Reviewer | The note, text digest reviewed |
| Approved | Reviewer | Text digest approved, rubric version |
| Published | Person or system | Text digest published, destination |
Store a digest (a SHA-256 hash) of the text in each entry. Do this instead of copying the full text into every entry, or as well as keeping the full versions elsewhere. The digest lets you prove that the approved text and the published text are identical. It also shows which of several stored versions a reviewer actually saw.
Provenance for AI-generated text
Provenance is the origin story of a piece of content. For AI drafts it needs more than "created by the model". Keep these facts with the first entry:
- The model name and version, because behavior changes between versions.
- The brief ID and the exact brief text, or a digest of it that points to a stored copy.
- The source material the model was given.
- The settings that affect output, such as temperature, if you control them.
- The person or service that triggered the generation.
You will not be able to reproduce a model's output exactly, so do not rely on re-running the prompt. Store the output you actually received. Provenance records what produced the text. It does not let you regenerate it.
Keep human edits in the same trail. Later, you may need to say which sentences came from the model and which a person wrote or changed. Storing each version's full text, keyed by digest, makes that possible.
Make the log append-only
The trail is only useful if people trust it. Two rules give you most of that trust:
- Entries are only added. Nothing edits or deletes an old entry. A correction is a new entry that refers to the old one.
- The log is stored where the people being audited cannot change it. If the author can edit the log, it does not prove anything about the author.
The second rule is a storage and permissions decision. A database table with insert-only permissions for the application, or a write-once storage bucket, enforces it. Application code cannot enforce it by itself.
You can add a cheap safeguard in code: hash chaining. Each entry stores the hash of the entry before it. If anyone changes or removes an old entry, the chain breaks at that point and a check can find it. This makes tampering detectable. It does not prevent tampering.
import hashlib
import json
from datetime import datetime, timezone
GENESIS = "0" * 64
def digest(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
class AuditLog:
def __init__(self):
self.entries = []
def record(self, item_id, actor, action, **details):
previous = self.entries[-1]["entry_hash"] if self.entries else GENESIS
entry = {
"seq": len(self.entries),
"at": datetime.now(timezone.utc).isoformat(),
"item_id": item_id,
"actor": actor,
"action": action,
"details": details,
"previous_hash": previous,
}
entry["entry_hash"] = digest(json.dumps(entry, sort_keys=True))
self.entries.append(entry)
return entry
def verify(self):
"""Return the index of the first bad entry, or None if the chain is intact."""
previous = GENESIS
for i, entry in enumerate(self.entries):
body = {k: v for k, v in entry.items() if k != "entry_hash"}
if body["previous_hash"] != previous:
return i
if digest(json.dumps(body, sort_keys=True)) != entry["entry_hash"]:
return i
previous = entry["entry_hash"]
return None
v1 = "Our spring plan starts on 1 March."
log = AuditLog()
log.record("post-17", "model-x", "draft_created", brief_id="brief-4", text_digest=digest(v1))
log.record("post-17", "ben", "submitted", text_digest=digest(v1))
log.record("post-17", "ana", "approved", text_digest=digest(v1))
print(log.verify())
log.entries[1]["actor"] = "carla"
print(log.verify())The first verify() call prints None, which means the chain is intact. After the change to entry 1, the second call prints 1, the index of the entry that no longer matches its hash.
The chain protects against edits made without the right tools. Someone with write access to the whole log could rebuild every hash after the change. For stronger protection, copy the latest entry_hash to a separate system on a schedule. A rebuilt chain would then no longer match the copy.
Link the trail to the state machine
The Item class from the state-machine example already logs transitions inside the object. In production, send those entries to a separate log service instead. Two points matter when you connect them:
- Write the audit entry in the same step as the state change. If the state changes and the entry fails to save, the item has an unrecorded transition. The safer order is to reject the transition if the entry cannot be written.
- Log refusals as well as successes. A blocked self-approval or a failed publish because of a hash mismatch is useful evidence. A run of refused attempts by one person is worth a look.
Query the trail
A log nobody can search is not much use. Keep a few standard queries ready:
def history(log, item_id):
return [e for e in log.entries if e["item_id"] == item_id]
def approvals_of(log, item_id, text_digest):
return [
e["actor"]
for e in history(log, item_id)
if e["action"] == "approved" and e["details"].get("text_digest") == text_digest
]
print(approvals_of(log, "post-17", digest(v1)))This prints ['ana']. The second function is the one that matters in a dispute. It lists who approved this exact text, which is a stronger claim than who approved this item at some point. Pair it with the publish check: before publishing, confirm that the text being released has an approval entry for its digest from someone other than the author.
What not to log
An audit trail can become a privacy problem of its own. Decide what goes in before you build it.
- Do not put secrets, such as API keys or credentials, in prompts or details fields. Logs are widely readable.
- Be careful with personal data in source material. Store a reference to the document, not a copy, when the document contains personal data.
- Record reviewer identity as a stable user ID, not a free-text name. Names change and can collide.
- Use one clock source and store UTC timestamps. Entries from different servers with drifting clocks produce confusing orderings, so the
seqnumber is the real order.
Set a retention period that fits your content's risk. High-risk content, such as legal or health claims, may need records for years. Low-risk content may need only months. Write the rule down and apply it automatically.
Common mistakes
- Logging the item but not the version. "Approved" with no digest does not say what was approved.
- Letting the author write the log. If the same account that edits can also edit the log, the trail proves nothing about that account.
- Recording only successes. Rejections and failed publishes show where the process is under strain.
- Treating the log as a backup. Keep the full text of every version in its own store. The log holds digests and references.
- Never checking it. A chain that nobody verifies gives false comfort. Run
verify()on a schedule and alert on failure.
Summary of the design
An audit trail for an AI-draft workflow does five things. It records every state change with the actor and a digest of the text. It stores provenance for the AI draft, including model, brief, and sources. It is append-only and stored beyond the reach of the people it audits. It makes tampering detectable with hash chaining or an external copy of the latest hash. It supports the queries you will need during a dispute, above all who approved this exact text.
Exercise
A reviewer approves post-17, then the author fixes a typo, and the item is published. The audit log has an "approved" entry and a "published" entry. Which two pieces of information in those entries let you detect that the published text is not the approved text, and what would you do in the publish step to prevent it?
Show answer
The "approved" entry's text digest and the "published" entry's text digest. If they differ, the text changed after approval. In the publish step, compute the digest of the text about to be released and compare it with the digest in an approval entry from someone other than the author. Refuse to publish, and log the refusal, if they do not match. The typo fix then goes back through review.
Exercise
Your hash-chained log passes verify(), but an administrator with full database access could have changed an entry and recomputed every later hash. Name one way to make that change detectable.
Show answer
Periodically copy the most recent entry_hash to a separate system that the administrator cannot write to, such as a write-once storage bucket or a different team's service. A rebuilt chain would produce a different final hash and would no longer match the stored copy.