Skip to content

: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.

fix(agent-proxy): log the network cause of failed side effects and retry awaiting_input once (#95238)

Alessandro Pogliaghidbcd28aedbec
diff --git a/services/agent-proxy/src/lib/side-effects.ts b/services/agent-proxy/src/lib/side-effects.ts
index 75eac22f86ea..62797aff60c0 100644
--- a/services/agent-proxy/src/lib/side-effects.ts
+++ b/services/agent-proxy/src/lib/side-effects.ts
@@ -109,6 +109,39 @@ export function isAgentGenerationEvent(event: Record<string, unknown>): boolean
)
}
+const CALLBACK_TIMEOUT_MS = 10_000
+const RETRY_DELAY_MS = 1000
+const RETRYABLE_KINDS: ReadonlySet<SideEffectKind> = new Set(['awaiting_input'])
+
+function fetchErrorCode(err: unknown): string | undefined {
+ if (!(err instanceof Error)) {
+ return undefined
+ }
+ const cause = (err as Error & { cause?: unknown }).cause
+ if (typeof cause === 'object' && cause !== null && 'code' in cause) {
+ return String((cause as { code: unknown }).code)
+ }
+ return err.name
+}
+
+async function postCallback(url: string, init: RequestInit, runId: string, kind: SideEffectKind): Promise<Response> {
+ const attempt = (): Promise<Response> => fetch(url, { ...init, signal: AbortSignal.timeout(CALLBACK_TIMEOUT_MS) })
+ try {
+ const response = await attempt()
+ if (!RETRYABLE_KINDS.has(kind) || response.status < 500) {
+ return response
+ }
+ logger.warn('side_effect:retry', { run: runId, kind, status: response.status })
+ } catch (err: unknown) {
+ if (!RETRYABLE_KINDS.has(kind)) {
+ throw err
+ }
+ logger.warn('side_effect:retry', { run: runId, kind, code: fetchErrorCode(err) })
+ }
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))
+ return attempt()
+}
+
// fireCallback issues a best-effort POST to the Django agent-proxy callback.
// The call is fire-and-forget: the promise is not returned to the caller.
// Any failure is logged but never thrown into the ingest path.
@@ -148,18 +181,13 @@ function fireCallback(
logger.debug('side_effect:fire', { run: runId, kind, agentActive })
// Detached promise — errors are swallowed and logged.
- fetch(url, {
- method: 'POST',
- headers,
- body,
- // Node 18+ fetch doesn't expose a timeout option in the standard API;
- // we rely on the OS TCP timeout (typically 2 min). The callback is
- // best-effort so a slow/hanging response is acceptable.
- })
+ postCallback(url, { method: 'POST', headers, body }, runId, kind)
.then(async (response) => {
if (!response.ok) {
logger.warn('side_effect:non_2xx', { run: runId, kind, status: response.status })
- await releaseMilestoneClaim(releaseClaim, runId, kind)
+ if (response.status >= 500) {
+ await releaseMilestoneClaim(releaseClaim, runId, kind)
+ }
return
}
const payload: unknown = await response.json().catch(() => null)
@@ -174,7 +202,7 @@ function fireCallback(
})
.catch(async (err: unknown) => {
const message = err instanceof Error ? err.message : String(err)
- logger.error('side_effect:failed', { run: runId, kind, error: message })
+ logger.error('side_effect:failed', { run: runId, kind, error: message, code: fetchErrorCode(err) })
await releaseMilestoneClaim(releaseClaim, runId, kind)
})
}
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index 1dab64f6c2de..7170bb8f8d37 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -1283,6 +1283,27 @@ describe('ingest-handler', () => {
global.fetch = originalFetch
})
+ it('keeps the command claim when the Django callback answers 400', async () => {
+ const originalFetch = global.fetch
+ global.fetch = vi.fn(async () => new Response('', { status: 400 })) as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+
+ const commandEvent = {
+ type: 'notification',
+ notification: { method: '_posthog/agent_command_dispatched', params: {} },
+ }
+ const ndjson = JSON.stringify({ seq: 1, event: commandEvent }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+ expect(res.status).toBe(200)
+
+ await new Promise((r) => setTimeout(r, 10))
+
+ expect(await redisStream.claimFirstAgentCommand()).toBe(false)
+ global.fetch = originalFetch
+ })
+
it('still returns 200 when the Django callback returns a non-2xx status', async () => {
const originalFetch = global.fetch
global.fetch = vi.fn(async () => new Response('', { status: 500 })) as typeof fetch
@@ -1327,6 +1348,41 @@ describe('ingest-handler', () => {
global.fetch = originalFetch
})
+ const turnComplete = { type: 'notification', notification: { method: '_posthog/turn_complete' } }
+ const sessionUpdate = { type: 'notification', notification: { method: 'session/update', params: {} } }
+ const networkFailure = Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNRESET' } })
+
+ it.each([
+ ['awaiting_input', turnComplete, 'network failure', networkFailure, 2],
+ ['awaiting_input', turnComplete, '503', new Response('', { status: 503 }), 2],
+ ['awaiting_input', turnComplete, '400', new Response('', { status: 400 }), 1],
+ ['heartbeat', sessionUpdate, 'network failure', networkFailure, 1],
+ ['heartbeat', sessionUpdate, '503', new Response('', { status: 503 }), 1],
+ ])(
+ 'a %s callback whose first attempt ends in a %s is sent %i time(s) in total',
+ async (_kind, event, _label, firstOutcome, expectedCalls) => {
+ vi.useFakeTimers()
+ const originalFetch = global.fetch
+ const fetchMock = vi
+ .fn()
+ .mockImplementationOnce(() =>
+ firstOutcome instanceof Error ? Promise.reject(firstOutcome) : Promise.resolve(firstOutcome)
+ )
+ .mockResolvedValue(new Response('{"dispatched": true}', { status: 200 }))
+ global.fetch = fetchMock as typeof fetch
+
+ const config = makeConfig({ djangoCallbackBaseUrl: 'http://django' })
+ await heartbeatWorkflowIfNeeded(redisStream, RUN_ID, event, TASK_ID, TEAM_ID, 'tok', config)
+ await vi.advanceTimersByTimeAsync(2000)
+
+ expect(fetchMock).toHaveBeenCalledTimes(expectedCalls)
+ expect((fetchMock.mock.calls[0]?.[1] as RequestInit).signal).toBeInstanceOf(AbortSignal)
+
+ global.fetch = originalFetch
+ vi.useRealTimers()
+ }
+ )
+
it('sets agent active and fires heartbeat for a session/update event', async () => {
const fired: { kind: string }[] = []
const originalFetch = global.fetch