:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): flush kafka producer before checking side-effect result (#59963)
Tue Haulunda18860c8295d
diff --git a/products/replay_vision/backend/temporal/activities/embed_indexer_observation.py b/products/replay_vision/backend/temporal/activities/embed_indexer_observation.pyindex dabcc5f376cc..9b96de30b13b 100644--- a/products/replay_vision/backend/temporal/activities/embed_indexer_observation.py+++ b/products/replay_vision/backend/temporal/activities/embed_indexer_observation.py@@ -12,6 +12,9 @@ from temporalio import activityfrom posthog.schema import EmbeddingModelNamefrom posthog.api.embedding_worker import emit_embedding_request+from posthog.kafka_client.client import ProduceResult+from posthog.kafka_client.routing import producer_scope+from posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPICfrom products.replay_vision.backend.temporal.types import EmbedIndexerObservationInputs@@ -40,27 +43,33 @@ async def embed_indexer_observation_activity(inputs: EmbedIndexerObservationInpu"observation_id": str(inputs.observation_id),}- for rendering, content in facets:- if not content.strip():- continue- result = await sync_to_async(emit_embedding_request, thread_sensitive=False)(- content=content,- team_id=inputs.team_id,- product=_PRODUCT,- document_type=_DOCUMENT_TYPE,- rendering=rendering,- document_id=str(inputs.observation_id),- models=[INDEXER_EMBEDDING_MODEL.value],- metadata=metadata,- )- # Block on the delivery callback so broker errors propagate; `.get()` raises KafkaException on failure.- await sync_to_async(result.get, thread_sensitive=False)(timeout=_KAFKA_DELIVERY_TIMEOUT_S)- logger.debug(- "replay_vision.embed_indexer.facet_emitted",- session_id=inputs.session_id,- observation_id=str(inputs.observation_id),- rendering=rendering,- )+ def emit_all() -> None:+ results: list[tuple[str, ProduceResult]] = []+ with producer_scope(topic=KAFKA_DOCUMENT_EMBEDDINGS_INPUT_TOPIC, flush_timeout=_KAFKA_DELIVERY_TIMEOUT_S):+ for rendering, content in facets:+ if not content.strip():+ continue+ result = emit_embedding_request(+ content=content,+ team_id=inputs.team_id,+ product=_PRODUCT,+ document_type=_DOCUMENT_TYPE,+ rendering=rendering,+ document_id=str(inputs.observation_id),+ models=[INDEXER_EMBEDDING_MODEL.value],+ metadata=metadata,+ )+ results.append((rendering, result))+ for rendering, result in results:+ result.get(timeout=0)+ logger.debug(+ "replay_vision.embed_indexer.facet_emitted",+ session_id=inputs.session_id,+ observation_id=str(inputs.observation_id),+ rendering=rendering,+ )++ await sync_to_async(emit_all, thread_sensitive=False)()__all__ = ["embed_indexer_observation_activity"]diff --git a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.pyindex d5665e874dd0..ef227c5f759e 100644--- a/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py+++ b/products/replay_vision/backend/temporal/activities/emit_classifier_tags.py@@ -12,8 +12,7 @@ from asgiref.sync import sync_to_asyncfrom temporalio import activityfrom temporalio.exceptions import ApplicationError-from posthog.kafka_client.client import ProduceResult-from posthog.kafka_client.routing import get_producer+from posthog.kafka_client.routing import producer_scopefrom posthog.kafka_client.topics import KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTSfrom posthog.models import Teamfrom posthog.models.event.util import format_clickhouse_timestamp@@ -68,9 +67,15 @@ async def emit_classifier_tags_activity(inputs: EmitClassifierTagsInputs) -> Non"ai_tags_fixed": list(inputs.classifier_output.tags),"ai_tags_freeform": list(inputs.classifier_output.tags_freeform),}- result = await sync_to_async(_produce, thread_sensitive=False)(payload)- # Block on the delivery callback so broker errors propagate; `.get()` raises KafkaException on failure.- await sync_to_async(result.get, thread_sensitive=False)(timeout=_KAFKA_DELIVERY_TIMEOUT_S)++ def emit() -> None:+ with producer_scope(+ topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, flush_timeout=_KAFKA_DELIVERY_TIMEOUT_S+ ) as producer:+ result = producer.produce(topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, data=payload)+ result.get(timeout=0)++ await sync_to_async(emit, thread_sensitive=False)()logger.debug("replay_vision.emit_classifier_tags.produced",session_id=inputs.session_id,@@ -80,10 +85,4 @@ async def emit_classifier_tags_activity(inputs: EmitClassifierTagsInputs) -> Non)-def _produce(payload: dict) -> ProduceResult:- return get_producer(topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS).produce(- topic=KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS, data=payload- )--__all__ = ["emit_classifier_tags_activity"]diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex e81f3ae0d1b8..056c4fab63ae 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -1150,12 +1150,11 @@ async def test_emit_classifier_tags_produces_kafka_payload() -> None:"products.replay_vision.backend.temporal.activities.emit_classifier_tags.SessionReplayEvents") as mock_se_cls,patch(- "products.replay_vision.backend.temporal.activities.emit_classifier_tags.get_producer"- ) as mock_producer_factory,+ "products.replay_vision.backend.temporal.activities.emit_classifier_tags.producer_scope"+ ) as mock_producer_scope,):mock_se_cls.return_value.get_metadata.return_value = fake_metadata- producer = MagicMock()- mock_producer_factory.return_value = producer+ producer = mock_producer_scope.return_value.__enter__.return_valueawait emit_classifier_tags_activity(inputs)@@ -1216,13 +1215,12 @@ async def test_emit_classifier_tags_raises_when_kafka_delivery_fails() -> None:"products.replay_vision.backend.temporal.activities.emit_classifier_tags.SessionReplayEvents") as mock_se_cls,patch(- "products.replay_vision.backend.temporal.activities.emit_classifier_tags.get_producer"- ) as mock_producer_factory,+ "products.replay_vision.backend.temporal.activities.emit_classifier_tags.producer_scope"+ ) as mock_producer_scope,):mock_se_cls.return_value.get_metadata.return_value = fake_metadata- producer = MagicMock()+ producer = mock_producer_scope.return_value.__enter__.return_valueproducer.produce.return_value = failed_result- mock_producer_factory.return_value = producerwith pytest.raises(RuntimeError, match="broker timeout"):await emit_classifier_tags_activity(inputs)