: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
fix(agent-platform): serve /metrics on the main server in local dev (#65137)
Ben White6614ac991eac
diff --git a/products/agent_platform/services/agent-ingress/src/index.ts b/products/agent_platform/services/agent-ingress/src/index.tsindex 9942fc4a709c..b2ea58930876 100644--- a/products/agent_platform/services/agent-ingress/src/index.ts+++ b/products/agent_platform/services/agent-ingress/src/index.ts@@ -22,6 +22,7 @@ import {HttpClient,initMetrics,installProcessHandlers,+ isDev,PgCredentialBroker,PgIdentityStore,PgRevisionStore,@@ -39,11 +40,15 @@ async function main(): Promise<void> {installProcessHandlers(log)const config = loadAgentIngressConfig()- // Prometheus: Node process defaults + the dedicated scrape server on a- // separate port from the public request listener, so /metrics is never- // exposed on the internet-facing ingress port.+ // Prometheus: Node process defaults. Prod runs a dedicated scrape server on+ // a separate port so /metrics is never exposed on the internet-facing+ // ingress listener. Dev mounts /metrics inside buildApp (no dedicated port —+ // three services on one host would collide); the dev request port isn't+ // public, so that's safe locally only.initMetrics({ service: 'agent-ingress' })- createMetricsServer({ port: config.metricsPort, log })+ if (!isDev()) {+ createMetricsServer({ port: config.metricsPort, log })+ }const posthogDb = createAgentPool(config.posthogDbUrl)const agentDb = createAgentPool(config.agentDbUrl)diff --git a/products/agent_platform/services/agent-ingress/src/routing/server.ts b/products/agent_platform/services/agent-ingress/src/routing/server.tsindex 8b57fd608a25..3b210fc07a71 100644--- a/products/agent_platform/services/agent-ingress/src/routing/server.ts+++ b/products/agent_platform/services/agent-ingress/src/routing/server.ts@@ -8,7 +8,14 @@ import express, { Express, Request, Response } from 'express'import { z } from 'zod'import type { IdentityStore, SecretResolver } from '@posthog/agent-shared'-import { createLogger, RevisionStore, SessionQueue, triggerAuthConfig } from '@posthog/agent-shared'+import {+ createLogger,+ handleMetricsRequest,+ isDev,+ RevisionStore,+ SessionQueue,+ triggerAuthConfig,+} from '@posthog/agent-shared'const log = createLogger('ingress')@@ -114,6 +121,17 @@ export interface BuildAppOpts {export function buildApp(opts: BuildAppOpts): Express {const app = express()+ // Dev only: serve /metrics on the request port (no dedicated scrape server —+ // three services on one host would collide). First in the chain so scrapes+ // bypass logging + routing. Prod uses the dedicated port and never serves+ // /metrics on this public listener.+ if (isDev()) {+ app.use((req, res, next) => {+ if (!handleMetricsRequest(req, res, log)) {+ next()+ }+ })+ }// First in the chain so it sees — and times — every request, including// those that never match a route (404s) or fail body parsing (400s).app.use(requestLogger(log))diff --git a/products/agent_platform/services/agent-janitor/src/index.ts b/products/agent_platform/services/agent-janitor/src/index.tsindex 26fd294c37b7..c21fa32e81a3 100644--- a/products/agent_platform/services/agent-janitor/src/index.ts+++ b/products/agent_platform/services/agent-janitor/src/index.ts@@ -25,6 +25,7 @@ import {createModalSandboxTerminator,initMetrics,installProcessHandlers,+ isDev,MemoryStore,MultiBackendSandboxTerminator,PgApprovalStore,@@ -49,11 +50,14 @@ async function main(): Promise<void> {installProcessHandlers(log)const config = loadAgentJanitorConfig()- // Prometheus: Node process defaults + the dedicated scrape server. The+ // Prometheus: Node process defaults. Prod runs a dedicated scrape server; the// sweep/cron metrics below let an alert catch a wedged singleton (rate of- // *_runs_total → 0); the queue-depth gauge is sampled once per tick.+ // *_runs_total → 0). Dev mounts /metrics on the request port inside+ // buildJanitorApp (no dedicated port — three services on one host collide).initMetrics({ service: 'agent-janitor' })- createMetricsServer({ port: config.metricsPort, log })+ if (!isDev()) {+ createMetricsServer({ port: config.metricsPort, log })+ }// S3 bundle storage is required (enforced on `bundleS3Bucket` in config —// dev default, fails closed at config-load in prod). Endpoint is optional:diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.tsindex eaedf6972ab7..edde1be1018d 100644--- a/products/agent_platform/services/agent-janitor/src/server.ts+++ b/products/agent_platform/services/agent-janitor/src/server.ts@@ -61,9 +61,11 @@ import {createLogger,EMPTY_USAGE_TOTAL,FRAMEWORK_PROMPT_VERSION,+ handleMetricsRequest,instrument,INTERNAL_JWT_AUDIENCE,InternalJwtVerifyError,+ isDev,lastAssistantTextPreview,MemoryStore,readTypedBundle,@@ -293,6 +295,16 @@ const DecideApprovalBodySchema = z.object({export function buildJanitorApp(opts: JanitorServerOpts): Express {const app = express()+ // Dev only: serve /metrics on the request port (no dedicated scrape server —+ // three services on one host would collide). First in the chain so scrapes+ // bypass auth + routing. Prod uses the dedicated port.+ if (isDev()) {+ app.use((req, res, next) => {+ if (!handleMetricsRequest(req, res, log)) {+ next()+ }+ })+ }// JSON bodies up to 8MB cover any reasonable bundle bulk-push (TS source +// a few markdown files). Larger bundles should land an S3 presigned URL// path eventually; flagged in the bundle-push action below.diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.tsindex 67b9b1a637f5..3ab5a732be1c 100644--- a/products/agent_platform/services/agent-runner/src/index.ts+++ b/products/agent_platform/services/agent-runner/src/index.ts@@ -29,6 +29,7 @@ import {EncryptedEnvSecretResolver,EncryptedFields,createMetricsServer,+ handleMetricsRequest,HttpClient,HttpGatewayClient,initMetrics,@@ -71,11 +72,12 @@ async function main(): Promise<void> {installProcessHandlers(log)const config = loadAgentRunnerConfig()- // Prometheus: register Node process defaults + start the dedicated scrape- // server before any work. Separate port from /healthz so the metrics- // surface is independent of the liveness server's lifecycle.+ // Prometheus: register Node process defaults. Prod runs a dedicated scrape+ // server on its own port (independent of /healthz). Dev mounts /metrics on+ // the health server instead (see below) — three services on one host can't+ // all bind the same dedicated port.initMetrics({ service: 'agent-runner' })- const metricsServer = createMetricsServer({ port: config.metricsPort, log })+ const metricsServer = isDev() ? null : createMetricsServer({ port: config.metricsPort, log })// Fail-fast prod guard for the dev-only bearer attached to auth-less// external MCP refs. Prod must route auth via integrations or the@@ -357,7 +359,12 @@ async function main(): Promise<void> {// path, so GET /healthz is the only thing on a port — 200 while running,// 503 once draining so k8s pulls a shutting-down pod out promptly.let healthy = true+ const devMetrics = isDev()const healthServer = createServer((req, res) => {+ // Dev: /metrics rides the health port (no dedicated scrape server).+ if (devMetrics && handleMetricsRequest(req, res, log)) {+ return+ }if (req.url === '/healthz') {res.writeHead(healthy ? 200 : 503, { 'content-type': 'application/json' })res.end(JSON.stringify({ ok: healthy }))@@ -372,7 +379,7 @@ async function main(): Promise<void> {log.info({ sig }, 'shutdown signal received — suspending in-flight sessions')healthy = falsehealthServer.close()- metricsServer.close()+ metricsServer?.close()void worker.stop()}process.on('SIGTERM', () => shutdown('SIGTERM'))diff --git a/products/agent_platform/services/agent-shared/src/runtime/metrics.test.ts b/products/agent_platform/services/agent-shared/src/runtime/metrics.test.tsnew file mode 100644index 000000000000..4777c74c1168--- /dev/null+++ b/products/agent_platform/services/agent-shared/src/runtime/metrics.test.ts@@ -0,0 +1,65 @@+/**+ * `handleMetricsRequest` — the shared scrape handler backing both the dedicated+ * prod server and the dev same-port mount. It must serve only the metrics paths+ * (GET /metrics + /_metrics) and otherwise report "not handled" so the caller+ * falls through to its own routing.+ */++import type { IncomingMessage, ServerResponse } from 'node:http'+import { describe, expect, it } from 'vitest'++import type { Logger } from './logger'+import { handleMetricsRequest } from './metrics'++const log = { error: () => {} } as unknown as Logger++function fakeReqRes(+ method: string,+ url: string+): {+ req: IncomingMessage+ res: ServerResponse & { statusCode: number; headers: Record<string, unknown>; body?: unknown }+ ended: Promise<void>+} {+ let resolveEnd!: () => void+ const ended = new Promise<void>((r) => {+ resolveEnd = r+ })+ const res = {+ statusCode: 0,+ headers: {} as Record<string, unknown>,+ body: undefined as unknown,+ writeHead(status: number, headers?: Record<string, unknown>) {+ this.statusCode = status+ this.headers = headers ?? {}+ return this+ },+ end(body?: unknown) {+ this.body = body+ resolveEnd()+ },+ }+ return { req: { method, url } as IncomingMessage, res: res as never, ended }+}++describe('handleMetricsRequest', () => {+ it.each(['/metrics', '/_metrics', '/metrics?foo=bar'])('serves GET %s', async (url) => {+ const { req, res, ended } = fakeReqRes('GET', url)+ expect(handleMetricsRequest(req, res, log)).toBe(true)+ await ended+ expect(res.statusCode).toBe(200)+ expect(String(res.headers['content-type'])).toContain('text/plain')+ expect(typeof res.body).toBe('string')+ })++ it.each([+ ['GET', '/healthz'],+ ['GET', '/'],+ ['POST', '/metrics'],+ ])('does not handle %s %s (returns false, leaves res untouched)', (method, url) => {+ const { req, res } = fakeReqRes(method, url)+ expect(handleMetricsRequest(req, res, log)).toBe(false)+ expect(res.statusCode).toBe(0)+ expect(res.body).toBeUndefined()+ })+})diff --git a/products/agent_platform/services/agent-shared/src/runtime/metrics.ts b/products/agent_platform/services/agent-shared/src/runtime/metrics.tsindex 9228f6ba124c..96db430a08a0 100644--- a/products/agent_platform/services/agent-shared/src/runtime/metrics.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/metrics.ts@@ -13,10 +13,15 @@* every series, including the Node process defaults, is sliceable per* service in a fleet dashboard) and registers default process metrics* (CPU, RSS/heap, GC pauses, event-loop lag, open FDs).- * 2. `createMetricsServer({ port, log })` on a DEDICATED port (default 6738,- * AGENT_METRICS_PORT) — never the public request port. vmagent scrapes- * the pod on this port; the internet-facing ingress listener never serves- * `/metrics`. The metrics server itself logs nothing per scrape.+ * 2. In prod, `createMetricsServer({ port, log })` on a DEDICATED port+ * (default 6738, AGENT_METRICS_PORT) — never the public request port.+ * vmagent scrapes the pod on this port; the internet-facing ingress+ * listener never serves `/metrics`. The metrics server logs nothing per+ * scrape. In LOCAL DEV the three services share a host, so binding the+ * same dedicated port thrice collides — instead each mounts the+ * `handleMetricsRequest` hook as a subpath on its own main/health server+ * (distinct ports already), and no dedicated server is started. Prod+ * behaviour (and the chart's scrape config) is unchanged.** Express services additionally record `agent_http_request_duration_seconds`* via a tiny middleware (kept in each service so agent-shared stays@@ -27,7 +32,7 @@* against the single shared `register` re-exported here.*/-import { createServer, type Server } from 'node:http'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'import { collectDefaultMetrics, Counter, Gauge, Histogram, register } from 'prom-client'import type { Logger } from './logger'@@ -89,26 +94,39 @@ export function recordHttpRequest(}/**- * Start the dedicated Prometheus scrape server. Serves `GET /metrics` and- * `GET /_metrics` (the chart's default scrape path) from the shared registry;- * everything else 404s. Deliberately silent per request — scrapes fire every- * ~60s and would otherwise flood the log.+ * Serve `GET /metrics` + `GET /_metrics` (the chart's default scrape path) from+ * the shared registry. Returns true if it handled the request (path matched),+ * false otherwise — so the same logic backs both the dedicated prod server and+ * a same-port dev mount on an existing service server. Silent per request.+ */+export function handleMetricsRequest(req: IncomingMessage, res: ServerResponse, log: Logger): boolean {+ const path = (req.url ?? '/').split('?', 1)[0]+ if (req.method === 'GET' && (path === '/metrics' || path === '/_metrics')) {+ register+ .metrics()+ .then((body) => {+ res.writeHead(200, { 'content-type': register.contentType })+ res.end(body)+ })+ .catch((err: unknown) => {+ log.error({ err: err instanceof Error ? err.message : String(err) }, 'metrics.collect_failed')+ res.writeHead(500)+ res.end()+ })+ return true+ }+ return false+}++/**+ * Start the dedicated Prometheus scrape server (prod). Everything other than the+ * metrics paths 404s. Deliberately silent per request — scrapes fire every ~60s+ * and would otherwise flood the log. In dev, services skip this and mount+ * `handleMetricsRequest` on their main server instead (see the module note).*/export function createMetricsServer(opts: { port: number; log: Logger }): Server {const server = createServer((req, res) => {- const url = req.url ?? '/'- if (req.method === 'GET' && (url === '/metrics' || url === '/_metrics')) {- register- .metrics()- .then((body) => {- res.writeHead(200, { 'content-type': register.contentType })- res.end(body)- })- .catch((err: unknown) => {- opts.log.error({ err: err instanceof Error ? err.message : String(err) }, 'metrics.collect_failed')- res.writeHead(500)- res.end()- })+ if (handleMetricsRequest(req, res, opts.log)) {return}res.writeHead(404)