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): scale the metrics scrape agent to a sharded, durable fleet (#75087)

Daniel Visca8fa32740ef27
diff --git a/products/metrics/agent/Dockerfile b/products/metrics/agent/Dockerfile
index fd5788582c8f..2ae3a27c8fa5 100644
--- a/products/metrics/agent/Dockerfile
+++ b/products/metrics/agent/Dockerfile
@@ -7,7 +7,8 @@
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
+RUN apk add --no-cache ca-certificates && adduser -D -u 10001 otel \
+ && mkdir -p /var/lib/posthog-agent && chown 10001 /var/lib/posthog-agent
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
diff --git a/products/metrics/agent/README.md b/products/metrics/agent/README.md
index 73f569dbae20..0f008b487916 100644
--- a/products/metrics/agent/README.md
+++ b/products/metrics/agent/README.md
@@ -21,19 +21,38 @@ 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) |
+| 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) |
+| `SHARD_COUNT` | no | `1` | Size of an agent fleet; above 1 each instance scrapes only its share |
+| `SHARD_INDEX` | no | from hostname ordinal | This instance's index in `0..SHARD_COUNT-1` (see Scaling out) |
+| `PERSIST_QUEUE` | no | unset | `1`/`true`: buffer undelivered batches to disk so restarts lose nothing |
+| `QUEUE_DIR` | no | `/var/lib/posthog-agent` | Where the persistent queue is stored |
\* not required when you mount your own scrape configs, see below.
+## Scaling out (sharding)
+
+A single agent scrapes every target itself.
+For a large target set, run a fleet: set `SHARD_COUNT` to the fleet size and each instance keeps only the targets whose address hashes to its `SHARD_INDEX`, so the fleet partitions the work with no coordination, no double-counting, and no gaps.
+
+`SHARD_INDEX` defaults to the trailing ordinal of the container hostname (`agent-0` → `0`), so a Kubernetes StatefulSet gets correct indices for free; set it explicitly for other orchestrators.
+This is the same target-sharding model vmagent uses.
+The Helm chart wires this up automatically — set `shards: <n>` and it runs a StatefulSet fleet.
+
+## Durability
+
+By default the export queue is in memory: if PostHog is briefly unreachable the agent retries, but a restart during that window drops whatever was buffered.
+Set `PERSIST_QUEUE=1` (and give the container a durable volume at `QUEUE_DIR`) to back the queue with disk, so samples scraped during an outage survive restarts and deliver on recovery.
+The Helm chart's `persistence.enabled=true` provisions the volume for you.
+
## Escape hatches
Checked in this order:
@@ -51,9 +70,10 @@ Checked in this order:
## 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.
+- Don't run bare replicas of one agent — they all scrape the same targets and double-count. To scale, use a sharded fleet (see Scaling out) so each instance takes a disjoint slice.
- 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 agent exposes its own metrics (scrape success, queue depth, points sent/dropped) at `:8888/metrics` — point your monitoring at it, or scrape it with the agent itself.
- The collector version is pinned in the `Dockerfile`; bump it together with `tests/integration/docker-compose.yml`.
## Development
@@ -62,8 +82,20 @@ Checked in this order:
# Config rendering golden tests (pure sh, no docker):
tests/render/run.sh
+# Helm chart render + behavior tests (needs helm):
+tests/helm/run.sh
+
# Integration smoke test (builds the image; asserts exemplars survive scrape -> OTLP):
tests/integration/run.sh
+
+# Durability: scrape through a simulated outage, hard-kill, assert nothing lost:
+tests/durability/run.sh
+
+# Fleet sharding at scale (synthetic target farm; completeness + disjointness):
+tests/scale/run.sh
+
+# Real-Kubernetes E2E on kind (restricted-PSS admission, discovery, sharding, exemplars):
+tests/kind/run.sh
```
End-to-end against the local dev stack (requires `hogli start` with capture-logs and the metrics ingestion consumer running):
diff --git a/products/metrics/agent/chart/posthog-metrics-agent/templates/_helpers.tpl b/products/metrics/agent/chart/posthog-metrics-agent/templates/_helpers.tpl
index d7f916de2287..8e0496fd5134 100644
--- a/products/metrics/agent/chart/posthog-metrics-agent/templates/_helpers.tpl
+++ b/products/metrics/agent/chart/posthog-metrics-agent/templates/_helpers.tpl
@@ -43,6 +43,22 @@ entrypoint's full-override escape hatch). The API key is referenced as
${env:POSTHOG_API_KEY} and resolved by the collector from the pod env,
so it never appears in the ConfigMap.
*/}}
+{{/*
+Hashmod pair appended to every generated scrape job when shards > 1: each
+pod keeps only targets hashing to its SHARD_INDEX (exported by the image
+entrypoint from the StatefulSet pod ordinal). Runs last so it hashes the
+final __address__, after the annotation port rewrite.
+*/}}
+{{- define "posthog-metrics-agent.shardRelabel" -}}
+- source_labels: [__address__]
+ modulus: {{ int .Values.shards }}
+ target_label: __tmp_shard
+ action: hashmod
+- source_labels: [__tmp_shard]
+ regex: '${env:SHARD_INDEX}'
+ action: keep
+{{- end }}
+
{{- define "posthog-metrics-agent.collectorConfig" -}}
{{- if and (not .Values.scrape.annotationDiscovery) (not .Values.scrape.staticTargets) (not .Values.scrape.extraScrapeConfigs) }}
{{- fail "at least one of scrape.annotationDiscovery, scrape.staticTargets or scrape.extraScrapeConfigs must be set" }}
@@ -77,6 +93,9 @@ receivers:
- source_labels: [__meta_kubernetes_pod_name]
action: replace
target_label: pod
+{{- if gt (int .Values.shards) 1 }}
+{{- include "posthog-metrics-agent.shardRelabel" . | nindent 22 }}
+{{- end }}
{{- end }}
{{- if .Values.scrape.staticTargets }}
- job_name: static-targets
@@ -85,6 +104,10 @@ receivers:
scrape_protocols: [OpenMetricsText1.0.0, OpenMetricsText0.0.1, PrometheusText0.0.4]
static_configs:
- targets: [{{ range $i, $t := .Values.scrape.staticTargets }}{{ if $i }}, {{ end }}'{{ $t }}'{{ end }}]
+{{- if gt (int .Values.shards) 1 }}
+ relabel_configs:
+{{- include "posthog-metrics-agent.shardRelabel" . | nindent 22 }}
+{{- end }}
{{- end }}
{{- with .Values.scrape.extraScrapeConfigs }}
{{ tpl . $ | indent 16 }}
@@ -102,19 +125,40 @@ 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: '{{ .Values.posthog.host }}/i/v1/metrics'
+ metrics_endpoint: '{{ .Values.posthog.host }}{{ .Values.posthog.ingestPath | default "/i/v1/metrics" }}'
compression: gzip
headers:
authorization: 'Bearer ${env:POSTHOG_API_KEY}'
+ {{- if .Values.persistence.enabled }}
+ # Persist undelivered batches so a restart during an outage loses nothing.
+ sending_queue:
+ enabled: true
+ storage: file_storage
+ {{- end }}
retry_on_failure:
enabled: true
extensions:
health_check:
endpoint: 0.0.0.0:13133
+ {{- if .Values.persistence.enabled }}
+ file_storage:
+ directory: /var/lib/posthog-agent
+ create_directory: true
+ {{- end }}
service:
- extensions: [health_check]
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ extensions: [health_check{{ if .Values.persistence.enabled }}, file_storage{{ end }}]
pipelines:
metrics:
receivers: [prometheus]
diff --git a/products/metrics/agent/chart/posthog-metrics-agent/templates/deployment.yaml b/products/metrics/agent/chart/posthog-metrics-agent/templates/deployment.yaml
index 1a74d6ddf52f..df815655f96d 100644
--- a/products/metrics/agent/chart/posthog-metrics-agent/templates/deployment.yaml
+++ b/products/metrics/agent/chart/posthog-metrics-agent/templates/deployment.yaml
@@ -1,13 +1,26 @@
+{{- $sharded := gt (int .Values.shards) 1 }}
apiVersion: apps/v1
+{{- if $sharded }}
+kind: StatefulSet
+{{- else }}
kind: Deployment
+{{- end }}
metadata:
name: {{ include "posthog-metrics-agent.fullname" . }}
labels:
{{- include "posthog-metrics-agent.labels" . | nindent 8 }}
spec:
+ {{- if $sharded }}
+ # Shards partition the target set by address hash (each pod's ordinal is
+ # its SHARD_INDEX), so every target is scraped by exactly one pod.
+ replicas: {{ int .Values.shards }}
+ serviceName: {{ include "posthog-metrics-agent.fullname" . }}-headless
+ podManagementPolicy: Parallel
+ {{- else }}
# A single replica by design: multiple replicas would scrape every target
- # multiple times and double-count all metrics.
+ # multiple times and double-count all metrics. Scale with shards instead.
replicas: 1
+ {{- end }}
selector:
matchLabels:
{{- include "posthog-metrics-agent.selectorLabels" . | nindent 12 }}
@@ -25,6 +38,10 @@ spec:
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
+ {{- if .Values.persistence.enabled }}
+ # The agent runs as uid 10001; the queue volume must be writable.
+ fsGroup: 10001
+ {{- end }}
containers:
- name: agent
image: '{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}'
@@ -40,14 +57,34 @@ spec:
secretKeyRef:
name: {{ include "posthog-metrics-agent.secretName" . }}
key: posthog-api-key
+ {{- if $sharded }}
+ # The entrypoint derives SHARD_INDEX from the pod ordinal
+ # and exports it for the ${env:SHARD_INDEX} keep regex.
+ - name: SHARD_COUNT
+ value: {{ int .Values.shards | quote }}
+ {{- end }}
+ {{- if .Values.persistence.enabled }}
+ - name: PERSIST_QUEUE
+ value: '1'
+ {{- end }}
+ {{- range $k, $v := .Values.podEnv }}
+ - name: {{ $k }}
+ value: {{ $v | quote }}
+ {{- end }}
volumeMounts:
- name: config
mountPath: /etc/posthog/config.yaml
subPath: config.yaml
readOnly: true
+ {{- if .Values.persistence.enabled }}
+ - name: queue
+ mountPath: /var/lib/posthog-agent
+ {{- end }}
ports:
- name: health
containerPort: 13133
+ - name: telemetry
+ containerPort: 8888
livenessProbe:
httpGet:
path: /
@@ -62,6 +99,11 @@ spec:
- name: config
configMap:
name: {{ include "posthog-metrics-agent.fullname" . }}
+ {{- if and .Values.persistence.enabled (not $sharded) }}
+ - name: queue
+ persistentVolumeClaim:
+ claimName: {{ include "posthog-metrics-agent.fullname" . }}-queue
+ {{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 16 }}
@@ -74,3 +116,16 @@ spec:
affinity:
{{- toYaml . | nindent 16 }}
{{- end }}
+ {{- if and .Values.persistence.enabled $sharded }}
+ volumeClaimTemplates:
+ - metadata:
+ name: queue
+ spec:
+ accessModes: [ReadWriteOnce]
+ resources:
+ requests:
+ storage: {{ .Values.persistence.size }}
+ {{- with .Values.persistence.storageClass }}
+ storageClassName: {{ . }}
+ {{- end }}
+ {{- end }}
diff --git a/products/metrics/agent/chart/posthog-metrics-agent/templates/headless-service.yaml b/products/metrics/agent/chart/posthog-metrics-agent/templates/headless-service.yaml
new file mode 100644
index 000000000000..0a491f422ab1
--- /dev/null
+++ b/products/metrics/agent/chart/posthog-metrics-agent/templates/headless-service.yaml
@@ -0,0 +1,17 @@
+{{- if gt (int .Values.shards) 1 }}
+# StatefulSets require a governing service; the agent serves no traffic, so
+# it is headless and only provides stable pod identities (the shard index).
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "posthog-metrics-agent.fullname" . }}-headless
+ labels:
+ {{- include "posthog-metrics-agent.labels" . | nindent 8 }}
+spec:
+ clusterIP: None
+ selector:
+ {{- include "posthog-metrics-agent.selectorLabels" . | nindent 8 }}
+ ports:
+ - name: health
+ port: 13133
+{{- end }}
diff --git a/products/metrics/agent/chart/posthog-metrics-agent/templates/pvc.yaml b/products/metrics/agent/chart/posthog-metrics-agent/templates/pvc.yaml
new file mode 100644
index 000000000000..5e9a8fe81345
--- /dev/null
+++ b/products/metrics/agent/chart/posthog-metrics-agent/templates/pvc.yaml
@@ -0,0 +1,18 @@
+{{- if and .Values.persistence.enabled (not (gt (int .Values.shards) 1)) }}
+# Sharded installs get per-pod queues via the StatefulSet's claim templates;
+# this standalone claim serves the single-instance Deployment.
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+ name: {{ include "posthog-metrics-agent.fullname" . }}-queue
+ labels:
+ {{- include "posthog-metrics-agent.labels" . | nindent 8 }}
+spec:
+ accessModes: [ReadWriteOnce]
+ resources:
+ requests:
+ storage: {{ .Values.persistence.size }}
+ {{- with .Values.persistence.storageClass }}
+ storageClassName: {{ . }}
+ {{- end }}
+{{- end }}
diff --git a/products/metrics/agent/chart/posthog-metrics-agent/values.yaml b/products/metrics/agent/chart/posthog-metrics-agent/values.yaml
index f33d95385c90..fc35be85c086 100644
--- a/products/metrics/agent/chart/posthog-metrics-agent/values.yaml
+++ b/products/metrics/agent/chart/posthog-metrics-agent/values.yaml
@@ -7,12 +7,21 @@ image:
posthog:
# PostHog ingestion origin. EU cloud: https://eu.i.posthog.com
host: https://us.i.posthog.com
+ # Per-signal ingest path. Defaults to PostHog's public metrics route;
+ # override only for a proxy or a test sink (e.g. /v1/metrics).
+ ingestPath: ''
# Project API key. Stored in a chart-managed Secret.
apiKey: ''
# Alternatively, the name of an existing Secret with the key `posthog-api-key`.
# Takes precedence over apiKey.
existingSecret: ''
+# Number of agent instances. 1 runs a single Deployment. Above 1 the chart
+# runs a StatefulSet fleet that partitions scrape targets by address hash, so
+# each target is scraped by exactly one shard. Scale this for large clusters
+# instead of replicas, which would double-count every target.
+shards: 1
+
scrape:
interval: 15s
# Scrape pods annotated with prometheus.io/scrape: "true"
@@ -21,8 +30,23 @@ scrape:
# Extra fixed host:port targets, e.g. ['my-svc:9090'].
staticTargets: []
# Raw Prometheus scrape_configs YAML (a list) appended verbatim.
+ # With shards > 1, add the hashmod relabel pair to each job here too
+ # (see templates/_helpers.tpl) or every shard will scrape it.
extraScrapeConfigs: ''
+# Extra environment variables passed to the agent container, e.g.
+# {POSTHOG_DEBUG: "1", SCRAPE_JOB_NAME: my-fleet}. See the image README for
+# the full env surface.
+podEnv: {}
+
+# Disk-backed delivery queue: samples scraped while PostHog is unreachable
+# survive pod restarts and deliver on recovery. Without it the queue is
+# in-memory and a restart during an outage drops whatever was buffered.
+persistence:
+ enabled: false
+ size: 10Gi
+ storageClass: ''
+
resources:
requests:
cpu: 100m
diff --git a/products/metrics/agent/config/config.yaml.tmpl b/products/metrics/agent/config/config.yaml.tmpl
index ce878875f61d..aa59fed4c58f 100644
--- a/products/metrics/agent/config/config.yaml.tmpl
+++ b/products/metrics/agent/config/config.yaml.tmpl
@@ -21,15 +21,27 @@ exporters:
compression: gzip
headers:
authorization: 'Bearer ${env:POSTHOG_API_KEY}'
+#__SENDING_QUEUE__
retry_on_failure:
enabled: true
extensions:
+#__FILE_STORAGE__
health_check:
endpoint: 0.0.0.0:13133
service:
- extensions: [health_check]
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ extensions: [__SERVICE_EXTENSIONS__]
pipelines:
metrics:
receivers: [prometheus]
diff --git a/products/metrics/agent/entrypoint.sh b/products/metrics/agent/entrypoint.sh
index 20c3a5aa22cf..3afedb9e3290 100755
--- a/products/metrics/agent/entrypoint.sh
+++ b/products/metrics/agent/entrypoint.sh
@@ -28,6 +28,42 @@ finish() {
exec "$OTELCOL" --config "$1"
}
+# Sharding: with SHARD_COUNT set, each instance keeps only the targets that
+# hash to its SHARD_INDEX, so a fleet partitions the target set with no
+# coordination. The index falls back to the hostname's trailing ordinal
+# (StatefulSet pods are named <name>-<ordinal>), matching how vmagent shards.
+# Resolved before any config path so mounted configs can reference
+# ${env:SHARD_INDEX} too.
+SHARD_COUNT="${SHARD_COUNT:-1}"
+case "$SHARD_COUNT" in
+ '' | *[!0-9]*)
+ echo "error: SHARD_COUNT must be a positive integer, got '$SHARD_COUNT'" >&2
+ exit 1
+ ;;
+esac
+if [ "$SHARD_COUNT" -gt 1 ]; then
+ if [ -z "${SHARD_INDEX:-}" ]; then
+ host="${HOSTNAME:-$(hostname)}"
+ SHARD_INDEX=$(printf '%s' "$host" | sed -n 's/.*-\([0-9][0-9]*\)$/\1/p')
+ if [ -z "$SHARD_INDEX" ]; then
+ echo "error: SHARD_INDEX is not set and cannot be derived from hostname '$host'" \
+ "(expected a trailing -<ordinal>, e.g. a StatefulSet pod name)" >&2
+ exit 1
+ fi
+ fi
+ case "$SHARD_INDEX" in
+ '' | *[!0-9]*)
+ echo "error: SHARD_INDEX must be a non-negative integer, got '$SHARD_INDEX'" >&2
+ exit 1
+ ;;
+ esac
+ if [ "$SHARD_INDEX" -ge "$SHARD_COUNT" ]; then
+ echo "error: SHARD_INDEX must be less than SHARD_COUNT ($SHARD_INDEX >= $SHARD_COUNT)" >&2
+ exit 1
+ fi
+ export SHARD_INDEX
+fi
+
if [ -f "$CONFIG_DIR/config.yaml" ]; then
finish "$CONFIG_DIR/config.yaml"
fi
@@ -81,6 +117,20 @@ else
static_configs:
- targets: [$TARGETS]
EOF
+
+ if [ "$SHARD_COUNT" -gt 1 ]; then
+ cat >>"$SNIPPET" <<EOF
+ # Shard $SHARD_INDEX of $SHARD_COUNT: keep only targets that hash to this shard.
+ relabel_configs:
+ - source_labels: [__address__]
+ modulus: $SHARD_COUNT
+ target_label: __tmp_shard
+ action: hashmod
+ - source_labels: [__tmp_shard]
+ regex: '$SHARD_INDEX'
+ action: keep
+EOF
+ fi
fi
DEBUG_ENABLED=0
@@ -88,7 +138,12 @@ case "${POSTHOG_DEBUG:-}" in
1 | true | TRUE | yes) DEBUG_ENABLED=1 ;;
esac
-awk -v snippet="$SNIPPET" -v debug="$DEBUG_ENABLED" '
+PERSIST_ENABLED=0
+case "${PERSIST_QUEUE:-}" in
+ 1 | true | TRUE | yes) PERSIST_ENABLED=1 ;;
+esac
+
+awk -v snippet="$SNIPPET" -v debug="$DEBUG_ENABLED" -v persist="$PERSIST_ENABLED" '
$0 == "#__SCRAPE_CONFIGS__" {
while ((getline line < snippet) > 0) print line
close(snippet)
@@ -101,6 +156,29 @@ awk -v snippet="$SNIPPET" -v debug="$DEBUG_ENABLED" '
}
next
}
+ $0 == "#__SENDING_QUEUE__" {
+ if (persist == "1") {
+ print " sending_queue:"
+ print " enabled: true"
+ print " # Survives restarts: batches persist to disk until delivered."
+ print " storage: file_storage"
+ }
+ next
+ }
+ $0 == "#__FILE_STORAGE__" {
+ if (persist == "1") {
+ print " file_storage:"
+ print " directory: \x27${env:QUEUE_DIR:-/var/lib/posthog-agent}\x27"
+ print " create_directory: true"
+ }
+ next
+ }
+ index($0, "__SERVICE_EXTENSIONS__") {
+ extensions = (persist == "1") ? "health_check, file_storage" : "health_check"
+ sub(/__SERVICE_EXTENSIONS__/, extensions)
+ print
+ next
+ }
index($0, "__PIPELINE_EXPORTERS__") {
exporters = (debug == "1") ? "otlphttp, debug" : "otlphttp"
sub(/__PIPELINE_EXPORTERS__/, exporters)
diff --git a/products/metrics/agent/tests/durability/.gitignore b/products/metrics/agent/tests/durability/.gitignore
new file mode 100644
index 000000000000..1fcb1529f8e5
--- /dev/null
+++ b/products/metrics/agent/tests/durability/.gitignore
@@ -0,0 +1 @@
+out
diff --git a/products/metrics/agent/tests/durability/assert.sh b/products/metrics/agent/tests/durability/assert.sh
new file mode 100755
index 000000000000..7e936cfa88fa
--- /dev/null
+++ b/products/metrics/agent/tests/durability/assert.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+# Asserts the sink received datapoints scraped before the agent restart.
+set -eu
+cd "$(dirname "$0")"
+
+RESTART_NS=$1
+FILE=out/metrics.json
+
+datapoints='[.[].resourceMetrics[].scopeMetrics[].metrics[]
+ | select(.name == "http_requests_total")
+ | .sum.dataPoints[]]'
+
+total=$(jq -rs "$datapoints | length" "$FILE")
+pre_restart=$(jq -rs "$datapoints | [.[] | select((.timeUnixNano | tonumber) < $RESTART_NS)] | length" "$FILE")
+
+echo "datapoints delivered: $total total, $pre_restart scraped before the restart"
+
+fail=0
+if [ "$total" -gt 0 ]; then
+ echo "PASS delivery: queue drained into the recovered sink"
+else
+ echo "FAIL delivery: nothing arrived" >&2
+ fail=1
+fi
+
+if [ "$pre_restart" -gt 0 ]; then
+ echo "PASS durability: pre-restart samples survived the process death"
+else
+ echo "FAIL durability: only post-restart samples arrived (queue was not persistent)" >&2
+ fail=1
+fi
+
+[ "$fail" -eq 0 ] && echo "durability assertions passed"
+exit "$fail"
diff --git a/products/metrics/agent/tests/durability/docker-compose.yml b/products/metrics/agent/tests/durability/docker-compose.yml
new file mode 100644
index 000000000000..b51d1a108406
--- /dev/null
+++ b/products/metrics/agent/tests/durability/docker-compose.yml
@@ -0,0 +1,35 @@
+services:
+ fixture:
+ image: python:3.12-alpine
+ command: python /app/fixture_server.py
+ volumes:
+ - ../integration/fixture_server.py:/app/fixture_server.py:ro
+ - ../integration/fixtures:/app/fixtures:ro
+
+ agent:
+ image: posthog-metrics-agent:test
+ environment:
+ POSTHOG_API_KEY: phc_test
+ POSTHOG_HOST: http://sink:4318
+ POSTHOG_INGEST_PATH: /v1/metrics
+ SCRAPE_TARGETS: fixture:9464
+ SCRAPE_INTERVAL: 1s
+ PERSIST_QUEUE: '1'
+ volumes:
+ - queue:/var/lib/posthog-agent
+ depends_on:
+ - fixture
+
+ # Started manually by run.sh only after the agent has scraped for a while
+ # and been restarted; its absence is the simulated PostHog outage.
+ sink:
+ # Keep the collector version in sync with ../../Dockerfile.
+ image: otel/opentelemetry-collector-contrib:0.142.0
+ command: ['--config', '/etc/sink-config.yaml']
+ volumes:
+ - ../integration/sink-config.yaml:/etc/sink-config.yaml:ro
+ - ./out:/out
+ profiles: [recovery]
+
+volumes:
+ queue:
diff --git a/products/metrics/agent/tests/durability/run.sh b/products/metrics/agent/tests/durability/run.sh
new file mode 100755
index 000000000000..0da1e45a4e84
--- /dev/null
+++ b/products/metrics/agent/tests/durability/run.sh
@@ -0,0 +1,59 @@
+#!/bin/sh
+# Durability test: samples scraped while PostHog is unreachable must survive
+# an agent restart and arrive once the destination comes back.
+#
+# Timeline: agent scrapes with the sink absent (outage) -> agent is killed and
+# restarted -> sink starts -> assert the sink receives datapoints whose scrape
+# timestamps predate the restart. Only the disk-backed queue can deliver
+# those; an in-memory queue would have lost them with the first process.
+# Usage: products/metrics/agent/tests/durability/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 persist-queue render must be valid for the real collector.
+docker run --rm --entrypoint /bin/sh \
+ -e POSTHOG_API_KEY=phc_test -e SCRAPE_TARGETS=app:9090 -e PERSIST_QUEUE=1 \
+ 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 persist-queue collector config validates"
+
+rm -rf out && mkdir -p out && chmod 777 out
+
+cleanup() {
+ docker compose --profile recovery down -v --remove-orphans >/dev/null 2>&1 || true
+}
+trap cleanup EXIT
+
+# Phase 1: outage. The agent scrapes but has nowhere to deliver.
+docker compose up -d fixture agent
+echo "phase 1: scraping during outage (12s)"
+sleep 12
+
+# Phase 2: hard restart. In-memory state dies here; the disk queue must not.
+RESTART_NS=$(date +%s)000000000
+docker compose kill agent
+docker compose up -d agent
+echo "phase 2: agent hard-restarted at $RESTART_NS"
+
+# Phase 3: recovery. The sink appears; the queue should drain into it.
+docker compose --profile recovery up -d sink
+echo "phase 3: sink up, waiting for delivery"
+
+for _ in $(seq 1 60); do
+ [ -s out/metrics.json ] && grep -q http_requests_total out/metrics.json && break
+ sleep 1
+done
+
+if [ ! -s out/metrics.json ]; then
+ echo "FAIL: sink never received metrics after recovery" >&2
+ docker compose logs agent --tail 15
+ exit 1
+fi
+sleep 5
+
+./assert.sh "$RESTART_NS"
diff --git a/products/metrics/agent/tests/helm/golden/default.yaml b/products/metrics/agent/tests/helm/golden/default.yaml
index 457ec3e3d372..3b4fbf159457 100644
--- a/products/metrics/agent/tests/helm/golden/default.yaml
+++ b/products/metrics/agent/tests/helm/golden/default.yaml
@@ -89,6 +89,16 @@ data:
health_check:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
@@ -149,7 +159,7 @@ metadata:
app.kubernetes.io/managed-by: Helm
spec:
# A single replica by design: multiple replicas would scrape every target
- # multiple times and double-count all metrics.
+ # multiple times and double-count all metrics. Scale with shards instead.
replicas: 1
selector:
matchLabels:
@@ -161,7 +171,7 @@ spec:
app.kubernetes.io/name: posthog-metrics-agent
app.kubernetes.io/instance: test-release
annotations:
- checksum/config: 1411c19dbd295f3baa0b938200623d437042a8fbba649ea037b24def467025bb
+ checksum/config: fb8d668241257723315f18c0fe4dd43a8d388a91d53d004a2b77075b8b5d1957
# Covers the chart-managed Secret so an API key rotation rolls the pod.
checksum/secret: e89605c80663cb97ad49cb086ea1470e13424ba9ac0f44429337d2f4e2eff7fe
spec:
@@ -193,6 +203,8 @@ spec:
ports:
- name: health
containerPort: 13133
+ - name: telemetry
+ containerPort: 8888
livenessProbe:
httpGet:
path: /
diff --git a/products/metrics/agent/tests/helm/run.sh b/products/metrics/agent/tests/helm/run.sh
index 28c25303fbf4..f1b8b7b68720 100755
--- a/products/metrics/agent/tests/helm/run.sh
+++ b/products/metrics/agent/tests/helm/run.sh
@@ -104,6 +104,68 @@ assert_contains sa-name-required 'serviceAccount.name is required' "$out"
out=$(render --set posthog.apiKey=phc_test --set posthog.host=https://eu.i.posthog.com)
assert_contains eu-host 'https://eu.i.posthog.com/i/v1/metrics' "$out"
+# --- ingest path override (proxies, test sinks) ---
+out=$(render --set posthog.apiKey=phc_test --set posthog.host=http://sink:4318 --set posthog.ingestPath=/v1/metrics)
+assert_contains ingest-path-override 'http://sink:4318/v1/metrics' "$out"
+
+# --- default: single instance, no sharding machinery ---
+out=$(render --set posthog.apiKey=phc_test)
+assert_contains default-is-deployment 'kind: Deployment' "$out"
+assert_not_contains default-no-statefulset 'kind: StatefulSet' "$out"
+assert_not_contains default-no-hashmod 'action: hashmod' "$out"
+
+# --- shards > 1: StatefulSet fleet partitioning targets via hashmod ---
+out=$(render --set posthog.apiKey=phc_test --set shards=3)
+assert_contains sharded-statefulset 'kind: StatefulSet' "$out"
+assert_not_contains sharded-no-deployment 'kind: Deployment' "$out"
+assert_contains sharded-replicas 'replicas: 3' "$out"
+assert_contains sharded-headless-service 'clusterIP: None' "$out"
+assert_contains sharded-modulus 'modulus: 3' "$out"
+assert_contains sharded-index-env "regex: '\${env:SHARD_INDEX}'" "$out"
+assert_contains sharded-hashmod 'action: hashmod' "$out"
+assert_contains sharded-count-env 'name: SHARD_COUNT' "$out"
+# Every chart-generated scrape job must be sharded, or a job would be
+# scraped by all shards (extraScrapeConfigs are verbatim: sharding those
+# is the author's responsibility, called out in values.yaml).
+static=$(render --set posthog.apiKey=phc_test --set shards=3 -f values/static-targets.yaml)
+assert_contains sharded-static-job-hashmod 'action: hashmod' "$static"
+
+# --- podEnv passthrough: extra agent env vars ---
+out=$(render --set posthog.apiKey=phc_test --set podEnv.POSTHOG_DEBUG=1 --set podEnv.SCRAPE_JOB_NAME=custom)
+assert_contains podenv-debug 'name: POSTHOG_DEBUG' "$out"
+assert_contains podenv-jobname 'name: SCRAPE_JOB_NAME' "$out"
+assert_contains podenv-jobname-value 'value: "custom"' "$out"
+
+# --- persistence: disk-backed delivery queue ---
+out=$(render --set posthog.apiKey=phc_test)
+assert_not_contains default-no-persist-env 'PERSIST_QUEUE' "$out"
+assert_not_contains default-no-pvc 'kind: PersistentVolumeClaim' "$out"
+
+out=$(render --set posthog.apiKey=phc_test --set persistence.enabled=true)
+assert_contains persist-env 'name: PERSIST_QUEUE' "$out"
+assert_contains persist-pvc 'kind: PersistentVolumeClaim' "$out"
+assert_contains persist-mount 'mountPath: /var/lib/posthog-agent' "$out"
+assert_contains persist-fsgroup 'fsGroup: 10001' "$out"
+assert_contains persist-size 'storage: 10Gi' "$out"
+# The mounted config itself must wire the queue: the chart's full-config
+# override means an unreferenced PERSIST_QUEUE env would silently do nothing.
+assert_contains persist-config-queue 'storage: file_storage' "$out"
+assert_contains persist-config-extension 'file_storage:' "$out"
+
+# Default (no persistence) must not carry the queue wiring.
+out=$(render --set posthog.apiKey=phc_test)
+assert_not_contains default-no-queue 'sending_queue' "$out"
+assert_not_contains default-no-file-storage 'file_storage' "$out"
+
+# Self-telemetry endpoint is exposed for operator monitoring.
+assert_contains telemetry-config 'port: 8888' "$out"
+assert_contains telemetry-port 'containerPort: 8888' "$out"
+
+# Sharded + persistent: each pod gets its own queue via claim templates.
+out=$(render --set posthog.apiKey=phc_test --set persistence.enabled=true --set shards=3)
+assert_contains persist-sharded-claim-template 'volumeClaimTemplates:' "$out"
+assert_not_contains persist-sharded-no-standalone-pvc 'kind: PersistentVolumeClaim' "$out"
+
# --- golden drift guard for the fully default render ---
# Blank lines are stripped before comparing: helm 3 and 4 disagree on
# blank-line placement between documents, and that isn't drift we care about.
diff --git a/products/metrics/agent/tests/kind/manifests/fixtures.yaml b/products/metrics/agent/tests/kind/manifests/fixtures.yaml
new file mode 100644
index 000000000000..02effc520bcd
--- /dev/null
+++ b/products/metrics/agent/tests/kind/manifests/fixtures.yaml
@@ -0,0 +1,149 @@
+# Scrape targets for the kind E2E: three pods annotated for discovery and a
+# decoy without annotations that must NOT be scraped. Both serve the
+# integration fixture (OpenMetrics + exemplars) from a ConfigMap.
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: fixture
+ namespace: fixtures
+spec:
+ replicas: 6
+ selector:
+ matchLabels:
+ app: fixture
+ template:
+ metadata:
+ labels:
+ app: fixture
+ annotations:
+ prometheus.io/scrape: 'true'
+ prometheus.io/port: '9464'
+ spec:
+ containers:
+ - name: fixture
+ image: python:3.12-alpine
+ command: [python, /app/fixture_server.py]
+ ports:
+ - containerPort: 9464
+ volumeMounts:
+ - name: server
+ mountPath: /app
+ - name: fixtures
+ mountPath: /app/fixtures
+ volumes:
+ - name: server
+ configMap:
+ name: fixture-server
+ - name: fixtures
+ configMap:
+ name: fixture-payload
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: fixture-decoy
+ namespace: fixtures
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: fixture-decoy
+ template:
+ metadata:
+ labels:
+ app: fixture-decoy
+ spec:
+ containers:
+ - name: fixture
+ image: python:3.12-alpine
+ command: [python, /app/fixture_server.py]
+ ports:
+ - containerPort: 9464
+ volumeMounts:
+ - name: server
+ mountPath: /app
+ - name: fixtures
+ mountPath: /app/fixtures
+ volumes:
+ - name: server
+ configMap:
+ name: fixture-server
+ - name: fixtures
+ configMap:
+ name: fixture-payload
+---
+# In-cluster stand-in for PostHog ingest: OTLP http in, JSON file out.
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: sink-config
+ namespace: fixtures
+data:
+ sink.yaml: |
+ receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+ exporters:
+ file:
+ path: /out/metrics.json
+ service:
+ pipelines:
+ metrics:
+ receivers: [otlp]
+ exporters: [file]
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: sink
+ namespace: fixtures
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: sink
+ template:
+ metadata:
+ labels:
+ app: sink
+ spec:
+ containers:
+ # Keep the collector version in sync with ../../Dockerfile.
+ - name: sink
+ image: otel/opentelemetry-collector-contrib:0.142.0
+ args: ['--config', '/etc/sink/sink.yaml']
+ ports:
+ - containerPort: 4318
+ volumeMounts:
+ - name: config
+ mountPath: /etc/sink
+ - name: out
+ mountPath: /out
+ # The collector image is distroless (no shell), so a busybox
+ # sidecar sharing the output volume lets the test read the file.
+ - name: reader
+ image: busybox:1.37
+ command: [sh, -c, 'sleep 2147483647']
+ volumeMounts:
+ - name: out
+ mountPath: /out
+ volumes:
+ - name: config
+ configMap:
+ name: sink-config
+ - name: out
+ emptyDir: {}
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: sink
+ namespace: fixtures
+spec:
+ selector:
+ app: sink
+ ports:
+ - port: 4318
+ targetPort: 4318
diff --git a/products/metrics/agent/tests/kind/run.sh b/products/metrics/agent/tests/kind/run.sh
new file mode 100755
index 000000000000..35f8eb43c536
--- /dev/null
+++ b/products/metrics/agent/tests/kind/run.sh
@@ -0,0 +1,141 @@
+#!/bin/sh
+# Real-Kubernetes E2E for the agent chart on a kind cluster. Validates the
+# legs compose cannot: restricted Pod Security admission, ClusterRole-backed
+# annotation discovery, StatefulSet ordinal -> SHARD_INDEX derivation,
+# volumeClaimTemplates binding, and exemplars surviving the in-cluster path.
+# Usage: products/metrics/agent/tests/kind/run.sh [--skip-build]
+# Requires: kind, kubectl, helm, jq, docker. Creates/reuses cluster
+# kind-metrics-agent-test; cleans up namespaces but leaves the cluster.
+set -eu
+cd "$(dirname "$0")"
+AGENT_DIR=$(cd ../.. && pwd)
+CLUSTER=metrics-agent-test
+CTX=kind-$CLUSTER
+K="kubectl --context $CTX"
+
+PASS=0
+FAIL=0
+check() {
+ name=$1
+ expected=$2
+ actual=$3
+ if [ "$actual" = "$expected" ]; then
+ echo "PASS $name"
+ PASS=$((PASS + 1))
+ else
+ echo "FAIL $name: expected '$expected', got '$actual'" >&2
+ FAIL=$((FAIL + 1))
+ fi
+}
+
+if [ "${1:-}" != "--skip-build" ]; then
+ docker build -t posthog-metrics-agent:test "$AGENT_DIR"
+fi
+
+kind get clusters 2>/dev/null | grep -qx "$CLUSTER" || kind create cluster --name "$CLUSTER" --wait 120s
+kind load docker-image posthog-metrics-agent:test --name "$CLUSTER"
+
+cleanup() {
+ helm --kube-context "$CTX" uninstall scrape -n agent >/dev/null 2>&1 || true
+ $K delete namespace agent fixtures --ignore-not-found --wait=false >/dev/null 2>&1 || true
+}
+trap cleanup EXIT
+cleanup
+# Namespace deletion is async; wait for full teardown before recreating.
+for _ in $(seq 1 60); do
+ $K get namespace agent fixtures >/dev/null 2>&1 || break
+ sleep 2
+done
+
+# The agent namespace enforces the restricted Pod Security Standard, so pod
+# admission itself asserts the chart's security contexts.
+$K create namespace agent
+$K label namespace agent \
+ pod-security.kubernetes.io/enforce=restricted \
+ pod-security.kubernetes.io/warn=restricted
+$K create namespace fixtures
+$K -n fixtures create configmap fixture-server \
+ --from-file=fixture_server.py=../integration/fixture_server.py
+$K -n fixtures create configmap fixture-payload \
+ --from-file=metrics.openmetrics.txt=../integration/fixtures/metrics.openmetrics.txt
+$K apply -f manifests/fixtures.yaml >/dev/null
+$K -n fixtures rollout status deployment/fixture deployment/fixture-decoy deployment/sink --timeout=180s
+
+helm --kube-context "$CTX" install scrape "$AGENT_DIR/chart/posthog-metrics-agent" \
+ -n agent \
+ --set posthog.apiKey=phc_test \
+ --set posthog.host=http://sink.fixtures.svc.cluster.local:4318 \
+ --set posthog.ingestPath=/v1/metrics \
+ --set shards=2 \
+ --set persistence.enabled=true \
+ --set persistence.size=1Gi \
+ --set scrape.interval=3s \
+ --set image.repository=posthog-metrics-agent \
+ --set image.tag=test \
+ --set image.pullPolicy=Never >/dev/null
+echo "chart installed into restricted namespace"
+
+# Read the sink's output file through its busybox sidecar (the collector
+# image is distroless).
+sink_json() {
+ $K -n fixtures exec deploy/sink -c reader -- cat /out/metrics.json 2>/dev/null
+}
+
+STS=scrape-posthog-metrics-agent
+$K -n agent rollout status "statefulset/$STS" --timeout=180s
+check restricted-admission-ready-pods 2 "$($K -n agent get pods -l app.kubernetes.io/name=posthog-metrics-agent --field-selector=status.phase=Running --no-headers | wc -l | tr -d ' ')"
+
+check pvcs-bound 2 "$($K -n agent get pvc --no-headers 2>/dev/null | grep -c Bound | tr -d ' ')"
+
+# The entrypoint must derive each pod's shard index from its ordinal; read it
+# back from the running collector's environment.
+for i in 0 1; do
+ derived=$($K -n agent exec "$STS-$i" -- sh -c "tr '\0' '\n' </proc/1/environ | sed -n 's/^SHARD_INDEX=//p'")
+ check "shard-index-derived-pod-$i" "$i" "$derived"
+done
+
+# Discovery -> scrape -> OTLP -> sink: wait until series from every annotated
+# fixture pod arrive (the relabel puts the pod name in the `pod` attribute).
+expected_pods=$($K -n fixtures get pods -l app=fixture -o name | sed 's|pod/||' | sort)
+seen=""
+for _ in $(seq 1 60); do
+ seen=$(sink_json | jq -rs '
+ [.[].resourceMetrics[].scopeMetrics[].metrics[]
+ | select(.name == "http_requests_total")
+ | .sum.dataPoints[].attributes[]
+ | select(.key == "pod") | .value.stringValue] | unique | .[]' 2>/dev/null | sort)
+ [ "$seen" = "$expected_pods" ] && break
+ sleep 3
+done
+check discovery-completeness "$expected_pods" "$seen"
+
+decoy_seen=$(sink_json | jq -rs '
+ [.[].resourceMetrics[].scopeMetrics[].metrics[].sum.dataPoints[]?.attributes[]?
+ | select(.key == "pod") | .value.stringValue]
+ | map(select(startswith("fixture-decoy"))) | length')
+check decoy-not-scraped 0 "$decoy_seen"
+
+exemplar=$(sink_json | jq -rs '
+ [.[].resourceMetrics[].scopeMetrics[].metrics[]
+ | select(.name == "http_requests_total")
+ | .sum.dataPoints[].exemplars[]?.traceId] | unique | first')
+check exemplar-survives-k8s-path 4bf92f3577b34da6a3ce929d0e0e4736 "$exemplar"
+
+# Both shards must be doing work. Each collector's own telemetry (:8888,
+# exposed by the chart) reports how many scraped points its prometheus
+# receiver accepted; both > 0 proves the fleet isn't silently idle on one pod.
+# Disjoint partitioning itself is proven exhaustively by the compose scale
+# test (60k series); here we confirm both shards are live in-cluster.
+shard_accepted() {
+ $K -n agent exec "$STS-$1" -- wget -qO- http://127.0.0.1:8888/metrics 2>/dev/null \
+ | awk '/^otelcol_receiver_accepted_metric_points/ {sum += $NF} END {printf "%d", sum}'
+}
+a0=$(shard_accepted 0)
+a1=$(shard_accepted 1)
+echo "accepted metric points: shard0=$a0 shard1=$a1"
+[ "${a0:-0}" -gt 0 ] 2>/dev/null && { echo "PASS shard-0-active"; PASS=$((PASS + 1)); } || { echo "FAIL shard-0-active: accepted 0 points" >&2; FAIL=$((FAIL + 1)); }
+[ "${a1:-0}" -gt 0 ] 2>/dev/null && { echo "PASS shard-1-active"; PASS=$((PASS + 1)); } || { echo "FAIL shard-1-active: accepted 0 points" >&2; FAIL=$((FAIL + 1)); }
+
+echo
+echo "kind tests: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/products/metrics/agent/tests/render/golden/debug.yaml b/products/metrics/agent/tests/render/golden/debug.yaml
index 87bc271baffd..86298fb1c065 100644
--- a/products/metrics/agent/tests/render/golden/debug.yaml
+++ b/products/metrics/agent/tests/render/golden/debug.yaml
@@ -36,6 +36,16 @@ extensions:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
diff --git a/products/metrics/agent/tests/render/golden/minimal.yaml b/products/metrics/agent/tests/render/golden/minimal.yaml
index 2a4bbf6ec566..4b29bc6efc1e 100644
--- a/products/metrics/agent/tests/render/golden/minimal.yaml
+++ b/products/metrics/agent/tests/render/golden/minimal.yaml
@@ -34,6 +34,16 @@ extensions:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
diff --git a/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml b/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml
index cec5e5b1d8c7..9c09b46c8322 100644
--- a/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml
+++ b/products/metrics/agent/tests/render/golden/mounted-scrape-configs.yaml
@@ -31,6 +31,16 @@ extensions:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
diff --git a/products/metrics/agent/tests/render/golden/multi.yaml b/products/metrics/agent/tests/render/golden/multi.yaml
index 3aa06d75edc9..a71738955e8e 100644
--- a/products/metrics/agent/tests/render/golden/multi.yaml
+++ b/products/metrics/agent/tests/render/golden/multi.yaml
@@ -34,6 +34,16 @@ extensions:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
diff --git a/products/metrics/agent/tests/render/golden/persist-queue.yaml b/products/metrics/agent/tests/render/golden/persist-queue.yaml
new file mode 100644
index 000000000000..40915e427f6d
--- /dev/null
+++ b/products/metrics/agent/tests/render/golden/persist-queue.yaml
@@ -0,0 +1,59 @@
+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}'
+ sending_queue:
+ enabled: true
+ # Survives restarts: batches persist to disk until delivered.
+ storage: file_storage
+ retry_on_failure:
+ enabled: true
+
+extensions:
+ file_storage:
+ directory: '${env:QUEUE_DIR:-/var/lib/posthog-agent}'
+ create_directory: true
+ health_check:
+ endpoint: 0.0.0.0:13133
+
+service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ extensions: [health_check, file_storage]
+ 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.yaml
index fb7a34ec30eb..6dc01e5a290f 100644
--- a/products/metrics/agent/tests/render/golden/quoted-target.yaml
+++ b/products/metrics/agent/tests/render/golden/quoted-target.yaml
@@ -34,6 +34,16 @@ extensions:
endpoint: 0.0.0.0:13133
service:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
extensions: [health_check]
pipelines:
metrics:
diff --git a/products/metrics/agent/tests/render/golden/sharded-hostname.yaml b/products/metrics/agent/tests/render/golden/sharded-hostname.yaml
new file mode 100644
index 000000000000..4691046a6119
--- /dev/null
+++ b/products/metrics/agent/tests/render/golden/sharded-hostname.yaml
@@ -0,0 +1,61 @@
+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']
+ # Shard 3 of 4: keep only targets that hash to this shard.
+ relabel_configs:
+ - source_labels: [__address__]
+ modulus: 4
+ target_label: __tmp_shard
+ action: hashmod
+ - source_labels: [__tmp_shard]
+ regex: '3'
+ action: keep
+
+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:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ extensions: [health_check]
+ pipelines:
+ metrics:
+ receivers: [prometheus]
+ processors: [memory_limiter, batch]
+ exporters: [otlphttp]
diff --git a/products/metrics/agent/tests/render/golden/sharded.yaml b/products/metrics/agent/tests/render/golden/sharded.yaml
new file mode 100644
index 000000000000..4a78f6f449c0
--- /dev/null
+++ b/products/metrics/agent/tests/render/golden/sharded.yaml
@@ -0,0 +1,61 @@
+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']
+ # Shard 2 of 4: keep only targets that hash to this shard.
+ relabel_configs:
+ - source_labels: [__address__]
+ modulus: 4
+ target_label: __tmp_shard
+ action: hashmod
+ - source_labels: [__tmp_shard]
+ regex: '2'
+ action: keep
+
+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:
+ # Expose the collector's own metrics (scrape health, queue depth, drops)
+ # on :8888 so the agent is self-observable, the way vmagent exposes its.
+ telemetry:
+ metrics:
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ 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.sh
index 4ee67e8b4b8c..92b92f9a23d5 100755
--- a/products/metrics/agent/tests/render/run.sh
+++ b/products/metrics/agent/tests/render/run.sh
@@ -8,13 +8,16 @@ cd "$(dirname "$0")"
AGENT_DIR=$(cd ../.. && pwd)
PASS=0
FAIL=0
+UPDATE=0
+[ "${1:-}" = "--update-golden" ] && UPDATE=1
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> [VAR=value ...] — renders and diffs against golden/<name>.yaml.
+# Pass --update-golden as the first script arg to overwrite goldens instead.
run_render() {
name=$1
shift
@@ -27,6 +30,11 @@ run_render() {
FAIL=$((FAIL + 1))
return
fi
+ if [ "$UPDATE" = "1" ]; then
+ cp "$out" "golden/$name.yaml"
+ echo "updated golden/$name.yaml"
+ return
+ fi
if diff -u "golden/$name.yaml" "$out"; then
echo "PASS $name"
PASS=$((PASS + 1))
@@ -61,6 +69,21 @@ expect_failure() {
new_case_dir
run_render minimal POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090
+# Every render exposes the collector's own metrics on :8888 for self-monitoring.
+if [ "$UPDATE" != "1" ]; then
+ new_case_dir
+ tele=$(env -i PATH="$PATH" CONFIG_DIR="$CASE_DIR" RENDER_ONLY=1 \
+ POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 \
+ sh "$AGENT_DIR/entrypoint.sh" 2>/dev/null | grep -c 'port: 8888')
+ if [ "$tele" -ge 1 ]; then
+ echo "PASS self-telemetry-port"
+ PASS=$((PASS + 1))
+ else
+ echo "FAIL self-telemetry-port: rendered config does not expose :8888"
+ FAIL=$((FAIL + 1))
+ fi
+fi
+
# 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'
@@ -72,6 +95,27 @@ run_render debug POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 POSTHOG_DEBUG=
new_case_dir
run_render quoted-target POSTHOG_API_KEY=phc_test "SCRAPE_TARGETS=app's-host:9090"
+# PERSIST_QUEUE backs the export queue with disk so a restart during a
+# PostHog outage loses nothing.
+new_case_dir
+run_render persist-queue POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 PERSIST_QUEUE=1
+
+# Sharding: SHARD_COUNT/SHARD_INDEX partition targets via hashmod so N agents
+# split the target set with no coordination, no duplicates, and no gaps.
+new_case_dir
+run_render sharded POSTHOG_API_KEY=phc_test SCRAPE_TARGETS='app:9090, worker:9091' SHARD_COUNT=4 SHARD_INDEX=2
+
+# The shard index falls back to the trailing ordinal of the hostname
+# (StatefulSet pods are named <name>-<ordinal>).
+new_case_dir
+run_render sharded-hostname POSTHOG_API_KEY=phc_test SCRAPE_TARGETS='app:9090, worker:9091' SHARD_COUNT=4 HOSTNAME=posthog-metrics-agent-3
+
+new_case_dir
+expect_failure shard-index-out-of-range 'SHARD_INDEX must be less than SHARD_COUNT' POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 SHARD_COUNT=2 SHARD_INDEX=2
+
+new_case_dir
+expect_failure shard-index-underivable 'SHARD_INDEX' POSTHOG_API_KEY=phc_test SCRAPE_TARGETS=app:9090 SHARD_COUNT=2 HOSTNAME=nodigits
+
# 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
diff --git a/products/metrics/agent/tests/scale/.gitignore b/products/metrics/agent/tests/scale/.gitignore
new file mode 100644
index 000000000000..1fcb1529f8e5
--- /dev/null
+++ b/products/metrics/agent/tests/scale/.gitignore
@@ -0,0 +1 @@
+out
diff --git a/products/metrics/agent/tests/scale/assert.sh b/products/metrics/agent/tests/scale/assert.sh
new file mode 100755
index 000000000000..2f3d9a75350f
--- /dev/null
+++ b/products/metrics/agent/tests/scale/assert.sh
@@ -0,0 +1,79 @@
+#!/bin/sh
+# Completeness + disjointness assertions over the per-shard sink files.
+set -eu
+cd "$(dirname "$0")"
+
+FARM_PORTS=$1
+FARM_SERIES_PER_TARGET=$2
+ELAPSED=$3
+EXPECTED=$((FARM_PORTS * FARM_SERIES_PER_TARGET))
+
+fail=0
+
+# Every farm_series datapoint carries target+series labels; a shard's set is
+# the unique (target, series) pairs it delivered.
+shard_series() {
+ jq -rs '
+ [.[].resourceMetrics[].scopeMetrics[].metrics[]
+ | select(.name == "farm_series")
+ | .gauge.dataPoints[]
+ | ([.attributes[] | select(.key == "target") | .value.stringValue][0])
+ + ":" +
+ ([.attributes[] | select(.key == "series") | .value.stringValue][0])]
+ | unique | .[]
+ ' "$1" 2>/dev/null
+}
+
+total_datapoints() {
+ jq -rs '
+ [.[].resourceMetrics[].scopeMetrics[].metrics[]
+ | select(.name == "farm_series")
+ | .gauge.dataPoints[]] | length
+ ' "$1" 2>/dev/null
+}
+
+union_file=$(mktemp)
+sum_unique=0
+datapoints=0
+for i in 0 1 2 3; do
+ f="out/shard$i.json"
+ shard_series "$f" >"/tmp/shard$i.series"
+ count=$(wc -l <"/tmp/shard$i.series" | tr -d ' ')
+ dp=$(total_datapoints "$f")
+ datapoints=$((datapoints + dp))
+ echo "shard$i: $count unique series, $dp datapoints"
+ sum_unique=$((sum_unique + count))
+ cat "/tmp/shard$i.series" >>"$union_file"
+done
+
+union=$(sort -u "$union_file" | wc -l | tr -d ' ')
+
+if [ "$union" -eq "$EXPECTED" ]; then
+ echo "PASS completeness: union covers all $EXPECTED series"
+else
+ echo "FAIL completeness: union $union != expected $EXPECTED" >&2
+ fail=1
+fi
+
+# If any series were delivered by two shards, the per-shard sum exceeds the union.
+if [ "$sum_unique" -eq "$union" ]; then
+ echo "PASS disjointness: no series delivered by more than one shard"
+else
+ echo "FAIL disjointness: per-shard sum $sum_unique != union $union (overlap)" >&2
+ fail=1
+fi
+
+# No shard may sit idle: hashmod should spread targets roughly evenly.
+for i in 0 1 2 3; do
+ count=$(wc -l <"/tmp/shard$i.series" | tr -d ' ')
+ if [ "$count" -eq 0 ]; then
+ echo "FAIL balance: shard$i delivered nothing" >&2
+ fail=1
+ fi
+done
+[ "$fail" -eq 0 ] && echo "PASS balance: every shard carried load"
+
+echo "throughput: $datapoints datapoints across the fleet in ~${ELAPSED}s ($((datapoints / (ELAPSED > 0 ? ELAPSED : 1))) samples/sec aggregate)"
+
+[ "$fail" -eq 0 ] && echo "scale assertions passed"
+exit "$fail"
diff --git a/products/metrics/agent/tests/scale/docker-compose.yml b/products/metrics/agent/tests/scale/docker-compose.yml
new file mode 100644
index 000000000000..b91202b25fa8
--- /dev/null
+++ b/products/metrics/agent/tests/scale/docker-compose.yml
@@ -0,0 +1,56 @@
+services:
+ farm:
+ image: python:3.12-alpine
+ command: python /app/farm_server.py
+ environment:
+ FARM_BASE_PORT: '9500'
+ FARM_PORTS: '${FARM_PORTS:-40}'
+ FARM_SERIES_PER_TARGET: '${FARM_SERIES_PER_TARGET:-200}'
+ volumes:
+ - ./farm_server.py:/app/farm_server.py: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
+
+ shard0:
+ image: posthog-metrics-agent:test
+ environment: &shard-env
+ POSTHOG_API_KEY: phc_test
+ POSTHOG_HOST: http://sink:4318
+ POSTHOG_INGEST_PATH: /v1/metrics
+ SCRAPE_TARGETS: '${SCRAPE_TARGETS}'
+ SCRAPE_INTERVAL: 2s
+ SHARD_COUNT: '4'
+ # Hostname carries the shard ordinal, as a StatefulSet pod's would;
+ # SHARD_INDEX is intentionally not set so derivation is what's tested.
+ hostname: agent-0
+ depends_on: [farm, sink]
+
+ shard1:
+ image: posthog-metrics-agent:test
+ environment:
+ <<: *shard-env
+ POSTHOG_HOST: http://sink:4418
+ hostname: agent-1
+ depends_on: [farm, sink]
+
+ shard2:
+ image: posthog-metrics-agent:test
+ environment:
+ <<: *shard-env
+ POSTHOG_HOST: http://sink:4518
+ hostname: agent-2
+ depends_on: [farm, sink]
+
+ shard3:
+ image: posthog-metrics-agent:test
+ environment:
+ <<: *shard-env
+ POSTHOG_HOST: http://sink:4618
+ hostname: agent-3
+ depends_on: [farm, sink]
diff --git a/products/metrics/agent/tests/scale/farm_server.py b/products/metrics/agent/tests/scale/farm_server.py
new file mode 100644
index 000000000000..ab00f6a4a6de
--- /dev/null
+++ b/products/metrics/agent/tests/scale/farm_server.py
@@ -0,0 +1,63 @@
+"""Synthetic Prometheus target farm for the sharding scale test.
+
+Serves FARM_PORTS consecutive ports starting at FARM_BASE_PORT. Every port
+answers /metrics with FARM_SERIES_PER_TARGET unique series, each labeled with
+its target port so assertions can attribute every sample to a target.
+"""
+
+import os
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+BASE_PORT = int(os.environ.get("FARM_BASE_PORT", "9500"))
+PORTS = int(os.environ.get("FARM_PORTS", "40"))
+SERIES_PER_TARGET = int(os.environ.get("FARM_SERIES_PER_TARGET", "200"))
+
+
+def render_metrics(port: int) -> bytes:
+ lines = [
+ "# HELP farm_series synthetic scale-test series",
+ "# TYPE farm_series gauge",
+ ]
+ for i in range(SERIES_PER_TARGET):
+ lines.append(f'farm_series{{target="{port}",series="{i}"}} {port}.{i}')
+ lines.append("")
+ return "\n".join(lines).encode()
+
+
+class FarmServer(ThreadingHTTPServer):
+ def __init__(self, port: int) -> None:
+ super().__init__(("0.0.0.0", port), Handler)
+ self.port = port
+
+
+class Handler(BaseHTTPRequestHandler):
+ server: FarmServer
+
+ def do_GET(self) -> None:
+ body = render_metrics(self.server.port)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain; version=0.0.4")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+
+def main() -> None:
+ servers = []
+ for port in range(BASE_PORT, BASE_PORT + PORTS):
+ server = FarmServer(port)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ servers.append(server)
+ print( # noqa: T201 — container log line, the harness's readiness signal
+ f"farm ready: {PORTS} targets on {BASE_PORT}-{BASE_PORT + PORTS - 1}, {SERIES_PER_TARGET} series each",
+ flush=True,
+ )
+ threading.Event().wait()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/products/metrics/agent/tests/scale/run.sh b/products/metrics/agent/tests/scale/run.sh
new file mode 100755
index 000000000000..fbff5b9d7122
--- /dev/null
+++ b/products/metrics/agent/tests/scale/run.sh
@@ -0,0 +1,68 @@
+#!/bin/sh
+# Sharded-fleet scale test: a farm of synthetic Prometheus targets is scraped
+# by 4 agent shards, each delivering to its own sink file. Asserts the fleet
+# partitions the target set: every series arrives (completeness) and no
+# series arrives via two shards (disjointness). Also reports throughput and
+# per-shard memory as evidence for capacity planning.
+# Usage: products/metrics/agent/tests/scale/run.sh [--skip-build]
+set -eu
+cd "$(dirname "$0")"
+AGENT_DIR=$(cd ../.. && pwd)
+
+FARM_PORTS="${FARM_PORTS:-40}"
+FARM_SERIES_PER_TARGET="${FARM_SERIES_PER_TARGET:-200}"
+export FARM_PORTS FARM_SERIES_PER_TARGET
+
+# The agents scrape the farm's ports; hashmod partitions this list.
+SCRAPE_TARGETS=$(i=0; while [ "$i" -lt "$FARM_PORTS" ]; do
+ printf '%sfarm:%s' "${SEP:-}" $((9500 + i))
+ SEP=,
+ i=$((i + 1))
+done)
+export SCRAPE_TARGETS
+
+if [ "${1:-}" != "--skip-build" ]; then
+ docker build -t posthog-metrics-agent:test "$AGENT_DIR"
+fi
+
+# The sharded render must be valid for the real collector, not just goldens.
+docker run --rm --entrypoint /bin/sh \
+ -e POSTHOG_API_KEY=phc_test -e SCRAPE_TARGETS=app:9090 \
+ -e SHARD_COUNT=4 -e SHARD_INDEX=1 \
+ 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 sharded collector config validates"
+
+rm -rf out && mkdir -p out && chmod 777 out
+
+cleanup() {
+ docker compose down -v --remove-orphans >/dev/null 2>&1 || true
+}
+trap cleanup EXIT
+
+docker compose up -d
+START=$(date +%s)
+
+# Wait for every shard to deliver at least one payload (all four files
+# non-empty), then a little longer so each target is scraped repeatedly.
+for _ in $(seq 1 90); do
+ nonempty=0
+ for f in out/shard0.json out/shard1.json out/shard2.json out/shard3.json; do
+ [ -s "$f" ] && nonempty=$((nonempty + 1))
+ done
+ [ "$nonempty" -eq 4 ] && break
+ sleep 1
+done
+if [ "$nonempty" -ne 4 ]; then
+ echo "FAIL: only $nonempty/4 shards delivered anything" >&2
+ docker compose logs --tail 10
+ exit 1
+fi
+sleep 10
+ELAPSED=$(($(date +%s) - START))
+
+# Per-shard memory while the fleet is under load, straight from the runtime.
+docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' \
+ | grep -E 'shard[0-3]' | sed 's/^/mem /'
+
+./assert.sh "$FARM_PORTS" "$FARM_SERIES_PER_TARGET" "$ELAPSED"
diff --git a/products/metrics/agent/tests/scale/sink-config.yaml b/products/metrics/agent/tests/scale/sink-config.yaml
new file mode 100644
index 000000000000..f67613860ab6
--- /dev/null
+++ b/products/metrics/agent/tests/scale/sink-config.yaml
@@ -0,0 +1,44 @@
+# One OTLP receiver + file exporter per shard, so assertions can prove which
+# shard delivered every series.
+receivers:
+ otlp/shard0:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+ otlp/shard1:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4418
+ otlp/shard2:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4518
+ otlp/shard3:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4618
+
+exporters:
+ file/shard0:
+ path: /out/shard0.json
+ file/shard1:
+ path: /out/shard1.json
+ file/shard2:
+ path: /out/shard2.json
+ file/shard3:
+ path: /out/shard3.json
+
+service:
+ pipelines:
+ metrics/shard0:
+ receivers: [otlp/shard0]
+ exporters: [file/shard0]
+ metrics/shard1:
+ receivers: [otlp/shard1]
+ exporters: [file/shard1]
+ metrics/shard2:
+ receivers: [otlp/shard2]
+ exporters: [file/shard2]
+ metrics/shard3:
+ receivers: [otlp/shard3]
+ exporters: [file/shard3]