← Writing

Post

How to build an audit trail for AI agent tool calls that survives an auditor

Most agent audit logs are a table someone can UPDATE. That records what the system believed at write time.

25 September 2026 Anatolii Maltsev 8 min read Agent runtime & security audit compliance

Most agent audit logs are a table someone can UPDATE. That records what the system believed at write time. A record of what happened is a different artifact, and an auditor who works this out once will not take the second one seriously.

Writing rows is the easy part. Making rows that survive a compromised application and a compromised operator is the hard part.

One row carries one event

The single most common mistake is one table that mixes what was requested, what was allowed, what was spent, and who approved it. Every writer then updates the row in place to reflect the latest state, and the previous state is gone.

The enforcement layer splits the audit surface into four tables that never overwrite each other:

TableAnswers
audit_eventsWhat decision was taken, and why
execution_recordsWhat was actually run
cost_eventsWhat it cost
approvalsWho said yes

The decisions are append-only and a correction is a new row, which is the difference between a ledger and a mutable document. It is why the hash chain below is even possible.

The execution ID must be minted by the server

Here is an attack that a self-reported ID makes trivial:

# The bug.
gate.check(execution_id=client_supplied_id, ...)

A client that chooses its own execution ID controls the namespace it writes into. It can reuse one ID across two unrelated calls so they collapse into a single row, or collide with another org’s ID so their events attribute to the wrong party, or replay a known-approved action under a fresh payload.

The fix is structural: the server mints the ID, binds it to the identity that asked, and re-compares that binding at settlement.

  1. Server generates a UUIDv7, time-ordered, so the ID itself carries a rough chronology and concurrent mints stay monotonic.
  2. The server binds org_id + api_key_id to that ID, in the same atomic operation as the reservation.
  3. At settlement, the org and key are re-read and compared atomically. A mismatch rejects the settlement.

Step 3 is the one that gets skipped. Binding on the way in and not re-checking on the way out means an approved action can be replayed with a different payload and nobody notices, because the binding check already passed once.

Refusals are evidence too

The instinct on a 402 budget rejection is to skip the write. Nothing was spent, so there is nothing to record.

That loses the most useful signal in the system. A budget rejection is the enforcement working. It is the event an operator needs when asking “why did my agent stop making calls at 14:00”, and the event a compliance reviewer needs when asking whether a control actually fired.

So refusals are recorded on the same path as approvals. The rule is “record what the gate decided, and the gate decides on every call”.

Recording does not mean universal coverage. If your plan tiers deliberately exclude audit logging, those calls produce no row at all, and any claim you make about total coverage is false by construction. Know which tiers are entitled before you answer that question.

Tampering has to be detectable

Blocking UPDATE and DELETE is table grants, and table grants are one ALTER TABLE away from gone. The durable defense is a hash chain: each row commits to the hash of the row before it, so modifying any historical row breaks every hash after it.

hash(n) = H(hash(n-1) || canonical_json(row n))

The property this buys: an attacker who edits row 40 has to recompute row 40’s hash and every hash after it, and the recomputation has to land before anyone reads the chain.

Two details decide whether this is real:

  • Canonicalization must be total. The hash is computed over a canonical JSON serialization, not over the storage row. If it hashes the raw row and Postgres normalizes anything on write, the verifier disagrees with the writer and the chain reports false tampering.
  • The verifier must be exercised against known-bad input. A chain check that has only ever seen a clean database will pass on a broken one. Test it with a deliberately tampered row, or you are testing that the code runs.

The two mechanisms cover different attackers, and only one of them is load-bearing:

MechanismDefends againstFails when
Table grants blocking UPDATE and DELETEAn ordinary application bug writing to the wrong tableOne ALTER TABLE from an operator or a compromised superuser
Hash chain over canonical JSONAn edit to a historical row, whoever made itThe verifier has only ever run against a clean database

Verify the write path

The outbox pattern keeps the audit trail from becoming the weakest link:

gate decision → outbox row (transactional)
              → dispatcher drains
              → audit_events + hash chain
  gate decision
       │
       ▼
  ┌───────────────────────────────┐
  │ INSERT outbox                 │
  │ COMMIT                        │
  │ one transaction               │
  └───────────────────────────────┘
       │
       ▼
  ┌───────────────────────────────┐
  │ dispatcher                    │
  │ drain                         │
  │ async, retryable              │
  └───────────────────────────────┘
       │
       ▼
  ┌───────────────────────────────┐
  │ audit_events                  │
  │ + hash chain                  │
  └───────────────────────────────┘

The write and the enqueue happen in one transaction, so a decision can never be made without a queued record, and a record can never be queued without a decision. The drain is then free to be slow, retryable and asynchronous.

This matters most where it looks least important: when Postgres is unavailable at /track. The inference already happened and the cost is already incurred, so failing the response teaches the caller nothing and blocks a write that is already too late to prevent. Return 200, keep the outbox row, retry. The alternative turns a database blip into a client-visible error and loses the audit row in the process.

What to actually check

An audit trail you have never verified is a claim, not a control. Worth testing on a schedule:

CheckA real passA vacuous pass
Does a rejection produce a row?A 402 leaves a row you can query by execution_idOnly approvals produce rows, and the run was all-allow
Does the chain verify after a deliberate mutation?The mutated copy reports the break, at the mutated rowThe check ran against a clean copy
Does a cross-org write attempt leave anything readable behind?The write is refused and a follow-up read returns nothingThe attempt used an org the reader already had access to
Does an outbox row survive a dispatcher restart?The row drains after the restartThe dispatcher was never stopped

Each check pairs a real failure against the version that would pass without proving anything.

What to do, and what not to

What not to

Do not keep one mutable row per action. A table that holds a whole action in one place has a single writer, and that writer owns the history: the state before it is gone the moment the next writer lands, and there is nothing left to correct afterwards. A row updated in place cannot answer what was allowed at the moment of the incident, because the answer it gives is the answer of the last writer, not the answer of the moment. The loss shows up where the record matters most. A 402 refusal is the entry you want when the agent goes quiet at 14:00, and a table of approvals alone has no row for it at all. Table grants that block UPDATE and DELETE do not close the gap either: that defense is one schema change away from being revoked.

What to do

Give each kind of record its own table, four of them, and let a correction be a new row rather than an edit. Tie them together with an execution ID the server mints and binds to the organization and the key atomically with the write, then check that binding again when the action settles, because a binding checked once at entry can be replayed later, under a different payload. Chain each row onto the hash of its predecessor over a canonical serialization, and commit the decision and the enqueue together, so neither can exist without the other. The price is four tables to keep, one dispatcher to run, one transaction on the decision path, and a chain verifier that has to be pointed at a deliberately tampered copy or it proves nothing. What it buys is an audit trail with no path back: every change lands as a new row, and a change to an older row invalidates every hash that follows it.

FAQ

Do we need to log the prompts themselves?

No, and logging them is usually the wrong default. What a reviewer needs is the decision context: which tool, which policy, which outcome, which execution. The prompt body is the expensive and sensitive part, and a hash or a length is usually sufficient to prove a given call is the one under discussion.

How long should audit records be retained?

Longer than the operational log, and set by policy. Disk pressure is a poor reason to shorten it. Records that get deleted on a rotation schedule are records that were not retained; decide the window deliberately and write it down.

Can we run our own audit store instead?

Yes, and that is a common and reasonable choice. The property to insist on is append-only plus tamper detection. Where the rows live matters much less than whether the trail can be rewritten after the fact.

Neighbors in time

when name

Related: the posts that share this one's subject, and where the thread goes next.