: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
feat(usage): report usage records from ingestion and cdp (#87143)
Ben Whitee6c4c68e3b17
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.mdnew file mode 100644index 000000000000..6c3b1cf1a5fc--- /dev/null+++ b/docs/internal/usage-record-producers.md@@ -0,0 +1,197 @@+# Where billing usage records come from++Every producer of `billing_usage_records` and the exact point in its flow where usage is counted.+The rule that shapes all of them: **count after the last step that can drop the thing being billed, and before the row is written.**++## Reading the tables++`ReplacingMergeTree(inserted_at)` sorts by `(team_id, toDate(timestamp), producer_id, usage_key, record_id)`.+Two records sharing those five collapse to one — they do not add, and the later send wins.+So a producer's `record_id` has to be a stable identity for the billed thing: the same work replayed must produce the same ID, and different work must never share one.++What it protects against is our own duplication, not a sender's.+If someone sends the same thing twice we ingest it twice and bill it twice, which is correct.+The identity exists so our retries and reprocessing of one ingested thing collapse to one row.++`timestamp` is in the sort key as a date, because every billing read filters a time range and a date in the key prunes where a skip index only skips granules.+Every producer stamps it from its own clock when it flushes, never from anything a customer sends — a customer-controlled value would decide whether their own records deduplicate.+The cost is that deduplication is scoped to a UTC day, so a reprocess that crosses midnight leaves two rows.++`inserted_at` is the engine's version column but is deliberately absent from the HogQL schema.+`timestamp` is monotonic per resend, so `argMax(quantity, timestamp)` reads what a merge would keep, and one time column cannot be confused for the other.++Read with `argMax(quantity, timestamp)` grouped by the sort key. HogQL rejects `FINAL` outright, so this is the only correct shape there.+The collapse happens on merge, so a plain `sum(quantity)` counts every un-merged duplicate.+Measured locally: two identical batches landing in separate parts read as 6 rows summing 18 without `FINAL`, and 3 rows summing 9 with it.++| producer_id | usage_key | unit | record_id | deployment |+| ---------------- | -------------------------- | ----------- | ----------------------------------------------------------------------------------------------- | --------------------- |+| `ingestion` | `events`, `ai_events` | events | `{day}:{event}:{distinct_id}:{uuid}` | ingestion consumers |+| `ai-ingestion` | `ai_events` | events | `{day}:{event}:{distinct_id}:{uuid}` | AI ingestion consumer |+| `error-tracking` | `exceptions` | events | `{day}:{event}:{distinct_id}:{uuid}` | error tracking server |+| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers |+| `feature-flags` | `feature_flag_requests` | requests | fresh UUIDv7 per flush | feature flags service |++Every producer reads one env var, `USAGE_INGESTION_REPORT_TEAMS`: `''` reports nothing, `*` every team, `1,2` those teams.+Each producer above is its own deployment, so one name still rolls out per producer, set in that service's config.+Empty is the default everywhere, so nothing reports until it is set.+There is deliberately no percentage option: sampling a share of a team's events would bill that team a fraction of what it used.++Every record carries quantity 1 and names one billed thing, so the aggregate lives in ClickHouse rather than in the producer.+A producer that sees the same identity twice sends one record, because two records sharing an identity collapse rather than add.++## Analytics ingestion++```mermaid+flowchart TD+ K[events_plugin_ingestion] --> DENY[deny $exception, heatmap, client warning]+ DENY --> RESTRICT[token restrictions: drop / force overflow]+ RESTRICT --> RL[rate limit to overflow]+ RL --> PARSE[parse message]+ PARSE --> TEAM[resolve team]+ TEAM --> HIST[validate historical migration]+ HIST --> FILTERS[customer event filters]+ FILTERS --> COOKIELESS[cookieless processing]+ COOKIELESS --> DROPOLD[drop old events]+ DROPOLD --> TRANSFORM[hog transformations]+ TRANSFORM --> PERSONS[person processing]+ PERSONS --> PREPARE[prepare event]+ PREPARE --> GROUPS[process groups]+ GROUPS --> COUNT[**count usage**]+ COUNT --> CREATE[create event]+ CREATE --> EMIT[emit to clickhouse_events_json]++ DENY -.dropped.-> X[not counted]+ RESTRICT -.dropped.-> X+ RL -.redirected.-> OF[overflow topic, counted on the overflow lane]+ PARSE -.dlq.-> X+ TEAM -.dlq.-> X+ HIST -.dropped.-> X+ FILTERS -.dropped.-> X+ DROPOLD -.dropped.-> X+ TRANSFORM -.dropped.-> X+```++Counting sits between group processing and event creation, the last point where the event still carries its own team, name and Kafka message.+Everything that can drop an event runs upstream of it.++`resolveAnalyticsUsageKey` decides the key from the event name, so an event is billed under the product that owns it wherever it turns up.+A known AI event that reaches this lane is billed as `ai_events`, not as a standard event, and the non-billable names (`$feature_flag_called`, `$experiment_exposure`, survey events, `$exception`, conversations widget events) return no key at all.+That list mirrors `BILLABLE_EVENT_EXCLUDED_EVENTS` in `posthog/tasks/usage_report.py`; the two have to agree or the same team is billed differently by the two systems.+The AI check matches the exact names in `AI_EVENT_TYPES` rather than the `$ai_` prefix, for the same reason: the report excludes the exact `AIEventType` values, so an unknown `$ai_something` is a standard billable event on both sides.++Overflow is not a drop. A redirected event is consumed again on the overflow lane, whose consumer reports under its own topic and partition, so it is counted exactly once.++### Why the identity mirrors the events table++The first version of this keyed a record on the batch's consumed offset range and carried the batch's count.+That is not replay-safe: Kafka does not promise the same batch boundaries twice, so a replay produces different IDs and the totals add.+Measured before the change: 6 events read as batches of 3 produced `0-2:events`; the same events re-read as one batch produced `0-8:events`, a new ID overlapping the first, and the total doubled.++The event's own identity has none of that. It travels inside the event and does not depend on how a consumer batched.+Measured after the change: the same events re-consumed by a fresh consumer group with a different batch size wrote 6 raw rows where `FINAL` still reads 3 — the replay landed and deduplicated instead of billing twice.++The UUID alone is not that identity. `sharded_events` is itself a `ReplacingMergeTree` sorted by `(team_id, toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid))`, so two events sharing a UUID but differing in day, name or distinct ID are separate rows there.+The nightly report counts them separately too — `get_teams_with_billable_event_count_in_period` counts `distinct toDate(timestamp), event, cityHash64(distinct_id), cityHash64(uuid)` — so keying on the UUID alone would have collapsed rows the report bills for.+The `record_id` therefore carries that whole tuple minus the team the billing sorting key already holds. The timestamp is UTC-normalized upstream, so its first ten characters are the day `toDate` resolves.++The cost is one record per event rather than one per batch. Records are still batched into requests of up to `USAGE_INGESTION_MAX_BATCH_SIZE`, so the request count is a function of batch size, not event count.++### The one case that over-counts++Counting happens before the Kafka produce, and the produce is not awaited.+An event that fails to emit with `message_size_too_large` is counted but never lands in `clickhouse_events_json`.+Moving the count onto the acknowledgement does not work: it resolves after the batch's flush step, so the count would land in a cleared accumulator.+Emission retries five times, so the residue is bounded by that one non-retried failure, which also raises an ingestion warning.++## AI ingestion++Same shape, on its own lane. The allow step DLQs anything that is not an AI event, so every event that reaches the counting step is billable and the resolver returns `ai_events` unconditionally.++AI events are double-written to `clickhouse_events_json` and `clickhouse_ai_events_json`. Counting runs before the split, so the double write bills once.++## Error tracking++```mermaid+flowchart TD+ K[exceptions_ingestion] --> RESTRICT[token restrictions]+ RESTRICT --> RL[rate limit to overflow]+ RL --> PARSE[parse message]+ PARSE --> TEAM[resolve team]+ TEAM --> COOKIELESS[cookieless processing]+ COOKIELESS --> CYMBAL[cymbal: symbolication, fingerprint, issue link]+ CYMBAL --> PERSON[fetch person]+ PERSON --> TRANSFORM[hog transformations]+ TRANSFORM --> PREPARE[prepare event]+ PREPARE --> GROUPS[process groups]+ GROUPS --> COUNT[**count usage**]+ COUNT --> CREATE[create event]+ CREATE --> EMIT[emit to clickhouse_events_json]++ CYMBAL -.suppressed.-> X[not counted]+ RESTRICT -.dropped.-> X+ PARSE -.dlq.-> X+```++Cymbal is the Rust symbolication service, and it suppresses exceptions — a suppressed exception is dropped from the pipeline.+Counting runs after it, so a suppressed exception is never billed.+Cymbal runs before enrichment for an unrelated reason (it only needs the raw exception, so suppressing early saves the enrichment work), which happens to put every one of its drops upstream of the counting step.++## CDP++CDP reports through `CdpUsageReporterService`, which owns its own batching and flush timer.+It is deliberately not derived from the `billable_invocation` app metric: the app metrics could be deleted without touching billing.+Three call sites report, each next to the app metric it is independent of:++| Site | When | record_id |+| --------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------- |+| `hog-function-invocation-pipeline.service.ts` | an event triggers at least one destination | `event:{eventUuid}` |+| `hogflows/actions/hog_function.ts` | a workflow function action executed and was not skipped | `flow:{invocationId}:{actionStepCount}:{kind}` |+| `cdp-source-webhooks.consumer.ts` | a webhook produced a workflow trigger | `webhook:{invocationId}` |++The event-triggered site bills once per triggering event, not per destination, matching the existing app metric.+The workflow site keys on `actionStepCount` so a cyclotron retry of the same step reuses the ID and deduplicates, while a loop that revisits the same action gets a new one and bills again.++The reporter flushes on a timer rather than at a consumer batch boundary, and `CdpBaseConsumer.stop()` flushes it, so a graceful deploy loses nothing.+An ungraceful exit can still lose up to one interval of records per pod.++## Feature flags++The billing aggregator already counts requests in memory per `(team, request_type, library, bucket)` and flushes them to Redis on a tick.+Usage records are emitted from inside that flush, once a chunk has been credited to Redis, so a Redis retry cannot bill twice and the two stores can only disagree by a failed usage request.++`record_id` is a fresh UUIDv7 per emission rather than something derived from the aggregation key.+The key is not a stable identity for a delta: a Redis outage rebuckets and merges requeued entries, so the same key legitimately carries different quantities across flushes.+ID reuse is therefore scoped to the retry the gRPC client performs on one request. This is the one producer whose records are aggregates rather than one per billed thing.++Sends go through a bounded queue drained by one owned task, and `shutdown` closes the queue and awaits it within the aggregator's flush timeout, so a deploy does not lose records Redis just credited.+A full queue drops and counts the drop rather than growing; Redis still holds the authoritative count.++## Trying it locally++The service's compose entry sits behind the `ingestion` profile and builds from source, so run it from cargo instead:++```sh+docker compose -f docker-compose.dev.yml up -d db redis7 kafka clickhouse+DEBUG=1 python manage.py migrate_clickhouse+cd rust && USAGE_INGESTION_DATABASE_URL=postgres://posthog:posthog@localhost:5432/posthog \+ cargo run -p usage-ingestion+```++Then point a producer at it and turn its team matcher on:++```sh+USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' ./bin/start+FLAGS_USAGE_INGESTION_URL=http://localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' cargo run -p feature-flags+```++Records land within one flush interval:++```sql+SELECT producer_id, usage_key, sum(quantity), count()+FROM billing_usage_records GROUP BY 1, 2 ORDER BY 1, 2+```++## What is not reported yet++Session replay, surveys, data warehouse rows synced, batch export rows, logs and APM all still reach billing only through the nightly usage report.diff --git a/nodejs/buf.gen.usage-ingestion.yaml b/nodejs/buf.gen.usage-ingestion.yamlnew file mode 100644index 000000000000..a5999785af0f--- /dev/null+++ b/nodejs/buf.gen.usage-ingestion.yaml@@ -0,0 +1,6 @@+version: v2+plugins:+ - local: ../nodejs/node_modules/.bin/protoc-gen-es+ out: ../nodejs/src/common/generated/usage-ingestion+ opt:+ - target=tsdiff --git a/nodejs/src/cdp/cdp-services.ts b/nodejs/src/cdp/cdp-services.tsindex 7e81ce43663b..1fc0bbee0687 100644--- a/nodejs/src/cdp/cdp-services.ts+++ b/nodejs/src/cdp/cdp-services.ts@@ -2,6 +2,7 @@ import { AppMetricsOutput, HogInvocationResultsOutput, LogEntriesOutput } from 'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { RedisV2, createRedisV2PoolFromConfig } from '~/common/redis/redis-v2'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'import { PostgresRouter } from '~/common/utils/db/postgres'import { getRedisHost } from '~/common/utils/db/redis'import { logger } from '~/common/utils/logger'@@ -44,6 +45,7 @@ import { HogWatcherService } from './services/monitoring/hog-watcher.service'import { NativeDestinationExecutorService } from './services/native-destination-executor.service'import { RateLimiterService } from './services/rate-limiter/rate-limiter.service'import { SegmentDestinationExecutorService } from './services/segment-destination-executor.service'+import { CdpUsageReporterService } from './services/usage/cdp-usage-reporter.service'import { WarehouseWebhooksService } from './services/warehouse/warehouse-webhooks.service'import { MAX_FETCH_TIMEOUT_MS, cdpTrackedFetch } from './utils/cdp-fetch'import { configureValkeyReads } from './utils/dual-store'@@ -90,6 +92,7 @@ export interface CdpCoreServices {cohortMembershipRepository: CohortMembershipRepositoryhogFlowExecutor: HogFlowExecutorServicehogFunctionMonitoringService: HogFunctionMonitoringService+ cdpUsageReporter: CdpUsageReporterServicecapturedEventsService: CapturedEventsService/** Per-invocation lifecycle row producer for the new runs/invocations UI + rerun path. */hogInvocationResultsService: HogInvocationResultsService@@ -109,6 +112,7 @@ export type CdpCoreServicesConfig = Pick<CommonConfig,'REDIS_URL' | 'REDIS_POOL_MIN_SIZE' | 'REDIS_POOL_MAX_SIZE' | 'ENCRYPTION_SALT_KEYS' | 'SITE_URL'> &+ UsageIngestionConfig &Pick<CdpConfig,| 'CDP_REDIS_HOST'@@ -480,12 +484,17 @@ export function createCdpCoreServices(const cohortMembershipRepository = new PostgresCohortMembershipRepository(deps.postgres)// Observer writes to both stores; the read source decides which verdict drives the metric.const hogFlowDuplicateObserver = new HogFlowDuplicateObserverService(redis, valkeyShadow.writer)+ const cdpUsageReporter = new CdpUsageReporterService(+ createUsageIngestionClient(config, 'cdp'),+ usageReportTeamMatcher(config)+ )const hogFlowExecutor = new HogFlowExecutorService(hogFlowFunctionsService,recipientPreferencesService,emailValidationService,cohortMembershipRepository,- hogFlowDuplicateObserver+ hogFlowDuplicateObserver,+ cdpUsageReporter)const hogFunctionMonitoringService = new HogFunctionMonitoringService(outputs)@@ -521,6 +530,7 @@ export function createCdpCoreServices(cohortMembershipRepository,hogFlowExecutor,hogFunctionMonitoringService,+ cdpUsageReporter,capturedEventsService,hogInvocationResultsService,invocationResultsService,diff --git a/nodejs/src/cdp/consumers/cdp-base.consumer.ts b/nodejs/src/cdp/consumers/cdp-base.consumer.tsindex 10531dadc1ac..34b7af63624d 100644--- a/nodejs/src/cdp/consumers/cdp-base.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-base.consumer.ts@@ -34,6 +34,7 @@ import { HogMaskerService } from '../services/monitoring/hog-masker.service'import { HogWatcherService } from '../services/monitoring/hog-watcher.service'import { NativeDestinationExecutorService } from '../services/native-destination-executor.service'import { SegmentDestinationExecutorService } from '../services/segment-destination-executor.service'+import { CdpUsageReporterService } from '../services/usage/cdp-usage-reporter.service'export type CdpConsumerBaseConfig = CdpCoreServicesConfig &Pick<CommonConfig, 'KAFKA_CLIENT_RACK'> &@@ -73,6 +74,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = CdemailService: EmailServicehogFunctionMonitoringService: HogFunctionMonitoringService+ cdpUsageReporter: CdpUsageReporterServiceinvocationResultsService: InvocationResultsServicenativeDestinationExecutorService: NativeDestinationExecutorServicepluginDestinationExecutorService: LegacyPluginExecutorService@@ -103,6 +105,7 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cdthis.hogFlowExecutor = services.hogFlowExecutorthis.emailService = services.emailServicethis.hogFunctionMonitoringService = services.hogFunctionMonitoringService+ this.cdpUsageReporter = services.cdpUsageReporterthis.invocationResultsService = services.invocationResultsServicethis.nativeDestinationExecutorService = services.nativeDestinationExecutorServicethis.segmentDestinationExecutorService = services.segmentDestinationExecutorService@@ -129,11 +132,12 @@ export abstract class CdpConsumerBase<TConfig extends CdpConsumerBaseConfig = Cd// through `cdpProducerRegistry.disconnectAll()`.}- public stop(): Promise<void> {+ public async stop(): Promise<void> {logger.info('🔁', `${this.name} - stopping`)this.isStopping = true+ // Billing records live only in memory until they are sent, so a graceful stop drains them.+ await this.cdpUsageReporter.shutdown()logger.info('👍', `${this.name} - stopped!`)- return Promise.resolve()}public abstract isHealthy(): HealthCheckResultdiff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex e043ee9a518a..16e0a4be8b6c 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -73,6 +73,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {hogWatcherMirror: this.hogWatcherMirror,hogMasker: this.hogMasker,hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ cdpUsageReporter: this.cdpUsageReporter,quotaLimiting: deps.quotaLimiting,redis: this.redis,valkeyShadow: this.valkeyShadow,diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex e9064e92b1e7..210318c28b3a 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -47,6 +47,7 @@ export class CdpEventsConsumer<hogWatcherMirror: this.hogWatcherMirror,hogMasker: this.hogMasker,hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ cdpUsageReporter: this.cdpUsageReporter,quotaLimiting: deps.quotaLimiting,redis: this.redis,valkeyShadow: this.valkeyShadow,diff --git a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.tsindex e79990c73c8f..801cc180a655 100644--- a/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-internal-event.consumer.ts@@ -52,6 +52,7 @@ export class CdpInternalEventsConsumer extends CdpConsumerBase {hogWatcherMirror: this.hogWatcherMirror,hogMasker: this.hogMasker,hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ cdpUsageReporter: this.cdpUsageReporter,quotaLimiting: deps.quotaLimiting,redis: this.redis,valkeyShadow: this.valkeyShadow,diff --git a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.tsindex 182292782f42..7aea74893f1e 100644--- a/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-person-updates-consumer.ts@@ -38,6 +38,7 @@ export class CdpPersonUpdatesConsumer extends CdpConsumerBase {hogWatcherMirror: this.hogWatcherMirror,hogMasker: this.hogMasker,hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ cdpUsageReporter: this.cdpUsageReporter,quotaLimiting: deps.quotaLimiting,redis: this.redis,valkeyShadow: this.valkeyShadow,diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.tsindex 04f5a9d1d689..69a4cd24a740 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.test.ts@@ -536,6 +536,32 @@ describe('SourceWebhooksConsumer', () => {])})+ it('does not report usage when queueing the workflow fails', async () => {+ const reportBillableInvocation = jest.spyOn(+ api['cdpSourceWebhooksConsumer']['cdpUsageReporter'],+ 'reportBillableInvocation'+ )+ mockQueueHogflowInvocationsSpy.mockRejectedValueOnce(new Error('queue unavailable'))++ const res = await doPostRequest({+ webhookId: hogFlow.id,+ body: {+ event: 'my-event',+ distinct_id: 'test-distinct-id',+ },+ })++ expect(res.status).toEqual(500)+ await waitForBackgroundTasks()+ expect(reportBillableInvocation).not.toHaveBeenCalled()+ expect(getMetrics()).not.toContainEqual(+ expect.objectContaining({+ metric_kind: 'billing',+ metric_name: 'billable_invocation',+ })+ )+ })+it('should not capture webhook event to database and should remove execution count property', async () => {// Mock the monitoring service to track what events would be capturedconst mockQueueInvocationResults = jest.spyOn(diff --git a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.tsindex babf5fe07c94..e87ec14d9972 100644--- a/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-source-webhooks.consumer.ts@@ -299,13 +299,18 @@ export class CdpSourceWebhooksConsumer extends CdpConsumerBase<PluginsServerConfcount: 1,})+ await this.hogflowQueue.queueInvocations([hogFlowInvocation])+addMetric({metric_kind: 'billing',metric_name: 'billable_invocation',count: 1,})- await this.hogflowQueue.queueInvocations([hogFlowInvocation])+ 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 30240c372fef..284c33b11583 100644--- a/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-function-invocation-pipeline.service.ts@@ -22,6 +22,7 @@ import { HogFunctionManagerService } from './managers/hog-function-manager.serviimport { HogFunctionMonitoringService } from './monitoring/hog-function-monitoring.service'import { HogMaskerService } from './monitoring/hog-masker.service'import { HogWatcherService, HogWatcherState, sameWatcherStates } from './monitoring/hog-watcher.service'+import { CdpUsageReporterService } from './usage/cdp-usage-reporter.service'export interface HogFunctionInvocationPipelineConfig {CDP_RATE_LIMITER_BUCKET_SIZE: number@@ -37,6 +38,7 @@ export interface HogFunctionInvocationPipelineDeps {hogWatcherMirror: HogWatcherServicehogMasker: HogMaskerServicehogFunctionMonitoringService: HogFunctionMonitoringService+ cdpUsageReporter?: CdpUsageReporterServicequotaLimiting: QuotaLimitingredis: RedisV2valkeyShadow: CdpValkeyShadowPools@@ -229,6 +231,10 @@ export class HogFunctionInvocationPipeline {metric_name: 'billable_invocation',count: 1,})+ this.deps.cdpUsageReporter?.reportBillableInvocation({+ teamId: item.teamId,+ recordId: `event:${eventUuid}`,+ })}}})diff --git a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts b/nodejs/src/cdp/services/hogflows/actions/hog_function.tsindex 26fa549b01a3..f5550bb23505 100644--- a/nodejs/src/cdp/services/hogflows/actions/hog_function.ts+++ b/nodejs/src/cdp/services/hogflows/actions/hog_function.ts@@ -12,6 +12,7 @@ import {import { HogExecutorExecuteAsyncOptions } from '../../hog-executor-async.service'import { EmailValidationService } from '../../messaging/email-validation.service'import { RecipientPreferencesService } from '../../messaging/recipient-preferences.service'+import { CdpUsageReporterService } from '../../usage/cdp-usage-reporter.service'import { trackHogFlowBillableInvocation } from '../billing-utils'import { HogFlowFunctionsService } from '../hogflow-functions.service'import { actionIdForLogging, findContinueAction } from '../hogflow-utils'@@ -27,7 +28,8 @@ export class HogFunctionHandler implements ActionHandler {private hogFlowFunctionsService: HogFlowFunctionsService,private recipientPreferencesService: RecipientPreferencesService,private emailValidationService: EmailValidationService,- private hogFlowActionBillingType: 'fetch' | 'email' | 'push'+ private hogFlowActionBillingType: 'fetch' | 'email' | 'push',+ private usageReporter?: CdpUsageReporterService) {}async execute({@@ -97,6 +99,12 @@ export class HogFunctionHandler implements ActionHandler {billingMetricType: this.hogFlowActionBillingType,})+ // actionStepCount holds across a retry of this step but changes on a loop revisit.+ this.usageReporter?.reportBillableInvocation({+ teamId: invocation.teamId,+ recordId: `flow:${invocation.id}:${invocation.state.actionStepCount}:${this.hogFlowActionBillingType}`,+ })+// Re-pin the attribution version to the one that actually sent. Live edits reach runs// already in flight, so a run that entered on v2 can send its email after v3 is// published — and the conversion belongs to the version whose message the persondiff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex ecc1a2df8629..b393d8dfca7b 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -25,6 +25,7 @@ import { CohortMembershipRepository } from '../cohorts/cohort-membership-repositimport { HogExecutorExecuteAsyncOptions } from '../hog-executor-async.service'import { EmailValidationService } from '../messaging/email-validation.service'import { RecipientPreferencesService } from '../messaging/recipient-preferences.service'+import { CdpUsageReporterService } from '../usage/cdp-usage-reporter.service'import { ActionHandler } from './actions/action.interface'import { ConditionalBranchHandler } from './actions/conditional_branch'import { DelayHandler } from './actions/delay'@@ -114,7 +115,8 @@ export class HogFlowExecutorService {recipientPreferencesService: RecipientPreferencesService,emailValidationService: EmailValidationService,cohortMembershipRepository: CohortMembershipRepository,- duplicateObserver?: HogFlowDuplicateObserverService+ duplicateObserver?: HogFlowDuplicateObserverService,+ usageReporter?: CdpUsageReporterService) {this.hogFlowFunctionsService = hogFlowFunctionsServicethis.duplicateObserver = duplicateObserver ?? null@@ -122,19 +124,22 @@ export class HogFlowExecutorService {hogFlowFunctionsService,recipientPreferencesService,emailValidationService,- 'fetch'+ 'fetch',+ usageReporter)const hogFunctionEmailHandler = new HogFunctionHandler(hogFlowFunctionsService,recipientPreferencesService,emailValidationService,- 'email'+ 'email',+ usageReporter)const hogFunctionPushHandler = new HogFunctionHandler(hogFlowFunctionsService,recipientPreferencesService,emailValidationService,- 'push'+ 'push',+ usageReporter)this.actionHandlers = {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.tsnew file mode 100644index 000000000000..634579b5464b--- /dev/null+++ b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.test.ts@@ -0,0 +1,59 @@+import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'++import { CdpUsageReporterService } from './cdp-usage-reporter.service'++describe('CdpUsageReporterService', () => {+ let ingested: UsageRecordInput[][]+ let client: UsageIngestionClient++ beforeEach(() => {+ jest.useFakeTimers()+ ingested = []+ client = {+ ingest: jest.fn((records: UsageRecordInput[]) => {+ ingested.push(records)+ return Promise.resolve()+ }),+ } as unknown as UsageIngestionClient+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ 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' })+ await reporter.flush()++ expect(ingested[0]).toEqual([+ expect.objectContaining({+ recordId: 'event:abc',+ teamId: 1,+ quantity: 1,+ usageKey: 'cdp_billable_invocations',+ }),+ ])+ })++ 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' })++ expect(client.ingest).not.toHaveBeenCalled()++ jest.advanceTimersByTime(1000)+ await Promise.resolve()++ expect(client.ingest).toHaveBeenCalledTimes(1)+ })++ 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' })+ 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.tsnew file mode 100644index 000000000000..ae21d2fcf146--- /dev/null+++ b/nodejs/src/cdp/services/usage/cdp-usage-reporter.service.ts@@ -0,0 +1,72 @@+import { UsageIngestionClient } from '~/common/usage-ingestion/client'+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_000+const MAX_PENDING_RECORDS = 2_000++export interface CdpBillableInvocation {+ teamId: number+ /** Identity of the billed thing. A replay must produce the same value, or it bills twice. */+ recordId: string+}++/**+ * Deliberately independent of `app_metrics2`: it owns its own batching and flushing, so the app+ * metric a call site also emits can be deleted without touching billing. The timer bounds how+ * long a record waits; `shutdown()` is what keeps a graceful deploy lossless.+ */+export class CdpUsageReporterService {+ private batch: UsageRecordBatch+ private timer: NodeJS.Timeout | null = null++ constructor(+ client: UsageIngestionClient | null,+ isTeamEnabled: ValueMatcher<number>,+ private readonly flushIntervalMs: number = DEFAULT_FLUSH_INTERVAL_MS+ ) {+ this.batch = new UsageRecordBatch(client, { unit: 'invocations', isTeamEnabled })+ }++ reportBillableInvocation(invocation: CdpBillableInvocation): void {+ this.batch.add(invocation.teamId, USAGE_KEY, invocation.recordId)+ if (this.batch.size >= MAX_PENDING_RECORDS) {+ void this.flush()+ return+ }+ this.scheduleFlush()+ }++ /** One pass, for the timer: an invocation reported mid-send waits for the next flush. */+ async flush(): Promise<void> {+ await this.send(() => this.batch.flush())+ }++ /** For a consumer that is stopping: keeps flushing until nothing is left in memory. */+ async shutdown(): Promise<void> {+ await this.send(() => this.batch.drain())+ }++ private async send(sendBatch: () => Promise<void>): Promise<void> {+ if (this.timer) {+ clearTimeout(this.timer)+ this.timer = null+ }+ try {+ await sendBatch()+ } catch (error) {+ logger.warn('\u26a0\ufe0f', 'failed to flush cdp usage records', { error: String(error) })+ }+ }++ private scheduleFlush(): void {+ if (this.timer || this.batch.size === 0) {+ return+ }+ // Unreferenced so a pending flush never keeps the process alive on shutdown.+ this.timer = setTimeout(() => void this.flush(), this.flushIntervalMs)+ this.timer.unref()+ }+}diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.tsindex 281db4378fce..37d0c6012633 100644--- a/nodejs/src/common/config.ts+++ b/nodejs/src/common/config.ts@@ -137,6 +137,15 @@ export type CommonConfig = BaseServerConfig & {PERSONHOG_IDLE_CONNECTION_TIMEOUT_MS: numberPERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS: number+ // Usage ingestion gRPC. One team list per deployment, because each reporting site is its+ // own service: '' reports nothing, '*' every team, '1,2' those teams. No percentage: it+ // would bill a fraction of a team.+ USAGE_INGESTION_ADDR: string+ USAGE_INGESTION_TLS: boolean+ USAGE_INGESTION_TIMEOUT_MS: number+ USAGE_INGESTION_MAX_BATCH_SIZE: number+ USAGE_INGESTION_REPORT_TEAMS: string+// RedisREDIS_URL: stringINGESTION_REDIS_HOST: string@@ -319,6 +328,13 @@ export function getDefaultCommonConfig(): CommonConfig {PERSONHOG_IDLE_CONNECTION_TIMEOUT_MS: 15 * 60 * 1000,PERSONHOG_STATE_MONITOR_POLL_INTERVAL_MS: 5_000,+ // Usage ingestion gRPC+ USAGE_INGESTION_ADDR: isDevEnv() ? 'localhost:7143' : '',+ USAGE_INGESTION_TLS: false,+ USAGE_INGESTION_TIMEOUT_MS: 5_000,+ USAGE_INGESTION_MAX_BATCH_SIZE: 500,+ USAGE_INGESTION_REPORT_TEAMS: '',+// Redis// ok to connect to localhost over plaintext// nosemgrep: trailofbits.generic.redis-unencrypted-transport.redis-unencrypted-transportdiff --git a/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.ts b/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.tsnew file mode 100644index 000000000000..0ceac46548e4--- /dev/null+++ b/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.ts@@ -0,0 +1,136 @@+// @generated by protoc-gen-es v2.11.0 with parameter "target=ts"+// @generated from file usage_ingestion/v1/service.proto (package usage_ingestion.v1, syntax proto3)+import type { Message } from '@bufbuild/protobuf'+import type { GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2'+import { fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2'++/**+ * Describes the file usage_ingestion/v1/service.proto.+ */+export const file_usage_ingestion_v1_service: GenFile =+ /*@__PURE__*/+ fileDesc(+ 'CiB1c2FnZV9pbmdlc3Rpb24vdjEvc2VydmljZS5wcm90bxISdXNhZ2VfaW5nZXN0aW9uLnYxIpYBChJCaWxsaW5nVXNhZ2VSZWNvcmQSDwoHdGVhbV9pZBgBIAEoAxIUCgx0aW1lc3RhbXBfbXMYAiABKAMSEwoLcHJvZHVjZXJfaWQYAyABKAkSEQoJdXNhZ2Vfa2V5GAQgASgJEhEKCXJlY29yZF9pZBgFIAEoCRIQCghxdWFudGl0eRgGIAEoAxIMCgR1bml0GAcgASgJIlQKGUluZ2VzdEJpbGxpbmdVc2FnZVJlcXVlc3QSNwoHcmVjb3JkcxgBIAMoCzImLnVzYWdlX2luZ2VzdGlvbi52MS5CaWxsaW5nVXNhZ2VSZWNvcmQiOQoaSW5nZXN0QmlsbGluZ1VzYWdlUmVzcG9uc2USGwoTYWNjZXB0ZWRfcmVjb3JkX2lkcxgBIAMoCTKFAQoOVXNhZ2VJbmdlc3Rpb24ScwoSSW5nZXN0QmlsbGluZ1VzYWdlEi0udXNhZ2VfaW5nZXN0aW9uLnYxLkluZ2VzdEJpbGxpbmdVc2FnZVJlcXVlc3QaLi51c2FnZV9pbmdlc3Rpb24udjEuSW5nZXN0QmlsbGluZ1VzYWdlUmVzcG9uc2ViBnByb3RvMw'+ )++/**+ * Fields 1-5 are the record's identity, in the order the storage sorting key uses them:+ * (team_id, toDate(timestamp), producer_id, usage_key, record_id). A retry reuses all five+ * and collapses to one row. Correcting a quantity means re-sending the same identity, and+ * the last send wins.+ *+ * @generated from message usage_ingestion.v1.BillingUsageRecord+ */+export type BillingUsageRecord = Message<'usage_ingestion.v1.BillingUsageRecord'> & {+ /**+ * The service owns organization attribution: it resolves the organization from team_id,+ * so producers cannot supply one.+ *+ * @generated from field: int64 team_id = 1;+ */+ teamId: bigint++ /**+ * Stamp this from the producer's own clock when it emits, never from a customer payload.+ * It is part of the identity, so a value a customer controls would let them decide+ * whether their own records deduplicate.+ *+ * @generated from field: int64 timestamp_ms = 2;+ */+ timestampMs: bigint++ /**+ * @generated from field: string producer_id = 3;+ */+ producerId: string++ /**+ * @generated from field: string usage_key = 4;+ */+ usageKey: string++ /**+ * @generated from field: string record_id = 5;+ */+ recordId: string++ /**+ * @generated from field: int64 quantity = 6;+ */+ quantity: bigint++ /**+ * @generated from field: string unit = 7;+ */+ unit: string+}++/**+ * Describes the message usage_ingestion.v1.BillingUsageRecord.+ * Use `create(BillingUsageRecordSchema)` to create a new message.+ */+export const BillingUsageRecordSchema: GenMessage<BillingUsageRecord> =+ /*@__PURE__*/+ messageDesc(file_usage_ingestion_v1_service, 0)++/**+ * @generated from message usage_ingestion.v1.IngestBillingUsageRequest+ */+export type IngestBillingUsageRequest = Message<'usage_ingestion.v1.IngestBillingUsageRequest'> & {+ /**+ * @generated from field: repeated usage_ingestion.v1.BillingUsageRecord records = 1;+ */+ records: BillingUsageRecord[]+}++/**+ * Describes the message usage_ingestion.v1.IngestBillingUsageRequest.+ * Use `create(IngestBillingUsageRequestSchema)` to create a new message.+ */+export const IngestBillingUsageRequestSchema: GenMessage<IngestBillingUsageRequest> =+ /*@__PURE__*/+ messageDesc(file_usage_ingestion_v1_service, 1)++/**+ * @generated from message usage_ingestion.v1.IngestBillingUsageResponse+ */+export type IngestBillingUsageResponse = Message<'usage_ingestion.v1.IngestBillingUsageResponse'> & {+ /**+ * The service validates a whole batch before producing, so validation failures accept no+ * records. The RPC waits for Kafka delivery confirmation, so callers must use it off their+ * request-critical path. A retry after an unavailable response is safe because record_id is+ * the deduplication identity, including when Kafka delivered only part of the batch.+ *+ * @generated from field: repeated string accepted_record_ids = 1;+ */+ acceptedRecordIds: string[]+}++/**+ * Describes the message usage_ingestion.v1.IngestBillingUsageResponse.+ * Use `create(IngestBillingUsageResponseSchema)` to create a new message.+ */+export const IngestBillingUsageResponseSchema: GenMessage<IngestBillingUsageResponse> =+ /*@__PURE__*/+ messageDesc(file_usage_ingestion_v1_service, 2)++/**+ * UsageIngestion accepts usage records for durable analytics. Producers must reuse+ * record_id when retrying a record. The service preserves the producer's timestamp and+ * assigns insertion time when it publishes.+ *+ * IngestBillingUsage carries tenant-billable usage: exact, idempotent, retained+ * indefinitely. Cost and resource metering is a separate RPC and table.+ *+ * @generated from service usage_ingestion.v1.UsageIngestion+ */+export const UsageIngestion: GenService<{+ /**+ * @generated from rpc usage_ingestion.v1.UsageIngestion.IngestBillingUsage+ */+ ingestBillingUsage: {+ methodKind: 'unary'+ input: typeof IngestBillingUsageRequestSchema+ output: typeof IngestBillingUsageResponseSchema+ }+}> = /*@__PURE__*/ serviceDesc(file_usage_ingestion_v1_service, 0)diff --git a/nodejs/src/common/usage-ingestion/client.ts b/nodejs/src/common/usage-ingestion/client.tsnew file mode 100644index 000000000000..46708e4b1c3d--- /dev/null+++ b/nodejs/src/common/usage-ingestion/client.ts@@ -0,0 +1,114 @@+import { create } from '@bufbuild/protobuf'+import { Client, Code, ConnectError, createClient } from '@connectrpc/connect'+import { createGrpcTransport } from '@connectrpc/connect-node'+import { Counter } from 'prom-client'++import {+ BillingUsageRecordSchema,+ IngestBillingUsageRequestSchema,+ UsageIngestion,+} from '~/common/generated/usage-ingestion/usage_ingestion/v1/service_pb'+import { logger } from '~/common/utils/logger'++const usageRecordsSentCounter = new Counter({+ name: 'usage_ingestion_records_sent_total',+ help: 'Usage records accepted by the usage-ingestion service.',+ labelNames: ['producer_id', 'usage_key'],+})++const usageRecordsFailedCounter = new Counter({+ name: 'usage_ingestion_records_failed_total',+ help: 'Usage records dropped after the client exhausted its retries.',+ labelNames: ['producer_id', 'usage_key', 'error_code'],+})++const RETRYABLE_CODES = new Set([Code.Unavailable, Code.DeadlineExceeded, Code.ResourceExhausted, Code.Aborted])++export interface UsageRecordInput {+ /** Unique per (teamId, producerId, usageKey). Reused verbatim on retry, which is what makes ingest idempotent. */+ recordId: string+ teamId: number+ usageKey: string+ unit: string+ quantity: number+ timestampMs: number+}++export interface UsageIngestionClientConfig {+ addr: string+ producerId: string+ timeoutMs?: number+ maxBatchSize?: number+ useTls?: boolean+}++export class UsageIngestionClient {+ private readonly client: Client<typeof UsageIngestion>+ private readonly producerId: string+ private readonly maxBatchSize: number++ constructor(config: UsageIngestionClientConfig) {+ const scheme = config.useTls ? 'https' : 'http'+ this.client = createClient(+ UsageIngestion,+ createGrpcTransport({+ baseUrl: `${scheme}://${config.addr}`,+ defaultTimeoutMs: config.timeoutMs ?? 5_000,+ })+ )+ this.producerId = config.producerId+ this.maxBatchSize = config.maxBatchSize ?? 500+ }++ async ingest(records: UsageRecordInput[]): Promise<void> {+ if (records.length === 0) {+ return+ }+ const chunks: UsageRecordInput[][] = []+ for (let i = 0; i < records.length; i += this.maxBatchSize) {+ chunks.push(records.slice(i, i + this.maxBatchSize))+ }+ await Promise.all(chunks.map((chunk) => this.ingestChunk(chunk)))+ }++ private async ingestChunk(chunk: UsageRecordInput[], attempt = 0): Promise<void> {+ const request = create(IngestBillingUsageRequestSchema, {+ records: chunk.map((record) =>+ create(BillingUsageRecordSchema, {+ recordId: record.recordId,+ producerId: this.producerId,+ teamId: BigInt(record.teamId),+ usageKey: record.usageKey,+ unit: record.unit,+ quantity: BigInt(record.quantity),+ timestampMs: BigInt(record.timestampMs),+ })+ ),+ })++ try {+ await this.client.ingestBillingUsage(request)+ for (const record of chunk) {+ usageRecordsSentCounter.inc({ producer_id: this.producerId, usage_key: record.usageKey })+ }+ } catch (error) {+ const code = error instanceof ConnectError ? error.code : Code.Unknown+ if (attempt === 0 && RETRYABLE_CODES.has(code)) {+ await this.ingestChunk(chunk, attempt + 1)+ return+ }+ for (const record of chunk) {+ usageRecordsFailedCounter.inc({+ producer_id: this.producerId,+ usage_key: record.usageKey,+ error_code: Code[code] ?? 'unknown',+ })+ }+ logger.warn('⚠️', 'failed to ingest usage records', {+ producerId: this.producerId,+ records: chunk.length,+ error: String(error),+ })+ }+ }+}diff --git a/nodejs/src/common/usage-ingestion/index.ts b/nodejs/src/common/usage-ingestion/index.tsnew file mode 100644index 000000000000..67d3134e6c68--- /dev/null+++ b/nodejs/src/common/usage-ingestion/index.ts@@ -0,0 +1,43 @@+import { CommonConfig } from '~/common/config'+import { buildIntegerMatcher } from '~/common/config/config'+import { ValueMatcher } from '~/types'++import { UsageIngestionClient } from './client'++export type UsageIngestionConfig = Pick<+ CommonConfig,+ | 'USAGE_INGESTION_ADDR'+ | 'USAGE_INGESTION_TLS'+ | 'USAGE_INGESTION_TIMEOUT_MS'+ | 'USAGE_INGESTION_MAX_BATCH_SIZE'+ | 'USAGE_INGESTION_REPORT_TEAMS'+>++export type UsageReportSite = 'events' | 'ai_events' | 'exceptions' | 'cdp'++const PRODUCER_IDS = {+ events: 'ingestion',+ ai_events: 'ai-ingestion',+ exceptions: 'error-tracking',+ cdp: 'cdp',+} as const++export function usageReportTeamMatcher(config: UsageIngestionConfig): ValueMatcher<number> {+ return buildIntegerMatcher(config.USAGE_INGESTION_REPORT_TEAMS, true)+}++export function createUsageIngestionClient(+ config: UsageIngestionConfig,+ site: UsageReportSite+): UsageIngestionClient | null {+ if (!config.USAGE_INGESTION_ADDR || !config.USAGE_INGESTION_REPORT_TEAMS) {+ return null+ }+ return new UsageIngestionClient({+ addr: config.USAGE_INGESTION_ADDR,+ producerId: PRODUCER_IDS[site],+ useTls: config.USAGE_INGESTION_TLS,+ timeoutMs: config.USAGE_INGESTION_TIMEOUT_MS,+ maxBatchSize: config.USAGE_INGESTION_MAX_BATCH_SIZE,+ })+}diff --git a/nodejs/src/common/usage-ingestion/usage-record-batch.test.ts b/nodejs/src/common/usage-ingestion/usage-record-batch.test.tsnew file mode 100644index 000000000000..c5ee5313aee8--- /dev/null+++ b/nodejs/src/common/usage-ingestion/usage-record-batch.test.ts@@ -0,0 +1,124 @@+import { UsageIngestionClient, UsageRecordInput } from './client'+import { UsageRecordBatch } from './usage-record-batch'++describe('UsageRecordBatch', () => {+ let ingested: UsageRecordInput[][]+ let client: UsageIngestionClient++ beforeEach(() => {+ ingested = []+ client = {+ ingest: jest.fn((records: UsageRecordInput[]) => {+ ingested.push(records)+ return Promise.resolve()+ }),+ } as unknown as UsageIngestionClient+ })++ function batch(isTeamEnabled: (teamId: number) => boolean = () => true): UsageRecordBatch {+ return new UsageRecordBatch(client, { unit: 'invocations', isTeamEnabled })+ }++ it('bills a repeated identity once', async () => {+ const b = batch()+ b.add(1, 'cdp_billable_invocations', 'event:abc')+ b.add(1, 'cdp_billable_invocations', 'event:abc')+ await b.flush()++ expect(ingested[0]).toEqual([expect.objectContaining({ recordId: 'event:abc', quantity: 1 })])+ })++ it('keeps two teams that share a record ID apart', async () => {+ const b = batch()+ b.add(1, 'cdp_billable_invocations', 'event:abc')+ b.add(2, 'cdp_billable_invocations', 'event:abc')+ await b.flush()++ expect(ingested[0].map((r) => r.teamId).sort()).toEqual([1, 2])+ })++ it('keeps two usage keys apart for one team', async () => {+ const b = batch()+ b.add(1, 'events', 'uuid-1')+ b.add(1, 'ai_events', 'uuid-1')+ await b.flush()++ expect(ingested[0].map((r) => r.usageKey).sort()).toEqual(['ai_events', 'events'])+ })++ it('drops teams the matcher excludes', async () => {+ const b = batch((teamId) => teamId === 2)+ b.add(1, 'events', 'uuid-1')+ b.add(2, 'events', 'uuid-2')+ await b.flush()++ expect(ingested[0].map((r) => r.teamId)).toEqual([2])+ })++ it('does not send twice for one accumulation', async () => {+ const b = batch()+ b.add(1, 'events', 'uuid-1')+ await b.flush()+ await b.flush()++ expect(client.ingest).toHaveBeenCalledTimes(1)+ })++ /**+ * Queues one record, starts the send, then queues a second while the first is in flight.+ * Both acknowledgements are the test's to resolve, so neither case depends on timing.+ */+ async function sendWithALateAcknowledgement(send: (b: UsageRecordBatch) => Promise<void>): Promise<void> {+ const b = batch()+ let acknowledgeFirst!: (info: object) => void+ let acknowledgeSecond!: (info: object) => void+ const first = new Promise<object>((resolve) => (acknowledgeFirst = resolve))+ const second = new Promise<object>((resolve) => (acknowledgeSecond = resolve))++ b.addAfterAcknowledgements([first], 1, 'events', 'uuid-1')+ const sending = send(b)+ b.addAfterAcknowledgements([second], 1, 'events', 'uuid-2')+ acknowledgeFirst({})+ await new Promise((resolve) => setImmediate(resolve))+ acknowledgeSecond({})+ await sending+ }++ it('drains a record acknowledged while it is already sending', async () => {+ await sendWithALateAcknowledgement((b) => b.drain())++ expect(+ ingested+ .flat()+ .map((record) => record.recordId)+ .sort()+ ).toEqual(['uuid-1', 'uuid-2'])+ })++ it('leaves a record acknowledged mid-flush for the next flush', async () => {+ // One pass, so a caller that keeps adding cannot hold a flush open forever.+ await sendWithALateAcknowledgement((b) => b.flush())++ expect(ingested.flat().map((record) => record.recordId)).toEqual(['uuid-1'])+ })++ it('sends nothing when no client is configured', async () => {+ const b = new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => true })+ b.add(1, 'events', 'uuid-1')+ await b.flush()++ expect(client.ingest).not.toHaveBeenCalled()+ })++ it.each([+ ['no client', new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => true })],+ [+ 'an excluded team',+ new UsageRecordBatch({} as UsageIngestionClient, { unit: 'events', isTeamEnabled: () => false }),+ ],+ ])('flushes without waiting on acknowledgements for %s', async (_name, b) => {+ b.addAfterAcknowledgements([new Promise(() => {})], 1, 'events', 'uuid-1')++ await expect(b.flush()).resolves.toBeUndefined()+ })+})diff --git a/nodejs/src/common/usage-ingestion/usage-record-batch.ts b/nodejs/src/common/usage-ingestion/usage-record-batch.tsnew file mode 100644index 000000000000..bb8ecb6cea34--- /dev/null+++ b/nodejs/src/common/usage-ingestion/usage-record-batch.ts@@ -0,0 +1,122 @@+import { ValueMatcher } from '~/types'++import { UsageIngestionClient, UsageRecordInput } from './client'++export interface UsageRecordBatchConfig {+ unit: string+ isTeamEnabled: ValueMatcher<number>+}++interface PendingRecord {+ teamId: number+ usageKey: string+ recordId: string+}++/**+ * Collects one usage record per billed thing, identified by a record ID the+ * producer can reproduce. Every record carries quantity 1, so a second `add` of+ * the same identity is the same thing seen twice and is discarded rather than+ * added — the aggregate lives in ClickHouse, keyed the same way.+ *+ * Keyed by (team, usage key, record ID) to match the ingest contract's identity.+ * Keying on the record ID alone would merge two teams that share an ID and bill+ * both to the first one.+ */+export class UsageRecordBatch {+ private records = new Map<string, PendingRecord>()+ private pendingAcknowledgements: Promise<void>[] = []++ constructor(+ private readonly client: UsageIngestionClient | null,+ private readonly config: UsageRecordBatchConfig+ ) {}++ get size(): number {+ return this.records.size+ }++ /** Whether a record for this team would be kept, so a caller can skip building one. */+ accepts(teamId: number): boolean {+ return this.client !== null && this.config.isTeamEnabled(teamId)+ }++ add(teamId: number, usageKey: string, recordId: string): void {+ if (!this.accepts(teamId)) {+ return+ }+ const key = `${teamId}:${usageKey}:${recordId}`+ if (!this.records.has(key)) {+ this.records.set(key, { teamId, usageKey, recordId })+ }+ }++ /**+ * Adds a record only after every Kafka write for its logical event has+ * succeeded. The flush side effect waits for these acknowledgements, so it+ * is safe to schedule both production and usage reporting in the background.+ */+ addAfterAcknowledgements(+ acknowledgements: Promise<unknown | null>[],+ teamId: number,+ usageKey: string,+ recordId: string+ ): void {+ // A team that is not reporting must not put the flush behind its Kafka writes.+ if (!this.accepts(teamId)) {+ return+ }+ this.pendingAcknowledgements.push(+ Promise.all(acknowledgements)+ .then((results) => {+ if (results.every((result) => result !== null)) {+ this.add(teamId, usageKey, recordId)+ }+ })+ // Kafka errors are handled by the producer side effect. They must+ // not turn into a billing record or an unhandled rejection here.+ .catch(() => undefined)+ )+ }++ /**+ * Sends what is queued when the call starts. An acknowledgement that lands while this+ * awaits belongs to the next flush, so a caller that keeps adding stays bounded: one+ * pass, one send. A caller that is finished adding wants {@link drain} instead, because+ * nothing would flush that record afterwards.+ */+ async flush(): Promise<void> {+ const pending = this.pendingAcknowledgements+ this.pendingAcknowledgements = []+ await Promise.all(pending)+ if (!this.client || this.records.size === 0) {+ return+ }+ // Flush time, never anything off the event. toDate of this lands in the storage+ // sorting key, so a customer-supplied value would let a customer decide whether+ // their own records deduplicate.+ const timestampMs = Date.now()+ const records: UsageRecordInput[] = [...this.records.values()].map((record) => ({+ recordId: record.recordId,+ teamId: record.teamId,+ usageKey: record.usageKey,+ unit: this.config.unit,+ quantity: 1,+ timestampMs,+ }))+ this.records.clear()+ await this.client.ingest(records)+ }++ /**+ * Flushes until nothing is left queued. Only for a caller that has stopped adding: the+ * end of a batch, or a consumer shutting down. Records live in memory until they are+ * sent, so a batch that ends without draining bills nothing for the writes it was still+ * waiting on.+ */+ async drain(): Promise<void> {+ do {+ await this.flush()+ } while (this.pendingAcknowledgements.length > 0 || this.records.size > 0)+ }+}diff --git a/nodejs/src/ingestion/pipelines/ai/ai-event-types.ts b/nodejs/src/ingestion/common/ai-event-types.tssimilarity index 100%rename from nodejs/src/ingestion/pipelines/ai/ai-event-types.tsrename to nodejs/src/ingestion/common/ai-event-types.tsdiff --git a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.tsindex a402c94c2712..03f1164fc84b 100644--- a/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/create-event-step.ts@@ -1,8 +1,10 @@import { Message } from 'node-rdkafka'import { parse as parseUuid, v5 as uuidv5 } from 'uuid'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { parseTeamsList } from '~/common/utils/env-utils'import { createEvent } from '~/ingestion/common/steps/event-processing/create-event'+import { EventUsageRecord } from '~/ingestion/common/steps/usage-records-steps'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { EventHeaders, Person, PreIngestionEvent } from '~/types'@@ -38,6 +40,8 @@ export interface CreateEventStepInput {historicalMigration: booleanheaders: EventHeadersmessage: Message+ eventUsageRecord?: EventUsageRecord+ eventUsageBatch?: UsageRecordBatch}export interface CreateEventStepResult<O extends string> {@@ -45,6 +49,8 @@ export interface CreateEventStepResult<O extends string> {teamId: numberheaders: EventHeadersmessage: Message+ eventUsageRecord?: EventUsageRecord+ eventUsageBatch?: UsageRecordBatch}export function createCreateEventStep<O extends string, T extends CreateEventStepInput>(@@ -54,7 +60,16 @@ export function createCreateEventStep<O extends string, T extends CreateEventSteconst exposureDuplicationTeams = parseTeamsList(experimentExposureDuplicationTeams)return function createEventStep(input) {- const { person, preparedEvent, processPerson, historicalMigration, headers, message } = input+ const {+ person,+ preparedEvent,+ processPerson,+ historicalMigration,+ headers,+ message,+ eventUsageRecord,+ eventUsageBatch,+ } = inputconst capturedAt = headers.now ?? nullconst rawEvent = createEvent(preparedEvent, person, processPerson, historicalMigration, capturedAt)@@ -84,6 +99,8 @@ export function createCreateEventStep<O extends string, T extends CreateEventSteteamId: preparedEvent.teamId,headers,message,+ eventUsageRecord,+ eventUsageBatch,}return Promise.resolve(ok(result, []))diff --git a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.tsindex c2364e31512e..7011986ba8cb 100644--- a/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/emit-event-step.ts@@ -3,11 +3,13 @@ import { Message } from 'node-rdkafka'import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { MessageSizeTooLarge } from '~/common/utils/db/error'import { safeClickhouseString } from '~/common/utils/db/utils'import { castTimestampOrNow, castTimestampToClickhouseFormat } from '~/common/utils/utils'import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'import { eventProcessedAndIngestedCounter } from '~/ingestion/common/metrics'+import { EventUsageRecord } from '~/ingestion/common/steps/usage-records-steps'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'import { EventHeaders, ProcessedEvent, RawKafkaEvent, TimestampFormat } from '~/types'@@ -26,6 +28,8 @@ export interface EmitEventStepInput<O extends string> {teamId: numberheaders: EventHeadersmessage: Message+ eventUsageRecord?: EventUsageRecord+ eventUsageBatch?: UsageRecordBatch}/**@@ -50,6 +54,8 @@ export interface EmitEventStepOutput {* been ingested. Empty when nothing was emitted.*/ingested: Promise<IngestedEventInfo | null>[]+ eventUsageRecord?: EventUsageRecord+ eventUsageBatch?: UsageRecordBatch}export function createEmitEventStep<O extends string, T extends EmitEventStepInput<O>>(@@ -109,7 +115,16 @@ export function createEmitEventStep<O extends string, T extends EmitEventStepInpingested.push(emitPromise)}- return Promise.resolve(ok({ ingested }, ingested))+ return Promise.resolve(+ ok(+ {+ ingested,+ eventUsageRecord: input.eventUsageRecord,+ eventUsageBatch: input.eventUsageBatch,+ },+ ingested+ )+ )}}diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.test.tsnew file mode 100644index 000000000000..b2bdc281051f--- /dev/null+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.test.ts@@ -0,0 +1,134 @@+import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'+import { isOkResult } from '~/ingestion/framework/results'++import { createRecordEventUsageAfterIngestStep, createRecordEventUsageStep } from './usage-records-steps'++describe('usage-records-steps', () => {+ const FLUSH_TIMESTAMP_MS = 1_700_000_000_000++ let ingestedUsage: UsageRecordInput[]+ let eventUsageBatch: UsageRecordBatch++ beforeEach(() => {+ jest.useFakeTimers()+ jest.setSystemTime(FLUSH_TIMESTAMP_MS)+ ingestedUsage = []+ const usageClient = {+ ingest: jest.fn((records: UsageRecordInput[]) => {+ ingestedUsage.push(...records)+ return Promise.resolve()+ }),+ } as unknown as UsageIngestionClient+ eventUsageBatch = new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: () => true })+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ async function queueEventUsage(+ ingested: Promise<IngestedEventInfo | null>[],+ event: Partial<{ event: string; eventUuid: string; distinctId: string }> = {}+ ): Promise<void> {+ const prepare = createRecordEventUsageStep(() => 'events')+ const prepared = await prepare({+ preparedEvent: {+ teamId: 42,+ event: '$pageview',+ eventUuid: 'event-uuid',+ distinctId: 'user-7',+ timestamp: '2026-06-15T23:55:00.000Z',+ ...event,+ },+ eventUsageBatch,+ })+ expect(isOkResult(prepared)).toBe(true)+ if (!isOkResult(prepared)) {+ throw new Error('expected usage preparation to succeed')+ }++ const recordAfterIngest = createRecordEventUsageAfterIngestStep()+ await recordAfterIngest({ ...prepared.value, ingested })+ }++ it.each([+ [+ 'Kafka rejects the write',+ (): Promise<IngestedEventInfo | null> => Promise.reject(new Error('Kafka unavailable')),+ ],+ ['Kafka declines the event', (): Promise<IngestedEventInfo | null> => Promise.resolve(null)],+ ])('does not report usage when %s', async (_name, acknowledgement) => {+ await queueEventUsage([acknowledgement()])++ await eventUsageBatch.flush()++ expect(ingestedUsage).toEqual([])+ })++ it.each([+ ['ordinary values', {}],+ [+ 'the longest event name and distinct ID a client can send',+ { event: 'e'.repeat(200), distinctId: 'd'.repeat(400) },+ ],+ ])('keeps the record ID inside the service identifier limit with %s', async (_name, event) => {+ await queueEventUsage([Promise.resolve({ topic: 'events', partition: 0 })], event)++ await eventUsageBatch.flush()++ expect(ingestedUsage[0].recordId).toMatch(/^2026-06-15:[0-9a-f]{32}$/)+ })++ it.each([+ ['distinct ID', { distinctId: 'user-8' }],+ ['event name', { event: '$autocapture' }],+ ['UUID', { eventUuid: 'other-uuid' }],+ ])('bills two events that differ only in %s separately', async (_name, event) => {+ const acknowledged = (): Promise<IngestedEventInfo> => Promise.resolve({ topic: 'events', partition: 0 })+ await queueEventUsage([acknowledged()])+ await queueEventUsage([acknowledged()], event)++ await eventUsageBatch.flush()++ expect(new Set(ingestedUsage.map((record) => record.recordId)).size).toBe(2)+ })++ it('bills two events apart when only the position of a newline differs', async () => {+ const acknowledged = (): Promise<IngestedEventInfo> => Promise.resolve({ topic: 'events', partition: 0 })+ await queueEventUsage([acknowledged()], { event: 'a\nb', distinctId: 'c' })+ await queueEventUsage([acknowledged()], { event: 'a', distinctId: 'b\nc' })++ await eventUsageBatch.flush()++ expect(new Set(ingestedUsage.map((record) => record.recordId)).size).toBe(2)+ })++ it('reports the event usage payload only after Kafka acknowledges the write', async () => {+ let acknowledgeKafka!: (info: IngestedEventInfo) => void+ const kafkaAcknowledgement = new Promise<IngestedEventInfo>((resolve) => {+ acknowledgeKafka = resolve+ })++ await queueEventUsage([kafkaAcknowledgement])+ const flush = eventUsageBatch.flush()+ await expect(Promise.resolve()).resolves.toBeUndefined()+ expect(ingestedUsage).toEqual([])++ acknowledgeKafka({ topic: 'events', partition: 0 })+ await flush++ expect(ingestedUsage).toEqual([+ {+ recordId: expect.stringMatching(/^2026-06-15:[0-9a-f]{32}$/),+ teamId: 42,+ usageKey: 'events',+ unit: 'events',+ quantity: 1,+ timestampMs: FLUSH_TIMESTAMP_MS,+ dimensions: undefined,+ },+ ])+ })+})diff --git a/nodejs/src/ingestion/common/steps/usage-records-steps.ts b/nodejs/src/ingestion/common/steps/usage-records-steps.tsnew file mode 100644index 000000000000..5f9923cfdd3c--- /dev/null+++ b/nodejs/src/ingestion/common/steps/usage-records-steps.ts@@ -0,0 +1,120 @@+import { createHash } from 'node:crypto'++import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'+import { IngestedEventInfo } from '~/ingestion/common/steps/event-processing/emit-event-step'+import { UsageKeyResolver } from '~/ingestion/common/usage-records/billable-events'+import { BeforeBatchStep } from '~/ingestion/framework/batching-pipeline'+import { PipelineResult, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++export interface EventUsageBatchContext {+ eventUsageBatch: UsageRecordBatch+}++export function createEventUsageBeforeBatchStep<TInput, CInput, CBatch>(+ createBatch: () => UsageRecordBatch+): BeforeBatchStep<TInput, CInput, CBatch, CBatch & EventUsageBatchContext> {+ return function eventUsageBeforeBatchStep(input) {+ return Promise.resolve(+ ok({+ elements: input.elements,+ batchContext: { ...input.batchContext, eventUsageBatch: createBatch() },+ })+ )+ }+}++export interface RecordEventUsageInput {+ preparedEvent: { teamId: number; event: string; eventUuid: string; distinctId: string; timestamp: string }+ eventUsageBatch: UsageRecordBatch+}++/**+ * Mirrors the events table's dedup identity, `(team_id, toDate(timestamp), event,+ * distinct_id, uuid)`, minus the team the billing sorting key already carries. The UUID alone+ * is not that identity: two events sharing one but differing in day, name or distinct_id are+ * separate rows there, and the nightly report counts them separately, so billing must too.+ *+ * Hashed rather than joined, because event names and distinct IDs are client-supplied and+ * together exceed the 512-byte identifier the service accepts. One oversized record makes the+ * service reject the whole request, which would drop every record batched with it.+ *+ * The timestamp is UTC-normalized upstream, so its first ten characters are the same day+ * `toDate` resolves.+ */+function analyticsRecordId(preparedEvent: RecordEventUsageInput['preparedEvent']): string {+ const day = preparedEvent.timestamp.slice(0, 10)+ // JSON rather than a separator: an event name and a distinct ID can both contain any+ // character, so `a\nb` with `c` and `a` with `b\nc` would hash the same and bill once.+ const identity = JSON.stringify([preparedEvent.event, preparedEvent.distinctId, preparedEvent.eventUuid])+ return `${day}:${createHash('sha256').update(identity).digest('hex').slice(0, 32)}`+}++export interface EventUsageRecord {+ teamId: number+ usageKey: string+ recordId: string+}++export interface EventUsageRecordContext {+ eventUsageRecord?: EventUsageRecord+}++/**+ * One record per event. Its identity travels inside the event, so a replay reproduces it+ * whatever the consumer's batching, which an offset-derived identity cannot.+ *+ * TODO: decide how usage records should treat events dated in the past. This step bills every+ * billable event at the moment it is processed, including a historical migration. The nightly+ * report does not: `get_teams_with_billable_event_count_in_period` filters the events table on+ * the event's own `timestamp`, so an event backdated outside the current period lands in a+ * period that has already been billed and is charged for nowhere. The two systems therefore+ * disagree on exactly the imports customers run deliberately, and the choice — bill regardless+ * of event age, or mirror the report and skip old events — is a pricing decision rather than an+ * implementation one. `historicalMigration` is available upstream in the pipeline if we pick+ * the second.+ */+export function createRecordEventUsageStep<T extends RecordEventUsageInput>(+ resolveUsageKey: UsageKeyResolver+): ProcessingStep<T, T & EventUsageRecordContext> {+ return function recordEventUsageStep(input: T): Promise<PipelineResult<T & EventUsageRecordContext>> {+ const usageKey = input.eventUsageBatch.accepts(input.preparedEvent.teamId)+ ? resolveUsageKey(input.preparedEvent.event)+ : undefined+ const eventUsageRecord = usageKey+ ? { teamId: input.preparedEvent.teamId, usageKey, recordId: analyticsRecordId(input.preparedEvent) }+ : undefined+ return Promise.resolve(ok({ ...input, eventUsageRecord }))+ }+}++export interface RecordEventUsageAfterIngestInput extends EventUsageRecordContext {+ eventUsageBatch?: UsageRecordBatch+ ingested: Promise<IngestedEventInfo | null>[]+}++/** Queues billing only once every Kafka write for the logical event has been acknowledged. */+export function createRecordEventUsageAfterIngestStep<T extends RecordEventUsageAfterIngestInput>(): ProcessingStep<+ T,+ T+> {+ return function recordEventUsageAfterIngestStep(input: T): Promise<PipelineResult<T>> {+ const record = input.eventUsageRecord+ if (record && input.eventUsageBatch) {+ input.eventUsageBatch.addAfterAcknowledgements(+ input.ingested,+ record.teamId,+ record.usageKey,+ record.recordId+ )+ }+ return Promise.resolve(ok(input))+ }+}++/** Ends the batch's usage reporting: the batch object goes away after this, so it drains. */+export function createFlushEventUsageStep<T extends { batchContext: EventUsageBatchContext }>(): ProcessingStep<T, T> {+ return function flushEventUsageStep(input: T): Promise<PipelineResult<T>> {+ return Promise.resolve(ok(input, [input.batchContext.eventUsageBatch.drain()]))+ }+}diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.test.ts b/nodejs/src/ingestion/common/usage-records/billable-events.test.tsnew file mode 100644index 000000000000..2e275a5d787b--- /dev/null+++ b/nodejs/src/ingestion/common/usage-records/billable-events.test.ts@@ -0,0 +1,25 @@+import { AI_EVENTS_USAGE_KEY, EVENTS_USAGE_KEY, resolveAiUsageKey, resolveAnalyticsUsageKey } from './billable-events'++describe('usage key resolvers', () => {+ it.each([+ ['$pageview', EVENTS_USAGE_KEY],+ ['custom event', EVENTS_USAGE_KEY],+ ['$ai_generation', AI_EVENTS_USAGE_KEY],+ ['$ai_trace', AI_EVENTS_USAGE_KEY],+ // Not a known AI event name, so it bills as a standard event — matching the nightly report,+ // which excludes the exact AIEventType values rather than everything prefixed `$ai_`.+ ['$ai_not_a_real_event', EVENTS_USAGE_KEY],+ ['$feature_flag_called', null],+ ['$experiment_exposure', null],+ ['survey sent', null],+ ['$exception', null],+ ['$conversations_message_sent', null],+ ])('resolveAnalyticsUsageKey bills %s under %s', (event, expected) => {+ expect(resolveAnalyticsUsageKey(event)).toBe(expected)+ })++ it('bills everything on the ai lane under the ai key', () => {+ expect(resolveAiUsageKey('$ai_generation')).toBe(AI_EVENTS_USAGE_KEY)+ expect(resolveAiUsageKey('$ai_not_a_real_event')).toBe(AI_EVENTS_USAGE_KEY)+ })+})diff --git a/nodejs/src/ingestion/common/usage-records/billable-events.ts b/nodejs/src/ingestion/common/usage-records/billable-events.tsnew file mode 100644index 000000000000..8a97faf7b2db--- /dev/null+++ b/nodejs/src/ingestion/common/usage-records/billable-events.ts@@ -0,0 +1,43 @@+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'++export const EVENTS_USAGE_KEY = 'events'+export const AI_EVENTS_USAGE_KEY = 'ai_events'+export const EXCEPTIONS_USAGE_KEY = 'exceptions'++/** Null means the event is not billed at all. */+export type UsageKeyResolver = (event: string) => string | null++// Mirrors BILLABLE_EVENT_EXCLUDED_EVENTS in posthog/tasks/usage_report.py, minus the AI events,+// which are billed under their own key rather than excluded. The two lists have to agree or the+// usage records and the org usage report bill the same team differently.+const NON_BILLABLE_EVENTS = new Set([+ '$feature_flag_called',+ '$experiment_exposure',+ 'survey sent',+ 'survey shown',+ 'survey dismissed',+ '$exception',+ '$conversations_loaded',+ '$conversations_widget_loaded',+ '$conversations_message_sent',+ '$conversations_user_identified',+ '$conversations_restore_link_requested',+ '$conversations_widget_state_changed',+ '$conversations_back_to_tickets',+])++/**+ * Bills each event under the key its own product owns, wherever the event turns up.+ * Matching the exact AI event names rather than the `$ai_` prefix keeps an unknown+ * `$ai_*` event billable as a standard event, which is what the nightly report does.+ */+export const resolveAnalyticsUsageKey: UsageKeyResolver = (event) => {+ if (AI_EVENT_TYPES.has(event)) {+ return AI_EVENTS_USAGE_KEY+ }+ return NON_BILLABLE_EVENTS.has(event) ? null : EVENTS_USAGE_KEY+}++export const resolveAiUsageKey: UsageKeyResolver = () => AI_EVENTS_USAGE_KEY++export const resolveExceptionUsageKey: UsageKeyResolver = () => EXCEPTIONS_USAGE_KEYdiff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex eb094ace2d81..d5d46309d6e6 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -25,6 +25,8 @@ import {import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PersonRepository } from '~/common/persons/repositories/person-repository'import { instrumentFn } from '~/common/tracing/tracing-utils'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { PostgresRouter } from '~/common/utils/db/postgres'import {EventIngestionRestrictionManager,@@ -64,6 +66,7 @@ import { createAnalyticsOverflowStrategies } from './common/overflow-redirect/ovimport { IngestionConsumerConfig, IngestionOutputsConfig } from './config'export type IngestionConsumerFullConfig = IngestionConsumerConfig &+ UsageIngestionConfig &Pick<CommonConfig, 'KAFKA_CLIENT_RACK'> &// The general server builds the consumer from a config that includes IngestionOutputsConfig; the// merge-events gate reads the topic, so surface it here rather than relying on the runtime shape.@@ -298,6 +301,7 @@ export class IngestionConsumer {EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS: this.config.EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS,},concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,+ createEventUsageBatch: this.createEventUsageBatch(),}const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore: this.personsStore,@@ -382,6 +386,12 @@ export class IngestionConsumer {return new HealthCheckResultOk()}+ private createEventUsageBatch(): () => UsageRecordBatch {+ const client = createUsageIngestionClient(this.config, 'events')+ const isTeamEnabled = usageReportTeamMatcher(this.config)+ return () => new UsageRecordBatch(client, { unit: 'events', isTeamEnabled })+ }+private runInstrumented<T>(name: string, func: () => Promise<T>): Promise<T> {return instrumentFn<T>(`ingestionConsumer.${name}`, func)}diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts b/nodejs/src/ingestion/pipelines/ai/consumer.test.tsindex 6db274fd6ebc..72b34ace1546 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.test.ts@@ -30,6 +30,11 @@ describe('createAiConsumer', () => {SKIP_PERSONS_PROCESSING_BY_TOKEN_DISTINCT_ID: '',INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',EVENT_SCHEMA_ENFORCEMENT_ENABLED: false,+ USAGE_INGESTION_ADDR: '',+ USAGE_INGESTION_TLS: false,+ USAGE_INGESTION_TIMEOUT_MS: 5000,+ USAGE_INGESTION_MAX_BATCH_SIZE: 500,+ USAGE_INGESTION_REPORT_TEAMS: '',// Read eagerly by createAiConsumer (not deferred like the scope-builder services// below), so these need real fail-closed values rather than the cast-away pattern.AI_BLOB_S3_BUCKET: '',diff --git a/nodejs/src/ingestion/pipelines/ai/consumer.ts b/nodejs/src/ingestion/pipelines/ai/consumer.tsindex 28b2e6759b67..9b118fa67399 100644--- a/nodejs/src/ingestion/pipelines/ai/consumer.ts+++ b/nodejs/src/ingestion/pipelines/ai/consumer.ts@@ -16,6 +16,8 @@ import { PersonHogConfig } from '~/common/personhog'import { PersonHogClientComponent } from '~/common/personhog/personhog-client-component'import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { PostgresRouter } from '~/common/utils/db/postgres'import { EventIngestionRestrictionManagerComponent } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'@@ -41,6 +43,7 @@ import { createAiIngestionPipeline } from './pipeline'export type AiConsumerConfig = CommonIngestionConsumerConfig &IngestionOutputsConfig &PersonHogConfig &+ UsageIngestionConfig &Pick<IngestionConsumerConfig,| 'INGESTION_OVERFLOW_MODE'@@ -168,6 +171,9 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiShared`AI_BLOB_OFFLOAD_UPLOAD_MAX_CONCURRENCY must be a positive integer, got ${uploadMaxConcurrency}`)}+ const usageClient = createUsageIngestionClient(config, 'ai_events')+ const usageTeamMatcher = usageReportTeamMatcher(config)+const aiBlobOffloadConfig = {isTeamEnabled: buildIntegerMatcher(config.AI_BLOB_OFFLOAD_TEAMS, true),minBase64Length: config.AI_BLOB_OFFLOAD_MIN_BASE64_LENGTH,@@ -203,6 +209,8 @@ export function createAiConsumer(config: AiConsumerConfig, sharedScope: AiSharedtopHog: container.topHog,aiBlobStore: container.aiBlobStore.store,aiBlobOffloadConfig,+ createEventUsageBatch: () =>+ new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: usageTeamMatcher }),}))}diff --git a/nodejs/src/ingestion/pipelines/ai/index.ts b/nodejs/src/ingestion/pipelines/ai/index.tsindex faa27891620a..3231b188393d 100644--- a/nodejs/src/ingestion/pipelines/ai/index.ts+++ b/nodejs/src/ingestion/pipelines/ai/index.ts@@ -1,4 +1,4 @@export { normalizeTraceProperties, processAiEvent, type EventWithProperties } from './process-ai-event'-export { AI_EVENT_TYPES } from './ai-event-types'+export { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'export { createAiIngestionPipeline, type AiIngestionPipelineConfig } from './pipeline'export { createAiConsumer, type AiConsumerConfig, type AiSharedScope } from './consumer'diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.test.tsindex 384c3c4f764a..5a38f0af8278 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.test.ts@@ -7,6 +7,8 @@ import { APP_METRICS_OUTPUT, DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTimport { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { SingleIngestionOutput } from '~/common/outputs/single-ingestion-output'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'+import { UsageIngestionClient, UsageRecordInput } from '~/common/usage-ingestion/client'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'import { parseJSON } from '~/common/utils/json-parse'@@ -43,6 +45,7 @@ describe('AiIngestionPipeline', () => {let mockPersonRepository: jest.Mocked<PersonReadRepository>let mockGroupTypeManager: jest.Mocked<ReadOnlyGroupTypeManager>let promiseScheduler: PromiseScheduler+ let ingestedUsage: UsageRecordInput[]let config: AiIngestionPipelineConfigconst team = createTestTeam({ id: 123, api_token: 'token-123' })@@ -139,6 +142,14 @@ describe('AiIngestionPipeline', () => {promiseScheduler = new PromiseScheduler()+ ingestedUsage = []+ const usageClient = {+ ingest: jest.fn((records: UsageRecordInput[]) => {+ ingestedUsage.push(...records)+ return Promise.resolve()+ }),+ } as unknown as UsageIngestionClient+const single = (output: string, topic: string) =>new SingleIngestionOutput(output, topic, mockKafkaProducer, 'test')@@ -174,9 +185,23 @@ describe('AiIngestionPipeline', () => {maxBlobsPerEvent: 50,uploadMaxConcurrency: 8,},+ createEventUsageBatch: () =>+ new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: () => true }),}})+ it('reports one ai_events usage record per event', async () => {+ await runPipeline([createMessage('$ai_generation'), createMessage('$ai_span')])++ expect(ingestedUsage).toHaveLength(2)+ // What the identity is made of belongs to usage-records-steps.test.ts. Here it only has to+ // be one record per event, on the event's own day.+ expect(new Set(ingestedUsage.map((r) => r.recordId)).size).toBe(2)+ expect(ingestedUsage.every((r) => /^2024-01-01:[0-9a-f]{32}$/.test(r.recordId))).toBe(true)+ expect(ingestedUsage.every((r) => r.usageKey === 'ai_events' && r.quantity === 1)).toBe(true)+ expect(ingestedUsage.every((r) => r.teamId === team.id)).toBe(true)+ })+it('double-writes AI events to both the events and ai_events outputs', async () => {await runPipeline([createMessage('$ai_generation')])diff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.tsindex 68145245e781..36268299a347 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts@@ -5,10 +5,12 @@ import { HogTransformer } from '~/common/hog-transformations/hog-transformer.intimport { AppMetricsOutput, DlqOutput, IngestionWarningsOutput, OverflowOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { TeamManager } from '~/common/utils/team-manager'+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { newCommonIngestionPipeline } from '~/ingestion/common/common-ingestion-pipeline'import { CookielessManager } from '~/ingestion/common/cookieless/cookieless-manager'import { EventFilterManager } from '~/ingestion/common/event-filters'@@ -43,11 +45,17 @@ import { createPrepareEventStep } from '~/ingestion/common/steps/event-processinimport { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'import { createStripPersonUpdatePropertiesStep } from '~/ingestion/common/steps/event-processing/strip-person-update-properties-step'import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'+import {+ createEventUsageBeforeBatchStep,+ createFlushEventUsageStep,+ createRecordEventUsageAfterIngestStep,+ createRecordEventUsageStep,+} from '~/ingestion/common/steps/usage-records-steps'+import { resolveAiUsageKey } from '~/ingestion/common/usage-records/billable-events'import { IngestionOverflowMode } from '~/ingestion/config'import { TopHogRegistry, sum, sumOk, sumResult } from '~/ingestion/framework/extensions/tophog'import { isDropResult } from '~/ingestion/framework/results'-import { AI_EVENT_TYPES } from './ai-event-types'import { BlobStore } from './blob-offload/blob-store'import { AiEventOutput, EVENTS_OUTPUT, EventOutput } from './outputs'import {@@ -84,6 +92,7 @@ export interface AiIngestionPipelineConfig {topHog: TopHogRegistryaiBlobStore: BlobStore | nullaiBlobOffloadConfig: OffloadAiBlobsConfig+ createEventUsageBatch?: () => UsageRecordBatch}interface AiIngestionPipelineInput {@@ -131,6 +140,7 @@ export function createAiIngestionPipeline<topHog,aiBlobStore,aiBlobOffloadConfig,+ createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),} = configreturn (@@ -141,7 +151,11 @@ export function createAiIngestionPipeline<concurrentBatches,topHog,})- .beforeBatch((b) => b.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs)))+ .beforeBatch((b) =>+ b+ .pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs))+ .pipe(createEventUsageBeforeBatchStep(createEventUsageBatch))+ )// Header-only steps: allow only AI events, apply token restrictions..parseHeaders().pipe(createAllowEventsStep([...AI_EVENT_TYPES]))@@ -244,6 +258,7 @@ export function createAiIngestionPipeline<.pipe(createReadOnlyProcessGroupsStep(groupTypeManager), {retry: { tries: 5, sleepMs: 100, name: 'readonly_process_groups' },})+ .pipe(createRecordEventUsageStep(resolveAiUsageKey)).pipe(createCreateEventStep(EVENTS_OUTPUT))// Double-write to events + ai_events outputs..pipe(createSplitAiEventsStep())@@ -265,10 +280,12 @@ export function createAiIngestionPipeline<),],})+ .pipe(createRecordEventUsageAfterIngestStep()).pipe(createRecordIngestionLagStep()).afterBatch((b) =>b.pipe(createFlushEventFiltersBatchAppMetricsStep())+ .pipe(createFlushEventUsageStep())// Drain hog transformer invocation results once per batch..pipe(createFlushHogTransformerStep(hogTransformer)))diff --git a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts b/nodejs/src/ingestion/pipelines/ai/process-ai-event.tsindex c1bfe78a4228..1bc84aca4261 100644--- a/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts+++ b/nodejs/src/ingestion/pipelines/ai/process-ai-event.ts@@ -8,7 +8,7 @@* - Model parameter extraction (for generation/embedding/evaluation events)*/import { logger } from '~/common/utils/logger'-import { AI_EVENT_TYPES } from '~/ingestion/pipelines/ai/ai-event-types'+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { PluginEvent } from '~/plugin-scaffold'import { convertRawEvent } from './convert-raw-event'diff --git a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.tsindex a868cf2f3de2..28fa3a1df121 100644--- a/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts+++ b/nodejs/src/ingestion/pipelines/ai/steps/process-ai-event-step.ts@@ -1,8 +1,8 @@import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { dlq, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { AI_EVENT_TYPES } from '~/ingestion/pipelines/ai/ai-event-types'import { processAiEvent } from '~/ingestion/pipelines/ai/process-ai-event'import { PluginEvent } from '~/plugin-scaffold'diff --git a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.tsindex 0d2b4f092c5a..976fbb5c7667 100644--- a/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts+++ b/nodejs/src/ingestion/pipelines/ai/steps/split-ai-events-step.ts@@ -1,8 +1,8 @@import { AI_EVENTS_OUTPUT, AiEventOutput, EventOutput } from '~/common/outputs'+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { EventToEmit } from '~/ingestion/common/steps/event-processing/emit-event-step'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { AI_EVENT_TYPES } from '~/ingestion/pipelines/ai/ai-event-types'import { LARGE_AI_PROPERTIES } from '~/ingestion/pipelines/ai/large-ai-properties'import { ProcessedEvent } from '~/types'diff --git a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.tsindex 34e66890beef..eb2593136319 100644--- a/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts+++ b/nodejs/src/ingestion/pipelines/ai/steps/validate-ai-event-tokens.ts@@ -1,7 +1,7 @@+import { AI_EVENT_TYPES } from '~/ingestion/common/ai-event-types'import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { AI_EVENT_TYPES } from '~/ingestion/pipelines/ai/ai-event-types'import { PipelineEvent } from '~/types'const TOKEN_PROPERTIES = [diff --git a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.tsindex 55ae7fb274e5..97b2afd1bc0c 100644--- a/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/event-subpipeline.ts@@ -4,6 +4,7 @@ import { GroupTypeManager } from '~/common/groups/group-type-manager'import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { TeamManager } from '~/common/utils/team-manager'import { GroupStoreForBatch } from '~/ingestion/common/groups/group-store-for-batch'import { WithMergeFoldDecision } from '~/ingestion/common/persons/person-merge-fold'@@ -19,6 +20,11 @@ import { createProcessGroupsStep } from '~/ingestion/common/steps/event-processiimport { createProcessPersonlessStep } from '~/ingestion/common/steps/event-processing/process-personless-step'import { createProcessPersonsStep } from '~/ingestion/common/steps/event-processing/process-persons-step'import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'+import {+ createRecordEventUsageAfterIngestStep,+ createRecordEventUsageStep,+} from '~/ingestion/common/steps/usage-records-steps'+import { resolveAnalyticsUsageKey } from '~/ingestion/common/usage-records/billable-events'import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'import { TopHogWrapper, sum, sumOk, sumResult, timer } from '~/ingestion/framework/extensions/tophog'import { isDropResult } from '~/ingestion/framework/results'@@ -52,6 +58,7 @@ export interface EventSubpipelineInput {headers: EventHeaderspersonsStoreForBatch: PersonsStoreForBatchgroupStoreForBatch: GroupStoreForBatch+ eventUsageBatch: UsageRecordBatch}export interface EventSubpipelineConfig {@@ -150,6 +157,7 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi]),{ retry: { tries: 5, sleepMs: 100, name: 'process_groups' } })+ .pipe(createRecordEventUsageStep(resolveAnalyticsUsageKey)).pipe(createCreateEventStep(EVENTS_OUTPUT, options.EXPERIMENT_EXPOSURE_DUPLICATION_TEAMS)).pipe(topHog(@@ -183,5 +191,6 @@ export function createEventSubpipeline<TInput extends EventSubpipelineInput & Wi),{ retry: { tries: 5, sleepMs: 100, name: 'emit_event' } })+ .pipe(createRecordEventUsageAfterIngestStep()).pipe(createRecordIngestionLagStep())}diff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex 9d61debf191c..54c167b34188 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -4,6 +4,7 @@ import { GroupTypeManager } from '~/common/groups/group-type-manager'import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'import { AppMetricsOutput, DlqOutput, GroupsOutput, IngestionWarningsOutput, OverflowOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'import { EventSchemaEnforcementManager } from '~/common/utils/event-schema-enforcement-manager'import { PromiseScheduler } from '~/common/utils/promise-scheduler'@@ -32,6 +33,10 @@ import { createFlushBatchStoresStep } from '~/ingestion/common/steps/event-proceimport { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'import { createGroupStoreBeforeBatchStep } from '~/ingestion/common/steps/group-store-batch-step'import { createPersonsStoreBeforeBatchStep } from '~/ingestion/common/steps/persons-store-batch-step'+import {+ createEventUsageBeforeBatchStep,+ createFlushEventUsageStep,+} from '~/ingestion/common/steps/usage-records-steps'import { IngestionOverflowMode } from '~/ingestion/config'import { TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'@@ -69,6 +74,7 @@ export interface JoinedIngestionPipelineConfig {* (`ingestion_api_batch_capacity_rejections_total`).*/concurrentBatches: number+ createEventUsageBatch?: () => UsageRecordBatch}export interface JoinedIngestionPipelineDeps {@@ -116,6 +122,7 @@ export function createJoinedIngestionPipeline<outputs,perDistinctIdOptions,concurrentBatches,+ createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),} = configconst {@@ -180,6 +187,7 @@ export function createJoinedIngestionPipeline<.beforeBatch((beforeBatch) =>beforeBatch.pipe(createEventFiltersBatchAppMetricsBeforeBatchStep(outputs))+ .pipe(createEventUsageBeforeBatchStep(createEventUsageBatch)).pipe(createPersonsStoreBeforeBatchStep(personsStore)).pipe(createGroupStoreBeforeBatchStep(groupStore)))@@ -218,6 +226,7 @@ export function createJoinedIngestionPipeline<afterBatch.pipe(createFlushBatchStoresStep({ personsStore, groupStore, outputs })).pipe(createFlushEventFiltersBatchAppMetricsStep())+ .pipe(createFlushEventUsageStep()).pipe(createFlushHogTransformerStep(hogTransformer))).build<CFeed>()diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.tsindex 6a9774286bf6..24e5acd26dc9 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts@@ -8,6 +8,7 @@ import { HogTransformationResult } from '~/common/hog-transformations/hog-transfimport { KafkaConsumerInterface, createKafkaConsumer } from '~/common/kafka/consumer'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'import { instrumentFn } from '~/common/tracing/tracing-utils'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import {EventIngestionRestrictionManager,EventIngestionRestrictionManagerComponent,@@ -83,6 +84,7 @@ export interface ErrorTrackingConsumerDeps {cookielessManager: CookielessManagerredisPool: GenericPool<Redis>personRepository: PersonReadRepository+ createEventUsageBatch?: () => UsageRecordBatch}// Batch processing status - useful for tracking failures (batch sizes already tracked by KafkaConsumer)@@ -224,6 +226,7 @@ export class ErrorTrackingConsumer {overflowRedirectService: this.overflowRedirectService,overflowLaneTTLRefreshService: this.overflowLaneTTLRefreshService,topHog: this.topHog,+ createEventUsageBatch: this.deps.createEventUsageBatch,})logger.info('✅', `${this.name} - pipeline initialized`)diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex c8408762d24f..8f90f7c7eb17 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -12,6 +12,7 @@ import {} from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PersonReadRepository } from '~/common/persons/repositories/person-repository'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'import { PromiseScheduler } from '~/common/utils/promise-scheduler'import { TeamManager } from '~/common/utils/team-manager'@@ -31,6 +32,14 @@ import { createFetchPersonChunkStep } from '~/ingestion/common/steps/event-proceimport { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'+import {+ EventUsageBatchContext,+ createEventUsageBeforeBatchStep,+ createFlushEventUsageStep,+ createRecordEventUsageAfterIngestStep,+ createRecordEventUsageStep,+} from '~/ingestion/common/steps/usage-records-steps'+import { resolveExceptionUsageKey } from '~/ingestion/common/usage-records/billable-events'import { IngestionOverflowMode } from '~/ingestion/config'import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'import { TopHogRegistry, count } from '~/ingestion/framework/extensions/tophog'@@ -57,7 +66,7 @@ export type ErrorTrackingPipeline = BatchingPipeline<ErrorTrackingPipelineInput,ErrorTrackingPipelineOutput,{ message: Message },- Record<never, object>,+ EventUsageBatchContext,{ message: Message } & BatchingContext,OverflowOutput>@@ -93,6 +102,7 @@ export interface ErrorTrackingPipelineConfig {overflowLaneTTLRefreshService?: OverflowRedirectService/** TopHog registry for metrics. */topHog: TopHogRegistry+ createEventUsageBatch?: () => UsageRecordBatch}/**@@ -136,6 +146,7 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)overflowRedirectService,overflowLaneTTLRefreshService,topHog,+ createEventUsageBatch = () => new UsageRecordBatch(null, { unit: 'events', isTeamEnabled: () => false }),} = configconst preCymbal = newCommonIngestionPipeline<ErrorTrackingPipelineInput, { message: Message }, OverflowOutput>({@@ -145,6 +156,7 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)concurrentBatches: 1,topHog,})+ .beforeBatch((b) => b.pipe(createEventUsageBeforeBatchStep(createEventUsageBatch)))// Header-only steps: parse Kafka headers and apply token-level restrictions.// Cheap; runs per-event before we touch the body..parseHeaders()@@ -203,6 +215,8 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig).pipe(createErrorTrackingPrepareEventStep())// Map group types to indexes (read-only, no new group types created).pipe(createReadOnlyProcessGroupsStep(groupTypeManager))+ // After Cymbal, so an exception it suppresses is never billed.+ .pipe(createRecordEventUsageStep(resolveExceptionUsageKey)).pipe(createCreateEventStep(EVENTS_OUTPUT)).pipe(createEmitEventStep({ outputs }), {topHog: [@@ -215,7 +229,9 @@ export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig)})),],})+ .pipe(createRecordEventUsageAfterIngestStep()).pipe(createRecordIngestionLagStep())+ .afterBatch((b) => b.pipe(createFlushEventUsageStep())).build())}diff --git a/nodejs/src/servers/error-tracking-server.ts b/nodejs/src/servers/error-tracking-server.tsindex ab6f46bed52a..9fdcabd5866c 100644--- a/nodejs/src/servers/error-tracking-server.ts+++ b/nodejs/src/servers/error-tracking-server.ts@@ -10,6 +10,8 @@ import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'import { PersonHogConfig, createPersonHogClient } from '~/common/personhog'import { PersonHogGroupReadRepository } from '~/common/personhog/personhog-group-read-repository'import { PersonHogPersonReadRepository } from '~/common/personhog/personhog-person-read-repository'+import { UsageIngestionConfig, createUsageIngestionClient, usageReportTeamMatcher } from '~/common/usage-ingestion'+import { UsageRecordBatch } from '~/common/usage-ingestion/usage-record-batch'import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter } from '~/common/utils/db/postgres'import { createRedisPoolFromConfig } from '~/common/utils/db/redis'@@ -76,6 +78,7 @@ export type ErrorTrackingServerConfig = BaseServerConfig &RedisConnectionsConfig &KafkaConsumerBaseConfig &PersonHogConfig &+ UsageIngestionConfig &CookielessServerConfig &Pick<CommonConfig,@@ -194,6 +197,10 @@ export class ErrorTrackingServer implements NodeServer {// 3. Error tracking consumerconst serviceLoaders: (() => Promise<PluginServerService>)[] = []+ // One client for the process: the batch factory runs per batch, and each client owns a transport.+ const usageClient = createUsageIngestionClient(this.config, 'exceptions')+ const usageTeamMatcher = usageReportTeamMatcher(this.config)+serviceLoaders.push(async () => {const consumer = new ErrorTrackingConsumer({@@ -222,6 +229,8 @@ export class ErrorTrackingServer implements NodeServer {cookielessManager: this.cookielessManager!,redisPool: this.redisPool!,personRepository,+ createEventUsageBatch: () =>+ new UsageRecordBatch(usageClient, { unit: 'events', isTeamEnabled: usageTeamMatcher }),})await consumer.start()diff --git a/nodejs/src/servers/ingestion-general-server.ts b/nodejs/src/servers/ingestion-general-server.tsindex 1c7ac6980302..1353eb1399f2 100644--- a/nodejs/src/servers/ingestion-general-server.ts+++ b/nodejs/src/servers/ingestion-general-server.ts@@ -19,6 +19,7 @@ import { HogTransformerComponent } from '~/common/hog-transformations/hog-transfimport { IngestionOutputsComponent } from '~/common/outputs/ingestion-outputs'import { PersonHogConfig, buildGroupRepository, buildPersonRepository, createPersonHogClient } from '~/common/personhog'import { PostgresPersonRepository } from '~/common/persons/repositories/postgres-person-repository'+import { UsageIngestionConfig } from '~/common/usage-ingestion'import { ServerCommands } from '~/common/utils/commands'import { PostgresRouter, PostgresRouterComponent } from '~/common/utils/db/postgres'import { RedisPoolComponent } from '~/common/utils/db/redis'@@ -89,6 +90,7 @@ export type IngestionGeneralServerConfig = BaseServerConfig &RedisConnectionsConfig &KafkaConsumerBaseConfig &PersonHogConfig &+ UsageIngestionConfig &Pick<CommonConfig,| 'LOG_LEVEL'