: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): treat teardown ingest disconnects as success (#68487)
Charles Vien3947cd36d72f
diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex 65385ef46fc8..eafea3e316f8 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -4,12 +4,12 @@// Node services read/write the same Redis stream during the cutover window.//// HTTP status codes:-// 200 success: {accepted, duplicate, last_accepted_seq}+// 200 success, or post-turn client disconnect (sandbox teardown): {accepted, duplicate, last_accepted_seq}// 400 bad NDJSON: invalid JSON, non-object, wrong field types, ordering// 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}+// 408 client disconnected mid-turn: {error, last_accepted_seq}// 409 SequenceGap / AlreadyCompleted / CompletionSequenceMismatch: {error, last_accepted_seq}// 413 payload too large: {error, last_accepted_seq}@@ -35,13 +35,14 @@ import {TaskRunStreamSequenceGap,TaskRunStreamAlreadyCompleted,TaskRunStreamCompletionSequenceMismatch,+ type DisconnectClassification,type IngestEventLine,type IngestCompleteLine,type IngestLine,type EventIngestResult,type SandboxEventIngestTokenPayload,} from '../lib/types.js'-import { observeStreamIngestEvents } from './metrics.js'+import { observeIngestClientDisconnect, observeStreamIngestEvents } from './metrics.js'// Diagnostic (temporary): records when request-body chunks arrive at the Node// process, to tell a live upload (chunks spread across the request lifetime)@@ -119,15 +120,25 @@ export async function handleIngest(result = await ingestEventLines(redisStream, claims, token, config, c.req.raw, bodyTiming)} catch (err: unknown) {if (err instanceof ClientDisconnected) {+ const classification = await classifyDisconnect(redisStream)+ observeIngestClientDisconnect(classification)+ observeStreamIngestEvents({ accepted: err.accepted, duplicate: err.duplicate })logger.info('ingest:client_disconnect', {run: claims.runId,+ classification,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 (classification === 'mid_turn') {+ return c.json({ error: 'Client disconnected', last_accepted_seq: err.lastAcceptedSeq }, 408)+ }+ return c.json(+ { accepted: err.accepted, duplicate: err.duplicate, last_accepted_seq: err.lastAcceptedSeq },+ 200+ )}if (err instanceof EventIngestBadRequest) {return c.json({ error: err.message }, 400)@@ -177,6 +188,18 @@ export async function handleIngest()}+// Post-turn disconnects are expected sandbox teardown; fail toward 'mid_turn' so real cuts stay visible.+async function classifyDisconnect(redisStream: TaskRunRedisStream): Promise<DisconnectClassification> {+ try {+ if (await redisStream.isComplete()) {+ return 'run_over'+ }+ return (await redisStream.getAgentActive()) ? 'mid_turn' : 'idle'+ } catch {+ return 'mid_turn'+ }+}+// ---------------------------------------------------------------------------// NDJSON body parsing + Redis write loop// ---------------------------------------------------------------------------diff --git a/services/agent-proxy/src/hono/metrics.ts b/services/agent-proxy/src/hono/metrics.tsindex fc14c5bae94e..4127afa5d8bc 100644--- a/services/agent-proxy/src/hono/metrics.ts+++ b/services/agent-proxy/src/hono/metrics.ts@@ -10,7 +10,7 @@import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from 'prom-client'-import type { StreamConnectionOutcome } from '../lib/types.js'+import type { DisconnectClassification, StreamConnectionOutcome } from '../lib/types.js'export const register = new Registry()@@ -83,6 +83,14 @@ export const streamIngestEventsTotal = new Counter({registers: [register],})+// 'run_over'/'idle' are expected sandbox teardown; 'mid_turn' is a genuine cut worth alerting on.+export const ingestClientDisconnectsTotal = new Counter({+ name: 'agent_proxy_ingest_client_disconnects_total',+ help: 'Ingest requests whose client disconnected mid-body, by stream state at disconnect',+ labelNames: ['classification'],+ registers: [register],+})+// ---------------------------------------------------------------------------// HTTP infrastructure metrics// ---------------------------------------------------------------------------@@ -112,11 +120,12 @@ export const httpRequestsTotal = new Counter({registers: [register],})+// Ingest requests are long-lived chunked POSTs (30-300s); without buckets up there percentiles pin at 10s.export const httpRequestDurationSeconds = new Histogram({name: 'agent_proxy_http_request_duration_seconds',help: 'HTTP request duration in seconds',labelNames: ['method', 'route', 'status'],- buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600],registers: [register],})@@ -179,3 +188,7 @@ export function observeStreamIngestEvents(opts: { accepted: number; duplicate: nstreamIngestEventsTotal.labels({ result: 'duplicate' }).inc(opts.duplicate)}}++export function observeIngestClientDisconnect(classification: DisconnectClassification): void {+ ingestClientDisconnectsTotal.labels({ classification }).inc()+}diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.tsindex 8a74da5eac76..a26e07296b03 100644--- a/services/agent-proxy/src/lib/redis-stream.ts+++ b/services/agent-proxy/src/lib/redis-stream.ts@@ -364,6 +364,11 @@ export class TaskRunRedisStream {return raw === '1'}+ // EXISTS completed-key -> bool+ async isComplete(): Promise<boolean> {+ return (await this.redis.exists(getCompletedKey(this.streamKey))) > 0+ }+// SET heartbeat-key '1' EX throttleSeconds NX. True if claimed.async claimAgentActiveHeartbeat(throttleSeconds: number): Promise<boolean> {const result = await this.redis.set(getHeartbeatKey(this.streamKey), '1', 'EX', throttleSeconds, 'NX')diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex 95252aef9cb6..d12df8917281 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -108,6 +108,8 @@ export interface SandboxEventIngestTokenPayload {export type StreamConnectionOutcome = 'completed' | 'stream_error' | 'unavailable' | 'client_disconnect'+export type DisconnectClassification = 'run_over' | 'idle' | 'mid_turn'+// ---------------------------------------------------------------------------// Ingest HTTP response shape (200 OK body)// ---------------------------------------------------------------------------diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex c252b39b2f94..db18b04b5c22 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -26,7 +26,7 @@ import {HEARTBEAT_THROTTLE_SECONDS,} from '@/lib/constants.js'import { logger } from '@/lib/logging.js'-import { TaskRunRedisStream, getStreamKey } from '@/lib/redis-stream.js'+import { TaskRunRedisStream, getCompletedKey, getStreamKey } from '@/lib/redis-stream.js'import { heartbeatWorkflowIfNeeded } from '@/lib/side-effects.js'import type { SandboxEventIngestTokenPayload } from '@/lib/types.js'@@ -917,18 +917,84 @@ describe('ingest-handler', () => {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(res.status).toBe(200)+ const responseBody = (await decodeJson(res)) as { accepted: number; last_accepted_seq: number }+ expect(responseBody.accepted).toBe(1)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 })+ expect(log).toMatchObject({ run: RUN_ID, accepted: 1, lastSeq: 1, classification: 'idle' })expect(errorSpy).not.toHaveBeenCalledWith('http.unhandled_error', expect.anything())})+ it.each([+ {+ state: 'agent actively streaming',+ classification: 'mid_turn',+ setup: async (): Promise<void> => {+ await redisStream.setAgentActive(true)+ },+ sendEventBeforeDrop: true,+ expectedStatus: 408,+ },+ {+ state: 'agent idle after turn-complete',+ classification: 'idle',+ setup: async (): Promise<void> => {+ await redisStream.setAgentActive(false)+ },+ sendEventBeforeDrop: true,+ expectedStatus: 200,+ },+ {+ state: 'stream already completed',+ classification: 'run_over',+ setup: async (): Promise<void> => {+ await fakeRedis.set(getCompletedKey(getStreamKey(RUN_ID)), '1')+ },+ sendEventBeforeDrop: false,+ expectedStatus: 200,+ },+ ])(+ 'classifies a disconnect with $state as $classification -> $expectedStatus',+ async ({ classification, setup, sendEventBeforeDrop, expectedStatus }) => {+ 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')+ await setup()++ let sentFirstChunk = false+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (sendEventBeforeDrop && !sentFirstChunk) {+ sentFirstChunk = true+ controller.enqueue(line)+ return+ }+ controller.error(Object.assign(new Error('read failed'), { code: 'ECONNRESET' }))+ },+ })++ const res = await handleIngest(+ makeContext({ body }),+ fakeRedis as unknown as Redis,+ config,+ [] as CryptoKey[]+ )++ expect(res.status).toBe(expectedStatus)+ const log = infoSpy.mock.calls.find((c) => c[0] === 'ingest:client_disconnect')?.[1] as Record<+ string,+ unknown+ >+ expect(log).toMatchObject({ classification })+ }+ )+// -----------------------------------------------------------------------// Empty body// -----------------------------------------------------------------------diff --git a/services/agent-proxy/tests/setup.ts b/services/agent-proxy/tests/setup.tsindex 278f7e5f1026..15ae78693fdf 100644--- a/services/agent-proxy/tests/setup.ts+++ b/services/agent-proxy/tests/setup.ts@@ -42,6 +42,7 @@ vi.mock('@/hono/metrics.js', () => ({taskRunStreamResumeGapTotal: mockCounter,taskRunStreamConnectionsRejectedTotal: mockCounter,streamIngestEventsTotal: mockCounter,+ ingestClientDisconnectsTotal: mockCounter,httpRequestsTotal: mockCounter,httpRequestDurationSeconds: mockHistogram,inflightRequests: mockGauge,@@ -53,4 +54,5 @@ vi.mock('@/hono/metrics.js', () => ({observeStreamResumeGap: vi.fn(),observeStreamConnectionRejected: vi.fn(),observeStreamIngestEvents: vi.fn(),+ observeIngestClientDisconnect: vi.fn(),}))