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.

fix(kafka): return undelivered count from _KafkaProducer.flush (#64313)

Arno Hillen11ba1806ce2b
diff --git a/posthog/kafka_client/client.py b/posthog/kafka_client/client.py
index 918cd7423552..4a70121c8267 100644
--- a/posthog/kafka_client/client.py
+++ b/posthog/kafka_client/client.py
@@ -322,11 +322,11 @@ class _KafkaProducer:
return result
- def flush(self, timeout: Optional[float] = None):
- if timeout is not None:
- self.producer.flush(timeout)
- else:
- self.producer.flush()
+ def flush(self, timeout: Optional[float] = None) -> int:
+ # confluent's flush() returns the count still undelivered (0 once acked);
+ # surface it so callers can detect a partial flush. It rejects a None
+ # timeout, so only pass one when set.
+ return self.producer.flush(timeout) if timeout is not None else self.producer.flush()
def close(self):
self.producer.flush()
diff --git a/posthog/kafka_client/test/test_client.py b/posthog/kafka_client/test/test_client.py
index 0d3ff02d31cd..5c7be5e253c7 100644
--- a/posthog/kafka_client/test/test_client.py
+++ b/posthog/kafka_client/test/test_client.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch
from django.test import TestCase, override_settings
+from parameterized import parameterized
+
from posthog.kafka_client.client import _KafkaProducer
from posthog.settings.kafka import KafkaProfileSettings
@@ -82,6 +84,22 @@ class KafkaClientTestCase(TestCase):
config = mock_producer_class.call_args[0][0]
self.assertEqual(config["security.protocol"], "PLAINTEXT")
+ # confluent's flush() returns the count still queued (0 once acked). The
+ # wrapper must surface that int, not swallow it as None, so callers can
+ # detect a partial flush. A None timeout calls flush() with no arg.
+ @parameterized.expand([("with_timeout", 5.0, (5.0,)), ("no_timeout", None, ())])
+ @patch("posthog.kafka_client.client.ConfluentProducer")
+ def test_flush_returns_undelivered_count(
+ self, _name: str, timeout: float | None, expected_call_args: tuple, mock_producer_class: MagicMock
+ ):
+ inner = MagicMock()
+ inner.flush.return_value = 3
+ mock_producer_class.return_value = inner
+ producer = _KafkaProducer(test=False)
+
+ self.assertEqual(producer.flush(timeout=timeout), 3)
+ inner.flush.assert_called_once_with(*expected_call_args)
+
@override_settings(
KAFKA_PROFILES=_make_profiles(
security_protocol="SASL_PLAINTEXT",