# Audit

Every statement sent to Db2 produces an event, whether it succeeds or fails. Events go to the **sinks** declared in `audit.sinks`.

## Event content

| Field                     | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Use for optimization                                                       |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------- |
| `id`, `at`                | Number of the event within the process, start of the execution (ISO 8601)                                                                                                                                                                                                                                                                                                                                                                                             |                                                                            |
| `kind`                    | `select`, `dml`, `call` or `other`, from the first word of the statement                                                                                                                                                                                                                                                                                                                                                                                              |                                                                            |
| `fingerprint`             | Fingerprint of the SQL text (whitespace normalized, `IN` lists grouped)                                                                                                                                                                                                                                                                                                                                                                                               | Group executions of the same query, quote it to the DBA                    |
| `sql`                     | Text with `?` markers                                                                                                                                                                                                                                                                                                                                                                                                                                                 | Never any value, except in a `sql.raw` fragment                            |
| `params`                  | Depending on `audit.params`: absent, types (`string(10)`), or values                                                                                                                                                                                                                                                                                                                                                                                                  |                                                                            |
| `tag`, `correlationId`    | Business label and HTTP request identifier                                                                                                                                                                                                                                                                                                                                                                                                                            | Know which endpoint consumes resources                                     |
| `source`                  | `query`, `queryOne`, `execute`, `call`, `findMany`, `findFirst`, `findUnique`, `findPages`, `count`, `exists`, `aggregate`, `groupBy`, `create`, `update`, `updateMany`, `delete`, `deleteMany`, `findMany:include:<relation>` for the related rows of an include, `run:<name>` for a named query, `ping`, `transaction`. The CLI uses the same methods, with the tag `doctor`                                                                                        |                                                                            |
| `timings.acquireMs`       | Wait for a free connection                                                                                                                                                                                                                                                                                                                                                                                                                                            | High: pool saturated, slow query holding connections                       |
| `timings.executeMs`       | Prepare and execute on the Db2 side                                                                                                                                                                                                                                                                                                                                                                                                                                   | High: expensive query on the mainframe side                                |
| `timings.fetchMs`         | Row fetching                                                                                                                                                                                                                                                                                                                                                                                                                                                          | High: too many rows or columns too wide                                    |
| `timings.totalMs`         | From the request of a connection to the end of the fetch. `slow` compares it with `audit.slowQueryMs`: a first login counts in it                                                                                                                                                                                                                                                                                                                                     |                                                                            |
| `rows`                    | Rows read, or affected                                                                                                                                                                                                                                                                                                                                                                                                                                                | Many rows for little use: filter more                                      |
| `resultSets`, `truncated` | Number of result sets read, and whether one was cut at `maxRows` (`query.onMaxRowsExceeded: 'truncate'`)                                                                                                                                                                                                                                                                                                                                                              |                                                                            |
| `hasRaw`                  | The statement holds a `sql.raw` fragment, whose text is not a marker                                                                                                                                                                                                                                                                                                                                                                                                  | Review it: raw text is the only way a value reaches the SQL text           |
| `connectionId`            | Number of the connection within the process. Absent when none could be borrowed                                                                                                                                                                                                                                                                                                                                                                                       | Two events on the same id inside a transaction: the same pinned connection |
| `pool`                    | Used, free, pending and opening connections                                                                                                                                                                                                                                                                                                                                                                                                                           |                                                                            |
| `slow`                    | Above `audit.slowQueryMs`                                                                                                                                                                                                                                                                                                                                                                                                                                             |                                                                            |
| `warnings`                | `N_PLUS_ONE`, `TRUNCATED`, `RAW_SQL`, `RETRIED` (second attempt of a read whose connection was lost: the event before it holds the `CONNECTION_LOST` error), `NO_REPLY` (no reply within `pool.receiveTimeoutMs`: the driver gave the connection up, the statement is not retried). Object API: `ALLOW_SCAN` (`allowScan: true` ran a read the index guard refuses), `SCAN_RISK` (same read with `models.indexGuard: 'warn'`), see [models.md](models.md#index-guard) | `ALLOW_SCAN`, `SCAN_RISK`: a table scan, check its cost with the DBA       |
| `scanReason`              | With the warning `ALLOW_SCAN`: the reason a person wrote with `allowScan` to accept the scan of a large table. Text of the code, never a value of the application, written whatever `audit.params`                                                                                                                                                                                                                                                                    |
| `procedure`               | `CALL` only: `name`, `outcome`, `status`, `fields`, `warnings`, `resultSets`, `messages` (below)                                                                                                                                                                                                                                                                                                                                                                      |                                                                            |
| `transaction`             | Inside `db.$transaction`: `id`. On `COMMIT` and `ROLLBACK`, also `durationMs` and `statements`                                                                                                                                                                                                                                                                                                                                                                        | `durationMs` is the time locks were held: keep it short                    |
| `error`                   | `code`, `sqlcode`, `sqlstate`, `message`. For a Db2 error, `message` holds the text of Db2 with `audit.params: 'full'` only ([below](#the-text-of-a-db2-error))                                                                                                                                                                                                                                                                                                       |                                                                            |

### Procedure calls

| `procedure` field | Content                                                                                                                                                                                                                                                                                                                                |
| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`            | `SCHEMA.NAME`                                                                                                                                                                                                                                                                                                                          |
| `outcome`         | `success`, `rejected`, `unknown` (verdict of the outcome rule), `unchecked` (no rule). Absent when Db2 returned an error                                                                                                                                                                                                               |
| `unchecked`       | The reason given to `unchecked(descriptor, reason)`, as a person wrote it: why the call goes without its outcome rule. Only on such a call                                                                                                                                                                                             |
| `status`          | Status parameters declared by the rule, **in clear**: they are codes, chosen by the team                                                                                                                                                                                                                                               |
| `fields`          | Fields named by a rejection                                                                                                                                                                                                                                                                                                            |
| `warnings`        | Fields reported with a warning, on a success or a rejection                                                                                                                                                                                                                                                                            |
| `resultSets`      | How the result sets received differ from the `.results.ts` file of the procedure, when it has one ([procedures.md](procedures.md#result-set-types)): a result set more or fewer, a column missing, added or of another type, a null in a column marked never null. Names and types only. The console sink writes the line as a warning |
| `messages`        | `notice` of a success, `reasons` of a rejection and `warnings`, as the rule gave them. Only with `audit.params: 'full'`, since they can contain identifiers                                                                                                                                                                            |

`COMMIT` and `ROLLBACK` ending a `db.$transaction` are events too, with `source: 'transaction'` and `sql: 'COMMIT'` or `'ROLLBACK'`. `consoleSink` shows `tx=12 (35 ms, 3 statement(s))`. They never count towards N+1 detection.

### Error codes

| `error.code`              | When                                                                                                                                                                       |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A code of `Db2QueryError` | Db2 returned an error: `DUPLICATE_KEY`, `CONNECTION_LOST`, `SQL_SYNTAX`... ([errors.md](errors.md#db2queryerror-codes)). `sqlcode` and `sqlstate` come with it             |
| `PROC_REJECTED`           | The outcome rule of a procedure recognized a rejection. `consoleSink` logs it with `warn`, not `error`: it is a business answer, not a fault                               |
| `PROC_STATUS_UNKNOWN`     | The procedure ran, its outcome is unknown: status not recognized, rule that threw, output unreadable                                                                       |
| `POOL_TIMEOUT`            | No connection within `pool.acquireTimeoutMs`: nothing was sent                                                                                                             |
| `UNAVAILABLE`             | Db2 counted as unreachable after network failures: nothing was sent, no login was attempted ([production.md](production.md#8-connection-recovery))                         |
| `CONFIG`                  | A connection variable read by `connectionFromEnv` was missing or invalid as a new connection opened: nothing was sent, and the message names the variable, never its value |
| `MAX_ROWS`                | A result set had more rows than `maxRows`, with `query.onMaxRowsExceeded: 'throw'`                                                                                         |
| `USAGE`                   | Refused by db2kit once the statement reached the path to Db2: read-only mode, a column name twice in a result                                                              |
| `INDEX_GUARD`             | With `audit.refusals`: a read or a write of the object API that the index guard refused on a large table                                                                   |
| `INVALID_INPUT`           | Input values of `db.call` refused before sending (`Db2InputError`)                                                                                                         |
| `OTHER`                   | An error that does not come from Db2 nor from db2kit, for instance the native module of ibm_db missing                                                                     |

A call refused before that path leaves no event, since nothing was attempted: a wrong argument of the object API, an input value refused by `db.call` (`Db2InputError`), a statement through `db` inside a transaction.

With `audit.refusals: true`, a call of the object API refused before sending (the index guard, an unknown property, a value of the wrong type, a model not writable) adds an event too, so that refusals count in `statsSink` and in the logs like other errors: `kind` `'other'`, the method as `source`, the tag, no SQL text nor parameter, every time at 0, and `error.code` the code of the refusal, `INDEX_GUARD` for the index guard, `USAGE` otherwise, with the message of the refusal (db2kit writes it: it names properties and types, never a value of the call). Refusals are never counted as an N+1. `db.compile` never adds an event.

### The text of a Db2 error

The text of a Db2 error can carry a value: SQLCODE `-433` names the value too long, `-438` and `-443` carry the text a routine or a legacy program sets, which can hold an identifier. So unless `audit.params` is `AuditParams.Full`, the `message` of a Db2 error in the audit trail keeps its codes and what db2kit adds, never the text of Db2:

```text
SQLCODE -433, SQLSTATE 22001: text of Db2 left out (audit.params 'full' keeps it).
SQLCODE -4743, SQLSTATE 56038: text of Db2 left out (audit.params 'full' keeps it). db2kit: The statement uses SQL newer than ...
```

The statement of the event (`sql`, with its markers) still names the tables and columns, which is most of what the text of `-204`, `-206` or `-803` says. What is lost: the reason code of `-471`, `-904` or `-911`, kept by the error itself.

The `Db2QueryError` thrown to the application keeps its whole message: a log of the application that writes `error.message` writes the text of Db2. `messageWithoutDb2Text(error)` gives the form above, to log it the same way. The server-fault log of `db2kit/nestjs` follows `audit.params` ([nestjs.md](nestjs.md#exception-filter)).

## Built-in sinks

```ts
import { ConsoleLevel, consoleSink, jsonlSink, statsSink } from 'db2kit';
```

| Sink                                 | Purpose                                                                                 | Options                                                                                                                                 |
| :----------------------------------- | :-------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
| `consoleSink()`                      | One line per query: `log`, `warn` when slow or flagged, `error` on failure              | `logger` (default `console`, accepts the NestJS `Logger`), `only` (levels below), `maxSqlLength` (characters of SQL shown, default 300) |
| `jsonlSink({ path, retentionDays })` | One JSON line per event, one file per day (UTC), the files past `retentionDays` deleted | For offline analysis (`jq`, spreadsheet). `retentionDays` is required: see [Retention](#retention)                                      |
| `statsSink()`                        | In-memory aggregates by fingerprint                                                     | Keep the reference and call `snapshot()`                                                                                                |

Levels of `consoleSink`, from the most verbose to the least. `ConsoleLevel.X` and its text are the same value: `only: ConsoleLevel.All` equals `only: 'all'`. Any other value stops the startup.

| `only`                       | Text                | Writes                                                                                 | Use                                             |
| :--------------------------- | :------------------ | :------------------------------------------------------------------------------------- | :---------------------------------------------- |
| `ConsoleLevel.All` (default) | `'all'`             | Every query, one line each                                                             | Development, or to follow a problem for a while |
| `ConsoleLevel.SlowAndErrors` | `'slow-and-errors'` | Slow queries, warnings (`SCAN_RISK`, `N_PLUS_ONE`...), procedure rejections and errors | Production                                      |

What a line shows does not change with the level: parameter values follow `audit.params` (below), never the console level.

Sample console line:

```
[db2] 48 ms (acquire 0, execute 41, fetch 7) 50 row(s) tag=ContractController.search fp=3fa1c09b27de | SELECT ID, LABEL FROM MYSCHEMA.CONTRACT WHERE ...
```

### Retention

An event is kept only as long as a sink writes it somewhere:

| Sink          | Where the events go                                                | Who deletes them                                                                                                                                                                                                                                                    |
| :------------ | :----------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `consoleSink` | The logs of the application (container, journald, a log platform)  | The platform: set its retention there, for every log of the application                                                                                                                                                                                             |
| `jsonlSink`   | One file per day, `<name>-YYYY-MM-DD.jsonl` next to `path`, in UTC | The sink: at startup and at each new day, it deletes its files older than `retentionDays`, the current day included, never another file. A file of the day that cannot be opened stops the startup, and at a new day the events go on to the file of the day before |
| `statsSink`   | Memory                                                             | Nobody: gone with the process                                                                                                                                                                                                                                       |

How long to keep them is a decision of the organization, with its data protection officer: data are kept no longer than their purpose needs (GDPR, storage limitation). What the events hold decides it:

| Content                                                                                                           | Suggested retention                          | Why                                                                                                                                                                                                     |
| :---------------------------------------------------------------------------------------------------------------- | :------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `audit.params: 'types'` or `'none'` (the default): statements with markers, timings, codes, tags, correlation ids | 30 days, 90 at most                          | A month of fingerprints to review with the DBA, and time to analyse an incident after the fact. Not anonymous: a correlation id leads to a request, and through the logs of the application to a person |
| `audit.params: 'full'`: the values of the parameters                                                              | 7 days at most, for a limited diagnosis only | The values are personal data: never in production by default                                                                                                                                            |
| Aggregates per fingerprint, built by the application from `statsSink`                                             | Longer, for instance 13 months               | Counts and timings without any request or person: a year to compare with the year before                                                                                                                |

The same events can exist in several places: the JSONL files, and every place the console logs go. They are kept as long as their longest-lived copy, so set the retention at each place that keeps them:

- **The central log store**, when there is one: Elasticsearch or OpenSearch (an index lifecycle policy with a delete phase, counted from the rollover of the index, so an index rolled over daily and deleted at 30 days keeps about 31), Grafana Loki, Graylog, Splunk, a cloud service (CloudWatch Logs, Azure Monitor, Google Cloud Logging). The platform team usually sets one retention for every log of an application: the lines of db2kit can go to their own index or stream, with a logger context such as `new Logger('Db2')`, when they need another one.
- **The way there**: files on the host before a shipper (Filebeat, Fluent Bit, Logstash) reads them, logs of the container runtime or of `journald`, files of a process manager such as PM2. Often rotated by size rather than by age: check how long they last.
- **Backups and snapshots** of the store: a snapshot kept a year keeps the events a year.

### Reading the statistics

```ts
const stats = statsSink();
// in audit.sinks: [consoleSink(), stats]

stats.snapshot();
// [{ fingerprint, sql, tags, count, errors, slow, totalMs, avgMs, p95Ms, maxMs, avgRows, maxRows }, ...]
```

The array is sorted by descending total time: **the first rows are the queries to optimize first**. Expose it on a protected admin endpoint, or log it periodically.

### Writing your own sink

```ts
const mySink: AuditSink = {
  name: 'otel',
  handle(event) {
    /* send to OpenTelemetry, Elastic... Must neither throw nor block. */
  },
};
```

A sink that throws is isolated: the error is printed once, and the query is never affected.

## Context: automatic tag and correlation

```ts
await db.withContext({ tag: 'ContractController.search', correlationId: requestId }, async () => {
  // every query started here, even deep down, carries this tag and this id
});
```

The context follows async calls (`AsyncLocalStorage`). The `tag` option of a call takes precedence over the context one. In NestJS, an interceptor sets the context for each HTTP request: see [nestjs.md](nestjs.md).

## N+1 detection

When the same query (same fingerprint) runs `nPlusOneThreshold` times within one context, the event carries the `N_PLUS_ONE` warning, once per context. It is the sign of a query inside a loop: group it with `IN ${sql.in(ids)}`. Detection only happens within a context (`withContext` or interceptor).

## Correlation with the DBA

When each connection opens, db2kit sends Db2:

- `CLIENT_APPLNAME` = `audit.applicationName`,
- `CLIENT_WRKSTNNAME` = name of the machine or pod.

The DBA finds these values in `DISPLAY THREAD` and in accounting traces, which ties CPU consumption to the application. For the DBA to analyze a specific query, give them the SQL text from the audit trail.
