Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

backend: metrics the scan reads from a log tail (requests, CPU and DB bytes per route, last hour) and /metrics (#1880)

0xken15c47b2d2645f5
diff --git a/backend/integration/prismaQueryTiming.test.ts b/backend/integration/prismaQueryTiming.test.ts
new file mode 100644
index 000000000..e62928ef6
--- /dev/null
+++ b/backend/integration/prismaQueryTiming.test.ts
@@ -0,0 +1,65 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import { createMetrics } from '../src/lib/metrics.js'
+import { withQueryStats } from '../src/lib/queryStats.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
+let replica: MongoMemoryReplSet
+let base: PrismaClient
+let uri: string
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ uri = replica.getUri(`query_timing_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ base = new PrismaClient({ datasources: { db: { url: uri } } })
+})
+afterAll(async () => {
+ await base?.$disconnect()
+ await replica?.stop()
+})
+
+async function queryCounts(metrics: ReturnType<typeof createMetrics>) {
+ return (await metrics.registry.metrics()).split('\n').filter(line => line.startsWith('prisma_query_duration_seconds_count'))
+}
+
+describe('Prisma query timing against a real database', () => {
+ it('times model queries, raw commands and queries inside an interactive transaction', async () => {
+ const metrics = createMetrics()
+ const db = withQueryStats(base, () => undefined, undefined, metrics.observeQuery)
+ const id = randomUUID().replaceAll('-', '').slice(0, 24)
+ await db.user.create({ data: { id, externalId: `fixture-${id}`, email: `${id}@example.com`, autonomousEnv: 'prod' } })
+ await db.$transaction(async (tx) => {
+ await tx.user.findUnique({ where: { id } })
+ await tx.user.findUnique({ where: { id } })
+ })
+ await db.$runCommandRaw({ ping: 1 })
+
+ expect((await queryCounts(metrics)).sort()).toEqual([
+ 'prisma_query_duration_seconds_count{model="User",operation="create"} 1',
+ 'prisma_query_duration_seconds_count{model="User",operation="findUnique"} 2',
+ 'prisma_query_duration_seconds_count{model="raw",operation="$runCommandRaw"} 1',
+ ])
+ // The timed client is the same database: what it wrote, the plain client reads.
+ expect(await base.user.findUnique({ where: { id }, select: { email: true } })).toEqual({ email: `${id}@example.com` })
+ })
+
+ it('times the shared backend client, so every route\'s queries are measured', async () => {
+ process.env.DATABASE_URL = uri
+ vi.resetModules()
+ const { prisma } = await import('../src/lib/prisma.js')
+ const { metrics } = await import('../src/lib/metrics.js')
+ await prisma.user.count()
+ expect(await queryCounts(metrics)).toEqual(['prisma_query_duration_seconds_count{model="User",operation="count"} 1'])
+ await prisma.$disconnect()
+ })
+})
diff --git a/backend/package-lock.json b/backend/package-lock.json
index a0079b2d0..417ee75c5 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -20,6 +20,7 @@
"fastify": "^5.6.2",
"http-proxy": "^1.18.1",
"ioredis": "^5.11.1",
+ "prom-client": "^15.1.3",
"ws": "^8.21.0",
"zod": "^4.0.0"
},
@@ -868,6 +869,15 @@
],
"license": "MIT"
},
+ "node_modules/@opentelemetry/api": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz",
+ "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/@oxc-project/types": {
"version": "0.148.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.148.0.tgz",
@@ -1748,6 +1758,12 @@
"node": "*"
}
},
+ "node_modules/bintrees": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/bintrees/-/bintrees-1.0.2.tgz",
+ "integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
+ "license": "MIT"
+ },
"node_modules/bson": {
"version": "6.10.4",
"resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz",
@@ -3663,6 +3679,20 @@
],
"license": "MIT"
},
+ "node_modules/prom-client": {
+ "version": "15.1.3",
+ "resolved": "https://registry.npmjs.org/prom-client/-/prom-client-15.1.3.tgz",
+ "integrity": "sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==",
+ "deprecated": "prom-client has been replaced by @prometheus-io/client",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api": "^1.4.0",
+ "tdigest": "^0.1.1"
+ },
+ "engines": {
+ "node": "^16 || ^18 || >=20"
+ }
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -4115,6 +4145,15 @@
"streamx": "^2.28.1"
}
},
+ "node_modules/tdigest": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/tdigest/-/tdigest-0.1.3.tgz",
+ "integrity": "sha512-zbRt+lT+/H4fRItHshczHErVCQnitJk8MfMT24MqFJf3YL7SJJPqGIGeuOdvxXxM/AHFzKBl7WoyaYwqO9s3Kw==",
+ "license": "MIT",
+ "dependencies": {
+ "bintrees": "1.0.2"
+ }
+ },
"node_modules/teeny-request": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-11.1.1.tgz",
diff --git a/backend/package.json b/backend/package.json
index d926d1732..e842a8ec3 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -40,6 +40,7 @@
"fastify": "^5.6.2",
"http-proxy": "^1.18.1",
"ioredis": "^5.11.1",
+ "prom-client": "^15.1.3",
"ws": "^8.21.0",
"zod": "^4.0.0"
},
diff --git a/backend/scripts/metrics-overhead.ts b/backend/scripts/metrics-overhead.ts
new file mode 100644
index 000000000..dd28a30d8
--- /dev/null
+++ b/backend/scripts/metrics-overhead.ts
@@ -0,0 +1,89 @@
+/**
+ * What the metrics cost: per request (the histogram and the last-hour ring, fed from route latency's hook) and per query (the
+ * histogram on main's one query hook, lib/queryStats.ts, against a throwaway local replica set). Plain and measured alternate so drift in the
+ * machine hits both alike; the median of each is reported.
+ *
+ * npx tsx scripts/metrics-overhead.ts
+ */
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import Fastify from 'fastify'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import { createMetrics } from '../src/lib/metrics.js'
+import { registerRouteLatency } from '../src/lib/routeLatency.js'
+import { withQueryStats } from '../src/lib/queryStats.js'
+
+const ROUNDS = 7
+const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!
+
+async function microsPerCall(times: number, call: () => Promise<unknown>): Promise<number> {
+ const started = performance.now()
+ for (let i = 0; i < times; i++) await call()
+ return ((performance.now() - started) * 1000) / times
+}
+
+async function requestApp(measured: boolean) {
+ const app = Fastify()
+ // Both sides have main's route latency hook; the measured one also feeds the histogram and the last hour.
+ registerRouteLatency(app, { log: () => {}, ...(measured ? { observe: createMetrics().request } : {}) })
+ app.get('/api/super-tabs/:tabId/changes', async () => ({ ok: true }))
+ await app.ready()
+ return app
+}
+
+async function requests() {
+ const plain = await requestApp(false)
+ const measured = await requestApp(true)
+ const get = (app: typeof plain) => () => app.inject({ method: 'GET', url: '/api/super-tabs/c51479bd73b59e58176ad9e4/changes?since=1' })
+ await microsPerCall(5_000, get(plain))
+ await microsPerCall(5_000, get(measured))
+ const [a, b]: number[][] = [[], []]
+ for (let round = 0; round < ROUNDS; round++) {
+ a.push(await microsPerCall(20_000, get(plain)))
+ b.push(await microsPerCall(20_000, get(measured)))
+ }
+ await plain.close()
+ await measured.close()
+ return { plain: median(a), measured: median(b) }
+}
+
+async function queries() {
+ const replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`metrics_overhead_${randomUUID().replaceAll('-', '_')}`)
+ try {
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], { env: { ...process.env, DATABASE_URL: uri }, timeout: 60000 })
+ const client = new PrismaClient({ datasources: { db: { url: uri } } })
+ // Both sides have the hook main already runs; the measured one also feeds the histogram.
+ const base = withQueryStats(client)
+ const timed = withQueryStats(client, undefined, undefined, createMetrics().observeQuery)
+ const id = randomUUID().replaceAll('-', '').slice(0, 24)
+ await client.user.create({ data: { id, externalId: `bench-${id}`, email: `${id}@example.com`, autonomousEnv: 'prod' } })
+ const find = (db: PrismaClient) => () => db.user.findUnique({ where: { id } })
+ await microsPerCall(500, find(base))
+ await microsPerCall(500, find(timed))
+ // Database latency varies more than the extension costs, so alternate call by call and compare the
+ // medians of single calls rather than of batches.
+ const [a, b]: number[][] = [[], []]
+ for (let i = 0; i < 10_000; i++) {
+ a.push(await microsPerCall(1, find(base)))
+ b.push(await microsPerCall(1, find(timed)))
+ }
+ await client.$disconnect()
+ return { plain: median(a), measured: median(b) }
+ } finally {
+ await replica.stop()
+ }
+}
+
+const line = (what: string, { plain, measured }: { plain: number; measured: number }) =>
+ `${what}: ${plain.toFixed(1)} µs plain, ${measured.toFixed(1)} µs measured, +${(measured - plain).toFixed(1)} µs (${(((measured - plain) / plain) * 100).toFixed(1)}%)`
+
+const r = await requests()
+process.stdout.write(`${line('request (Fastify inject, one route)', r)}\n`)
+const q = await queries()
+process.stdout.write(`${line('query (findUnique, local replica set)', q)}\n`)
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 52204310a..8af13ab54 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -78,6 +78,12 @@ const envSchema = z.object({
// Kubernetes sets it, with probes and grace period, as backend/README.md describes.
DRAIN_DELAY_MS: z.coerce.number().int().min(0).max(60_000).default(0),
+ // Prometheus /metrics on an internal listener of its own (lib/metrics.ts), never the public PORT. Always
+ // on; each pm2 worker binds METRICS_PORT_BASE + NODE_APP_INSTANCE. Loopback by default: a pod whose
+ // scraper reads the pod IP sets METRICS_HOST=0.0.0.0 and does NOT list the port on its Service.
+ METRICS_PORT_BASE: z.coerce.number().int().min(1).max(65535).default(9464),
+ METRICS_HOST: z.string().default('127.0.0.1'),
+
// Remote-terminal WebRTC is STUN-only: successful ICE bypasses the backend data relay; failed ICE
// keeps using the existing WebSocket route. Enabled by default; percentage 0 is the kill switch.
TERMINAL_P2P_ROLLOUT_PERCENT: z.coerce.number().int().min(0).max(100).default(100),
diff --git a/backend/src/lib/instance.ts b/backend/src/lib/instance.ts
index 5a31c98f3..be466faa7 100644
--- a/backend/src/lib/instance.ts
+++ b/backend/src/lib/instance.ts
@@ -9,7 +9,7 @@ import { hostname } from 'os'
import { env } from '../config/env.js'
// pm2 sets NODE_APP_INSTANCE to the 0-based worker index; a bare `node dist/server.js` has none → 0.
-const WORKER_INDEX = Number(process.env.NODE_APP_INSTANCE ?? '0') || 0
+export const WORKER_INDEX = Number(process.env.NODE_APP_INSTANCE ?? '0') || 0
/** Unique + stable id for this instance/worker (used as the value of agent:{machineId}:appinst). */
export const INSTANCE_ID = `${env.BACKEND_INSTANCE_ID || hostname()}-${WORKER_INDEX}`
diff --git a/backend/src/lib/lastHour.test.ts b/backend/src/lib/lastHour.test.ts
new file mode 100644
index 000000000..c1895e43b
--- /dev/null
+++ b/backend/src/lib/lastHour.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from 'vitest'
+import { createLastHour, type LastHourOptions } from './lastHour.js'
+
+type Line = Record<string, any>
+
+/** An hour on a clock the test moves: one minute per roll, with `cpuPerMinute` ms of process CPU in each. */
+function hour(options: Partial<LastHourOptions> & { cpuPerMinute?: number } = {}) {
+ let at = 0, cpu = 0
+ const lines: Line[] = []
+ const h = createLastHour({ pod: 'pod-1', now: () => at, cpuMs: () => cpu, log: (message, context) => lines.push({ message, ...context }), ...options })
+ const minute = () => { at += 60_000; cpu += options.cpuPerMinute ?? 0; h.roll() }
+ return { h, lines, minute, last: () => lines.at(-1)! }
+}
+
+describe('the last hour', () => {
+ it('sums every minute of the last 60 and drops older ones, so the newest line alone covers the hour', () => {
+ const { h, minute, last } = hour({ cpuPerMinute: 600 })
+ for (let i = 0; i < 61; i++) {
+ h.request('GET /api/super-tabs/:tabId/changes', 10, false)
+ minute()
+ }
+ expect(last()).toMatchObject({ message: 'last hour', pod: 'pod-1', minutes: 60, windowMs: 3_600_000, requests: 60, cpuMs: 36_000 })
+ expect(last().routes['GET /api/super-tabs/:tabId/changes']).toMatchObject({ n: 60, perMinute: 1, ms: 600, errors: 0 })
+ })
+
+ it('says how much of the hour it covers after a restart', () => {
+ const { h, minute, last } = hour()
+ for (let i = 0; i < 10; i++) { h.request('GET /api/health', 1, false); minute() }
+ expect(last()).toMatchObject({ minutes: 10, windowMs: 600_000, requests: 10 })
+ expect(last().routes['GET /api/health'].perMinute).toBe(1)
+ })
+
+ it('gives CPU and DB bytes per request, the whole process and per route', () => {
+ const { h, minute, last } = hour({ cpuPerMinute: 1_000 })
+ for (let i = 0; i < 4; i++) h.request('GET /api/a', 20, i === 0)
+ h.db(new Map([['http GET /api/a', { n: 8, ms: 4, bytes: 40_000 }], ['web-ws terminal_input', { n: 2, ms: 1, bytes: 500 }]]))
+ h.busy(new Map([['http GET /api/a', 200], ['web-ws terminal_input', 30]]))
+ minute()
+ expect(last()).toMatchObject({ requests: 4, errors: 1, cpuMs: 1_000, cpuMsPerRequest: 250, dbQueries: 10, dbBytes: 40_500, dbBytesPerRequest: 10_000 })
+ expect(last().routes['GET /api/a']).toEqual({ n: 4, perMinute: 4, errors: 1, ms: 80, dbQueries: 8, dbBytes: 40_000, dbBytesPerRequest: 10_000,
+ busyMs: 200, busyMsPerRequest: 50 })
+ expect(last().work).toEqual({ 'web-ws terminal_input': { dbQueries: 2, dbBytes: 500, busyMs: 30 } })
+ })
+
+ it('leaves busy time out when the CPU profile is off, rather than reporting zero', () => {
+ const { h, minute, last } = hour()
+ h.request('GET /api/a', 5, false)
+ minute()
+ expect(last().routes['GET /api/a']).not.toHaveProperty('busyMs')
+ expect(last()).not.toHaveProperty('busyMs')
+ })
+
+ it('reports zero per request for an hour with no requests, never NaN or Infinity', () => {
+ const { h, minute, last } = hour({ cpuPerMinute: 500 })
+ h.db(new Map([['background', { n: 3, ms: 2, bytes: 900 }]]))
+ minute()
+ expect(last()).toMatchObject({ requests: 0, cpuMsPerRequest: 0, dbBytesPerRequest: 0, dbBytes: 900 })
+ expect(JSON.stringify(last())).not.toMatch(/NaN|Infinity|null/)
+ })
+
+ it('keeps at most maxKeys names; any further one counts as other', () => {
+ const { h, minute, last } = hour({ maxKeys: 5, top: 100 })
+ for (let i = 0; i < 9; i++) h.request(`GET /api/r${i}`, 1, false)
+ minute()
+ expect(Object.keys(last().routes)).toHaveLength(5)
+ expect(last().routes.other.n).toBe(5)
+ expect(last()).toMatchObject({ requests: 9, routeCount: 5 })
+ })
+
+ it('caps the sum across minutes too, when each minute brings new names', () => {
+ const { h, minute, last } = hour({ maxKeys: 5, top: 100 })
+ for (let i = 0; i < 9; i++) { h.request(`GET /api/r${i}`, 1, false); minute() }
+ expect(Object.keys(last().routes)).toHaveLength(5)
+ expect(last().routes.other.n).toBe(5)
+ })
+
+ it('lists the routes that took the most time, read the most DB bytes or burned the most CPU', () => {
+ const { h, minute, last } = hour({ top: 2 })
+ h.request('GET /slow', 900, false)
+ h.request('GET /slower', 1_000, false)
+ h.request('GET /heavy', 1, false)
+ h.request('GET /hot', 1, false)
+ h.request('GET /quiet', 1, false)
+ h.db(new Map([['http GET /heavy', { n: 1, ms: 1, bytes: 9_000_000 }]]))
+ h.busy(new Map([['http GET /hot', 5_000]]))
+ minute()
+ expect(Object.keys(last().routes)).toEqual(['GET /slower', 'GET /slow', 'GET /heavy', 'GET /hot'])
+ expect(last()).toMatchObject({ requests: 5, routeCount: 5 })
+ })
+})
+
+describe('the line\'s size (review of #1880)', () => {
+ it('stays under 12 KB, below the 16 KiB where the container runtime splits a log line, and says how many routes it cut', () => {
+ // The worst case: long patterns, the CPU profile on, and the top lists by time, DB bytes and busy time all different.
+ const { h, minute, last } = hour({ cpuPerMinute: 1_000 })
+ const name = (i: number) => `GET /api/super-tabs/:tabId/projects/:projectId/conversations/:conversationId/part-${i}`
+ for (let i = 0; i < 120; i++) h.request(name(i), i < 40 ? 10_000 - i : 1, false)
+ const db = new Map<string, { n: number; ms: number; bytes: number }>(), busy = new Map<string, number>()
+ for (let i = 0; i < 120; i++) {
+ db.set(`http ${name(i)}`, { n: 1, ms: 1, bytes: i >= 40 && i < 60 ? 9_000_000 - i : 1 })
+ busy.set(`http ${name(i)}`, i >= 60 && i < 80 ? 50_000 - i : 1)
+ }
+ for (let i = 0; i < 40; i++) {
+ db.set(`web-ws a-rather-long-frame-type-name-${i}`, { n: 1, ms: 1, bytes: 5_000_000 - i })
+ busy.set(`job a-rather-long-timer-function-name-${i}`, 40_000 - i)
+ }
+ h.db(db)
+ h.busy(busy)
+ minute()
+ const line = last()
+ expect(Buffer.byteLength(JSON.stringify(line))).toBeLessThanOrEqual(12_000)
+ expect(line.routesCut).toBeGreaterThan(0)
+ expect(Object.keys(line.routes).length + line.routesCut).toBe(80)
+ // The totals still cover every route, and the busiest route by time is kept.
+ expect(line).toMatchObject({ requests: 120, routeCount: 120 })
+ expect(line.routes[name(0)]).toBeDefined()
+ })
+
+ it('cuts nothing from a line that fits', () => {
+ const { h, minute, last } = hour()
+ h.request('GET /api/a', 1, false)
+ minute()
+ expect(last().routesCut).toBe(0)
+ })
+})
diff --git a/backend/src/lib/lastHour.ts b/backend/src/lib/lastHour.ts
new file mode 100644
index 000000000..0f590e459
--- /dev/null
+++ b/backend/src/lib/lastHour.ts
@@ -0,0 +1,165 @@
+import { hostname } from 'node:os'
+import { performance } from 'node:perf_hooks'
+import { logger } from '../utils/logger.js'
+
+/**
+ * The last hour of this process, in one line a minute (task #2957). A pod's logs keep only its last ~3 minutes (Ken's
+ * scan, 2026-11-04: 424 lines for 3 pods over an hour), so the per-minute lines (`route latency`, `db by shape`,
+ * `cpu by kind`) cannot be summed over an hour from outside. `last hour` sums the last 60 one-minute buckets of the same
+ * events the Prometheus counters count (lib/metrics.ts): the newest line of each pod is in any log tail, and it alone
+ * gives the hour's requests, CPU and DB bytes per route. Keys are route patterns and kinds of work, never ids; each map
+ * keeps at most `maxKeys`, past that `other`.
+ */
+
+type Totals = { n: number; errors: number; ms: number; dbQueries: number; dbBytes: number; busyMs: number }
+type Minute = { startedAt: number; cpuMs: number; requests: Map<string, Totals>; work: Map<string, Totals>; busy: boolean }
+
+export type DbWindow = ReadonlyMap<string, { n: number; ms: number; bytes: number }>
+export type BusyWindow = ReadonlyMap<string, number>
+
+export type LastHourOptions = {
+ pod?: string
+ /** Minutes the line sums. */
+ minutes?: number
+ /** Routes the line lists by time; half as many more by DB bytes and by busy time. */
+ top?: number
+ /** Names one map keeps, `other` included. */
+ maxKeys?: number
+ /** Bytes the line's JSON may take; its lists are shortened to fit. */
+ maxBytes?: number
+ now?: () => number
+ /** This process's user + system CPU so far, in ms. */
+ cpuMs?: () => number
+ log?: (message: string, context: Record<string, unknown>) => void
+}
+
+export type LastHour = {
+ /** One HTTP response: its `METHOD /pattern`, its time, and whether it failed (5xx). */
+ request(route: string, ms: number, failed: boolean): void
+ /** A minute of `db by shape`: every kind of work's queries, time and result bytes. */
+ db(work: DbWindow): void
+ /** A minute of `cpu by kind` (CPU_SELF_PROFILE=1): every kind of work's busy ms. */
+ busy(work: BusyWindow): void
+ /** Closes this minute and logs the last hour. */
+ roll(): void
+}
+
+const OTHER = 'other'
+const HTTP = 'http '
+const empty = (): Totals => ({ n: 0, errors: 0, ms: 0, dbQueries: 0, dbBytes: 0, busyMs: 0 })
+const per = (total: number, n: number) => n ? Math.round(total / n * 10) / 10 : 0
+
+function slot(map: Map<string, Totals>, key: string, maxKeys: number): Totals {
+ let totals = map.get(key)
+ if (totals) return totals
+ if (map.size >= maxKeys - 1) key = OTHER
+ totals = map.get(key)
+ if (!totals) map.set(key, totals = empty())
+ return totals
+}
+
+function add(into: Totals, from: Totals): void {
+ into.n += from.n; into.errors += from.errors; into.ms += from.ms
+ into.dbQueries += from.dbQueries; into.dbBytes += from.dbBytes; into.busyMs += from.busyMs
+}
+
+/** The first `n` keys of `rows` by `by`, largest first, skipping zeros. */
+const ranked = (rows: Array<[string, Totals]>, by: (t: Totals) => number, n: number) =>
+ rows.filter(([, t]) => by(t) > 0).sort((a, b) => by(b[1]) - by(a[1])).slice(0, n).map(([key]) => key)
+
+const processCpuMs = () => { const used = process.cpuUsage(); return (used.user + used.system) / 1000 }
+
+export function createLastHour({ pod = `${hostname()}:${process.pid}`, minutes = 60, top = 40, maxKeys = 300, maxBytes = 12_000, now = () => performance.now(),
+ cpuMs = processCpuMs, log = (m, c) => logger.info(m, c) }: LastHourOptions = {}): LastHour {
+ const ring: Minute[] = []
+ const fresh = (): Minute => ({ startedAt: now(), cpuMs: 0, requests: new Map(), work: new Map(), busy: false })
+ let current = fresh(), cpuBefore = cpuMs()
+
+ const line = (): Record<string, unknown> => {
+ const requests = new Map<string, Totals>(), work = new Map<string, Totals>()
+ let cpu = 0, busy = false
+ for (const minute of ring) {
+ cpu += minute.cpuMs
+ busy ||= minute.busy
+ for (const [key, t] of minute.requests) add(slot(requests, key, maxKeys), t)
+ for (const [key, t] of minute.work) add(slot(work, key, maxKeys), t)
+ }
+ // A route's DB and busy time are those of its `http` work.
+ for (const [key, t] of requests) {
+ const own = work.get(HTTP + key)
+ if (!own) continue
+ t.dbQueries += own.dbQueries; t.dbBytes += own.dbBytes; t.busyMs += own.busyMs
+ work.delete(HTTP + key)
+ }
+ const all = empty()
+ for (const t of requests.values()) add(all, t)
+ const httpDbBytes = all.dbBytes
+ for (const t of work.values()) { all.dbQueries += t.dbQueries; all.dbBytes += t.dbBytes; all.busyMs += t.busyMs }
+
+ const routeRows = [...requests], workRows = [...work]
+ const busyOf = (t: Totals, perRequest: boolean) => busy ? { busyMs: Math.round(t.busyMs), ...(perRequest ? { busyMsPerRequest: per(t.busyMs, t.n) } : {}) } : {}
+ const totals = {
+ pod, windowMs: ring.length ? Math.round(now() - ring[0]!.startedAt) : 0, minutes: ring.length,
+ requests: all.n, errors: all.errors, cpuMs: Math.round(cpu), cpuMsPerRequest: per(cpu, all.n),
+ dbQueries: all.dbQueries, dbBytes: Math.round(all.dbBytes), dbBytesPerRequest: Math.round(per(httpDbBytes, all.n)), ...busyOf(all, false),
+ routeCount: requests.size,
+ }
+ /** The `limit` routes with the most time, plus half as many by DB bytes and by busy time, and the work by the same. */
+ const lists = (limit: number) => {
+ const half = Math.max(1, Math.floor(limit / 2))
+ const shown = new Set([...ranked(routeRows, t => t.ms, limit), ...ranked(routeRows, t => t.dbBytes, half), ...(busy ? ranked(routeRows, t => t.busyMs, half) : [])])
+ const shownWork = new Set([...ranked(workRows, t => t.dbBytes, half), ...(busy ? ranked(workRows, t => t.busyMs, half) : [])])
+ return {
+ routes: Object.fromEntries([...shown].map(key => {
+ const t = requests.get(key)!
+ return [key, { n: t.n, perMinute: per(t.n, ring.length), errors: t.errors, ms: Math.round(t.ms), dbQueries: t.dbQueries, dbBytes: Math.round(t.dbBytes),
+ dbBytesPerRequest: Math.round(per(t.dbBytes, t.n)), ...busyOf(t, true) }]
+ })),
+ work: Object.fromEntries([...shownWork].map(key => {
+ const t = work.get(key)!
+ return [key, { dbQueries: t.dbQueries, dbBytes: Math.round(t.dbBytes), ...busyOf(t, false) }]
+ })),
+ }
+ }
+ // The container runtime splits a log line past 16 KiB, and the scan would read half a JSON line: shorten the lists,
+ // lowest-ranked first, until the line fits. The totals above always cover every route.
+ const full = lists(top), listed = Object.keys(full.routes).length
+ let picked = full
+ for (let limit = top; limit > 1 && Buffer.byteLength(JSON.stringify({ ...totals, routesCut: 0, ...picked })) > maxBytes;) {
+ limit = Math.max(1, Math.floor(limit * 3 / 4))
+ picked = lists(limit)
+ }
+ return { ...totals, routesCut: listed - Object.keys(picked.routes).length, ...picked }
+ }
+
+ return {
+ request(route, ms, failed) {
+ const t = slot(current.requests, route, maxKeys)
+ t.n++; t.ms += ms
+ if (failed) t.errors++
+ },
+ db(window) {
+ for (const [key, w] of window) { const t = slot(current.work, key, maxKeys); t.dbQueries += w.n; t.dbBytes += w.bytes }
+ },
+ busy(window) {
+ current.busy = true
+ for (const [key, ms] of window) slot(current.work, key, maxKeys).busyMs += ms
+ },
+ roll() {
+ const cpuNow = cpuMs()
+ current.cpuMs = cpuNow - cpuBefore
+ cpuBefore = cpuNow
+ ring.push(current)
+ if (ring.length > minutes) ring.shift()
+ current = fresh()
+ log('last hour', line())
+ },
+ }
+}
+
+/** Rolls the hour every minute. Returns its stop. */
+export function startLastHour(hour: LastHour, everyMs = 60_000): () => void {
+ const timer = setInterval(() => hour.roll(), everyMs)
+ timer.unref()
+ return () => clearInterval(timer)
+}
diff --git a/backend/src/lib/metrics.test.ts b/backend/src/lib/metrics.test.ts
new file mode 100644
index 000000000..f4ce0d407
--- /dev/null
+++ b/backend/src/lib/metrics.test.ts
@@ -0,0 +1,175 @@
+import Fastify from 'fastify'
+import { describe, expect, it, vi } from 'vitest'
+import type { AddressInfo } from 'node:net'
+import { createLastHour } from './lastHour.js'
+import { createMetrics, metricsAddress, startMetricsServer, type Metrics } from './metrics.js'
+import { registerRouteLatency } from './routeLatency.js'
+
+/** The metrics fed as server.ts feeds them: from route latency's one response hook. */
+const registerRequestMetrics = (app: ReturnType<typeof Fastify>, metrics: Metrics) => { registerRouteLatency(app, { log: () => {}, observe: metrics.request }) }
+
+async function appWithMetrics() {
+ const metrics = createMetrics()
+ const app = Fastify()
+ registerRequestMetrics(app, metrics)
+ app.get('/api/things/:id', async () => ({ ok: true }))
+ app.get('/api/broken', async () => { throw new Error('boom') })
+ await app.ready()
+ return { app, metrics }
+}
+
+/** The `_count` sample lines of the request histogram, which name every label set seen. */
+async function requestCounts(metrics: ReturnType<typeof createMetrics>) {
+ return (await metrics.registry.metrics()).split('\n').filter(line => line.startsWith('http_request_duration_seconds_count'))
+}
+
+describe('request latency', () => {
+ it('records the route pattern and status, never the id or query from the URL', async () => {
+ const { app, metrics } = await appWithMetrics()
+ await app.inject({ method: 'GET', url: '/api/things/6a730145e13f6277cdf98c1a?token=secret-value' })
+ await app.inject({ method: 'GET', url: '/api/things/other' })
+ expect(await requestCounts(metrics)).toEqual([
+ 'http_request_duration_seconds_count{method="GET",route="/api/things/:id",status_code="200"} 2',
+ ])
+ const text = await metrics.registry.metrics()
+ expect(text).not.toContain('6a730145e13f6277cdf98c1a')
+ expect(text).not.toContain('secret-value')
+ await app.close()
+ })
+
+ it('records a URL that matches no route as "unrouted", as the per-minute lines do, so scanners cannot grow the label set', async () => {
+ const { app, metrics } = await appWithMetrics()
+ await app.inject({ method: 'GET', url: '/wp-admin/6a730145e13f6277cdf98c1a/install.php' })
+ expect(await requestCounts(metrics)).toEqual([
+ 'http_request_duration_seconds_count{method="GET",route="unrouted",status_code="404"} 1',
+ ])
+ expect(await metrics.registry.metrics()).not.toContain('6a730145e13f6277cdf98c1a')
+ await app.close()
+ })
+
+ it('records a route that throws as a 500', async () => {
+ const { app, metrics } = await appWithMetrics()
+ await app.inject({ method: 'GET', url: '/api/broken' })
+ expect(await requestCounts(metrics)).toEqual([
+ 'http_request_duration_seconds_count{method="GET",route="/api/broken",status_code="500"} 1',
+ ])
+ await app.close()
+ })
+})
+
+describe('what the scan reads: the counters and the last hour from the same events (#2957)', () => {
+ function measured() {
+ const lines: Record<string, any>[] = []
+ let at = 0
+ const hour = createLastHour({ pod: 'pod-1', now: () => at, cpuMs: () => at / 100, log: (_m, c) => lines.push(c) })
+ return { metrics: createMetrics(hour), hour, lines, minute: () => { at += 60_000; hour.roll() } }
+ }
+ const series = async (metrics: ReturnType<typeof createMetrics>, name: string) =>
+ (await metrics.registry.metrics()).split('\n').filter(line => line.startsWith(`${name}{`))
+
+ it('counts each response into the histogram and into the last hour, by route pattern, with 5xx as errors', async () => {
+ const { metrics, lines, minute } = measured()
+ const app = Fastify()
+ registerRequestMetrics(app, metrics)
+ app.get('/api/super-tabs/:tabId/changes', async () => ({ ok: true }))
+ app.get('/api/broken', async () => { throw new Error('boom') })
+ await app.ready()
+ await app.inject({ method: 'GET', url: '/api/super-tabs/c51479bd73b59e58176ad9e4/changes?since=1' })
+ await app.inject({ method: 'GET', url: '/api/broken' })
+ await app.close()
+ minute()
+ expect(lines[0]).toMatchObject({ requests: 2, errors: 1 })
+ expect(Object.keys(lines[0]!.routes).sort()).toEqual(['GET /api/broken', 'GET /api/super-tabs/:tabId/changes'])
+ expect(JSON.stringify(lines[0])).not.toContain('c51479bd73b59e58176ad9e4')
+ })
+
+ it('counts a minute of DB results by kind of work, a bus channel by its kind only, and joins them to the route', async () => {
+ const { metrics, lines, minute } = measured()
+ metrics.request('GET', '/api/a', 200, 0.01)
+ metrics.dbWindow(new Map([['http GET /api/a', { n: 3, ms: 2, bytes: 1_200 }], [`bus web termup`, { n: 1, ms: 1, bytes: 50 }]]))
+ expect(await series(metrics, 'db_result_bytes_total')).toEqual(['db_result_bytes_total{work="http GET /api/a"} 1200', 'db_result_bytes_total{work="bus web termup"} 50'])
+ expect(await series(metrics, 'db_queries_total')).toEqual(['db_queries_total{work="http GET /api/a"} 3', 'db_queries_total{work="bus web termup"} 1'])
+ minute()
+ expect(lines[0]!.routes['GET /api/a']).toMatchObject({ n: 1, dbQueries: 3, dbBytes: 1_200, dbBytesPerRequest: 1_200 })
+ })
+
+ it('counts busy time by kind of work when the CPU profile runs', async () => {
+ const { metrics, lines, minute } = measured()
+ metrics.request('GET', '/api/a', 200, 0.01)
+ metrics.busyWindow(new Map([['http GET /api/a', 250]]))
+ expect(await series(metrics, 'work_busy_seconds_total')).toEqual(['work_busy_seconds_total{work="http GET /api/a"} 0.25'])
+ minute()
+ expect(lines[0]!.routes['GET /api/a']).toMatchObject({ busyMs: 250, busyMsPerRequest: 250 })
+ })
+
+ it('keeps at most 300 kinds of work as labels; any further one counts as other', async () => {
+ const { metrics } = measured()
+ metrics.dbWindow(new Map(Array.from({ length: 310 }, (_, i) => [`job name${i}`, { n: 1, ms: 1, bytes: 10 }] as const)))
+ const rows = await series(metrics, 'db_queries_total')
+ expect(rows).toHaveLength(300)
+ expect(rows).toContain('db_queries_total{work="other"} 11')
+ })
+})
+
+describe('process metrics', () => {
+ it('reports event-loop delay and GC pauses', async () => {
+ const { registry } = createMetrics()
+ const text = await registry.metrics()
+ expect(text).toContain('nodejs_eventloop_lag_p99_seconds')
+ expect(text).toContain('# TYPE nodejs_gc_duration_seconds histogram')
+ })
+})
+
+describe('database query timing', () => {
+ it('labels each query by model and operation only', async () => {
+ const metrics = createMetrics()
+ metrics.observeQuery('User', 'findFirst', 0.15)
+ metrics.observeQuery('raw', '$runCommandRaw', 0.003)
+ const counts = (await metrics.registry.metrics()).split('\n').filter(line => line.startsWith('prisma_query_duration_seconds_count'))
+ expect(counts).toEqual(['prisma_query_duration_seconds_count{model="User",operation="findFirst"} 1',
+ 'prisma_query_duration_seconds_count{model="raw",operation="$runCommandRaw"} 1'])
+ })
+})
+
+describe('metrics listener', () => {
+ it('is always on, with no switch: each pm2 worker gets its own port, on loopback by default', () => {
+ expect(metricsAddress({}, 0)).toEqual({ port: 9464, host: '127.0.0.1' })
+ expect(metricsAddress({}, 3)).toEqual({ port: 9467, host: '127.0.0.1' })
+ expect(metricsAddress({ portBase: 9464 }, 0)).toEqual({ port: 9464, host: '127.0.0.1' })
+ expect(metricsAddress({ portBase: 9464 }, 3)).toEqual({ port: 9467, host: '127.0.0.1' })
+ expect(metricsAddress({ portBase: 9464, host: '0.0.0.0' }, 0)).toEqual({ port: 9464, host: '0.0.0.0' })
+ })
+
+ it('serves the registry at GET /metrics and nothing else', async () => {
+ const metrics = createMetrics()
+ const server = startMetricsServer(metrics.registry, { port: 0, host: '127.0.0.1' })
+ await new Promise(resolve => server.once('listening', resolve))
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ try {
+ const scrape = await fetch(`${base}/metrics`)
+ expect(scrape.status).toBe(200)
+ expect(scrape.headers.get('content-type')).toBe('text/plain; version=0.0.4; charset=utf-8')
+ expect(await scrape.text()).toContain('# TYPE http_request_duration_seconds histogram')
+ expect((await fetch(`${base}/api/health`)).status).toBe(404)
+ expect((await fetch(`${base}/metrics`, { method: 'POST' })).status).toBe(404)
+ } finally {
+ await new Promise(resolve => server.close(resolve))
+ }
+ })
+
+ it('logs a port already in use instead of crashing the API', async () => {
+ const metrics = createMetrics()
+ const first = startMetricsServer(metrics.registry, { port: 0, host: '127.0.0.1' })
+ await new Promise(resolve => first.once('listening', resolve))
+ const lines: string[] = []
+ vi.spyOn(console, 'error').mockImplementation((line: unknown) => { lines.push(String(line)) })
+ const second = startMetricsServer(metrics.registry, { port: (first.address() as AddressInfo).port, host: '127.0.0.1' })
+ await new Promise(resolve => setTimeout(resolve, 50))
+ vi.restoreAllMocks()
+ expect(second.listening).toBe(false)
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toContain('metrics listener failed')
+ expect(lines[0]).toContain('EADDRINUSE')
+ await new Promise(resolve => first.close(resolve))
+ })
+})
diff --git a/backend/src/lib/metrics.ts b/backend/src/lib/metrics.ts
new file mode 100644
index 000000000..93384f88a
--- /dev/null
+++ b/backend/src/lib/metrics.ts
@@ -0,0 +1,109 @@
+import http from 'node:http'
+import { collectDefaultMetrics, Counter, Histogram, Registry } from 'prom-client'
+import { createLastHour, type BusyWindow, type DbWindow, type LastHour } from './lastHour.js'
+import { logger } from '../utils/logger.js'
+
+/**
+ * Prometheus metrics for this process. Node's defaults bring event-loop delay (perf_hooks
+ * monitorEventLoopDelay, as nodejs_eventloop_lag_*) and GC pauses (a PerformanceObserver on 'gc', as
+ * nodejs_gc_duration_seconds) along with heap, handles and CPU (process_cpu_seconds_total).
+ *
+ * What the production scan reads (task #2957) is counted here once and goes two ways: cumulative series for a scraper
+ * at /metrics, and the one-minute buckets of `last hour` (lib/lastHour.ts), the line the scan reads from a log tail.
+ *
+ * Labels stay small and bounded: a method, a route PATTERN, a status code, a Prisma model and
+ * operation, a kind of work (lib/queryStats.ts workKind). Never a raw URL, a tab, person or machine id —
+ * each would be a new series per value. Kinds of work are capped at MAX_WORK, past that `other`.
+ */
+export function createMetrics(hour: LastHour = createLastHour()) {
+ const registry = new Registry()
+ collectDefaultMetrics({ register: registry })
+ const httpDuration = new Histogram({
+ name: 'http_request_duration_seconds',
+ help: 'Control API request duration, by route pattern and status',
+ labelNames: ['method', 'route', 'status_code'] as const,
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
+ registers: [registry],
+ })
+ const queryDuration = new Histogram({
+ name: 'prisma_query_duration_seconds',
+ help: 'Database query duration through Prisma, by model and operation',
+ labelNames: ['model', 'operation'] as const,
+ buckets: [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5],
+ registers: [registry],
+ })
+ const dbQueries = new Counter({ name: 'db_queries_total', help: 'Database queries, by kind of work', labelNames: ['work'] as const, registers: [registry] })
+ const dbBytes = new Counter({ name: 'db_result_bytes_total', help: 'Database result bytes (JSON characters, sampled and scaled up), by kind of work',
+ labelNames: ['work'] as const, registers: [registry] })
+ const workBusy = new Counter({ name: 'work_busy_seconds_total', help: 'Main-thread busy time, by kind of work, while CPU_SELF_PROFILE=1',
+ labelNames: ['work'] as const, registers: [registry] })
+ const works = new Set<string>()
+ const work = (kind: string) => {
+ if (works.has(kind)) return kind
+ if (works.size >= MAX_WORK - 1) { works.add(OTHER); return OTHER }
+ works.add(kind)
+ return kind
+ }
+ return {
+ registry, hour,
+ /** One Prisma operation's time, from the one query hook (lib/queryStats.ts withQueryStats). */
+ observeQuery(model: string, operation: string, seconds: number) { queryDuration.observe({ model, operation }, seconds) },
+ /** One HTTP response, by its route pattern (`unrouted` without one), from route latency's hook (lib/routeLatency.ts). */
+ request(method: string, route: string, status: number, seconds: number) {
+ httpDuration.observe({ method, route, status_code: String(status) }, seconds)
+ hour.request(`${method} ${route}`, seconds * 1000, status >= 500)
+ },
+ /** A minute of `db by shape`, every kind of work's queries and result bytes. */
+ dbWindow(window: DbWindow) {
+ for (const [kind, w] of window) {
+ const labels = { work: work(kind) }
+ dbQueries.inc(labels, w.n)
+ dbBytes.inc(labels, w.bytes)
+ }
+ hour.db(window)
+ },
+ /** A minute of `cpu by kind`, every kind of work's busy ms. */
+ busyWindow(window: BusyWindow) {
+ for (const [kind, ms] of window) workBusy.inc({ work: work(kind) }, ms / 1000)
+ hour.busy(window)
+ },
+ }
+}
+
+export type Metrics = ReturnType<typeof createMetrics>
+
+/** Kinds of work one process labels, `other` included. */
+const MAX_WORK = 300
+const OTHER = 'other'
+
+/** This process's metrics, served by startMetricsServer. */
+export const metrics = createMetrics()
+
+/**
+ * Where this worker serves /metrics: always on, with no switch; each pm2 worker binds base + its index (as the mesh
+ * port does); loopback unless the deploy says otherwise. Never the public control port.
+ */
+export function metricsAddress({ portBase = 9464, host = '127.0.0.1' }: { portBase?: number; host?: string }, workerIndex: number) {
+ return { port: portBase + workerIndex, host }
+}
+
+/** A listener of its own for the scraper: GET /metrics, and 404 for everything else. A failure to bind is logged. */
+export function startMetricsServer(registry: Registry, { port, host }: { port: number; host: string }): http.Server {
+ const server = http.createServer((req, res) => {
+ if (req.method !== 'GET' || (req.url ?? '').split('?')[0] !== '/metrics') {
+ res.writeHead(404).end()
+ return
+ }
+ registry.metrics().then(
+ (text) => { res.writeHead(200, { 'Content-Type': registry.contentType }).end(text) },
+ (err) => { logger.error('metrics scrape failed', err); res.writeHead(500).end() },
+ )
+ })
+ // A port already taken must cost the scrape, not the API: unhandled, this 'error' reaches
+ // uncaughtException in server.ts, which drains every socket and exits.
+ server.on('error', (err) => { logger.error('metrics listener failed', err, { host, port }) })
+ server.listen(port, host, () => {
+ logger.info(`backend metrics listener on ${host}:${(server.address() as { port: number }).port}`)
+ })
+ return server
+}
diff --git a/backend/src/lib/prisma.ts b/backend/src/lib/prisma.ts
index 51416d500..9146ddc67 100644
--- a/backend/src/lib/prisma.ts
+++ b/backend/src/lib/prisma.ts
@@ -2,14 +2,16 @@ import { PrismaClient, type Prisma } from '@prisma/client'
import { env } from '../config/env.js'
import { POOL_DEFAULTS, withPoolDefaults } from './databaseUrl.js'
import { withQueryStats } from './queryStats.js'
+import { metrics } from './metrics.js'
// The Prisma CLI (db push) reads env("DATABASE_URL"); keep it in sync for any manual run.
process.env.DATABASE_URL ??= env.DATABASE_URL
-// Every query is timed for the per-minute `db by shape` log (lib/queryStats.ts, DB roadmap Phase 1).
+// Every query is timed for the per-minute `db by shape` log (lib/queryStats.ts, DB roadmap Phase 1) and into
+// prisma_query_duration_seconds (lib/metrics.ts).
export const prisma = withQueryStats(new PrismaClient({
datasources: { db: { url: withPoolDefaults(env.DATABASE_URL, POOL_DEFAULTS) } },
-}))
+}), undefined, undefined, metrics.observeQuery)
/** "Not soft-deleted" filter for Machine findMany where-clauses. Mongo-Prisma gotcha: legacy
* rows have NO `deletedAt` field and `{deletedAt: null}` matches only an explicit null, so the
diff --git a/backend/src/lib/queryStats.test.ts b/backend/src/lib/queryStats.test.ts
index f8497cfb1..3d93b2df4 100644
--- a/backend/src/lib/queryStats.test.ts
+++ b/backend/src/lib/queryStats.test.ts
@@ -1,6 +1,7 @@
import Fastify from 'fastify'
import { afterEach, describe, expect, it } from 'vitest'
-import { createQueryStats, enterWork, estimateBytes, filterShape, registerWorkContext, runWork, workKind, type QueryStatsOptions } from './queryStats.js'
+import type { PrismaClient } from '@prisma/client'
+import { createQueryStats, enterWork, estimateBytes, filterShape, registerWorkContext, runWork, withQueryStats, workKind, type QueryStatsOptions } from './queryStats.js'
type Logged = { message: string; context: Record<string, unknown> }
@@ -251,3 +252,51 @@ describe('estimateBytes', () => {
expect(infos[0]!.context).toMatchObject({ bytesCapped: 1 })
})
})
+
+describe('the query hook', () => {
+ type Call = { model?: string; operation: string; args: unknown; query: (args: unknown) => Promise<unknown> }
+ /** A client whose only part is `$extends`: it keeps the hook so a test can call it as Prisma would. */
+ function hooked(observe: (model: string, operation: string, seconds: number) => void) {
+ let hook: ((call: Call) => Promise<unknown>) | undefined
+ const client = { $extends: (extension: { query: { $allOperations: (call: Call) => Promise<unknown> } }) => { hook = extension.query.$allOperations; return client } }
+ withQueryStats(client as unknown as PrismaClient, () => undefined, () => {}, observe)
+ return (call: Call) => hook!(call)
+ }
+
+ it('times every query once into the duration histogram, a failed one and a raw command too (#1880)', async () => {
+ const seen: Array<[string, string, number]> = []
+ const run = hooked((model, operation, seconds) => { seen.push([model, operation, seconds]) })
+ await expect(run({ model: 'User', operation: 'findFirst', args: { where: { email: '[email protected]' } }, query: async () => ({ id: 'u1' }) })).resolves.toEqual({ id: 'u1' })
+ const failure = new Error('write conflict')
+ await expect(run({ model: 'User', operation: 'update', args: {}, query: async () => { throw failure } })).rejects.toBe(failure)
+ await run({ operation: '$runCommandRaw', args: { ping: 1 }, query: async () => ({ ok: 1 }) })
+ expect(seen.map(([model, operation]) => [model, operation])).toEqual([['User', 'findFirst'], ['User', 'update'], ['raw', '$runCommandRaw']])
+ for (const [, , seconds] of seen) expect(seconds).toBeGreaterThanOrEqual(0)
+ expect(JSON.stringify(seen)).not.toContain('[email protected]')
+ })
+
+ it('keeps a query\'s result when the histogram throws', async () => {
+ const run = hooked(() => { throw new Error('registry broke') })
+ await expect(run({ model: 'User', operation: 'count', args: {}, query: async () => 3 })).resolves.toBe(3)
+ })
+})
+
+describe('the minute handed on to the counters (#2957)', () => {
+ it('hands every route of the minute to onWindow, not only the 40 the line lists', () => {
+ const windows: Array<Map<string, { n: number; ms: number; bytes: number }>> = []
+ const { s, infos } = stats({ sampleEvery: 1, onWindow: routes => { windows.push(new Map(routes)) } })
+ for (let i = 0; i < 45; i++) runWork(`http GET /api/r${i}`, () => s.record('User', 'findFirst', { where: { k: 'y' } }, 1, [{ a: 1 }]))
+ s.flush()
+ expect(Object.keys(infos[0]!.context.routes as object)).toHaveLength(40)
+ expect(windows[0]!.size).toBe(45)
+ expect(windows[0]!.get('http GET /api/r44')).toMatchObject({ n: 1, ms: 1, bytes: JSON.stringify([{ a: 1 }]).length })
+ })
+
+ it('still logs its line, and warns, when onWindow throws', () => {
+ const { s, infos, warns } = stats({ onWindow: () => { throw new Error('counter broke') } })
+ runWork('http GET /api/a', () => s.record('User', 'count', {}, 1, 3))
+ expect(() => s.flush()).not.toThrow()
+ expect(infos).toHaveLength(1)
+ expect(warns.map(w => w.message)).toContain('query stats window failed')
+ })
+})
diff --git a/backend/src/lib/queryStats.ts b/backend/src/lib/queryStats.ts
index 0382ed815..6744fd12c 100644
--- a/backend/src/lib/queryStats.ts
+++ b/backend/src/lib/queryStats.ts
@@ -214,6 +214,8 @@ export type QueryStatsOptions = {
top?: { bytes: number; count: number; ms: number }
log?: (message: string, context: Record<string, unknown>) => void
warn?: (message: string, context: Record<string, unknown>) => void
+ /** Every route's totals of the window, before the line's top-40 cut: the counters and the last hour (lib/metrics.ts). */
+ onWindow?: (routes: ReadonlyMap<string, { n: number; ms: number; docs: number; bytes: number }>) => void
}
export type QueryStats = {
@@ -225,7 +227,7 @@ export type QueryStats = {
const OTHER = 'other'
export function createQueryStats({ pod = `${hostname()}:${process.pid}`, slowMs = 200, slowPerWindow = 20, maxKeys = 1000, sampleEvery = 8, byteBudget = BYTE_BUDGET,
- top = { bytes: 20, count: 10, ms: 10 }, log = (m, c) => logger.info(m, c), warn = (m, c) => logger.warn(m, c) }: QueryStatsOptions = {}): QueryStats {
+ top = { bytes: 20, count: 10, ms: 10 }, log = (m, c) => logger.info(m, c), warn = (m, c) => logger.warn(m, c), onWindow }: QueryStatsOptions = {}): QueryStats {
let entries = new Map<string, Entry>()
let overflowQueries = 0, slowLogged = 0, slowSuppressed = 0, slowQueries = 0, slowTotalMs = 0, bytesCapped = 0, started = performance.now()
@@ -282,6 +284,8 @@ export function createQueryStats({ pod = `${hostname()}:${process.pid}`, slowMs
if (!total) routes.set(r.route, total = { n: 0, ms: 0, docs: 0, bytes: 0, ops: {} })
total.n += r.n; total.ms += r.ms; total.docs += r.docs; total.bytes += r.bytes; total.ops[r.op] = (total.ops[r.op] ?? 0) + r.n
}
+ // A failure here must cost the counters, not the line, nor the timer (an exception there would end the process).
+ try { onWindow?.(routes) } catch (error) { warn('query stats window failed', { error: error instanceof Error ? error.message : String(error) }) }
const byRoute = Object.fromEntries([...routes].sort((a, b) => b[1].ms - a[1].ms).slice(0, 40).map(([route, t]) =>
[route, { ...t, ops: Object.fromEntries(Object.entries(t.ops).sort((a, b) => b[1] - a[1]).slice(0, 12)) }]))
log('db by shape', { pod, windowMs: Math.round(performance.now() - started), queries: sum(r => r.n), ms: sum(r => r.ms), docs: sum(r => r.docs),
@@ -311,14 +315,17 @@ export function startQueryStats(options: QueryStatsOptions & { reportMs?: number
}
}
-/** The client with one query hook that times every operation, model calls and raw commands alike, for `db by shape`.
- * Query extensions keep the client's types, so it is still a PrismaClient to its callers. A failure of the stats never
- * reaches the query: it is warned about once per client, and the query's own result or error goes back unchanged. */
+/** The client with one query hook that times every operation, model calls and raw commands alike, for `db by shape` and
+ * for `observe` (the Prometheus histogram, lib/metrics.ts; `raw` for a call without a model). Query extensions keep the
+ * client's types, so it is still a PrismaClient to its callers. A failure of either never reaches the query: it is warned
+ * about once per client, and the query's own result or error goes back unchanged. */
export function withQueryStats(client: PrismaClient, stats: () => QueryStats | undefined = () => active,
- warn: (message: string, context: Record<string, unknown>) => void = (m, c) => logger.warn(m, c)): PrismaClient {
+ warn: (message: string, context: Record<string, unknown>) => void = (m, c) => logger.warn(m, c),
+ observe?: (model: string, operation: string, seconds: number) => void): PrismaClient {
let warned = false
const note = (model: string | undefined, operation: string, args: unknown, ms: number, result: unknown, failed: boolean) => {
try {
+ observe?.(model ?? 'raw', operation, ms / 1000)
stats()?.record(model, operation, args, ms, result, failed)
} catch (error) {
if (warned) return
diff --git a/backend/src/lib/routeLatency.test.ts b/backend/src/lib/routeLatency.test.ts
index c9e64a4f6..58fa778aa 100644
--- a/backend/src/lib/routeLatency.test.ts
+++ b/backend/src/lib/routeLatency.test.ts
@@ -105,3 +105,17 @@ it('leaves empty and bytes out of a route that has none', () => {
l.flush()
expect(routes()['GET /a']).toEqual({ n: 1, p50: 1, p95: 1, max: 1 })
})
+
+it('hands each response to the metrics from the same hook, by pattern and status, so a request is timed once (review of #1880)', async () => {
+ const seen: Array<[string, string, number, number]> = []
+ const app = Fastify()
+ registerRouteLatency(app, { pod: 'p', log: () => {}, observe: (method, route, status, seconds) => { seen.push([method, route, status, seconds]) } })
+ app.get('/api/things/:id', async () => ({ ok: true }))
+ await app.ready()
+ await app.inject({ method: 'GET', url: '/api/things/6a730145e13f6277cdf98c1a?token=secret-value' })
+ await app.inject({ method: 'GET', url: '/wp-admin/6a730145e13f6277cdf98c1a' })
+ await app.close()
+ expect(seen.map(([method, route, status]) => [method, route, status])).toEqual([['GET', '/api/things/:id', 200], ['GET', 'unrouted', 404]])
+ for (const [, , , seconds] of seen) expect(seconds).toBeGreaterThanOrEqual(0)
+ expect(JSON.stringify(seen)).not.toContain('6a730145e13f6277cdf98c1a')
+})
diff --git a/backend/src/lib/routeLatency.ts b/backend/src/lib/routeLatency.ts
index 2c53d21f6..757d6e5fc 100644
--- a/backend/src/lib/routeLatency.ts
+++ b/backend/src/lib/routeLatency.ts
@@ -91,8 +91,13 @@ export function createRouteLatency({ pod = `${hostname()}:${process.pid}`, maxSa
return { record, flush }
}
-/** Records every response's time under its route pattern. Returns the recorder, for a flush on shutdown. */
-export function registerRouteLatency(app: FastifyInstance, options: RouteLatencyOptions = {}): RouteLatency {
+/** Each response, by method, route pattern (`unrouted` without one) and status: the Prometheus histogram and the last
+ * hour (lib/metrics.ts), fed from this one hook so a request is timed once. */
+export type ObserveResponse = (method: string, route: string, status: number, seconds: number) => void
+
+/** Records every response's time under its route pattern, and hands it to `observe`. Returns the recorder, for a flush
+ * on shutdown. */
+export function registerRouteLatency(app: FastifyInstance, { observe, ...options }: RouteLatencyOptions & { observe?: ObserveResponse } = {}): RouteLatency {
const latency = createRouteLatency(options)
app.addHook('onSend', (request, _reply, payload, done) => {
const bytes = typeof payload === 'string' ? Buffer.byteLength(payload) : Buffer.isBuffer(payload) ? payload.length : 0
@@ -101,8 +106,10 @@ export function registerRouteLatency(app: FastifyInstance, options: RouteLatency
})
app.addHook('onResponse', (request, reply, done) => {
const asAgent = typeof (request.query as Record<string, unknown> | undefined)?.asAgentId === 'string'
- latency.record(`${request.method} ${request.routeOptions.url ?? 'unrouted'}`, reply.elapsedTime, clientKind(request.headers['user-agent'], asAgent),
+ const route = request.routeOptions.url ?? 'unrouted'
+ latency.record(`${request.method} ${route}`, reply.elapsedTime, clientKind(request.headers['user-agent'], asAgent),
{ empty: nothingNew.has(request), bytes: replyBytes.get(request) })
+ observe?.(request.method, route, reply.statusCode, reply.elapsedTime / 1000)
done()
})
return latency
diff --git a/backend/src/lib/selfProfile.test.ts b/backend/src/lib/selfProfile.test.ts
index 96c2b0d40..7fa634fdc 100644
--- a/backend/src/lib/selfProfile.test.ts
+++ b/backend/src/lib/selfProfile.test.ts
@@ -1,6 +1,7 @@
import Fastify from 'fastify'
import { afterEach, expect, it } from 'vitest'
-import { busKind, frameKind, markCpuKind, selfProfileFromEnv, startSelfProfile, topCalls, topSelfTime } from './selfProfile.js'
+import { readFileSync } from 'node:fs'
+import { BUS_CHANNEL_KINDS, busKind, frameKind, markCpuKind, selfProfileFromEnv, startSelfProfile, topCalls, topSelfTime } from './selfProfile.js'
import { enterWork, workKind } from './queryStats.js'
let stop = () => {}
@@ -149,3 +150,42 @@ it('names a Redis message by its subscriber and channel kind, never the id in th
expect(busKind('main', 'Weird Channel:1')).toBe('bus main other')
expect(busKind('main', `${'x'.repeat(40)}:1`)).toBe('bus main other')
})
+
+it('names only the bus\'s own channel kinds; an id sent as a whole channel name, or an unknown kind, counts as other (review of #1880)', () => {
+ // These names are Prometheus labels too (work_busy_seconds_total, db_queries_total), so a bare id must never pass.
+ expect(busKind('main', '6a730145e13f6277cdf98c1a')).toBe('bus main other')
+ expect(busKind('main', 'person-name')).toBe('bus main other')
+ expect(busKind('main', 'newkind:6a730145e13f6277cdf98c1a')).toBe('bus main other')
+ expect(busKind('main', 'swarm-deliveries:m1')).toBe('bus main swarm-deliveries')
+})
+
+it('knows every channel kind the bus subscribes to, so none counts as other by mistake', () => {
+ const source = readFileSync(new URL('./bus.ts', import.meta.url), 'utf8')
+ const prefixes = [...source.matchAll(/`([a-z0-9-]+):\$\{/g)].map(m => m[1]!)
+ // Calls only: `addSub(X, …)`, `addBinarySub(X, …)`, `addSubOn(someSubscriber, X, …)`; a definition's typed parameters (`channel: string`) are not calls.
+ const subscribed = [...source.matchAll(/\b(?:addSub|addBinarySub)\(\s*([^,]+),|\baddSubOn\(\s*\w+Subscriber,\s*([^,]+),/g)]
+ .map(m => (m[1] ?? m[2])!.trim()).filter(channel => !/:\s/.test(channel))
+ // Each subscribed channel is a `kind:${id}` literal, a builder made from one, or SWARM_STAMP.
+ expect(subscribed.length).toBeGreaterThan(20)
+ const builders = new Map([...source.matchAll(/const (\w+) = \([^)]*\): string => `([a-z0-9-]+):/g)].map(m => [m[1]!, m[2]!]))
+ const kinds = new Set<string>()
+ for (const channel of subscribed) {
+ if (channel === 'channel') continue // addSub's own body passes its parameter on
+ if (channel === 'SWARM_STAMP') { kinds.add('swarm-stamp'); continue }
+ const literal = channel.match(/^`([a-z0-9-]+):/)
+ const builder = builders.get(channel.replace(/\(.*$/, ''))
+ const kind = literal?.[1] ?? builder
+ expect(kind, channel).toBeDefined()
+ kinds.add(kind!)
+ }
+ for (const kind of kinds) expect(BUS_CHANNEL_KINDS.has(kind), kind).toBe(true)
+ expect(prefixes.length).toBeGreaterThan(0)
+})
+
+it('hands every kind\'s busy ms of the minute to onWindow, for the counters and the last hour (#2957)', async () => {
+ const windows: Array<Map<string, number>> = []
+ stop = startSelfProfile({ everyMs: 3_600_000, reportMs: 200, log: () => {}, onWindow: busy => { windows.push(new Map(busy)) } })
+ await new Promise<void>(resolve => setImmediate(() => { markCpuKind('http GET /api/y'); spin(30); resolve() }))
+ await reported(windows)
+ expect(windows[0]!.get('http GET /api/y')).toBeGreaterThanOrEqual(25)
+})
diff --git a/backend/src/lib/selfProfile.ts b/backend/src/lib/selfProfile.ts
index 40367b582..a5289ed82 100644
--- a/backend/src/lib/selfProfile.ts
+++ b/backend/src/lib/selfProfile.ts
@@ -58,12 +58,18 @@ export function frameKind(prefix: string, type: unknown, known: ReadonlySet<stri
return `${prefix} ${typeof type === 'string' && known.has(type) ? type : 'other'}`
}
+/** Every kind of channel the bus subscribes to (lib/bus.ts), the name before its first `:`; a test keeps the two in step. */
+export const BUS_CHANNEL_KINDS: ReadonlySet<string> = new Set(['amsg', 'amsg-share', 'appdown', 'appup', 'connvault', 'desk', 'devctl', 'deve2eepair',
+ 'devkeys', 'devmachines', 'devstatus', 'down', 'harness-share', 'machine-share', 'mgr', 'mgrreply', 'status', 'swarm-access', 'swarm-deliveries',
+ 'swarm-host', 'swarm-member', 'swarm-stamp', 'termdown', 'terminal-answer', 'termpod', 'termup', 'tui', 'up', 'uppod', 'zoo'])
+
/** A Redis message's kind: `bus <subscriber> <channel kind>`, the channel's name before its first `:` (`termup:<machine>` is
- * `termup`), never the id after it. A name that is not one of the bus's own counts as `other`. Before these were named, a
- * sixth of prod's CPU ran under `untagged` (2026-10-31): Redis deliveries, the daemons' sockets and the share sockets. */
+ * `termup`), never the id after it. Only the bus's own kinds are named, and anything else counts as `other`, so a bare id
+ * sent as a channel name never becomes a log key or a Prometheus label. Before these were named, a sixth of prod's CPU ran
+ * under `untagged` (2026-10-31): Redis deliveries, the daemons' sockets and the share sockets. */
export function busKind(subscriber: string, channel: string): string {
const name = channel.split(':', 1)[0]!
- return `bus ${subscriber} ${/^[a-z0-9-]{1,24}$/.test(name) ? name : 'other'}`
+ return `bus ${subscriber} ${BUS_CHANNEL_KINDS.has(name) ? name : 'other'}`
}
/** Every HTTP request is named by its route pattern, never its URL (no ids). */
@@ -79,10 +85,12 @@ export function selfProfileFromEnv(app: FastifyInstance, env: NodeJS.ProcessEnv
return startSelfProfile(options)
}
-export type SelfProfileOptions = { everyMs?: number; profileMs?: number; reportMs?: number; log?: (message: string, context: Record<string, unknown>) => void }
+export type SelfProfileOptions = { everyMs?: number; profileMs?: number; reportMs?: number; log?: (message: string, context: Record<string, unknown>) => void
+ /** Every kind's busy ms of the window: the counters and the last hour (lib/metrics.ts). */
+ onWindow?: (busy: ReadonlyMap<string, number>) => void }
export function startSelfProfile({ everyMs = 15 * 60_000, profileMs = 30_000, reportMs = 60_000,
- log = (message, context) => logger.info(message, context) }: SelfProfileOptions = {}): () => void {
+ log = (message, context) => logger.info(message, context), onWindow }: SelfProfileOptions = {}): () => void {
enabled = true
const hook = createHook({
init(_id, type, _trigger, resource) {
@@ -101,6 +109,7 @@ export function startSelfProfile({ everyMs = 15 * 60_000, profileMs = 30_000, re
const used = process.cpuUsage(cpu), elapsed = performance.now() - wall
const kinds = Object.fromEntries([...busy].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([k, ms]) => [k, Math.round(ms)]))
log('cpu by kind', { windowMs: Math.round(elapsed), processCpuMs: Math.round((used.user + used.system) / 1000), busyMs: kinds })
+ try { onWindow?.(busy) } catch (error) { logger.warn('cpu by kind window failed', { error: error instanceof Error ? error.message : String(error) }) }
busy = new Map(); cpu = process.cpuUsage(); wall = performance.now()
}, reportMs)
report.unref()
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 6727b75a1..b4e8b5259 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -19,6 +19,9 @@ import { handleManagerUpgrade } from './lib/managerWs.js'
import { handleAdapterUpgrade } from './lib/adapterWs.js'
import { logger } from './utils/logger.js'
import { registerSecurityHeaders } from './middlewares/securityHeaders.js'
+import { metrics, metricsAddress, startMetricsServer } from './lib/metrics.js'
+import { startLastHour } from './lib/lastHour.js'
+import { WORKER_INDEX } from './lib/instance.js'
import { startTurnCredentialRefresh } from './lib/turnCredentials.js'
import { closeBus, pub, redisCount, redisSsoProfileStore, redisSwarmStamps } from './lib/bus.js'
import { prisma } from './lib/prisma.js'
@@ -150,13 +153,16 @@ async function start(): Promise<void> {
// Every request is named by its route pattern before any hook reads the database, so its queries count for it.
registerWorkContext(app)
// Off by default: logs this process's CPU by kind of work every minute, and a 30 s profile every 15 min (#314).
- selfProfileFromEnv(app)
+ selfProfileFromEnv(app, process.env, { onWindow: busy => metrics.busyWindow(busy) })
// Always on, every minute: process CPU by thread (main, Prisma engine, libuv pool, V8 workers), GC pauses and reply JSON.
// Before any route is added, so every route's object replies are timed (lib/cpuStats.ts).
const cpuStats = startCpuStats()
registerReplyJsonTiming(app, cpuStats)
// Always on, every minute (DB roadmap Phase 1): queries by model.action, filter shape and route, and each route's p50/p95.
- const stopQueryStats = startQueryStats()
+ const stopQueryStats = startQueryStats({ onWindow: routes => metrics.dbWindow(routes) })
+ // Always on, every minute: `last hour`, the sums of the last 60 minutes the production scan reads from a log tail
+ // (lib/lastHour.ts, task #2957).
+ const stopLastHour = startLastHour(metrics.hour)
// Every minute, how often Swarm transactions ran again and commands loaded twice (superTabs/retryStats.ts, DB 2.1).
const stopRetryStats = startRetryStats()
// Every minute: re-claims, refused receipt reads and holds, what the daemons' delivery loop costs (spec 2026-11-02 poll cost).
@@ -165,7 +171,8 @@ async function start(): Promise<void> {
const stopCacheStats = startCacheStats()
// Every minute: the process's memory and what the read cache holds of it (lib/memoryStats.ts; the HPA scales on memory).
const stopMemoryStats = startMemoryStats({ cache: () => swarmReadCache()?.size ?? null })
- const stopRouteLatency = startRouteLatency(registerRouteLatency(app))
+ // The same hook feeds the Prometheus histogram and the last hour (lib/metrics.ts); WS upgrades never reach Fastify.
+ const stopRouteLatency = startRouteLatency(registerRouteLatency(app, { observe: metrics.request }))
// Every minute: who reads messages how, with the rows each page decoded and showed (superTabs/messageReadStats.ts).
const stopMessageReadStats = startMessageReadStats()
// Every minute: how long messages took to reach their readers, p50/p95 per reader kind (superTabs/messageReachStats.ts).
@@ -225,6 +232,8 @@ async function start(): Promise<void> {
const appProxyServer = startSubdomainProxy()
// Internal mesh listener (Phase 2, MESH_ENABLED) — peers forward here when this instance owns the socket.
const meshServer = startMeshProxy()
+ // Prometheus scrape on an internal port of its own (loopback unless METRICS_HOST says otherwise).
+ const metricsServer = startMetricsServer(metrics.registry, metricsAddress({ portBase: env.METRICS_PORT_BASE, host: env.METRICS_HOST }, WORKER_INDEX))
// Connect counts are kept in memory and written once a minute; shutdown writes what is left (lib/productUsageRelay.ts).
const stopRelayUsage = startRelayUsageFlush()
@@ -239,6 +248,7 @@ async function start(): Promise<void> {
await drainBeforeClosing(processDrain, exitCode === 0 ? env.DRAIN_DELAY_MS : 0)
appProxyServer.close()
meshServer?.close()
+ metricsServer.close()
// Start Fastify's close (it tells the http server to stop accepting new connections) but DON'T await
// it yet: http.Server#close only resolves once every connection has ended, and an upgraded WebSocket
// is a connection that never ends on its own — so awaiting here would hang until clients happened to
@@ -256,6 +266,7 @@ async function start(): Promise<void> {
await Promise.race([stopRelayUsage().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 3_000))])
// The last partial minute of these logs, once the drain and the usage flush have run their queries.
stopQueryStats()
+ stopLastHour()
stopRetryStats()
stopDeliveryCalls()
stopCacheStats()
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 656eb212d..086216bba 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/docs/plans/2026-11-04-backend-metrics-plan.md b/docs/plans/2026-11-04-backend-metrics-plan.md
new file mode 100644
index 000000000..d3e48e353
--- /dev/null
+++ b/docs/plans/2026-11-04-backend-metrics-plan.md
@@ -0,0 +1,111 @@
+# Backend metrics the scan can read from the log tail: implementation plan
+
+This plan is followed task by task, test first, by the Engineer of task #2957 (project instructions, Engineer role),
+on PR #1880's own branch. There is no execution handoff.
+
+**Goal:** The production scan measures an hour of backend load from what one `argocd app logs` call returns today,
+even though each pod's logs keep only its last ~3 minutes (Ken's scan, 2026-11-04 21:30): requests per route, CPU per
+request and DB bytes per request, with no tab, person or machine id anywhere.
+
+**Architecture:** PR #1880 (10-28) adds prom-client counters and a `/metrics` listener; main has since added per-minute
+log lines (`route latency`, `db by shape`, `cpu by thread`, `cpu by kind`) from the same hooks. After merging main, the
+two are one: the events that feed the Prometheus counters also feed a ring of 60 one-minute buckets, and every minute
+the process logs `last hour`, the ring's sums. The newest `last hour` line of each pod is in any log tail, so one read
+gives the hour. `/metrics` serves the same counters, cumulative, for a scraper.
+
+**Tech Stack:** Node 22, Fastify 5, Prisma 5 (MongoDB), prom-client 15, vitest.
+
+**Spec:** Task #2957's brief (Ken's prod scan, 2026-11-04) and Ken's decision of 2026-11-04 (through River): node log size stays,
+the counters are how scans measure the backend, so they cover everything the scan reads from logs today.
+
+## Global Constraints
+
+- Labels and log keys are bounded and carry no ids: a route is its Fastify pattern (`/api/super-tabs/:tabId/changes`)
+ or `unrouted`; a kind of work is the name `workKind()` gives (`http GET /x`, `web-ws <frame>`, `bus <sub> <channel>`,
+ `background`); a Prisma model and operation; a status code. Each set is capped (300 values), past that `other`.
+- Ships on, with no switch (ENGINEERING.md §1, Ken): the counters, the `last hour` line and the `/metrics` listener
+ run in every process. The port base and host are addresses, not switches.
+- One way to do a thing (ENGINEERING.md §1): one Prisma query extension, one slow-query log (main's `slow query`,
+ ≥ 200 ms, at most 20 a minute), one stack in a 500's log line (main's `trace`).
+- Measurement never blocks or slows the product (ENGINEERING.md §8): no work per request beyond a few map updates;
+ DB bytes come from `db by shape`'s existing sampled estimate, once a minute.
+
+## Review Focus
+
+- A request to an unknown URL full of ids (`/wp-admin/6a7301…`) is one `unrouted` series, in `/metrics` and in the line.
+- A pod that restarted 10 minutes ago logs an hour line covering 10 minutes and says so (`windowMs`, `minutes`).
+- A 301st kind of work (a new bus channel, a new frame) lands in `other`, in both views, never a new series.
+- A minute with no requests divides by nothing: per-request numbers are 0, not `NaN` or `Infinity`.
+- A metrics port already taken (two local backends) is logged and the API keeps serving.
+
+---
+
+### Task 1: One Prisma query hook times every query into the histogram
+
+**Files:**
+- Modify: `backend/src/lib/queryStats.ts` (`withQueryStats`), `backend/src/lib/metrics.ts` (remove `timeQuery`,
+ `withQueryTiming`, `SLOW_QUERY_MS`, `QueryCall`), `backend/src/lib/prisma.ts`
+- Test: `backend/src/lib/queryStats.test.ts`, `backend/src/lib/metrics.test.ts`, `backend/integration/prismaQueryTiming.test.ts`
+
+**Interfaces:**
+- Produces: `withQueryStats(client, stats?, warn?, observe?: (model: string, operation: string, seconds: number) => void)`;
+ `model` is `raw` for a call without one. `metrics.observeQuery(model, operation, seconds)`.
+
+- [ ] **Step 1: Failing test** in `queryStats.test.ts`: `withQueryStats` on a fake client whose `$extends` keeps the
+ hook; a `User.findFirst` that succeeds, one that throws, and a `$runCommandRaw` each call `observe` once with
+ (`User`,`findFirst`) / (`raw`,`$runCommandRaw`) and the elapsed seconds; the thrown error passes unchanged.
+- [ ] **Step 2:** Run `npx vitest run src/lib/queryStats.test.ts`: FAIL (observe never called).
+- [ ] **Step 3:** Add the `observe` parameter; a throwing `observe` is caught like a throwing `stats`. `prisma.ts` wraps
+ once: `withQueryStats(client, undefined, undefined, metrics.observeQuery)`. Delete `withQueryTiming` and `timeQuery`
+ with their tests; the integration test uses the shared client and `withQueryStats`.
+- [ ] **Step 4:** Run the unit tests above and `npm run typecheck`: PASS.
+- [ ] **Step 5:** Commit.
+
+### Task 2: The `/metrics` listener is always on
+
+**Files:** Modify `backend/src/lib/metrics.ts` (`metricsAddress`), `backend/src/config/env.ts`; test `metrics.test.ts`.
+
+**Interfaces:** `metricsAddress({ portBase = 9464, host = '127.0.0.1' }, workerIndex): { port, host }` (never undefined).
+
+- [ ] **Step 1: Failing test:** `metricsAddress({}, 0)` is `{ port: 9464, host: '127.0.0.1' }`; worker 3 gets 9467.
+- [ ] **Step 2:** Run it: FAIL (`undefined`).
+- [ ] **Step 3:** Default the base to 9464 in `env.ts` (`METRICS_PORT_BASE` default `'9464'`, no "empty means off").
+- [ ] **Step 4:** PASS. **Step 5:** Commit.
+
+### Task 3: The last hour, from the same events as the counters
+
+**Files:**
+- Create: `backend/src/lib/lastHour.ts`, test `backend/src/lib/lastHour.test.ts`
+- Modify: `backend/src/lib/metrics.ts` (counters, `request`, `dbWindow`, `busyWindow`, unmatched → `unrouted`),
+ `backend/src/lib/queryStats.ts` (`onWindow` option), `backend/src/lib/selfProfile.ts` (`onWindow` option),
+ `backend/src/server.ts` (wiring), tests `metrics.test.ts`, `queryStats.test.ts`, `selfProfile.test.ts`
+
+**Interfaces:**
+- `createLastHour({ pod?, minutes = 60, top = 40, maxKeys = 300, cpuMs = () => process CPU ms, log? }): LastHour`
+ with `request(route: string, ms: number, failed: boolean)`, `db(work: ReadonlyMap<string, { n: number; ms: number; bytes: number }>)`,
+ `busy(work: ReadonlyMap<string, number>)`, `roll()` (closes the minute and logs `last hour`).
+ `startLastHour(hour, everyMs = 60_000): () => void`.
+- `createMetrics(hour = createLastHour())` gains Counters `db_queries_total{work}`, `db_result_bytes_total{work}`,
+ `work_busy_seconds_total{work}` and methods `request(method, route, status, seconds)`, `dbWindow(routes)`,
+ `busyWindow(kinds)`, each updating the Prometheus series and the hour.
+- `QueryStatsOptions.onWindow?(routes)` gets every route's `{ n, ms, bytes }` of the minute (before the top-40 cut);
+ `SelfProfileOptions.onWindow?(busy)` gets every kind's busy ms.
+- The line: `last hour {pod, windowMs, minutes, requests, errors, cpuMs, cpuMsPerRequest, dbQueries, dbBytes,
+ dbBytesPerRequest, routes: {"GET /x": {n, perMinute, errors, ms, dbQueries, dbBytes, dbBytesPerRequest, busyMs,
+ busyMsPerRequest}}, work: {"web-ws x": {dbQueries, dbBytes, busyMs}}}`; `routes` joins `http GET /x` work to its route.
+
+- [ ] **Step 1: Failing tests** in `lastHour.test.ts`: sums across minutes and drops the 61st-oldest; per-request
+ numbers; `minutes`/`windowMs` after 10 minutes; zero requests gives 0; the 301st key is `other`; a route joins its
+ `http` work's DB bytes and busy ms; the line lists the top routes by time, by DB bytes and by busy ms.
+- [ ] **Step 2:** Run: FAIL (module missing).
+- [ ] **Step 3:** Implement `lastHour.ts`.
+- [ ] **Step 4: Failing tests** in `metrics.test.ts`: an unknown URL is `unrouted`; `dbWindow` of a bus channel kind adds
+ `db_result_bytes_total{work="bus web termup"}` with no id in the scrape; the 301st work is `other`; in
+ `queryStats.test.ts`, `onWindow` gets every route, not only the top 40; in `selfProfile.test.ts`, `onWindow` gets the
+ minute's busy ms.
+- [ ] **Step 5:** Run: FAIL. **Step 6:** Implement and wire in `server.ts`. **Step 7:** PASS, typecheck. **Step 8:** Commit.
+
+### Task 4: The pull request says how the scan reads it
+
+- [ ] PR body: first line `Requested by [email protected] through Harness.`; the exact `argocd app logs` command and
+ how to sum pods; `/metrics` for a scraper; the Design section; red/green evidence in a comment; backend `npm test`.