: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(cdp): route workflow usage by billing category (#99235)
Ben Whiteb740ffbb602f
diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.tsindex f9cdab499840..5bee38308cf9 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts@@ -538,14 +538,28 @@ describe('SourceWebhooksConsumer', () => {metric_name: 'triggered',count: 1,}),- expect.objectContaining({- metric_kind: 'billing',- metric_name: 'billable_invocation',- count: 1,- }),])})+ it('does not report a workflow trigger as CDP usage', async () => {+ const reportBillableInvocation = jest.spyOn(+ api['cdpSourceWebhooksConsumer']['cdpUsageReporter'],+ 'reportBillableInvocation'+ )++ const res = await doPostRequest({+ webhookId: hogFlow.id,+ body: {+ event: 'my-event',+ distinct_id: 'test-distinct-id',+ },+ })++ expect(res.status).toEqual(201)+ await waitForBackgroundTasks()+ expect(reportBillableInvocation).not.toHaveBeenCalled()+ })+it('does not report usage when queueing the workflow fails', async () => {const reportBillableInvocation = jest.spyOn(api['cdpSourceWebhooksConsumer']['cdpUsageReporter'],diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.tsindex e87ec14d9972..1683f8f478e3 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts@@ -300,17 +300,6 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConf})await this.hogflowQueue.queueInvocations([hogFlowInvocation])-- addMetric({- metric_kind: 'billing',- metric_name: 'billable_invocation',- count: 1,- })-- this.cdpUsageReporter.reportBillableInvocation({- teamId: invocation.teamId,- recordId: `webhook:${invocationId}`,- })} else {addMetric({metric_kind: 'failure',diff --git a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.tsindex 284c33b11583..1c554155d12c 100644--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts@@ -233,6 +233,7 @@ export class HogFunctionInvocationPipeline {})this.deps.cdpUsageReporter?.reportBillableInvocation({teamId: item.teamId,+ usageKey: 'cdp_billable_invocations',recordId: `event:${eventUuid}`,})}diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.tsindex 058e1e28a955..929f5c8d2d98 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.test.ts@@ -28,6 +28,7 @@ import { EmailService } from '../../messaging/email.service'import { EmailTrackingCodeSigner } from '../../messaging/helpers/tracking-code'import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'import { RecipientTokensService } from '../../messaging/recipient-tokens.service'+import { CdpUsageReporterService } from '../../usage/cdp-usage-reporter.service'import { HogFlowFunctionsService } from '../hogflow-functions.service'import { findActionByType } from '../hogflow-utils'import { HogFunctionHandler } from './hog_function'@@ -476,14 +477,23 @@ describe('HogFunctionHandler', () => {// The billing kind is the whole point of the per-channel handlers: push bills at its own rate// (roughly half of email), so a completed invocation must emit exactly one billable_invocation// carrying the handler's billing type — never fall back to another channel's kind.- it.each(['fetch', 'email', 'push'] as const)(+ it.each([+ ['fetch', 'workflow_billable_invocations'],+ ['email', 'workflow_emails_sent'],+ ['push', 'workflow_push_sent'],+ ['sms', 'workflow_sms_sent'],+ ] as const)('emits a single billable_invocation with %s kind matching the handler billing type',- async (billingType) => {+ async (billingType, usageKey) => {+ const usageReporter: Pick<CdpUsageReporterService, 'reportBillableInvocation'> = {+ reportBillableInvocation: jest.fn(),+ }const handler = new HogFunctionHandler(mockHogFlowFunctionsService,mockRecipientPreferencesService,mockEmailValidationService,- billingType+ billingType,+ usageReporter)const invocationResult = createInvocationResult<CyclotronJobInvocationHogFlow>(invocation, {@@ -507,6 +517,9 @@ describe('HogFunctionHandler', () => {metric_name: 'billable_invocation',count: 1,})+ expect(usageReporter.reportBillableInvocation).toHaveBeenCalledWith(+ expect.objectContaining({ teamId: team.id, usageKey })+ )})diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex 71534aa5a09c..dd9f7d7ae30d 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -27,6 +27,14 @@ import { observeMissingVariableReferences } from '../hogflow-variable-usage'import { ActionHandler, ActionHandlerOptions, ActionHandlerResult } from './action.interface'type FunctionActionType = 'function' | 'function_email' | 'function_sms'+type HogFlowActionBillingType = 'fetch' | 'email' | 'push' | 'sms'++const WORKFLOW_USAGE_KEYS = {+ fetch: 'workflow_billable_invocations',+ email: 'workflow_emails_sent',+ push: 'workflow_push_sent',+ sms: 'workflow_sms_sent',+} as consttype Action = Extract<HogFlowAction, { type: FunctionActionType }>@@ -84,8 +92,8 @@ export class HogFunctionHandler implements ActionHandler {private hogFlowFunctionsService: HogFlowFunctionsService,private recipientPreferencesService: RecipientPreferencesService,private emailValidationService: EmailValidationService,- private hogFlowActionBillingType: 'fetch' | 'email' | 'push',- private usageReporter?: CdpUsageReporterService,+ private hogFlowActionBillingType: HogFlowActionBillingType,+ private usageReporter?: Pick<CdpUsageReporterService, 'reportBillableInvocation'>,private options: { awaitedStepsEnabled?: boolean } = {}) {}@@ -166,6 +174,7 @@ export class HogFunctionHandler implements ActionHandler {// actionStepCount holds across a retry of this step but changes on a loop revisit.this.usageReporter?.reportBillableInvocation({teamId: invocation.teamId,+ usageKey: WORKFLOW_USAGE_KEYS[this.hogFlowActionBillingType],recordId: `flow:${invocation.id}:${invocation.state.actionStepCount}:${this.hogFlowActionBillingType}`,})diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 054dce0f01d9..34ab46ddb2d8 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -139,6 +139,14 @@ export class HogFlowExecutorService {'email',usageReporter)+ const hogFunctionSmsHandler = new HogFunctionHandler(+ hogFlowFunctionsService,+ recipientPreferencesService,+ emailValidationService,+ 'sms',+ usageReporter,+ options+ )const hogFunctionPushHandler = new HogFunctionHandler(hogFlowFunctionsService,recipientPreferencesService,@@ -155,7 +163,7 @@ export class HogFlowExecutorService {wait_until_time_window: new WaitUntilTimeWindowHandler(),random_cohort_branch: new RandomCohortBranchHandler(),function: hogFunctionHandler,- function_sms: hogFunctionHandler,+ function_sms: hogFunctionSmsHandler,function_push: hogFunctionPushHandler,function_email: hogFunctionEmailHandler,exit: new ExitHandler(),diff --git a/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.test.ts b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.test.tsindex 634579b5464b..246886428e03 100644--- a/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.test.ts+++ b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.test.ts@@ -23,8 +23,8 @@ describe('CdpUsageReporterService', () => {it('bills a retried invocation once', async () => {const reporter = new CdpUsageReporterService(client, () => true)- reporter.reportBillableInvocation({ teamId: 1, recordId: 'event:abc' })- reporter.reportBillableInvocation({ teamId: 1, recordId: 'event:abc' })+ reporter.reportBillableInvocation({ teamId: 1, usageKey: 'cdp_billable_invocations', recordId: 'event:abc' })+ reporter.reportBillableInvocation({ teamId: 1, usageKey: 'cdp_billable_invocations', recordId: 'event:abc' })await reporter.flush()expect(ingested[0]).toEqual([@@ -39,7 +39,7 @@ describe('CdpUsageReporterService', () => {it('flushes on its own schedule without a caller flush', async () => {const reporter = new CdpUsageReporterService(client, () => true, 1000)- reporter.reportBillableInvocation({ teamId: 1, recordId: 'event:abc' })+ reporter.reportBillableInvocation({ teamId: 1, usageKey: 'cdp_billable_invocations', recordId: 'event:abc' })expect(client.ingest).not.toHaveBeenCalled()@@ -51,7 +51,7 @@ describe('CdpUsageReporterService', () => {it('records nothing for a team the matcher excludes', async () => {const reporter = new CdpUsageReporterService(client, (teamId) => teamId === 2, 1000)- reporter.reportBillableInvocation({ teamId: 1, recordId: 'event:abc' })+ reporter.reportBillableInvocation({ teamId: 1, usageKey: 'cdp_billable_invocations', recordId: 'event:abc' })await reporter.flush()expect(client.ingest).not.toHaveBeenCalled()diff --git a/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.ts b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.tsindex ae21d2fcf146..4a832b3fc07f 100644--- a/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.ts+++ b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.ts@@ -3,12 +3,17 @@ import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { logger } from '~/common/utils/logger'import { ValueMatcher } from '~/types'-const USAGE_KEY = 'cdp_billable_invocations'const DEFAULT_FLUSH_INTERVAL_MS = 10_000const MAX_PENDING_RECORDS = 2_000export interface CdpBillableInvocation {teamId: number+ usageKey:+ | 'cdp_billable_invocations'+ | 'workflow_billable_invocations'+ | 'workflow_emails_sent'+ | 'workflow_push_sent'+ | 'workflow_sms_sent'/** Identity of the billed thing. A replay must produce the same value, or it bills twice. */recordId: string}@@ -31,7 +36,7 @@ export class CdpUsageReporterService {}reportBillableInvocation(invocation: CdpBillableInvocation): void {- this.batch.add(invocation.teamId, USAGE_KEY, invocation.recordId)+ this.batch.add(invocation.teamId, invocation.usageKey, invocation.recordId)if (this.batch.size >= MAX_PENDING_RECORDS) {void this.flush()return