: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): add deployable prometheus scrape agent image (#73376)
Daniel Viscac1c720ec35da
diff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex a159fd1a03dd..bc9b5f8dd5f9 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -119,6 +119,7 @@"services/mcp/worker-configuration.d.ts","frontend/src/taxonomy/core-filter-definitions-by-group.json","products/review_hog/backend/reviewer/prompts/**/schema.json",+ "products/metrics/agent/tests/**/golden/**","frontend/dist/","frontend/**/*LogicType.ts","bin/validate-setup-tasks.mjs",diff --git a/products/metrics/agent/Dockerfile b/products/metrics/agent/Dockerfilenew file mode 100644index 000000000000..fd5788582c8f--- /dev/null+++ b/products/metrics/agent/Dockerfile@@ -0,0 +1,16 @@+# PostHog metrics agent: scrapes Prometheus /metrics endpoints in your infra+# and forwards them to PostHog as OTLP metrics (exemplars included).+#+# The upstream collector image has no shell, so the collector binary is+# re-based onto alpine to support the config-rendering entrypoint.+# Keep the collector version in sync with tests/integration/docker-compose.yml.+FROM otel/opentelemetry-collector-contrib:0.142.0@sha256:38c349c3b7a2fd7ea46700cde8fa13d35b699ef2ce245bdf34dae2a413512f76 AS collector++FROM alpine:3.21@sha256:48b0309ca019d89d40f670aa1bc06e426dc0931948452e8491e3d65087abc07d+RUN apk add --no-cache ca-certificates && adduser -D -u 10001 otel+COPY --from=collector /otelcol-contrib /usr/local/bin/otelcol-contrib+COPY config/config.yaml.tmpl /etc/posthog/config.yaml.tmpl+COPY entrypoint.sh /entrypoint.sh+USER 10001+EXPOSE 13133+ENTRYPOINT ["/entrypoint.sh"]diff --git a/products/metrics/agent/README.md b/products/metrics/agent/README.mdnew file mode 100644index 000000000000..73f569dbae20--- /dev/null+++ b/products/metrics/agent/README.md@@ -0,0 +1,89 @@+# PostHog metrics agent++A small deployable image that scrapes the Prometheus `/metrics` endpoints you already expose and forwards them to PostHog as OTLP metrics.+Use it when you want PostHog Metrics without touching application code: no PostHog SDK, no exporter changes.++Under the hood it is the OpenTelemetry Collector (contrib distribution, pinned) with a PostHog-rendered config:+prometheus receiver → memory_limiter + batch → otlphttp exporter pointed at PostHog ingestion.+Exemplars survive the trip: counters and histograms scraped with OpenMetrics exemplars (`trace_id`/`span_id`) become clickable trace links in the PostHog Metrics UI.++## Quickstart (Docker)++```sh+docker run -d --name posthog-metrics-agent \+ -e POSTHOG_API_KEY=<your project API key> \+ -e POSTHOG_HOST=https://us.i.posthog.com \+ -e SCRAPE_TARGETS=your-app:9090,your-worker:9091 \+ posthog/metrics-agent:latest+```++EU cloud: set `POSTHOG_HOST=https://eu.i.posthog.com`.++## Environment variables++| Variable | Required | Default | Meaning |+| --------------------- | -------- | -------------------------- | ---------------------------------------------------------------------- |+| `POSTHOG_API_KEY` | yes | — | Project API key, sent as `Authorization: Bearer` |+| `POSTHOG_HOST` | no | `https://us.i.posthog.com` | PostHog ingestion origin |+| `SCRAPE_TARGETS` | yes\* | — | Comma-separated `host:port` list to scrape |+| `SCRAPE_INTERVAL` | no | `15s` | Scrape interval |+| `SCRAPE_METRICS_PATH` | no | `/metrics` | Metrics path on the targets |+| `SCRAPE_JOB_NAME` | no | `posthog-metrics-agent` | Prometheus job name; becomes `service_name` on every metric in PostHog |+| `POSTHOG_DEBUG` | no | unset | `1`/`true`: also log exported batches to the container's stdout |+| `POSTHOG_INGEST_PATH` | no | `/i/v1/metrics` | Advanced: override the ingest route (used by tests) |++\* not required when you mount your own scrape configs, see below.++## Escape hatches++Checked in this order:++1. **Full config override**: mount a complete collector config at `/etc/posthog/config.yaml`. It is used verbatim (`${env:POSTHOG_API_KEY}`-style references still resolve). This is how the Helm chart drives the image.+2. **Custom scrape configs**: mount a YAML list of Prometheus `scrape_configs` at `/etc/posthog/scrape_configs.yaml` to replace the env-generated job while keeping the PostHog exporter wiring. Tip: add `scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]` to each job so exemplars keep flowing.+3. Otherwise the scrape job is rendered from `SCRAPE_TARGETS`.++## Exemplars (metric ↔ trace linking)++- The agent scrapes with OpenMetrics negotiation enabled, which is the only Prometheus exposition format that carries exemplars. Exemplar `trace_id`/`span_id` labels are converted to OTLP exemplars and linked to traces in PostHog automatically.+- Exemplars exist only on counters and histogram buckets; gauges never have them.+- The agent preserves exemplars, it cannot create them: your application's Prometheus client must be configured to attach them (for example prom-client's `enableExemplars`, or a span-context supplier in Micrometer). If your endpoint only serves classic Prometheus text, metrics still flow but without trace links.++## Notes and limits++- One `service_name` per scrape job: Prometheus `job_name` maps to `service_name` in PostHog and target labels cannot override it. Run one agent (or one mounted scrape job) per logical service if you need distinct service names.+- Run a single replica. Two agents scraping the same targets double-count every metric.+- Metrics are rate limited server side per project; keep label cardinality sane (avoid user IDs, request IDs and the like as label values).+- Health endpoint for probes: `:13133`.+- The collector version is pinned in the `Dockerfile`; bump it together with `tests/integration/docker-compose.yml`.++## Development++```sh+# Config rendering golden tests (pure sh, no docker):+tests/render/run.sh++# Integration smoke test (builds the image; asserts exemplars survive scrape -> OTLP):+tests/integration/run.sh+```++End-to-end against the local dev stack (requires `hogli start` with capture-logs and the metrics ingestion consumer running):++```sh+docker build -t posthog-metrics-agent:dev .+docker run --rm \+ -e POSTHOG_API_KEY=phc_local \+ -e POSTHOG_HOST=http://host.docker.internal:4320 \+ -e SCRAPE_TARGETS=host.docker.internal:6738 \+ -e SCRAPE_METRICS_PATH=/_metrics \+ -e SCRAPE_JOB_NAME=agent-e2e \+ posthog-metrics-agent:dev+```++Then observe rows arriving:++```sql+SELECT service_name, metric_name, count()+FROM posthog.metrics+WHERE service_name = 'agent-e2e'+GROUP BY 1, 2+```diff --git a/products/metrics/agent/config/config.yaml.tmpl b/products/metrics/agent/config/config.yaml.tmplnew file mode 100644index 000000000000..ce878875f61d--- /dev/null+++ b/products/metrics/agent/config/config.yaml.tmpl@@ -0,0 +1,37 @@+receivers:+ prometheus:+ config:+ scrape_configs:+#__SCRAPE_CONFIGS__++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+#__DEBUG_EXPORTER__+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [__PIPELINE_EXPORTERS__]diff --git a/products/metrics/agent/entrypoint.sh b/products/metrics/agent/entrypoint.shnew file mode 100755index 000000000000..20c3a5aa22cf--- /dev/null+++ b/products/metrics/agent/entrypoint.sh@@ -0,0 +1,113 @@+#!/bin/sh+# Renders the OpenTelemetry Collector config for the PostHog metrics agent,+# then execs the collector. See README.md for the env var surface.+#+# Config resolution order:+# 1. $CONFIG_DIR/config.yaml - full config override, used verbatim+# 2. $CONFIG_DIR/scrape_configs.yaml - custom scrape_configs spliced into the template+# 3. SCRAPE_TARGETS env var - static scrape job rendered from env+#+# Scalar values (API key, host, interval, ...) are left as ${env:VAR} references+# for the collector's native config substitution, so secrets never pass through+# this script. Only the scrape_configs block structure is rendered here, because+# env substitution cannot expand a comma-separated string into a YAML list.+#+# RENDER_ONLY=1 prints the resolved config and exits (used by tests/render).+set -eu++CONFIG_DIR="${CONFIG_DIR:-/etc/posthog}"+TEMPLATE="$CONFIG_DIR/config.yaml.tmpl"+RENDERED="${RENDERED_CONFIG:-/tmp/config.yaml}"+OTELCOL="${OTELCOL_BIN:-/usr/local/bin/otelcol-contrib}"++finish() {+ if [ "${RENDER_ONLY:-}" = "1" ]; then+ cat "$1"+ exit 0+ fi+ exec "$OTELCOL" --config "$1"+}++if [ -f "$CONFIG_DIR/config.yaml" ]; then+ finish "$CONFIG_DIR/config.yaml"+fi++if [ -z "${POSTHOG_API_KEY:-}" ]; then+ echo "error: POSTHOG_API_KEY is required (your PostHog project API key)" >&2+ exit 1+fi++SNIPPET=$(mktemp)+trap 'rm -f "$SNIPPET"' EXIT++if [ -f "$CONFIG_DIR/scrape_configs.yaml" ]; then+ # Re-indent the mounted scrape_configs list under the prometheus receiver.+ awk '{ if ($0 == "") print ""; else print " " $0 }' \+ "$CONFIG_DIR/scrape_configs.yaml" >"$SNIPPET"+else+ if [ -z "${SCRAPE_TARGETS:-}" ]; then+ echo "error: SCRAPE_TARGETS is required (comma-separated host:port list)," \+ "unless you mount $CONFIG_DIR/scrape_configs.yaml or $CONFIG_DIR/config.yaml" >&2+ exit 1+ fi++ TARGETS=""+ OLDIFS=$IFS+ IFS=,+ for target in $SCRAPE_TARGETS; do+ target=$(printf '%s' "$target" | sed 's/^ *//;s/ *$//')+ [ -n "$target" ] || continue+ # Double single quotes so the target stays valid inside YAML quotes.+ target=$(printf '%s' "$target" | sed "s/'/''/g")+ if [ -n "$TARGETS" ]; then+ TARGETS="$TARGETS, '$target'"+ else+ TARGETS="'$target'"+ fi+ done+ IFS=$OLDIFS++ if [ -z "$TARGETS" ]; then+ echo "error: SCRAPE_TARGETS contained no targets" >&2+ exit 1+ fi++ cat >"$SNIPPET" <<EOF+ - job_name: '\${env:SCRAPE_JOB_NAME:-posthog-metrics-agent}'+ scrape_interval: '\${env:SCRAPE_INTERVAL:-15s}'+ metrics_path: '\${env:SCRAPE_METRICS_PATH:-/metrics}'+ # OpenMetrics first so exemplars (trace links) survive the scrape.+ scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]+ static_configs:+ - targets: [$TARGETS]+EOF+fi++DEBUG_ENABLED=0+case "${POSTHOG_DEBUG:-}" in+ 1 | true | TRUE | yes) DEBUG_ENABLED=1 ;;+esac++awk -v snippet="$SNIPPET" -v debug="$DEBUG_ENABLED" '+ $0 == "#__SCRAPE_CONFIGS__" {+ while ((getline line < snippet) > 0) print line+ close(snippet)+ next+ }+ $0 == "#__DEBUG_EXPORTER__" {+ if (debug == "1") {+ print " debug:"+ print " verbosity: detailed"+ }+ next+ }+ index($0, "__PIPELINE_EXPORTERS__") {+ exporters = (debug == "1") ? "otlphttp, debug" : "otlphttp"+ sub(/__PIPELINE_EXPORTERS__/, exporters)+ next+ }+ { print }+' "$TEMPLATE" >"$RENDERED"++finish "$RENDERED"diff --git a/products/metrics/agent/tests/integration/.gitignore b/products/metrics/agent/tests/integration/.gitignorenew file mode 100644index 000000000000..89f9ac04aac6--- /dev/null+++ b/products/metrics/agent/tests/integration/.gitignore@@ -0,0 +1 @@+out/diff --git a/products/metrics/agent/tests/integration/assert.sh b/products/metrics/agent/tests/integration/assert.shnew file mode 100755index 000000000000..662ce749fb9b--- /dev/null+++ b/products/metrics/agent/tests/integration/assert.sh@@ -0,0 +1,63 @@+#!/bin/sh+# Asserts the sink received the scraped metrics with exemplars intact.+# Expects the compose stack from docker-compose.yml to be running.+set -eu+cd "$(dirname "$0")"+FILE=out/metrics.json++for _ in $(seq 1 60); do+ if [ -s "$FILE" ] && grep -q http_requests_total "$FILE" && grep -q exemplars "$FILE"; then+ break+ fi+ sleep 1+done++if [ ! -s "$FILE" ]; then+ echo "FAIL: sink never received metrics (out/metrics.json empty)" >&2+ exit 1+fi++fail=0+check() {+ name=$1+ expected=$2+ actual=$3+ if [ "$actual" = "$expected" ]; then+ echo "PASS $name"+ else+ echo "FAIL $name: expected '$expected', got '$actual'" >&2+ fail=1+ fi+}++metrics='[.[].resourceMetrics[].scopeMetrics[].metrics[]]'++names=$(jq -rs "$metrics | [.[].name] | unique | join(\",\")" "$FILE")+echo "metric names seen: $names"+for wanted in http_requests_total request_duration_seconds cpu_usage; do+ case ",$names," in+ *",$wanted,"*) echo "PASS metric $wanted present" ;;+ *)+ echo "FAIL metric $wanted missing" >&2+ fail=1+ ;;+ esac+done++check counter-value 42 "$(jq -rs "$metrics | [.[] | select(.name == \"http_requests_total\") | .sum.dataPoints[].asDouble] | first" "$FILE")"++check counter-exemplar-trace-id 4bf92f3577b34da6a3ce929d0e0e4736 \+ "$(jq -rs "$metrics | [.[] | select(.name == \"http_requests_total\") | .sum.dataPoints[].exemplars[]?.traceId] | first" "$FILE")"++check counter-exemplar-span-id 00f067aa0ba902b7 \+ "$(jq -rs "$metrics | [.[] | select(.name == \"http_requests_total\") | .sum.dataPoints[].exemplars[]?.spanId] | first" "$FILE")"++check histogram-exemplar-trace-id 4bf92f3577b34da6a3ce929d0e0e4736 \+ "$(jq -rs "$metrics | [.[] | select(.name == \"request_duration_seconds\") | .histogram.dataPoints[].exemplars[]?.traceId] | first" "$FILE")"++# job_name becomes the service.name resource attribute (and service_name in PostHog).+check service-name posthog-metrics-agent \+ "$(jq -rs '[.[].resourceMetrics[].resource.attributes[] | select(.key == "service.name") | .value.stringValue] | first' "$FILE")"++[ "$fail" -eq 0 ] && echo "integration assertions passed"+exit "$fail"diff --git a/products/metrics/agent/tests/integration/docker-compose.yml b/products/metrics/agent/tests/integration/docker-compose.ymlnew file mode 100644index 000000000000..8d4a5533b49f--- /dev/null+++ b/products/metrics/agent/tests/integration/docker-compose.yml@@ -0,0 +1,29 @@+services:+ fixture:+ image: python:3.12-alpine+ command: python /app/fixture_server.py+ volumes:+ - ./fixture_server.py:/app/fixture_server.py:ro+ - ./fixtures:/app/fixtures:ro++ sink:+ # Keep the collector version in sync with ../../Dockerfile.+ image: otel/opentelemetry-collector-contrib:0.142.0+ command: ['--config', '/etc/sink-config.yaml']+ volumes:+ - ./sink-config.yaml:/etc/sink-config.yaml:ro+ - ./out:/out++ agent:+ image: posthog-metrics-agent:test+ environment:+ POSTHOG_API_KEY: phc_test+ POSTHOG_HOST: http://sink:4318+ # The sink's stock otlp receiver only serves /v1/metrics; prod+ # capture-logs is behind /i/v1/metrics (the template default).+ POSTHOG_INGEST_PATH: /v1/metrics+ SCRAPE_TARGETS: fixture:9464+ SCRAPE_INTERVAL: 1s+ depends_on:+ - fixture+ - sinkdiff --git a/products/metrics/agent/tests/integration/fixture_server.py b/products/metrics/agent/tests/integration/fixture_server.pynew file mode 100644index 000000000000..ee908cc424a1--- /dev/null+++ b/products/metrics/agent/tests/integration/fixture_server.py@@ -0,0 +1,24 @@+"""Serves a static OpenMetrics payload with exemplars, mimicking an app's+/metrics endpoint. The OpenMetrics content type is what makes the collector's+prometheus receiver parse exemplars; plain Prometheus text has no exemplar+syntax."""++import pathlib+import http.server++FIXTURE = pathlib.Path(__file__).parent / "fixtures" / "metrics.openmetrics.txt"+CONTENT_TYPE = "application/openmetrics-text; version=1.0.0; charset=utf-8"+++class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ body = FIXTURE.read_bytes()+ self.send_response(200)+ self.send_header("Content-Type", CONTENT_TYPE)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+++if __name__ == "__main__":+ http.server.HTTPServer(("0.0.0.0", 9464), Handler).serve_forever()diff --git a/products/metrics/agent/tests/integration/fixtures/metrics.openmetrics.txt b/products/metrics/agent/tests/integration/fixtures/metrics.openmetrics.txtnew file mode 100644index 000000000000..0eabb1008a0d--- /dev/null+++ b/products/metrics/agent/tests/integration/fixtures/metrics.openmetrics.txt@@ -0,0 +1,14 @@+# TYPE http_requests counter+# HELP http_requests Total HTTP requests.+http_requests_total{path="/api"} 42 # {trace_id="4bf92f3577b34da6a3ce929d0e0e4736",span_id="00f067aa0ba902b7"} 1.0+# TYPE request_duration_seconds histogram+# HELP request_duration_seconds Request duration.+request_duration_seconds_bucket{le="0.1"} 5 # {trace_id="4bf92f3577b34da6a3ce929d0e0e4736",span_id="00f067aa0ba902b7"} 0.05+request_duration_seconds_bucket{le="1.0"} 9+request_duration_seconds_bucket{le="+Inf"} 10+request_duration_seconds_sum 1.2+request_duration_seconds_count 10+# TYPE cpu_usage gauge+# HELP cpu_usage CPU usage ratio (gauges cannot carry exemplars).+cpu_usage 0.5+# EOFdiff --git a/products/metrics/agent/tests/integration/run.sh b/products/metrics/agent/tests/integration/run.shnew file mode 100755index 000000000000..036bbf0ee7ea--- /dev/null+++ b/products/metrics/agent/tests/integration/run.sh@@ -0,0 +1,31 @@+#!/bin/sh+# End-to-end smoke test: fixture /metrics endpoint (OpenMetrics + exemplars)+# -> agent image -> OTLP sink -> JSON assertions.+# Usage: products/metrics/agent/tests/integration/run.sh [--skip-build]+set -eu+cd "$(dirname "$0")"+AGENT_DIR=$(cd ../.. && pwd)++if [ "${1:-}" != "--skip-build" ]; then+ docker build -t posthog-metrics-agent:test "$AGENT_DIR"+fi++# The sink container may run as a non-root user; make the output dir writable.+rm -rf out && mkdir -p out && chmod 777 out++cleanup() {+ docker compose logs agent 2>/dev/null | tail -20 || true+ docker compose down -v --remove-orphans >/dev/null 2>&1 || true+}+trap cleanup EXIT++docker compose up -d++# The rendered config must be valid for the real collector, not just our goldens.+docker run --rm --entrypoint /bin/sh \+ -e POSTHOG_API_KEY=phc_test -e SCRAPE_TARGETS=app:9090 \+ posthog-metrics-agent:test \+ -c 'RENDER_ONLY=1 /entrypoint.sh > /tmp/validate.yaml && /usr/local/bin/otelcol-contrib validate --config /tmp/validate.yaml' \+ && echo "PASS collector config validates"++./assert.shdiff --git a/products/metrics/agent/tests/integration/sink-config.yaml b/products/metrics/agent/tests/integration/sink-config.yamlnew file mode 100644index 000000000000..63b95b93dbdf--- /dev/null+++ b/products/metrics/agent/tests/integration/sink-config.yaml@@ -0,0 +1,17 @@+# OTLP sink standing in for PostHog ingestion: receives what the agent exports+# and writes it as OTLP JSON lines for assert.sh to inspect.+receivers:+ otlp:+ protocols:+ http:+ endpoint: 0.0.0.0:4318++exporters:+ file:+ path: /out/metrics.json++service:+ pipelines:+ metrics:+ receivers: [otlp]+ exporters: [file]diff --git a/products/metrics/agent/tests/render/golden/debug.yaml b/products/metrics/agent/tests/render/golden/debug.yamlnew file mode 100644index 000000000000..87bc271baffd--- /dev/null+++ b/products/metrics/agent/tests/render/golden/debug.yaml@@ -0,0 +1,44 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: '${env:SCRAPE_JOB_NAME:-posthog-metrics-agent}'+ scrape_interval: '${env:SCRAPE_INTERVAL:-15s}'+ metrics_path: '${env:SCRAPE_METRICS_PATH:-/metrics}'+ # OpenMetrics first so exemplars (trace links) survive the scrape.+ scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]+ static_configs:+ - targets: ['app:9090']++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+ debug:+ verbosity: detailed+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp, debug]diff --git a/products/metrics/agent/tests/render/golden/full-override.yaml b/products/metrics/agent/tests/render/golden/full-override.yamlnew file mode 100644index 000000000000..6c1004e9115c--- /dev/null+++ b/products/metrics/agent/tests/render/golden/full-override.yaml@@ -0,0 +1,19 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: 'byo'+ static_configs:+ - targets: ['own:9999']++exporters:+ otlphttp:+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}/i/v1/metrics'+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'++service:+ pipelines:+ metrics:+ receivers: [prometheus]+ exporters: [otlphttp]diff --git a/products/metrics/agent/tests/render/golden/minimal.yaml b/products/metrics/agent/tests/render/golden/minimal.yamlnew file mode 100644index 000000000000..2a4bbf6ec566--- /dev/null+++ b/products/metrics/agent/tests/render/golden/minimal.yaml@@ -0,0 +1,42 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: '${env:SCRAPE_JOB_NAME:-posthog-metrics-agent}'+ scrape_interval: '${env:SCRAPE_INTERVAL:-15s}'+ metrics_path: '${env:SCRAPE_METRICS_PATH:-/metrics}'+ # OpenMetrics first so exemplars (trace links) survive the scrape.+ scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]+ static_configs:+ - targets: ['app:9090']++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]diff --git a/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml b/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yamlnew file mode 100644index 000000000000..cec5e5b1d8c7--- /dev/null+++ b/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml@@ -0,0 +1,39 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: 'custom'+ scrape_interval: 30s+ static_configs:+ - targets: ['legacy:8080']++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]diff --git a/products/metrics/agent/tests/render/golden/multi.yaml b/products/metrics/agent/tests/render/golden/multi.yamlnew file mode 100644index 000000000000..3aa06d75edc9--- /dev/null+++ b/products/metrics/agent/tests/render/golden/multi.yaml@@ -0,0 +1,42 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: '${env:SCRAPE_JOB_NAME:-posthog-metrics-agent}'+ scrape_interval: '${env:SCRAPE_INTERVAL:-15s}'+ metrics_path: '${env:SCRAPE_METRICS_PATH:-/metrics}'+ # OpenMetrics first so exemplars (trace links) survive the scrape.+ scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]+ static_configs:+ - targets: ['app:9090', 'worker:9091', 'db-exporter:9187']++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]diff --git a/products/metrics/agent/tests/render/golden/quoted-target.yaml b/products/metrics/agent/tests/render/golden/quoted-target.yamlnew file mode 100644index 000000000000..fb7a34ec30eb--- /dev/null+++ b/products/metrics/agent/tests/render/golden/quoted-target.yaml@@ -0,0 +1,42 @@+receivers:+ prometheus:+ config:+ scrape_configs:+ - job_name: '${env:SCRAPE_JOB_NAME:-posthog-metrics-agent}'+ scrape_interval: '${env:SCRAPE_INTERVAL:-15s}'+ metrics_path: '${env:SCRAPE_METRICS_PATH:-/metrics}'+ # OpenMetrics first so exemplars (trace links) survive the scrape.+ scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]+ static_configs:+ - targets: ['app''s-host:9090']++processors:+ # Shed load instead of buffering unbounded memory when PostHog is unreachable.+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++exporters:+ otlphttp:+ # The otlphttp exporter appends /v1/metrics to `endpoint`, but PostHog's+ # public ingest route is /i/v1/metrics, so pin the per-signal path.+ metrics_endpoint: '${env:POSTHOG_HOST:-https://us.i.posthog.com}${env:POSTHOG_INGEST_PATH:-/i/v1/metrics}'+ compression: gzip+ headers:+ authorization: 'Bearer ${env:POSTHOG_API_KEY}'+ retry_on_failure:+ enabled: true++extensions:+ health_check:+ endpoint: 0.0.0.0:13133++service:+ extensions: [health_check]+ pipelines:+ metrics:+ receivers: [prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]diff --git a/products/metrics/agent/tests/render/run.sh b/products/metrics/agent/tests/render/run.shnew file mode 100755index 000000000000..4ee67e8b4b8c--- /dev/null+++ b/products/metrics/agent/tests/render/run.sh@@ -0,0 +1,103 @@+#!/bin/sh+# Golden tests for entrypoint.sh config rendering.+# Usage: products/metrics/agent/tests/render/run.sh+# Each case runs the entrypoint with RENDER_ONLY=1 in a clean environment and+# diffs the rendered collector config against a golden file.+set -u+cd "$(dirname "$0")"+AGENT_DIR=$(cd ../.. && pwd)+PASS=0+FAIL=0++new_case_dir() {+ CASE_DIR=$(mktemp -d)+ cp "$AGENT_DIR/config/config.yaml.tmpl" "$CASE_DIR/"+}++# run_render <name> [VAR=value ...] — renders and diffs against golden/<name>.yaml+run_render() {+ name=$1+ shift+ out=$(mktemp)+ err=$(mktemp)+ if ! env -i PATH="$PATH" CONFIG_DIR="$CASE_DIR" RENDERED_CONFIG="$CASE_DIR/rendered.yaml" RENDER_ONLY=1 "$@" \+ sh "$AGENT_DIR/entrypoint.sh" >"$out" 2>"$err"; then+ echo "FAIL $name: entrypoint exited non-zero"+ cat "$err"+ FAIL=$((FAIL + 1))+ return+ fi+ if diff -u "golden/$name.yaml" "$out"; then+ echo "PASS $name"+ PASS=$((PASS + 1))+ else+ echo "FAIL $name: rendered config differs from golden/$name.yaml"+ FAIL=$((FAIL + 1))+ fi+}++# expect_failure <name> <stderr needle> [VAR=value ...]+expect_failure() {+ name=$1+ needle=$2+ shift 2+ err=$(mktemp)+ if env -i PATH="$PATH" CONFIG_DIR="$CASE_DIR" RENDERED_CONFIG="$CASE_DIR/rendered.yaml" RENDER_ONLY=1 "$@" \+ sh "$AGENT_DIR/entrypoint.sh" >/dev/null 2>"$err"; then+ echo "FAIL $name: expected non-zero exit"+ FAIL=$((FAIL + 1))+ return+ fi+ if grep -q "$needle" "$err"; then+ echo "PASS $name"+ PASS=$((PASS + 1))+ else+ echo "FAIL $name: stderr does not mention '$needle'"+ cat "$err"+ FAIL=$((FAIL + 1))+ fi+}++new_case_dir+run_render minimal POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090++# Comma-separated targets with stray whitespace and an empty entry get trimmed.+new_case_dir+run_render multi POSTHOG_API_KEY=phc_test SCRAPE_TARGETS='app:9090, worker:9091 ,,db-exporter:9187'++new_case_dir+run_render debug POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 POSTHOG_DEBUG=1++# Single quotes in a target are doubled so the rendered YAML stays valid.+new_case_dir+run_render quoted-target POSTHOG_API_KEY=phc_test "SCRAPE_TARGETS=app's-host:9090"++# A mounted scrape_configs.yaml replaces the env-generated job verbatim+# (re-indented under the receiver), and SCRAPE_TARGETS is not required.+new_case_dir+cat >"$CASE_DIR/scrape_configs.yaml" <<'EOF'+- job_name: 'custom'+ scrape_interval: 30s+ static_configs:+ - targets: ['legacy:8080']+EOF+run_render mounted-scrape-configs POSTHOG_API_KEY=phc_test++# A mounted config.yaml wins over everything and is used verbatim; no env vars+# are required because the file may carry its own ${env:...} references.+new_case_dir+cp golden/full-override.yaml "$CASE_DIR/config.yaml"+run_render full-override++new_case_dir+expect_failure missing-api-key POSTHOG_API_KEY SCRAPE_TARGETS=app:9090++new_case_dir+expect_failure missing-targets SCRAPE_TARGETS POSTHOG_API_KEY=phc_test++new_case_dir+expect_failure empty-targets SCRAPE_TARGETS POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=' , '++echo+echo "render tests: $PASS passed, $FAIL failed"+[ "$FAIL" -eq 0 ]