: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(data-warehouse): add data warehouse table trigger for workflows (#59468)
Tom Owersaf445118918d
diff --git a/nodejs/src/cdp/cdp-e2e.test.ts b/nodejs/src/cdp/cdp-e2e.test.tsindex 75c91c42fd9e..bc95295eccd3 100644--- a/nodejs/src/cdp/cdp-e2e.test.ts+++ b/nodejs/src/cdp/cdp-e2e.test.ts@@ -5,16 +5,18 @@ import { KafkaProducerObserver } from '~/tests/helpers/mocks/producer.spy'import { createCdpConsumerDeps } from '~/tests/helpers/cdp'import { waitForExpect } from '~/tests/helpers/expectations'-import { TEST_KAFKA_TOPICS, ensureKafkaTopics } from '~/tests/helpers/kafka'+import { TEST_KAFKA_TOPICS, ensureKafkaTopics, resetKafka } from '~/tests/helpers/kafka'import { forSnapshot } from '~/tests/helpers/snapshots'import { getFirstTeam, resetTestDatabase } from '~/tests/helpers/sql'import { CdpCyclotronWorker } from '../../src/cdp/consumers/cdp-cyclotron-worker.consumer'+import { CdpDatawarehouseEventsConsumer } from '../../src/cdp/consumers/cdp-data-warehouse-events.consumer'import { HogFunctionInvocationGlobals, HogFunctionType } from '../../src/cdp/types'import { KAFKA_APP_METRICS_2, KAFKA_LOG_ENTRIES } from '../../src/config/kafka-topics'import { KafkaProducerWrapper } from '../../src/kafka/producer'import { Hub, Team } from '../../src/types'import { closeHub, createHub } from '../../src/utils/db/hub'+import { UUIDT } from '../../src/utils/utils'import { logger } from '../utils/logger'import { HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from './_tests/examples'import {@@ -570,4 +572,139 @@ describe('CDP Consumer loop', () => {])})})++ describe('e2e data warehouse destination', () => {+ let dwhConsumer: CdpDatawarehouseEventsConsumer+ let cyclotronWorker: CdpCyclotronWorker++ let hub: Hub+ let kafkaProducer: KafkaProducerWrapper = undefined as unknown as KafkaProducerWrapper+ let team: Team+ let fnDataWarehouseDestination: HogFunctionType+ let mockProducerObserver: KafkaProducerObserver++ const TABLE_NAME = 'postgres.orders'++ const insertHogFunction = async (hogFunction: Partial<HogFunctionType>): Promise<HogFunctionType> => {+ return await _insertHogFunction(hub.postgres, team.id, hogFunction)+ }++ /** Row-scoped globals the DWH consumer produces for a synced warehouse row. */+ const createDwhGlobals = (rowProperties: Record<string, any> = {}): HogFunctionInvocationGlobals =>+ createHogExecutionGlobals({+ project: { id: team.id } as any,+ event: {+ uuid: new UUIDT().toString(),+ event: '$warehouse_source_row',+ distinct_id: '',+ properties: { ...rowProperties, $source_table: TABLE_NAME },+ timestamp: '2024-09-03T09:00:00Z',+ } as any,+ })++ beforeEach(async () => {+ MockKafkaProducerWrapper.create = jest.fn((...args) => {+ return ActualKafkaProducerWrapper.create(...args)+ })++ await resetKafka()+ await resetTestDatabase()+ hub = await createHub()++ kafkaProducer = await ActualKafkaProducerWrapper.create(hub.KAFKA_CLIENT_RACK)+ mockProducerObserver = new KafkaProducerObserver(kafkaProducer)++ team = await getFirstTeam(hub.postgres)+ mockProducerObserver.resetKafkaProducer()++ hub.CDP_FETCH_RETRIES = 2+ hub.CDP_FETCH_BACKOFF_BASE_MS = 100+ hub.CDP_CYCLOTRON_COMPRESS_KAFKA_DATA = true++ const hog = `+ let res := fetch(inputs.url, { 'body': inputs.body, 'method': inputs.method });+ print('Fetch response:', res);+ `++ // Destination subscribed to the data-warehouse-table source — only fires on synced rows.+ fnDataWarehouseDestination = await insertHogFunction({+ type: 'destination',+ hog,+ bytecode: await compileHog(hog),+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters_data_warehouse_table,+ })++ const kafkaQueue = new CyclotronJobQueueKafka(hub.KAFKA_CLIENT_RACK, hub, hub.CONSUMER_BATCH_SIZE)+ const postgresV2Queue = new CyclotronJobQueuePostgresV2(hub.CONSUMER_BATCH_SIZE, hub)++ dwhConsumer = new CdpDatawarehouseEventsConsumer(hub, createCdpConsumerDeps(hub, kafkaProducer), {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })+ await dwhConsumer.start()++ cyclotronWorker = new CdpCyclotronWorker(hub, createCdpConsumerDeps(hub, kafkaProducer), kafkaQueue)+ await cyclotronWorker.start()++ mockFetch.mockResolvedValue({+ status: 200,+ json: () => Promise.resolve({ success: true }),+ text: () => Promise.resolve(JSON.stringify({ success: true })),+ headers: { 'Content-Type': 'application/json' },+ dump: () => Promise.resolve(),+ })++ expect(mockProducerObserver.getProducedKafkaMessages()).toHaveLength(0)+ })++ afterEach(async () => {+ await Promise.all([dwhConsumer?.stop(), cyclotronWorker?.stop()])+ await kafkaProducer.disconnect()+ await closeHub(hub)+ mockProducerObserver.resetKafkaProducer()+ })++ afterAll(() => {+ jest.useRealTimers()+ })++ it('invokes a data-warehouse-sourced destination for a synced row', async () => {+ const { invocations } = await dwhConsumer.processBatch([createDwhGlobals({ order_id: 42 })])+ expect(invocations).toHaveLength(1)++ try {+ await waitForExpect(() => {+ expect(mockProducerObserver.getProducedKafkaMessagesForTopic('log_entries_test')).toHaveLength(2)+ }, 5000)+ } catch (e) {+ logger.warn('[TESTS] Failed to wait for log messages', {+ messages: mockProducerObserver.getProducedKafkaMessages(),+ })+ throw e+ }++ expect(mockFetch).toHaveBeenCalledTimes(1)+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://example.com/posthog-webhook',+ expect.objectContaining({ method: 'POST' })+ )++ const metricsMessages = mockProducerObserver.getProducedKafkaMessagesForTopic(KAFKA_APP_METRICS_2)+ expect(metricsMessages).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ topic: 'clickhouse_app_metrics2_test',+ value: expect.objectContaining({+ app_source: 'hog_function',+ app_source_id: fnDataWarehouseDestination.id.toString(),+ metric_kind: 'success',+ metric_name: 'succeeded',+ team_id: team.id,+ }),+ }),+ ])+ )+ })+ })})diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.tsindex a2150c1ddd0a..ac9cd84c37a1 100644--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-hogflow.consumer.ts@@ -57,7 +57,14 @@ export class CdpCyclotronWorkerHogFlow extends CdpCyclotronWorker {const hogFlowInvocationState = item.state as CyclotronJobInvocationHogFlow['state']- const personIdOrDistinctId = hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personId+ // Warehouse-row invocations don't have a real person — the row is the unit of work+ // and person-dependent steps no-op for these flows. Explicitly skip the person lookup+ // rather than relying on event.distinct_id being empty so future changes to the+ // synthetic event shape don't accidentally re-enable the lookup.+ const isWarehouseRow = hogFlow.trigger?.type === 'data-warehouse-table'+ const personIdOrDistinctId = isWarehouseRow+ ? undefined+ : hogFlowInvocationState.event.distinct_id || hogFlowInvocationState.personIdconst kind = hogFlowInvocationState.event.distinct_id ? 'distinct_id' : 'person_id'const [person, groups] = await Promise.all([diff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.tsindex 39f5045b7247..3eeafd614d1d 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.test.ts@@ -1,12 +1,16 @@import { createMockJobQueue } from '../../../tests/helpers/mocks/job-queue.mock'import { mockProducerObserver } from '../../../tests/helpers/mocks/producer.mock'+import { HogFlow } from '~/schema/hogflow'+import { createCdpConsumerDeps } from '../../../tests/helpers/cdp'import { createOrganization, createTeam, getFirstTeam, getTeam, resetTestDatabase } from '../../../tests/helpers/sql'import { Hub, Team } from '../../types'import { closeHub, createHub } from '../../utils/db/hub'+import { FixtureHogFlowBuilder } from '../_tests/builders/hogflow.builder'import { HOG_EXAMPLES, HOG_FILTERS_EXAMPLES, HOG_INPUTS_EXAMPLES } from '../_tests/examples'import { insertHogFunction as _insertHogFunction, createKafkaMessage } from '../_tests/fixtures'+import { insertHogFlow as _insertHogFlow } from '../_tests/fixtures-hogflows'import { CdpDataWarehouseEvent } from '../schema'import { HogWatcherState } from '../services/monitoring/hog-watcher.service'import { HogFunctionInvocationGlobals, HogFunctionType } from '../types'@@ -21,9 +25,14 @@ describe('CdpDatawarehouseEventsConsumer', () => {let team2: Teamlet mockQueueInvocations: jest.MockedFunction<any>- const createDataWarehouseEvent = (teamId: number, properties: Record<string, any> = {}): CdpDataWarehouseEvent => {+ const createDataWarehouseEvent = (+ teamId: number,+ properties: Record<string, any> = {},+ tableName?: string+ ): CdpDataWarehouseEvent => {return {team_id: teamId,+ table_name: tableName,event_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',properties: {column1: 'value1',@@ -44,6 +53,10 @@ describe('CdpDatawarehouseEventsConsumer', () => {return item}+ const insertHogFlow = async (hogFlow: HogFlow): Promise<HogFlow> => {+ return await _insertHogFlow(hub.postgres, hogFlow)+ }+beforeEach(async () => {await resetTestDatabase()hub = await createHub()@@ -59,7 +72,10 @@ describe('CdpDatawarehouseEventsConsumer', () => {const mockJobQueue = createMockJobQueue()- processor = new CdpDatawarehouseEventsConsumer(hub, createCdpConsumerDeps(hub), mockJobQueue)+ processor = new CdpDatawarehouseEventsConsumer(hub, createCdpConsumerDeps(hub), {+ hogQueue: mockJobQueue,+ hogflowQueue: mockJobQueue,+ })// NOTE: We don't want to actually connect to Kafka for these tests as it is slow and we are testing the core logic onlyprocessor['kafkaConsumer'] = {@@ -104,6 +120,7 @@ describe('CdpDatawarehouseEventsConsumer', () => {column2: 123,test_prop: 'test_value',})+ // Deterministic per-row id from the producer, surfaced as event.uuid for stable billing dedup.expect(invocations[0].event.uuid).toBe('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')expect(invocations[0].event.event).toBe('$warehouse_source_row')})@@ -313,6 +330,19 @@ describe('CdpDatawarehouseEventsConsumer', () => {)})+ it('should queue a running lifecycle row for each invocation so the runs UI shows in-flight work', async () => {+ const queueLifecycleRowSpy = jest.spyOn(+ processor['invocationResultsService']['invocationResultsRowsService'],+ 'queueLifecycleRow'+ )++ const { invocations } = await processor.processBatch([globals])++ expect(invocations).toHaveLength(1)+ expect(queueLifecycleRowSpy).toHaveBeenCalledTimes(1)+ expect(queueLifecycleRowSpy).toHaveBeenCalledWith(invocations[0], 'running')+ })+it('should bill once per event when multiple destinations match', async () => {// Add a second function that also matchesconst fnSecondDestination = await insertHogFunction({@@ -343,6 +373,61 @@ describe('CdpDatawarehouseEventsConsumer', () => {})})+ describe('hog flow invocations', () => {+ const buildDataWarehouseHogFlow = (teamId: number, tableName: string): HogFlow =>+ new FixtureHogFlowBuilder()+ .withTeamId(teamId)+ .withSimpleWorkflow({+ trigger: {+ type: 'data-warehouse-table',+ table_name: tableName,+ // Always-true bytecode (return true)+ filters: { properties: [], bytecode: ['_h', 29] } as any,+ },+ })+ .build()++ it('should build a hog flow invocation when the row table matches the trigger', async () => {+ const hogFlow = await insertHogFlow(buildDataWarehouseHogFlow(team.id, 'postgres.table_1'))++ const event = createDataWarehouseEvent(team.id, { test_prop: 'test_value' }, 'postgres.table_1')+ const globals = await processor._parseKafkaBatch([createKafkaMessage(event)])+ expect(globals).toHaveLength(1)++ const { invocations } = await processor.processBatch(globals)++ const hogFlowInvocations = invocations.filter((i: any) => i.hogFlow)+ expect(hogFlowInvocations).toHaveLength(1)+ expect(hogFlowInvocations[0].functionId).toBe(hogFlow.id)+ })++ it('should not build a hog flow invocation when the row table does not match', async () => {+ await insertHogFlow(buildDataWarehouseHogFlow(team.id, 'postgres.table_1'))++ const event = createDataWarehouseEvent(team.id, {}, 'postgres.other_table')+ const globals = await processor._parseKafkaBatch([createKafkaMessage(event)])++ const { invocations } = await processor.processBatch(globals)++ const hogFlowInvocations = invocations.filter((i: any) => i.hogFlow)+ expect(hogFlowInvocations).toHaveLength(0)+ })++ it('should parse rows for workflow-only teams (no hog functions)', async () => {+ await insertHogFlow(buildDataWarehouseHogFlow(team.id, 'postgres.table_1'))++ const event = createDataWarehouseEvent(team.id, {}, 'postgres.table_1')+ const globals = await processor._parseKafkaBatch([createKafkaMessage(event)])++ // Team has a workflow but no hog functions - the row must not be dropped.+ // The source table is exposed via event.properties.$source_table so the pipeline's+ // eligibilityFn can match warehouse-table triggers without a top-level globals field.+ expect(globals).toHaveLength(1)+ expect(globals[0].event?.event).toBe('$warehouse_source_row')+ expect(globals[0].event?.properties?.$source_table).toBe('postgres.table_1')+ })+ })+describe('quota limiting', () => {let fnFetchNoFilters: HogFunctionTypelet fnDataWarehouseFunction: HogFunctionTypediff --git a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.tsindex 82ff80987367..66d5377a17d7 100644--- a/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-data-warehouse-events.consumer.ts@@ -9,26 +9,40 @@ import { parseJSON } from '../../utils/json-parse'import { logger } from '../../utils/logger'import { captureException } from '../../utils/posthog'import { CdpDataWarehouseEvent, CdpDataWarehouseEventSchema } from '../schema'+import { HogFlowInvocationPipeline } from '../services/hog-flow-invocation-pipeline.service'import { HogFunctionInvocationPipeline } from '../services/hog-function-invocation-pipeline.service'import { JobQueue } from '../services/job-queue/job-queue.interface'import { CyclotronJobInvocation, HogFunctionInvocationGlobals, HogFunctionTypeType } from '../types'import { CdpConsumerBase, CdpConsumerBaseDeps } from './cdp-base.consumer'import { counterParseError } from './metrics'-/* NOTE: This is not released yet - outstanding work to be done:- * Make it clear that Workflows are not supported / add support (the filter hog function logic is the key part)- */+// Synthetic event name stamped on the synthetic event built for a warehouse-row trigger.+// Acts as the "this globals object originated from a synced warehouse row" discriminator.+export const WAREHOUSE_SOURCE_ROW_EVENT = '$warehouse_source_row'++// Special property on the synthetic event holding the dot-notated source table name.+// Used by the pipeline's eligibility predicate to match warehouse-table HogFlow triggers+// against the row's source table without adding a top-level field to globals.+export const DWH_SOURCE_TABLE_PROPERTY = '$source_table'+export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {protected name = 'CdpDatawarehouseEventsConsumer'protected hogTypes: HogFunctionTypeType[] = ['destination']protected hogQueue: JobQueue+ protected hogflowQueue: JobQueueprotected kafkaConsumer: KafkaConsumerInterfaceprivate hogFunctionPipeline: HogFunctionInvocationPipeline+ private hogFlowPipeline: HogFlowInvocationPipeline- constructor(config: PluginsServerConfig, deps: CdpConsumerBaseDeps, hogQueue: JobQueue) {+ constructor(+ config: PluginsServerConfig,+ deps: CdpConsumerBaseDeps,+ jobQueues: { hogQueue: JobQueue; hogflowQueue: JobQueue }+ ) {super(config, deps)- this.hogQueue = hogQueue+ this.hogQueue = jobQueues.hogQueue+ this.hogflowQueue = jobQueues.hogflowQueuethis.kafkaConsumer = createKafkaConsumer({groupId: 'cdp-data-warehouse-events-consumer',topic: 'cdp_data_warehouse_source_table',@@ -44,6 +58,17 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {redis: this.redis,valkeyShadow: this.valkeyShadow,})+ this.hogFlowPipeline = new HogFlowInvocationPipeline(config, {+ hogFlowManager: this.hogFlowManager,+ hogFlowExecutor: this.hogFlowExecutor,+ hogWatcher: this.hogWatcher,+ hogWatcherMirror: this.hogWatcherMirror,+ hogMasker: this.hogMasker,+ hogFunctionMonitoringService: this.hogFunctionMonitoringService,+ quotaLimiting: deps.quotaLimiting,+ redis: this.redis,+ valkeyShadow: this.valkeyShadow,+ })}public async processBatch(@@ -53,17 +78,42 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {return { backgroundTask: Promise.resolve(), invocations: [] }}- await this.groupsManager.addGroupsToGlobalsList(invocationGlobals)-- const invocationsToBeQueued = await this.hogFunctionPipeline.buildInvocations(invocationGlobals, {- hogTypes: this.hogTypes,- filterFn: (fn) => (fn.filters?.source ?? 'events') === 'data-warehouse-table',- })+ // Warehouse rows carry no `$groups` property — group enrichment is a no-op here, so we skip the+ // call entirely to avoid the per-batch group-types lookup.++ const [hogInvocations, hogflowInvocations] = await Promise.all([+ this.hogFunctionPipeline.buildInvocations(invocationGlobals, {+ hogTypes: this.hogTypes,+ filterFn: (fn) => (fn.filters?.source ?? 'events') === 'data-warehouse-table',+ }),+ // Source-compatibility matching lives in the consumer rather than the executor — the+ // consumer knows it's serving warehouse rows, so it filters flows to only those whose+ // trigger.table_name matches the row's $source_table property. The executor then just+ // evaluates filter bytecode on the matched flows.+ this.hogFlowPipeline.buildInvocations(invocationGlobals, {+ eligibilityFn: (flow, globals) =>+ flow.trigger.type === 'data-warehouse-table' &&+ flow.trigger.table_name === globals.event?.properties?.[DWH_SOURCE_TABLE_PROPERTY],+ }),+ ])++ const invocationsToBeQueued = [...hogInvocations, ...hogflowInvocations]++ // Emit a `running` lifecycle row for each freshly-created invocation so the runs UI shows+ // warehouse-triggered flows as in-flight (matching the event consumer). The terminal row is+ // queued later by the cyclotron worker; both collapse under the same `invocation_id` via+ // ReplacingMergeTree, with the terminal row's later `version` superseding the running row.+ for (const invocation of invocationsToBeQueued) {+ this.invocationResultsService.invocationResultsRowsService.queueLifecycleRow(invocation, 'running')+ }return {backgroundTask: Promise.all([- instrumentFn({ key: 'cdp.background_task.queue_invocations', sendException: false }, () =>- this.hogQueue.queueInvocations(invocationsToBeQueued)+ instrumentFn({ key: 'cdp.background_task.queue_hog_invocations', sendException: false }, () =>+ this.hogQueue.queueInvocations(hogInvocations)+ ),+ instrumentFn({ key: 'cdp.background_task.queue_hogflow_invocations', sendException: false }, () =>+ this.hogflowQueue.queueInvocations(hogflowInvocations)),instrumentFn({ key: 'cdp.background_task.monitoring_flush', sendException: false }, async () => {try {@@ -73,6 +123,9 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {logger.error('🔴', 'Error producing queued messages for monitoring', { err })}}),+ instrumentFn({ key: 'cdp.background_task.lifecycle_running_flush', sendException: false }, () =>+ this.invocationResultsService.invocationResultsRowsService.flush()+ ),]),invocations: invocationsToBeQueued,}@@ -88,12 +141,13 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {const kafkaEvent = parseJSON(message.value!.toString()) as unknownconst event = CdpDataWarehouseEventSchema.parse(kafkaEvent)- const [teamHogFunctions, team] = await Promise.all([+ const [teamHogFunctions, teamHogFlows, team] = await Promise.all([this.hogFunctionManager.getHogFunctionsForTeam(event.team_id, this.hogTypes),+ this.hogFlowManager.getHogFlowsForTeam(event.team_id),this.deps.teamManager.getTeam(event.team_id),])- if (!teamHogFunctions.length || !team) {+ if ((!teamHogFunctions.length && !teamHogFlows.length) || !team) {return}@@ -112,7 +166,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {public override async start(): Promise<void> {await super.start()- await this.hogQueue.startAsProducer()+ await Promise.all([this.hogQueue.startAsProducer(), this.hogflowQueue.startAsProducer()])await this.kafkaConsumer.connect(async (messages) => {logger.info('🔁', `${this.name} - handling batch`, { size: messages.length })return await instrumentFn('cdpConsumer.handleEachBatch', async () => {@@ -126,7 +180,7 @@ export class CdpDatawarehouseEventsConsumer extends CdpConsumerBase {public override async stop(): Promise<void> {logger.info('💤', 'Stopping consumer...')await this.kafkaConsumer.disconnect()- await this.hogQueue.stopProducer()+ await Promise.all([this.hogQueue.stopProducer(), this.hogflowQueue.stopProducer()])await super.stop()}@@ -143,7 +197,13 @@ function convertDataWarehouseEventToHogFunctionInvocationGlobals(const data = event.propertiesconst projectUrl = `${siteUrl}/project/${team.id}`- const context: HogFunctionInvocationGlobals = {+ // The synthetic event carries:+ // - the producer's deterministic per-row id (CDPProducer._build_event_id) as the uuid, so+ // billing dedup (keyed on event.uuid) counts each row distinctly and stably across re-runs+ // - `$warehouse_source_row` as the event name so downstream code can identify warehouse-row globals+ // - the dot-notated source table name on `properties.$source_table` so consumers can match+ // warehouse-table HogFlow triggers without a new top-level field on globals+ return {project: {id: team.id,name: team.name,@@ -151,14 +211,15 @@ function convertDataWarehouseEventToHogFunctionInvocationGlobals(},event: {uuid: event.event_id,- event: '$warehouse_source_row',+ event: WAREHOUSE_SOURCE_ROW_EVENT,elements_chain: '', // Not applicable but left here for compatibilitydistinct_id: 'data-warehouse-table-distinct-id-do-not-use',- properties: data,+ properties: {+ ...data,+ [DWH_SOURCE_TABLE_PROPERTY]: event.table_name ?? '',+ },timestamp: DateTime.now().toISO(),url: '',},}-- return context}diff --git a/nodejs/src/cdp/consumers/cdp-events.consumer.ts b/nodejs/src/cdp/consumers/cdp-events.consumer.tsindex 7bf77f9aac8a..af19ecaa4a92 100644--- a/nodejs/src/cdp/consumers/cdp-events.consumer.ts+++ b/nodejs/src/cdp/consumers/cdp-events.consumer.ts@@ -78,7 +78,12 @@ export class CdpEventsConsumer<hogTypes: this.hogTypes,filterFn: (fn) => (fn.filters?.source ?? 'events') === 'events',}),- this.hogFlowPipeline.buildInvocations(invocationGlobals),+ // Source-compatibility lives in the consumer. The events consumer matches event-triggered+ // flows only; other trigger types (data-warehouse-table, batch, schedule, webhook, manual)+ // are dispatched from their respective consumers and never reach the executor from here.+ this.hogFlowPipeline.buildInvocations(invocationGlobals, {+ eligibilityFn: (flow) => flow.trigger.type === 'event',+ }),])const invocationsToBeQueued = [...hogInvocations, ...hogflowInvocations]diff --git a/nodejs/src/cdp/schema.ts b/nodejs/src/cdp/schema.tsindex 3f15237a7b77..c154a34f51b0 100644--- a/nodejs/src/cdp/schema.ts+++ b/nodejs/src/cdp/schema.ts@@ -28,6 +28,9 @@ export type CdpInternalEvent = z.infer<typeof CdpInternalEventSchema>export const CdpDataWarehouseEventSchema = z.object({team_id: z.number(),+ // Dot-notated table name the row was synced into. Optional for backwards compatibility with+ // messages produced before the producer started including it.+ table_name: z.string().optional(),// Deterministic id, unique per row per external data job run (see CDPProducer._build_event_id)event_id: z.string(),properties: z.record(z.string(), z.any()),diff --git a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.tsindex 6eabf01c9c49..d60d8b391dae 100644--- a/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts+++ b/nodejs/src/cdp/services/hog-flow-invocation-pipeline.service.ts@@ -1,6 +1,7 @@import { DateTime } from 'luxon'import { instrumentFn, instrumented } from '~/common/tracing/tracing-utils'+import { HogFlow } from '~/schema/hogflow'import { RedisV2 } from '../../common/redis/redis-v2'import { KeyedRateLimitRequest, KeyedRateLimiterService } from '../../common/services/keyed-rate-limiter.service'@@ -64,18 +65,30 @@ export class HogFlowInvocationPipeline {@instrumented('cdpConsumer.handleEachBatch.queueMatchingFlows')public async buildInvocations(- invocationGlobals: HogFunctionInvocationGlobals[]+ invocationGlobals: HogFunctionInvocationGlobals[],+ options?: {+ // Predicate evaluated per (flow, globals) before the executor runs filter bytecode.+ // The consumer is the natural layer to decide trigger-source compatibility because it+ // knows its own source (events consumer → event triggers; DWH consumer → matching+ // warehouse-table triggers). Flows that fail the predicate are skipped without+ // touching the executor.+ eligibilityFn?: (hogFlow: HogFlow, globals: HogFunctionInvocationGlobals) => boolean+ }): Promise<CyclotronJobInvocation[]> {const teamsToLoad = [...new Set(invocationGlobals.map((x) => x.project.id))]const hogFlowsByTeam = await this.deps.hogFlowManager.getHogFlowsForTeams(teamsToLoad)+ const eligibilityFn = options?.eligibilityFnconst possibleInvocations = (await Promise.all(invocationGlobals.map(async (globals) => {const teamHogFlows = hogFlowsByTeam[globals.project.id]+ const eligibleFlows = eligibilityFn+ ? teamHogFlows.filter((flow) => eligibilityFn(flow, globals))+ : teamHogFlowsconst { invocations, metrics, logs } = await this.deps.hogFlowExecutor.buildHogFlowInvocations(- teamHogFlows,+ eligibleFlows,globals)diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.tsindex 9dd031701847..b2ccd092dff8 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts@@ -1383,6 +1383,41 @@ describe('Hogflow Executor', () => {})})+ describe('data-warehouse-table trigger', () => {+ // Trigger-source compatibility is decided by the pipeline's eligibilityFn (per consumer),+ // not the executor — coverage for source matching lives in the consumer tests. Here we just+ // assert that when a warehouse-trigger flow with always-true filters is handed to the+ // executor with warehouse-row globals, an invocation is produced.+ it('builds an invocation when filter bytecode evaluates true for warehouse-row globals', async () => {+ const hogFlow = new FixtureHogFlowBuilder()+ .withSimpleWorkflow({+ trigger: {+ type: 'data-warehouse-table',+ table_name: 'postgres.table_1',+ // Always-true bytecode (return true) like the no-filter data warehouse example+ filters: { properties: [], bytecode: ['_h', 29] } as any,+ },+ })+ .build()+ const globals = createHogExecutionGlobals({+ event: {+ uuid: 'row-uuid-0001',+ event: '$warehouse_source_row',+ distinct_id: '',+ elements_chain: '',+ timestamp: new Date().toISOString(),+ url: '',+ properties: { column1: 'value1', column2: 123, $source_table: 'postgres.table_1' },+ },+ })++ const result = await executor.buildHogFlowInvocations([hogFlow], globals)++ expect(result.invocations).toHaveLength(1)+ expect(result.invocations[0].hogFlow.id).toBe(hogFlow.id)+ })+ })+describe('variable merging', () => {it('merges default and provided variables correctly', () => {const hogFlow: HogFlow = new FixtureHogFlowBuilder()diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.tsindex 99a092e3b57d..ef5bcbdee55d 100644--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.ts@@ -123,13 +123,20 @@ export class HogFlowExecutorService {// TRICKY: The frontend generates filters matching the Clickhouse event type so we are converting backconst filterGlobals = convertToHogFunctionFilterGlobal(triggerGlobals)+ // Trigger-source compatibility is decided by the pipeline's eligibilityFn (see+ // HogFlowInvocationPipeline). Flows that reach this loop are assumed to be source-compatible+ // with the given globals — the executor's job is just to evaluate filter bytecode.for (const hogFlow of hogFlows) {- if (hogFlow.trigger.type !== 'event') {+ const trigger = hogFlow.trigger++ // Defensive: only the trigger types that carry `filters` make it through eligibility.+ if (trigger.type !== 'event' && trigger.type !== 'data-warehouse-table') {continue}+const filterResults = await filterFunctionInstrumented({fn: hogFlow,- filters: hogFlow.trigger.filters,+ filters: trigger.filters,filterGlobals,})diff --git a/nodejs/src/cdp/workflows-e2e.test.ts b/nodejs/src/cdp/workflows-e2e.test.tsindex 7bbcbc05e665..d8a85d239767 100644--- a/nodejs/src/cdp/workflows-e2e.test.ts+++ b/nodejs/src/cdp/workflows-e2e.test.ts@@ -40,6 +40,7 @@ import { createHogExecutionGlobals, insertHogFunctionTemplate, insertIntegrationimport { insertHogFlow } from './_tests/fixtures-hogflows'import { CdpCyclotronWorkerEmail } from './consumers/cdp-cyclotron-worker-email.consumer'import { CdpCyclotronWorkerHogFlow } from './consumers/cdp-cyclotron-worker-hogflow.consumer'+import { CdpDatawarehouseEventsConsumer } from './consumers/cdp-data-warehouse-events.consumer'import { CdpEventsConsumer } from './consumers/cdp-events.consumer'import { CdpHogflowSubscriptionMatcherConsumer } from './consumers/cdp-hogflow-subscription-matcher.consumer'import { CyclotronJobQueueKafka } from './services/job-queue/job-queue-kafka'@@ -64,6 +65,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)jest.setTimeout(30000)let eventsConsumer: CdpEventsConsumer+ let dwhConsumer: CdpDatawarehouseEventsConsumerlet hogflowWorker: CdpCyclotronWorkerHogFlowlet hogflowQueue: JobQueue@@ -146,6 +148,12 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)hogQueue: kafkaQueue,hogflowQueue,})+ // Drives the data-warehouse-table trigger path. We call processBatch() directly, so the+ // Kafka consumer is never connected — the shared queues below are the only producers.+ dwhConsumer = new CdpDatawarehouseEventsConsumer(hub, deps, {+ hogQueue: kafkaQueue,+ hogflowQueue,+ })await Promise.all([kafkaQueue.startAsProducer(), hogflowQueue.startAsProducer()])// Start hogflow worker (consumer side — polls from the mode's backend)@@ -162,6 +170,7 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)})afterEach(async () => {+ // dwhConsumer shares the already-stopped queues with eventsConsumer, so it has nothing to stop.await Promise.all([eventsConsumer?.stop() ?? Promise.resolve(), hogflowWorker?.stop() ?? Promise.resolve()])await kafkaProducer.disconnect()await closeHub(hub)@@ -206,6 +215,33 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)await backgroundTask}+ /**+ * Build the row-scoped globals the DWH consumer produces for a synced warehouse row: a synthetic+ * event named `$warehouse_source_row` with no real person, and the source table on+ * `event.properties.$source_table` so the consumer's eligibilityFn matches warehouse-table triggers.+ */+ function createDwhGlobals(+ tableName: string,+ rowProperties: Record<string, any> = {}+ ): HogFunctionInvocationGlobals {+ return createHogExecutionGlobals({+ project: { id: team.id } as any,+ event: {+ uuid: new UUIDT().toString(),+ event: '$warehouse_source_row',+ distinct_id: '',+ properties: { ...rowProperties, $source_table: tableName },+ timestamp: '2024-09-03T09:00:00Z',+ } as any,+ })+ }++ /** Send a synced warehouse row through the DWH consumer and wait for it to be queued */+ async function triggerDwhWorkflow(rowGlobals: HogFunctionInvocationGlobals): Promise<void> {+ const { backgroundTask } = await dwhConsumer.processBatch([rowGlobals])+ await backgroundTask+ }+/** Insert an active hogflow for the current team */async function createWorkflow(workflow: Parameters<FixtureHogFlowBuilder['withWorkflow']>[0],@@ -1290,6 +1326,76 @@ describe.each(['postgres-v2' as const, 'postgres' as const])('Workflows E2E (%s)})})+ describe('data warehouse table trigger workflow', () => {+ const TABLE_NAME = 'postgres.orders'++ // Row-scoped trigger that always matches (return-true bytecode), so the row payload alone+ // decides whether the flow fires.+ const dwhTrigger = (tableName: string) =>+ ({+ type: 'trigger' as const,+ config: {+ type: 'data-warehouse-table',+ table_name: tableName,+ filters: { properties: [], bytecode: ['_h', 29] },+ },+ }) as any++ beforeEach(async () => {+ await createWorkflow({+ actions: {+ trigger: dwhTrigger(TABLE_NAME),+ function_1: fetchAction('https://example.com/warehouse-row'),+ exit: exitAction(),+ },+ edges: [+ { from: 'trigger', to: 'function_1', type: 'continue' },+ { from: 'function_1', to: 'exit', type: 'continue' },+ ],+ })+ })++ it('runs the workflow end-to-end when a row syncs into the matching table', async () => {+ await triggerDwhWorkflow(createDwhGlobals(TABLE_NAME, { order_id: 42 }))++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)++ expect(mockFetch).toHaveBeenCalledWith(+ 'https://example.com/warehouse-row',+ expect.objectContaining({ method: 'POST' })+ )+ })++ it('does not run the workflow when the synced row belongs to a different table', async () => {+ await triggerDwhWorkflow(createDwhGlobals('postgres.other_table', { order_id: 1 }))++ // Give the worker a chance to (not) pick anything up before asserting it stayed idle.+ await waitForExpect(async () => {+ const jobs = await queryCyclotronJobs()+ expect(jobs).toHaveLength(0)+ }, 3000)++ expect(mockFetch).not.toHaveBeenCalled()+ })++ it('does not look up a person for warehouse rows (no synthetic distinct_id resolution)', async () => {+ // Regression guard: warehouse rows carry a made-up event.distinct_id that evals truthy.+ // The worker must skip the person lookup for data-warehouse-table triggers so we don't+ // pay a person round-trip (or accidentally resolve a bogus person) per synced row.+ const personSpy = jest.spyOn((hogflowWorker as any).personsManager, 'getCyclotronPerson')++ await triggerDwhWorkflow(createDwhGlobals(TABLE_NAME, { order_id: 7 }))++ await waitForExpect(() => {+ expect(mockFetch).toHaveBeenCalledTimes(1)+ }, 10000)++ expect(personSpy).not.toHaveBeenCalled()+ })+ })+describe('posthog_ticket_tags input resolves templated values per element', () => {// Regression guard for the templating opt-in in posthog/cdp/validation.py.// Reproduces the real user-reported case: a ticket tag set todiff --git a/nodejs/src/schema/hogflow.ts b/nodejs/src/schema/hogflow.tsindex 20d9f94b4051..07ca13cf6b44 100644--- a/nodejs/src/schema/hogflow.ts+++ b/nodejs/src/schema/hogflow.ts@@ -67,6 +67,18 @@ const HogFlowTriggerSchema = z.discriminatedUnion('type', [properties: z.array(z.any()),}),}),+ z.object({+ type: z.literal('data-warehouse-table'),+ // Dot-notated table name, matching the format produced by the Python CDPProducer+ // (see get_data_warehouse_table_name) so producer gating and trigger config use identical strings.+ table_name: z.string(),+ filters: z.object({+ // Row-property filters only - warehouse-triggered workflows are person-less ("row-scoped")+ properties: z.array(z.any()).optional(),+ }),+ // Optional row column used as the masking / dedup key in place of distinct_id+ key_property: z.string().optional(),+ }),])export const HogFlowActionSchema = z.discriminatedUnion('type', [diff --git a/nodejs/src/server.ts b/nodejs/src/server.tsindex a74a7641bbcf..01936b6fa5a2 100644--- a/nodejs/src/server.ts+++ b/nodejs/src/server.ts@@ -167,7 +167,10 @@ export class PluginServer implements NodeServer {if (capabilities.cdpDataWarehouseEvents) {serviceLoaders.push(async () => {- const consumer = new CdpDatawarehouseEventsConsumer(this.config, cdpDeps!, kafkaQueue)+ const consumer = new CdpDatawarehouseEventsConsumer(this.config, cdpDeps!, {+ hogQueue: kafkaQueue,+ hogflowQueue: postgresV2Queue,+ })await consumer.start()return consumer.service})diff --git a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.pyindex 74409ff533ed..28c5e6dbe2f3 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/cdp_producer.py@@ -23,6 +23,7 @@ from posthog.temporal.data_imports.pipelines.helpers import build_table_namefrom products.cdp.backend.models.hog_functions import HogFunctionfrom products.data_warehouse.backend.s3 import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowclass CDPProducer:@@ -31,6 +32,7 @@ class CDPProducer:job_id: strlogger: FilteringBoundLogger_should_produce_cache: bool | None+ _table_name_cache: str | Nonedef __init__(self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger) -> None:self.team_id = team_id@@ -38,6 +40,7 @@ class CDPProducer:self.job_id = job_idself.logger = loggerself._should_produce_cache = None+ self._table_name_cache = Nonedef _get_fs(self) -> pa_fs.S3FileSystem:if settings.USE_LOCAL_SETUP:@@ -82,6 +85,19 @@ class CDPProducer:raise ValueError("Could not serialize record to JSON") from e+ async def get_dot_notated_table_name(self) -> str:+ if self._table_name_cache is not None:+ return self._table_name_cache++ @database_sync_to_async_pool+ def _resolve() -> str:+ schema = ExternalDataSchema.objects.get(id=self.schema_id, team_id=self.team_id)+ raw_table_name = build_table_name(schema.source, schema.name)+ return get_data_warehouse_table_name(schema.source, raw_table_name)++ self._table_name_cache = await _resolve()+ return self._table_name_cache+def _build_event_id(self, row: object) -> str:"""Build a deterministic event id that is unique per row per job.@@ -96,17 +112,14 @@ class CDPProducer:if self._should_produce_cache is not None:return self._should_produce_cache- @database_sync_to_async_pool- def _check():- schema = ExternalDataSchema.objects.get(id=self.schema_id, team_id=self.team_id)-- raw_table_name = build_table_name(schema.source, schema.name)- dot_notated_table_name = get_data_warehouse_table_name(schema.source, raw_table_name)+ dot_notated_table_name = await self.get_dot_notated_table_name()- self.logger.debug(f"Checking if table {dot_notated_table_name} is used in any hog functions")+ @database_sync_to_async_pool+ def _check() -> bool:+ self.logger.debug(f"Checking if table {dot_notated_table_name} is used in any hog functions or workflows")self.logger.debug(f"Using table_name = {dot_notated_table_name}, source = data-warehouse-table")- return (+ has_matching_hog_function = (HogFunction.objects.filter(team_id=self.team_id,enabled=True,@@ -117,6 +130,18 @@ class CDPProducer:.exists())+ if has_matching_hog_function:+ return True++ # Also gate on active workflows (HogFlows) triggered by this table - without this the+ # producer never emits to Kafka for a team whose only consumer is a warehouse-triggered workflow.+ return HogFlow.objects.filter(+ team_id=self.team_id,+ status=HogFlow.State.ACTIVE,+ trigger__type="data-warehouse-table",+ trigger__table_name=dot_notated_table_name,+ ).exists()+self._should_produce_cache = await _check()return self._should_produce_cache@@ -148,6 +173,10 @@ class CDPProducer:await self.logger.adebug(f"Producing CDP data to Kafka from S3 path prefix {self._get_path_prefix()}")+ # Propagate the dot-notated table name so the Node consumer can match warehouse-triggered+ # workflows (HogFlows) against trigger.table_name without an extra lookup.+ dot_notated_table_name = await self.get_dot_notated_table_name()+files_to_produce = await self._list_files_to_produce()await self.logger.adebug(f"Found {len(files_to_produce)} files to produce to Kafka")@@ -166,6 +195,7 @@ class CDPProducer:for row in batch.to_pylist():row_as_props = {"team_id": self.team_id,+ "table_name": dot_notated_table_name,"event_id": self._build_event_id(row),"properties": row,}diff --git a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.pyindex 7e27e9ab537f..4b1aa0fd36f3 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/test/test_cdp_producer.py@@ -18,6 +18,7 @@ from products.data_warehouse.backend.types import ExternalDataSourceTypefrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchemafrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowdef _patch_async_producer_scope(mock_producer):@@ -189,6 +190,153 @@ async def test_should_produce_table_with_leading_underscore_source_prefix(team):assert await producer.should_produce_table() is True[email protected]_db(transaction=True)+async def test_should_produce_table_with_matching_hog_flow(team):+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ await sync_to_async(HogFlow.objects.create)(+ team=team,+ status=HogFlow.State.ACTIVE,+ trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},+ )++ producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())+ assert await producer.should_produce_table() is True++[email protected]_db(transaction=True)+async def test_should_not_produce_table_with_draft_hog_flow(team):+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ await sync_to_async(HogFlow.objects.create)(+ team=team,+ status=HogFlow.State.DRAFT,+ trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},+ )++ producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())+ assert await producer.should_produce_table() is False++[email protected]_db(transaction=True)+async def test_should_not_produce_table_with_non_matching_hog_flow_table(team):+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ await sync_to_async(HogFlow.objects.create)(+ team=team,+ status=HogFlow.State.ACTIVE,+ trigger={"type": "data-warehouse-table", "table_name": "postgres.some_other_table"},+ )++ producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())+ assert await producer.should_produce_table() is False++[email protected]_db(transaction=True)+async def test_should_produce_table_with_both_hog_function_and_flow(team):+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ await sync_to_async(HogFunction.objects.create)(+ team=team,+ enabled=True,+ filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},+ )+ await sync_to_async(HogFlow.objects.create)(+ team=team,+ status=HogFlow.State.ACTIVE,+ trigger={"type": "data-warehouse-table", "table_name": "postgres.table_1"},+ )++ producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())+ assert await producer.should_produce_table() is True++[email protected]_db(transaction=True)+@patch("posthog.temporal.data_imports.pipelines.pipeline.cdp_producer.aget_s3_client")+async def test_produce_to_kafka_from_s3_includes_table_name(mock_get_s3_client, team):+ source = await sync_to_async(ExternalDataSource.objects.create)(+ team=team, source_type=ExternalDataSourceType.POSTGRES+ )+ table = await sync_to_async(DataWarehouseTable.objects.create)(+ team=team, name="postgres_table_1", external_data_source=source+ )+ schema = await sync_to_async(ExternalDataSchema.objects.create)(+ team=team, name="table_1", source=source, table=table+ )++ mock_s3_client = mock.AsyncMock()+ mock_s3_client._ls.return_value = [{"Key": "path/chunk_0.parquet", "type": "file"}]+ mock_get_s3_client.return_value.__aenter__ = mock.AsyncMock(return_value=mock_s3_client)+ mock_get_s3_client.return_value.__aexit__ = mock.AsyncMock(return_value=False)++ mock_kafka_producer = MagicMock()+ mock_kafka_producer.produce = mock.AsyncMock()+ mock_kafka_producer.flush = mock.AsyncMock()+ mock_kafka_producer.close = mock.AsyncMock()++ test_data = pa.table({"id": [1], "name": ["Alice"]})+ parquet_buffer = BytesIO()+ pq.write_table(test_data, parquet_buffer, compression="zstd")+ parquet_buffer.seek(0)++ mock_fs = MagicMock()+ mock_file = MagicMock()+ mock_file.__enter__ = MagicMock(return_value=parquet_buffer)+ mock_file.__exit__ = MagicMock(return_value=False)+ mock_fs.open_input_file.return_value = mock_file+ mock_fs.delete_file = MagicMock()++ producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())++ with (+ patch.object(producer, "_get_fs", return_value=mock_fs),+ _patch_async_producer_scope(mock_kafka_producer),+ ):+ await producer.produce_to_kafka_from_s3()++ first_call_kwargs = mock_kafka_producer.produce.call_args_list[0][1]+ assert first_call_kwargs["data"]["team_id"] == team.id+ assert first_call_kwargs["data"]["table_name"] == "postgres.table_1"+ assert "id" in first_call_kwargs["data"]["properties"]++@pytest.mark.django_db(transaction=True)@pytest.mark.asyncio@patch("posthog.temporal.data_imports.pipelines.pipeline.cdp_producer.aget_s3_client")diff --git a/posthog/temporal/tests/data_imports/test_end_to_end.py b/posthog/temporal/tests/data_imports/test_end_to_end.pyindex 7cdf23e31d31..afb0f4ed6330 100644--- a/posthog/temporal/tests/data_imports/test_end_to_end.py+++ b/posthog/temporal/tests/data_imports/test_end_to_end.py@@ -3543,6 +3543,7 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cliassert str(uuid.UUID(data["event_id"])) == data["event_id"]assert {key: value for key, value in data.items() if key != "event_id"} == {"team_id": team.id,+ "table_name": "stripe.customer","properties": expected_properties,}diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.pyindex 25ce340fbe40..973beaf986de 100644--- a/products/workflows/backend/api/hog_flow.py+++ b/products/workflows/backend/api/hog_flow.py@@ -61,7 +61,11 @@ from products.feature_flags.backend.user_blast_radius import (from products.workflows.backend.api.graph_operations import apply_graph_operationsfrom products.workflows.backend.api.graph_validation import validate_graphfrom products.workflows.backend.api.hog_flow_batch_job import HogFlowBatchJobSerializer-from products.workflows.backend.models.hog_flow.hog_flow import BILLABLE_ACTION_TYPES, HogFlow+from products.workflows.backend.models.hog_flow.hog_flow import (+ BILLABLE_ACTION_TYPES,+ PERSON_DEPENDENT_ACTION_TYPES,+ HogFlow,+)from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJobfrom products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedulefrom products.workflows.backend.utils.batch_trigger_limit import get_hogflow_batch_trigger_limit@@ -418,6 +422,31 @@ class HogFlowActionSerializer(serializers.Serializer):filters = data.get("config", {}).get("filters", {})if isinstance(filters, dict):self._reject_behavioral_cohorts_in_audience(filters.get("properties"))+ elif data.get("config", {}).get("type") == "data-warehouse-table":+ # Warehouse-triggered workflows are person-less ("row-scoped"): one workflow run+ # per synced row, filtering only against the row payload. The dot-notated table_name+ # must match the format produced by the Python CDPProducer so producer gating and+ # trigger config use identical strings.+ config = data.get("config", {})+ table_name = config.get("table_name")+ if not is_draft and (not table_name or not isinstance(table_name, str)):+ raise serializers.ValidationError(+ {"table_name": "A data warehouse table name is required for this trigger."}+ )++ # Compile the row-property filters to bytecode so the executor can evaluate them.+ # We force the data-warehouse-table source so only row properties are considered.+ filters = config.get("filters", {}) or {}+ if not isinstance(filters, dict):+ raise serializers.ValidationError({"filters": "Filters must be a dictionary."})+ filters["source"] = "data-warehouse-table"+ serializer = HogFunctionFiltersSerializer(data=filters, context=self.context)+ if is_draft:+ if serializer.is_valid():+ data["config"]["filters"] = serializer.validated_data+ else:+ serializer.is_valid(raise_exception=True)+ data["config"]["filters"] = serializer.validated_dataelse:if strict:raise serializers.ValidationError({"config": "Invalid trigger type"})@@ -852,6 +881,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):def validate(self, data):instance = cast(Optional[HogFlow], self.instance)+ is_draft = self.context.get("is_draft")actions = data.get("actions", instance.actions if instance else [])# When activating a draft, re-validate actions from the instance with full (non-draft) checks@@ -869,6 +899,31 @@ class HogFlowSerializer(HogFlowMinimalSerializer):data["trigger"] = trigger_actions[0]["config"]+ # Warehouse-triggered workflows are person-less ("row-scoped"): one run per synced row with no+ # associated person. Person-dependent steps and person-aware exit conditions would silently+ # assume person data, so we block them here — the serializer is the source of truth, so the API,+ # MCP, and frontend can't bypass it. We force exit_only_at_end since the other exit conditions+ # re-evaluate trigger/conversion filters that may reference person properties.+ if data["trigger"].get("type") == "data-warehouse-table":+ data["exit_condition"] = HogFlow.ExitCondition.ONLY_AT_END+ if not is_draft:+ offending_types = sorted(+ {+ action.get("type", "")+ for action in actions+ if action.get("type") in PERSON_DEPENDENT_ACTION_TYPES+ }+ )+ if offending_types:+ raise serializers.ValidationError(+ {+ "actions": (+ "These step types rely on person data, which is unavailable for data warehouse "+ f"table triggers: {', '.join(offending_types)}"+ )+ }+ )+# Compute and store unique billable action types for efficient quota checking# Only track billable actions defined in BILLABLE_ACTION_TYPESbillable_action_types = sorted(diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.pyindex 4e2ba7a17cf9..555daed819fd 100644--- a/products/workflows/backend/api/test/test_hog_flow.py+++ b/products/workflows/backend/api/test/test_hog_flow.py@@ -1491,6 +1491,194 @@ class TestHogFlowAPI(APIBaseTest):"type": "validation_error",}+ def test_hog_flow_data_warehouse_table_trigger_valid(self):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": {"properties": []},+ },+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "active",+ "actions": [trigger_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+ trigger = response.json()["trigger"]+ assert trigger["type"] == "data-warehouse-table"+ assert trigger["table_name"] == "postgres.table_1"+ # Filters should be compiled to bytecode with the data-warehouse-table source+ assert trigger["filters"]["source"] == "data-warehouse-table"+ assert "bytecode" in trigger["filters"]++ def test_hog_flow_data_warehouse_table_trigger_without_table_name(self):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "filters": {"properties": []},+ },+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "active",+ "actions": [trigger_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 400, response.json()+ assert response.json() == {+ "attr": "actions__0__table_name",+ "code": "invalid_input",+ "detail": "A data warehouse table name is required for this trigger.",+ "type": "validation_error",+ }++ def test_hog_flow_data_warehouse_table_trigger_draft_allows_missing_table_name(self):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "filters": {"properties": []},+ },+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "draft",+ "actions": [trigger_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()++ def test_hog_flow_data_warehouse_table_trigger_filters_not_dict(self):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": "not a dict",+ },+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "active",+ "actions": [trigger_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 400, response.json()+ assert response.json() == {+ "attr": "actions__0__filters",+ "code": "invalid_input",+ "detail": "Filters must be a dictionary.",+ "type": "validation_error",+ }++ @parameterized.expand(+ [+ ("wait_until_condition", {"condition": {"filters": {"properties": []}}, "max_wait_duration": "5m"}),+ ("random_cohort_branch", {"cohorts": [{"percentage": 50}]}),+ ]+ )+ def test_hog_flow_data_warehouse_table_trigger_rejects_person_dependent_steps(self, action_type, action_config):+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": {"properties": []},+ },+ }+ person_dependent_action = {+ "id": "person_step",+ "name": "person_step",+ "type": action_type,+ "config": action_config,+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "active",+ "actions": [trigger_action, person_dependent_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 400, response.json()+ assert response.json()["attr"] == "actions"+ assert action_type in response.json()["detail"]++ def test_hog_flow_data_warehouse_table_trigger_draft_allows_person_dependent_steps(self):+ # Drafts are not executed, so we defer the hard rejection until activation.+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": {"properties": []},+ },+ }+ person_dependent_action = {+ "id": "person_step",+ "name": "person_step",+ "type": "random_cohort_branch",+ "config": {"cohorts": [{"percentage": 50}]},+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "draft",+ "actions": [trigger_action, person_dependent_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()++ def test_hog_flow_data_warehouse_table_trigger_forces_exit_only_at_end(self):+ # Other exit conditions re-evaluate trigger/conversion filters that may reference person+ # data, so warehouse-triggered flows are coerced to exit_only_at_end regardless of input.+ trigger_action = {+ "id": "trigger_node",+ "name": "trigger_1",+ "type": "trigger",+ "config": {+ "type": "data-warehouse-table",+ "table_name": "postgres.table_1",+ "filters": {"properties": []},+ },+ }++ hog_flow = {+ "name": "Test DWH Flow",+ "status": "active",+ "exit_condition": "exit_on_conversion",+ "actions": [trigger_action],+ }++ response = self.client.post(f"/api/projects/{self.team.id}/hog_flows", hog_flow)+ assert response.status_code == 201, response.json()+ assert response.json()["exit_condition"] == "exit_only_at_end"+@parameterized.expand([("events", {"events": [{"id": "$pageview", "type": "events"}]}),diff --git a/products/workflows/backend/models/hog_flow/hog_flow.py b/products/workflows/backend/models/hog_flow/hog_flow.pyindex 3c691893c41c..bfc9f51ce19b 100644--- a/products/workflows/backend/models/hog_flow/hog_flow.py+++ b/products/workflows/backend/models/hog_flow/hog_flow.py@@ -26,6 +26,14 @@ BILLABLE_ACTION_TYPES: Final[set[str]] = {"function_push", # Push notification actions}+# Action types that read person data and therefore cannot be used in person-less ("row-scoped")+# workflows such as those triggered by a data warehouse table row sync. Keep in sync with the+# frontend's PERSON_DEPENDENT_ACTION_TYPES.+PERSON_DEPENDENT_ACTION_TYPES: Final[set[str]] = {+ "wait_until_condition",+ "random_cohort_branch",+}+class HogFlow(UUIDTModel):"""diff --git a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsxindex 499b88d373f7..7a24812bb73e 100644--- a/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx+++ b/products/workflows/frontend/Workflows/hogflows/panel/HogFlowEditorPanelBuild.tsx@@ -14,6 +14,7 @@ import { CreateActionType, hogFlowEditorLogic } from '../hogFlowEditorLogic'// Side-effect imports: register product-specific trigger and action nodesimport '../registry'+import { PERSON_DEPENDENT_ACTION_TYPES, workflowLogic } from '../../workflowLogic'import { getRegisteredActionNodeCategories } from '../registry/actions/actionNodeRegistry'import { useHogFlowStep } from '../steps/HogFlowSteps'import { getDelayDescription } from '../steps/stepDelayLogic'@@ -275,11 +276,19 @@ function HogFunctionTemplatesChooser(): JSX.Element {export function HogFlowEditorPanelBuild(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)+ const { isRowScopedTrigger } = useValues(workflowLogic)const registeredCategories = getRegisteredActionNodeCategories().filter((cat) => !cat.featureFlag || featureFlags[cat.featureFlag])+ // Warehouse-triggered workflows have no person, so don't offer person-dependent steps at all.+ const hideIfRowScoped = (nodes: CreateActionType[]): CreateActionType[] =>+ isRowScopedTrigger ? nodes.filter((node) => !PERSON_DEPENDENT_ACTION_TYPES.has(node.type)) : nodes++ const delayNodes = hideIfRowScoped(DELAY_NODES_TO_SHOW)+ const logicNodes = hideIfRowScoped(LOGIC_NODES_TO_SHOW)+return (<div className="flex overflow-y-auto flex-col gap-px p-2" data-attr="workflow-add-action"><span className="flex gap-2 text-sm font-semibold mt-2 items-center">@@ -293,16 +302,20 @@ export function HogFlowEditorPanelBuild(): JSX.Element {<span className="flex gap-2 text-sm font-semibold mt-2 items-center">Delays <LemonDivider className="flex-1" /></span>- {DELAY_NODES_TO_SHOW.map((action, index) => (+ {delayNodes.map((action, index) => (<HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />))}- <span className="flex gap-2 text-sm font-semibold mt-2 items-center">- Audience split <LemonDivider className="flex-1" />- </span>- {LOGIC_NODES_TO_SHOW.map((action, index) => (- <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />- ))}+ {logicNodes.length > 0 && (+ <>+ <span className="flex gap-2 text-sm font-semibold mt-2 items-center">+ Audience split <LemonDivider className="flex-1" />+ </span>+ {logicNodes.map((action, index) => (+ <HogFlowEditorToolbarNode key={`${action.type}-${index}`} action={action} />+ ))}+ </>+ )}<span className="flex gap-2 text-sm font-semibold mt-2 items-center">PostHog actions <LemonDivider className="flex-1" />diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.test.tsnew file mode 100644index 000000000000..92f37ad2e81c--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.test.ts@@ -0,0 +1,59 @@+import { isDataWarehouseTableTriggerConfig } from './data_warehouse_table'+import { getRegisteredTriggerTypes } from './triggerTypeRegistry'++describe('data warehouse table trigger', () => {+ const getTriggerType = (): ReturnType<typeof getRegisteredTriggerTypes>[number] => {+ const triggerType = getRegisteredTriggerTypes().find((t) => t.value === 'data-warehouse-table')+ if (!triggerType) {+ throw new Error('Data warehouse table trigger type not registered')+ }+ return triggerType+ }++ describe('isDataWarehouseTableTriggerConfig', () => {+ it.each([+ {+ name: 'data-warehouse-table config',+ config: { type: 'data-warehouse-table', table_name: 'x' } as any,+ expected: true,+ },+ { name: 'event config', config: { type: 'event', filters: {} } as any, expected: false },+ { name: 'schedule config', config: { type: 'schedule' } as any, expected: false },+ ])('returns $expected for $name', ({ config, expected }) => {+ expect(isDataWarehouseTableTriggerConfig(config)).toBe(expected)+ })+ })++ describe('validate', () => {+ it.each([+ {+ name: 'missing table name',+ config: { type: 'data-warehouse-table', table_name: '', filters: { properties: [] } },+ expected: { valid: false, errors: { table_name: 'Please select a data warehouse table' } },+ },+ {+ name: 'table name set',+ config: { type: 'data-warehouse-table', table_name: 'postgres.table_1', filters: { properties: [] } },+ expected: { valid: true, errors: {} },+ },+ {+ name: 'non data-warehouse-table config returns null',+ config: { type: 'event', filters: {} },+ expected: null,+ },+ ])('returns $expected for $name', ({ config, expected }) => {+ expect(getTriggerType().validate!(config as any)).toEqual(expected)+ })+ })++ it('is gated behind the CDP_DWH_TABLE_SOURCE feature flag', () => {+ expect(getTriggerType().featureFlag).toBe('cdp-dwh-table-source')+ })++ it('buildConfig produces a config recognized by matchConfig', () => {+ const triggerType = getTriggerType()+ const config = triggerType.buildConfig()+ expect(config.type).toBe('data-warehouse-table')+ expect(triggerType.matchConfig!(config)).toBe(true)+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsxnew file mode 100644index 000000000000..b86e970f9910--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_table.tsx@@ -0,0 +1,130 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { IconServer } from '@posthog/icons'+import { LemonBanner, LemonSelect } from '@posthog/lemon-ui'++import { LemonField } from 'lib/lemon-ui/LemonField'+import { Link } from 'lib/lemon-ui/Link'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'+import { urls } from 'scenes/urls'++import { HogFlowPropertyFilters } from 'products/workflows/frontend/Workflows/hogflows/filters/HogFlowFilters'+import { registerTriggerType } from 'products/workflows/frontend/Workflows/hogflows/registry/triggers/triggerTypeRegistry'+import { workflowLogic } from 'products/workflows/frontend/Workflows/workflowLogic'++import { HogFlowAction } from '../../types'++export type DataWarehouseTableTriggerConfig = {+ type: 'data-warehouse-table'+ table_name: string+ filters: {+ properties?: any[]+ }+ key_property?: string+}++export function isDataWarehouseTableTriggerConfig(+ config: Extract<HogFlowAction, { type: 'trigger' }>['config']+): config is DataWarehouseTableTriggerConfig {+ return config.type === 'data-warehouse-table'+}++function StepTriggerConfigurationDataWarehouseTable({ node }: { node: any }): JSX.Element {+ const { setWorkflowActionConfig } = useActions(workflowLogic)+ const { actionValidationErrorsById } = useValues(workflowLogic)+ const { dataWarehouseTables, databaseLoading } = useValues(databaseTableListLogic)+ const { loadDatabase } = useActions(databaseTableListLogic)++ useEffect(() => {+ // The list isn't loaded automatically on mount, so kick it off when the panel opens.+ if (!dataWarehouseTables.length) {+ loadDatabase()+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ const config = node.data.config as DataWarehouseTableTriggerConfig+ const selectedTableName = config.table_name || null+ const properties = config.filters?.properties ?? []+ const validationResult = actionValidationErrorsById[node.data.id]+ const hasNoTables = !databaseLoading && dataWarehouseTables.length === 0++ const tableOptions = dataWarehouseTables.map((table) => ({+ label: table.name,+ value: table.name,+ }))++ const updateTriggerConfig = (tableName: string | null, newProperties: any[]): void => {+ setWorkflowActionConfig(node.data.id, {+ type: 'data-warehouse-table',+ table_name: tableName ?? '',+ filters: { properties: newProperties },+ // Preserve any existing masking/dedup key set via the API or a future UI+ ...(config.key_property ? { key_property: config.key_property } : {}),+ })+ }++ return (+ <div className="flex flex-col gap-2 w-full">+ <p className="mb-0 text-sm text-muted-alt">+ This workflow runs once for each new row synced into the selected data warehouse table. Runs are+ row-scoped — there is no associated person, so person-dependent steps are unavailable.+ </p>+ <LemonField.Pure label="Data warehouse table" error={validationResult?.errors?.table_name}>+ <LemonSelect+ options={tableOptions}+ value={selectedTableName}+ loading={databaseLoading}+ disabledReason={hasNoTables ? 'Sync a data warehouse source first' : undefined}+ onChange={(tableName) => updateTriggerConfig(tableName, properties)}+ placeholder="Select a table"+ />+ {hasNoTables && (+ <LemonBanner type="warning" className="w-full mt-1">+ <p className="mb-0">+ You don't have any data warehouse tables yet, so this trigger has nothing to listen to. Sync+ a source first, then come back and pick the table this workflow should run on.{' '}+ <Link to={urls.dataPipelinesNew('source')} target="_blank" className="font-semibold">+ Set up a source+ </Link>+ </p>+ </LemonBanner>+ )}+ </LemonField.Pure>++ <LemonField.Pure label="Only trigger for specific rows">+ <HogFlowPropertyFilters+ filtersKey={`data-warehouse-table-trigger-${node.data.id}`}+ filters={{ properties }}+ setFilters={(filters) => updateTriggerConfig(selectedTableName, filters?.properties ?? [])}+ />+ </LemonField.Pure>+ </div>+ )+}++registerTriggerType({+ value: 'data-warehouse-table',+ label: 'Data warehouse row synced',+ icon: <IconServer />,+ description: 'Trigger when a new row is synced into a data warehouse table',+ group: 'Data warehouse',+ featureFlag: 'cdp-dwh-table-source',+ matchConfig: (config) => isDataWarehouseTableTriggerConfig(config),+ buildConfig: () => ({+ type: 'data-warehouse-table',+ table_name: '',+ filters: { properties: [] },+ }),+ validate: (config): { valid: boolean; errors: Record<string, string> } | null => {+ if (config.type !== 'data-warehouse-table') {+ return null+ }+ if (!config.table_name) {+ return { valid: false, errors: { table_name: 'Please select a data warehouse table' } }+ }+ return { valid: true, errors: {} }+ },+ ConfigComponent: StepTriggerConfigurationDataWarehouseTable,+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.tsindex 38aa61e06dd1..451eb63cce82 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/index.ts@@ -1,2 +1,3 @@import './conversations'+import './data_warehouse_table'import './surveys'diff --git a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsxindex 842e66b60891..626ea104e66d 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx+++ b/products/workflows/frontend/Workflows/hogflows/steps/StepTrigger.tsx@@ -285,6 +285,10 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }const selectedItem = allTriggerItems.find((item) => item.value === displayType)+ // Registered trigger types (e.g. data warehouse) can own non-event configs, so resolve the+ // matching definition regardless of config.type and render its ConfigComponent below.+ const registeredMatch = getRegisteredTriggerTypes().find((t) => t.matchConfig?.(node.data.config))+const handleSelect = (value: string): void => {const registered = getRegisteredTriggerTypes().find((t) => t.value === value)if (registered) {@@ -336,14 +340,10 @@ export function StepTriggerConfiguration({ node }: { node: Node<TriggerAction> }</LemonField.Pure>{type === 'schedule' && <ScheduleStatusBadge />}</div>- {node.data.config.type === 'event' ? (- (() => {- const match = getRegisteredTriggerTypes().find((t) => t.matchConfig?.(node.data.config))- if (match?.ConfigComponent) {- return <match.ConfigComponent node={node} />- }- return <StepTriggerConfigurationEvents action={node.data} config={node.data.config} />- })()+ {registeredMatch?.ConfigComponent ? (+ <registeredMatch.ConfigComponent node={node} />+ ) : node.data.config.type === 'event' ? (+ <StepTriggerConfigurationEvents action={node.data} config={node.data.config} />) : node.data.config.type === 'webhook' ? (<StepTriggerConfigurationWebhook action={node.data} config={node.data.config} />) : node.data.config.type === 'manual' ? (diff --git a/products/workflows/frontend/Workflows/hogflows/steps/types.ts b/products/workflows/frontend/Workflows/hogflows/steps/types.tsindex 9c4b72a70ba6..19c3e5f4031e 100644--- a/products/workflows/frontend/Workflows/hogflows/steps/types.ts+++ b/products/workflows/frontend/Workflows/hogflows/steps/types.ts@@ -146,6 +146,15 @@ export const HogFlowTriggerSchema = z.discriminatedUnion('type', [properties: z.array(z.any()),}),}),+ z.object({+ type: z.literal('data-warehouse-table'),+ // Dot-notated table name matching the Python CDPProducer naming+ table_name: z.string(),+ filters: z.object({+ properties: z.array(z.any()).optional(),+ }),+ key_property: z.string().optional(),+ }),])/** Trigger types that use HogFlowSchedule for recurring execution */diff --git a/products/workflows/frontend/Workflows/workflowLogic.ts b/products/workflows/frontend/Workflows/workflowLogic.tsindex 55c553414e93..bd6e6fe51f7e 100644--- a/products/workflows/frontend/Workflows/workflowLogic.ts+++ b/products/workflows/frontend/Workflows/workflowLogic.ts@@ -103,6 +103,10 @@ export const NEW_WORKFLOW: HogFlow = {updated_at: '',}+// Step types that depend on person data and so cannot run for person-less (row-scoped)+// data-warehouse-table triggers. Module-scoped to avoid reallocating on every selector recompute.+export const PERSON_DEPENDENT_ACTION_TYPES = new Set(['wait_until_condition', 'random_cohort_branch'])+function getTemplatingError(value: string, templating?: 'liquid' | 'hog'): string | undefined {if (templating === 'liquid' && typeof value === 'string') {try {@@ -441,6 +445,12 @@ export const workflowLogic = kea<workflowLogicType>([hogFunctionTemplatesByIdLoading,scheduleStartsAt): Record<string, HogFlowActionValidationResult | null> => {+ // Warehouse-triggered workflows are person-less ("row-scoped"). Person-dependent+ // step types make no sense without a person, so we block them at save time.+ const triggerAction = workflow.actions.find((a) => a.type === 'trigger')+ const isRowScopedTrigger =+ triggerAction?.type === 'trigger' && triggerAction.config?.type === 'data-warehouse-table'+return workflow.actions.reduce((acc, action) => {const result: HogFlowActionValidationResult = {@@ -449,6 +459,17 @@ export const workflowLogic = kea<workflowLogicType>([errors: {},warnings: {},}++ if (isRowScopedTrigger && PERSON_DEPENDENT_ACTION_TYPES.has(action.type)) {+ result.valid = false+ result.errors = {+ _action:+ 'This step relies on person data, which is not available for data warehouse table triggers',+ }+ acc[action.id] = result+ return acc+ }+const schemaValidation = HogFlowActionSchema.safeParse(action)if (!schemaValidation.success) {@@ -577,6 +598,14 @@ export const workflowLogic = kea<workflowLogicType>([},],+ // Warehouse-triggered workflows are person-less ("row-scoped"): no person data is available,+ // so person-dependent steps and person-aware exit conditions are blocked (see the serializer+ // for the authoritative enforcement).+ isRowScopedTrigger: [+ (s) => [s.triggerAction],+ (triggerAction: TriggerAction | null): boolean => triggerAction?.config?.type === 'data-warehouse-table',+ ],+workflowSanitized: [(s) => [s.workflow, s.hogFunctionTemplatesById],(workflow, hogFunctionTemplatesById): HogFlow => {