Record the agent, model version, run and the person it acted for. On PostgreSQL 18.4 a session-level SET leaked an agent identity onto the next pooled request.
The audit column that stopped meaning anything
Most business tables at Belgavi's Book Store carry an updated_by column, and most of the time it is filled by a default such as current_user, or by the application from the logged-in user. When Geetha approved a refund on the help desk, the row said so. Then a refund agent started proposing and applying refunds through the same service, under the service's database role, and updated_by on thousands of rows began to read refund_service. Nothing was wrong with the data. The audit trail simply could no longer answer the two questions it exists for: who decided this, and on whose behalf.
An agent action has more parties than a click. There is the agent component that issued the write, the model and its version that produced the proposal, the run that the step belongs to, and the person or system the agent was acting for. A help desk agent drafting a refund for Geetha's case is acting for Geetha; a nightly reconciliation agent is acting for nobody in particular and should say so. When any of these is missing, the trail cannot separate "the model changed" from "the person asked for something different" from "the job ran twice".
Tracing helps while an incident is fresh. Correlation and causation ids connect hops across services, and they belong in every message. But traces are sampled and expire after days or weeks, and auditors ask months later. Attribution has to live in the records themselves.
What to record
Five attributes cover most cases. They go into audit rows and into the envelope of every event that announces a change.
| Attribute | Example | Why it is separate |
|---|---|---|
actor_type | person, agent or job | Policies and reports differ by kind of actor |
actor_id | refund-agent, geetha | The component or person that issued the change |
on_behalf_of | geetha | Whose request or authority the change used |
run_id | run-7f3a | Groups every step of one agent run |
model_version | model-2026-11-01 | Separates a model change from a prompt or data change |
The database role stays in the audit row too, because it is what the database actually authorised. A service role in db_role next to actor_type = agent and on_behalf_of = geetha is the honest description: the service wrote it, the agent decided it, for Geetha.
Two rules make the attributes trustworthy. The application must set them from its own authenticated context, never from the model's output, because a model can be talked into claiming any identity. And the database should refuse a change that arrives without them, so a forgotten code path fails loudly instead of writing an anonymous row.
Setting the actor per transaction in PostgreSQL
A trigger is the most reliable place to write the audit row, because every path to the table goes through it. The trigger needs the actor, and PostgreSQL's custom settings are the usual way to pass request context into a trigger: the application calls set_config('app.actor_id', ..., true) and the trigger reads current_setting('app.actor_id', true).
The third argument to set_config is the whole story. With true, the setting is local to the current transaction and disappears at commit or rollback, like SET LOCAL. With false, or with a plain SET, it lasts for the session. With a connection pool, a session is shared by whichever requests borrow that connection next.
BEGIN;
SELECT set_config('app.actor_type', 'agent', true),
set_config('app.actor_id', 'refund-agent', true),
set_config('app.on_behalf_of', 'geetha', true),
set_config('app.run_id', 'run-7f3a', true),
set_config('app.model_version', 'model-2026-11-01', true);
UPDATE refunds SET status = 'approved' WHERE id = 1;
COMMIT;The trigger in the companion example reads each setting with nullif(current_setting(name, true), ''), raises an exception when the actor type or id is missing, and raises another when an agent change has no on_behalf_of or run_id. It then inserts the audit row with the old and new status, current_user as the database role, and the five attributes.
What one pooled session did
I ran the companion script on PostgreSQL 18.4 on one connection, statement by statement, the way consecutive requests share a pooled session. The steps and results:
- An agent request sets the five attributes with
set_config(..., true)inside a transaction and approves refund 1. The audit row has all five. - The next request on the same session sets nothing and approves refund 2. The trigger refuses it: "refund 2 changed without an actor". The transaction-local settings ended with the first commit, which is the behaviour you want.
- A careless handler uses plain
SET app.actor_type = 'agent'and the other session-level settings, then approves refund 2. It succeeds. - A different request, which in the scenario is Jenya rejecting refund 3 directly, sets nothing. It also succeeds, and its audit row says
agent,refund-agent, on behalf ofgeetha, runrun-7f3a. Jenya's own decision is now recorded as an agent action for Geetha. - After
RESET ALL, the same unset request is refused again. - An agent request that sets only the type and id is refused: "agent change to refund 3 needs on_behalf_of and run_id".
Step 4 is the dangerous one, and nothing in the logs flags it. The row is complete, plausible and wrong. Pools that run a reset query on check-in, for example DISCARD ALL or RESET ALL, limit the leak to one request, but transaction-mode poolers such as PgBouncer share a server connection across clients between transactions, where a session-level setting leaks to whoever runs next. Transaction-local settings are correct under every pooling mode; session-level ones are correct under none of them.
The example also contains a small standard-library model of the same session, with three requests in a row. With transaction-local settings, the second and third requests are refused for having no actor. With session-level settings, both are accepted and recorded as the agent acting for Geetha. With a reset on check-in, the second is refused again.
Event envelopes
Audit rows answer questions about one table. Events carry the change to other systems, and consumers often store them for longer than the source keeps its audit table. Put the same attributes in the envelope, next to the correlation and causation ids, not inside the business payload where each consumer would have to know the schema:
{
"type": "refund.approved",
"id": "evt-91c2",
"subject": "CASE-2101",
"correlation_id": "corr-55d0",
"causation_id": "cmd-1208",
"actor": {"type": "agent", "id": "refund-agent", "on_behalf_of": "geetha", "run_id": "run-7f3a", "model_version": "model-2026-11-01"},
"data": {"refund_id": 1, "amount": 640.00}
}If the event is written through a transactional outbox, fill the actor from the same transaction-local settings the trigger reads, so the row and the event cannot disagree.
Migration steps
- Add the columns to audit tables as nullable, deploy, then start writing them from every code path. Leave historical rows as they are and mark them as recorded before attribution.
- Move every
SETof request context toset_config(..., true)inside the request's transaction. Search for plainSET app.in application code and in connection initialisation hooks. - Make the trigger raise when the actor is missing, first in a staging environment with real traffic replayed, then in production. The exceptions find the code paths nobody remembered.
- Add the attributes to the event envelope and teach consumers to store them.
- Report by actor type. The first useful report is usually the share of changes made by agents per table and per day, which is also how you notice an agent writing somewhere it was never meant to.
Failure modes and limits
Autocommit writes. A statement outside an explicit transaction is its own transaction, so set_config(..., true) in a separate statement ends before the update runs. Set the context and run the write in one transaction.
Identity from the model. If on_behalf_of comes from a field the model filled, a prompt can change it. Take it from the authenticated request that started the run.
Bulk paths. Batch jobs that bypass the application with COPY or direct SQL also need an actor; give them actor_type = job and a job id rather than exempting them from the trigger.
Performance. A row trigger adds an insert per changed row. For very high-volume tables, logical decoding with the actor written to a side table per transaction is an alternative, at the cost of more moving parts.
When you do not need this. If agents only read, or if they act only by creating proposals that a person approves in a separate transaction, the person's approval is the attributable change and the existing audit trail may be enough. Record the run id on the proposal anyway.
Verification
The companion example runs the SQL on a scratch database when PG_DSN is set, and its standard-library model and tests run without one. The tests check that the good path uses transaction-local settings, that the recording contains exactly two refusals for a missing actor and one for a missing on_behalf_of, and that the leaked row in step 4 carries the agent identity. In your own system, a useful test runs two requests back to back on one pooled connection, the first as an agent and the second as a person, and asserts that the second audit row names the person.