: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
feat(logs): add a logs preset to the kafka dlq replay command (#95101)
Frank Hamand8b2342929d8f
diff --git a/posthog/kafka_client/dlq_replay.py b/posthog/kafka_client/dlq_replay.pyindex 03cc837cae58..a37f5e23fc67 100644--- a/posthog/kafka_client/dlq_replay.py+++ b/posthog/kafka_client/dlq_replay.py@@ -4,10 +4,43 @@ from typing import Any, Optional, castfrom confluent_kafka import Consumer, KafkaError, KafkaException, Producer+from posthog.dataclasses import frozenfrom posthog.kafka_client.routing import get_profile_settings+from posthog.kafka_client.topics import (+ KAFKA_LOGS_INGESTION,+ KAFKA_LOGS_INGESTION_DLQ,+ KAFKA_TRACES_INGESTION,+ KAFKA_TRACES_INGESTION_DLQ,+)Header = tuple[str, bytes]++@frozen+class DLQReplayPipeline:+ """The DLQ topic, the topic it drains into, and the consumer group that tracks the drain."""++ source_topic: str+ target_topic: str+ group_id: str+++# One entry per ingestion consumer that quarantines to a DLQ this tool can drain. The topic+# constants keep the replay on the cluster the consumer uses, because routing resolves the+# exact topic string.+DLQ_REPLAY_PIPELINES: dict[str, DLQReplayPipeline] = {+ "traces": DLQReplayPipeline(+ source_topic=KAFKA_TRACES_INGESTION_DLQ,+ target_topic=KAFKA_TRACES_INGESTION,+ group_id="dlq-replay-ingestion-traces",+ ),+ "logs": DLQReplayPipeline(+ source_topic=KAFKA_LOGS_INGESTION_DLQ,+ target_topic=KAFKA_LOGS_INGESTION,+ group_id="dlq-replay-ingestion-logs",+ ),+}+# The logs/traces ingestion consumer records the resolved team on every quarantined# message, so a replay can read past a team's records without reproducing them.TEAM_ID_HEADER = "team_id"@@ -157,6 +190,7 @@ def drain_dlq(security_protocol: Optional[str] = None,skip_team_ids: frozenset[int] = frozenset(),max_messages_per_second: Optional[float] = None,+ max_message_bytes: Optional[int] = None,unassigned_timeout_seconds: float = 60.0,should_stop: Callable[[], bool] = lambda: False,log: Callable[[str], None] = print,@@ -172,8 +206,11 @@ def drain_dlq(Records whose team is in skip_team_ids are read past without reproducing, so theiroffsets advance but they stay on the DLQ. max_messages_per_second caps the produce- rate. should_stop is polled between batches so a caller can stop the run after the- current batch commits, rather than abandoning it mid-flight. A run that holds no+ rate. max_message_bytes is the largest record the producer sends; unset, it takes the+ target profile's max_request_size (KAFKA_<PROFILE>_PRODUCER_MAX_REQUEST_SIZE), and+ then the librdkafka default of 1 MiB. should_stop is polled between batches so a+ caller can stop the run after the current batch commits, rather than abandoning it+ mid-flight. A run that holds nopartitions for unassigned_timeout_seconds gives up, so a spare member of anover-subscribed group exits instead of polling forever."""@@ -209,6 +246,12 @@ def drain_dlq(),"acks": "all",}+ # A DLQ record can be as large as the ingestion producer allowed, so the replay+ # producer must accept the same size or the broker rejects the record and the run+ # stops on the first big one.+ message_max_bytes = max_message_bytes or target.producer_settings.get("max_request_size")+ if message_max_bytes:+ producer_conf["message.max.bytes"] = int(message_max_bytes)producer = Producer(producer_conf)replayed = 0diff --git a/posthog/kafka_client/profiles.py b/posthog/kafka_client/profiles.pyindex 0a42dcb8e306..80e174493b34 100644--- a/posthog/kafka_client/profiles.py+++ b/posthog/kafka_client/profiles.py@@ -17,3 +17,4 @@ class KafkaClusterProfile(StrEnum):SHARED = "shared"REPLAY = "replay"TRACES = "traces"+ LOGS = "logs"diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.pyindex 3098a6b467ba..f534707f93dc 100644--- a/posthog/kafka_client/routing.py+++ b/posthog/kafka_client/routing.py@@ -44,6 +44,8 @@ from posthog.kafka_client.topics import (KAFKA_GROUPS,KAFKA_HOG_INVOCATION_RESULTS,KAFKA_LOG_ENTRIES,+ KAFKA_LOGS_INGESTION,+ KAFKA_LOGS_INGESTION_DLQ,KAFKA_METRICS_TIME_TO_SEE_DATA,KAFKA_NOTIFICATION_EVENTS,KAFKA_PERSON,@@ -109,6 +111,9 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS: KafkaClusterProfile.REPLAY,KAFKA_TRACES_INGESTION: KafkaClusterProfile.TRACES,KAFKA_TRACES_INGESTION_DLQ: KafkaClusterProfile.TRACES,+ # --- LOGS (Warpstream logs) ---+ KAFKA_LOGS_INGESTION: KafkaClusterProfile.LOGS,+ KAFKA_LOGS_INGESTION_DLQ: KafkaClusterProfile.LOGS,}diff --git a/posthog/kafka_client/test/test_dlq_replay.py b/posthog/kafka_client/test/test_dlq_replay.pyindex 798414b68098..4c64fa2c4367 100644--- a/posthog/kafka_client/test/test_dlq_replay.py+++ b/posthog/kafka_client/test/test_dlq_replay.py@@ -131,6 +131,7 @@ class FakeConsumer:class FakeProducer:def __init__(self, delivery_error: Optional[str] = None) -> None:self.delivery_error = delivery_error+ self.conf: dict[str, Any] = {}self.produced: list[dict[str, Any]] = []self._pending: list[Callable[[Any, Any], None]] = []@@ -154,12 +155,18 @@ class DrainDlqTest(TestCase):batches: list[list[FakeMessage]],producer: FakeProducer,consumer: Optional[FakeConsumer] = None,+ producer_settings: Optional[dict[str, Any]] = None,**kwargs: Any,) -> tuple[dict[str, int], FakeConsumer]:consumer = consumer or FakeConsumer(batches)++ def build_producer(conf: dict[str, Any]) -> FakeProducer:+ producer.conf = conf+ return producer+with (patch("posthog.kafka_client.dlq_replay.Consumer", return_value=consumer),- patch("posthog.kafka_client.dlq_replay.Producer", return_value=producer),+ patch("posthog.kafka_client.dlq_replay.Producer", side_effect=build_producer),patch("posthog.kafka_client.dlq_replay.get_profile_settings",return_value=SimpleNamespace(@@ -168,6 +175,7 @@ class DrainDlqTest(TestCase):sasl_mechanism=None,sasl_user=None,sasl_password=None,+ producer_settings=producer_settings or {},),),):@@ -191,6 +199,31 @@ class DrainDlqTest(TestCase):assert [record["value"] for record in producer.produced] == [b"one", b"two"]assert dict(producer.produced[0]["headers"]) == {REPLAY_COUNT_HEADER: b"1"}+ @parameterized.expand(+ [+ ("flag_wins_over_profile", 8_000_000, {"max_request_size": 4_000_000}, 8_000_000),+ ("profile_when_flag_unset", None, {"max_request_size": 4_000_000}, 4_000_000),+ ("librdkafka_default_when_both_unset", None, {}, None),+ ]+ )+ def test_producer_message_max_bytes(+ self,+ _name: str,+ max_message_bytes: Optional[int],+ producer_settings: dict[str, Any],+ expected: Optional[int],+ ) -> None:+ producer = FakeProducer()++ self._drain(+ [[FakeMessage(b"one")]],+ producer,+ producer_settings=producer_settings,+ max_message_bytes=max_message_bytes,+ )++ assert producer.conf.get("message.max.bytes") == expected+def test_delivery_failure_is_reported_and_not_committed(self) -> None:producer = FakeProducer(delivery_error="Broker: Message too large")diff --git a/posthog/kafka_client/test/test_routing.py b/posthog/kafka_client/test/test_routing.pyindex 40cfcb713963..7886f88fc097 100644--- a/posthog/kafka_client/test/test_routing.py+++ b/posthog/kafka_client/test/test_routing.py@@ -25,6 +25,8 @@ from posthog.kafka_client.topics import (KAFKA_DEAD_LETTER_QUEUE,KAFKA_DWH_CDP_RAW_TABLE,KAFKA_EVENTS_JSON,+ KAFKA_LOGS_INGESTION,+ KAFKA_LOGS_INGESTION_DLQ,KAFKA_TRACES_INGESTION,KAFKA_TRACES_INGESTION_DLQ,KAFKA_WAREHOUSE_SOURCE_WEBHOOKS,@@ -117,6 +119,8 @@ class CurrentTopicRoutingTest(TestCase):self.assertEqual(mapping.get(KAFKA_APP_METRICS2), KafkaClusterProfile.INGESTION)self.assertEqual(mapping.get(KAFKA_TRACES_INGESTION), KafkaClusterProfile.TRACES)self.assertEqual(mapping.get(KAFKA_TRACES_INGESTION_DLQ), KafkaClusterProfile.TRACES)+ self.assertEqual(mapping.get(KAFKA_LOGS_INGESTION), KafkaClusterProfile.LOGS)+ self.assertEqual(mapping.get(KAFKA_LOGS_INGESTION_DLQ), KafkaClusterProfile.LOGS)def test_env_overrides_add_new_topic(self):# KAFKA_DEAD_LETTER_QUEUE is deliberately absent from the defaults, so this coversdiff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.pyindex 9e29c385b245..6de01fb71f03 100644--- a/posthog/kafka_client/topics.py+++ b/posthog/kafka_client/topics.py@@ -92,5 +92,8 @@ KAFKA_FLAGS_CACHE_INVALIDATION_DLQ = f"{KAFKA_PREFIX}flags_cache_invalidation_dlKAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES = f"{KAFKA_PREFIX}warehouse_person_property_updates{SUFFIX}"KAFKA_WAREHOUSE_PERSON_PROPERTY_UPDATES_DLQ = f"{KAFKA_PREFIX}warehouse_person_property_updates_dlq{SUFFIX}"+KAFKA_LOGS_INGESTION = f"{KAFKA_PREFIX}logs_ingestion{SUFFIX}"+KAFKA_LOGS_INGESTION_DLQ = f"{KAFKA_PREFIX}logs_ingestion_dlq{SUFFIX}"+KAFKA_TRACES_INGESTION = f"{KAFKA_PREFIX}ingestion-traces{SUFFIX}"KAFKA_TRACES_INGESTION_DLQ = f"{KAFKA_PREFIX}ingestion-traces-dlq{SUFFIX}"diff --git a/posthog/management/commands/replay_kafka_dlq.py b/posthog/management/commands/replay_kafka_dlq.pyindex fe8c0a508e45..f0061e1da86e 100644--- a/posthog/management/commands/replay_kafka_dlq.py+++ b/posthog/management/commands/replay_kafka_dlq.py@@ -1,25 +1,51 @@import signal+import dataclassesfrom argparse import ArgumentParserfrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError-from posthog.kafka_client.dlq_replay import drain_dlq+from posthog.kafka_client.dlq_replay import DLQ_REPLAY_PIPELINES, DLQReplayPipeline, drain_dlqdef _parse_team_ids(raw: str) -> frozenset[int]:return frozenset(int(part) for part in raw.split(",") if part.strip())+def resolve_pipeline(+ pipeline: str,+ source_topic: str | None = None,+ target_topic: str | None = None,+ group_id: str | None = None,+) -> DLQReplayPipeline:+ """Start from the named pipeline and apply any topic or group id given on the command line."""+ overrides = {+ name: value+ for name, value in (+ ("source_topic", source_topic),+ ("target_topic", target_topic),+ ("group_id", group_id),+ )+ if value is not None+ }+ return dataclasses.replace(DLQ_REPLAY_PIPELINES[pipeline], **overrides)++class Command(BaseCommand):help = "Replay a Kafka DLQ topic back into its target topic using a consumer group."def add_arguments(self, parser: ArgumentParser) -> None:- parser.add_argument("--source-topic", required=True, help="DLQ topic to read from")- parser.add_argument("--target-topic", required=True, help="Topic to replay messages to")+ parser.add_argument(+ "--pipeline",+ choices=sorted(DLQ_REPLAY_PIPELINES),+ default="traces",+ help="Ingestion pipeline whose DLQ to drain; sets the topics and group id unless overridden",+ )+ parser.add_argument("--source-topic", default=None, help="DLQ topic to read from")+ parser.add_argument("--target-topic", default=None, help="Topic to replay messages to")parser.add_argument("--group-id",- default="dlq-replay-ingestion-traces",+ default=None,help="Consumer group id; reuse the same id to resume an interrupted run",)parser.add_argument("--max-replays", type=int, default=2, help="Skip a message replayed this many times")@@ -40,6 +66,12 @@ class Command(BaseCommand):default=None,help="Cap the replay produce rate; unset means no limit",)+ parser.add_argument(+ "--max-message-bytes",+ type=int,+ default=None,+ help="Largest record to produce, in bytes; unset uses KAFKA_<PROFILE>_PRODUCER_MAX_REQUEST_SIZE, then 1 MiB",+ )parser.add_argument("--dry-run", action="store_true", help="Count without producing or committing")def handle(self, *args: Any, **options: Any) -> None:@@ -51,10 +83,19 @@ class Command(BaseCommand):signal.signal(signal.SIGTERM, request_stop)signal.signal(signal.SIGINT, request_stop)- result = drain_dlq(+ pipeline = resolve_pipeline(+ options["pipeline"],source_topic=options["source_topic"],target_topic=options["target_topic"],group_id=options["group_id"],+ )+ self.stdout.write(+ f"Draining {pipeline.source_topic} into {pipeline.target_topic} with group {pipeline.group_id}"+ )+ result = drain_dlq(+ source_topic=pipeline.source_topic,+ target_topic=pipeline.target_topic,+ group_id=pipeline.group_id,max_replays=options["max_replays"],batch_size=options["batch_size"],idle_polls=options["idle_polls"],@@ -64,6 +105,7 @@ class Command(BaseCommand):security_protocol=options["security_protocol"],skip_team_ids=options["skip_team_ids"],max_messages_per_second=options["max_messages_per_second"],+ max_message_bytes=options["max_message_bytes"],should_stop=lambda: stop_requested["value"],log=lambda message: self.stdout.write(message),)diff --git a/posthog/management/commands/test/test_replay_kafka_dlq.py b/posthog/management/commands/test/test_replay_kafka_dlq.pynew file mode 100644index 000000000000..be6776400bdd--- /dev/null+++ b/posthog/management/commands/test/test_replay_kafka_dlq.py@@ -0,0 +1,50 @@+from unittest import TestCase++from parameterized import parameterized++from posthog.kafka_client.dlq_replay import DLQ_REPLAY_PIPELINES+from posthog.kafka_client.topics import (+ KAFKA_LOGS_INGESTION,+ KAFKA_LOGS_INGESTION_DLQ,+ KAFKA_TRACES_INGESTION,+ KAFKA_TRACES_INGESTION_DLQ,+)+from posthog.management.commands.replay_kafka_dlq import resolve_pipeline+++class ResolvePipelineTest(TestCase):+ @parameterized.expand(+ [+ (+ "traces_preset",+ {"pipeline": "traces"},+ (KAFKA_TRACES_INGESTION_DLQ, KAFKA_TRACES_INGESTION, "dlq-replay-ingestion-traces"),+ ),+ (+ "logs_preset",+ {"pipeline": "logs"},+ (KAFKA_LOGS_INGESTION_DLQ, KAFKA_LOGS_INGESTION, "dlq-replay-ingestion-logs"),+ ),+ (+ "explicit_topics_keep_preset_group",+ {"pipeline": "traces", "source_topic": "custom-dlq", "target_topic": "custom"},+ ("custom-dlq", "custom", "dlq-replay-ingestion-traces"),+ ),+ (+ "explicit_group_keeps_preset_topics",+ {"pipeline": "logs", "group_id": "dlq-replay-logs-retry"},+ (KAFKA_LOGS_INGESTION_DLQ, KAFKA_LOGS_INGESTION, "dlq-replay-logs-retry"),+ ),+ ]+ )+ def test_applies_overrides_on_top_of_preset(+ self, _name: str, options: dict[str, str], expected: tuple[str, str, str]+ ) -> None:+ pipeline = resolve_pipeline(**options)++ assert (pipeline.source_topic, pipeline.target_topic, pipeline.group_id) == expected++ def test_every_preset_drains_a_distinct_topic_pair(self) -> None:+ pairs = {(p.source_topic, p.target_topic) for p in DLQ_REPLAY_PIPELINES.values()}+ assert len(pairs) == len(DLQ_REPLAY_PIPELINES)+ assert all(p.source_topic != p.target_topic for p in DLQ_REPLAY_PIPELINES.values())