: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-proxy): handle client disconnects during ingest (#67555)
Charles Vien20fc3e98b902
diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.tsindex 1dbac1e73e47..71c58149639d 100644--- a/services/agent-proxy/src/hono/app.ts+++ b/services/agent-proxy/src/hono/app.ts@@ -20,7 +20,7 @@ import type { Redis } from 'ioredis'import type { Config } from '../lib/config.js'import { validateStreamReadToken } from '../lib/jwt.js'-import { logger } from '../lib/logging.js'+import { logger, type RequestLogger } from '../lib/logging.js'import { getStreamKey } from '../lib/redis-stream.js'import { StreamCapacity } from '../lib/stream-capacity.js'import type { StreamReadTokenPayload } from '../lib/types.js'@@ -29,14 +29,14 @@ import { observeStreamConnectionRejected } from './metrics.js'import { corsHeaders, corsPreflightHandler, httpMetrics, requestLog, securityHeaders } from './middleware.js'import { registerPublicRoutes } from './public-routes.js'import { streamTaskRunEvents } from './sse-handler.js'-import type { Lifecycle } from './types.js'+import type { HonoVariables, Lifecycle } from './types.js'// ---------------------------------------------------------------------------// Exported types// ---------------------------------------------------------------------------export interface App {- app: Hono+ app: Hono<{ Variables: HonoVariables }>lifecycle: Lifecycle}@@ -45,10 +45,23 @@ export interface App {// ---------------------------------------------------------------------------export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[]): App {- const app = new Hono()+ const app = new Hono<{ Variables: HonoVariables }>()const lifecycle: Lifecycle = { shuttingDown: false }const streamCapacity = new StreamCapacity(config.maxConcurrentStreams, config.maxStreamsPerRun)+ app.onError((err, c) => {+ const requestLogger: RequestLogger | undefined = c.get('requestLogger')+ requestLogger?.extend({ error: err.message })+ logger.error('http.unhandled_error', {+ requestId: requestLogger?.id,+ method: c.req.method,+ path: new URL(c.req.url).pathname,+ error: err.message,+ stack: err.stack,+ })+ return c.json({ error: 'Internal server error' }, 500)+ })+app.use('*', securityHeaders)app.use('*', corsHeaders(config))app.use('*', httpMetrics)diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex 4bea8dfb1a12..0838c40e0840 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -9,6 +9,7 @@// 401 missing / invalid JWT// 403 JWT claims don't match URL params// 405 wrong HTTP method+// 408 client disconnected mid-body: {error, last_accepted_seq}// 409 SequenceGap / AlreadyCompleted / CompletionSequenceMismatch: {error, last_accepted_seq}// 413 payload too large: {error, last_accepted_seq}@@ -28,6 +29,7 @@ import { logger } from '../lib/logging.js'import { TaskRunRedisStream, getStreamKey } from '../lib/redis-stream.js'import { heartbeatWorkflowIfNeeded } from '../lib/side-effects.js'import {+ ClientDisconnected,EventIngestBadRequest,EventIngestPayloadTooLarge,TaskRunStreamSequenceGap,@@ -116,6 +118,17 @@ export async function handleIngest(try {result = await ingestEventLines(redisStream, claims, token, config, c.req.raw, bodyTiming)} catch (err: unknown) {+ if (err instanceof ClientDisconnected) {+ logger.info('ingest:client_disconnect', {+ run: claims.runId,+ accepted: err.accepted,+ duplicate: err.duplicate,+ lastSeq: err.lastAcceptedSeq,+ chunks: bodyTiming.chunks,+ bodyBytes: bodyTiming.bytes,+ })+ return c.json({ error: 'Client disconnected', last_accepted_seq: err.lastAcceptedSeq }, 408)+ }if (err instanceof EventIngestBadRequest) {return c.json({ error: err.message }, 400)}@@ -231,6 +244,11 @@ async function ingestEventLines()}} catch (err: unknown) {+ if (err instanceof ClientDisconnected) {+ err.accepted = result.accepted+ err.duplicate = result.duplicate+ err.lastAcceptedSeq = result.last_accepted_seq+ }// Re-throw EventIngestPayloadTooLarge with the current last_accepted_seq// if the error didn't carry one (mirrors Python's except re-raise).if (err instanceof EventIngestPayloadTooLarge && result.last_accepted_seq > 0 && err.lastAcceptedSeq === 0) {@@ -307,7 +325,9 @@ async function* iterRequestLines(request: Request, run: string, timing: IngestBotry {while (true) {- const { done, value } = await reader.read()+ const { done, value } = await reader.read().catch((err: unknown) => {+ throw isClientAbortError(err) ? new ClientDisconnected() : err+ })if (value !== undefined && value.length > 0) {const chunkAt = Date.now()@@ -383,6 +403,17 @@ async function* iterRequestLines(request: Request, run: string, timing: IngestBo}}+function isClientAbortError(err: unknown): boolean {+ if (!(err instanceof Error)) {+ return false+ }+ if (err.name === 'AbortError') {+ return true+ }+ const code = (err as NodeJS.ErrnoException).code+ return code === 'ECONNRESET' || code === 'ERR_STREAM_PREMATURE_CLOSE' || err.message === 'aborted'+}+// Decode bytes as UTF-8, mapping decode errors to EventIngestBadRequest.function decodeUtf8(bytes: Uint8Array): string {try {diff --git a/services/agent-proxy/src/hono/public-routes.ts b/services/agent-proxy/src/hono/public-routes.tsindex 1c22ebd77190..10bcf21b28b1 100644--- a/services/agent-proxy/src/hono/public-routes.ts+++ b/services/agent-proxy/src/hono/public-routes.ts@@ -9,7 +9,7 @@// provisioned. Unset keeps the route open for in-cluster scrapes that have// no token configured.-import type { Hono } from 'hono'+import type { Env, Hono } from 'hono'import { createHash, timingSafeEqual } from 'node:crypto'import { register, shuttingDown as shuttingDownGauge } from './metrics.js'@@ -26,7 +26,7 @@ function tokensMatch(provided: string, expected: string): boolean {return timingSafeEqual(providedDigest, expectedDigest)}-export function registerPublicRoutes(app: Hono, lifecycle: Lifecycle, metricsToken: string): void {+export function registerPublicRoutes<E extends Env>(app: Hono<E>, lifecycle: Lifecycle, metricsToken: string): void {app.get('/_health', (c) => c.json({ status: 'ok' }))app.get('/_readyz', (c) => {diff --git a/services/agent-proxy/src/lib/logging.ts b/services/agent-proxy/src/lib/logging.tsindex 60544ce9992b..c0da4f191fcb 100644--- a/services/agent-proxy/src/lib/logging.ts+++ b/services/agent-proxy/src/lib/logging.ts@@ -110,6 +110,10 @@ export class RequestLogger {this.data['requestId'] = this.requestId}+ get id(): string {+ return this.requestId+ }+// Merge additional fields into the accumulated record. Later calls win on// key conflicts — route handlers overwrite middleware-set placeholders.extend(data: Record<string, unknown>): void {diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex 93c18513b809..59707432b35c 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -62,6 +62,17 @@ export class EventIngestPayloadTooLarge extends Error {}}+export class ClientDisconnected extends Error {+ constructor(+ public accepted: number = 0,+ public duplicate: number = 0,+ public lastAcceptedSeq: number = 0+ ) {+ super('Client disconnected during event ingest')+ this.name = 'ClientDisconnected'+ }+}+// ---------------------------------------------------------------------------// Redis stream types// ---------------------------------------------------------------------------diff --git a/services/agent-proxy/tests/hono/app.test.ts b/services/agent-proxy/tests/hono/app.test.tsnew file mode 100644index 000000000000..da213b83795a--- /dev/null+++ b/services/agent-proxy/tests/hono/app.test.ts@@ -0,0 +1,59 @@+import type { Redis } from 'ioredis'+import { describe, it, expect, vi, beforeEach } from 'vitest'++import type { Config } from '@/lib/config.js'+import { logger } from '@/lib/logging.js'++vi.mock('@/lib/jwt.js', () => ({+ validateSandboxEventIngestToken: vi.fn(),+ validateStreamReadToken: vi.fn(),+ loadPublicKeys: vi.fn(),+}))++import { createApp } from '@/hono/app.js'+import { validateSandboxEventIngestToken } from '@/lib/jwt.js'++const mockValidate = vi.mocked(validateSandboxEventIngestToken)++function makeConfig(): Config {+ return {+ redisUrl: 'redis://localhost:6379',+ sandboxJwtPublicKeysPem: [],+ corsOrigins: new Set(),+ djangoCallbackBaseUrl: '',+ agentProxyCallbackSecret: '',+ maxConcurrentStreams: 1000,+ maxStreamsPerRun: 25,+ metricsToken: '',+ port: 8003,+ host: '0.0.0.0',+ shutdownGraceMs: 300_000,+ shutdownPrestopDelayMs: 0,+ }+}++describe('app onError', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockValidate.mockResolvedValue({ runId: 'run-123', taskId: 'task-abc', teamId: 42 })+ })++ it('logs unexpected route errors with request context and returns JSON 500', async () => {+ const errorSpy = vi.spyOn(logger, 'error')+ const failingRedis = { get: vi.fn().mockRejectedValue(new Error('redis exploded')) } as unknown as Redis+ const { app } = createApp(failingRedis, makeConfig(), [])++ const res = await app.request('/v1/runs/run-123/ingest', {+ method: 'POST',+ headers: { Authorization: 'Bearer tok' },+ body: JSON.stringify({ seq: 1, event: {} }) + '\n',+ })++ expect(res.status).toBe(500)+ expect(await res.json()).toEqual({ error: 'Internal server error' })++ const logged = errorSpy.mock.calls.find((c) => c[0] === 'http.unhandled_error')?.[1] as Record<string, unknown>+ expect(logged).toMatchObject({ error: 'redis exploded', path: '/v1/runs/run-123/ingest', method: 'POST' })+ expect(logged.requestId).toBeTruthy()+ })+})diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 68272901b0c6..34d1ab3abb82 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -883,6 +883,50 @@ describe('ingest-handler', () => {expect(res.status).toBe(400)})+ it.each([+ {+ variant: 'ECONNRESET code',+ makeError: (): Error => Object.assign(new Error('read failed'), { code: 'ECONNRESET' }),+ },+ { variant: 'aborted message', makeError: (): Error => new Error('aborted') },+ {+ variant: 'AbortError name',+ makeError: (): Error => Object.assign(new Error('This operation was aborted'), { name: 'AbortError' }),+ },+ {+ variant: 'premature close code',+ makeError: (): Error => Object.assign(new Error('Premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }),+ },+ ])('treats a mid-body $variant as a client disconnect, not a server error', async ({ makeError }) => {+ const infoSpy = vi.spyOn(logger, 'info')+ const config = makeConfig()+ const enc = new TextEncoder()+ const line = enc.encode(JSON.stringify({ seq: 1, event: { type: 'before-drop' } }) + '\n')+ let sentFirstChunk = false+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (!sentFirstChunk) {+ sentFirstChunk = true+ controller.enqueue(line)+ return+ }+ controller.error(makeError())+ },+ })++ const res = await handleIngest(makeContext({ body }), fakeRedis as unknown as Redis, config, [] as CryptoKey[])++ expect(res.status).toBe(408)+ const responseBody = (await decodeJson(res)) as { last_accepted_seq: number }+ expect(responseBody.last_accepted_seq).toBe(1)++ const entries = await fakeRedis.xrange(getStreamKey(RUN_ID))+ expect(entries).toHaveLength(1)++ const log = infoSpy.mock.calls.find((c) => c[0] === 'ingest:client_disconnect')?.[1] as Record<string, unknown>+ expect(log).toMatchObject({ run: RUN_ID, accepted: 1, lastSeq: 1 })+ })+// -----------------------------------------------------------------------// Empty body// -----------------------------------------------------------------------diff --git a/services/agent-proxy/tests/setup.ts b/services/agent-proxy/tests/setup.tsindex a907f838c947..278f7e5f1026 100644--- a/services/agent-proxy/tests/setup.ts+++ b/services/agent-proxy/tests/setup.ts@@ -12,20 +12,19 @@ const mockInc = vi.fn()const mockDec = vi.fn()const mockSet = vi.fn()const mockObserve = vi.fn()-const mockLabels = vi.fn()// Counters-const mockCounter = { labels: mockLabels.mockReturnValue({ inc: mockInc }), inc: mockInc }+const mockCounter = { labels: vi.fn().mockReturnValue({ inc: mockInc }), inc: mockInc }// Gaugesconst mockGauge = {- labels: mockLabels.mockReturnValue({ inc: mockInc, dec: mockDec, set: mockSet }),+ labels: vi.fn().mockReturnValue({ inc: mockInc, dec: mockDec, set: mockSet }),inc: mockInc,dec: mockDec,set: mockSet,}// Histogramsconst mockHistogram = {- labels: mockLabels.mockReturnValue({ observe: mockObserve }),+ labels: vi.fn().mockReturnValue({ observe: mockObserve }),observe: mockObserve,startTimer: vi.fn().mockReturnValue(vi.fn()),}