Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(mcp): add observability table refs to querying-posthog-data skill (#59084)

Daniel Viscaf45593ed8864
diff --git a/products/posthog_ai/skills/querying-posthog-data/SKILL.md b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
index ee971b51502a..350f471837be 100644
--- a/products/posthog_ai/skills/querying-posthog-data/SKILL.md
+++ b/products/posthog_ai/skills/querying-posthog-data/SKILL.md
@@ -34,6 +34,7 @@ Schema reference for PostHog's core system models, organized by domain:
- [Actions](./references/models-actions.md)
- [Alerts](./references/models-alerts.md)
- [Annotations](./references/models-annotations.md)
+- [APM / tracing (`posthog.trace_spans`)](./references/models-apm-spans.md)
- [Batch exports](./references/models-batch-exports.md)
- [Early Access Features](./references/models-early-access-features.md)
- [Cohorts & Persons](./references/models-cohorts.md)
@@ -46,7 +47,8 @@ Schema reference for PostHog's core system models, organized by domain:
- [Hog Functions](./references/models-hog-functions.md)
- [Integrations](./references/models-integrations.md)
- [LLM analytics reviews](./references/models-llm-analytics-reviews.md)
-- [Logs](./references/models-logs.md)
+- [Logs (`logs` data plane + saved views and alerts)](./references/models-logs.md)
+- [Metrics (`posthog.metrics`)](./references/models-metrics.md)
- [Notebooks](./references/models-notebooks.md)
- [Session Recording Playlists](./references/models-session-recording-playlists.md)
- [Session Recordings](./references/models-session-recordings.md)
@@ -84,6 +86,7 @@ Use the examples below to create optimized analytical queries.
- [Web overview](./references/example-web-overview.md)
- [Error tracking (search for a value in an error and filtering by custom properties)](./references/example-error-tracking.md)
- [Logs (filtering by severity and searching for a term)](./references/example-logs.md)
+- [Cross-signal correlation (metric exemplar → trace → logs)](./references/example-observability-correlation.md)
- [Sessions (listing sessions with duration, pageviews, and bounce rate)](./references/example-sessions.md)
- [Session replay (listing recordings with activity filters)](./references/example-session-replay.md)
- [Team taxonomy (top events by count, paginated)](./references/example-team-taxonomy.md)
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md b/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md
new file mode 100644
index 000000000000..28aef77bae7b
--- /dev/null
+++ b/products/posthog_ai/skills/querying-posthog-data/references/example-observability-correlation.md
@@ -0,0 +1,141 @@
+# Cross-signal correlation (metric exemplar → trace → logs)
+
+Use when investigating a metric anomaly (latency spike, error rate jump) and you want to inspect a representative trace and the logs from that request in one round trip.
+
+The three observability tables — `posthog.metrics`, `posthog.trace_spans`, `logs` — share `trace_id` as a join key. The schema is wired so `posthog.metrics` can carry an exemplar `trace_id` on every point when the SDK attached one (OpenTelemetry exemplar pattern).
+
+**Namespacing:** `logs` is registered at the HogQL root level; `posthog.trace_spans` and `posthog.metrics` live under the `posthog.` namespace and must be referenced with the prefix. Bare names fail.
+
+**`trace_id` format:** All three tables store `trace_id` as base64-encoded 16 bytes. Joins are direct equality (no decoding needed). Use `hex(tryBase64Decode(trace_id))` to display in hex.
+
+> ⚠️ **Status (as of PR [#50936](https://github.com/PostHog/posthog/pull/50936)):** exemplar extraction is not yet wired up in `rust/capture-logs/src/metric_record.rs` — the `_exemplars` argument is prefixed with underscore (unused). Every metric row has `trace_id = ''` today. The example query below describes the intended pattern but returns empty until exemplars are populated. The "Works today" alternative further down uses `posthog.trace_spans` directly as the starting point and works against current data.
+
+## Pattern
+
+1. **Locate the spike** in `metrics` for a specific `(service, metric, time window)`.
+2. **Pick an exemplar** — `argMax(trace_id, value)` returns the trace_id from the row with the highest value.
+3. **Fetch spans and logs** for that trace_id in a single `UNION ALL`, ordered by timestamp so the timeline interleaves.
+
+## Query
+
+```sql
+WITH exemplar AS (
+ SELECT argMax(trace_id, value) AS trace_id
+ FROM posthog.metrics
+ WHERE service_name = 'checkout'
+ AND metric_name = 'http.server.duration'
+ AND timestamp >= now() - INTERVAL 15 MINUTE
+ AND trace_id != ''
+)
+SELECT
+ 'span' AS source,
+ name AS detail,
+ service_name,
+ duration_nano,
+ status_code,
+ NULL AS severity_number,
+ timestamp
+FROM posthog.trace_spans
+WHERE trace_id = (SELECT trace_id FROM exemplar)
+
+UNION ALL
+
+SELECT
+ 'log',
+ body,
+ service_name,
+ NULL,
+ NULL,
+ severity_number,
+ timestamp
+FROM logs
+WHERE trace_id = (SELECT trace_id FROM exemplar)
+
+ORDER BY timestamp
+```
+
+## Notes
+
+- **`argMax(trace_id, value)` is cheap** because the per-minute projection on `posthog.metrics` pre-aggregates by `(service_name, metric_name, ...)`. Constrain the time window tightly (15 minutes is plenty for a spike).
+- **Filter `trace_id != ''`** — metric points without an exemplar use empty string, not null.
+- **`UNION ALL` (not `UNION`)** — `UNION` deduplicates and adds cost.
+- **`status_code = 2` is Error** in `posthog.trace_spans` (OTel semantics). Use this column to flag error spans inline in the result.
+- If you need to drill into the span tree visually, take the resulting `trace_id` and call `posthog:apm-trace-get` to get the full waterfall.
+
+## Works today: span-anchored correlation
+
+Until metric exemplars are populated by ingestion, anchor on a span instead. Find an interesting trace (slowest error, longest duration, specific service), then pull its logs.
+
+```sql
+WITH slow_error_trace AS (
+ SELECT trace_id
+ FROM posthog.trace_spans
+ WHERE service_name = 'checkout'
+ AND is_root_span
+ AND status_code = 2
+ AND timestamp >= now() - INTERVAL 1 HOUR
+ ORDER BY duration_nano DESC
+ LIMIT 1
+)
+SELECT
+ 'span' AS source,
+ name AS detail,
+ service_name,
+ duration_nano,
+ status_code,
+ NULL AS severity_number,
+ timestamp
+FROM posthog.trace_spans
+WHERE trace_id = (SELECT trace_id FROM slow_error_trace)
+
+UNION ALL
+
+SELECT
+ 'log',
+ body,
+ service_name,
+ NULL,
+ NULL,
+ severity_number,
+ timestamp
+FROM logs
+WHERE trace_id = (SELECT trace_id FROM slow_error_trace)
+
+ORDER BY timestamp
+```
+
+`trace_id` is base64 in both tables, so the equality join works directly.
+
+## Variants
+
+**Pick a sample of exemplar traces, not just one:**
+
+```sql
+SELECT trace_id, max(value) AS peak
+FROM posthog.metrics
+WHERE service_name = 'checkout'
+ AND metric_name = 'http.server.duration'
+ AND timestamp >= now() - INTERVAL 15 MINUTE
+ AND trace_id != ''
+GROUP BY trace_id
+ORDER BY peak DESC
+LIMIT 5
+```
+
+**Find services with the biggest error-rate jump and pick an exemplar trace per service:**
+
+```sql
+SELECT
+ service_name,
+ countIf(status_code = 2) / count() AS error_rate,
+ argMax(trace_id, status_code = 2) AS sample_error_trace
+FROM posthog.trace_spans
+WHERE timestamp >= now() - INTERVAL 1 HOUR
+ AND is_root_span
+GROUP BY service_name
+HAVING count() > 100
+ORDER BY error_rate DESC
+LIMIT 10
+```
+
+`sample_error_trace` is then a candidate for `posthog:apm-trace-get` or a `logs` lookup by `trace_id`.
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md b/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md
new file mode 100644
index 000000000000..e51644a0f693
--- /dev/null
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-apm-spans.md
@@ -0,0 +1,110 @@
+# APM / tracing (OpenTelemetry spans)
+
+The `posthog.trace_spans` table holds OpenTelemetry span data from instrumented services. Each row is one span — a unit of work in a distributed trace. Spans within the same trace share a `trace_id`; the parent-child hierarchy is reconstructed via `parent_span_id` → `span_id`.
+
+**Namespacing:** Reference this table as `posthog.trace_spans`, not bare `trace_spans` — it's registered under the `posthog.` namespace in the HogQL database (see `posthog/hogql/database/database.py`). The same applies to `posthog.trace_attributes`. Bare names fail with "Unknown table" at HogQL compile time. (Asymmetric with `logs`, which is registered at root level — `logs` works without a prefix.)
+
+**Prefer the typed tools when they fit:** `posthog:query-apm-spans` for span listing with structured filters, `posthog:apm-trace-get` for full-trace fetches, `posthog:apm-spans-aggregate` / `posthog:apm-spans-tree` for aggregations. Reach for HogQL when you need cross-signal joins (with `logs` or `posthog.metrics` by `trace_id`), exemplar lookups, or aggregations the typed tools don't expose.
+
+## `posthog.trace_spans`
+
+OpenTelemetry spans. One row per span. Backed by ClickHouse `trace_spans_distributed`.
+
+### Columns
+
+| Column | Type | Description |
+| ----------------------- | ----------------------------------- | ------------------------------------------------------------------------------------ |
+| `uuid` | String | Row UUID (not the OTel span_id) |
+| `team_id` | Int32 | Team this span belongs to |
+| `trace_id` | String | OTel trace ID (24-char base64-encoded 16 bytes). Same on every span in the trace |
+| `span_id` | String | OTel span ID (12-char base64-encoded 8 bytes). Unique within a trace |
+| `parent_span_id` | String | OTel parent span ID (12-char base64). `'AAAAAAAAAAA='` (8 zero bytes) for root spans |
+| `is_root_span` | Bool | Convenience flag — prefer this over string-matching `parent_span_id` |
+| `name` | LowCardinality(String) | Span name (operation name) |
+| `kind` | Int8 | OTel SpanKind: 0 Unspecified, 1 Internal, 2 Server, 3 Client, 4 Producer, 5 Consumer |
+| `status_code` | Int16 | OTel StatusCode: 0 Unset, 1 OK, 2 Error |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `timestamp` | DateTime64(6) | Span start time |
+| `end_time` | DateTime64(6) | Span end time |
+| `observed_timestamp` | DateTime64(6) | Ingest time |
+| `duration_nano` | UInt64 | Span duration in **nanoseconds** (1 s = 1_000_000_000) |
+| `attributes` | Map(String, String) | Span-level attributes (e.g. `http.method`, `http.status_code`, `db.statement`) |
+| `resource_attributes` | Map(LowCardinality(String), String) | Resource-level attributes (k8s labels, deployment info, host) |
+| `resource_fingerprint` | UInt64 | Hash of `resource_attributes` — cheap equality filter |
+| `instrumentation_scope` | String | Instrumentation library name |
+| `time_bucket` | DateTime | `toStartOfDay(timestamp)` — first sort key component |
+
+### Sort key
+
+`(team_id, time_bucket, service_name, resource_fingerprint, status_code, name, timestamp)`. Queries that filter on `service_name` + `time_bucket` are very efficient. Filters on `name` further narrow the read.
+
+### Important notes
+
+- **Durations are nanoseconds.** Filter `duration_nano > 1000000000` for spans longer than 1 second.
+- **`status_code == 2` is Error.** Use `status_code = 2` (not the string `"ERROR"`).
+- **`trace_id`, `span_id`, `parent_span_id` are base64-encoded bytes**, not hex. The MCP layer (`posthog:query-apm-spans`, `posthog:apm-trace-get`) converts to hex via `hex(tryBase64Decode(...))` for display. Raw HogQL queries against this table see the base64 form.
+- **`parent_span_id` of a root span** is `'AAAAAAAAAAA='` (12-char base64 of 8 zero bytes), not null. **Use `is_root_span` to find trace entries** — don't string-match the padding.
+- **Use `hex(tryBase64Decode(trace_id))` to display trace_ids in hex** for human-readable output.
+- Cross-signal joins by `trace_id` work against `logs` (both store base64). For `posthog.metrics`, exemplar extraction is not yet wired up in the ingestion pipeline — see the metrics reference for the current state.
+- User HogQL queries on `posthog.trace_spans` are capped at 50 GB read per query.
+
+## `posthog.trace_attributes`
+
+AggregatingMergeTree rollup of span attribute values, partitioned by service and 10-minute bucket. Backs the attribute discovery endpoints used by `posthog:apm-attributes-list` and `posthog:apm-attribute-values-list`. Same `posthog.` namespacing rule — reference as `posthog.trace_attributes`.
+
+### Columns
+
+| Column | Type | Description |
+| ---------------------- | ------------------------------------ | --------------------------------------------- |
+| `team_id` | Int32 | Team |
+| `time_bucket` | DateTime64(0) | 10-minute bucket |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `resource_fingerprint` | UInt64 | Resource identity hash |
+| `attribute_key` | LowCardinality(String) | Attribute name |
+| `attribute_value` | String | Attribute value |
+| `attribute_type` | LowCardinality(String) | `span_attribute` or `span_resource_attribute` |
+| `attribute_count` | SimpleAggregateFunction(sum, UInt64) | Number of spans where this attribute appeared |
+
+Prefer `posthog:apm-attributes-list` / `posthog:apm-attribute-values-list` over querying this table directly — they handle the aggregation correctly.
+
+## Common query patterns
+
+**Top-10 slowest root spans for a service in the last hour** (convert `trace_id` to hex for display):
+
+```sql
+SELECT name, duration_nano, hex(tryBase64Decode(trace_id)) AS trace_id, timestamp
+FROM posthog.trace_spans
+WHERE service_name = 'checkout'
+ AND is_root_span
+ AND timestamp >= now() - INTERVAL 1 HOUR
+ORDER BY duration_nano DESC
+LIMIT 10
+```
+
+**Error rate per service in the last hour:**
+
+```sql
+SELECT
+ service_name,
+ countIf(status_code = 2) AS errors,
+ count() AS total,
+ errors / total AS error_rate
+FROM posthog.trace_spans
+WHERE timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY service_name
+HAVING total > 100
+ORDER BY error_rate DESC
+```
+
+**Find traces touching both `payments` and `inventory` services:**
+
+```sql
+SELECT hex(tryBase64Decode(trace_id)) AS trace_id, min(timestamp) AS started, count() AS span_count
+FROM posthog.trace_spans
+WHERE service_name IN ('payments', 'inventory')
+ AND timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY trace_id
+HAVING uniqExact(service_name) = 2
+ORDER BY started DESC
+LIMIT 20
+```
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md b/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md
index 92d522208385..7b10c27b190e 100644
--- a/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-logs.md
@@ -1,5 +1,67 @@
# Logs
+## `logs` (data plane)
+
+OpenTelemetry log entries. One row per log line. Backed by ClickHouse `logs_distributed`.
+
+**Prefer the typed tool when it fits:** `posthog:query-logs` for filtered list queries (with the encoded discovery → narrow → count → drill-down workflow). Reach for HogQL when you need cross-signal joins (with `posthog.trace_spans` or `posthog.metrics` by `trace_id`) or aggregations the typed tool doesn't expose.
+
+**Namespacing:** `logs` and `log_attributes` are registered at the HogQL root level — reference them as bare names. (Asymmetric with `posthog.trace_spans` and `posthog.metrics`, which require the `posthog.` namespace prefix.)
+
+### Columns
+
+| Column | Type | Description |
+| ----------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------- |
+| `uuid` | String | Row UUID |
+| `team_id` | Int32 | Team this log belongs to |
+| `trace_id` | String | OTel trace ID (24-char base64-encoded 16 bytes). `'AAAAAAAAAAAAAAAAAAAAAA=='` when unset, not null |
+| `span_id` | String | OTel span ID (12-char base64-encoded 8 bytes). `'AAAAAAAAAAA='` when unset |
+| `body` | String | Log message. Also exposed as `message` |
+| `severity_text` | LowCardinality(String) | `trace`, `debug`, `info`, `warn`, `error`, `fatal` |
+| `severity_number` | Int32 | OTel severity number (lower = less severe) |
+| `level` | LowCardinality(String) | Alias for `severity_text` |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `attributes` | Map(String, String) | Log-level attributes (e.g. `http.method`, `error.type`) |
+| `resource_attributes` | Map(LowCardinality(String), String) | Resource-level attributes (k8s labels, deployment info) |
+| `resource_fingerprint` | UInt64 | Hash of `resource_attributes` |
+| `instrumentation_scope` | String | Instrumentation library |
+| `event_name` | String | OTel event name (often empty) |
+| `time_bucket` | DateTime | `toStartOfDay(timestamp)` |
+| `timestamp` | DateTime64(9) | Log time |
+| `observed_timestamp` | DateTime64(9) | Ingest time |
+
+### Sort key
+
+`(team_id, service_name, toUnixTimestamp(timestamp))`. Queries that filter on `service_name` + a time window are very efficient. **Never query without a `service_name` (or `resource_attributes` filter) and a time window** — unfiltered queries can scan terabytes.
+
+### Important notes
+
+- **`trace_id` and `span_id` are base64-encoded bytes**, not hex. The displayed hex form (e.g. `21EDB3A025A9ECD32ADF3E5D7548A4F4`) comes from the API layer via `hex(tryBase64Decode(trace_id))`. Raw HogQL queries see the 24-character base64 form (e.g. `21EDB3A025A9ECD32ADF...` becomes `IepzoCWp7NMq3z5ddUik9A==`).
+- **Unset `trace_id` is `'AAAAAAAAAAAAAAAAAAAAAA=='`** (16 zero bytes encoded), not the hex zero-padded form. Use `trace_id != 'AAAAAAAAAAAAAAAAAAAAAA=='` to find logs with trace context. Or use the explicit decode: `tryBase64Decode(trace_id) != unhex('00000000000000000000000000000000')`.
+- **Use `hex(tryBase64Decode(trace_id))` to display trace_ids in hex** for human-readable output.
+- **Prefer `severity_text` over `severity_number` / `level`** for human-readable filters.
+- Cross-signal joins by `trace_id` work against `posthog.trace_spans` (both store base64) and `posthog.metrics` _once exemplar extraction is wired up in ingestion_ — see the metrics reference for the current state.
+- User HogQL queries on `logs` are capped at 50 GB read per query.
+
+## `log_attributes`
+
+AggregatingMergeTree rollup of log attribute values, partitioned by service and 10-minute bucket. Same pattern as `trace_attributes` / `metric_attributes`.
+
+| Column | Type | Description |
+| ---------------------- | ------------------------------------ | -------------------------------------------- |
+| `team_id` | Int32 | Team |
+| `time_bucket` | DateTime64(0) | 10-minute bucket |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `resource_fingerprint` | UInt64 | Resource identity hash |
+| `attribute_key` | LowCardinality(String) | Attribute name |
+| `attribute_value` | String | Attribute value |
+| `attribute_type` | LowCardinality(String) | `log` or `resource` |
+| `attribute_count` | SimpleAggregateFunction(sum, UInt64) | Number of logs where this attribute appeared |
+
+Prefer `posthog:logs-attributes-list` / `posthog:logs-attribute-values-list` over querying this table directly — they handle the aggregation correctly.
+
+---
+
## LogsView (`system.logs_views`)
Saved log views — named filter configurations that users create to quickly access frequently-used log queries.
@@ -83,6 +145,52 @@ Alerts that monitor log volume and notify users when thresholds are breached. Us
## Common Query Patterns
+### Data plane (`logs`)
+
+**Top-10 noisiest services by error log volume in the last hour:**
+
+```sql
+SELECT service_name, count() AS errors
+FROM logs
+WHERE severity_text IN ('error', 'fatal')
+ AND timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY service_name
+ORDER BY errors DESC
+LIMIT 10
+```
+
+**Logs in a specific trace** (input the hex form; convert internally):
+
+```sql
+SELECT timestamp, severity_text, service_name, body
+FROM logs
+WHERE trace_id = base64Encode(unhex('<hex_trace_id>'))
+ORDER BY timestamp
+```
+
+If you already have the trace_id in base64 form (e.g. selected directly from the table), compare it as-is:
+
+```sql
+SELECT timestamp, severity_text, service_name, body
+FROM logs
+WHERE trace_id = 'IepzoCWp7NMq3z5ddUik9A=='
+ORDER BY timestamp
+```
+
+**Logs matching a body substring on a service in a time window:**
+
+```sql
+SELECT timestamp, severity_text, body
+FROM logs
+WHERE service_name = 'api-gateway'
+ AND timestamp >= now() - INTERVAL 6 HOUR
+ AND body ILIKE '%connection refused%'
+ORDER BY timestamp DESC
+LIMIT 100
+```
+
+### Control plane
+
**List all saved log views:**
```sql
diff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md b/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md
new file mode 100644
index 000000000000..ec34e69b7d06
--- /dev/null
+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-metrics.md
@@ -0,0 +1,135 @@
+# Metrics (OpenTelemetry metric points)
+
+The `posthog.metrics` table holds OpenTelemetry metric data points from instrumented services. Each row is one observation of a metric (a counter increment, a gauge sample, or a histogram bucket).
+
+**Namespacing:** Reference this table as `posthog.metrics`, not bare `metrics` — it's registered under the `posthog.` namespace in the HogQL database (see `posthog/hogql/database/database.py`). The same applies to `posthog.metric_attributes`. Bare names fail with "Unknown table" at HogQL compile time. (Asymmetric with `logs`, which is registered at root level.)
+
+There is no typed `query-metrics` MCP tool yet — **HogQL is the primary interface for metrics**. The schema mirrors `logs` and `posthog.trace_spans` deliberately so cross-signal joins are cheap, and `trace_id` / `span_id` are first-class columns on every metric row (the OpenTelemetry exemplar pattern).
+
+> ⚠️ **Exemplar extraction is not yet wired up in the ingestion pipeline as of PR [#50936](https://github.com/PostHog/posthog/pull/50936)**. The `trace_id` and `span_id` columns exist on `posthog.metrics`, but `rust/capture-logs/src/metric_record.rs` currently ignores the `_exemplars` field (prefixed with underscore → unused). Every ingested metric row has `trace_id = ''` and `span_id = ''` today. The exemplar-based cross-signal correlation patterns documented below describe the intended capability once exemplar ingestion lands.
+
+## `posthog.metrics`
+
+OpenTelemetry metric points. One row per observation. Backed by ClickHouse `metrics1` (distributed alias `metrics`).
+
+### Columns
+
+| Column | Type | Description |
+| ------------------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
+| `uuid` | String | Row UUID |
+| `team_id` | Int32 | Team this point belongs to |
+| `trace_id` | String | OTel trace ID — exemplar trace. Empty string when no exemplar is attached |
+| `span_id` | String | OTel span ID — exemplar span |
+| `time_bucket` | DateTime | `toStartOfDay(timestamp)` — first sort key component |
+| `timestamp` | DateTime64(6) | Observation time |
+| `observed_timestamp` | DateTime64(6) | Ingest time |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `metric_name` | LowCardinality(String) | Metric name (e.g. `http.server.duration`, `process.cpu.utilization`) |
+| `metric_type` | LowCardinality(String) | `counter`, `gauge`, `histogram`, `summary` (OTel data point kind) |
+| `value` | Float64 | The metric value. For counters/gauges, the observation. For histograms, the sum |
+| `count` | UInt64 | For histograms: number of observations in this point. Defaults to 1 |
+| `histogram_bounds` | Array(Float64) | For histograms: explicit bucket boundaries |
+| `histogram_counts` | Array(UInt64) | For histograms: per-bucket counts (length = `length(histogram_bounds) + 1`) |
+| `unit` | LowCardinality(String) | OTel unit string (e.g. `ms`, `s`, `By`, `1`) |
+| `aggregation_temporality` | LowCardinality(String) | `delta` or `cumulative` (OTel temporality) |
+| `is_monotonic` | Bool | For counters: whether the counter is monotonically increasing |
+| `attributes` | Map(String, String) | Metric-point attributes (label dimensions) |
+| `resource_attributes` | Map(LowCardinality(String), String) | Resource-level attributes (k8s labels, host info) |
+| `resource_fingerprint` | UInt64 | Hash of `resource_attributes` |
+| `instrumentation_scope` | String | Instrumentation library name |
+
+### Sort key
+
+`(team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp)`. Queries that filter on `service_name` + `metric_name` + a time window are very efficient.
+
+### Per-minute aggregate projection
+
+The table has a projection `projection_aggregate_counts` that pre-aggregates by:
+
+`(team_id, time_bucket, toStartOfMinute(timestamp), service_name, metric_name, metric_type, resource_fingerprint)`
+
+with `count() AS event_count`, `sum(value) AS total_value`, `min(value) AS min_value`, `max(value) AS max_value`.
+
+**Queries that group by those exact keys hit the projection and are near-free.** Use this for sparklines, top-N services by metric value, and per-minute breakdowns. The query optimizer picks the projection automatically when the SELECT and GROUP BY match.
+
+### Important notes
+
+- **Unit is metric-dependent.** Always check `unit` — `http.server.duration` may be reported in `ms`, `s`, or `ns` depending on the SDK. Don't assume.
+- **`trace_id` is currently always empty string** because exemplar extraction isn't wired up (see warning above). The Rust ingestion uses `String::new()` for both `trace_id` and `span_id`. Filtering `trace_id != ''` correctly excludes unset rows once exemplars start landing.
+- **`trace_id` will be base64-encoded** (matching `logs` and `posthog.trace_spans`) once exemplars are populated. Joins to those tables will be direct equality on `trace_id`. Use `hex(tryBase64Decode(trace_id))` to display in hex.
+- **Histograms store `histogram_bounds` and `histogram_counts` per row** — you need to expand them for quantile estimation. For a quick p95-ish summary, `value / count` gives the mean per-point.
+- **Choose the right temporality.** `delta` metrics measure activity in the interval; `cumulative` metrics are running totals. Summing `value` over time only makes sense for `delta`.
+- User HogQL queries on `posthog.metrics` are capped at 50 GB read per query.
+
+## `posthog.metric_attributes`
+
+AggregatingMergeTree rollup of metric attribute values, partitioned by service and 10-minute bucket. Same pattern as `log_attributes` / `posthog.trace_attributes`. Same `posthog.` namespacing rule — reference as `posthog.metric_attributes`.
+
+### Columns
+
+| Column | Type | Description |
+| ---------------------- | ------------------------------------ | ----------------------------------------------------- |
+| `team_id` | Int32 | Team |
+| `time_bucket` | DateTime64(0) | 10-minute bucket |
+| `service_name` | LowCardinality(String) | Emitting service |
+| `resource_fingerprint` | UInt64 | Resource identity hash |
+| `attribute_key` | LowCardinality(String) | Attribute name |
+| `attribute_value` | String | Attribute value |
+| `attribute_type` | LowCardinality(String) | `metric` or `resource` |
+| `attribute_count` | SimpleAggregateFunction(sum, UInt64) | Number of metric points where this attribute appeared |
+
+Use this for cheap discovery of which attribute keys exist on which services.
+
+## Common query patterns
+
+**List metric names emitted by a service in the last hour:**
+
+```sql
+SELECT metric_name, metric_type, count() AS n
+FROM posthog.metrics
+WHERE service_name = 'checkout'
+ AND timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY metric_name, metric_type
+ORDER BY n DESC
+```
+
+**Per-minute mean value of a metric, broken down by service (projection-friendly):**
+
+```sql
+SELECT
+ toStartOfMinute(timestamp) AS minute,
+ service_name,
+ sum(value) / sum(count) AS mean_value
+FROM posthog.metrics
+WHERE metric_name = 'http.server.duration'
+ AND timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY minute, service_name
+ORDER BY minute, mean_value DESC
+```
+
+**Top services by counter rate in the last hour:**
+
+```sql
+SELECT service_name, sum(value) AS total
+FROM posthog.metrics
+WHERE metric_name = 'http.server.request.count'
+ AND metric_type = 'counter'
+ AND aggregation_temporality = 'delta'
+ AND timestamp >= now() - INTERVAL 1 HOUR
+GROUP BY service_name
+ORDER BY total DESC
+LIMIT 10
+```
+
+**Pick the slowest exemplar trace for a metric in a window (exemplar lookup):**
+
+```sql
+SELECT argMax(trace_id, value) AS exemplar_trace_id, max(value) AS peak
+FROM posthog.metrics
+WHERE service_name = 'checkout'
+ AND metric_name = 'http.server.duration'
+ AND timestamp >= now() - INTERVAL 10 MINUTE
+ AND trace_id != ''
+```
+
+Pair this with `posthog:apm-trace-get` (or a SQL join on `trace_spans`) to inspect the trace that drove the spike.