: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-platform): unique Idempotency-Key per model call so resumes don't replay (#64610)
Ben White1b861bee5c7f
diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts b/products/agent_platform/services/agent-runner/src/loop/driver.test.tsindex a1a4d6a87a49..e40c7297ada7 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.test.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.test.ts@@ -679,16 +679,50 @@ describe('driver runSession', () => {expect(calls[0].headers).toMatchObject({'X-PostHog-Distinct-Id': 'team:1:agent:app','X-PostHog-Trace-Id': TEST_SESSION_ID,- 'Idempotency-Key': `agent:${TEST_SESSION_ID}:1`,- 'X-Request-Id': `agent:${TEST_SESSION_ID}:1`,})+ // The id carries the `agent:<session>:<turn>:<nonce>` shape;+ // Idempotency-Key and X-Request-Id are the same id, and the nonce+ // makes each call unique (see the resume regression test below).+ const reqId = calls[0].headers?.['Idempotency-Key']+ expect(reqId).toMatch(new RegExp(`^agent:${TEST_SESSION_ID}:1:[0-9a-f-]{36}$`))+ expect(calls[0].headers?.['X-Request-Id']).toBe(reqId)// getUsage was called for that exact request id; the returned// cost landed in usage_total.expect(getUsage).toHaveBeenCalledTimes(1)- expect(getUsage).toHaveBeenCalledWith(`agent:${TEST_SESSION_ID}:1`, { phc: 'phc_test' })+ expect(getUsage).toHaveBeenCalledWith(reqId, { phc: 'phc_test' })expect(session.usage_total.cost_total).toBeCloseTo(0.42, 5)})+ it('uses a unique Idempotency-Key per call so resumes never collide', async () => {+ // Regression: `outboundTurn` resets to 1 on every runSession, so a+ // key of just `agent:<session>:<turn>` made every follow-up's first+ // call reuse `agent:<session>:1`. The gateway then replayed the+ // first turn's cached response (24h Idempotency-Key window) instead+ // of calling the model, and the follow-up ended instantly with no+ // output. The per-call nonce must make each key distinct.+ const calls: Array<{ headers: Record<string, string> | undefined }> = []+ const gatewayHeaders = { 'X-PostHog-Trace-Id': TEST_SESSION_ID }+ const session = makeSession()+ // Two independent runSession invocations against the SAME session —+ // an initial turn followed by a /send-driven resume.+ await run(makeRev(), session, {+ script: [stop('first')],+ streamFn: recordingStreamFn(calls),+ gatewayHeaders,+ })+ await run(makeRev(), session, {+ script: [stop('second')],+ streamFn: recordingStreamFn(calls),+ gatewayHeaders,+ })+ expect(calls).toHaveLength(2)+ const firstKey = calls[0].headers?.['Idempotency-Key']+ const secondKey = calls[1].headers?.['Idempotency-Key']+ expect(firstKey).toMatch(new RegExp(`^agent:${TEST_SESSION_ID}:1:`))+ expect(secondKey).toMatch(new RegExp(`^agent:${TEST_SESSION_ID}:1:`))+ expect(secondKey).not.toBe(firstKey)+ })+it('survives a getUsage NaN/failure without polluting cost_total', async () => {const calls: Array<{ headers: Record<string, string> | undefined }> = []const getUsage = vi.fn(async () => ({diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex 5c10be8b32b3..fc4d80b7e3bc 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -1253,15 +1253,23 @@ export function translateAssistantNamesBack(}/**- * Stamp `Idempotency-Key` + `X-Request-Id` (both `agent:<session>:<turn>`)- * on every outbound model call, plus any caller-supplied gateway headers- * (`X-PostHog-Distinct-Id`, `X-PostHog-Trace-Id`). The id is recorded in- * `turnRequestIds` keyed by the loop's outbound-call counter so the sink- * can fetch settled cost via `GET /v1/usage/<request_id>` after `turn_end`.+ * Stamp `Idempotency-Key` + `X-Request-Id` on every outbound model call,+ * plus any caller-supplied gateway headers (`X-PostHog-Distinct-Id`,+ * `X-PostHog-Trace-Id`). The id is recorded in `turnRequestIds` keyed by the+ * loop's outbound-call counter so the sink can fetch settled cost via+ * `GET /v1/usage/<request_id>` after `turn_end`.*- * Idempotency on this exact id buys gateway-side dedupe for pi-ai's own- * retries on transient 5xx — the gateway collapses both attempts onto the- * same usage row and bills the team once.+ * The id MUST be globally unique per outbound call. `outboundTurn` is a+ * per-`runSession` counter that resets to 0 on every resume, so a key of just+ * `agent:<session>:<turn>` collides across turns: the first model call of+ * every follow-up reuses `agent:<session>:1`, which the gateway already has+ * cached under its 24h Idempotency-Key window from the session's first turn.+ * The gateway then replays that stale response instead of calling the model,+ * so the follow-up turn ends instantly with no output (0 tokens). The+ * per-call `randomUUID()` nonce keeps the id unique across resumes while+ * staying stable within a single call — pi-ai's SDK-level retries on+ * transient 5xx reuse these same headers, so the gateway still collapses one+ * call's retries onto a single billed usage row.*/function gatewayMetadataStreamFn(base: StreamFn,@@ -1272,7 +1280,7 @@ function gatewayMetadataStreamFn(let outboundTurn = 0return async (model, context, options) => {outboundTurn++- const requestId = `agent:${sessionId}:${outboundTurn}`+ const requestId = `agent:${sessionId}:${outboundTurn}:${randomUUID()}`turnRequestIds.set(outboundTurn, requestId)const headers = {...gatewayHeaders,