: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
chore(agent-proxy): log ingest request body chunk timing (#67241)
Charles Vien63dad5f4e73e
diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex 7dddb18bdacc..4bea8dfb1a12 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -41,6 +41,20 @@ import {} from '../lib/types.js'import { 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)+// from a body buffered upstream and delivered in one burst at request close.+// The sandbox holds one long-lived chunked POST open for the whole turn; if+// chunks only land when that request closes, the stall is upstream of this+// process. Remove once the buffering hop is pinned down.+interface IngestBodyTiming {+ startedAt: number+ firstChunkAt: number | null+ lastChunkAt: number | null+ chunks: number+ bytes: number+}+// ---------------------------------------------------------------------------// Route handler (exported; wired in app.ts)// ---------------------------------------------------------------------------@@ -90,9 +104,17 @@ export async function handleIngest(const streamKey = getStreamKey(claims.runId)const redisStream = new TaskRunRedisStream(streamKey, redis)+ const bodyTiming: IngestBodyTiming = {+ startedAt: Date.now(),+ firstChunkAt: null,+ lastChunkAt: null,+ chunks: 0,+ bytes: 0,+ }+let result: EventIngestResulttry {- result = await ingestEventLines(redisStream, claims, token, config, c.req.raw)+ result = await ingestEventLines(redisStream, claims, token, config, c.req.raw, bodyTiming)} catch (err: unknown) {if (err instanceof EventIngestBadRequest) {return c.json({ error: err.message }, 400)@@ -119,6 +141,17 @@ export async function handleIngest(accepted: result.accepted,duplicate: result.duplicate,lastSeq: result.last_accepted_seq,+ // Body-arrival timing. Live upload: firstChunkMs small, chunkSpanMs+ // large. Buffered upstream: firstChunkMs ~= lastChunkMs, chunkSpanMs ~0+ // (every chunk lands together when the request closes).+ chunks: bodyTiming.chunks,+ bodyBytes: bodyTiming.bytes,+ firstChunkMs: bodyTiming.firstChunkAt === null ? null : bodyTiming.firstChunkAt - bodyTiming.startedAt,+ lastChunkMs: bodyTiming.lastChunkAt === null ? null : bodyTiming.lastChunkAt - bodyTiming.startedAt,+ chunkSpanMs:+ bodyTiming.firstChunkAt === null || bodyTiming.lastChunkAt === null+ ? null+ : bodyTiming.lastChunkAt - bodyTiming.firstChunkAt,})return c.json(@@ -140,7 +173,8 @@ async function ingestEventLines(claims: SandboxEventIngestTokenPayload,originalToken: string,config: Config,- rawRequest: Request+ rawRequest: Request,+ bodyTiming: IngestBodyTiming): Promise<EventIngestResult> {const result: EventIngestResult = {accepted: 0,@@ -152,7 +186,7 @@ async function ingestEventLines(let completionLineFinalSeq: number | null = nulltry {- for await (const line of iterRequestLines(rawRequest)) {+ for await (const line of iterRequestLines(rawRequest, claims.runId, bodyTiming)) {const parsed = parseIngestLine(line)if (parsed.kind === 'complete') {@@ -260,7 +294,7 @@ function parseIngestLine(line: string): IngestLine {// Streaming NDJSON body reader (mirrors _iter_request_lines)// ----------------------------------------------------------------------------async function* iterRequestLines(request: Request): AsyncGenerator<string> {+async function* iterRequestLines(request: Request, run: string, timing: IngestBodyTiming): AsyncGenerator<string> {const body = request.bodyif (body === null) {return@@ -276,6 +310,20 @@ async function* iterRequestLines(request: Request): AsyncGenerator<string> {const { done, value } = await reader.read()if (value !== undefined && value.length > 0) {+ const chunkAt = Date.now()+ if (timing.firstChunkAt === null) {+ timing.firstChunkAt = chunkAt+ }+ timing.lastChunkAt = chunkAt+ timing.chunks += 1+ timing.bytes += value.length+ logger.debug('ingest:body_chunk', {+ run,+ chunk: timing.chunks,+ bytes: value.length,+ sinceStartMs: chunkAt - timing.startedAt,+ })+requestSize += value.lengthif (requestSize > MAX_REQUEST_BYTES) {throw new EventIngestPayloadTooLarge('Event ingest request is too large')diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 43cc91a8b8af..4e658532e1a3 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -25,6 +25,7 @@ import {MAX_EVENTS_PER_REQUEST,HEARTBEAT_THROTTLE_SECONDS,} from '@/lib/constants.js'+import { logger } from '@/lib/logging.js'import { TaskRunRedisStream, getStreamKey } from '@/lib/redis-stream.js'import { heartbeatWorkflowIfNeeded } from '@/lib/side-effects.js'import type { SandboxEventIngestTokenPayload } from '@/lib/types.js'@@ -1145,4 +1146,53 @@ describe('ingest-handler', () => {fetchSpy.mockRestore()})})++ // -----------------------------------------------------------------------+ // Body-arrival timing diagnostic+ //+ // The ingest log carries chunks/bodyBytes/firstChunkMs/lastChunkMs/chunkSpanMs+ // so operators can tell a live upload (chunks spread over the request) from a+ // body buffered upstream and delivered in one burst at request close. If those+ // numbers are wrong the diagnostic misleads that investigation, so lock in that+ // they reflect the actual body read.+ // -----------------------------------------------------------------------++ describe('body-arrival timing', () => {+ it('reports chunk count, byte total, and a consistent span on the ingest log', async () => {+ const infoSpy = vi.spyOn(logger, 'info')+ const enc = new TextEncoder()+ const chunk1 = enc.encode(JSON.stringify({ seq: 1, event: { type: 'a' } }) + '\n')+ const chunk2 = enc.encode(JSON.stringify({ seq: 2, event: { type: 'b' } }) + '\n')++ const ctx = makeContext({ body: makeChunkedBody([chunk1, chunk2]) })+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, makeConfig(), [] as CryptoKey[])+ expect(res.status).toBe(200)++ const log = infoSpy.mock.calls.find((c) => c[0] === 'ingest')?.[1] as Record<string, number>+ expect(log).toBeTruthy()+ expect(log.chunks).toBe(2)+ expect(log.bodyBytes).toBe(chunk1.length + chunk2.length)+ const firstChunkMs = log.firstChunkMs as number+ const lastChunkMs = log.lastChunkMs as number+ expect(typeof firstChunkMs).toBe('number')+ expect(lastChunkMs).toBeGreaterThanOrEqual(firstChunkMs)+ expect(log.chunkSpanMs as number).toBe(lastChunkMs - firstChunkMs)+ })++ it('reports zero chunks and null timing for an empty body', async () => {+ const infoSpy = vi.spyOn(logger, 'info')++ const ctx = makeContext({ body: makeStringBody('') })+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, makeConfig(), [] as CryptoKey[])+ expect(res.status).toBe(200)++ const log = infoSpy.mock.calls.find((c) => c[0] === 'ingest')?.[1] as Record<string, unknown>+ expect(log).toBeTruthy()+ expect(log.chunks).toBe(0)+ expect(log.bodyBytes).toBe(0)+ expect(log.firstChunkMs).toBeNull()+ expect(log.lastChunkMs).toBeNull()+ expect(log.chunkSpanMs).toBeNull()+ })+ })})