: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): gateway-only generation events; never use pi cost estimates (#65457)
Ben Whited96f9b4dad3e
diff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.tsindex a77af44c7394..e02b292363b7 100644--- a/products/agent_platform/services/agent-janitor/src/server.test.ts+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts@@ -326,7 +326,9 @@ describe('janitor HTTP', () => {expect(real.body).toMatchObject({ scanned: 1, updated: 1, dry_run: false })const after = (await queue.get(uuidFor('s-backfill')))!expect(after.usage_total.tokens_in).toBe(7)- expect(after.usage_total.cost_total).toBeCloseTo(0.015, 10)+ // Cost is owned by the gateway's settled figure, never recomputed from pi-ai's+ // conversation estimates — so the backfill rewrites tokens but leaves cost at zero.+ expect(after.usage_total.cost_total).toBe(0)// Second run finds nothing to update.const repeat = await request(app)diff --git a/products/agent_platform/services/agent-runner/src/index.ts b/products/agent_platform/services/agent-runner/src/index.tsindex 3487189cff5f..9b4fdb689e64 100644--- a/products/agent_platform/services/agent-runner/src/index.ts+++ b/products/agent_platform/services/agent-runner/src/index.ts@@ -312,6 +312,13 @@ async function main(): Promise<void> {? (session) => ({'X-PostHog-Distinct-Id': analyticsDistinctId(session),'X-PostHog-Trace-Id': session.id,+ // Agent attribution onto the gateway's `$ai_generation` so the+ // observability board can slice per agent. The gateway strips+ // `$ai_*` from this passthrough but keeps `$agent_*`.+ 'X-PostHog-Properties': JSON.stringify({+ $agent_application_id: session.application_id,+ $agent_session_id: session.id,+ }),}): undefined,// /v1/usage + /v1/wallet reads use the same static phs_ (the `phc` field@@ -319,10 +326,11 @@ async function main(): Promise<void> {resolveGatewayUsage: gatewayClient? () => ({ client: gatewayClient, phc: config.posthogAiGatewayKey! }): undefined,- // On the gateway path pi-ai's cost numbers are client-side estimates;- // the gateway itself owns billing. We keep token counts. Cost is- // recovered post-turn via /v1/usage/{request_id} (see resolveGatewayUsage).- useGatewayCost: config.useAiGateway,+ // Gateway path: the gateway emits the `$ai_generation` (settled cost ++ // the attribution above), so the runner suppresses its own. Session-row+ // cost comes from /v1/usage post-turn (resolveGatewayUsage); pi-ai's+ // estimate is never used.+ gatewayEmitsGenerations: config.useAiGateway,analytics,maxConcurrency: config.maxConcurrency,maxOutputTokens: config.maxOutputTokens,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 682c44e75660..16dd641fd29a 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@@ -11,6 +11,9 @@ import {import { Pool } from 'pg'import {+ type AnalyticsEvent,+ type AnalyticsGenerationEvent,+ type AnalyticsSink,AgentRevision,type ApprovalRequest,type ApprovalStore,@@ -664,7 +667,7 @@ describe('driver runSession', () => {streamFn: recordingStreamFn(calls),gatewayHeaders: { 'X-PostHog-Distinct-Id': 'team:1:agent:app', 'X-PostHog-Trace-Id': TEST_SESSION_ID },gatewayUsage: { client: { getUsage } as never, phc: 'phc_test' },- useGatewayCost: true,+ gatewayEmitsGenerations: true,})expect(out.state).toBe('completed')// One outbound call, headers carry the static gateway headers@@ -731,7 +734,7 @@ describe('driver runSession', () => {streamFn: recordingStreamFn(calls),gatewayHeaders: {},gatewayUsage: { client: { getUsage } as never, phc: 'phc_test' },- useGatewayCost: true,+ gatewayEmitsGenerations: true,})expect(out.state).toBe('completed')expect(session.usage_total.cost_total).toBe(0)@@ -750,6 +753,43 @@ describe('driver runSession', () => {})})+ /**+ * Generation-event emission splits by path: on the gateway path the gateway+ * emits the cost-bearing `$ai_generation`, so the runner must NOT emit its+ * own (double-counting); off the gateway path it emits one, without cost+ * (pi-ai's estimate is never used — ingestion prices it from the catalog).+ * Spans/trace are runner-only and emitted on both paths.+ */+ describe('analytics generation emission', () => {+ function recordingSink(events: AnalyticsEvent[]): AnalyticsSink {+ return { write: async (batch) => void events.push(...batch) }+ }++ it('suppresses the runner $ai_generation on the gateway path; still emits the trace', async () => {+ const events: AnalyticsEvent[] = []+ const out = await run(makeRev(), makeSession(), {+ script: [stop('hi back')],+ analytics: recordingSink(events),+ gatewayEmitsGenerations: true,+ })+ expect(out.state).toBe('completed')+ expect(events.filter((e) => e.kind === 'generation')).toHaveLength(0)+ expect(events.some((e) => e.kind === 'trace')).toBe(true)+ })++ it('emits one $ai_generation without cost on the direct path', async () => {+ const events: AnalyticsEvent[] = []+ const out = await run(makeRev(), makeSession(), {+ script: [stop('hi back')],+ analytics: recordingSink(events),+ })+ expect(out.state).toBe('completed')+ const gens = events.filter((e): e is AnalyticsGenerationEvent => e.kind === 'generation')+ expect(gens).toHaveLength(1)+ expect(gens[0].cost_usd).toBeUndefined()+ })+ })+/*** The chat stop button: ingress publishes a `cancel` bus event (caught by* the runner's existing per-session subscription) and writes the durablediff --git a/products/agent_platform/services/agent-runner/src/loop/driver.ts b/products/agent_platform/services/agent-runner/src/loop/driver.tsindex b066384fb9f8..34eb0e0990fd 100644--- a/products/agent_platform/services/agent-runner/src/loop/driver.ts+++ b/products/agent_platform/services/agent-runner/src/loop/driver.ts@@ -141,8 +141,13 @@ export interface RunSessionDeps {analytics?: AnalyticsSink/** Agent display name, used to name the `$ai_trace`. Falls back to the slug, then the app id. */applicationName?: string- /** Suppress pi-ai's client-side cost numbers (gateway tracks cost server-side). */- useGatewayCost?: boolean+ /**+ * True on the ai-gateway path: the gateway emits its own `$ai_generation`+ * (settled cost + the `X-PostHog-Properties` attribution), so the runner+ * suppresses its duplicate. Still emits `$ai_span`/`$ai_trace` and still+ * settles cost into the session row via `gatewayUsage`.+ */+ gatewayEmitsGenerations?: boolean/** Approval-gated tool store. MANDATORY — gated tools queue instead of* executing and resume via the decided-marker path in getSteeringMessages.* `runSession` throws if it's missing rather than running gated tools@@ -161,11 +166,12 @@ export interface RunSessionDeps {tabularStore?: TabularStore/*** Per-session static HTTP headers stamped on every outbound model call.- * On the ai-gateway path this carries `X-PostHog-Distinct-Id` +- * `X-PostHog-Trace-Id` so gateway-emitted `$ai_generation` events- * attribute correctly. 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+ * On the ai-gateway path this carries `X-PostHog-Distinct-Id`,+ * `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`.*/@@ -699,9 +705,7 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depserrorMessage: msg.errorMessage,timestamp: msg.timestamp,}- session.usage_total = accumulateUsage(session.usage_total, record, {- useGatewayCost: deps.useGatewayCost,- })+ session.usage_total = accumulateUsage(session.usage_total, record)for (const b of msg.content) {if (b.type === 'text' && b.text) {@@ -738,14 +742,12 @@ export async function runSession(rev: AgentRevision, session: AgentSession, deps}}- // Gateway settled-cost recovery: pi-ai's `usage.cost.*` numbers- // are client-side estimates on the gateway path (zeroed by- // `accumulateUsage` when `useGatewayCost`), so fetch the real- // cost from `GET /v1/usage/<request_id>` and merge it. Best-- // effort — a transient fetch failure leaves cost_total- // unchanged for that turn (the gateway also emits its own- // `$ai_generation` event with the cost, so the loss is- // bounded to the session row's running total).+ // Gateway settled-cost recovery: `accumulateUsage` never+ // trusts pi-ai estimates, so `GET /v1/usage/<request_id>` is+ // the sole source of the session row's cost on this path.+ // Best-effort — a failed/NaN fetch leaves cost_total+ // unchanged (the gateway's own $ai_generation still carries+ // the cost).if (deps.gatewayUsage) {const requestId = turnRequestIds.get(turn)if (requestId) {@@ -779,34 +781,39 @@ export async function runSession(rev: AgentRevision, session: AgentSession, depsturnRequestIds.delete(turn)}- await analytics.write([- {- kind: 'generation',- ts: new Date(msg.timestamp).toISOString(),- team_id: session.team_id,- application_id: session.application_id,- revision_id: rev.id,- session_id: session.id,- turn,- span_id: genSpan,- distinct_id: distinctId,- model: msg.model ?? deps.model.id,- provider: msg.provider ?? deps.model.provider,- input: inputSnapshot,- output: msg.content,- input_tokens: msg.usage?.input ?? 0,- output_tokens: msg.usage?.output ?? 0,- cache_read_tokens: msg.usage?.cacheRead,- cache_write_tokens: msg.usage?.cacheWrite,- total_tokens: msg.usage?.totalTokens,- latency_ms: Date.now() - turnStart,- cost_usd: deps.useGatewayCost ? undefined : msg.usage?.cost?.total,- stop_reason: msg.stopReason,- is_error: msg.stopReason === 'error',- error: msg.stopReason === 'error' ? msg.errorMessage : undefined,- is_preview: session.is_preview,- },- ])+ // Gateway path: the gateway emits the `$ai_generation` (with+ // cost), so skip ours to avoid double-counting. Direct path:+ // emit without cost and let ingestion price it — pi-ai's+ // estimate is never used.+ if (!deps.gatewayEmitsGenerations) {+ await analytics.write([+ {+ kind: 'generation',+ ts: new Date(msg.timestamp).toISOString(),+ team_id: session.team_id,+ application_id: session.application_id,+ revision_id: rev.id,+ session_id: session.id,+ turn,+ span_id: genSpan,+ distinct_id: distinctId,+ model: msg.model ?? deps.model.id,+ provider: msg.provider ?? deps.model.provider,+ input: inputSnapshot,+ output: msg.content,+ input_tokens: msg.usage?.input ?? 0,+ output_tokens: msg.usage?.output ?? 0,+ cache_read_tokens: msg.usage?.cacheRead,+ cache_write_tokens: msg.usage?.cacheWrite,+ total_tokens: msg.usage?.totalTokens,+ latency_ms: Date.now() - turnStart,+ stop_reason: msg.stopReason,+ is_error: msg.stopReason === 'error',+ error: msg.stopReason === 'error' ? msg.errorMessage : undefined,+ is_preview: session.is_preview,+ },+ ])+ }await deps.onTurnPersist?.(session)return}diff --git a/products/agent_platform/services/agent-runner/src/workers/worker.ts b/products/agent_platform/services/agent-runner/src/workers/worker.tsindex 4faa1af5919a..c6752754769a 100644--- a/products/agent_platform/services/agent-runner/src/workers/worker.ts+++ b/products/agent_platform/services/agent-runner/src/workers/worker.ts@@ -135,11 +135,11 @@ export interface WorkerDeps {/** Operator override (AGENT_MAX_OUTPUT_TOKENS); clamps per-turn max_tokens below model ceiling. */maxOutputTokens?: number/**- * Set to true when calls go through PostHog's ai-gateway. The runner- * keeps token counts but drops pi-ai's `cost.*` accumulation — the- * gateway tracks cost server-side; client-side estimates are unreliable.+ * True on the ai-gateway path: the gateway emits the `$ai_generation`+ * (settled cost + forwarded attribution), so the runner suppresses its+ * duplicate. pi-ai's `cost.*` estimates are never used regardless.*/- useGatewayCost?: boolean+ gatewayEmitsGenerations?: boolean/*** Approval-gated tools store. MANDATORY and* fail-closed: `requires_approval` in spec.tools is a security control, so@@ -536,7 +536,7 @@ export class Worker {applicationName: application?.name || application?.slug,shutdownSignal: this.shutdownController.signal,getSessionState: async (id) => (await this.deps.queue.get(id))?.state ?? null,- useGatewayCost: this.deps.useGatewayCost,+ gatewayEmitsGenerations: this.deps.gatewayEmitsGenerations,gatewayHeaders,gatewayUsage,approvals: this.deps.approvals,diff --git a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.tsindex 510354f937e4..5f759216b66c 100644--- a/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts+++ b/products/agent_platform/services/agent-shared/src/runtime/analytics-sink.ts@@ -90,7 +90,11 @@ export interface AnalyticsGenerationEvent extends AnalyticsEventBase {total_tokens?: number/** Wall-clock duration of the pi-ai call, milliseconds. */latency_ms: number- /** Total cost in USD as reported by pi-ai. Suppressed when the gateway path is in use (see useGatewayCost). */+ /**+ * Total cost in USD. No longer set by the runner — the gateway emits cost on+ * the gateway path, and ingestion prices direct-path events from the+ * catalog. pi-ai's estimate is never used. Kept on the shape for consumers.+ */cost_usd?: number/** pi-ai stopReason — `stop`, `length`, `toolUse`, `error`, `aborted`. */stop_reason?: stringdiff --git a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.tsindex 4b07da48330b..05474487238b 100644--- a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts+++ b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts@@ -99,7 +99,7 @@ describe('totalConversationUsage', () => {})})- it('aggregates tokens + cost across multiple assistant turns', () => {+ it('aggregates token counts across assistant turns but never pi-estimated cost', () => {const c: ConversationMessage[] = [user('q1'),assistant({ text: 'a1', input: 100, output: 10, costIn: 0.001, costOut: 0.0005 }),@@ -109,9 +109,11 @@ describe('totalConversationUsage', () => {const total = totalConversationUsage(c)expect(total.tokens_in).toBe(150)expect(total.tokens_out).toBe(15)- expect(total.cost_input).toBeCloseTo(0.0015, 10)- expect(total.cost_output).toBeCloseTo(0.0008, 10)- expect(total.cost_total).toBeCloseTo(0.0023, 10)+ // pi-ai's per-message cost estimates are never trusted — cost is owned+ // by the gateway settlement merged onto the persisted column, not here.+ expect(total.cost_input).toBe(0)+ expect(total.cost_output).toBe(0)+ expect(total.cost_total).toBe(0)})it('ignores user / toolResult messages and assistant turns missing usage', () => {@@ -129,22 +131,26 @@ describe('totalConversationUsage', () => {})describe('accumulateUsage', () => {- it('folds one assistant message into a running total', () => {+ it('folds token counts into a running total but never pi-estimated cost', () => {const msg = assistant({ input: 10, output: 2, costIn: 0.1, costOut: 0.05 })const after = accumulateUsage(EMPTY_USAGE_TOTAL, msg)expect(after.tokens_in).toBe(10)expect(after.tokens_out).toBe(2)- expect(after.cost_total).toBeCloseTo(0.15, 10)+ // Cost is never taken from pi-ai's estimate, even when the message reports it.+ expect(after.cost_input).toBe(0)+ expect(after.cost_output).toBe(0)+ expect(after.cost_total).toBe(0)})- it('keeps tokens but zeros cost when useGatewayCost is true', () => {+ it('carries prior cost forward unchanged — gateway settlement owns cost_total', () => {+ // The driver merges the gateway's settled /v1/usage figure into+ // cost_total post-turn; accumulateUsage must preserve it, not clobber or+ // add a pi estimate on top.+ const prev = { ...EMPTY_USAGE_TOTAL, cost_total: 0.42 }const msg = assistant({ input: 10, output: 2, costIn: 0.1, costOut: 0.05 })- const after = accumulateUsage(EMPTY_USAGE_TOTAL, msg, { useGatewayCost: true })+ const after = accumulateUsage(prev, msg)expect(after.tokens_in).toBe(10)- expect(after.tokens_out).toBe(2)- expect(after.cost_input).toBe(0)- expect(after.cost_output).toBe(0)- expect(after.cost_total).toBe(0)+ expect(after.cost_total).toBe(0.42)})it('returns the prev total unchanged when the message has no usage', () => {diff --git a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.tsindex 4de02537476c..8584aa816bcb 100644--- a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts+++ b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts@@ -62,34 +62,27 @@ export function totalConversationUsage(conversation: ConversationMessage[]): Ses}/**- * Fold one assistant message's `usage` into a running total. Used by both- * the runner's per-turn accumulator and the backfill walk.- *- * `useGatewayCost: true` means the model went through PostHog's- * ai-gateway — pi-ai's cost fields in that path are unreliable estimates,- * so we keep token counts but zero the cost contribution. The gateway is- * the source of truth for cost on that path; a future revision pulls our- * own price-table calc in here.+ * Fold one assistant message's `usage` into a running total (runner per-turn+ * accumulator + backfill walk). Accumulates tokens but NEVER pi-ai's `cost.*`+ * estimates — cost is owned by the gateway's settled /v1/usage figure, which+ * the driver merges into `cost_total` post-turn. Off the gateway path the row+ * cost stays zero (ingestion prices events from the catalog). Cost fields carry+ * forward unchanged here.*/-export function accumulateUsage(- prev: SessionUsageTotal,- msg: AssistantMessageRecord,- opts: { useGatewayCost?: boolean } = {}-): SessionUsageTotal {+export function accumulateUsage(prev: SessionUsageTotal, msg: AssistantMessageRecord): SessionUsageTotal {const usage = msg.usageif (!usage) {return prev}- const trustCost = !opts.useGatewayCostreturn {tokens_in: prev.tokens_in + (usage.input ?? 0),tokens_out: prev.tokens_out + (usage.output ?? 0),cache_read: prev.cache_read + (usage.cacheRead ?? 0),cache_write: prev.cache_write + (usage.cacheWrite ?? 0),- cost_input: prev.cost_input + (trustCost ? (usage.cost?.input ?? 0) : 0),- cost_output: prev.cost_output + (trustCost ? (usage.cost?.output ?? 0) : 0),- cost_cache_read: prev.cost_cache_read + (trustCost ? (usage.cost?.cacheRead ?? 0) : 0),- cost_cache_write: prev.cost_cache_write + (trustCost ? (usage.cost?.cacheWrite ?? 0) : 0),- cost_total: prev.cost_total + (trustCost ? (usage.cost?.total ?? 0) : 0),+ cost_input: prev.cost_input,+ cost_output: prev.cost_output,+ cost_cache_read: prev.cost_cache_read,+ cost_cache_write: prev.cost_cache_write,+ cost_total: prev.cost_total,}}