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.

feat(metrics): deployment docs, attribute seam, query contracts (#63122)

Daniel Visca201439cb7938
diff --git a/docs/internal/metrics/deployment-layout.md b/docs/internal/metrics/deployment-layout.md
new file mode 100644
index 000000000000..fb001bb43d47
--- /dev/null
+++ b/docs/internal/metrics/deployment-layout.md
@@ -0,0 +1,106 @@
+# Metrics — deployment layout (local / dev / prod-us / prod-eu / charts)
+
+Companion to [`dashboard-mvp.md`](./dashboard-mvp.md). This is the "what has to exist where" checklist for metrics to be fully functional, plus the schema decision.
+
+## Schema decision (settled)
+
+**Alpha ships on the current `metrics1` table.** The streams-table layout (Snuffle's default schema: `metrics_series` id→labels + `metrics_samples` id,ts,value + inverted `metrics_label_index`) is the **post-alpha storage track**, not a blocker.
+
+Why this is safe and correct for a days-to-alpha timeline:
+
+- Snuffle's `create_metrics_posthog_schema.sql` is **our current `metrics1` verbatim** — Rory built his PromQL bridge to read our existing table. So prom-compat works against `metrics1` as-is; we lose nothing by not migrating first.
+- The streams layout is the _eventual_ target (Snuffle benchmarks ~89.5% less disk, ~31→3 bytes/sample) but it changes the ingestion write path + adds a backfill — too much risk to land under an alpha deadline.
+- The `attribute_field()` helper (P0) is the migration seam: when storage moves to streams, only that one function changes, not every query call site.
+
+**Action when we do the storage track:** model `metrics_series` keyed by a full series fingerprint — Snuffle computes it as `cityHash64(metric_name, service_name, mapSort(resource_attributes), mapSort(attributes_map_str))`. We already materialize a partial `resource_fingerprint = cityHash64(resource_attributes)` on `metrics1`; the full series identity adds metric_name + service_name + sorted data-point attributes.
+
+## The full data path (all environments)
+
+```text
+producers ─► capture-logs /i/v1/metrics ─► Kafka (WarpStream "metrics") ─► metrics-ingestion consumer ─► ClickHouse metrics1 (logs cluster)
+ │ │
+ ├─ app SDKs (OTLP, customer traffic) ▼
+ └─ infra/service metrics via vmagent ─► otel-collector bridge (prometheusremotewrite→OTLP) products/metrics (HogQL) + prom-compat (PromQL)
+```
+
+Two producer classes:
+
+1. **Customer OTLP** — apps push OTLP straight to `/i/v1/metrics`. Already works in every env where the ingest path is live.
+2. **Our own infra/service metrics** — vmagent already scrapes them; the otel-collector bridge (INFRA-A) fans a copy into `/i/v1/metrics`. This is the "pipe our logs services through" path.
+
+## Status matrix — what exists where
+
+Legend: ✅ live · ⏳ in-flight (PR) · ➕ this stack adds it · — n/a
+
+| Layer | local | dev | prod-us | prod-eu | Where it lives |
+| -------------------------------------------------------- | ----------------- | ----------------- | ------------- | ------------- | ---------------------------------------------- |
+| Kafka topics (`ingestion_metrics`, `clickhouse_metrics`) | ✅ (compose) | ✅ | ✅ | ✅ | cloud-infra #8321 |
+| WarpStream metrics cluster + S3 + IRSA | — | ✅ | ⏳ | ⏳ | charts `warpstream-metrics`; cloud-infra #8322 |
+| CH named collection `warpstream_metrics` | — | ✅ | ✅ | ✅ | cloud-infra #8415/#8489 |
+| metrics-ingestion Postgres app user | ✅ | ✅ | ✅ | ✅ | cloud-infra #8434 |
+| capture-logs `kafka.metricsBrokers`/`metricsTopic` | ✅ (compose) | ✅ | ⏳ | ⏳ | charts `capture-logs` (global in rollout) |
+| Contour ingress `/i/v1/metrics` | ✅ (caddy) | ✅ | ⏳ | ⏳ | charts `contour-ingress` |
+| metrics-ingestion consumer deploy | ✅ (mprocs) | ✅ | ⏳ | ⏳ | charts `logs/metrics-ingestion` |
+| ClickHouse `metrics1` + MVs | ✅ (CH bootstrap) | ✅ | ⏳ direct SQL | ⏳ direct SQL | `posthog/clickhouse/metrics/` |
+| **otel-collector bridge** (infra→metrics1) | ➕ local recipe | ➕ INFRA-A #11808 | ➕ INFRA-D | ➕ INFRA-D | charts `otel-collector` + `vmagent` |
+| Rate-limit/quota exemption for internal-infra token | — | ➕ INFRA-B | ➕ INFRA-D | ➕ INFRA-D | `nodejs/.../metrics-rate-limiter.service.ts` |
+| Feature flag `METRICS` + `metrics:read` scope | ✅ code | ✅ code | ✅ code | ✅ code | posthog repo (all envs share) |
+| Query layer (filters/group-by/rate/hist/formula) | ➕ this stack | ➕ | ➕ | ➕ | `products/metrics/backend` |
+
+**Read:** the ingestion data plane is **done in dev**, and **pending in prod** behind `daniel/metrics-prod-rollout` (charts) + the post-merge `metrics1` SQL apply on the prod-us/prod-eu logs CH clusters. cloud-infra scaffolding (topics/S3/IRSA/CH collection/PG user) is **merged in all three envs**.
+
+## What still has to be added, by repo
+
+### posthog (this stack)
+
+- Query layer: `MetricQueryRequest`/`MetricSeries` contracts → endpoint → shared metric-math library (filters, group-by, rate, increase, histogram_quantile, formula). **This is the product gap; nothing else replaces it.**
+- INFRA-B: internal-infra token quota exemption in `MetricsRateLimiterService`.
+- (Post-alpha) Alerting on the shared math library; streams-table storage migration.
+
+### charts
+
+- INFRA-A (#11808, dev): otel-collector `prometheusremotewrite` bridge + vmagent second remote-write. **Draft up.**
+- INFRA-C (dev): drop the `debug` exporter once metrics1 arrival is confirmed.
+- INFRA-D (prod-us + prod-eu): replicate the bridge after `metrics-prod-rollout` merges and prod `metrics1` SQL is applied. Decide internal-infra project here.
+- INFRA-E: broaden the bridge filter beyond the initial dashboard metric set once the query layer can render more.
+- (Merge) `daniel/metrics-prod-rollout`: takes the ingestion data plane to prod-us + prod-eu.
+
+### posthog-cloud-infra
+
+- **Nothing new required** for alpha — topics/S3/IRSA/CH collection/PG user are all merged in every env.
+- Open decision (INFRA-D): provision a dedicated `posthog-internal-infra` project + token per env so scraped infra metrics don't flip `team_has_metrics` on the dogfood team and so internal-infra volume is billed/quota'd separately.
+
+### Per-env "go live" checklist for prod
+
+1. Merge `daniel/metrics-prod-rollout` (charts).
+2. Apply `metrics1` + MV DDL to prod-us and prod-eu logs CH clusters (direct SQL, as in dev).
+3. Point a smoke OTLP producer at the prod `/i/v1/metrics`; confirm rows in `metrics1`.
+4. Land INFRA-D (bridge) per env; confirm vmagent → bridge → metrics1 for the dashboard metric set.
+5. Verify `team_has_metrics` + the query layer against real prod series.
+
+## Local validation (the priority) — fully functional metrics on a laptop
+
+No charts/cloud-infra needed locally. The `metrics` dev intent boots the whole pipe.
+
+1. `hogli dev:setup` → select the **`metrics`** intent (boots `capture-logs`, `ingestion-metrics`, deps; `metrics1` created by CH bootstrap). `hogli start`.
+2. Enable the `metrics` feature flag for your user.
+3. Pipe a real PostHog logs service through (its `prom-client` metrics):
+ - `logs-ingestion` exposes `/_metrics` on `:6743`; `metrics-ingestion` on `:6744`.
+ - Run the local OTel collector recipe (see `bin/`/docker-compose profile added by the "local pipe" task) to scrape `:6743` and push OTLP to `http://localhost:8010/i/v1/metrics` with the project-2 capture token.
+4. Search/validate:
+ - `/metrics` SQL tab: `SELECT metric_name, count() FROM posthog.metrics WHERE metric_name ILIKE '%logs_ingestion%' GROUP BY 1 ORDER BY 2 DESC`
+ - `/metrics` Viewer: the new query layer (filters/group-by/rate/histogram_quantile) against the same data.
+
+Ad-hoc seed without the pipe (no PRs needed):
+
+```bash
+clickhouse-client -h localhost --query "
+INSERT INTO metrics1 (uuid, team_id, timestamp, service_name, metric_name, metric_type, value, attributes_map_str, resource_attributes)
+SELECT generateUUIDv4(), 2, now() - INTERVAL number SECOND, 'logs-ingestion', 'logs_ingestion_bytes_received_total', 'sum',
+ toFloat64(number * 1024),
+ map('container_str','logs-ingestion','team_id_str','2'),
+ map('namespace','posthog')
+FROM numbers(3600)"
+```
+
+(`team_has_metrics` caches for 7 days — after wiping CH, `cache.delete("team:2:has_metrics")`.)
diff --git a/products/metrics/backend/facade/contracts.py b/products/metrics/backend/facade/contracts.py
index 7b522e751e6e..da6adedf74d1 100644
--- a/products/metrics/backend/facade/contracts.py
+++ b/products/metrics/backend/facade/contracts.py
@@ -10,4 +10,106 @@ Characteristics:
- Used by facade as inputs/outputs
Do NOT depend on Django models, DRF serializers, or request objects.
+
+These define the query wire shape used by the viewer, the dashboard
+widget, and (later) alerting. The response is always a list of
+`MetricSeries` — a single ungrouped query returns one series with empty
+labels, so consumers never branch on "single vs multi series".
"""
+
+from __future__ import annotations
+
+import datetime as dt
+from dataclasses import dataclass
+
+from .enums import AttributeScope, FilterOp, MetricAggregation
+
+
+@dataclass(frozen=True, slots=True)
+class MetricFilter:
+ """A single label predicate on a clause."""
+
+ key: str
+ op: FilterOp
+ value: str
+ scope: AttributeScope = AttributeScope.AUTO
+
+
+@dataclass(frozen=True, slots=True)
+class MetricGroupBy:
+ """One label to split a clause's result into separate series by."""
+
+ key: str
+ scope: AttributeScope = AttributeScope.AUTO
+
+
+@dataclass(frozen=True, slots=True)
+class MetricQueryClause:
+ """One metric selection: a name, an aggregation, and optional
+ filters / group-by. `name` is the alias a formula refers to (e.g. "a").
+ """
+
+ name: str
+ metric_name: str
+ aggregation: MetricAggregation
+ filters: tuple[MetricFilter, ...] = ()
+ group_by: tuple[MetricGroupBy, ...] = ()
+ # Required for QUANTILE / HISTOGRAM_QUANTILE; ignored otherwise.
+ quantile: float | None = None
+
+ def __post_init__(self) -> None:
+ if self.aggregation.needs_quantile:
+ if self.quantile is None:
+ raise ValueError(f"{self.aggregation} requires a quantile")
+ if not 0.0 < self.quantile < 1.0:
+ raise ValueError("quantile must be in (0, 1)")
+ if not self.name:
+ raise ValueError("clause name must be non-empty")
+
+
+@dataclass(frozen=True, slots=True)
+class MetricQueryRequest:
+ """A whole metric query: one or more clauses over a shared time grid,
+ with an optional formula combining them by clause name.
+
+ `interval` is on the request (not per clause) so every series in the
+ response shares one bucket grid — required for a formula like "a / b"
+ to align, and the right default anyway. None means auto-pick from the
+ range.
+ """
+
+ clauses: tuple[MetricQueryClause, ...]
+ date_from: dt.datetime
+ date_to: dt.datetime
+ interval: str | None = None
+ formula: str | None = None
+
+ def __post_init__(self) -> None:
+ if not self.clauses:
+ raise ValueError("at least one clause is required")
+ if self.date_to <= self.date_from:
+ raise ValueError("date_to must be after date_from")
+ names = [c.name for c in self.clauses]
+ if len(names) != len(set(names)):
+ raise ValueError("clause names must be unique")
+
+
+@dataclass(frozen=True, slots=True)
+class MetricPoint:
+ """One bucketed datapoint. `time` is the bucket start, ISO 8601."""
+
+ time: str
+ value: float
+
+
+@dataclass(frozen=True, slots=True)
+class MetricSeries:
+ """One line on a chart: the label values that identify it plus its
+ points. `labels` is empty for an ungrouped query. `clause` records
+ which clause produced it (the formula result uses `clause="formula"`).
+ """
+
+ labels: dict[str, str]
+ points: tuple[MetricPoint, ...]
+ metric_name: str | None = None
+ clause: str | None = None
diff --git a/products/metrics/backend/facade/enums.py b/products/metrics/backend/facade/enums.py
index 81ca0757deea..8b48bee9e367 100644
--- a/products/metrics/backend/facade/enums.py
+++ b/products/metrics/backend/facade/enums.py
@@ -1,13 +1,72 @@
"""
Exported enums and constants for metrics.
-Small products can keep enums in contracts.py instead. Split
-into this file when contracts.py gets crowded.
+These appear in the contract dataclasses (contracts.py) and are the
+vocabulary other products / the presentation layer use to build metric
+queries. Framework-free: no Django, no DRF.
+"""
-Rule: if an enum appears in a contract dataclass field, it
-belongs here (or in contracts.py). Shared types that other
-products need to interpret contract objects also belong here.
+from __future__ import annotations
-Internal-only constants (DB magic values, feature flags, etc.)
-should stay in the implementation (logic.py, models.py).
-"""
+from enum import StrEnum
+
+
+class AttributeScope(StrEnum):
+ """Where a label lives on a `metrics1` row.
+
+ - RESOURCE: `resource_attributes` (set once per scrape target, e.g.
+ `service.name`, `k8s.pod.name`).
+ - ATTRIBUTE: per-data-point `attributes` (the alias that strips the
+ 5-char `_str` type tag, e.g. `http.method`).
+ - AUTO: resource first, fall back to attribute. ClickHouse map lookups
+ return '' for missing keys, so the fallback compares against '' — you
+ cannot meaningfully match "equals empty string" in AUTO scope; use an
+ explicit scope for that edge case.
+ """
+
+ RESOURCE = "resource"
+ ATTRIBUTE = "attribute"
+ AUTO = "auto"
+
+
+class FilterOp(StrEnum):
+ """Comparison operators for a label filter."""
+
+ EQ = "eq"
+ NEQ = "neq"
+ REGEX = "regex"
+ NOT_REGEX = "not_regex"
+
+
+class MetricAggregation(StrEnum):
+ """How a clause collapses the values in each time bucket into one number.
+
+ Instant aggregations operate on the values that fell in the bucket:
+ SUM, AVG, COUNT, MIN, MAX, QUANTILE.
+
+ Counter functions operate on the change across the bucket (cumulative
+ counters get reset-corrected; deltas are summed): RATE, INCREASE.
+
+ HISTOGRAM_QUANTILE reads the `histogram_bounds`/`histogram_counts`
+ arrays rather than the scalar `value`.
+
+ QUANTILE and HISTOGRAM_QUANTILE require the clause's `quantile` field.
+ """
+
+ SUM = "sum"
+ AVG = "avg"
+ COUNT = "count"
+ MIN = "min"
+ MAX = "max"
+ QUANTILE = "quantile"
+ RATE = "rate"
+ INCREASE = "increase"
+ HISTOGRAM_QUANTILE = "histogram_quantile"
+
+ @property
+ def needs_quantile(self) -> bool:
+ return self in (MetricAggregation.QUANTILE, MetricAggregation.HISTOGRAM_QUANTILE)
+
+ @property
+ def is_counter_function(self) -> bool:
+ return self in (MetricAggregation.RATE, MetricAggregation.INCREASE)
diff --git a/products/metrics/backend/tests/test_contracts.py b/products/metrics/backend/tests/test_contracts.py
new file mode 100644
index 000000000000..301fd2d4e7f8
--- /dev/null
+++ b/products/metrics/backend/tests/test_contracts.py
@@ -0,0 +1,96 @@
+import datetime as dt
+
+import pytest
+
+from products.metrics.backend.facade.contracts import (
+ MetricFilter,
+ MetricGroupBy,
+ MetricPoint,
+ MetricQueryClause,
+ MetricQueryRequest,
+ MetricSeries,
+)
+from products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation
+
+
+def _clause(**overrides) -> MetricQueryClause:
+ base = {"name": "a", "metric_name": "m", "aggregation": MetricAggregation.SUM}
+ return MetricQueryClause(**{**base, **overrides})
+
+
+class TestMetricQueryClause:
+ def test_minimal_clause(self):
+ clause = _clause()
+ assert clause.filters == ()
+ assert clause.group_by == ()
+ assert clause.quantile is None
+
+ def test_quantile_aggregation_requires_quantile(self):
+ with pytest.raises(ValueError):
+ _clause(aggregation=MetricAggregation.QUANTILE)
+ with pytest.raises(ValueError):
+ _clause(aggregation=MetricAggregation.HISTOGRAM_QUANTILE)
+
+ def test_quantile_must_be_in_open_unit_interval(self):
+ for bad in (0.0, 1.0, -0.1, 1.5):
+ with pytest.raises(ValueError):
+ _clause(aggregation=MetricAggregation.QUANTILE, quantile=bad)
+ assert _clause(aggregation=MetricAggregation.QUANTILE, quantile=0.95).quantile == 0.95
+
+ def test_empty_name_rejected(self):
+ with pytest.raises(ValueError):
+ _clause(name="")
+
+
+class TestMetricQueryRequest:
+ def _req(self, **overrides) -> MetricQueryRequest:
+ now = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.UTC)
+ base = {
+ "clauses": (_clause(),),
+ "date_from": now - dt.timedelta(hours=1),
+ "date_to": now,
+ }
+ return MetricQueryRequest(**{**base, **overrides})
+
+ def test_minimal_request(self):
+ req = self._req()
+ assert req.interval is None
+ assert req.formula is None
+
+ def test_requires_at_least_one_clause(self):
+ now = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.UTC)
+ with pytest.raises(ValueError):
+ MetricQueryRequest(clauses=(), date_from=now - dt.timedelta(hours=1), date_to=now)
+
+ def test_rejects_inverted_range(self):
+ now = dt.datetime(2026, 1, 1, 12, 0, 0, tzinfo=dt.UTC)
+ with pytest.raises(ValueError):
+ MetricQueryRequest(clauses=(_clause(),), date_from=now, date_to=now - dt.timedelta(hours=1))
+
+ def test_rejects_duplicate_clause_names(self):
+ with pytest.raises(ValueError):
+ self._req(clauses=(_clause(name="a"), _clause(name="a", metric_name="other")))
+
+ def test_allows_distinct_clause_names_for_formula(self):
+ req = self._req(
+ clauses=(_clause(name="a"), _clause(name="b", metric_name="other")),
+ formula="a / b",
+ )
+ assert req.formula == "a / b"
+
+
+class TestFiltersAndGroupBy:
+ def test_filter_defaults_to_auto_scope(self):
+ f = MetricFilter(key="container", op=FilterOp.EQ, value="logs-ingestion")
+ assert f.scope == AttributeScope.AUTO
+
+ def test_group_by_explicit_scope(self):
+ g = MetricGroupBy(key="service_name", scope=AttributeScope.RESOURCE)
+ assert g.scope == AttributeScope.RESOURCE
+
+
+class TestMetricSeries:
+ def test_ungrouped_series_has_empty_labels(self):
+ series = MetricSeries(labels={}, points=(MetricPoint(time="2026-01-01T00:00:00", value=1.0),))
+ assert series.labels == {}
+ assert series.points[0].value == 1.0