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.

chore(warehouse-sources): formalize the inline pipeline taps as chunk sinks (#77335)

estefaniadd7d726b6440
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index f1e95e5b1194..1795ab2a179b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -18,14 +18,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
BillingLimitsWillBeReachedException,
DuplicatePrimaryKeysException,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import (
is_transient_object_store_error,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (
- PersonPropertyRowSink,
-)
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import (
decrement_rows,
increment_rows,
@@ -676,23 +672,3 @@ async def advance_xmin_state(
ceiling_xid8=resource.xmin_ceiling_xid8,
num_wraparound=resource.xmin_num_wraparound,
)
-
-
-async def cdp_producer_clear_chunks(cdp_producer: CDPProducer):
- if await cdp_producer.should_produce_table():
- await cdp_producer.clear_s3_chunks()
-
-
-async def write_chunk_for_cdp_producer(cdp_producer: CDPProducer, index: int, pa_table: pa.Table):
- if await cdp_producer.should_produce_table():
- await cdp_producer.write_chunk_for_cdp_producer(chunk=index, table=pa_table)
-
-
-async def person_property_sink_clear_chunks(sink: PersonPropertyRowSink):
- if await sink.should_stage():
- await sink.clear_chunks()
-
-
-async def stage_chunk_for_person_property_sink(sink: PersonPropertyRowSink, index: int, pa_table: pa.Table):
- if await sink.should_stage():
- await sink.stage_chunk(chunk=index, table=pa_table)
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 5ce64dc20111..97836c876142 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
@@ -33,7 +33,7 @@ class CDPProducer:
schema_id: str
job_id: str
logger: FilteringBoundLogger
- _should_produce_cache: bool | None
+ _should_run_cache: bool | None
_table_name_cache: str | None
def __init__(self, team_id: int, schema_id: str, job_id: str, logger: FilteringBoundLogger) -> None:
@@ -41,7 +41,7 @@ class CDPProducer:
self.schema_id = schema_id
self.job_id = job_id
self.logger = logger
- self._should_produce_cache = None
+ self._should_run_cache = None
self._table_name_cache = None
def _get_fs(self) -> pa_fs.S3FileSystem:
@@ -110,9 +110,9 @@ class CDPProducer:
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}"))
- async def should_produce_table(self) -> bool:
- if self._should_produce_cache is not None:
- return self._should_produce_cache
+ 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()
@@ -154,10 +154,10 @@ class CDPProducer:
"Failed to check hog function/workflow triggers in PostHog's database"
) from e
- self._should_produce_cache = await _check()
- return self._should_produce_cache
+ self._should_run_cache = await _check()
+ return self._should_run_cache
- async def clear_s3_chunks(self):
+ async def clear(self):
async with aget_s3_client() as s3_client:
await self.logger.adebug(f"Clearing S3 chunks at path prefix {self._get_path_prefix()}")
@@ -167,7 +167,7 @@ class CDPProducer:
except FileNotFoundError:
pass
- async def write_chunk_for_cdp_producer(self, chunk: int, table: pa.Table) -> None:
+ async def stage_chunk(self, chunk: int, table: pa.Table) -> None:
await self.logger.adebug(f"Writing chunk {chunk} for CDP producer to S3 path prefix {self._get_path_prefix()}")
# Write operations in pyarrow are CPU-bound, so run in thread pool
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py
index c78716d6588b..68248951ffda 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py
@@ -89,7 +89,7 @@ class PersonPropertyRowSink:
self._projection_resolved = True
return self._projection
- async def should_stage(self) -> bool:
+ async def should_run(self) -> bool:
return bool(await self._get_projection())
async def stage_chunk(self, chunk: int, table: pa.Table) -> None:
@@ -120,7 +120,7 @@ class PersonPropertyRowSink:
use_dictionary=True,
)
- async def clear_chunks(self) -> None:
+ async def clear(self) -> None:
"""Drop this job's own staged files (full refresh only), plus sibling job prefixes
abandoned long enough.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py
index 5fcd7d773f48..e9fd6e8e91dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py
@@ -33,14 +33,14 @@ def _projection(key_column: str, *columns: str) -> PersonPropertySourceProjectio
@pytest.mark.asyncio
-async def test_should_stage_reflects_projection():
+async def test_should_run_reflects_projection():
sink = _sink()
with patch(f"{_MODULE}.person_property_projection_for", return_value=None):
- assert await sink.should_stage() is False
+ assert await sink.should_run() is False
other = _sink()
with patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan")]):
- assert await other.should_stage() is True
+ assert await other.should_run() is True
@pytest.mark.asyncio
@@ -116,7 +116,7 @@ def _s3_client(find_result=None) -> MagicMock:
@pytest.mark.asyncio
-async def test_clear_chunks_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_ones():
+async def test_clear_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_ones():
# A fresh sibling prefix belongs to a consumer that is merely lagging — deleting it loses an
# incremental sync's staged delta for good. Only long-abandoned prefixes may be swept.
sink = _sink()
@@ -132,7 +132,7 @@ async def test_clear_chunks_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_on
)
with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
- await sink.clear_chunks()
+ await sink.clear()
removed = [call.args[0] for call in s3_client._rm.await_args_list]
assert f"s3://{sink._get_path_prefix()}/" in removed # own job prefix cleared on full refresh
@@ -141,7 +141,7 @@ async def test_clear_chunks_keeps_fresh_sibling_prefixes_and_sweeps_abandoned_on
@pytest.mark.asyncio
-async def test_clear_chunks_keeps_own_prefix_on_incremental_syncs():
+async def test_clear_keeps_own_prefix_on_incremental_syncs():
# An incremental retry resumes past the committed cursor, so the failed attempt's staged
# files are the only record of those rows — clearing the job prefix would lose them for good.
sink = _sink(is_incremental=True)
@@ -151,7 +151,7 @@ async def test_clear_chunks_keeps_own_prefix_on_incremental_syncs():
)
with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
- await sink.clear_chunks()
+ await sink.clear()
removed = [call.args[0] for call in s3_client._rm.await_args_list]
assert f"s3://{sink._get_path_prefix()}/" not in removed # own prefix survives the retry
@@ -178,7 +178,7 @@ async def test_stage_chunk_filenames_are_unique_per_attempt():
@pytest.mark.asyncio
-async def test_clear_chunks_tolerates_missing_prefixes():
+async def test_clear_tolerates_missing_prefixes():
# First sync of a schema has nothing staged anywhere; clearing must not fail the sync.
sink = _sink()
s3_client = _s3_client()
@@ -186,4 +186,4 @@ async def test_clear_chunks_tolerates_missing_prefixes():
s3_client._find = AsyncMock(side_effect=FileNotFoundError)
with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):
- await sink.clear_chunks()
+ await sink.clear()
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
new file mode 100644
index 000000000000..aef1ebd32112
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/sinks.py
@@ -0,0 +1,74 @@
+from collections.abc import Sequence
+from typing import Protocol
+
+import pyarrow as pa
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (
+ PersonPropertyRowSink,
+)
+
+
+class ChunkSink(Protocol):
+ """A gated tap on the pipeline write loop.
+
+ A sink observes every chunk the pipeline writes without being part of the write itself:
+ it is cleared once at run start, then handed each chunk in write order. `should_run` is
+ the sink's own gate (e.g. "does any enabled HogFunction reference this table?") — the
+ loop consults it before every operation so a gated-off sink costs nothing beyond the
+ (cached) gate check, and a sink failure fails the sync like any other write-loop error.
+ """
+
+ async def should_run(self) -> bool: ...
+
+ async def clear(self) -> None: ...
+
+ async def stage_chunk(self, chunk: int, table: pa.Table) -> None: ...
+
+
+class PipelineSinks:
+ """The pipeline's chunk sinks, iterated at one call site per moment (clear / per-chunk).
+
+ `cdp_producer` is also exposed directly: its gate feeds `PipelineResult.should_trigger_cdp_producer`,
+ which the workflow reads to start the post-sync Kafka producer job — a post-run concern
+ outside the chunk-sink contract.
+ """
+
+ def __init__(self, sinks: Sequence[ChunkSink], cdp_producer: CDPProducer) -> None:
+ self.all: list[ChunkSink] = list(sinks)
+ self.cdp_producer = cdp_producer
+
+ async def clear(self) -> None:
+ for sink in self.all:
+ if await sink.should_run():
+ await sink.clear()
+
+ async def stage_chunk(self, chunk: int, table: pa.Table) -> None:
+ for sink in self.all:
+ if await sink.should_run():
+ await sink.stage_chunk(chunk, table)
+
+
+def build_pipeline_sinks(
+ *,
+ team_id: int,
+ schema_id: str,
+ job_id: str,
+ logger: FilteringBoundLogger,
+ is_incremental: bool,
+) -> PipelineSinks:
+ """The single wiring point for every chunk sink, shared by the v2 and v3 pipelines.
+
+ 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)
+ person_property_sink = PersonPropertyRowSink(
+ team_id=team_id,
+ schema_id=schema_id,
+ job_id=job_id,
+ logger=logger,
+ is_incremental=is_incremental,
+ )
+ return PipelineSinks([cdp_producer, person_property_sink], cdp_producer)
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 a7ed39ce7a8c..250277fc388f 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
@@ -39,7 +39,7 @@ def _patch_async_producer_scope(mock_producer):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_no_hog_function(team):
+async def test_should_run_no_hog_function(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -51,12 +51,12 @@ async def test_should_produce_table_no_hog_function(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is False
+ assert await producer.should_run() is False
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_matching_hog_function(team):
+async def test_should_run_with_matching_hog_function(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -74,7 +74,7 @@ async def test_should_produce_table_with_matching_hog_function(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@@ -97,7 +97,7 @@ async def test_should_not_produce_table_with_disabled_matching_hog_function(team
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is False
+ assert await producer.should_run() is False
@pytest.mark.django_db(transaction=True)
@@ -121,12 +121,12 @@ async def test_should_not_produce_table_with_deleted_matching_hog_function(team)
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is False
+ assert await producer.should_run() is False
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_new_style_table_name(team):
+async def test_should_run_with_new_style_table_name(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -144,12 +144,12 @@ async def test_should_produce_table_with_new_style_table_name(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_source_prefix(team):
+async def test_should_run_with_source_prefix(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES, prefix="eu"
)
@@ -167,12 +167,12 @@ async def test_should_produce_table_with_source_prefix(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_leading_underscore_source_prefix(team):
+async def test_should_run_with_leading_underscore_source_prefix(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES, prefix="_eu"
)
@@ -190,12 +190,12 @@ async def test_should_produce_table_with_leading_underscore_source_prefix(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_matching_hog_flow(team):
+async def test_should_run_with_matching_hog_flow(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -213,7 +213,7 @@ async def test_should_produce_table_with_matching_hog_flow(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@@ -236,7 +236,7 @@ async def test_should_not_produce_table_with_draft_hog_flow(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is False
+ assert await producer.should_run() is False
@pytest.mark.django_db(transaction=True)
@@ -259,12 +259,12 @@ async def test_should_not_produce_table_with_non_matching_hog_flow_table(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is False
+ assert await producer.should_run() is False
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_with_both_hog_function_and_flow(team):
+async def test_should_run_with_both_hog_function_and_flow(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -287,13 +287,13 @@ async def test_should_produce_table_with_both_hog_function_and_flow(team):
)
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="", logger=mock.AsyncMock())
- assert await producer.should_produce_table() is True
+ assert await producer.should_run() is True
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_should_produce_table_posthog_database_connection_failure_stays_retryable(team):
- # `should_produce_table` queries PostHog's own database (HogFunction/HogFlow), not the
+async def test_should_run_posthog_database_connection_failure_stays_retryable(team):
+ # `should_run` queries PostHog's own database (HogFunction/HogFlow), not the
# source being synced. A transient connection failure there (e.g. a DNS blip resolving our
# host) surfaces the same "Name or service not known" wording a customer's misconfigured
# source host would, so it must be re-raised as PostHogInternalDatabaseError to avoid being
@@ -315,7 +315,7 @@ async def test_should_produce_table_posthog_database_connection_failure_stays_re
) as mock_hog_function_objects:
mock_hog_function_objects.filter.side_effect = DjangoOperationalError("[Errno -2] Name or service not known")
with pytest.raises(PostHogInternalDatabaseError) as exc_info:
- await producer.should_produce_table()
+ await producer.should_run()
non_retryable = PostgresSource().get_non_retryable_errors()
error_msg = str(exc_info.value)
@@ -615,7 +615,7 @@ async def test_produce_to_kafka_from_s3_with_large_batch(mock_get_s3_client, tea
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_write_chunk_for_cdp_producer(team):
+async def test_stage_chunk(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -635,7 +635,7 @@ async def test_write_chunk_for_cdp_producer(team):
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.write_table"
) as mock_write_table:
with patch.object(producer, "_get_fs", return_value=mock_fs):
- await producer.write_chunk_for_cdp_producer(chunk=5, table=test_data)
+ await producer.stage_chunk(chunk=5, table=test_data)
mock_write_table.assert_called_once()
call_args = mock_write_table.call_args
@@ -648,7 +648,7 @@ async def test_write_chunk_for_cdp_producer(team):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
-async def test_write_chunk_for_cdp_producer_with_empty_table(team):
+async def test_stage_chunk_with_empty_table(team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -668,7 +668,7 @@ async def test_write_chunk_for_cdp_producer_with_empty_table(team):
"products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.write_table"
) as mock_write_table:
with patch.object(producer, "_get_fs", return_value=mock_fs):
- await producer.write_chunk_for_cdp_producer(chunk=0, table=test_data)
+ await producer.stage_chunk(chunk=0, table=test_data)
mock_write_table.assert_called_once()
@@ -676,7 +676,7 @@ async def test_write_chunk_for_cdp_producer_with_empty_table(team):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")
-async def test_clear_s3_chunks_with_files(mock_get_s3_client, team):
+async def test_clear_with_files(mock_get_s3_client, team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -697,7 +697,7 @@ async def test_clear_s3_chunks_with_files(mock_get_s3_client, team):
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
- await producer.clear_s3_chunks()
+ await producer.clear()
mock_s3_client._rm.assert_called_once()
@@ -705,7 +705,7 @@ async def test_clear_s3_chunks_with_files(mock_get_s3_client, team):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")
-async def test_clear_s3_chunks_with_no_files(mock_get_s3_client, team):
+async def test_clear_with_no_files(mock_get_s3_client, team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -723,7 +723,7 @@ async def test_clear_s3_chunks_with_no_files(mock_get_s3_client, team):
producer = CDPProducer(team_id=team.id, schema_id=str(schema.id), job_id="test_job", logger=mock.AsyncMock())
- await producer.clear_s3_chunks()
+ await producer.clear()
mock_s3_client._rm.assert_not_called()
@@ -731,7 +731,7 @@ async def test_clear_s3_chunks_with_no_files(mock_get_s3_client, team):
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@patch("products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.aget_s3_client")
-async def test_clear_s3_chunks_handles_file_not_found_on_delete(mock_get_s3_client, team):
+async def test_clear_handles_file_not_found_on_delete(mock_get_s3_client, team):
source = await sync_to_async(ExternalDataSource.objects.create)(
team=team, source_type=ExternalDataSourceType.POSTGRES
)
@@ -753,7 +753,7 @@ async def test_clear_s3_chunks_handles_file_not_found_on_delete(mock_get_s3_clie
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):
- await producer.clear_s3_chunks()
+ await producer.clear()
@pytest.mark.django_db(transaction=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_sinks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_sinks.py
new file mode 100644
index 000000000000..d2f1a78abec4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_sinks.py
@@ -0,0 +1,66 @@
+import pytest
+from unittest.mock import AsyncMock, MagicMock
+
+import pyarrow as pa
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sinks import PipelineSinks
+
+
+def _sink(*, gated_on: bool) -> MagicMock:
+ return MagicMock(
+ should_run=AsyncMock(return_value=gated_on),
+ clear=AsyncMock(),
+ stage_chunk=AsyncMock(),
+ )
+
+
+class TestPipelineSinks:
+ @parameterized.expand(
+ [
+ # A gated-off sink must cost nothing beyond its gate check: staging to it would
+ # write S3 chunks (or produce Kafka rows downstream) for a table no consumer wants.
+ # A gated-on sink must receive the clear and every chunk, or its consumer silently
+ # reads stale/partial data.
+ ("gated_on", True),
+ ("gated_off", False),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_gate_is_consulted_per_operation(self, _name: str, gated_on: bool) -> None:
+ sink = _sink(gated_on=gated_on)
+ sinks = PipelineSinks([sink], cdp_producer=MagicMock())
+ table = pa.table({"id": [1]})
+
+ await sinks.clear()
+ await sinks.stage_chunk(0, table)
+ await sinks.stage_chunk(1, table)
+
+ if gated_on:
+ sink.clear.assert_awaited_once()
+ assert [c.args for c in sink.stage_chunk.await_args_list] == [(0, table), (1, table)]
+ else:
+ sink.clear.assert_not_awaited()
+ sink.stage_chunk.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_one_sinks_gate_does_not_gate_the_others(self) -> None:
+ gated_off, gated_on = _sink(gated_on=False), _sink(gated_on=True)
+ sinks = PipelineSinks([gated_off, gated_on], cdp_producer=MagicMock())
+
+ await sinks.stage_chunk(0, pa.table({"id": [1]}))
+
+ gated_off.stage_chunk.assert_not_awaited()
+ gated_on.stage_chunk.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_sink_failure_propagates(self) -> None:
+ # A sink failure must fail the sync like any other write-loop error. Swallowing it here
+ # would let a sync report success while its consumer's staged data is silently missing —
+ # an incremental sync never re-stages those rows until they change again.
+ sink = _sink(gated_on=True)
+ sink.stage_chunk.side_effect = RuntimeError("staging blew up")
+ sinks = PipelineSinks([sink], cdp_producer=MagicMock())
+
+ with pytest.raises(RuntimeError, match="staging blew up"):
+ await sinks.stage_chunk(0, pa.table({"id": [1]}))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
index 1e44a00336ca..8687ab4bba5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/pipeline.py
@@ -20,21 +20,17 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
advance_xmin_state,
- cdp_producer_clear_chunks,
cleanup_memory,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
- person_property_sink_clear_chunks,
reset_rows_synced_if_needed,
resolve_primary_keys,
setup_row_tracking_with_billing_check,
should_check_shutdown,
- stage_chunk_for_person_property_sink,
update_incremental_field_values,
update_row_tracking_after_batch,
validate_incremental_sync,
- write_chunk_for_cdp_producer,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.load import (
run_post_load_operations,
@@ -51,14 +47,14 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.async_iterate import async_iterate
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriter
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchema
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.partitioning import setup_partitioning
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (
- PersonPropertyRowSink,
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sinks import (
+ PipelineSinks,
+ build_pipeline_sinks,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import record_source_item_stats
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
@@ -86,7 +82,7 @@ class PipelineNonDLT(Generic[ResumableData]):
_delta_table_ref: DeltaTableRef
_resumable_source_manager: ResumableSourceManager[ResumableData] | None
_internal_schema = HogQLSchema()
- _cdp_producer: CDPProducer
+ _sinks: PipelineSinks
_batcher: Batcher
_load_id: int
@@ -136,10 +132,7 @@ class PipelineNonDLT(Generic[ResumableData]):
schema_name=self._schema.name,
)
self._internal_schema = HogQLSchema()
- self._cdp_producer = CDPProducer(
- team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._logger
- )
- self._person_property_sink = PersonPropertyRowSink(
+ self._sinks = build_pipeline_sinks(
team_id=self._job.team_id,
schema_id=self._schema.id,
job_id=job_id,
@@ -166,8 +159,7 @@ class PipelineNonDLT(Generic[ResumableData]):
await self._logger.ainfo("Resumable source detected - attempting to resume previous import")
try:
- await cdp_producer_clear_chunks(self._cdp_producer)
- await person_property_sink_clear_chunks(self._person_property_sink)
+ await self._sinks.clear()
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
@@ -267,7 +259,7 @@ class PipelineNonDLT(Generic[ResumableData]):
await advance_xmin_state(self._resource, self._schema, self._logger)
- result = PipelineResult(should_trigger_cdp_producer=await self._cdp_producer.should_produce_table())
+ result = PipelineResult(should_trigger_cdp_producer=await self._sinks.cdp_producer.should_run())
if isinstance(prepared_queryable_folder, str):
result["prepared_queryable_folder"] = prepared_queryable_folder
return result
@@ -353,8 +345,7 @@ class PipelineNonDLT(Generic[ResumableData]):
self._internal_schema.add_pyarrow_table(pa_table)
- await write_chunk_for_cdp_producer(self._cdp_producer, index, pa_table)
- await stage_chunk_for_person_property_sink(self._person_property_sink, index, pa_table)
+ await self._sinks.stage_chunk(index, pa_table)
(
self._last_incremental_field_value,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
index 8115885fa3a4..6e9b6a58d602 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v2/test/test_pipeline.py
@@ -4,7 +4,6 @@ from typing import cast
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline import PipelineNonDLT
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -12,7 +11,7 @@ _PIPELINE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pip
@pytest.mark.asyncio
-async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_import_error(monkeypatch):
+async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_import_error():
# Regression: run()'s finally used to call get_delta_table() (object-storage I/O) purely for
# memory cleanup, even on a run that failed before ever fetching a delta table (nothing
# cached, nothing to clean up). A transient object-storage blip on that spurious call then
@@ -23,7 +22,6 @@ async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_impor
pipeline = PipelineNonDLT.__new__(PipelineNonDLT)
pipeline._logger = AsyncMock()
pipeline._resumable_source_manager = None
- pipeline._cdp_producer = cast(CDPProducer, object()) # unused: the patched clear-chunks ignores it
pipeline._resource = cast(SourceResponse, object())
delta_table_ref = AsyncMock()
delta_table_ref.get_delta_table.cache_pop.return_value = None
@@ -32,13 +30,7 @@ async def test_run_cleanup_does_not_call_get_delta_table_and_does_not_mask_impor
class ImportError_(Exception):
pass
- async def _raise_import_error(_cdp_producer):
- raise ImportError_("Can't connect to MySQL server on")
-
- monkeypatch.setattr(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v2.pipeline.cdp_producer_clear_chunks",
- _raise_import_error,
- )
+ pipeline._sinks = MagicMock(clear=AsyncMock(side_effect=ImportError_("Can't connect to MySQL server on")))
with pytest.raises(ImportError_, match="Can't connect to MySQL server on"):
await pipeline.run()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
index d81e0c01baef..4a3cff629594 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/pipeline.py
@@ -27,22 +27,18 @@ from products.warehouse_sources.backend.models.external_data_schema import (
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
advance_xmin_state,
- cdp_producer_clear_chunks,
cleanup_memory,
finalize_desc_sort_incremental_value,
handle_corrupted_delta_log,
handle_reset_or_full_refresh,
persist_primary_keys,
- person_property_sink_clear_chunks,
reset_rows_synced_if_needed,
resolve_primary_keys,
setup_row_tracking_with_billing_check,
should_check_shutdown,
- stage_chunk_for_person_property_sink,
update_incremental_field_values,
update_row_tracking_after_batch,
validate_incremental_sync,
- write_chunk_for_cdp_producer,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
_append_debug_column_to_pyarrows_table,
@@ -55,12 +51,12 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arr
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.async_iterate import async_iterate
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.maintenance import DeltaMaintenance
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.hogql_schema import HogQLSchema
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink import (
- PersonPropertyRowSink,
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.sinks import (
+ PipelineSinks,
+ build_pipeline_sinks,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.table_stats import record_source_item_stats
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
@@ -100,7 +96,7 @@ class PipelineV3(Generic[ResumableData]):
_delta_table_ref: DeltaTableRef
_resumable_source_manager: ResumableSourceManager[ResumableData] | None
_internal_schema: HogQLSchema
- _cdp_producer: CDPProducer
+ _sinks: PipelineSinks
_batcher: Batcher
_load_id: int
_s3_batch_writer: S3BatchWriter
@@ -222,10 +218,7 @@ class PipelineV3(Generic[ResumableData]):
schema_name=self._schema.name,
)
self._internal_schema = HogQLSchema()
- self._cdp_producer = CDPProducer(
- team_id=self._job.team_id, schema_id=self._schema.id, job_id=job_id, logger=self._logger
- )
- self._person_property_sink = PersonPropertyRowSink(
+ self._sinks = build_pipeline_sinks(
team_id=self._job.team_id,
schema_id=self._schema.id,
job_id=job_id,
@@ -268,8 +261,7 @@ class PipelineV3(Generic[ResumableData]):
)
try:
- await cdp_producer_clear_chunks(self._cdp_producer)
- await person_property_sink_clear_chunks(self._person_property_sink)
+ await self._sinks.clear()
await reset_rows_synced_if_needed(self._job, self._is_incremental, self._reset_pipeline, should_resume)
@@ -373,7 +365,7 @@ class PipelineV3(Generic[ResumableData]):
await self._finalize(row_count=row_count)
return {
- "should_trigger_cdp_producer": await self._cdp_producer.should_produce_table(),
+ "should_trigger_cdp_producer": await self._sinks.cdp_producer.should_run(),
"consumer_manages_job_status": len(self._batch_results) > 0,
}
except Exception:
@@ -445,8 +437,7 @@ class PipelineV3(Generic[ResumableData]):
self._internal_schema.add_pyarrow_table(pa_table)
- await write_chunk_for_cdp_producer(self._cdp_producer, batch_index, pa_table)
- await stage_chunk_for_person_property_sink(self._person_property_sink, batch_index, pa_table)
+ await self._sinks.stage_chunk(batch_index, pa_table)
# Update accumulated schema with any new columns from this batch
if self._accumulated_pa_schema is None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
index ded05c50c5f8..ee7891e4aec6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/test_pipeline.py
@@ -40,8 +40,11 @@ def _make_pipeline() -> PipelineV3:
pipeline._delta_table_ref = MagicMock(is_first_sync=True)
pipeline._resumable_source_manager = None
pipeline._internal_schema = MagicMock()
- pipeline._cdp_producer = MagicMock()
- pipeline._person_property_sink = MagicMock(should_stage=AsyncMock(return_value=False))
+ pipeline._sinks = MagicMock(
+ clear=AsyncMock(),
+ stage_chunk=AsyncMock(),
+ cdp_producer=MagicMock(should_run=AsyncMock(return_value=False)),
+ )
pipeline._batcher = MagicMock()
pipeline._load_id = 1
pipeline._s3_batch_writer = MagicMock()
@@ -138,13 +141,8 @@ class TestAttemptScopedRunUuid:
pipeline = _make_pipeline()
pipeline._attempt = 2
pipeline._reset_pipeline = True
- pipeline._cdp_producer = MagicMock(should_produce_table=AsyncMock(return_value=False))
with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.cdp_producer_clear_chunks",
- new_callable=AsyncMock,
- ),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.reset_rows_synced_if_needed",
new_callable=AsyncMock,
@@ -178,12 +176,9 @@ class TestExtractionFailureDoesNotCleanupS3:
async def test_s3_files_preserved_when_extraction_fails(self) -> None:
pipeline = _make_pipeline()
s3_writer = cast(MagicMock, pipeline._s3_batch_writer)
+ pipeline._sinks = MagicMock(clear=AsyncMock(side_effect=RuntimeError("simulated extraction failure")))
with (
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.cdp_producer_clear_chunks",
- side_effect=RuntimeError("simulated extraction failure"),
- ),
patch(
"products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline.activity"
) as mock_activity,