: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): pipe our logs services into metrics1 locally + verify script (#63123)
Daniel Visca73fc19807560
diff --git a/bin/clickhouse-metrics.sql b/bin/clickhouse-metrics.sqlindex e28982e7beb1..5f91bc019570 100644--- a/bin/clickhouse-metrics.sql+++ b/bin/clickhouse-metrics.sql@@ -262,4 +262,19 @@ ASFROM kafka_metrics_avrogroup by _partition, _topic;+-- Read aliases in the `posthog` database.+-- The product connection uses CLICKHOUSE_DATABASE=posthog and resolves the+-- bare names `metrics`, `metric_attributes`, `metrics_kafka_metrics` there,+-- while everything above lives in `default` (this script runs unqualified+-- through docker clickhouse-client). Without these aliases the product reads+-- empty same-named tables in `posthog` while data accumulates in `default`.+DROP TABLE IF EXISTS posthog.metrics1_to_metric_attributes;+DROP TABLE IF EXISTS posthog.metrics1_to_resource_attributes;+DROP TABLE IF EXISTS posthog.metrics1;+CREATE OR REPLACE TABLE posthog.metrics AS default.metrics1 ENGINE = Distributed('posthog', 'default', 'metrics1');+DROP TABLE IF EXISTS posthog.metric_attributes;+CREATE TABLE posthog.metric_attributes AS default.metric_attributes ENGINE = Distributed('posthog', 'default', 'metric_attributes');+DROP TABLE IF EXISTS posthog.metrics_kafka_metrics;+CREATE TABLE posthog.metrics_kafka_metrics AS default.metrics_kafka_metrics ENGINE = Distributed('posthog', 'default', 'metrics_kafka_metrics');+select 'clickhouse metrics tables initialised successfully!';diff --git a/bin/send-dev-metrics.sh b/bin/send-dev-metrics.shnew file mode 100755index 000000000000..a624e24bf545--- /dev/null+++ b/bin/send-dev-metrics.sh@@ -0,0 +1,161 @@+#!/usr/bin/env bash+# Smoke-test the metrics ingest chain by POSTing a synthetic OTLP payload to+# capture-logs. Same shape as nodejs/src/logs-ingestion/sampling-seed-services-curl.sh.+#+# Usage:+# # Local dev (default — same path logs scripts use):+# TOKEN=phc_yourtoken bin/send-dev-metrics.sh+# TOKEN=phc_yourtoken bin/send-dev-metrics.sh loop # send every 5s+#+# # Cloud dev via kubectl port-forward (capture-logs Service inside the cluster):+# aws login+# kubectl port-forward -n posthog svc/capture-logs 4320:4318+# ENDPOINT=http://localhost:4320/v1/metrics TOKEN=phc_yourtoken bin/send-dev-metrics.sh+#+# # Prod (once the public ingress is live):+# ENDPOINT=https://us.i.posthog.com/i/v1/metrics TOKEN=phc_yourtoken bin/send-dev-metrics.sh+# ENDPOINT=https://eu.i.posthog.com/i/v1/metrics TOKEN=phc_yourtoken bin/send-dev-metrics.sh+set -euo pipefail++# Default to the same local-OTel-collector endpoint the logs seed scripts use.+# `otel-collector-config.dev.yaml` routes /v1/metrics to capture-logs:4320 internally.+ENDPOINT="${ENDPOINT:-http://localhost:4318/v1/metrics}"+TOKEN="${TOKEN:-}"++if [ -z "$TOKEN" ]; then+ echo "Set TOKEN=phc_... (project API token — for local dev, any phc_... from your local project works)" >&2+ exit 1+fi++TRACE_ID="${TRACE_ID:-$(openssl rand -hex 16)}"+SPAN_ID="${SPAN_ID:-$(openssl rand -hex 8)}"+SUFFIX="${METRIC_SUFFIX:-$(date +%s)}"++send_one() {+ local now_ns=$(($(date +%s) * 1000000000))+ local body+ body=$(cat <<EOF+{+ "resourceMetrics": [{+ "resource": {"attributes": [+ {"key":"service.name","value":{"stringValue":"e2e-dev-test"}},+ {"key":"deployment.environment","value":{"stringValue":"dev"}}+ ]},+ "scopeMetrics": [{+ "scope": {"name":"send-dev-metrics-sh","version":"v1"},+ "metrics": [+ {+ "name": "e2e_dev_test_counter",+ "unit": "1",+ "sum": {+ "aggregationTemporality": 2,+ "isMonotonic": true,+ "dataPoints": [{+ "timeUnixNano": "${now_ns}",+ "asDouble": 42.0,+ "attributes": [{"key":"endpoint","value":{"stringValue":"/api/test"}}],+ "exemplars": [{+ "timeUnixNano": "${now_ns}",+ "asDouble": 42.0,+ "traceId": "${TRACE_ID}",+ "spanId": "${SPAN_ID}"+ }]+ }]+ }+ },+ {+ "name": "e2e_dev_test_gauge",+ "unit": "By",+ "gauge": {+ "dataPoints": [{+ "timeUnixNano": "${now_ns}",+ "asDouble": $((RANDOM % 1000)),+ "attributes": [{"key":"host","value":{"stringValue":"host-1"}}]+ }]+ }+ },+ {+ "name": "e2e_dev_test_histogram",+ "unit": "ms",+ "histogram": {+ "aggregationTemporality": 2,+ "dataPoints": [{+ "timeUnixNano": "${now_ns}",+ "count": 100,+ "sum": 12345.67,+ "bucketCounts": [10, 30, 40, 15, 5],+ "explicitBounds": [10, 50, 100, 500],+ "attributes": [{"key":"route","value":{"stringValue":"/api/x"}}],+ "exemplars": [{+ "timeUnixNano": "${now_ns}",+ "asDouble": 42.0,+ "traceId": "${TRACE_ID}",+ "spanId": "${SPAN_ID}"+ }]+ }]+ }+ }+ ]+ }]+ }]+}+EOF+)+ printf "→ POST %s ... " "$ENDPOINT"+ local http+ http=$(curl -sS -o /tmp/send-dev-metrics.out -w "%{http_code}" \+ -X POST "$ENDPOINT" \+ -H "Authorization: Bearer ${TOKEN}" \+ -H "Content-Type: application/json" \+ --data-binary "$body")+ printf "%s\n" "$http"+ if [ "$http" = "302" ]; then+ echo " ⚠️ 302 — endpoint is behind an auth proxy (e.g. cloud dev's Cognito ALB). Use a port-forward or local endpoint instead. See script header." >&2+ return 1+ fi+ if [ "$http" = "000" ] || [ "$http" = "" ]; then+ echo " ⚠️ Could not reach $ENDPOINT — is your local OTel collector / capture-logs running? (\`hogli start\`)" >&2+ return 1+ fi+ if [ "$http" != "200" ] && [ "$http" != "202" ]; then+ echo " Response body:" >&2+ cat /tmp/send-dev-metrics.out >&2+ echo >&2+ return 1+ fi+ return 0+}++case "${1:-once}" in+ once)+ send_one+ echo+ echo "trace_id: ${TRACE_ID}"+ echo "span_id: ${SPAN_ID}"+ echo+ echo "Verify in the dev PostHog SQL editor:"+ echo+ cat <<SQL+ SELECT metric_name, value, service_name, metric_type,+ trace_id, hex(tryBase64Decode(trace_id)) AS trace_id_hex,+ span_id, timestamp+ FROM posthog.metrics+ WHERE metric_name LIKE 'e2e_dev_test_%'+ AND timestamp >= now() - INTERVAL 5 MINUTE+ ORDER BY timestamp DESC+ LIMIT 10+ FORMAT Vertical+SQL+ ;;+ loop)+ echo "Sending every 5s (Ctrl-C to stop)..."+ while true; do+ send_one || true+ sleep 5+ done+ ;;+ *)+ echo "Usage: TOKEN=phc_... $0 [once|loop]" >&2+ exit 2+ ;;+esacdiff --git a/bin/verify-metrics-pipe b/bin/verify-metrics-pipenew file mode 100755index 000000000000..fe9b09d2ee52--- /dev/null+++ b/bin/verify-metrics-pipe@@ -0,0 +1,82 @@+#!/usr/bin/env bash+# Verify the local metrics pipe end to end.+#+# Confirms that PostHog's own logs/metrics ingestion services (scraped by the+# dev otel-collector, see otel-collector-config.dev.yaml) have landed in+# ClickHouse and are queryable through the same table the product reads:+# `posthog.metrics` (the Distributed alias over the local storage table).+# Always database-qualify here — the docker clickhouse-client defaults to the+# `default` database, which is NOT what the product connection uses.+#+# Prereqs: `hogli start` with the `metrics` intent running (capture-logs,+# ingestion-metrics, ingestion-logs, clickhouse), and the dev otel-collector+# container up (it's part of docker-compose.dev.yml).+#+# Usage: bin/verify-metrics-pipe+set -euo pipefail++CH_CONTAINER="${CH_CONTAINER:-posthog-clickhouse-1}"+LOOKBACK="${LOOKBACK:-10 MINUTE}"++# LOOKBACK is interpolated into SQL — only accept "<n> <unit>".+if ! [[ "$LOOKBACK" =~ ^[0-9]+\ (SECOND|MINUTE|HOUR|DAY)$ ]]; then+ echo "✗ Invalid LOOKBACK '${LOOKBACK}' — use e.g. '10 MINUTE', '2 HOUR'." >&2+ exit 1+fi++ch() {+ # Prefer a host clickhouse-client; fall back to docker exec into the dev CH.+ if command -v clickhouse-client >/dev/null 2>&1; then+ clickhouse-client -h localhost --query "$1"+ else+ docker exec -i "$CH_CONTAINER" clickhouse-client --query "$1"+ fi+}++echo "→ Checking posthog.metrics for piped PostHog service metrics (last ${LOOKBACK})…"+echo++# `|| true`: a failing query (CH down, tables missing) must fall through to+# the troubleshooting message below instead of tripping set -e.+ROWS=$(ch "+ SELECT service_name, count() AS samples, uniq(metric_name) AS metric_names+ FROM posthog.metrics+ WHERE timestamp > now() - INTERVAL ${LOOKBACK}+ AND service_name IN ('logs-ingestion', 'metrics-ingestion', 'nodejs')+ GROUP BY service_name+ ORDER BY samples DESC+ FORMAT TSV+" || true)++if [ -z "$ROWS" ]; then+ cat <<'MSG'+✗ No PostHog service metrics found in posthog.metrics yet.++Check, in order:+ 1. Is the stack up with the `metrics` intent? hogli dev:setup → metrics+ 2. Is the dev otel-collector running? docker ps | grep otel-collector-local+ 3. Are the ingestion services exposing /_metrics?+ curl -s localhost:6743/_metrics | head # logs-ingestion+ curl -s localhost:6744/_metrics | head # metrics-ingestion+ 4. Is capture-logs receiving? docker logs capture-logs | tail+ 5. Were the CH tables initialised? bin/clickhouse-metrics-init+ 6. Give it ~30s after start (15s scrape + ingest lag), then re-run.+MSG+ exit 1+fi++printf 'service_name\tsamples\tmetric_names\n'+echo "$ROWS"+echo+echo "→ Ingestion-lag metrics (the on-call signal this pipe exists for):"+ch "+ SELECT service_name, metric_name, max(timestamp) AS latest, argMax(value, timestamp) AS latest_value+ FROM posthog.metrics+ WHERE timestamp > now() - INTERVAL ${LOOKBACK}+ AND metric_name IN ('metrics_rate_limiter_message_lag_seconds', 'logs_rate_limiter_message_lag_seconds')+ GROUP BY service_name, metric_name+ ORDER BY service_name, metric_name+ FORMAT Vertical+"+echo+echo "✓ Metrics pipe is live. Open /metrics (Viewer or SQL tab) to explore."diff --git a/docs/internal/metrics/deployment-layout.md b/docs/internal/metrics/deployment-layout.mdindex fb001bb43d47..1c392a7c720b 100644--- a/docs/internal/metrics/deployment-layout.md+++ b/docs/internal/metrics/deployment-layout.md@@ -80,16 +80,15 @@ Legend: ✅ live · ⏳ in-flight (PR) · ➕ this stack adds it · — n/a## Local validation (the priority) — fully functional metrics on a laptop-No charts/cloud-infra needed locally. The `metrics` dev intent boots the whole pipe.+No charts/cloud-infra needed locally. The `metrics` dev intent boots the whole pipe, and the dev `otel-collector` container **already scrapes our logs services and pushes them into `metrics1`** — no manual collector to run.-1. `hogli dev:setup` → select the **`metrics`** intent (boots `capture-logs`, `ingestion-metrics`, deps; `metrics1` created by CH bootstrap). `hogli start`.+1. `hogli dev:setup` → select the **`metrics`** intent (boots `capture-logs`, `ingestion-metrics`, `ingestion-logs`, the dev `otel-collector`, 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.+3. Real PostHog logs services pipe through automatically: the dev collector (`otel-collector-config.dev.yaml`) scrapes `/_metrics` on `logs-ingestion` (`:6743`), `metrics-ingestion` (`:6744`), and the plugin server (`:6738`) every 15s and exports OTLP to `capture-logs` (token `phc_local` → team*id 1). Their `prom-client` counters (`logs_ingestion*_`, `metrics*ingestion*_`, consumer lag, batch utilization) are exactly the Grafana logs-dashboard metrics.+4. Validate:+ - `bin/verify-metrics-pipe` — checks `metrics1` for the piped service metrics and prints what arrived (pass/fail with troubleshooting).+ - `/metrics` SQL tab: `SELECT metric_name, count() FROM posthog.metrics WHERE service_name = 'logs-ingestion' GROUP BY 1 ORDER BY 2 DESC` (note: data lands on **team_id 1** via `phc_local`).+ - `/metrics` Viewer: the query layer (filters/group-by/rate/histogram_quantile) against the same data.Ad-hoc seed without the pipe (no PRs needed):diff --git a/hogli.yaml b/hogli.yamlindex 5942690bb901..726619fe4133 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1031,3 +1031,11 @@ environment:bin_script: build-dashboard-widget-types.pydescription: Widget enum preflight, date options, and form-field manifest codegenhidden: true+ verify:metrics:pipe:+ bin_script: verify-metrics-pipe+ description: 'Verify the local metrics pipe reached ClickHouse metrics1'+ hidden: true+ send:dev:metrics:+ bin_script: send-dev-metrics.sh+ description: 'Send a synthetic OTLP counter/gauge/histogram through the metrics ingest chain'+ hidden: truediff --git a/otel-collector-config.dev.yaml b/otel-collector-config.dev.yamlindex 873c353c386a..3e8758474ce1 100644--- a/otel-collector-config.dev.yaml+++ b/otel-collector-config.dev.yaml@@ -62,6 +62,27 @@ receivers:metrics_path: /_metricsstatic_configs:- targets: ['host.docker.internal:6738']+ # PostHog's own logs/metrics ingestion services. Their+ # prom-client counters (logs_ingestion_*, metrics_ingestion_*,+ # consumer lag, batch utilization) are exactly the metrics the+ # Grafana logs dashboard charts — scraping them here pipes a+ # real PostHog service through the metrics product locally, so+ # they're queryable in /metrics. Ports match HTTP_SERVER_PORT+ # in bin/mprocs.yaml (ingestion-logs 6743, ingestion-metrics+ # 6744). Targets that aren't running are simply scraped-down.+ # The job_name becomes the row's service_name downstream (the+ # receiver maps it to the service.name resource attribute);+ # static_configs labels can NOT override it.+ - job_name: 'logs-ingestion'+ scrape_interval: 15s+ metrics_path: /_metrics+ static_configs:+ - targets: ['host.docker.internal:6743']+ - job_name: 'metrics-ingestion'+ scrape_interval: 15s+ metrics_path: /_metrics+ static_configs:+ - targets: ['host.docker.internal:6744']exporters:otlp: # Using the standard OTLP exporter