:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): stop a view row triggering a workflow every sync (#104309)
posthog[bot]bef8c6179038
diff --git a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsxindex 218806958b44..4d17a978edc6 100644--- a/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx+++ b/frontend/src/scenes/hog-functions/filters/HogFunctionFilters.tsx@@ -387,9 +387,10 @@ export function HogFunctionFilters({{selectedFullRefreshView ? (<LemonBanner type="warning" className="w-full"><p className="mb-0">- This view rebuilds its whole table on every run, so every row runs this- destination again each time. Set the view to update incrementally to run- only on the rows that changed.{' '}+ This view rebuilds its whole table on every run. A row runs this+ destination again only if its values changed since the last run. In a+ view with more than 200,000 rows, the rows past that limit run it again+ each time. Set the view to update incrementally to avoid this.{' '}<Linkto={urls.sqlEditor({ view_id: selectedFullRefreshView.id })}target="_blank"diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_emitted_rows.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_emitted_rows.pynew file mode 100644index 000000000000..cb8270b3e63f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_emitted_rows.py@@ -0,0 +1,184 @@+"""Remember which view rows a run already produced, so an unchanged row triggers only once.++A materialized view's incremental window is inclusive of the previous run's watermark, so the rows+on the boundary are recomputed and read again on every run without having changed. Each of those+rows reaches ``CDPProducer``, which is what starts a subscribed workflow or destination, so a+workflow that sends a message sends it again every sync period.++The producer already keys a view row's event id on row content alone, which makes an unchanged row+recognizable across runs. This store keeps the ids a view produced and suppresses the repeats.++The record is one Redis set per view, replaced on each run. It holds the ids this run produced plus+the ids this run suppressed, so a row that keeps coming back stays suppressed for as long as it+does, and a row that stops coming back drops out after one run.++Two runs of the same view can overlap, because the producer workflow is keyed on the job rather+than the view, and only same-schedule runs take ``ScheduleOverlapPolicy.SKIP``. Both then read the+same record and the later commit replaces the earlier one's ids. That costs a repeat trigger on a+later run, which is the behavior this store removes, and never a dropped one: an id is only ever+suppressed because an earlier run produced it. Serializing the load through the commit would mean+holding a lock across the whole produce loop, which runs for as long as the rows take to reach+Kafka, and a lock that expires under that would give the same interleaving with more to go wrong.+"""++import asyncio+from itertools import batched+from typing import Any++from prometheus_client import Counter+from structlog.types import FilteringBoundLogger++from posthog.redis import get_async_client++CDP_PRODUCER_ROWS_SUPPRESSED_TOTAL = Counter(+ "warehouse_cdp_producer_rows_suppressed_total",+ "Warehouse view rows not produced because a previous run produced the identical row",+ labelnames=["team_id"],+)++# A row only has to stay remembered from one run of its view to the next. The longest cadence a view+# can take is 30day, which runs monthly, so two runs can be 31 days apart plus schedule jitter. 35+# days covers that with room for a run that is late or retried. Each run replaces the record, so a+# longer lifetime only keeps the record of a view that stopped running for longer.+EMITTED_ROWS_TTL_SECONDS = 35 * 24 * 60 * 60++# Above this, the run stops recording, and the rows it did not record trigger again on the next run.+# The record keeps the first rows a run sees, so a view that stays past the limit repeats the rows+# past it on every run. Suppression is best effort, like the rest of this path, and a view large+# enough to pass the limit must not be able to grow one Redis key without bound.+MAX_TRACKED_ROWS = 200_000++# Kept well under Redis' argument limit, so a large run cannot build a command the server rejects.+_WRITE_CHUNK_SIZE = 1_000+++def emitted_rows_key(team_id: int, saved_query_id: str) -> str:+ # The braces are a Redis Cluster hash tag. commit() renames a scratch key onto this one inside a+ # transaction, and on a cluster that fails with CROSSSLOT unless both keys hash to the same slot.+ return f"cdp_produced_view_rows:{{{team_id}:{saved_query_id}}}"+++class EmittedRowStore:+ """The event ids a view produced on its previous run.++ Fail-open by design: a Redis problem disables suppression for the run, which costs a repeated+ trigger. Failing closed would drop a real one.+ """++ def __init__(self, key: str | None, logger: FilteringBoundLogger) -> None:+ self._key = key+ self._logger = logger+ self._previous: set[str] = set()+ self._current: set[str] = set()+ self._pending_deliveries: list[tuple[str, asyncio.Future[Any]]] = []+ self._enabled = key is not None+ self._at_limit = False++ async def load(self) -> None:+ if not self._enabled:+ return++ try:+ members = await get_async_client().smembers(self._key)+ self._previous = {member.decode() if isinstance(member, bytes) else member for member in members}+ except Exception as e:+ self._enabled = False+ await self._logger.awarning(f"Could not read produced view rows; not suppressing repeats this run: {e}")++ def is_repeat(self, event_id: str) -> bool:+ """Whether a previous run already produced this exact row.++ A repeat is recorded now: an earlier run delivered it, and keeping it in the record is what+ holds a row on the boundary suppressed across many runs. A row that is not a repeat is+ recorded only once Kafka confirms its delivery, through record_on_delivery, so a row no+ subscriber received is not remembered as delivered.+ """+ if not self._enabled:+ return False++ if event_id in self._previous:+ self._track(event_id)+ return True++ return False++ def record_on_delivery(self, event_id: str, delivery: asyncio.Future[Any]) -> None:+ """Hold a produced row until record_delivered reads its delivery result.++ produce() only queues the row. Kafka reports a failed delivery later, on this future, so a+ row recorded at produce time could be one that no subscriber received.+ """+ if not self._enabled:+ return++ self._pending_deliveries.append((event_id, delivery))++ def record_settled(self) -> None:+ """Record the held rows whose delivery Kafka confirmed so far, and keep the rest held.++ Call it between the batches of a file. A delivered row's future keeps the row's serialized+ payload, and one file can hold millions of rows, so holding every future until the file is+ flushed can run the worker out of memory. A row still in flight stays held for a later call.+ """+ in_flight: list[tuple[str, asyncio.Future[Any]]] = []+ for event_id, delivery in self._pending_deliveries:+ if not delivery.done():+ in_flight.append((event_id, delivery))+ elif not delivery.cancelled() and delivery.exception() is None:+ self.record_produced(event_id)+ self._pending_deliveries = in_flight++ def record_delivered(self) -> None:+ """Record the held rows whose delivery Kafka confirmed, and drop the rest.++ Call it after a file's rows are flushed, or after the file fails. A row with no confirmed+ delivery at that point is not recorded, so the worst case is one more trigger next run.+ """+ self.record_settled()+ self._pending_deliveries.clear()++ def record_produced(self, event_id: str) -> None:+ """Remember a row this run delivered."""+ if not self._enabled:+ return++ self._track(event_id)++ def _track(self, event_id: str) -> None:+ if len(self._current) < MAX_TRACKED_ROWS:+ self._current.add(event_id)+ else:+ self._at_limit = True++ async def commit(self) -> None:+ """Replace the record with what this run saw.++ Written to a scratch key and renamed, so a failure part way through leaves the previous+ run's record in place instead of a half-written one.+ """+ if not self._enabled:+ return++ if self._at_limit:+ await self._logger.awarning(+ f"More than {MAX_TRACKED_ROWS} view rows in one run; rows past that may trigger again next run"+ )++ try:+ client = get_async_client()+ if not self._current:+ await client.delete(self._key)+ return++ scratch_key = f"{self._key}:writing"+ # One flush rather than a round trip per chunk, which at the tracked-row limit would be+ # hundreds of them at the end of every run.+ pipeline = client.pipeline(transaction=True)+ pipeline.delete(scratch_key)+ for chunk in batched(self._current, _WRITE_CHUNK_SIZE, strict=False):+ pipeline.sadd(scratch_key, *chunk)+ pipeline.expire(scratch_key, EMITTED_ROWS_TTL_SECONDS)+ pipeline.rename(scratch_key, self._key)+ await pipeline.execute()+ except Exception as e:+ await self._logger.awarning(f"Could not record produced view rows; repeats may not be suppressed: {e}")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.pyindex e5dc720ce7c9..81d34286eec4 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@@ -27,6 +27,11 @@ from products.cdp.backend.models.hog_functions import HogFunctionfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_emitted_rows import (+ CDP_PRODUCER_ROWS_SUPPRESSED_TOTAL,+ EmittedRowStore,+ emitted_rows_key,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (aretry_staged_write,)@@ -190,8 +195,9 @@ class CDPProducer:A source sync also mixes in the job id: the same row arriving in a later sync is a newdelivery. 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.+ watermark — the rows on the boundary are recomputed and read again on every run without+ having changed. Keying those on content alone is what lets EmittedRowStore recognize the+ repeat and hold it back, and a destination recognize one that still gets through."""row_hash = hashlib.sha256(self._serialize_json(row, sort_keys=True)).hexdigest()scope = self.table.id if self.table.kind == "view" else self.job_id@@ -305,6 +311,16 @@ class CDPProducer:logger=self.logger,)+ def _build_emitted_row_store(self) -> EmittedRowStore:+ """Repeat suppression only applies to a view.++ A source sync mixes the job id into every event id, so the same row in a later sync is a+ new delivery and never a repeat. Leaving the source path clear of Redis also keeps the+ high-volume path as it was.+ """+ key = emitted_rows_key(self.team_id, self.table.id) if self.table.kind == "view" else None+ return EmittedRowStore(key, self.logger)+async def produce_to_kafka_from_s3(self) -> None:fs = self._get_fs()@@ -318,6 +334,10 @@ class CDPProducer:await self.logger.adebug(f"Found {len(files_to_produce)} files to produce to Kafka")+ emitted_rows = self._build_emitted_row_store()+ await emitted_rows.load()+ suppressed_rows = 0+async with async_producer_scope(profile=KafkaClusterProfile.CYCLOTRON) as kafka_producer:for file_path in files_to_produce:await self.logger.adebug(f"Producing file {file_path} to Kafka")@@ -330,20 +350,28 @@ class CDPProducer:for batch in pf.iter_batches(batch_size=10_000):for row in batch.to_pylist():+ event_id = self._build_event_id(row)+ if emitted_rows.is_repeat(event_id):+ suppressed_rows += 1+ continue+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),+ "event_id": event_id,"properties": row,}- await kafka_producer.produce(+ delivery = await kafka_producer.produce(topic=KAFKA_DWH_CDP_RAW_TABLE,data=row_as_props,value_serializer=self._serialize_json,)+ emitted_rows.record_on_delivery(event_id, delivery)row_index += 1+ emitted_rows.record_settled()+await kafka_producer.flush()CDP_PRODUCER_FILES_TOTAL.labels(team_id=str(self.team_id), outcome="produced").inc()await self.logger.adebug(f"Finished producing file {file_path} to Kafka")@@ -352,6 +380,9 @@ class CDPProducer:capture_exception(e)await self.logger.adebug(f"Error producing file {file_path} to Kafka: {e}")finally:+ # A row is remembered only once Kafka confirms it, or the next run would+ # suppress a row that no subscriber received.+ emitted_rows.record_delivered()# TODO(Gilbert09): have better row tracking so we can retry from a particular rowif row_index:CDP_PRODUCER_ROWS_TOTAL.labels(team_id=str(self.team_id)).inc(row_index)@@ -360,3 +391,9 @@ class CDPProducer:await asyncio.to_thread(fs.delete_file, file_path)await self.logger.adebug("Finished producing all CDP data to Kafka")++ if suppressed_rows:+ CDP_PRODUCER_ROWS_SUPPRESSED_TOTAL.labels(team_id=str(self.team_id)).inc(suppressed_rows)+ await self.logger.ainfo(f"Suppressed {suppressed_rows} unchanged rows an earlier run already produced")++ await emitted_rows.commit()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.pyindex cb149d02a405..959fdfd6f5d6 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,5 +1,6 @@import jsonimport uuid+import asynciofrom contextlib import asynccontextmanagerfrom decimal import Decimalfrom io import BytesIO@@ -15,12 +16,19 @@ import pyarrow as paimport pyarrow.parquet as pqfrom asgiref.sync import sync_to_asyncfrom parameterized import parameterized+from redis.crc import key_slot++from posthog.redis import get_async_clientfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom 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.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_emitted_rows import (+ EmittedRowStore,+ emitted_rows_key,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducerfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (ObjectStoreConfigurationError,@@ -1245,3 +1253,199 @@ def test_staging_paths_never_collide_between_a_schema_and_a_view_of_the_same_id(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()+++def _producer_with_known_table_name(producer: CDPProducer) -> CDPProducer:+ """Prime the table-name cache so a produce cycle needs no database."""+ producer._table_name_cache = "my_view"+ return producer+++async def _produce_staged_rows(+ producer: CDPProducer,+ rows: list[dict],+ *,+ produce_raises: bool = False,+ delivery_fails: bool = False,+ delivery_settles_on_flush: bool = False,+) -> list[dict]:+ """Stage `rows` as one chunk, run a whole produce cycle, and return the rows it produced.++ With `produce_raises`, the Kafka produce raises on every call. With `delivery_fails`, the produce+ returns a delivery that Kafka later reports as failed, the way a real produce does. With+ `delivery_settles_on_flush`, Kafka confirms a delivery only when the producer flushes, the way it+ does for the rows still in flight at the end of a file.+ """+ parquet_buffer = BytesIO()+ pq.write_table(pa.Table.from_pylist(rows), parquet_buffer, compression="zstd")+ parquet_buffer.seek(0)++ mock_s3_client = MagicMock()+ mock_s3_client._ls = mock.AsyncMock(return_value=[{"Key": "chunk_0.parquet", "type": "file"}])++ in_flight: list[asyncio.Future[None]] = []++ def _delivery(**_kwargs: object) -> asyncio.Future[None]:+ delivery: asyncio.Future[None] = asyncio.get_running_loop().create_future()+ if delivery_fails:+ delivery.set_exception(Exception("Message timed out"))+ elif delivery_settles_on_flush:+ in_flight.append(delivery)+ else:+ delivery.set_result(None)+ return delivery++ async def _flush() -> None:+ for delivery in in_flight:+ delivery.set_result(None)++ mock_kafka_producer = MagicMock()+ mock_kafka_producer.produce = mock.AsyncMock(+ side_effect=Exception("Kafka connection failed") if produce_raises else _delivery+ )+ mock_kafka_producer.flush = mock.AsyncMock(side_effect=_flush)+ mock_kafka_producer.close = mock.AsyncMock()++ 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()++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client"+ ) as mock_get_s3_client,+ patch.object(producer, "_get_fs", return_value=mock_fs),+ _patch_async_producer_scope(mock_kafka_producer),+ ):+ 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)+ await producer.produce_to_kafka_from_s3()++ return [call[1]["data"]["properties"] for call in mock_kafka_producer.produce.call_args_list]+++def _view_producer_for_id(saved_query_id: str, job_id: str = "job_1") -> CDPProducer:+ return _producer_with_known_table_name(+ CDPProducer.for_view(team_id=1, saved_query_id=saved_query_id, job_id=job_id, logger=mock.AsyncMock())+ )+++ "runs,produced_by_the_last_run",+ [+ # A view's incremental window is inclusive of the watermark, so the boundary rows come back+ # unchanged every run. Producing them again runs every subscribed workflow again, which for+ # an outbound message means sending it again every sync period.+ ([[{"id": 1, "total": 5}, {"id": 2, "total": 7}]] * 2, []),+ # A row whose content changed is a real change, so it still goes out.+ (+ [[{"id": 1, "total": 5}, {"id": 2, "total": 7}], [{"id": 1, "total": 9}, {"id": 2, "total": 7}]],+ [{"id": 1, "total": 9}],+ ),+ # The record holds a run's suppressed rows as well as its produced ones. Without that, a row+ # that sits on the boundary for many runs comes back on every other run.+ ([[{"id": 1, "total": 5}]] * 3, []),+ ],+ ids=["unchanged rows", "one changed row", "a row that keeps coming back"],+)+async def test_what_a_later_view_run_produces(runs, produced_by_the_last_run):+ view_id = str(uuid.uuid4())++ produced: list[dict] = []+ for run, rows in enumerate(runs):+ produced = await _produce_staged_rows(_view_producer_for_id(view_id, f"job_{run}"), rows)++ assert produced == produced_by_the_last_run+++ "failure",+ [+ # A produce that raises is caught and the file dropped.+ {"produce_raises": True},+ # A produce only queues the row. Kafka reports a failed delivery later, on the future it returns.+ {"delivery_fails": True},+ ],+ ids=["produce raises", "delivery fails"],+)+async def test_a_view_row_whose_produce_failed_is_produced_on_the_next_run(failure):+ # The row never reached a subscriber. Recording it as produced would suppress it next run,+ # silently losing the trigger for good.+ view_id = str(uuid.uuid4())+ rows = [{"id": 1, "total": 5}]++ await _produce_staged_rows(_view_producer_for_id(view_id), rows, **failure)++ assert await _produce_staged_rows(_view_producer_for_id(view_id, "job_2"), rows) == rows+++async def test_a_view_row_confirmed_only_at_flush_is_suppressed_on_the_next_run():+ # Settled deliveries are recorded between batches to bound memory. A delivery still in flight at+ # that point must stay held until the flush confirms it, or the row triggers again next run.+ view_id = str(uuid.uuid4())+ rows = [{"id": 1, "total": 5}]++ await _produce_staged_rows(_view_producer_for_id(view_id), rows, delivery_settles_on_flush=True)++ assert await _produce_staged_rows(_view_producer_for_id(view_id, "job_2"), rows) == []+++async def test_a_source_row_is_produced_on_every_sync():+ # A source's event id already mixes in the job id, so the same row in a later sync is a new+ # delivery rather than a repeat. Suppression must not reach this path.+ schema_id = str(uuid.uuid4())+ rows = [{"id": 1, "name": "Alice"}]++ def _producer(job_id: str) -> CDPProducer:+ return _producer_with_known_table_name(+ CDPProducer.for_source(team_id=1, schema_id=schema_id, job_id=job_id, logger=mock.AsyncMock())+ )++ assert await _produce_staged_rows(_producer("job_1"), rows) == rows+ assert await _produce_staged_rows(_producer("job_2"), rows) == rows+++async def test_view_rows_are_produced_when_the_record_is_unreadable():+ # Suppression is best effort. A Redis problem costs a repeated trigger; failing closed would+ # drop a real one.+ view_id = str(uuid.uuid4())+ rows = [{"id": 1, "total": 5}]++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_emitted_rows.get_async_client",+ side_effect=RuntimeError("redis down"),+ ):+ assert await _produce_staged_rows(_view_producer_for_id(view_id), rows) == rows+ assert await _produce_staged_rows(_view_producer_for_id(view_id, "job_2"), rows) == rows+++async def test_the_record_never_holds_more_than_the_tracked_row_limit():+ # One key per view, so a view big enough to pass the limit must not be able to grow it without+ # bound. The rows past the limit repeat on every run instead, which is the cheaper failure.+ key = f"test_emitted_rows:{uuid.uuid4()}"+ store = EmittedRowStore(key, mock.AsyncMock())++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_emitted_rows.MAX_TRACKED_ROWS", 2+ ):+ await store.load()+ for event_id in ["a", "b", "c", "d"]:+ store.record_produced(event_id)+ await store.commit()++ assert await get_async_client().scard(key) == 2+++def test_the_emitted_rows_key_and_its_scratch_key_share_a_cluster_slot():+ key = emitted_rows_key(1, "01a0d0f3-b1c8-0000-1589-739b4a75582c")++ assert key_slot(key.encode()) == key_slot(f"{key}:writing".encode())diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_view.tsx b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_view.tsxindex 97b781c8c2cc..bd04bce432bd 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_view.tsx+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/data_warehouse_view.tsx@@ -128,8 +128,9 @@ function StepTriggerConfigurationDataWarehouseView({ node }: { node: any }): JSX{selectedIsFullRefresh && (<LemonBanner type="warning" className="w-full"><p className="mb-0">- This view rebuilds its whole table on every run, so every row runs this workflow again each- time. Set the view to update incrementally to run only on the rows that changed.{' '}+ This view rebuilds its whole table on every run. A row runs this workflow again only if its+ values changed since the last run. In a view with more than 200,000 rows, the rows past that+ limit run it again each time. Set the view to update incrementally to avoid this.{' '}{selectedView && (<Linkto={urls.sqlEditor({ view_id: selectedView.id })}