Skip to content

: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.

feat(data-warehouse): let the CDP producer emit rows for a materialized view (#84415)

Tom Owers4bab962e5e9d
diff --git a/posthog/temporal/utils.py b/posthog/temporal/utils.py
index fd34cf3580bb..5d9bdbdd6656 100644
--- a/posthog/temporal/utils.py
+++ b/posthog/temporal/utils.py
@@ -24,16 +24,24 @@ class ExternalDataWorkflowInputs:
}
[email protected](frozen=True)
class CDPProducerWorkflowInputs:
+ """Which staged run to produce to Kafka.
+
+ Exactly one of `schema_id` (a source sync) or `saved_query_id` (a materialized view) is set.
+ Both are optional and defaulted so payloads written by an older worker stay decodable.
+ """
+
team_id: int
- schema_id: str
job_id: str
+ schema_id: str | None = None
+ saved_query_id: str | None = None
@property
def properties_to_log(self) -> dict[str, typing.Any]:
return {
"team_id": self.team_id,
"schema_id": self.schema_id,
+ "saved_query_id": self.saved_query_id,
"job_id": self.job_id,
}
diff --git a/products/warehouse_sources/backend/facade/pipelines.py b/products/warehouse_sources/backend/facade/pipelines.py
index 4fd8b7081c23..b97658519c5c 100644
--- a/products/warehouse_sources/backend/facade/pipelines.py
+++ b/products/warehouse_sources/backend/facade/pipelines.py
@@ -29,6 +29,7 @@ _LAZY = {
"start_health_server": "pipelines.pipeline_v3.load.health",
"ensure_bucket": "pipelines.pipeline_v3.s3.common",
"strip_s3_protocol": "pipelines.pipeline_v3.s3.common",
+ "CDPProducer": "pipelines.core.cdp_producer",
}
__all__ = sorted(_LAZY)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdp_producer_job.py b/products/warehouse_sources/backend/temporal/data_imports/cdp_producer_job.py
index 057cae226cb9..45ced6d5b5d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdp_producer_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdp_producer_job.py
@@ -26,10 +26,19 @@ async def produce_to_cdp_kafka_activity(inputs: CDPProducerWorkflowInputs) -> No
bind_contextvars(team_id=inputs.team_id)
logger = LOGGER.bind()
- try:
- await CDPProducer(
+ if inputs.saved_query_id is not None:
+ producer = CDPProducer.for_view(
+ team_id=inputs.team_id, saved_query_id=inputs.saved_query_id, job_id=inputs.job_id, logger=logger
+ )
+ elif inputs.schema_id is not None:
+ producer = CDPProducer.for_source(
team_id=inputs.team_id, schema_id=inputs.schema_id, job_id=inputs.job_id, logger=logger
- ).produce_to_kafka_from_s3()
+ )
+ else:
+ raise ValueError("CDP producer needs either a schema_id or a saved_query_id")
+
+ try:
+ await producer.produce_to_kafka_from_s3()
except Exception:
CDP_PRODUCER_RUNS_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
raise
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py
index 59610e7f69a4..a090afe9684b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py
@@ -1,5 +1,6 @@
import json
import uuid
+import typing
import asyncio
import hashlib
@@ -16,12 +17,14 @@ from structlog.types import FilteringBoundLogger
from posthog.hogql.database.database import get_data_warehouse_table_name
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from posthog.kafka_client.routing import KafkaClusterProfile, async_producer_scope
from posthog.kafka_client.topics import KAFKA_DWH_CDP_RAW_TABLE
from posthog.sync import database_sync_to_async_pool
from products.cdp.backend.models.hog_functions import HogFunction
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_exists
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_name
@@ -42,25 +45,55 @@ CDP_PRODUCER_ROWS_TOTAL = Counter(
labelnames=["team_id"],
)
+TableKind = typing.Literal["source", "view"]
+
+# Trigger identifiers a HogFunction's `filters.source` or a HogFlow's `trigger.type` carries,
+# keyed by the kind of warehouse table the rows came from.
+TRIGGER_SOURCE_BY_KIND: dict[TableKind, str] = {
+ "source": "data-warehouse-table",
+ "view": "data-warehouse-view",
+}
+
+
+@frozen
+class CDPTriggerTable:
+ """The warehouse table a producer run emits rows for.
+
+ A source-synced table is identified by its ExternalDataSchema, a materialized view by its
+ DataWarehouseSavedQuery. The two share every step after this — the staging area, the Kafka
+ topic, the consumer — so they differ only in how the table's name and subscribers resolve.
+ """
+
+ kind: TableKind
+ id: str
+
class CDPProducer:
team_id: int
- schema_id: str
+ table: CDPTriggerTable
job_id: str
logger: FilteringBoundLogger
_should_run_cache: bool | None
_table_name_cache: str | None
_fs_cache: pa_fs.S3FileSystem | None
- def __init__(self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger) -> None:
+ def __init__(self, team_id: int, table: CDPTriggerTable, job_id: str, logger: FilteringBoundLogger) -> None:
self.team_id = team_id
- self.schema_id = schema_id
+ self.table = table
self.job_id = job_id
self.logger = logger
self._should_run_cache = None
self._table_name_cache = None
self._fs_cache = None
+ @classmethod
+ def for_source(cls, *, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger) -> "CDPProducer":
+ return cls(team_id, CDPTriggerTable(kind="source", id=schema_id), job_id, logger)
+
+ @classmethod
+ def for_view(cls, *, team_id: int, saved_query_id: str, job_id: str, logger: FilteringBoundLogger) -> "CDPProducer":
+ return cls(team_id, CDPTriggerTable(kind="view", id=saved_query_id), job_id, logger)
+
def _get_fs(self) -> pa_fs.S3FileSystem:
# Cached per instance: stage_chunk() calls this once per chunk, and a producer lives for
# a whole sync (potentially thousands of chunks). A fresh S3FileSystem per call opens its
@@ -88,7 +121,10 @@ class CDPProducer:
return self._fs_cache
def _get_path_prefix(self) -> str:
- return f"{settings.DATAWAREHOUSE_BUCKET}/cdp_producer/{self.team_id}/{self.schema_id}/{self.job_id}"
+ # Views get their own middle segment so the two kinds never share a prefix and the source
+ # layout stays exactly what it was.
+ segment = self.table.id if self.table.kind == "source" else f"view_{self.table.id}"
+ return f"{settings.DATAWAREHOUSE_BUCKET}/cdp_producer/{self.team_id}/{segment}/{self.job_id}"
async def _list_files_to_produce(self) -> list[str]:
async with aget_s3_client() as s3_client:
@@ -102,7 +138,10 @@ class CDPProducer:
def _serialize_json(self, record: object, *, sort_keys: bool = False) -> bytes:
try:
- return orjson.dumps(record, option=orjson.OPT_SORT_KEYS if sort_keys else None)
+ # `default=str` covers Decimal, which orjson refuses natively and which materialized
+ # view aggregates produce routinely. Without it the fallback below stringifies every
+ # value in the row, not just the offending one.
+ return orjson.dumps(record, default=str, option=orjson.OPT_SORT_KEYS if sort_keys else None)
except TypeError:
try:
return json.dumps(record, sort_keys=sort_keys).encode("utf-8")
@@ -119,7 +158,13 @@ class CDPProducer:
@database_sync_to_async_pool
def _resolve() -> str:
- schema = ExternalDataSchema.objects.get(id=self.schema_id, team_id=self.team_id)
+ if self.table.kind == "view":
+ # A saved query's name is already the name it is queryable by in HogQL.
+ return DataWarehouseSavedQuery.objects.values_list("name", flat=True).get(
+ id=self.table.id, team_id=self.team_id
+ )
+
+ schema = ExternalDataSchema.objects.get(id=self.table.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)
@@ -127,32 +172,60 @@ class CDPProducer:
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.
+ """Build a deterministic event id for a row.
+
+ The row is hashed with sorted keys, so the id is stable for identical row data and changes
+ whenever the data changes.
- The row is hashed (sorted keys so re-runs of the same job produce the same hash)
- and combined with the job id, so the id is stable for the same row + job but
- changes whenever the row's data changes.
+ A source sync also mixes in the job id: the same row arriving in a later sync is a new
+ delivery. A materialized view does not, because its incremental filter is inclusive of the
+ watermark — the rows on the boundary are recomputed and re-emitted on every run without
+ having changed. Keying those on content alone lets a destination recognize the repeat.
"""
row_hash = hashlib.sha256(self._serialize_json(row, sort_keys=True)).hexdigest()
- return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{self.job_id}:{row_hash}"))
+ scope = self.table.id if self.table.kind == "view" else self.job_id
+ return str(uuid.uuid5(uuid.NAMESPACE_OID, f"{scope}:{row_hash}"))
+
+ def _view_can_trigger(self) -> bool:
+ """Only a user-created, materialized saved query can drive a trigger.
+
+ Endpoints carry a version suffix (`name_v1`), so a trigger's stored name would break on
+ every version bump, and managed viewsets are generated by other products rather than chosen
+ by the user.
+ """
+ return (
+ DataWarehouseSavedQuery.objects.filter(
+ id=self.table.id,
+ team_id=self.team_id,
+ is_materialized=True,
+ is_test=False,
+ origin=DataWarehouseSavedQuery.Origin.DATA_WAREHOUSE,
+ )
+ .exclude(deleted=True)
+ .exists()
+ )
async def should_run(self) -> bool:
if self._should_run_cache is not None:
return self._should_run_cache
dot_notated_table_name = await self.get_dot_notated_table_name()
+ trigger_source = TRIGGER_SOURCE_BY_KIND[self.table.kind]
@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")
+ self.logger.debug(f"Using table_name = {dot_notated_table_name}, source = {trigger_source}")
try:
+ if self.table.kind == "view" and not self._view_can_trigger():
+ return False
+
has_matching_hog_function = (
HogFunction.objects.filter(
team_id=self.team_id,
enabled=True,
- filters__source="data-warehouse-table",
+ filters__source=trigger_source,
filters__data_warehouse__contains=[{"table_name": dot_notated_table_name}],
)
.exclude(deleted=True)
@@ -167,7 +240,7 @@ class CDPProducer:
return HogFlow.objects.filter(
team_id=self.team_id,
status=HogFlow.State.ACTIVE,
- trigger__type="data-warehouse-table",
+ trigger__type=trigger_source,
trigger__table_name=dot_notated_table_name,
).exists()
except (DjangoOperationalError, OSError) as e:
@@ -198,9 +271,14 @@ class CDPProducer:
except FileNotFoundError:
pass
- async def stage_chunk(self, chunk: int, table: pa.Table) -> None:
+ async def stage_chunk(self, chunk: int, table: pa.Table | pa.RecordBatch) -> None:
await self.logger.adebug(f"Writing chunk {chunk} for CDP producer to S3 path prefix {self._get_path_prefix()}")
+ # The import pipeline hands over tables, the data modeling activity record batches. Normalize
+ # here so neither call site has to know what parquet writing wants. from_batches is zero-copy.
+ if isinstance(table, pa.RecordBatch):
+ table = pa.Table.from_batches([table])
+
# Write operations in pyarrow are CPU-bound, so run in thread pool
await asyncio.to_thread(
write_table,
@@ -217,7 +295,7 @@ 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.
+ # destinations and workflows against their configured table without an extra lookup.
dot_notated_table_name = await self.get_dot_notated_table_name()
files_to_produce = await self._list_files_to_produce()
@@ -239,6 +317,7 @@ class CDPProducer:
row_as_props = {
"team_id": self.team_id,
"table_name": dot_notated_table_name,
+ "table_type": self.table.kind,
"event_id": self._build_event_id(row),
"properties": row,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py
index 23c1de516500..10bbfcd8a1f1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py
@@ -64,7 +64,7 @@ def build_pipeline_sinks(
A new publisher becomes one entry here instead of new constructor blocks and call
sites in each pipeline.
"""
- cdp_producer = CDPProducer(team_id=team_id, schema_id=schema_id, job_id=job_id, logger=logger)
+ cdp_producer = CDPProducer.for_source(team_id=team_id, schema_id=schema_id, job_id=job_id, logger=logger)
person_property_sink = PersonPropertyRowSink(
team_id=team_id,
binding=schema_binding(schema_id),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py
index ca1bf3afd688..e62180a28d88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py
@@ -1,6 +1,7 @@
import json
import uuid
from contextlib import asynccontextmanager
+from decimal import Decimal
from io import BytesIO
import pytest
@@ -16,6 +17,7 @@ from asgiref.sync import sync_to_async
from parameterized import parameterized
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
@@ -52,7 +54,7 @@ async def test_should_run_no_hog_function(team):
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is False
@@ -75,7 +77,7 @@ async def test_should_run_with_matching_hog_function(team):
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -98,7 +100,7 @@ async def test_should_not_produce_table_with_disabled_matching_hog_function(team
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is False
@@ -122,7 +124,7 @@ async def test_should_not_produce_table_with_deleted_matching_hog_function(team)
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is False
@@ -145,7 +147,7 @@ async def test_should_run_with_new_style_table_name(team):
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -168,7 +170,7 @@ async def test_should_run_with_source_prefix(team):
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.eu.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -191,7 +193,7 @@ async def test_should_run_with_leading_underscore_source_prefix(team):
filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "postgres.eu.table_1"}]},
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -214,7 +216,7 @@ async def test_should_run_with_matching_hog_flow(team):
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())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -237,7 +239,7 @@ async def test_should_not_produce_table_with_draft_hog_flow(team):
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())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is False
@@ -260,7 +262,7 @@ async def test_should_not_produce_table_with_non_matching_hog_flow_table(team):
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())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is False
@@ -288,7 +290,7 @@ async def test_should_run_with_both_hog_function_and_flow(team):
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())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
assert await producer.should_run() is True
@@ -322,7 +324,7 @@ async def test_should_run_posthog_database_connection_failure_stays_retryable(
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
with patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.HogFunction.objects"
@@ -373,7 +375,9 @@ async def test_produce_to_kafka_from_s3_includes_table_name(mock_get_s3_client,
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())
+ producer = CDPProducer.for_source(
+ 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),
@@ -426,7 +430,9 @@ async def test_produce_to_kafka_from_s3_success(mock_get_s3_client, team):
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())
+ producer = CDPProducer.for_source(
+ 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),
@@ -476,7 +482,9 @@ async def test_produce_to_kafka_from_s3_with_no_files(mock_get_s3_client, team):
mock_kafka_producer.close = mock.AsyncMock()
mock_fs = MagicMock()
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ 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),
@@ -524,7 +532,9 @@ async def test_produce_to_kafka_from_s3_kafka_failure(mock_capture_exception, mo
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())
+ producer = CDPProducer.for_source(
+ 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),
@@ -565,7 +575,9 @@ async def test_produce_to_kafka_from_s3_s3_read_failure(mock_capture_exception,
mock_fs.open_input_file.side_effect = Exception("S3 read failed")
mock_fs.delete_file = MagicMock()
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ 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),
@@ -614,7 +626,9 @@ async def test_produce_to_kafka_from_s3_with_large_batch(mock_get_s3_client, tea
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())
+ producer = CDPProducer.for_source(
+ 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),
@@ -643,7 +657,9 @@ async def test_stage_chunk(team):
mock_fs = MagicMock()
test_data = pa.table({"id": [1, 2, 3], "name": ["Alice", "Bob", "Charlie"]})
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
with patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.write_table"
@@ -676,7 +692,9 @@ async def test_stage_chunk_with_empty_table(team):
mock_fs = MagicMock()
test_data = pa.table({"id": [], "name": []})
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
with patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.write_table"
@@ -709,7 +727,9 @@ async def test_clear_with_files(mock_get_s3_client, team):
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)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
await producer.clear()
@@ -735,7 +755,9 @@ async def test_clear_with_no_files(mock_get_s3_client, team):
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)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
await producer.clear()
@@ -764,7 +786,9 @@ async def test_clear_handles_file_not_found_on_delete(mock_get_s3_client, team):
mock_fs = MagicMock()
mock_fs.delete_dir.side_effect = FileNotFoundError()
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ 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):
await producer.clear()
@@ -783,7 +807,9 @@ async def test_serialize_json_with_orjson_success(team):
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
record = {"id": 1, "name": "Alice", "score": 95.5}
result = producer._serialize_json(record)
@@ -805,7 +831,9 @@ async def test_serialize_json_fallback_to_standard_json(team):
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
class CustomObject:
def __str__(self):
@@ -838,7 +866,9 @@ async def test_serialize_json_fallback_with_stringify(team):
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
class UnserializableKey:
def __str__(self):
@@ -874,7 +904,9 @@ async def test_serialize_json_raises_on_non_dict_unsupported(team):
team=team, name="table_1", source=source, table=table
)
- producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
+ producer = CDPProducer.for_source(
+ team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock()
+ )
class CompletelyUnserializable:
pass
@@ -890,7 +922,11 @@ async def test_serialize_json_raises_on_non_dict_unsupported(team):
def _make_producer(job_id: str) -> CDPProducer:
- return CDPProducer(team_id=1, schema_id="schema_1", job_id=job_id, logger=mock.AsyncMock())
+ return CDPProducer.for_source(team_id=1, schema_id="schema_1", job_id=job_id, logger=mock.AsyncMock())
+
+
+def _make_view_producer(job_id: str) -> CDPProducer:
+ return CDPProducer.for_view(team_id=1, saved_query_id="view_1", job_id=job_id, logger=mock.AsyncMock())
@parameterized.expand([("local_setup", True), ("non_local_setup", False)])
@@ -950,3 +986,185 @@ def test_build_event_id_changes_when_row_data_changes(row_a, row_b):
def test_build_event_id_changes_with_job_id():
row = {"id": 1, "name": "Alice"}
assert _make_producer("job_1")._build_event_id(row) != _make_producer("job_2")._build_event_id(row)
+
+
+def test_build_event_id_for_a_view_is_the_same_across_runs():
+ # A view's incremental filter is inclusive of the watermark, so the boundary rows come back
+ # unchanged on every run. Keying those on content alone is what lets a destination tell a
+ # repeat from a genuine change.
+ row = {"id": 1, "name": "Alice"}
+ assert _make_view_producer("job_1")._build_event_id(row) == _make_view_producer("job_2")._build_event_id(row)
+
+
+def test_build_event_id_for_a_view_still_changes_with_the_row():
+ producer = _make_view_producer("job_1")
+ assert producer._build_event_id({"id": 1}) != producer._build_event_id({"id": 2})
+
+
+def test_serialize_json_keeps_other_fields_when_a_value_is_a_decimal():
+ # Materialized view aggregates produce Decimals, which orjson refuses natively. The fallback
+ # path stringifies every value in the row, so only the Decimal itself may degrade.
+ serialized = _make_view_producer("job_1")._serialize_json({"id": 1, "amount": Decimal("10.50")})
+ assert json.loads(serialized) == {"id": 1, "amount": "10.50"}
+
+
+async def _create_view(team, **overrides) -> DataWarehouseSavedQuery:
+ fields = {
+ "team": team,
+ "name": "daily_revenue",
+ "query": {"kind": "HogQLQuery", "query": "select 1"},
+ "is_materialized": True,
+ "origin": DataWarehouseSavedQuery.Origin.DATA_WAREHOUSE,
+ **overrides,
+ }
+ return await sync_to_async(DataWarehouseSavedQuery.objects.create)(**fields)
+
+
+def _view_producer_for(view: DataWarehouseSavedQuery) -> CDPProducer:
+ return CDPProducer.for_view(
+ team_id=view.team_id, saved_query_id=str(view.id), job_id="test_job", logger=mock.AsyncMock()
+ )
+
+
[email protected]_db(transaction=True)
+async def test_view_should_run_with_matching_hog_function(team):
+ view = await _create_view(team)
+ await sync_to_async(HogFunction.objects.create)(
+ team=team,
+ enabled=True,
+ filters={"source": "data-warehouse-view", "data_warehouse": [{"table_name": "daily_revenue"}]},
+ )
+
+ assert await _view_producer_for(view).should_run() is True
+
+
[email protected]_db(transaction=True)
+async def test_view_should_run_with_matching_hog_flow(team):
+ view = await _create_view(team)
+ await sync_to_async(HogFlow.objects.create)(
+ team=team,
+ name="test workflow",
+ status=HogFlow.State.ACTIVE,
+ trigger={"type": "data-warehouse-view", "table_name": "daily_revenue"},
+ edges=[],
+ actions=[],
+ )
+
+ assert await _view_producer_for(view).should_run() is True
+
+
[email protected]_db(transaction=True)
+async def test_view_does_not_match_a_source_table_subscriber_of_the_same_name(team):
+ # A view's name and a source table's dot-notated name share one namespace, so the trigger type
+ # is the only thing keeping the two apart.
+ view = await _create_view(team)
+ await sync_to_async(HogFunction.objects.create)(
+ team=team,
+ enabled=True,
+ filters={"source": "data-warehouse-table", "data_warehouse": [{"table_name": "daily_revenue"}]},
+ )
+
+ assert await _view_producer_for(view).should_run() is False
+
+
[email protected]_db(transaction=True)
+async def test_source_table_does_not_match_a_view_subscriber_of_the_same_name(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-view", "data_warehouse": [{"table_name": "postgres.table_1"}]},
+ )
+
+ producer = CDPProducer.for_source(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
+ assert await producer.should_run() is False
+
+
[email protected]_db(transaction=True)
+ "overrides",
+ [
+ {"is_materialized": False},
+ {"origin": DataWarehouseSavedQuery.Origin.ENDPOINT},
+ {"origin": DataWarehouseSavedQuery.Origin.MANAGED_VIEWSET},
+ {"is_test": True},
+ {"deleted": True},
+ ],
+)
+async def test_ineligible_views_never_produce(team, overrides):
+ view = await _create_view(team, **overrides)
+ await sync_to_async(HogFunction.objects.create)(
+ team=team,
+ enabled=True,
+ filters={"source": "data-warehouse-view", "data_warehouse": [{"table_name": "daily_revenue"}]},
+ )
+
+ assert await _view_producer_for(view).should_run() is False
+
+
[email protected]_db(transaction=True)
+async def test_view_table_name_is_the_saved_query_name(team):
+ view = await _create_view(team, name="my_view")
+ assert await _view_producer_for(view).get_dot_notated_table_name() == "my_view"
+
+
[email protected]_db(transaction=True)
+@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")
+async def test_produce_to_kafka_from_s3_marks_view_rows(mock_get_s3_client, team):
+ view = await _create_view(team, name="my_view")
+
+ mock_s3_client = MagicMock()
+ mock_s3_client._ls = mock.AsyncMock(return_value=[{"Key": "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=None)
+
+ mock_kafka_producer = MagicMock()
+ mock_kafka_producer.produce = mock.AsyncMock()
+ mock_kafka_producer.flush = mock.AsyncMock()
+ mock_kafka_producer.close = mock.AsyncMock()
+
+ parquet_buffer = BytesIO()
+ pq.write_table(pa.table({"id": [1]}), 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 = _view_producer_for(view)
+
+ with (
+ patch.object(producer, "_get_fs", return_value=mock_fs),
+ _patch_async_producer_scope(mock_kafka_producer),
+ ):
+ await producer.produce_to_kafka_from_s3()
+
+ data = mock_kafka_producer.produce.call_args_list[0][1]["data"]
+ assert data["table_name"] == "my_view"
+ assert data["table_type"] == "view"
+
+
+def test_staging_paths_never_collide_between_a_schema_and_a_view_of_the_same_id():
+ shared_id = "11111111-1111-1111-1111-111111111111"
+ source = CDPProducer.for_source(team_id=1, schema_id=shared_id, job_id="job", logger=mock.AsyncMock())
+ view = CDPProducer.for_view(team_id=1, saved_query_id=shared_id, job_id="job", logger=mock.AsyncMock())
+
+ assert source._get_path_prefix() != view._get_path_prefix()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
index 7731a03f423b..e36cb4a0fdb4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_end_to_end.py
@@ -4136,6 +4136,7 @@ async def test_cdp_producer_push_to_kafka(team, stripe_customer, mock_stripe_cli
assert {key: value for key, value in data.items() if key != "event_id"} == {
"team_id": team.id,
"table_name": "stripe.customer",
+ "table_type": "source",
"properties": expected_properties,
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_cdp_producer_job.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_cdp_producer_job.py
new file mode 100644
index 000000000000..a5665be58e97
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_cdp_producer_job.py
@@ -0,0 +1,14 @@
+import pytest
+
+from posthog.temporal.utils import CDPProducerWorkflowInputs
+
+from products.warehouse_sources.backend.temporal.data_imports.cdp_producer_job import produce_to_cdp_kafka_activity
+
+
[email protected]_db(transaction=True)
+async def test_produce_to_cdp_kafka_activity_requires_a_schema_or_saved_query(team):
+ inputs = CDPProducerWorkflowInputs(team_id=team.id, job_id="job-id", schema_id=None, saved_query_id=None)
+
+ with pytest.raises(ValueError, match="CDP producer needs either a schema_id or a saved_query_id"):
+ await produce_to_cdp_kafka_activity(inputs)