: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(demo): wait for kafka queue room while saving demo events (#108881)
Eli Reisman1e5e437b2c4c
diff --git a/products/demo/backend/logic/matrix/manager.py b/products/demo/backend/logic/matrix/manager.pyindex 2825e65d6976..89f58bc24c94 100644--- a/products/demo/backend/logic/matrix/manager.py+++ b/products/demo/backend/logic/matrix/manager.py@@ -1,6 +1,8 @@# ruff: noqa: T201 allow print statementsimport datetime as dt+from collections.abc import Callable+from functools import partialfrom time import sleepfrom typing import Any, Literal, cast@@ -9,6 +11,8 @@ from django.core import exceptionsfrom django.db import transactionfrom posthog.clickhouse.client import sync_execute+from posthog.kafka_client.routing import get_producer+from posthog.kafka_client.topics import KAFKA_EVENTS_JSONfrom posthog.models import Organization, OrganizationMembership, Team, Userfrom posthog.models.utils import UUIDT, generate_random_token_project@@ -24,6 +28,25 @@ from products.demo.backend.logic.matrix.taxonomy_inference import infer_taxonomyfrom .matrix import Matrixfrom .models import EVENT_IDENTIFY, SimEvent, SimPerson+# Each flush waits at most 1 second, so one event waits at most about this many seconds for queue room.+QUEUE_FULL_MAX_FLUSHES = 60+++def _produce_when_queue_has_room(produce: Callable[[], object]) -> None:+ """Run one produce, and wait for room when the local Kafka queue is full.++ confluent-kafka raises BufferError on a full queue instead of blocking. A demo run produces+ events faster than a slow broker accepts them, so flush and retry instead of failing.+ """+ for _ in range(QUEUE_FULL_MAX_FLUSHES):+ try:+ produce()+ return+ except BufferError:+ get_producer(topic=KAFKA_EVENTS_JSON).flush(timeout=1.0)+ # The last attempt lets a BufferError propagate, so a broker that stays down fails the run.+ produce()+class MatrixManager:# ID of the team under which demo data will be pre-saved@@ -292,26 +315,29 @@ class MatrixManager:for event in events:event_uuid = UUIDT(unix_time_ms=int(event.timestamp.timestamp() * 1000))- create_event(- event_uuid=event_uuid,- event=event.event,- team=team,- distinct_id=event.distinct_id,- timestamp=event.timestamp,- properties=event.properties,- person_id=event.person_id,- person_properties=event.person_properties,- person_created_at=event.person_created_at,- group0_properties=event.group0_properties,- group1_properties=event.group1_properties,- group2_properties=event.group2_properties,- group3_properties=event.group3_properties,- group4_properties=event.group4_properties,- group0_created_at=event.group0_created_at,- group1_created_at=event.group1_created_at,- group2_created_at=event.group2_created_at,- group3_created_at=event.group3_created_at,- group4_created_at=event.group4_created_at,+ _produce_when_queue_has_room(+ partial(+ create_event,+ event_uuid=event_uuid,+ event=event.event,+ team=team,+ distinct_id=event.distinct_id,+ timestamp=event.timestamp,+ properties=event.properties,+ person_id=event.person_id,+ person_properties=event.person_properties,+ person_created_at=event.person_created_at,+ group0_properties=event.group0_properties,+ group1_properties=event.group1_properties,+ group2_properties=event.group2_properties,+ group3_properties=event.group3_properties,+ group4_properties=event.group4_properties,+ group0_created_at=event.group0_created_at,+ group1_created_at=event.group1_created_at,+ group2_created_at=event.group2_created_at,+ group3_created_at=event.group3_created_at,+ group4_created_at=event.group4_created_at,+ ))@staticmethoddiff --git a/products/demo/backend/test/test_matrix_manager.py b/products/demo/backend/test/test_matrix_manager.pyindex 7a737e531766..dc79feafb729 100644--- a/products/demo/backend/test/test_matrix_manager.py+++ b/products/demo/backend/test/test_matrix_manager.py@@ -4,11 +4,21 @@ from typing import Optionalfrom zoneinfo import ZoneInfofrom posthog.test.base import ClickhouseDestroyTablesMixin+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute+from posthog.kafka_client.topics import KAFKA_EVENTS_JSONfrom posthog.models import OrganizationMembership-from products.demo.backend.logic.matrix.manager import MatrixManager+from products.demo.backend.logic.matrix.manager import (+ QUEUE_FULL_MAX_FLUSHES,+ MatrixManager,+ _produce_when_queue_has_room,+)from products.demo.backend.logic.matrix.matrix import Cluster, Matrixfrom products.demo.backend.logic.matrix.models import SimPerson, SimSessionIntent@@ -130,3 +140,35 @@ class TestMatrixManager(ClickhouseDestroyTablesMixin):)[0][0]>= 3)+++class TestProduceWhenQueueHasRoom(SimpleTestCase):+ @parameterized.expand(+ [+ ("room_on_first_try", 0, 0),+ ("queue_drains_after_flushes", 3, 3),+ ("queue_drains_on_last_attempt", QUEUE_FULL_MAX_FLUSHES, QUEUE_FULL_MAX_FLUSHES),+ ]+ )+ @patch("products.demo.backend.logic.matrix.manager.get_producer")+ def test_retries_until_the_queue_has_room(+ self, _name: str, buffer_errors: int, expected_flushes: int, mock_get_producer: MagicMock+ ) -> None:+ produce = MagicMock(side_effect=[BufferError("Local: Queue full")] * buffer_errors + [None])++ _produce_when_queue_has_room(produce)++ self.assertEqual(produce.call_count, buffer_errors + 1)+ self.assertEqual(mock_get_producer.return_value.flush.call_count, expected_flushes)++ @patch("products.demo.backend.logic.matrix.manager.get_producer")+ def test_raises_when_the_queue_stays_full(self, mock_get_producer: MagicMock) -> None:+ produce = MagicMock(side_effect=BufferError("Local: Queue full"))++ with self.assertRaises(BufferError):+ _produce_when_queue_has_room(produce)++ self.assertEqual(produce.call_count, QUEUE_FULL_MAX_FLUSHES + 1)+ self.assertEqual(mock_get_producer.return_value.flush.call_count, QUEUE_FULL_MAX_FLUSHES)+ mock_get_producer.assert_called_with(topic=KAFKA_EVENTS_JSON)+ mock_get_producer.return_value.flush.assert_called_with(timeout=1.0)