# Data governance: legal holds, audit retention, tamper evidence and end-user deletion

**Last updated:** 2026-11-25T08:23:14-03:00 (UTC-3)

Three controls decide how long the gateway keeps evidence, and what it erases on request:

- **Legal holds** (flag `legal_holds`) suspend every destructive retention purge while a hold is in force.
- **Audit retention** (flag `audit_retention`) keeps the administrative audit log within a contractual minimum and an optional maximum, and deletes older rows in small, audited batches.
- **Audit tamper evidence** (flag `audit_tamper_evidence`) seals every committed audit row into a hash chain and verifies it on demand.
- **End-user deletion** (flag `end_user_deletion`) erases what is stored for one declared end user of one team, without touching financial records.

All four flags are operator controls, off by default, and require PostgreSQL. They are managed only by the global administrator (`retention:manage`; the audit chain needs `audit:read`). In the console they live on **Settings → Data governance**.

**Nothing is deleted by default.** With `audit_retention` off or `retain_days: 0`, every audit row is kept forever.

## Legal holds

A legal hold is a named, audited switch: while at least one hold is active, the gateway does not run

| Destructive path | While a hold is active |
| --- | --- |
| Audit retention purge (this page) | Skipped; the state shows `last_skip: legal_hold`, and the purge resumes on the first tick after the last hold is released |
| [Metadata retention](/docs/features/metadata-retention/) purge | Skipped; the batch reports `legal_hold` and runs on a later tick once released |
| [End-user deletion](#end-user-deletion) | Refused (`409 legal_hold_active`); open jobs pause (`held`) |

A hold does **not** stop the short, privacy-driven expiries that each record carries from its own policy: captured content ([content capture](/docs/features/content-capture/)), evaluation captures and persisted client addresses ([source IP controls](/docs/security/source-ip-controls/#persisted-client-addresses)) still expire on schedule. If those records matter to a case, export them first or disable their capture.

**Holds are enforced even with the flag off.** Turning `legal_holds` off hides the API and console section, but an active hold keeps blocking the purges. To release a hold, turn the flag back on and release it explicitly.

**Placing a hold is safe against a batch already running.** A purge batch holds a shared lock for at most five seconds; placing a hold takes the same lock exclusively and waits for that batch to commit. Every batch that starts after the hold sees it. No batch deletes after the hold is stored.

Each hold has a reason (1–500 printable characters, required) and an optional reference (up to 128, such as a case or ticket ID). At most 100 holds can be active at once. Releasing requires its own reason. Released holds stay listed as history; nothing about a hold is ever deleted.

### Through the API

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/admin/legal-holds` | Active holds first, then recent releases (200 rows), with the `active` count |
| `POST /api/v1/admin/legal-holds` | `{reason, reference}` → `201` with the hold (`id` is `lh_` + 32 hex) |
| `POST /api/v1/admin/legal-holds/{id}/release` | `{reason}` → `204`; `404` when no active hold has that ID |

```http
POST /api/v1/admin/legal-holds
X-CSRF-Token: <session token>

{"reason": "Litigation hold for case 42", "reference": "CASE-42"}
```

```json
{"id": "lh_3f2a…", "reason": "Litigation hold for case 42", "reference": "CASE-42",
 "placed_by": "user:usr_…", "placed_at": "2026-11-14T04:00:00Z", "released_at": null, "active": true}
```

Audit actions: `legal_hold.place` and `legal_hold.release`, with the hold ID as target and the number of holds still active as the version.

## Audit retention

The audit tables are the identity audit (teams, keys, users, organizations, workloads) and the control audit (configuration, providers, policies, retention itself). Audit retention removes rows older than `retain_days`, measured by the PostgreSQL clock.

```yaml
features:
  audit_retention: true
audit_retention:
  revision: 1          # increase it on every YAML change
  retain_days: 400     # 0 preserves; otherwise minimum_days..maximum_days (or 3650)
  minimum_days: 365    # contractual floor
  maximum_days: 730    # contractual ceiling; 0 = none
  batch_size: 500      # rows per audit table per batch
  interval: 1h         # time between batches
```

| Field | Default | Accepted |
| --- | --- | --- |
| `revision` | `0` | `0`–`2147483647`; a positive `retain_days` in YAML requires a positive revision, raised on every change |
| `retain_days` | `0` (preserve) | `0`, or `minimum_days`..`maximum_days` (`3650` without a ceiling). `0` is refused when `maximum_days` is set |
| `minimum_days` | `365` (also when `0`) | `30`–`3650`. Any shorter `retain_days` is refused |
| `maximum_days` | `0` (no ceiling) | `0`, or `minimum_days`..`3650`. When set, audit rows cannot be preserved forever |
| `batch_size` | `500` (also when `0`) | `1`–`5000` rows per table per batch |
| `interval` | `1h` (also when empty) | Go duration, `1m`–`24h` |

**The contract only tightens.** The console and API may store an override, but it may never loosen the YAML contract: `minimum_days` cannot go below the YAML value, and a YAML `maximum_days` cannot be raised or removed. If a later YAML revision raises the floor or lowers the ceiling past an existing override, the override is dropped (audited as `audit_retention.override_dropped`) and the YAML policy applies.

**How the purge runs.** Every replica runs a worker each minute; PostgreSQL serializes them, so only one batch runs at a time across replicas. A batch:

1. checks the shared flag override (a runtime disable stops it before replicas reload) and the YAML revision (an older replica is fenced, exactly as in metadata retention);
2. waits for the interval since the last batch;
3. stops if a legal hold is active;
4. re-checks the floor and ceiling on the stored policy;
5. deletes at most `batch_size` of the oldest expired rows from each audit table and writes a new `audit_retention.purge` audit row (version = rows deleted) in the same transaction.

A full batch schedules the next one at the next worker tick, so a backlog drains at about `batch_size` rows per table per minute instead of one batch per interval. Statements are bounded to five seconds with a 200 ms lock timeout.

The first batch runs one interval after the policy is set: there is no "delete now". Before turning it on, export what you must keep beyond the period with the [audit CSV export](/docs/features/analytics-export/) (filters by time range).

**In the console:** the **Audit retention** section shows the policy in effect, its source, the contract, the last batch (or "Skipped: legal hold"), the total purged and the newest purged timestamp. **Preview audit purge** counts, without deleting, up to 10,000 eligible rows per table. Saving any positive period asks you to check **I authorize irreversible deletion of administrative audit rows older than the retention period**, unchecked on every edit.

### Through the API

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/admin/audit-retention` | Base, effective policy, source, version, last batch, `active_legal_holds`; the YAML `revision` in force is `audit_retention.revision` |
| `PUT /api/v1/admin/audit-retention` | `{base_fingerprint, version, policy, confirm_delete_expired_audit}` |
| `DELETE /api/v1/admin/audit-retention` | Reverts to the YAML (same confirmation when the YAML has a positive period) |
| `GET /api/v1/admin/audit-retention/preview` | Bounded counts, cutoff, oldest row, `blocked` by a hold |

```http
PUT /api/v1/admin/audit-retention
X-CSRF-Token: <session token>

{"base_fingerprint": "<from GET>", "version": 3,
 "policy": {"retain_days": 400, "minimum_days": 400, "maximum_days": 700, "batch_size": 500, "interval": "1h"},
 "confirm_delete_expired_audit": true}
```

| Status | Code | Meaning |
| --- | --- | --- |
| `204` | | Override stored (`audit_retention.set`) |
| `400` | `retention_contract` | The policy would loosen the YAML floor or ceiling |
| `400` | `invalid_retention` | Out of bounds (for example `retain_days` under `minimum_days`) |
| `400` | `confirmation_required` | Positive period without `confirm_delete_expired_audit` |
| `409` | `version_conflict` | Someone else changed the policy; reload |
| `409` | `retention_base_changed` | Replicas disagree on the YAML revision; publish one higher revision |

## Audit tamper evidence

Flag `audit_tamper_evidence` (operator, off by default, PostgreSQL). It makes the administrative audit log **tamper-evident**: every committed row of the identity and control audit tables is sealed into one SHA-256 hash chain, and a verification recomputes the chain and names the first row that was edited, deleted, inserted out of place or reordered.

How a row is sealed:

```text
row_hash   = SHA-256("aigw.audit.row.v1"   || every stored field, each length-prefixed:
                                              source table, id, occurred_at (microseconds),
                                              action, target_id, actor, request_id, version)
chain_hash = SHA-256("aigw.audit.chain.v1" || previous chain_hash || seq || row_hash)
```

- **Sealing runs after the write**, in the retention worker (about once a minute, up to 1,000 rows per batch and 20 seconds per tick). Audit writers never wait on a global lock; the chain order is the seal order. A row committed but not sealed yet is reported as **unsealed** (pending), never as verified.
- **One sealer at a time** across replicas (advisory lock plus the chain head row), so parallel writers never produce a gap or a duplicate position, and a rolled-back write never takes one.
- **The first seal is the genesis**: turning the flag on seals the existing history first (oldest first), then new rows as they arrive. Turning it off stops sealing; rows written meanwhile are sealed when it is turned on again.
- **Every seal logs the new head** as `audit_chain_sealed` (`head_seq`, `head_hash`), and every purge checkpoint as `audit_chain_checkpoint`. Those log lines, collected outside the database, are your external copy. **The seals carry no secret key**: someone with write access to the database can compute valid seals, so they could rebuild the whole chain, or delete history and append a correctly sealed checkpoint row for a new anchor. Only values kept elsewhere reveal that: check the newest logged head with `--expect <head_seq>:<head_hash>` and the newest logged checkpoint with `--expect-anchor <through_seq>:<chain_hash>` (a forged anchor never appears in your logs). Keep these log lines for at least as long as the audit retention period.
- **A row forged before it is sealed is sealed as genuine**: nothing ties `occurred_at` to the time of sealing. The chain proves that sealed rows were not changed afterwards, not that every row was written by the gateway.

### Retention and checkpoints

Audit retention removes sealed rows only as a **prefix of the chain**: in each batch it takes the oldest sealed positions after the current anchor, stops at the first row newer than the cutoff, **verifies** that prefix (and the first row it keeps), deletes it and records a `purge` checkpoint (`through_seq`, `chain_hash`, `purged`) that becomes the new anchor. The same batch appends the checkpoint to the chain as a sealed `audit_chain.checkpoint` control audit row (target `<through_seq>:<chain_hash>`), so the remaining chain itself attests its anchor: moving the anchor or re-inserting history below it with plain SQL is reported as `anchor_unattested` or `below_anchor`; a forger who also seals a checkpoint row is caught by `--expect-anchor`. The batch logs it as `audit_chain_checkpoint` with the new head. Sealed rows count against `batch_size`: no table loses more than `batch_size` rows in one batch.

- A prefix that does not verify is **never purged**: the batch reports `chain_broken` (shown on the audit retention card and logged once as `audit_retention_chain_broken`) and keeps the rows that prove the tampering. The whole audit purge stops, so rows may outlive `maximum_days` until it is resolved. To resolve it, run a verification, investigate the reported position and restore that row from a backup; the purge resumes on the next tick once the chain verifies. There is deliberately no command that re-anchors a broken chain.
- An old row sealed after a younger one (a late commit) waits until the younger one expires too, so it can outlive the cutoff by the gap between them.
- Rows that were never sealed keep the previous purge behavior (oldest first).
- Once a chain exists, purges keep it consistent even with `audit_tamper_evidence` off.

### Verifying

In the console, **Settings → Data governance → Audit tamper evidence** shows the stored result of the last verification (*Verified*, *Tampering detected* with the position and kind, or *Not verified yet*), the sealed and unsealed counts, the anchor and the head hash. **Verify now** runs a full verification.

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/admin/audit-chain` | Head (`head_seq`, `head_hash`), anchor, `unsealed`, last verification and the 20 newest checkpoints. Reads never seal or verify |
| `POST /api/v1/admin/audit-chain/verify` | Recomputes every seal after the anchor in one snapshot (60 s budget), stores the result and writes `audit_chain.verify` or `audit_chain.tampered`. Optional body `{"expect": {"seq": 42, "hash": "<64 hex>"}}` also checks a pair kept outside the database; the report then carries `expected.result`: `match`, `mismatch` or `purged` (below the anchor, no longer checkable). `{"expect_anchor": {"seq": 120, "hash": "<64 hex>"}}` requires the current anchor to equal a logged checkpoint (`expected_anchor.result`). A failure that only concerns these caller-supplied values is audited as `audit_chain.expect_mismatch` and does not change the stored indicator |

Both need a global administrator with `audit:read`; the verification is a write and needs the CSRF token. A tampered chain is a `200` with `status: "tampered"`:

```json
{"status": "tampered", "verified_rows": 6, "head_seq": 42, "head_hash": "ab12…",
 "anchor_seq": 0, "anchor_hash": "0000…", "unsealed": 3,
 "failure": {"kind": "altered", "seq": 7, "source": "control", "row_id": 19,
             "detail": "the row content or its position no longer matches its seal"},
 "verified_at": "2026-11-14T08:05:00Z"}
```

| `failure.kind` | Meaning |
| --- | --- |
| `altered` | The row at `seq` no longer matches its seal: edited content or timestamp, a forged seal, swapped or renumbered positions |
| `missing` | No row at `seq`: deleted, also at the end of the chain |
| `duplicate` | Two rows carry the same position |
| `beyond_head` | A sealed row is newer than the recorded head |
| `head_mismatch` | The recorded head differs from the recomputed chain |
| `head_missing` | Sealed rows exist but the chain head is gone |
| `anchor_mismatch` | The anchor differs from the newest recorded checkpoint |
| `anchor_unattested` | No sealed `audit_chain.checkpoint` row names the current anchor: history below it was removed outside a purge |
| `below_anchor` | A sealed row sits at or below the anchor, where every row was purged |
| `expected_mismatch` | The externally kept hash differs from the chain at that position |
| `expected_beyond_head` | The externally kept position is newer than the head: the chain was truncated or rebuilt (also when you verify a backup taken before that pair was logged) |
| `anchor_unexpected` | The current anchor is not the checkpoint passed in `expect_anchor` / `--expect-anchor` |

For a chain too long for the 60-second request, or against a replica or a restored backup, run the read-only command with the same configuration and database URL as the server:

```sh
gateway audit-verify
gateway audit-verify --expect 1842:9f2c…e1 --expect-anchor 1200:4b7a…09   # pairs from your logs
```

It prints the same report as one JSON line and never migrates, seals or records anything. It works whatever the flag says, without the pool's statement timeout (one hour at most). Exit status: `0` verified (or nothing sealed yet), `3` tampered or the expected pair does not match, `1` could not verify (for example a schema behind the binary), `2` usage.

## End-user deletion

Flag `end_user_deletion` (operator, off by default, PostgreSQL). It erases what the gateway stored for one **declared end user of one team**: the value a client sent in `X-Gateway-End-User` or the OpenAI `user` field, recorded with [`end_user_tracking`](/docs/features/observability/). The value is untrusted client metadata, so the gateway cannot prove who the person is: the administrator who runs the deletion is responsible for matching the request to the right team and value.

**Scope is exact.** The team is the exact team ID and the end user is the exact recorded value (case-sensitive, 1–128 printable characters). The same value in another team is a different person and is never touched.

| Stored data | Outcome |
| --- | --- |
| Request-log rows (usage events) of the team with that end user | **Attribution cleared** (`end_user` set to empty); tokens, status, timings, cost proof and fingerprints stay, so totals, analytics, budgets and invoices do not change |
| Finalized durable receipts | **Attribution cleared**, once finalized for 15 minutes (a retried finalization still has to match). Receipts never finalized wait, and the job shows `waiting_receipts`, until they are finalized or abandoned: no lease or update for 24 hours |
| Captured prompts and answers ([content capture](/docs/features/content-capture/)) of those requests | **Deleted** |
| Evaluation captures of those requests | **Deleted** |
| The task text of [agent runs](/docs/features/agent-recognition/#task-capture) whose first request is one of those requests | **Deleted**; the run, its counters and the keyed hash of the task stay |
| Evaluation scores and review comments attached to those requests (judge rationales and notes can quote content) | **Deleted**. A live evaluation already running for one of those requests can still write its score after the final sweep; evaluation queue items and jobs keep only the request ID |
| Persisted client addresses ([source IP controls](/docs/security/source-ip-controls/#persisted-client-addresses)) of those requests | **Deleted** |
| Budget counters, reservations, the ledger archive and budget alerts keyed `team/end user` (`end_user_budgets`) | **Kept**: they are financial evidence and follow their own windows and [ledger archiving](/docs/features/quota-finance/#archiving-the-ledger). The dry run counts the counters and alerts |
| Valuations, rollups, audit | Unchanged (they never held the value) |

A request ID can be sent by the client and reused. A capture is only deleted when no **other** declared end user of the same team used the same request ID.

**What the deletion cannot reach:** copies outside the gateway database (structured logs or OTLP exports you collect, request-event destinations, backups) and short-lived rate-limit windows. Usage fingerprints are SHA-256 hashes over the whole original event, kept as financial proof; they do not contain the value in readable form.

### How it runs

1. **Dry run** (`dry_run: true`): counts what would change, and whether a legal hold blocks it. Nothing is written.
2. **Request** (`confirm: true`): creates a durable job with the database time as its cutoff (later requests are out of scope) and audits `end_user.delete.request`. Repeating the request while the job is open returns the same job; after it completes, a new request creates a new job that finds nothing.
3. **Batches**: each batch is one transaction over at most 500 request-log rows (and their captures, annotations and addresses) plus 500 receipts. A failing batch rolls back completely and is retried; the job shows that the last batch failed. The request runs batches inline for up to 5 seconds, and every replica's worker resumes open jobs each minute — also if the flag is later turned off, because an accepted erasure is finished.
4. **Settling**: a request already running at the cutoff writes its usage row when it ends. Once everything found is erased, the job shows `settling` and sweeps once more after the longest request the configuration allows: the longest stream `max_duration` (network default or any model override) or Realtime `max_session`, plus one minute, and never less than 15 minutes (with the defaults, 31 minutes after the cutoff). With `durable_usage` on, a request in flight also holds the job in `waiting_receipts` until its receipt is finalized.
5. **Completion**: the job clears the stored end-user value (and its digest), records the counts and audits `end_user.delete.complete` with the total. Audit rows name the job ID, never the value. The dry run is audited too (`end_user.delete.dry_run`, with the team and the matching count only).

An active [legal hold](#legal-holds) refuses new requests (`409 legal_hold_active`) and pauses open jobs (`held`) until it is released.

**In the console:** **Settings → Data governance → End-user deletion** asks for the team ID and the end user, shows the dry-run counts and requires checking **I authorize irreversible erasure of this end user's stored data** before **Delete end-user data**. The job list shows state and counts, never the value.

### Through the API

| Endpoint | What it does |
| --- | --- |
| `POST /api/v1/admin/end-user-deletions` | `{team, end_user, dry_run}` or `{team, end_user, confirm: true}` |
| `GET /api/v1/admin/end-user-deletions` | The 100 most recent jobs |
| `GET /api/v1/admin/end-user-deletions/{id}` | One job |

```http
POST /api/v1/admin/end-user-deletions
X-CSRF-Token: <session token>

{"team": "support", "end_user": "customer-8841", "dry_run": true}
```

```json
{"dry_run": true, "team": "support", "blocked_by_legal_hold": false,
 "counts": {"usage_events": 42, "durable_receipts": 42, "content_captures": 5,
            "eval_captures": 0, "eval_annotations": 0, "client_sources": 12,
            "retained_quota_counters": 2, "retained_budget_alerts": 1}}
```

```http
POST /api/v1/admin/end-user-deletions

{"team": "support", "end_user": "customer-8841", "confirm": true}
```

```json
{"id": "eud_9c1f…", "team": "support", "state": "settling", "requested_by": "user:usr_…",
 "cutoff": "2026-11-14T04:10:00Z", "completed_at": null,
 "counts": {"usage_events": 42, "durable_receipts": 42, "content_captures": 5, "eval_captures": 0,
            "eval_annotations": 0, "client_sources": 12, "retained_quota_counters": 0, "retained_budget_alerts": 0},
 "deferred_receipts": 0, "attempts": 2}
```

| Status | Code | Meaning |
| --- | --- | --- |
| `201` | | New job (`200` returns the job already open for the same team and end user) |
| `400` | `invalid_team`, `invalid_end_user` | Not an exact team ID or recorded value |
| `400` | `confirmation_required` | Neither `dry_run` nor `confirm: true` |
| `409` | `legal_hold_active` | A legal hold is in force |

## Provider error redaction

The page also shows, read-only, which JSON key names have their string values redacted before a provider's error answer reaches a client: `security.provider_errors.credential_field_names`, the effective list after normalization (lowercase letters and digits), and whether it is the default or set in the YAML. An empty list reads as off. Changing it takes a restart. What the redaction does and does not cover is in [Security](/docs/security/security/) ("Provider errors never relay a credential-named field or a URL signature").

```yaml
security:
  provider_errors:
    credential_field_names: [password, secret, apikey, connectionstring, x_vendor_token]
```

## What is never removed

- The money path: usage events, receipts, valuations and the budgets ledger are outside audit retention ([metadata retention](/docs/features/metadata-retention/) and [financial reconciliation](/docs/features/quota-finance/) own them).
- Legal holds themselves and their history.
- Audit rows newer than the cutoff, including the purge's own `audit_retention.purge` row.

## Upgrade

Migration 132 adds `gateway_audit_retention`, `gateway_legal_holds` and an age index on each audit table; migration 133 adds `gateway_end_user_deletions` and an end-user index on durable receipts; migration 144 adds the `chain_seq`/`chain_hash` columns and their indexes to both audit tables, `gateway_audit_chain` and `gateway_audit_chain_checkpoints` (the new columns are nullable and their check is added `NOT VALID`, so existing rows are not rewritten or scanned for it; the four indexes are built in the migration transaction, which blocks writes to the audit tables, and so every audited change, while they build: plan the upgrade for a large audit log). Run them with this release and upgrade every replica before turning any of the flags on: an older replica does not know about holds and would keep running metadata retention while a hold is active, and it does not resume end-user deletion jobs. An older replica also purges audit rows without verifying or checkpointing the chain, which a later verification reports as `missing`: upgrade every replica before turning `audit_tamper_evidence` on.

## Limits

- Tamper evidence detects changes; it does not prevent them. The seals are not keyed (no secret outside the database), so a writer with database access who recomputes seals is caught only against the logged head and checkpoint pairs (`--expect`, `--expect-anchor`). Rows are covered once sealed, about a minute after they are written.
- The chain covers the two administrative audit tables only, not usage events, receipts or request logs.
- Backups are outside the gateway: a hold does not reach copies you keep elsewhere, and purged rows survive in backups until those expire.

## Admin API routes

Every route below needs a console session or an admin Bearer token, the role's permission and, for writes, the `X-CSRF-Token` header; the full contract is in the [API reference](/docs/api/).

| Route | What it does |
| --- | --- |
| `GET /api/v1/admin/audit/export` | Exports up to 10,000 administrative changes as CSV, with the same filters as the audit explorer |
| `GET /api/v1/admin/end-user-deletions/{id}` | The state and counts of one end-user deletion job |
| `PUT /api/v1/admin/audit-retention` | Stores a console override of the audit retention that may only tighten the YAML bounds |
