> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Analytics Cookbook

> Copy-pasteable SQL for your PromptGuard telemetry, p95 latency, token volume by model, high-risk users, blocked-over-time, threats by detector, and daily roll-ups.

> [!NOTE]
>
> Every guarded request writes one row to the `security_events` table (input and output are separate rows). Self-hosted deployments own that Postgres database directly, so you can point psql, a BI tool, or your warehouse's foreign-data wrapper at it and run these recipes as-is. On PromptGuard Cloud, pull the same data through the [Interactions API](https://docs.promptguard.co/platform/audit-logs.md#exporting-data) and load it into your own store.

> [!NOTE]
>
> There is **no pre-aggregated roll-up table today**: these recipes run directly against the raw `security_events` (and, for configuration/auth activity, `audit_events`) event tables. The [Daily and hourly roll-ups](#daily-and-hourly-roll-ups) section shows how to build your own materialized view if you want cheaper dashboards.

## The tables you'll query

### `security_events`: the request log

One row per policy evaluation. The columns that matter for analytics:

| Column | Type | Notes |
| - | - | - |
| `created_at` | `timestamptz` | Event time. Index exists on `(user_id, created_at)`. |
| `decision` | `varchar(20)` | `allow` \| `block` \| `redact` |
| `threat_type` | `varchar(50)` | `injection`, `pii`, `toxicity`, `data_exfiltration`, … (NULL when allowed) |
| `confidence` | `float` | 0.0-1.0 |
| `processing_time_ms` | `float` | **Engine-only** latency. Excludes the downstream LLM call on proxied requests. |
| `model` | `varchar(100)` | Upstream model, e.g. `gpt-4o-mini` (NULL on pure `/guard` scans) |
| `provider` | `varchar(50)` | `openai`, `anthropic`, … |
| `surface` | `varchar(20)` | `proxy` \| `sdk` \| `guard` \| `browser` \| `desktop`. Separates Shadow AI traffic from the developer path. NULL on historical rows. |
| `end_user_id` | `varchar(255)` | Per-end-user **attribution label**. Free text, never validated, and not a reference to an account. Set from the `X-End-User` header, or, on Shadow AI traffic, from the enrolled device's own label, which is the signed-in Member's email only where that device was enrolled by a person approving it in their browser. Treat it as a grouping key, not an identity. |
| `session_id` | `varchar(255)` | The `context.session_id` a [Guard API](https://docs.promptguard.co/api-reference/guard.md) request named: the conversation the event is a turn of, exactly as sent (at most 255 characters). With `end_user_id` it is one session: one end user's conversation. NULL when the request named none, on proxy requests, and on every event before 2026-10-17. Indexed with `project_id`, `end_user_id` and `created_at` where it is set. |
| `country_code` / `region` | `char(2)` / `varchar(100)` | GeoIP enrichment, filled lazily. |
| `tokens_input` / `tokens_output` | `integer` | From the upstream response. NULL on `/guard` scans that never proxy. |
| `upstream_cost_usd` | `numeric(18,12)` | What the provider will charge for the call, in USD: its own reported usage (cached and cache-written tokens priced at their own rates) times the vendor's **list price** for the model that answered, after any [fallback](https://docs.promptguard.co/gateway/fallback-models.md). On the event that carries the response's tokens, once per response. NULL whenever the call cannot be priced exactly; `cost_basis` says why. It does not know about discounts, credits or data-residency uplifts, so your provider's invoice is still the bill. Written from 2026-10-17. |
| `cost_basis` | `varchar(20)` | `list_price` (priced) \| `unpriced_model` (no list price for this model on the provider that answered, Gemini, Azure, Bedrock and self-hosted models, among others) \| `unpriced_usage` (billed on terms the table does not price exactly: a non-standard service tier, a long-context rate, priority or fast mode, regional processing, or a usage field it does not recognise) \| `no_usage` (no usage was reported that PromptGuard could read, a stream you sent with `stream_options.include_usage: false`, a stream from a provider PromptGuard does not ask for usage on, one whose frames it could not read, or an answer that broke off before it finished; your provider billed it all the same). NULL on every event that is not a call's cost-bearing event: input events, `/guard` scans, and the second and later output rows of a response that logged several. |
| `price_table_version` | `varchar(20)` | The version of PromptGuard's price table that produced `cost_basis`. If a rate is ever corrected, the rows it affected are exactly the ones carrying the old version, and their tokens are stored beside them. |
| `cost_usd_estimate` | `numeric(12,6)` | **Deprecated 2026-08-10, NULL on every event written since.** Historical rows keep their values and the column is not going away, so existing queries still run. It held tokens × a per-model price table PromptGuard maintained by hand, and that table could not be kept correct. Use `upstream_cost_usd`, which says where its figure came from. |
| `direction` | `varchar(10)` | `input` \| `output` |
| `event_metadata` | `json` | Free-form. Holds `detector` (`regex` \| `ml` \| `agentic` \| a detector name), `route_preset`, `content_preview`, and per-detector `latency_ms`. |
| `triage_status` | `varchar(20)` | `open` \| `in_review` \| `resolved` |

> [!WARNING]
>
> `security_events` is retention-bounded. Rows are purged on a per-plan schedule (Free 24h, Developer 30d, Enterprise 90d / custom). A query over a 90-day window on a Developer plan returns at most 30 days of rows. For durable analytics, raise your retention (Enterprise `custom_retention_days`) or stream events into your own warehouse. `audit_events` is **never** purged.

### `audit_events`: the compliance trail

Configuration changes, authentication, and data access. Hash-chained and never purged. Columns: `created_at`, `organization_id`, `user_id`, `event_type`, `category` (`security` | `authentication` | `data_access` | `configuration` | `billing`), `action`, `outcome` (`success` | `failure` | `denied` | `error`), `resource_type`, `resource_id`, `ip_address`, `details` (jsonb).

## Latency percentiles

Engine processing time by percentile over the last 24 hours. Use `percentile_cont` for interpolated percentiles.

```sql theme={"system"}
SELECT
  percentile_cont(0.50) WITHIN GROUP (ORDER BY processing_time_ms) AS p50_ms,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms) AS p95_ms,
  percentile_cont(0.99) WITHIN GROUP (ORDER BY processing_time_ms) AS p99_ms,
  count(*) AS events
FROM security_events
WHERE created_at > now() - interval '24 hours';
```

Break the same percentiles down by `surface` to compare the developer proxy against Shadow AI scans:

```sql theme={"system"}
SELECT
  surface,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms) AS p95_ms,
  percentile_cont(0.99) WITHIN GROUP (ORDER BY processing_time_ms) AS p99_ms,
  count(*) AS events
FROM security_events
WHERE created_at > now() - interval '24 hours'
GROUP BY surface
ORDER BY p99_ms DESC NULLS LAST;
```

> [!NOTE]
>
> `processing_time_ms` is the time PromptGuard's engine spent, not end-to-end request time. On the proxy path it excludes the upstream provider call. See [Latency Budgets](https://docs.promptguard.co/production/latency-budgets.md) for what each detector contributes.

## Token volume by model

Grouped by upstream model. Tokens are NULL on `/guard`-only scans (they never call a provider), so filter them out.

```sql theme={"system"}
SELECT
  provider,
  model,
  count(*)                                AS requests,
  sum(tokens_input)                       AS tokens_in,
  sum(tokens_output)                      AS tokens_out,
  sum(tokens_input + tokens_output)       AS tokens_total
FROM security_events
WHERE created_at > now() - interval '30 days'
  AND tokens_input IS NOT NULL
GROUP BY provider, model
ORDER BY tokens_total DESC;
```

> [!WARNING]
>
> **These are token counts, not dollars.** For dollars, use `upstream_cost_usd` in the next recipe. PromptGuard's earlier `cost_usd_estimate` was tokens multiplied by a price table maintained by hand, and it drifted, one model carried a price 7.5× its real rate for months, and nothing detected it, because a wrong price looks exactly like a right one. The table behind `upstream_cost_usd` is one versioned file whose every rate is dated, sourced to the vendor's own pricing page and checked against a second published price list, and a call it cannot price exactly is NULL with a reason rather than a guess.
>
> Token counts come from the provider's own `usage` block, so they cannot go stale.

## Upstream spend by model

What your providers will charge at list price, by the model that answered. The second figure is how much traffic the table could not price, so a total is never read as complete when it is not.

```sql theme={"system"}
SELECT
  model,
  sum(upstream_cost_usd)                                   AS list_price_usd,
  count(*) FILTER (WHERE cost_basis = 'list_price')        AS priced_calls,
  count(*) FILTER (WHERE cost_basis <> 'list_price')       AS unpriced_calls
FROM security_events
WHERE created_at > now() - interval '30 days'
  AND cost_basis IS NOT NULL
GROUP BY model
ORDER BY list_price_usd DESC NULLS LAST;
```

`cost_basis IS NOT NULL` selects the events that were costed: one per upstream response, so the sum counts each call once even when its response logged several output rows.

Every response your provider billed has exactly one costed event, and that event also carries the call's `tokens_input` and `tokens_output`; the call's other output rows carry neither, so summing tokens counts each call once too. When an output scan wrote an event, that event is the costed one. When none did, PromptGuard writes a **usage-only** output event: `decision` is `allow`, `threat_type` is NULL, and `event_metadata.usage_only` says why there was no scan:

| `usage_only` | The response |
| - | - |
| `no_text` | had no text to scan: only tool calls, or a reasoning model's empty answer |
| `not_scanned` | was a stream in a project in monitor mode |
| `scan_failed` | had an output scan that failed: a stream is released unscanned, a non-streamed completion is withheld with a `503`; your provider billed it either way |
| `unrecognised_stream` | was a stream in a format PromptGuard does not recognise |
| `cancelled` | was a stream your client disconnected from before PromptGuard released it; the provider had already answered in full |
| `interrupted` | began (a success status arrived) and never became a response: the connection dropped or the read timed out partway, or the body was not a completion. One event per such attempt, including attempts a [fallback](https://docs.promptguard.co/gateway/fallback-models.md) then answered, each naming the model and provider it was sent to. `cost_basis` is `no_usage`; `tokens_input` is set when the part that arrived reported it exactly |

A usage-only event is not a request, a finding or a check: the dashboard leaves it out of every request count, detection rate, risk band and latency figure, and keeps its tokens and cost in every sum. To do the same in your own queries, add `AND NOT event_metadata ? 'usage_only'` when counting requests, and leave it off when summing tokens or cost. To list them: `WHERE event_metadata ? 'usage_only'`.

> [!NOTE]
>
> OpenAI streams report usage only when asked with `stream_options: {"include_usage": true}`. When you do not set it, PromptGuard asks for you on OpenAI, DeepSeek, Groq, Ollama and vLLM, and removes the extra usage chunk before the stream reaches you, so your stream is unchanged. When you set it to `false`, PromptGuard respects that: the stream reports no usage and is recorded as `no_usage`. Other providers either report stream usage unasked or would refuse the field. Azure OpenAI is not asked: the API version PromptGuard pins predates the field. Gemini and Cohere calls record their tokens and are `unpriced_model`, with no figure. Your provider's billing console is the complete figure.

Token volume attributed to blocked requests (the calls you *avoided* sending, plus those redacted and still forwarded):

```sql theme={"system"}
SELECT
  decision,
  count(*)                                          AS requests,
  coalesce(sum(tokens_input + tokens_output), 0)    AS tokens_total
FROM security_events
WHERE created_at > now() - interval '30 days'
GROUP BY decision
ORDER BY tokens_total DESC;
```

## High-risk activity by attribution label

Ranks traffic by blocked-request volume, grouped by `end_user_id`.

> [!WARNING]
>
> Group by the label **or** by the account, never by both in one column. `end_user_id` is an attribution label, free text a caller or a device supplies, and `user_id` is the account that owns the events. Coalescing them produces a column where a proven account and an unvalidated hostname are indistinguishable, which is exactly the reading the product refuses to offer. Rows with a NULL `end_user_id` are traffic nobody was attributed to; count them, do not fill them in with the account.

```sql theme={"system"}
SELECT
  end_user_id AS attribution_label,
  count(*) FILTER (WHERE decision = 'block')  AS blocks,
  count(*) FILTER (WHERE decision = 'redact') AS redactions,
  count(*)                                     AS total_events,
  round(
    100.0 * count(*) FILTER (WHERE decision = 'block') / nullif(count(*), 0),
    1
  ) AS block_pct
FROM security_events
WHERE created_at > now() - interval '7 days'
GROUP BY end_user_id
HAVING count(*) FILTER (WHERE decision = 'block') > 0
ORDER BY blocks DESC
LIMIT 50;
```

Drill into a single label's most recent blocks, including the threat type and detector that fired:

```sql theme={"system"}
SELECT
  created_at,
  threat_type,
  event_metadata->>'detector' AS detector,
  confidence,
  event_metadata->>'content_preview' AS preview
FROM security_events
WHERE end_user_id = '<end-user-id>'
  AND decision = 'block'
ORDER BY created_at DESC
LIMIT 100;
```

## Blocked over time

Hourly blocked-vs-total counts for a time-series chart:

```sql theme={"system"}
SELECT
  date_trunc('hour', created_at)              AS bucket,
  count(*)                                     AS total,
  count(*) FILTER (WHERE decision = 'block')   AS blocked,
  count(*) FILTER (WHERE decision = 'redact')  AS redacted,
  round(
    100.0 * count(*) FILTER (WHERE decision = 'block') / nullif(count(*), 0),
    2
  ) AS block_rate_pct
FROM security_events
WHERE created_at > now() - interval '48 hours'
GROUP BY bucket
ORDER BY bucket;
```

Swap `date_trunc('hour', …)` for `date_trunc('day', …)` and widen the interval for a daily trend.

## Threats by detector

`decision`/`threat_type` tell you *what* was caught; the detector that caught it lives in `event_metadata->>'detector'` (values include `regex`, `ml`, `agentic`, and specific detector names). This recipe attributes blocks to the detection layer that fired, useful for tuning which layers earn their latency.

```sql theme={"system"}
SELECT
  threat_type,
  coalesce(event_metadata->>'detector', 'unknown') AS detector,
  count(*)                     AS hits,
  round(avg(confidence), 3)    AS avg_confidence,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms) AS p95_ms
FROM security_events
WHERE created_at > now() - interval '7 days'
  AND decision IN ('block', 'redact')
GROUP BY threat_type, detector
ORDER BY hits DESC;
```

Threat mix by surface (are Shadow AI pastes producing different threats than the developer proxy?):

```sql theme={"system"}
SELECT
  surface,
  threat_type,
  count(*) AS hits
FROM security_events
WHERE created_at > now() - interval '7 days'
  AND threat_type IS NOT NULL
GROUP BY surface, threat_type
ORDER BY surface, hits DESC;
```

## Daily and hourly roll-ups

There is no roll-up table shipped, so long-window dashboards scan raw events every load. If that gets expensive, materialize a daily summary yourself. This view is safe to `REFRESH` on a schedule (nightly, or hourly with `CONCURRENTLY`):

```sql theme={"system"}
CREATE MATERIALIZED VIEW IF NOT EXISTS security_events_daily AS
SELECT
  date_trunc('day', created_at)                AS day,
  surface,
  provider,
  model,
  count(*)                                      AS events,
  count(*) FILTER (WHERE decision = 'block')    AS blocked,
  count(*) FILTER (WHERE decision = 'redact')   AS redacted,
  sum(coalesce(tokens_input, 0))                AS tokens_in,
  sum(coalesce(tokens_output, 0))               AS tokens_out,
  percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms) AS p95_ms
FROM security_events
GROUP BY 1, 2, 3, 4;

-- A unique index lets you REFRESH ... CONCURRENTLY without locking readers.
CREATE UNIQUE INDEX IF NOT EXISTS idx_security_events_daily_key
  ON security_events_daily (day, surface, provider, model);
```

Refresh it:

```sql theme={"system"}
REFRESH MATERIALIZED VIEW CONCURRENTLY security_events_daily;
```

> [!WARNING]
>
> Because `security_events` is retention-bounded, a materialized view built from it inherits the same horizon, refreshing after a purge drops the aged-out days. To keep history beyond your plan's retention, `INSERT` each day's roll-up into a **plain table** you own (self-host) or into your warehouse (Cloud) before the source rows are purged, rather than relying on the view alone.

An `INSERT`-based accumulator that survives purges:

```sql theme={"system"}
CREATE TABLE IF NOT EXISTS security_events_daily_history (
  day        date PRIMARY KEY,
  events     bigint,
  blocked    bigint,
  redacted   bigint,
  tokens_in  bigint,
  tokens_out bigint,
  p95_ms     double precision
);

INSERT INTO security_events_daily_history
SELECT
  date_trunc('day', created_at)::date,
  count(*),
  count(*) FILTER (WHERE decision = 'block'),
  count(*) FILTER (WHERE decision = 'redact'),
  sum(coalesce(tokens_input, 0)),
  sum(coalesce(tokens_output, 0)),
  percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms)
FROM security_events
WHERE created_at >= current_date - interval '1 day'
  AND created_at <  current_date
GROUP BY 1
ON CONFLICT (day) DO UPDATE SET
  events   = excluded.events,
  blocked  = excluded.blocked,
  redacted  = excluded.redacted,
  tokens_in = excluded.tokens_in,
  tokens_out = excluded.tokens_out,
  p95_ms    = excluded.p95_ms;
```

Schedule that with `pg_cron` (self-host / Supabase) or any external scheduler:

```sql theme={"system"}
SELECT cron.schedule(
  'rollup-security-events-daily',
  '10 0 * * *',                       -- 00:10 UTC daily
  $$INSERT INTO security_events_daily_history
    SELECT date_trunc('day', created_at)::date, count(*),
           count(*) FILTER (WHERE decision = 'block'),
           count(*) FILTER (WHERE decision = 'redact'),
           sum(coalesce(tokens_input, 0)), sum(coalesce(tokens_output, 0)),
           percentile_cont(0.95) WITHIN GROUP (ORDER BY processing_time_ms)
    FROM security_events
    WHERE created_at >= current_date - interval '1 day'
      AND created_at < current_date
    GROUP BY 1
    ON CONFLICT (day) DO UPDATE SET
      events = excluded.events, blocked = excluded.blocked,
      redacted = excluded.redacted, tokens_in = excluded.tokens_in,
      tokens_out = excluded.tokens_out,
      p95_ms = excluded.p95_ms;$$
);
```

## Audit trail (configuration & auth)

Config changes and authentication live in `audit_events`, not `security_events`. Recent denied or failed sensitive actions:

```sql theme={"system"}
SELECT
  created_at,
  category,
  action,
  outcome,
  resource_type,
  resource_id,
  ip_address
FROM audit_events
WHERE created_at > now() - interval '7 days'
  AND outcome IN ('failure', 'denied', 'error')
ORDER BY created_at DESC;
```

## Next steps

> [card] [Latency Budgets](https://docs.promptguard.co/production/latency-budgets.md)
>
> Per-detector p99 budgets behind `processing_time_ms`

> [card] [Audit Logs](https://docs.promptguard.co/platform/audit-logs.md)
>
> Export the same data through the Interactions API

> [card] [Usage Tracking](https://docs.promptguard.co/platform/usage-tracking.md)
>
> Plan quotas, request counts, and spend

> [card] [Dashboard](https://docs.promptguard.co/platform/dashboard.md)
>
> Prebuilt analytics in the app


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.