: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-runner): key gateway settled-cost lookup by the gateway's request id (#65804)
Ben White8c4b48c2498f
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 16dd641fd29a..c3fa19d83e9d 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@@ -636,25 +636,35 @@ describe('driver runSession', () => {* cost fetch. Uses a recording `streamFn` injected via deps so we can* inspect the headers pi-ai would see, and a fake GatewayClient so we* can drive cost merge without hitting a real /v1/usage. The behaviour- * here is load-bearing for the ai-gateway path — without the per-turn- * `request_id` stamp + Idempotency-Key, the gateway can't dedupe pi-ai- * retries onto a single billed row, and without the post-turn- * `getUsage` merge `usage_total.cost_total` stays zero forever.+ * here is load-bearing for the ai-gateway path: the Idempotency-Key lets+ * the gateway collapse pi-ai retries onto one billed row, and the post-turn+ * `getUsage` keyed by the gateway's OWN response id is the sole source of+ * `usage_total.cost_total` — key it wrong and cost stays zero forever.*/describe('gateway metadata + post-turn settled cost', () => {- // Build a streamFn that just delegates to `streamSimple` but records- // every call's options.headers in the provided array.+ // Build a streamFn that delegates to `streamSimple` but records every+ // call's options.headers. When `gatewayRequestId` is given it first+ // fires `onResponse` with that id in the (lowercased) `x-request-id`+ // header — the faux provider returns no response headers, so this+ // simulates the gateway stamping its server-minted settlement id.function recordingStreamFn(- calls: Array<{ headers: Record<string, string> | undefined }>+ calls: Array<{ headers: Record<string, string> | undefined }>,+ gatewayRequestId?: string): Parameters<typeof runSession>[2]['streamFn'] {- return (model, ctx, opts) => {+ return async (model, ctx, opts) => {calls.push({ headers: opts?.headers as Record<string, string> | undefined })+ if (gatewayRequestId) {+ await opts?.onResponse?.({ status: 200, headers: { 'x-request-id': gatewayRequestId } }, model)+ }return streamSimple(model, ctx, opts)}}- it('stamps Idempotency-Key + X-Request-Id per turn and merges settled cost', async () => {+ it('keys settled cost by the gateway response id, not the Idempotency-Key', async () => {const calls: Array<{ headers: Record<string, string> | undefined }> = []+ // The gateway mints this server-side and returns it in X-Request-ID;+ // the runner must fetch usage by THIS id, never its own outbound key.+ const GW_ID = 'a1b2c3d4e5f600112233445566778899'const getUsage = vi.fn(async (requestId: string) => ({request_id: requestId,team_id: 1,@@ -664,29 +674,28 @@ describe('driver runSession', () => {const session = makeSession()const out = await run(makeRev(), session, {script: [stop('hi back')],- streamFn: recordingStreamFn(calls),+ streamFn: recordingStreamFn(calls, GW_ID),gatewayHeaders: { 'X-PostHog-Distinct-Id': 'team:1:agent:app', 'X-PostHog-Trace-Id': TEST_SESSION_ID },gatewayUsage: { client: { getUsage } as never, phc: 'phc_test' },gatewayEmitsGenerations: true,})expect(out.state).toBe('completed')- // One outbound call, headers carry the static gateway headers- // PLUS the per-turn id matching the `agent:<session>:<turn>` shape.+ // One outbound call carrying the static gateway headers + the per-turn+ // Idempotency-Key. X-Request-Id is NOT sent (the gateway ignores any+ // inbound value and mints its own).expect(calls).toHaveLength(1)expect(calls[0].headers).toMatchObject({'X-PostHog-Distinct-Id': 'team:1:agent:app','X-PostHog-Trace-Id': TEST_SESSION_ID,})- // 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.+ const idempotencyKey = calls[0].headers?.['Idempotency-Key']+ expect(idempotencyKey).toMatch(new RegExp(`^agent:${TEST_SESSION_ID}:1:[0-9a-f-]{36}$`))+ expect(calls[0].headers ?? {}).not.toHaveProperty('X-Request-Id')+ // getUsage was keyed by the GATEWAY id from the response header, not+ // our Idempotency-Key (the old bug); the cost merged into usage_total.expect(getUsage).toHaveBeenCalledTimes(1)- expect(getUsage).toHaveBeenCalledWith(reqId, { phc: 'phc_test' })+ expect(getUsage).toHaveBeenCalledWith(GW_ID, { phc: 'phc_test' })+ expect(getUsage).not.toHaveBeenCalledWith(idempotencyKey, { phc: 'phc_test' })expect(session.usage_total.cost_total).toBeCloseTo(0.42, 5)})@@ -723,12 +732,38 @@ describe('driver runSession', () => {it('survives a getUsage NaN/failure without polluting cost_total', async () => {const calls: Array<{ headers: Record<string, string> | undefined }> = []const getUsage = vi.fn(async () => ({- request_id: `agent:${TEST_SESSION_ID}:1`,+ request_id: 'gw-nan',team_id: 1,cost_usd: 'not-a-number',settled_at: new Date().toISOString(),}))const session = makeSession()+ const out = await run(makeRev(), session, {+ script: [stop('hi back')],+ // Simulate the gateway returning an id so the cost fetch is reached.+ streamFn: recordingStreamFn(calls, 'gw-nan'),+ gatewayHeaders: {},+ gatewayUsage: { client: { getUsage } as never, phc: 'phc_test' },+ gatewayEmitsGenerations: true,+ })+ expect(out.state).toBe('completed')+ expect(getUsage).toHaveBeenCalledWith('gw-nan', { phc: 'phc_test' })+ expect(session.usage_total.cost_total).toBe(0)+ })++ it('fails open when the gateway returns no X-Request-ID: no getUsage, cost stays 0', async () => {+ // No gateway id → recordingStreamFn lets the faux provider fire+ // onResponse with empty headers (the gateway-misroute / header-strip+ // case). turnRequestIds never gets an id, so the cost fetch is+ // skipped cleanly instead of 404'ing on a bogus key.+ const calls: Array<{ headers: Record<string, string> | undefined }> = []+ const getUsage = vi.fn(async () => ({+ request_id: 'unused',+ team_id: 1,+ cost_usd: '9.99',+ settled_at: new Date().toISOString(),+ }))+ const session = makeSession()const out = await run(makeRev(), session, {script: [stop('hi back')],streamFn: recordingStreamFn(calls),@@ -737,6 +772,7 @@ describe('driver runSession', () => {gatewayEmitsGenerations: true,})expect(out.state).toBe('completed')+ expect(getUsage).not.toHaveBeenCalled()expect(session.usage_total.cost_total).toBe(0)})diff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex 33235a99aecc..b21ad2540fb4 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -170,19 +170,21 @@ export interface RunSessionDeps {* `X-PostHog-Trace-Id`, and `X-PostHog-Properties` (the `$agent_*`* attribution) so the gateway-emitted `$ai_generation` events attribute to* the right user, trace, and agent application. The `gatewayMetadataStreamFn`- * wrapper merges these with a per-turn `Idempotency-Key` + `X-Request-Id` of- * the form `agent:<session>:<turn>` and forwards them to pi-ai's per-call- * `options.headers`. Presence also signals `errorContext()` to mark- * failures as `source: ai_gateway`.+ * wrapper merges these with a per-turn `Idempotency-Key` of the form+ * `agent:<session>:<turn>:<nonce>` and forwards them to pi-ai's per-call+ * `options.headers` (it does NOT send `X-Request-Id` — the gateway mints its+ * own and returns it in the response header). Presence also signals+ * `errorContext()` to mark failures as `source: ai_gateway`.*/gatewayHeaders?: Record<string, string>/*** Gateway read client + the team's `phc_` bearer. When set, after every* pi-ai turn the runner fetches `GET /v1/usage/<request_id>` (using the- * id stamped by `gatewayMetadataStreamFn`) and merges the- * gateway-computed cost into `usage_total.cost_total`. Best-effort: a- * transient fetch failure or NaN body is logged + skipped so a gateway- * blip can't strand the turn.+ * gateway's settlement id captured from the response by+ * `gatewayMetadataStreamFn`) and merges the gateway-computed cost into+ * `usage_total.cost_total`. Best-effort: a transient fetch failure, a+ * missing id, or a NaN body is logged/skipped so a gateway blip can't+ * strand the turn.*/gatewayUsage?: {client: GatewayClient@@ -1312,23 +1314,30 @@ export function translateAssistantNamesBack(}/**- * 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`.+ * Stamp `Idempotency-Key` + any caller-supplied gateway headers+ * (`X-PostHog-Distinct-Id`, `X-PostHog-Trace-Id`) on every outbound model call,+ * and capture the gateway's settlement reference into `turnRequestIds` (keyed+ * by the outbound-call counter) so the sink can fetch settled cost via+ * `GET /v1/usage/<id>` after `turn_end`.*- * The id MUST be globally unique per outbound call. `outboundTurn` is a+ * Idempotency-Key MUST be 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.+ * `agent:<session>:<turn>` collides across turns: the first 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, so the+ * follow-up replays that stale response with no output (0 tokens). The per-call+ * `randomUUID()` nonce keeps it unique across resumes yet stable within a call,+ * so pi-ai's SDK-level retries on transient 5xx still collapse onto one billed+ * row.+ *+ * The usage lookup keys off the GATEWAY's id, not ours. The gateway mints its+ * own settlement reference server-side — a client-chosen id would let a caller+ * collapse every debit as a duplicate — and returns it in the `X-Request-ID`+ * response header; it ignores any inbound `X-Request-Id`. We read it back via+ * pi-ai's `onResponse` (header keys are lowercased). Keying off the+ * runner-chosen id never matched the ledger → `getUsage` 404'd every turn and+ * cost stayed $0. A missing header (no `onResponse`, gateway misroute) just+ * leaves the turn's entry unset → cost merge is skipped (fail-open).*/function gatewayMetadataStreamFn(base: StreamFn,@@ -1339,15 +1348,20 @@ function gatewayMetadataStreamFn(let outboundTurn = 0return async (model, context, options) => {outboundTurn++- const requestId = `agent:${sessionId}:${outboundTurn}:${randomUUID()}`- turnRequestIds.set(outboundTurn, requestId)- const headers = {- ...gatewayHeaders,- ...options?.headers,- 'Idempotency-Key': requestId,- 'X-Request-Id': requestId,- }- return base(model, context, { ...options, headers })+ const turnIndex = outboundTurn+ const idempotencyKey = `agent:${sessionId}:${turnIndex}:${randomUUID()}`+ const priorOnResponse = options?.onResponse+ return base(model, context, {+ ...options,+ headers: { ...gatewayHeaders, ...options?.headers, 'Idempotency-Key': idempotencyKey },+ onResponse: async (response, m) => {+ const id = response.headers['x-request-id']+ if (id) {+ turnRequestIds.set(turnIndex, id)+ }+ await priorOnResponse?.(response, m)+ },+ })}}