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): delete the dead v3 Kafka load transport (#77651)

estefaniae2769ae03337
diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.py
index fc45095e1a19..769ee94b2085 100644
--- a/posthog/kafka_client/routing.py
+++ b/posthog/kafka_client/routing.py
@@ -54,8 +54,6 @@ from posthog.kafka_client.topics import (
KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS_DLQ,
- KAFKA_WAREHOUSE_SOURCES_JOBS,
- KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ,
)
from posthog.settings.kafka import KafkaProfileSettings
@@ -92,8 +90,6 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {
# so it needs no Django producer routing entry.
KAFKA_FLAGS_CACHE_INVALIDATION: KafkaClusterProfile.SHARED,
# --- WAREHOUSE_SOURCES (Warpstream warehouse-pipelines) ---
- KAFKA_WAREHOUSE_SOURCES_JOBS: KafkaClusterProfile.WAREHOUSE_SOURCES,
- KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS: KafkaClusterProfile.WAREHOUSE_SOURCES,
KAFKA_WAREHOUSE_SOURCE_WEBHOOKS_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,
KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES: KafkaClusterProfile.WAREHOUSE_SOURCES,
diff --git a/posthog/kafka_client/test/test_routing.py b/posthog/kafka_client/test/test_routing.py
index 256c932918e7..0ce347b8bf23 100644
--- a/posthog/kafka_client/test/test_routing.py
+++ b/posthog/kafka_client/test/test_routing.py
@@ -26,7 +26,7 @@ from posthog.kafka_client.topics import (
KAFKA_DEAD_LETTER_QUEUE,
KAFKA_DWH_CDP_RAW_TABLE,
KAFKA_EVENTS_JSON,
- KAFKA_WAREHOUSE_SOURCES_JOBS,
+ KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,
)
@@ -110,7 +110,7 @@ class CurrentTopicRoutingTest(TestCase):
def test_without_overrides_returns_defaults(self):
with override_settings(KAFKA_TOPIC_ROUTING_OVERRIDES=""):
mapping = current_topic_routing()
- self.assertEqual(mapping.get(KAFKA_WAREHOUSE_SOURCES_JOBS), KafkaClusterProfile.WAREHOUSE_SOURCES)
+ self.assertEqual(mapping.get(KAFKA_WAREHOUSE_SOURCE_WEBHOOKS), KafkaClusterProfile.WAREHOUSE_SOURCES)
self.assertEqual(mapping.get(KAFKA_DWH_CDP_RAW_TABLE), KafkaClusterProfile.CYCLOTRON)
# KAFKA_APP_METRICS2 is routed to the INGESTION cluster.
self.assertEqual(mapping.get(KAFKA_APP_METRICS2), KafkaClusterProfile.INGESTION)
@@ -125,7 +125,7 @@ class CurrentTopicRoutingTest(TestCase):
KafkaClusterProfile.CYCLOTRON,
)
# Defaults still present.
- self.assertEqual(mapping.get(KAFKA_WAREHOUSE_SOURCES_JOBS), KafkaClusterProfile.WAREHOUSE_SOURCES)
+ self.assertEqual(mapping.get(KAFKA_WAREHOUSE_SOURCE_WEBHOOKS), KafkaClusterProfile.WAREHOUSE_SOURCES)
def test_env_overrides_win_over_defaults(self):
with override_settings(KAFKA_TOPIC_ROUTING_OVERRIDES=f"{KAFKA_DWH_CDP_RAW_TABLE}=default"):
@@ -149,14 +149,14 @@ class ResolveAndGetProducerTest(TestCase):
def test_topic_in_map_resolves_to_profile(self):
with _mock_kafka_backend() as (sync_build, _):
- get_producer(topic=KAFKA_WAREHOUSE_SOURCES_JOBS)
+ get_producer(topic=KAFKA_WAREHOUSE_SOURCE_WEBHOOKS)
sync_build.assert_called_once_with(KafkaClusterProfile.WAREHOUSE_SOURCES)
def test_explicit_profile_wins_over_topic(self):
# Even though the topic is mapped to WAREHOUSE_SOURCES, an explicit
# `profile=` argument takes precedence.
with _mock_kafka_backend() as (sync_build, _):
- get_producer(topic=KAFKA_WAREHOUSE_SOURCES_JOBS, profile=KafkaClusterProfile.CYCLOTRON)
+ get_producer(topic=KAFKA_WAREHOUSE_SOURCE_WEBHOOKS, profile=KafkaClusterProfile.CYCLOTRON)
sync_build.assert_called_once_with(KafkaClusterProfile.CYCLOTRON)
def test_env_override_routes_to_new_profile(self):
diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.py
index 08a9e79d7009..ba1eceb41a06 100644
--- a/posthog/kafka_client/topics.py
+++ b/posthog/kafka_client/topics.py
@@ -79,8 +79,6 @@ KAFKA_DISTINCT_ID_USAGE_EVENTS_JSON = f"{KAFKA_PREFIX}distinct_id_usage_events_j
# Property values - pre-processed by WarpStream pipeline from clickhouse_events_json
KAFKA_CLICKHOUSE_PROPERTY_VALUES = f"{KAFKA_PREFIX}clickhouse_property_values{SUFFIX}"
-KAFKA_WAREHOUSE_SOURCES_JOBS = f"{KAFKA_PREFIX}data_warehouse_sources_jobs{SUFFIX}"
-KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ = f"{KAFKA_PREFIX}data_warehouse_sources_jobs_dlq{SUFFIX}"
KAFKA_NOTIFICATION_EVENTS = f"{KAFKA_PREFIX}notification_events{SUFFIX}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.md
index 8351a6fca9b5..02bff207be11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/README.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md
@@ -142,137 +142,16 @@ for index, schema_id in enumerate(schema_ids):
print(f"{index + 1}/{len(schema_ids)}")
```
-## How to replay load messages for a stuck/failed job in PipelineV3
+## Recovering a stuck or failed load in PipelineV3
-When extraction completed but the load consumer failed (OOM, crash, retries exhausted), the parquet files are still in S3. You can replay the Kafka messages to re-trigger just the load phase without re-extracting from the source.
+There is no manual replay step for the load phase.
+The extraction-to-load hand-off is a durable Postgres batch queue (`pipeline_v3/postgres_queue/`), not fire-and-forget messages: batch rows survive consumer crashes, transient failures retry automatically with backoff (`waiting_retry`), a crashed consumer's lease expires and its batches are reclaimed, and a reconcile sweep fails the `ExternalDataJob` for runs whose batches ended up terminally `failed`.
-Run this on a `temporal-worker-data-warehouse` pod via `manage.py shell_plus`:
+If a job still ends up failed, re-run the sync with the snippets above (use `reset_pipeline: false` to keep existing data).
+Queue rows and their parquet files are pruned after the queue's retention window (see `postgres_queue/README.md`), so there is nothing to replay from S3 after that point either.
-```python
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import list_parquet_files, read_parquet
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3.common import get_base_folder, get_data_folder, strip_s3_protocol
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import ExportSignalMessage, get_warpstream_kafka_producer
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.retry_tracker import clear_retry_info
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import is_batch_already_processed
-from posthog.kafka_client.topics import KAFKA_WAREHOUSE_SOURCES_JOBS
-from products.data_warehouse.backend.models import ExternalDataJob, ExternalDataSchema
-from products.data_warehouse.backend.s3 import get_s3_client
-
-schema_id = '...' # UUID of the schema to replay
-dry_run = True # Set to False to actually send messages
-skip_job_check = False # If True, ignore job status in DB and replay whatever is in S3
-
-schema = ExternalDataSchema.objects.select_related('source').get(id=schema_id)
-source = schema.source
-team_id = schema.team_id
-
-if skip_job_check:
- # Discover the latest run_uuid folder directly from S3 — strip the trailing run_uuid
- # segment from get_base_folder to get the schema-level prefix
- schema_base = get_base_folder(team_id, str(schema.id), '').rstrip('/')
- schema_prefix = strip_s3_protocol(schema_base)
- s3 = get_s3_client()
- try:
- run_folders = sorted(f.rstrip('/').split('/')[-1] for f in s3.ls(schema_prefix))
- except FileNotFoundError:
- run_folders = []
- if not run_folders:
- print(f"No S3 run folders found under {schema_prefix}")
- job = None
- else:
- run_uuid = run_folders[-1]
- job = ExternalDataJob.objects.filter(schema_id=schema_id, workflow_run_id=run_uuid).order_by('-created_at').first()
- if job is None:
- print(f"Found S3 run_uuid={run_uuid} but no matching ExternalDataJob")
-else:
- # Find the latest failed or running job for this schema
- job = (
- ExternalDataJob.objects
- .filter(schema_id=schema_id, status__in=[ExternalDataJob.Status.FAILED, ExternalDataJob.Status.RUNNING])
- .order_by('-created_at')
- .first()
- )
-
-if job is None:
- print(f"No job available for schema {schema_id}")
-else:
- run_uuid = job.workflow_run_id
- print(f"Found job {job.id} (status={job.status}, run_uuid={run_uuid})")
- base_folder = get_base_folder(team_id, str(schema.id), run_uuid)
- data_folder = get_data_folder(base_folder)
- parquet_files = list_parquet_files(data_folder)
- if not parquet_files:
- print(f"No parquet files found in {data_folder}")
- else:
- print(f"Found {len(parquet_files)} parquet files in {data_folder}")
- sync_type_config = schema.sync_type_config or {}
- sync_type = schema.sync_type or 'full_refresh'
- if sync_type == 'incremental':
- sync_type_literal = 'incremental'
- elif sync_type == 'append':
- sync_type_literal = 'append'
- else:
- sync_type_literal = 'full_refresh'
- total_rows = 0
- messages = []
- for i, s3_path in enumerate(parquet_files):
- pa_table = read_parquet(s3_path)
- row_count = pa_table.num_rows
- total_rows += row_count
- already_processed = is_batch_already_processed(team_id, str(schema.id), run_uuid, i)
- messages.append({
- 'batch_index': i,
- 's3_path': s3_path,
- 'row_count': row_count,
- 'byte_size': pa_table.nbytes,
- 'already_processed': already_processed,
- })
- print(f" batch {i}: {s3_path} ({row_count} rows) {'[SKIP - already processed]' if already_processed else ''}")
- print(f"\nTotal: {len(messages)} batches, {total_rows} rows")
- if not dry_run:
- producer = get_warpstream_kafka_producer()
- # Reset job status
- job.status = ExternalDataJob.Status.RUNNING
- job.latest_error = None
- job.finished_at = None
- job.save()
- print(f"Reset job {job.id} to RUNNING")
- for msg_info in messages:
- # Clear retry info so previously-exhausted retries don't block
- clear_retry_info(team_id, str(schema.id), run_uuid, msg_info['batch_index'])
- is_final = msg_info['batch_index'] == len(messages) - 1
- message = ExportSignalMessage(
- team_id=team_id,
- job_id=str(job.id),
- schema_id=str(schema.id),
- source_id=str(source.id),
- resource_name=schema.name,
- run_uuid=run_uuid,
- batch_index=msg_info['batch_index'],
- s3_path=msg_info['s3_path'],
- row_count=msg_info['row_count'],
- byte_size=msg_info['byte_size'],
- is_final_batch=is_final,
- total_batches=len(messages) if is_final else None,
- total_rows=total_rows if is_final else None,
- sync_type=sync_type_literal,
- data_folder=data_folder if is_final else None,
- schema_path=None,
- primary_keys=sync_type_config.get('primary_keys'),
- is_resume=True,
- partition_count=sync_type_config.get('partition_count'),
- partition_size=sync_type_config.get('partition_size'),
- partition_keys=sync_type_config.get('partition_keys'),
- partition_format=sync_type_config.get('partition_format'),
- partition_mode=sync_type_config.get('partition_mode'),
- )
- key = f"{team_id}:{schema.id}"
- producer.produce(topic=KAFKA_WAREHOUSE_SOURCES_JOBS, data=message.to_dict(), key=key)
- producer.flush()
- print(f"Sent {len(messages)} messages to {KAFKA_WAREHOUSE_SOURCES_JOBS}")
- else:
- print("\nDry run - set dry_run = False to send messages")
-```
+The Kafka-era replay runbook that used to live here reconstructed `ExportSignalMessage`s from S3 and re-produced them to the `data_warehouse_sources_jobs` topic.
+That transport was removed; see git history for the old procedure.
## How to clean up orphaned S3 data
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 0bff0975ae19..c8d3ba877173 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -62,7 +62,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import
from products.warehouse_sources.backend.temporal.data_imports.cdc.naming import cdc_qualified_table_name
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import resolve_table_and_folder_names
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import SyncTypeLiteral
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BatchQueue,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/__init__.py
deleted file mode 100644
index db4707870bb0..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import (
- ExportSignalMessage,
- SyncTypeLiteral,
- get_warpstream_kafka_producer,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer import (
- KafkaConsumerService,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.producer import (
- KafkaBatchProducer,
-)
-
-__all__ = [
- "ExportSignalMessage",
- "KafkaBatchProducer",
- "KafkaConsumerService",
- "SyncTypeLiteral",
- "get_warpstream_kafka_producer",
-]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/consumer.py
deleted file mode 100644
index c3913ac3a995..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/consumer.py
+++ /dev/null
@@ -1,493 +0,0 @@
-import json
-import time
-import signal
-import traceback
-from collections.abc import Callable
-from datetime import UTC, datetime
-from typing import Any, Optional
-
-import structlog
-import posthoganalytics
-from confluent_kafka import (
- Consumer as ConfluentConsumer,
- KafkaError,
- KafkaException,
-)
-
-from posthog.exceptions_capture import capture_exception
-from posthog.kafka_client.client import _KafkaProducer, _KafkaSecurityProtocol
-from posthog.kafka_client.routing import get_producer, get_profile_settings, resolve_profile_name
-from posthog.utils import get_machine_id
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.metrics import (
- BATCH_PROCESSING_DURATION_SECONDS,
- BATCH_RETRY_EXHAUSTED_TOTAL,
- BATCH_RETRY_TOTAL,
- BATCH_SIZE,
- BATCH_UTILIZATION,
- DLQ_MESSAGES_TOTAL,
- MESSAGES_PROCESSED_TOTAL,
- OFFSET_COMMITS_TOTAL,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.config import ConsumerConfig
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.retry_tracker import (
- TRANSIENT_ERRORS,
- RetryExhaustedError,
- classify_error,
- clear_retry_info,
- get_retry_info,
- increment_retry_count,
- is_retry_exhausted,
- update_retry_error_type,
-)
-
-logger = structlog.get_logger(__name__)
-
-
-def _extract_message_key(message: dict) -> Optional[tuple[int, str, str, int]]:
- """Extract retry tracking key fields from a message.
-
- Returns (team_id, schema_id, run_uuid, batch_index) or None if fields are missing.
- """
- try:
- return (message["team_id"], message["schema_id"], message["run_uuid"], message["batch_index"])
- except (KeyError, TypeError):
- return None
-
-
-class KafkaConsumerService:
- """A continuously running Kafka consumer service with graceful shutdown support:
- - Runs an infinite loop polling for messages
- - Supports graceful shutdown via SIGTERM/SIGINT
- - Manually commits offsets after successful processing
- - Sends poison-pill messages to a dead-letter queue
- - Reports health status each loop iteration
- """
-
- def __init__(
- self,
- config: ConsumerConfig,
- process_message: Callable[..., None],
- ):
- self._config = config
- self._process_message = process_message
- # Hosts + security come from the routing profile that the input topic maps to.
- # Topics unknown to the routing map fall through to DEFAULT. The enum is cached
- # alongside settings so the DLQ producer can route back to the consumer's own
- # cluster without re-resolving via the DLQ topic (which may not be in TOPIC_ROUTING).
- self._kafka_profile_name = resolve_profile_name(topic=config.input_topic)
- self._kafka_profile = get_profile_settings(profile=self._kafka_profile_name)
- self._shutdown_requested = False
- self._consumer: Optional[ConfluentConsumer] = None
- self._dlq_producer: Optional[_KafkaProducer] = None
-
- def _setup_signal_handlers(self) -> None:
- """Set up signal handlers for graceful shutdown."""
-
- def handle_signal(signum: int, frame: Any) -> None:
- signal_name = signal.Signals(signum).name
- logger.info("shutdown_signal_received", signal=signal_name)
- self._shutdown_requested = True
-
- for sig in (signal.SIGTERM, signal.SIGINT):
- try:
- signal.signal(sig, handle_signal)
- except ValueError:
- logger.warning("signal_registration_failed", signal=sig)
-
- def _create_consumer(self) -> ConfluentConsumer:
- profile = self._kafka_profile
- hosts = profile.hosts
- config: dict[str, str | int | float | bool | None] = {
- "bootstrap.servers": ",".join(hosts) if isinstance(hosts, list) else hosts,
- "security.protocol": profile.security_protocol or _KafkaSecurityProtocol.PLAINTEXT,
- "group.id": self._config.consumer_group,
- "auto.offset.reset": "latest",
- "enable.auto.commit": False,
- "partition.assignment.strategy": "cooperative-sticky",
- "max.poll.interval.ms": self._config.max_poll_interval_ms,
- }
- if profile.security_protocol in (
- _KafkaSecurityProtocol.SASL_PLAINTEXT,
- _KafkaSecurityProtocol.SASL_SSL,
- ):
- config["sasl.mechanism"] = profile.sasl_mechanism
- config["sasl.username"] = profile.sasl_user
- config["sasl.password"] = profile.sasl_password
- if self._config.session_timeout_ms is not None:
- config["session.timeout.ms"] = self._config.session_timeout_ms
- if self._config.heartbeat_interval_ms is not None:
- config["heartbeat.interval.ms"] = self._config.heartbeat_interval_ms
- consumer = ConfluentConsumer(config)
- consumer.subscribe(
- [self._config.input_topic],
- on_assign=self._on_assign,
- on_revoke=self._on_revoke,
- on_lost=self._on_lost,
- )
- return consumer
-
- def _on_assign(self, consumer: ConfluentConsumer, partitions: list) -> None:
- for p in partitions:
- logger.info(
- "partition_assigned",
- topic=p.topic,
- partition=p.partition,
- offset=p.offset,
- )
-
- def _on_revoke(self, consumer: ConfluentConsumer, partitions: list) -> None:
- """Graceful revoke during a cooperative-sticky rebalance.
-
- With cooperative-sticky the callback fires only for the partitions
- actually being revoked; other assignments stay put. The synchronous
- consume loop calls back here *between* batches, so there's no
- in-flight processing to drain at this point. Commit stored offsets
- so the next owner picks up from where we stopped.
- """
- logger.info(
- "partition_revocation_starting",
- revoked_partition_count=len(partitions),
- revoked_partitions=[{"topic": p.topic, "partition": p.partition} for p in partitions],
- )
- try:
- consumer.commit(asynchronous=False)
- except KafkaException as e:
- kafka_error = e.args[0]
- if hasattr(kafka_error, "code") and kafka_error.code() == KafkaError._NO_OFFSET: # type: ignore[attr-defined]
- logger.debug("no_offsets_to_commit_on_revoke")
- else:
- logger.warning("failed_to_commit_on_revoke", error=str(e))
- except Exception as e:
- logger.warning("failed_to_commit_on_revoke", error=str(e))
- logger.info("partition_revocation_complete", revoked_partition_count=len(partitions))
-
- def _on_lost(self, consumer: ConfluentConsumer, partitions: list) -> None:
- """Involuntary partition loss (session timeout, network blip, etc.).
-
- Do NOT commit: another consumer may already own these partitions,
- and committing here could cause the new owner to skip messages we
- never finished processing.
- """
- logger.warning(
- "partitions_lost",
- lost_partition_count=len(partitions),
- lost_partitions=[{"topic": p.topic, "partition": p.partition} for p in partitions],
- )
-
- def _get_dlq_producer(self) -> _KafkaProducer:
- if self._dlq_producer is None:
- # Route by the consumer's own profile rather than by topic so the DLQ
- # always lands on the same cluster as the input — regardless of whether
- # the DLQ topic is listed in TOPIC_ROUTING.
- self._dlq_producer = get_producer(profile=self._kafka_profile_name)
- return self._dlq_producer
-
- def _send_to_dlq(self, message: Any, error: Exception) -> None:
- try:
- producer = self._get_dlq_producer()
- dlq_message = {
- "original_message": message,
- "error_type": type(error).__name__,
- "error_message": str(error),
- "error_traceback": traceback.format_exception(error),
- "failed_at": datetime.now(tz=UTC).isoformat(),
- "input_topic": self._config.input_topic,
- "consumer_group": self._config.consumer_group,
- }
- producer.produce(
- topic=self._config.dlq_topic,
- data=dlq_message,
- )
- producer.flush(timeout=5.0)
- logger.warning(
- "message_sent_to_dlq",
- dlq_topic=self._config.dlq_topic,
- error_type=type(error).__name__,
- error_message=str(error),
- )
-
- posthoganalytics.capture(
- distinct_id=get_machine_id(),
- event="warehouse_v3_dlq_message",
- properties={
- "team_id": message.get("team_id") if isinstance(message, dict) else None,
- "schema_id": message.get("schema_id") if isinstance(message, dict) else None,
- "error_type": type(error).__name__,
- "input_topic": self._config.input_topic,
- },
- )
- except Exception as dlq_error:
- logger.exception(
- "dlq_send_failed",
- original_error_type=type(error).__name__,
- )
- capture_exception(dlq_error)
-
- def run(self, health_reporter: Optional[Callable[[], None]] = None) -> None:
- self._setup_signal_handlers()
-
- logger.info(
- "consumer_starting",
- input_topic=self._config.input_topic,
- consumer_group=self._config.consumer_group,
- batch_size=self._config.batch_size,
- batch_timeout_seconds=self._config.batch_timeout_seconds,
- kafka_hosts=self._kafka_profile.hosts,
- dlq_topic=self._config.dlq_topic,
- )
-
- try:
- self._consumer = self._create_consumer()
-
- logger.info("consumer_started")
-
- while not self._shutdown_requested:
- if health_reporter:
- health_reporter()
-
- raw_messages = self._consumer.consume(
- num_messages=self._config.batch_size,
- timeout=self._config.batch_timeout_seconds,
- )
-
- BATCH_UTILIZATION.labels(group_id=self._config.consumer_group).set(
- len(raw_messages) / self._config.batch_size
- )
-
- messages: list[tuple[Any, dict]] = []
- for msg in raw_messages:
- err = msg.error()
- if err is not None:
- if err.code() == KafkaError._PARTITION_EOF: # type: ignore[attr-defined]
- continue
- logger.error("kafka_message_error", error=err)
- continue
- raw = msg.value()
- if raw is None:
- continue
- messages.append((msg, json.loads(raw.decode("utf-8"))))
-
- if not messages:
- continue
-
- BATCH_SIZE.observe(len(messages))
-
- logger.debug("batch_received", message_count=len(messages))
-
- self._process_batch_with_retry(messages, health_reporter=health_reporter)
-
- except Exception as e:
- logger.exception("consumer_error")
- capture_exception(e)
- raise
- finally:
- self._cleanup()
-
- def _commit_message(self, raw_msg: Any) -> None:
- """Commit the offset for a single Kafka message synchronously.
-
- Used on DLQ paths so a stuck message doesn't block the offset commit of
- its healthy siblings in the same batch. Failures are logged but swallowed
- so a commit blip doesn't prevent continued processing — redelivery will
- hit the is_retry_exhausted branch and re-DLQ idempotently.
- """
- assert self._consumer is not None
- try:
- self._consumer.commit(message=raw_msg, asynchronous=False)
- OFFSET_COMMITS_TOTAL.labels(status="success").inc()
- except Exception as e:
- OFFSET_COMMITS_TOTAL.labels(status="failure").inc()
- logger.warning("per_message_commit_failed", error=str(e))
-
- def _process_batch_with_retry(
- self, messages: list[tuple[Any, dict]], health_reporter: Optional[Callable[[], None]] = None
- ) -> None:
- """Process a batch of messages with persistent retry tracking.
-
- Each message's retry count is tracked in Redis so that retries survive
- OOM process crashes. On each delivery the counter is pre-incremented
- before processing, so a crash mid-processing still counts as an attempt.
-
- Transient errors (DB connection, network) get up to 9 attempts.
- Non-transient or unknown errors (including OOM crashes) get up to 3.
- When retries are exhausted the message goes to the DLQ and the job is
- marked as failed.
- """
- assert self._consumer is not None
-
- dlq_count = 0
-
- for index, (raw_msg, message) in enumerate(messages):
- if self._shutdown_requested:
- # Graceful mid-batch shutdown: commit offsets for messages we've
- # already handled (successes + per-message DLQ commits are idempotent)
- # and leave the remainder for Kafka to redeliver after rebalance.
- try:
- self._consumer.commit()
- OFFSET_COMMITS_TOTAL.labels(status="success").inc()
- except Exception:
- OFFSET_COMMITS_TOTAL.labels(status="failure").inc()
- logger.warning("shutdown_commit_failed", exc_info=True)
- logger.info(
- "shutdown_during_batch",
- handled=index,
- dlq_count=dlq_count,
- remaining=len(messages) - index,
- )
- return
-
- team_id = str(message.get("team_id") or "unknown")
- schema_id = str(message.get("schema_id") or "unknown")
-
- msg_key = _extract_message_key(message)
-
- if msg_key is None:
- # Can't track retries without identifiers — process directly
- with BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).time():
- self._process_message(message, progress_callback=health_reporter)
- MESSAGES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="success").inc()
- if health_reporter:
- health_reporter()
- continue
-
- # Check if retries are already exhausted from a previous delivery
- retry_info = get_retry_info(*msg_key)
- if is_retry_exhausted(retry_info):
- error = RetryExhaustedError(retry_info)
- logger.warning(
- "retry_exhausted",
- team_id=team_id,
- schema_id=schema_id,
- retry_count=retry_info.count,
- error_type=retry_info.error_type,
- last_error=retry_info.last_error,
- )
- self._send_to_dlq(message, error)
- self._mark_job_failed_from_message(message, error)
- # Deliberately keep retry_info in Redis: if this per-message
- # commit or the trailing batch commit fails, redelivery must
- # still observe the exhausted state and re-DLQ idempotently
- # rather than starting a fresh retry cycle. Cleanup relies on
- # the 72h TTL.
- self._commit_message(raw_msg)
- MESSAGES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="dlq").inc()
- DLQ_MESSAGES_TOTAL.labels(team_id=team_id, schema_id=schema_id, error_type="RetryExhausted").inc()
- BATCH_RETRY_EXHAUSTED_TOTAL.labels(error_type=retry_info.error_type or "unknown").inc()
- dlq_count += 1
- continue
-
- # Pre-increment counter before processing (survives OOM)
- retry_info = increment_retry_count(*msg_key)
-
- try:
- self._process_single_with_inprocess_retry(message, health_reporter)
-
- # Success — clear retry info
- clear_retry_info(*msg_key)
- MESSAGES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="success").inc()
-
- except Exception as e:
- # Classify error and persist to Redis
- error_class = classify_error(e)
- update_retry_error_type(*msg_key, error_type=error_class, last_error=str(e))
-
- capture_exception(e)
- logger.exception(
- "message_processing_failed",
- error_type=type(e).__name__,
- error_class=error_class,
- retry_count=retry_info.count,
- )
-
- BATCH_RETRY_TOTAL.labels(attempt=str(retry_info.count), error_type=type(e).__name__).inc()
-
- if is_retry_exhausted(retry_info):
- # Exhausted after this attempt — DLQ and mark failed.
- # Retry state stays in Redis (72h TTL) so that if the
- # per-message commit or a sibling failure prevents the
- # trailing batch commit, redelivery will re-DLQ via the
- # is_retry_exhausted branch rather than retrying from zero.
- self._send_to_dlq(message, e)
- self._mark_job_failed_from_message(message, e)
- self._commit_message(raw_msg)
- MESSAGES_PROCESSED_TOTAL.labels(team_id=team_id, schema_id=schema_id, status="dlq").inc()
- DLQ_MESSAGES_TOTAL.labels(team_id=team_id, schema_id=schema_id, error_type=type(e).__name__).inc()
- BATCH_RETRY_EXHAUSTED_TOTAL.labels(error_type=error_class).inc()
- dlq_count += 1
- else:
- # Not exhausted — re-raise to prevent offset commit.
- # Kafka will redeliver the entire batch; already-processed
- # messages are skipped by the idempotency check.
- raise
-
- # All messages handled (success or DLQ) — commit offsets
- try:
- self._consumer.commit()
- OFFSET_COMMITS_TOTAL.labels(status="success").inc()
- except Exception:
- OFFSET_COMMITS_TOTAL.labels(status="failure").inc()
- raise
- processed = len(messages) - dlq_count
- logger.debug("batch_committed", message_count=processed, dlq_count=dlq_count)
-
- def _process_single_with_inprocess_retry(
- self, message: Any, health_reporter: Optional[Callable[[], None]] = None
- ) -> None:
- """Process a single message with in-process retries for transient errors.
-
- This handles fast-recovering transient errors (e.g. brief DB connection
- blip) without needing a full Kafka redeliver cycle. The persistent retry
- tracker in Redis is the outer safety net for process crashes.
- """
- team_id = str(message.get("team_id") or "unknown")
- schema_id = str(message.get("schema_id") or "unknown")
- for attempt in range(self._config.max_retries):
- try:
- with BATCH_PROCESSING_DURATION_SECONDS.labels(team_id=team_id, schema_id=schema_id).time():
- self._process_message(message, progress_callback=health_reporter)
- if health_reporter:
- health_reporter()
- return
- except TRANSIENT_ERRORS as e:
- BATCH_RETRY_TOTAL.labels(attempt=str(attempt + 1), error_type=type(e).__name__).inc()
- if attempt == self._config.max_retries - 1:
- raise
- backoff = self._config.retry_backoff_seconds * (2**attempt)
- logger.warning(
- "transient_error_inprocess_retry",
- attempt=attempt + 1,
- max_retries=self._config.max_retries,
- backoff_seconds=backoff,
- error_type=type(e).__name__,
- )
- time.sleep(backoff)
-
- def _mark_job_failed_from_message(self, message: Any, error: Exception) -> None:
- """Mark the job as failed when persistent retries are exhausted."""
- try:
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import (
- ExportSignalMessage,
- )
- from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.processor import (
- _mark_job_failed,
- )
-
- export_signal = ExportSignalMessage.from_dict(message)
- _mark_job_failed(export_signal, error)
- except Exception as e:
- logger.exception("failed_to_mark_job_failed", error_type=type(e).__name__)
- capture_exception(e)
-
- def _cleanup(self) -> None:
- logger.info("consumer_shutting_down")
-
- if self._consumer:
- try:
- self._consumer.close()
- logger.info("consumer_closed")
- except Exception as e:
- logger.exception("consumer_close_failed")
- capture_exception(e)
-
- logger.info("consumer_shutdown_complete")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/metrics.py
deleted file mode 100644
index 1a0df950a9a2..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/metrics.py
+++ /dev/null
@@ -1,51 +0,0 @@
-from prometheus_client import Counter, Gauge, Histogram
-
-MESSAGES_PROCESSED_TOTAL = Counter(
- "warehouse_consumer_messages_processed_total",
- "Total messages processed by the warehouse consumer",
- labelnames=["team_id", "schema_id", "status"],
-)
-
-BATCH_PROCESSING_DURATION_SECONDS = Histogram(
- "warehouse_consumer_batch_processing_duration_seconds",
- "Duration of batch processing in the warehouse consumer",
- labelnames=["team_id", "schema_id"],
- buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
-)
-
-DLQ_MESSAGES_TOTAL = Counter(
- "warehouse_consumer_dlq_messages_total",
- "Total messages sent to the dead-letter queue",
- labelnames=["team_id", "schema_id", "error_type"],
-)
-
-BATCH_RETRY_TOTAL = Counter(
- "warehouse_consumer_batch_retry_total",
- "Total batch retry attempts",
- labelnames=["attempt", "error_type"],
-)
-
-BATCH_RETRY_EXHAUSTED_TOTAL = Counter(
- "warehouse_consumer_batch_retry_exhausted_total",
- "Total batches that exhausted all retries",
- labelnames=["error_type"],
-)
-
-OFFSET_COMMITS_TOTAL = Counter(
- "warehouse_consumer_offset_commits_total",
- "Total offset commit attempts",
- labelnames=["status"],
-)
-
-BATCH_SIZE = Histogram(
- "warehouse_consumer_batch_size",
- "Number of messages in each consumed batch",
- buckets=(1, 5, 10, 25, 50, 100, 250, 500, 1000),
-)
-
-BATCH_UTILIZATION = Gauge(
- "warehouse_consumer_batch_utilization",
- "Ratio of messages returned per consume call to configured batch size (0.0-1.0). Leading signal for autoscaling — sustained high values mean the consumer is saturating.",
- labelnames=["group_id"],
- multiprocess_mode="liveall",
-)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/producer.py
deleted file mode 100644
index e2cf142f2f83..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/producer.py
+++ /dev/null
@@ -1,184 +0,0 @@
-from typing import Any, Optional
-
-from structlog.types import FilteringBoundLogger
-from temporalio import activity
-
-from posthog.exceptions_capture import capture_exception
-from posthog.kafka_client.topics import KAFKA_WAREHOUSE_SOURCES_JOBS
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import (
- ExportSignalMessage,
- SyncTypeLiteral,
- get_warpstream_kafka_producer,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.metrics import (
- get_kafka_flush_failures_metric,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
- PartitionFormat,
- PartitionMode,
-)
-
-
-class KafkaBatchProducer:
- _team_id: int
- _job_id: str
- _schema_id: str
- _source_id: str
- _resource_name: str
- _sync_type: SyncTypeLiteral
- _run_uuid: str
- _primary_keys: list[str] | None
- _is_resume: bool
- _logger: FilteringBoundLogger
- _producer: Any
- _pending_futures: list[Any]
- # Partitioning fields
- _partition_count: int | None
- _partition_size: int | None
- _partition_keys: list[str] | None
- _partition_format: PartitionFormat | None
- _partition_mode: PartitionMode | None
- # Partial data loading fields
- _is_first_ever_sync: bool
- # CDC write mode fields
- _cdc_write_mode: str | None
- _cdc_table_mode: str | None
-
- def __init__(
- self,
- team_id: int,
- job_id: str,
- schema_id: str,
- source_id: str,
- resource_name: str,
- sync_type: SyncTypeLiteral,
- run_uuid: str,
- logger: FilteringBoundLogger,
- primary_keys: list[str] | None = None,
- is_resume: bool = False,
- partition_count: int | None = None,
- partition_size: int | None = None,
- partition_keys: list[str] | None = None,
- partition_format: PartitionFormat | None = None,
- partition_mode: PartitionMode | None = None,
- is_first_ever_sync: bool = False,
- cdc_write_mode: str | None = None,
- cdc_table_mode: str | None = None,
- ) -> None:
- self._team_id = team_id
- self._job_id = job_id
- self._schema_id = schema_id
- self._source_id = source_id
- self._resource_name = resource_name
- self._sync_type = sync_type
- self._run_uuid = run_uuid
- self._primary_keys = primary_keys
- self._is_resume = is_resume
- self._logger = logger
- self._producer = get_warpstream_kafka_producer()
- self._pending_futures = []
- # Partitioning fields
- self._partition_count = partition_count
- self._partition_size = partition_size
- self._partition_keys = partition_keys
- self._partition_format = partition_format
- self._partition_mode = partition_mode
- # Partial data loading fields
- self._is_first_ever_sync = is_first_ever_sync
- # CDC write mode fields
- self._cdc_write_mode = cdc_write_mode
- self._cdc_table_mode = cdc_table_mode
-
- @property
- def sync_type(self) -> SyncTypeLiteral:
- return self._sync_type
-
- @property
- def is_first_ever_sync(self) -> bool:
- return self._is_first_ever_sync
-
- @is_first_ever_sync.setter
- def is_first_ever_sync(self, value: bool) -> None:
- self._is_first_ever_sync = value
-
- def _get_key(self) -> str:
- return f"{self._team_id}:{self._schema_id}" # we want ordering across multiple runs for the same schema
-
- def send_batch_notification(
- self,
- batch_result: BatchWriteResult,
- is_final_batch: bool = False,
- total_batches: Optional[int] = None,
- total_rows: Optional[int] = None,
- data_folder: Optional[str] = None,
- schema_path: Optional[str] = None,
- cumulative_row_count: int = 0,
- ) -> None:
- message = ExportSignalMessage(
- team_id=self._team_id,
- job_id=self._job_id,
- schema_id=self._schema_id,
- source_id=self._source_id,
- resource_name=self._resource_name,
- run_uuid=self._run_uuid,
- batch_index=batch_result.batch_index,
- s3_path=batch_result.s3_path,
- row_count=batch_result.row_count,
- byte_size=batch_result.byte_size,
- is_final_batch=is_final_batch,
- total_batches=total_batches,
- total_rows=total_rows,
- sync_type=self._sync_type,
- data_folder=data_folder,
- schema_path=schema_path,
- primary_keys=self._primary_keys,
- is_resume=self._is_resume,
- timestamp_ns=batch_result.timestamp_ns,
- partition_count=self._partition_count,
- partition_size=self._partition_size,
- partition_keys=self._partition_keys,
- partition_format=self._partition_format,
- partition_mode=self._partition_mode,
- is_first_ever_sync=self._is_first_ever_sync,
- cumulative_row_count=cumulative_row_count,
- cdc_write_mode=self._cdc_write_mode,
- cdc_table_mode=self._cdc_table_mode,
- )
-
- self._logger.debug(
- "Sending batch notification to Kafka",
- batch_index=batch_result.batch_index,
- is_final_batch=is_final_batch,
- )
-
- future = self._producer.produce(
- topic=KAFKA_WAREHOUSE_SOURCES_JOBS,
- data=message.to_dict(),
- key=self._get_key(),
- )
- self._pending_futures.append(future)
-
- def flush(self, timeout: Optional[float] = None) -> int:
- self._logger.debug(f"Flushing {len(self._pending_futures)} pending Kafka messages")
- self._producer.flush(timeout=timeout)
-
- errors: list[Exception] = []
- for future in self._pending_futures:
- try:
- future.get(timeout=0)
- except Exception as e:
- capture_exception(e)
- errors.append(e)
-
- flushed_count = len(self._pending_futures)
- self._pending_futures = []
-
- if errors:
- if activity.in_activity():
- get_kafka_flush_failures_metric().add(len(errors))
- raise Exception(f"Failed to deliver {len(errors)}/{flushed_count} Kafka messages: {errors[0]}")
-
- self._logger.debug(f"Successfully flushed {flushed_count} messages")
- return flushed_count
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py
deleted file mode 100644
index 74528b89c207..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py
+++ /dev/null
@@ -1,611 +0,0 @@
-from typing import Any, cast
-
-import pytest
-from unittest.mock import MagicMock, patch
-
-from parameterized import parameterized
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer import (
- KafkaConsumerService,
- _extract_message_key,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.config import ConsumerConfig
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.retry_tracker import RetryInfo
-
-
-def _make_config(**kwargs) -> ConsumerConfig:
- defaults: dict[str, Any] = {
- "input_topic": "test-topic",
- "consumer_group": "test-group",
- "dlq_topic": "test-dlq",
- }
- defaults.update(kwargs)
- return ConsumerConfig(**defaults)
-
-
-def _make_service(**kwargs) -> KafkaConsumerService:
- # Hosts + protocol are inherited from the routing DEFAULT profile
- # (`["kafka:9092"]` / PLAINTEXT) unless explicitly injected via kwargs.
- defaults: dict = {
- "config": _make_config(),
- "process_message": MagicMock(),
- }
- defaults.update(kwargs)
- return KafkaConsumerService(**defaults)
-
-
-class TestKafkaConsumerServiceConfig:
- def test_consumer_uses_latest_offset_reset(self):
- service = _make_service()
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.ConfluentConsumer"
- ) as mock_consumer_cls:
- mock_consumer_cls.return_value = MagicMock()
- service._create_consumer()
-
- config = mock_consumer_cls.call_args[0][0]
- assert config["auto.offset.reset"] == "latest"
-
- def test_subscribe_registers_callbacks(self):
- service = _make_service()
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.ConfluentConsumer"
- ) as mock_consumer_cls:
- mock_instance = MagicMock()
- mock_consumer_cls.return_value = mock_instance
- service._create_consumer()
-
- mock_instance.subscribe.assert_called_once_with(
- ["test-topic"],
- on_assign=service._on_assign,
- on_revoke=service._on_revoke,
- on_lost=service._on_lost,
- )
-
-
-class TestKafkaConsumerServiceCallbacks:
- @parameterized.expand(
- [
- ("single_partition", [("test-topic", 0, 42)]),
- ("multiple_partitions", [("test-topic", 0, 10), ("test-topic", 1, 20)]),
- ]
- )
- def test_on_assign_logs_partition_info(self, _name, partition_data):
- service = _make_service()
- partitions = []
- for topic, partition, offset in partition_data:
- p = MagicMock()
- p.topic = topic
- p.partition = partition
- p.offset = offset
- partitions.append(p)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- service._on_assign(MagicMock(), partitions)
-
- assert mock_logger.info.call_count == len(partition_data)
- for topic, partition, offset in partition_data:
- mock_logger.info.assert_any_call(
- "partition_assigned",
- topic=topic,
- partition=partition,
- offset=offset,
- )
-
- @parameterized.expand(
- [
- ("single_partition", [("test-topic", 0, 42)]),
- ("multiple_partitions", [("test-topic", 0, 10), ("test-topic", 1, 20)]),
- ]
- )
- def test_on_revoke_logs_partition_info(self, _name, partition_data):
- service = _make_service()
- partitions = []
- for topic, partition, offset in partition_data:
- p = MagicMock()
- p.topic = topic
- p.partition = partition
- p.offset = offset
- partitions.append(p)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- mock_consumer = MagicMock()
- service._on_revoke(mock_consumer, partitions)
-
- expected_partitions = [{"topic": t, "partition": p} for t, p, _ in partition_data]
- mock_logger.info.assert_any_call(
- "partition_revocation_starting",
- revoked_partition_count=len(partition_data),
- revoked_partitions=expected_partitions,
- )
- mock_logger.info.assert_any_call(
- "partition_revocation_complete",
- revoked_partition_count=len(partition_data),
- )
- mock_consumer.commit.assert_called_once_with(asynchronous=False)
-
- @parameterized.expand(
- [
- ("single_partition", [("test-topic", 0, 42)]),
- ("multiple_partitions", [("test-topic", 0, 10), ("test-topic", 1, 20)]),
- ]
- )
- def test_on_lost_logs_warning_and_does_not_commit(self, _name, partition_data):
- service = _make_service()
- partitions = []
- for topic, partition, offset in partition_data:
- p = MagicMock()
- p.topic = topic
- p.partition = partition
- p.offset = offset
- partitions.append(p)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- mock_consumer = MagicMock()
- service._on_lost(mock_consumer, partitions)
-
- expected_partitions = [{"topic": t, "partition": p} for t, p, _ in partition_data]
- mock_logger.warning.assert_called_once_with(
- "partitions_lost",
- lost_partition_count=len(partition_data),
- lost_partitions=expected_partitions,
- )
- mock_consumer.commit.assert_not_called()
-
- def test_on_revoke_logs_warning_on_commit_failure(self):
- service = _make_service()
- mock_consumer = MagicMock()
- mock_consumer.commit.side_effect = Exception("commit failed")
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- service._on_revoke(mock_consumer, [])
-
- mock_logger.warning.assert_called_once_with("failed_to_commit_on_revoke", error="commit failed")
-
- def test_on_revoke_logs_debug_on_no_offset(self):
- from confluent_kafka import KafkaError, KafkaException
-
- service = _make_service()
- mock_consumer = MagicMock()
- kafka_error = KafkaError(KafkaError._NO_OFFSET) # type: ignore[attr-defined]
- mock_consumer.commit.side_effect = KafkaException(kafka_error)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- service._on_revoke(mock_consumer, [])
-
- mock_logger.debug.assert_called_once_with("no_offsets_to_commit_on_revoke")
- mock_logger.warning.assert_not_called()
-
- def test_on_revoke_logs_warning_on_kafka_exception(self):
- from confluent_kafka import KafkaError, KafkaException
-
- service = _make_service()
- mock_consumer = MagicMock()
- kafka_error = KafkaError(KafkaError._FAIL) # type: ignore[attr-defined]
- mock_consumer.commit.side_effect = KafkaException(kafka_error)
-
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer.logger"
- ) as mock_logger:
- service._on_revoke(mock_consumer, [])
-
- mock_logger.warning.assert_called_once()
-
-
-def _make_message(**overrides) -> dict:
- defaults: dict[str, Any] = {
- "team_id": 1,
- "schema_id": "schema-1",
- "run_uuid": "run-1",
- "batch_index": 0,
- "job_id": "job-1",
- "source_id": "source-1",
- "resource_name": "test_resource",
- "s3_path": "s3://bucket/path",
- "row_count": 100,
- "byte_size": 1024,
- "is_final_batch": False,
- "total_batches": None,
- "total_rows": None,
- "sync_type": "full_refresh",
- "data_folder": None,
- "schema_path": None,
- "primary_keys": None,
- }
- defaults.update(overrides)
- return defaults
-
-
-RETRY_TRACKER_PATH = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.consumer"
-
-
-class TestExtractMessageKey:
- def test_extracts_key_from_valid_message(self):
- msg = _make_message()
- assert _extract_message_key(msg) == (1, "schema-1", "run-1", 0)
-
- @parameterized.expand(
- [
- ("missing_team_id", {"schema_id": "s", "run_uuid": "r", "batch_index": 0}),
- ("missing_schema_id", {"team_id": 1, "run_uuid": "r", "batch_index": 0}),
- ("missing_run_uuid", {"team_id": 1, "schema_id": "s", "batch_index": 0}),
- ("missing_batch_index", {"team_id": 1, "schema_id": "s", "run_uuid": "r"}),
- ("empty_dict", {}),
- ]
- )
- def test_returns_none_for_incomplete_message(self, _name, msg):
- assert _extract_message_key(msg) is None
-
-
-def _wrap(*messages: dict) -> list[tuple[Any, dict]]:
- """Pair each message dict with a MagicMock standing in for a confluent_kafka.Message."""
- return [(MagicMock(name=f"raw_msg_{i}"), m) for i, m in enumerate(messages)]
-
-
-class TestProcessBatchPersistentRetry:
- def _setup_service(self, process_message: Any = None) -> KafkaConsumerService:
- service = _make_service(process_message=process_message or MagicMock())
- service._consumer = MagicMock()
- return service
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_successful_processing_clears_retry_info(self, mock_get, mock_inc, mock_clear):
- service = self._setup_service()
- msg = _make_message()
-
- service._process_batch_with_retry(_wrap(msg))
-
- mock_inc.assert_called_once_with(1, "schema-1", "run-1", 0)
- mock_clear.assert_called_once_with(1, "schema-1", "run-1", 0)
- consumer = cast(MagicMock, service._consumer)
- # Success path: exactly one trailing batch commit, no per-message commit.
- consumer.commit.assert_called_once_with()
-
- @patch(f"{RETRY_TRACKER_PATH}.update_retry_error_type")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_non_exhausted_failure_reraises(self, mock_get, mock_inc, mock_update):
- process_fn = MagicMock(side_effect=ValueError("bad data"))
- service = self._setup_service(process_message=process_fn)
- msg = _make_message()
-
- with pytest.raises(ValueError, match="bad data"):
- service._process_batch_with_retry(_wrap(msg))
-
- mock_update.assert_called_once_with(
- 1, "schema-1", "run-1", 0, error_type="non_transient", last_error="bad data"
- )
- cast(MagicMock, service._consumer).commit.assert_not_called()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.update_retry_error_type")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=4, error_type="non_transient"))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=3, error_type="non_transient"))
- def test_exhausted_after_attempt_sends_to_dlq(self, mock_get, mock_inc, mock_update, mock_clear):
- process_fn = MagicMock(side_effect=ValueError("bad data"))
- service = self._setup_service(process_message=process_fn)
- msg = _make_message()
- wrapped = _wrap(msg)
- raw_msg = wrapped[0][0]
-
- with (
- patch.object(service, "_send_to_dlq") as mock_dlq,
- patch.object(service, "_mark_job_failed_from_message") as mock_fail,
- ):
- service._process_batch_with_retry(wrapped)
-
- mock_dlq.assert_called_once()
- mock_fail.assert_called_once()
- # Retry state must NOT be cleared — redelivery relies on it to re-DLQ
- # idempotently if any commit fails after DLQ'ing.
- mock_clear.assert_not_called()
- consumer = cast(MagicMock, service._consumer)
- # Per-message commit fires right after DLQ, trailing batch commit after the loop.
- assert consumer.commit.call_count == 2
- consumer.commit.assert_any_call(message=raw_msg, asynchronous=False)
- consumer.commit.assert_any_call()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count")
- @patch(
- f"{RETRY_TRACKER_PATH}.get_retry_info",
- return_value=RetryInfo(count=4, error_type="non_transient", last_error="previous error"),
- )
- def test_already_exhausted_skips_processing(self, mock_get, mock_inc, mock_clear):
- process_fn = MagicMock()
- service = self._setup_service(process_message=process_fn)
- msg = _make_message()
- wrapped = _wrap(msg)
- raw_msg = wrapped[0][0]
-
- with (
- patch.object(service, "_send_to_dlq") as mock_dlq,
- patch.object(service, "_mark_job_failed_from_message") as mock_fail,
- ):
- service._process_batch_with_retry(wrapped)
-
- process_fn.assert_not_called()
- mock_inc.assert_not_called()
- mock_dlq.assert_called_once()
- mock_fail.assert_called_once()
- mock_clear.assert_not_called()
- consumer = cast(MagicMock, service._consumer)
- assert consumer.commit.call_count == 2
- consumer.commit.assert_any_call(message=raw_msg, asynchronous=False)
- consumer.commit.assert_any_call()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_pre_increments_before_processing(self, mock_get, mock_inc, mock_clear):
- call_order: list[str] = []
-
- def track_process(msg, **kwargs):
- call_order.append("process")
-
- def _increment_side_effect(*a: Any) -> RetryInfo:
- call_order.append("increment")
- return RetryInfo(count=1)
-
- mock_inc.side_effect = _increment_side_effect
-
- service = self._setup_service(process_message=track_process)
- msg = _make_message()
-
- service._process_batch_with_retry(_wrap(msg))
-
- assert call_order == ["increment", "process"]
-
- # The in-process retry loop sleeps its real exponential backoff between attempts; skip it.
- @patch("time.sleep", return_value=None)
- @patch(f"{RETRY_TRACKER_PATH}.update_retry_error_type")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_transient_error_classified_correctly(self, mock_get, mock_inc, mock_update, _sleep):
- process_fn = MagicMock(side_effect=ConnectionError("reset"))
- service = self._setup_service(process_message=process_fn)
- msg = _make_message()
-
- with pytest.raises(ConnectionError):
- service._process_batch_with_retry(_wrap(msg))
-
- mock_update.assert_called_once_with(1, "schema-1", "run-1", 0, error_type="transient", last_error="reset")
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count")
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info")
- def test_multiple_messages_first_fails_second_not_attempted(self, mock_get, mock_inc, mock_clear):
- call_count = 0
-
- def process_fn(msg, **kwargs):
- nonlocal call_count
- call_count += 1
- if msg["batch_index"] == 0:
- raise ValueError("bad")
-
- mock_get.return_value = RetryInfo(count=0)
- mock_inc.return_value = RetryInfo(count=1)
-
- service = self._setup_service(process_message=process_fn)
- msg1 = _make_message(batch_index=0)
- msg2 = _make_message(batch_index=1)
-
- with pytest.raises(ValueError):
- service._process_batch_with_retry(_wrap(msg1, msg2))
-
- # Only the first message was attempted
- assert call_count == 1
- cast(MagicMock, service._consumer).commit.assert_not_called()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count")
- @patch(
- f"{RETRY_TRACKER_PATH}.get_retry_info",
- return_value=RetryInfo(count=4, error_type="non_transient", last_error="previous error"),
- )
- def test_redelivered_exhausted_message_redlqs_idempotently(self, mock_get, mock_inc, mock_clear):
- """On redelivery of a message that was DLQ'd but whose offset never advanced,
- the exhausted retry state in Redis must cause a fresh DLQ + per-message commit
- rather than a new retry cycle. Two deliveries → two DLQ sends, two per-message
- commits, zero process_message calls, zero clear_retry_info calls."""
- process_fn = MagicMock()
- service = self._setup_service(process_message=process_fn)
- msg = _make_message()
-
- with (
- patch.object(service, "_send_to_dlq") as mock_dlq,
- patch.object(service, "_mark_job_failed_from_message") as mock_fail,
- ):
- first = _wrap(msg)
- service._process_batch_with_retry(first)
-
- second = _wrap(msg)
- service._process_batch_with_retry(second)
-
- process_fn.assert_not_called()
- mock_inc.assert_not_called()
- mock_clear.assert_not_called()
- assert mock_dlq.call_count == 2
- assert mock_fail.call_count == 2
-
- consumer = cast(MagicMock, service._consumer)
- # Each delivery: 1 per-message commit on DLQ + 1 trailing batch commit = 2.
- assert consumer.commit.call_count == 4
- consumer.commit.assert_any_call(message=first[0][0], asynchronous=False)
- consumer.commit.assert_any_call(message=second[0][0], asynchronous=False)
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.update_retry_error_type")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- def test_sibling_failure_does_not_unwind_dlq_offset(self, mock_inc, mock_update, mock_clear):
- """Batch [A exhausted-on-arrival, B raises non-exhausted]. A must be DLQ'd and
- its offset committed via per-message commit *before* B's raise propagates out.
- The trailing batch commit is skipped — but A's offset has already advanced, so
- on redelivery A is no longer in the batch."""
- with patch(f"{RETRY_TRACKER_PATH}.get_retry_info") as mock_get:
- # A is exhausted on arrival; B starts fresh.
- mock_get.side_effect = [
- RetryInfo(count=4, error_type="non_transient", last_error="earlier"),
- RetryInfo(count=0),
- ]
-
- process_fn = MagicMock(side_effect=ValueError("B fails"))
- service = self._setup_service(process_message=process_fn)
- msg_a = _make_message(batch_index=0)
- msg_b = _make_message(batch_index=1)
- wrapped = _wrap(msg_a, msg_b)
- raw_a = wrapped[0][0]
-
- with (
- patch.object(service, "_send_to_dlq") as mock_dlq,
- patch.object(service, "_mark_job_failed_from_message") as mock_fail,
- pytest.raises(ValueError, match="B fails"),
- ):
- service._process_batch_with_retry(wrapped)
-
- # A was DLQ'd, B was attempted and failed.
- mock_dlq.assert_called_once()
- mock_fail.assert_called_once()
- process_fn.assert_called_once()
- mock_clear.assert_not_called()
-
- consumer = cast(MagicMock, service._consumer)
- # Only A's per-message commit — B's raise aborts the trailing batch commit.
- consumer.commit.assert_called_once_with(message=raw_a, asynchronous=False)
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_success_path_uses_batch_commit_not_per_message(self, mock_get, mock_inc, mock_clear):
- service = self._setup_service()
- msgs = [_make_message(batch_index=i) for i in range(3)]
-
- service._process_batch_with_retry(_wrap(*msgs))
-
- consumer = cast(MagicMock, service._consumer)
- consumer.commit.assert_called_once_with()
- # No per-message commit was issued on any message.
- for call in consumer.commit.call_args_list:
- assert call.kwargs.get("message") is None
-
-
-class TestProcessBatchGracefulShutdown:
- def _setup_service(self, process_message: Any = None) -> KafkaConsumerService:
- service = _make_service(process_message=process_message or MagicMock())
- service._consumer = MagicMock()
- return service
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count")
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info")
- def test_shutdown_before_batch_processes_nothing(self, mock_get, mock_inc, mock_clear):
- """Shutdown flag set before the loop starts: no message touched, retry
- tracker never queried, single early-return commit on the consumer."""
- process_fn = MagicMock()
- service = self._setup_service(process_message=process_fn)
- service._shutdown_requested = True
- msgs = [_make_message(batch_index=i) for i in range(3)]
-
- service._process_batch_with_retry(_wrap(*msgs))
-
- process_fn.assert_not_called()
- mock_get.assert_not_called()
- mock_inc.assert_not_called()
- mock_clear.assert_not_called()
- cast(MagicMock, service._consumer).commit.assert_called_once_with()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_shutdown_mid_batch_stops_after_current_message(self, mock_get, mock_inc, mock_clear):
- """Flipping _shutdown_requested while processing message K should let K
- finish cleanly, skip K+1..N, commit once for K, and not run the trailing
- batch commit."""
- processed: list[int] = []
- service_holder: dict[str, KafkaConsumerService] = {}
-
- def process_fn(msg, **kwargs):
- processed.append(msg["batch_index"])
- service_holder["svc"]._shutdown_requested = True
-
- service = self._setup_service(process_message=process_fn)
- service_holder["svc"] = service
- msgs = [_make_message(batch_index=i) for i in range(3)]
-
- service._process_batch_with_retry(_wrap(*msgs))
-
- # Only message 0 was touched; retry_info cleared for it and nothing else.
- assert processed == [0]
- mock_clear.assert_called_once_with(1, "schema-1", "run-1", 0)
- consumer = cast(MagicMock, service._consumer)
- # Exactly one commit — the early-return shutdown commit. The trailing
- # batch commit never runs because we returned early.
- consumer.commit.assert_called_once_with()
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))
- @patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))
- def test_shutdown_commit_failure_is_swallowed(self, mock_get, mock_inc, mock_clear):
- """If the shutdown-path commit raises (broker down), we must still return
- cleanly — shutdown should not depend on broker availability."""
- service = self._setup_service()
- cast(MagicMock, service._consumer).commit.side_effect = Exception("broker down")
- service._shutdown_requested = True
- msgs = [_make_message(batch_index=i) for i in range(2)]
-
- # Must not raise.
- service._process_batch_with_retry(_wrap(*msgs))
-
- @patch(f"{RETRY_TRACKER_PATH}.clear_retry_info")
- @patch(f"{RETRY_TRACKER_PATH}.increment_retry_count")
- @patch(
- f"{RETRY_TRACKER_PATH}.get_retry_info",
- return_value=RetryInfo(count=4, error_type="non_transient", last_error="previous error"),
- )
- def test_shutdown_after_dlq_still_runs_batch_commit(self, mock_get, mock_inc, mock_clear):
- """Batch [A already-exhausted, B healthy]. A is DLQ'd with its own
- per-message commit. Shutdown is flipped before B starts. The early-return
- commit still fires — which is fine: kafka commit() is idempotent over
- A's already-committed offset."""
- process_fn = MagicMock()
- service = self._setup_service(process_message=process_fn)
- msg_a = _make_message(batch_index=0)
- msg_b = _make_message(batch_index=1)
- wrapped = _wrap(msg_a, msg_b)
- raw_a = wrapped[0][0]
-
- with (
- patch.object(service, "_send_to_dlq") as mock_dlq,
- patch.object(service, "_mark_job_failed_from_message") as mock_fail,
- ):
-
- def dlq_then_shutdown(*args, **kwargs):
- service._shutdown_requested = True
-
- mock_dlq.side_effect = dlq_then_shutdown
- service._process_batch_with_retry(wrapped)
-
- # A was DLQ'd, B was never processed.
- mock_dlq.assert_called_once()
- mock_fail.assert_called_once()
- process_fn.assert_not_called()
-
- consumer = cast(MagicMock, service._consumer)
- # Per-message commit for A + early-return batch commit = 2 calls.
- assert consumer.commit.call_count == 2
- consumer.commit.assert_any_call(message=raw_a, asynchronous=False)
- consumer.commit.assert_any_call()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_producer.py
deleted file mode 100644
index b82729ea1b51..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_producer.py
+++ /dev/null
@@ -1,126 +0,0 @@
-import pytest
-from unittest.mock import MagicMock, patch
-
-from confluent_kafka import KafkaError, KafkaException
-from parameterized import parameterized
-
-from posthog.kafka_client.client import ProduceResult
-
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.producer import (
- KafkaBatchProducer,
-)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import BatchWriteResult
-
-
-def _make_producer(**kwargs) -> KafkaBatchProducer:
- defaults = {
- "team_id": 1,
- "job_id": "job-1",
- "schema_id": "schema-1",
- "source_id": "source-1",
- "resource_name": "test_resource",
- "sync_type": "full_refresh",
- "run_uuid": "run-1",
- "logger": MagicMock(),
- }
- defaults.update(kwargs)
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.producer.get_warpstream_kafka_producer"
- ) as mock_get:
- mock_get.return_value = MagicMock()
- return KafkaBatchProducer(**defaults) # type: ignore[arg-type]
-
-
-def _make_batch_result(batch_index: int = 0) -> BatchWriteResult:
- return BatchWriteResult(
- batch_index=batch_index,
- s3_path="s3://bucket/path",
- row_count=100,
- byte_size=1024,
- timestamp_ns=0,
- )
-
-
-def _successful_future() -> MagicMock:
- future = MagicMock(spec=ProduceResult)
- future.get.return_value = None
- return future
-
-
-def _failed_future(error_msg: str = "delivery failed") -> MagicMock:
- future = MagicMock(spec=ProduceResult)
- future.get.side_effect = KafkaException(KafkaError._MSG_TIMED_OUT, error_msg) # type: ignore[attr-defined]
- return future
-
-
-class TestKafkaBatchProducerFlush:
- def test_flush_returns_count_on_success(self):
- producer = _make_producer()
- producer._pending_futures = [_successful_future(), _successful_future()]
-
- result = producer.flush()
-
- assert result == 2
- assert producer._pending_futures == []
-
- def test_flush_returns_zero_when_no_pending(self):
- producer = _make_producer()
-
- result = producer.flush()
-
- assert result == 0
-
- def test_flush_raises_on_single_error(self):
- producer = _make_producer()
- producer._pending_futures = [_failed_future()]
-
- with pytest.raises(Exception, match="Failed to deliver 1/1 Kafka messages"):
- producer.flush()
-
- assert producer._pending_futures == []
-
- def test_flush_raises_on_partial_errors(self):
- producer = _make_producer()
- producer._pending_futures = [
- _successful_future(),
- _failed_future("first error"),
- _successful_future(),
- _failed_future("second error"),
- ]
-
- with pytest.raises(Exception, match="Failed to deliver 2/4 Kafka messages"):
- producer.flush()
-
- assert producer._pending_futures == []
-
- @parameterized.expand(
- [
- ("all_fail", [True, True, True], 3, 3),
- ("one_fails", [False, True, False], 1, 3),
- ]
- )
- def test_flush_error_counts(self, _name, failure_flags, expected_errors, expected_total):
- producer = _make_producer()
- producer._pending_futures = [
- _failed_future() if should_fail else _successful_future() for should_fail in failure_flags
- ]
-
- with pytest.raises(Exception, match=f"Failed to deliver {expected_errors}/{expected_total} Kafka messages"):
- producer.flush()
-
- def test_flush_clears_futures_even_on_error(self):
- producer = _make_producer()
- producer._pending_futures = [_failed_future()]
-
- with pytest.raises(Exception):
- producer.flush()
-
- assert producer._pending_futures == []
-
- def test_flush_passes_timeout_to_underlying_producer(self):
- producer = _make_producer()
- producer._pending_futures = [_successful_future()]
-
- producer.flush(timeout=5.0)
-
- producer._producer.flush.assert_called_once_with(timeout=5.0)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/__init__.py
index f3e02df33569..8a444e8ec10f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/__init__.py
@@ -1,4 +1,3 @@
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.config import ConsumerConfig
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.health import (
HealthState,
start_health_server,
@@ -8,7 +7,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
)
__all__ = [
- "ConsumerConfig",
"HealthState",
"process_message",
"start_health_server",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/config.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/config.py
deleted file mode 100644
index 292e0be96bf3..000000000000
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/config.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from dataclasses import dataclass
-
-
-@dataclass
-class ConsumerConfig:
- """Configuration for the Kafka consumer service."""
-
- input_topic: str
- consumer_group: str
- dlq_topic: str
- batch_size: int = 1000
- batch_timeout_seconds: float = 5.0
- health_port: int = 8080
- health_timeout_seconds: float = 60.0
- max_retries: int = 3
- retry_backoff_seconds: float = 1.0
- # librdkafka group-membership tuning. `max_poll_interval_ms` is raised above
- # librdkafka's 5-minute default because post-load processing on final batches
- # can exceed it and get the consumer evicted from the group. The other two
- # are left unset to use librdkafka's defaults (10s session, 3s heartbeat).
- max_poll_interval_ms: int = 1_080_000
- session_timeout_ms: int | None = None
- heartbeat_interval_ms: int | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index e00d6ccfb9a6..a4134d93c270 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -54,10 +54,6 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
OwnershipLostError,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import (
- ExportSignalMessage,
- SyncTypeLiteral,
-)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.load.idempotency import (
is_batch_already_processed,
mark_batch_as_processed,
@@ -68,6 +64,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
IDEMPOTENCY_HIT_TOTAL,
PARQUET_READ_DURATION_SECONDS,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import (
+ ExportSignalMessage,
+ SyncTypeLiteral,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.s3 import read_parquet
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
release_v3_pipeline_lock,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/common.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
similarity index 86%
rename from products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/common.py
rename to products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
index daa05307ee43..c50398b48854 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/common.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/messages.py
@@ -2,9 +2,6 @@ import time
from dataclasses import asdict, dataclass, field
from typing import Any, Literal, Optional
-from posthog.kafka_client.client import _KafkaProducer
-from posthog.kafka_client.routing import KafkaClusterProfile, get_producer
-
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import (
PartitionFormat,
PartitionMode,
@@ -13,14 +10,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
SyncTypeLiteral = Literal["full_refresh", "incremental", "append", "cdc"]
-def get_warpstream_kafka_producer() -> _KafkaProducer:
- """Get a singleton Kafka producer configured for WarpStream/warehouse pipelines."""
- return get_producer(profile=KafkaClusterProfile.WAREHOUSE_SOURCES)
-
-
@dataclass
class ExportSignalMessage:
- """Message structure for export signals sent to Kafka."""
+ """One extracted batch's hand-off from the extraction side to the load consumer.
+
+ Produced per batch by `postgres_queue.producer` (and the CDC extraction activities) and
+ consumed by `load.processor`. The schema predates the Postgres load queue — it was the
+ v3 Kafka transport's message format — which is why the queue bridge converts a
+ `PendingBatch` into this shape rather than the other way around.
+ """
team_id: int
job_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
index 93d01af0025f..3a5c03b6165e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/metrics.py
@@ -32,12 +32,6 @@ def get_s3_write_errors_metric(error_type: str) -> MetricCounter:
)
-def get_kafka_flush_failures_metric() -> MetricCounter:
- return activity.metric_meter().create_counter(
- "warehouse_producer_kafka_flush_failures_total", "Total Kafka flush failures"
- )
-
-
def get_pipeline_run_duration_metric(
team_id: str, source_type: str, sync_type: str, status: str
) -> MetricHistogramFloat:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
index 9084c4047e09..ebc745ef3a89 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/producer.py
@@ -16,7 +16,7 @@ import psycopg
import structlog
from structlog.types import FilteringBoundLogger
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.messages import SyncTypeLiteral
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
BATCH_TABLE,
BatchQueue,