This is an automated email from the ASF dual-hosted git repository.
eladkal pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 74794776256 split dagrun and task_instance events into separate kafka
topics (#73276)
74794776256 is described below
commit 747947762565e467b11692a7de3e502a7634979a
Author: stephen-bracken <[email protected]>
AuthorDate: Mon Nov 30 19:03:41 2026 +0000
split dagrun and task_instance events into separate kafka topics (#73276)
Co-authored-by: Stephen Bracken <email-protected>
---
providers/apache/kafka/docs/configurations-ref.rst | 10 +-
providers/apache/kafka/provider.yaml | 19 ++
.../providers/apache/kafka/get_provider_info.py | 16 ++
.../apache/kafka/plugins/event_producer.py | 108 ++++++---
.../apache/kafka/plugins/test_event_producer.py | 33 ++-
.../apache/kafka/plugins/test_event_producer.py | 242 +++++++++++++++++----
6 files changed, 344 insertions(+), 84 deletions(-)
diff --git a/providers/apache/kafka/docs/configurations-ref.rst
b/providers/apache/kafka/docs/configurations-ref.rst
index 2a5b108d497..a82880d9956 100644
--- a/providers/apache/kafka/docs/configurations-ref.rst
+++ b/providers/apache/kafka/docs/configurations-ref.rst
@@ -64,7 +64,7 @@ To enable event publishing you need to
* point the plugin at an Airflow Kafka connection via ``kafka_config_id``
(defaults to ``kafka_default``) that carries the broker address and any
other confluent-kafka client options on its extras
- * have a pre-existing kafka topic
+ * have pre-existing kafka topics for dagrun and task_instance (these can be
the same topic)
.. code-block:: ini
@@ -72,7 +72,8 @@ To enable event publishing you need to
dag_run_events_enabled = True
task_instance_events_enabled = True
kafka_config_id = kafka_events
- topic = airflow.events
+ dagrun_topic = airflow.dagrun
+ task_instance_topic = airflow.task_instance
The connection's ``extra`` JSON accepts the full confluent-kafka client
configuration — including SASL/TLS options and callbacks (e.g. ``error_cb``,
@@ -98,12 +99,13 @@ Environment-variable equivalents:
AIRFLOW__KAFKA_EVENT_PRODUCER__DAG_RUN_EVENTS_ENABLED=True
AIRFLOW__KAFKA_EVENT_PRODUCER__TASK_INSTANCE_EVENTS_ENABLED=True
AIRFLOW__KAFKA_EVENT_PRODUCER__KAFKA_CONFIG_ID=kafka_events
- AIRFLOW__KAFKA_EVENT_PRODUCER__TOPIC=airflow.events
+ AIRFLOW__KAFKA_EVENT_PRODUCER__DAGRUN_TOPIC=airflow.dagrun
+ AIRFLOW__KAFKA_EVENT_PRODUCER__TASK_INSTANCE_TOPIC=airflow.task_instance
The two event flags are independent, users can opt-in to get only DagRun
event messages or only TaskInstance event messages or both.
-The topic must already exist on the broker, it's not auto-created. On a missing
+The topics must already exist on the broker, they are not auto-created. On a
missing
topic, broker connection failure, or any other producer init error, the plugin
doesn't fail, instead it logs a warning and retries the init after
``topic_check_retry_interval``
seconds (default ``60``). Once the topic is created on the broker the plugin
will pick it up.
diff --git a/providers/apache/kafka/provider.yaml
b/providers/apache/kafka/provider.yaml
index e7123c535c7..abf6624649d 100644
--- a/providers/apache/kafka/provider.yaml
+++ b/providers/apache/kafka/provider.yaml
@@ -204,6 +204,25 @@ config:
version_added: 1.14.1
type: string
example: ~
+ default: ""
+ version_deprecated: 3.1.0
+ deprecation_reason: |
+ Topics for DagRun and TaskInstance were separated into different
config settings.
+ dagrun_topic:
+ description: |
+ Topic the plugin publishes DagRun events to. The topic must already
+ exist on the broker; the plugin will not auto-create it.
+ version_added: 3.1.0
+ type: string
+ example: ~
+ default: "airflow.events"
+ task_instance_topic:
+ description: |
+ Topic the plugin publishes TaskInstance events to. The topic must
already
+ exist on the broker; the plugin will not auto-create it.
+ version_added: 3.1.0
+ type: string
+ example: ~
default: "airflow.events"
source:
description: |
diff --git
a/providers/apache/kafka/src/airflow/providers/apache/kafka/get_provider_info.py
b/providers/apache/kafka/src/airflow/providers/apache/kafka/get_provider_info.py
index 18b6801e0f2..1bf37a1967f 100644
---
a/providers/apache/kafka/src/airflow/providers/apache/kafka/get_provider_info.py
+++
b/providers/apache/kafka/src/airflow/providers/apache/kafka/get_provider_info.py
@@ -150,6 +150,22 @@ def get_provider_info():
"version_added": "1.14.1",
"type": "string",
"example": None,
+ "default": "",
+ "version_deprecated": "3.1.0",
+ "deprecation_reason": "Topics for DagRun and
TaskInstance were separated into different config settings.\n",
+ },
+ "dagrun_topic": {
+ "description": "Topic the plugin publishes DagRun
events to. The topic must already\nexist on the broker; the plugin will not
auto-create it.\n",
+ "version_added": "3.1.0",
+ "type": "string",
+ "example": None,
+ "default": "airflow.events",
+ },
+ "task_instance_topic": {
+ "description": "Topic the plugin publishes
TaskInstance events to. The topic must already\nexist on the broker; the plugin
will not auto-create it.\n",
+ "version_added": "3.1.0",
+ "type": "string",
+ "example": None,
"default": "airflow.events",
},
"source": {
diff --git
a/providers/apache/kafka/src/airflow/providers/apache/kafka/plugins/event_producer.py
b/providers/apache/kafka/src/airflow/providers/apache/kafka/plugins/event_producer.py
index d3177ebddb2..0d8af9abb6f 100644
---
a/providers/apache/kafka/src/airflow/providers/apache/kafka/plugins/event_producer.py
+++
b/providers/apache/kafka/src/airflow/providers/apache/kafka/plugins/event_producer.py
@@ -21,11 +21,14 @@ import json
import logging
import os
import time
+import warnings
from datetime import UTC, datetime
+from enum import Enum
from fnmatch import fnmatch
-from functools import lru_cache
+from functools import lru_cache, partial
from typing import TYPE_CHECKING, Any
+from airflow.exceptions import AirflowProviderDeprecationWarning
from airflow.providers.apache.kafka.version_compat import AIRFLOW_V_3_0_PLUS
from airflow.providers.common.compat.sdk import AirflowPlugin, conf, hookimpl
from airflow.utils.net import get_hostname
@@ -42,6 +45,20 @@ log = logging.getLogger(__name__)
CONFIG_SECTION = "kafka_event_producer"
SCHEMA_VERSION = 2
+DEFAULT_TOPIC = "airflow.events"
+
+
+class EventProducerKafkaTopic(Enum):
+ """Event Producer Kafka Topic types to configure."""
+
+ DAG_RUN = "dag_run"
+ TASK_INSTANCE = "task_instance"
+
+
+TOPIC_CONFIG_MAP: dict[EventProducerKafkaTopic, str] = {
+ EventProducerKafkaTopic.DAG_RUN: "dagrun_topic",
+ EventProducerKafkaTopic.TASK_INSTANCE: "task_instance_topic",
+}
@lru_cache(maxsize=1)
@@ -59,9 +76,18 @@ def _get_kafka_config_id() -> str:
return conf.get(CONFIG_SECTION, "kafka_config_id", fallback="").strip()
-@lru_cache(maxsize=1)
-def _get_topic() -> str:
- return conf.get(CONFIG_SECTION, "topic", fallback="airflow.events")
+@lru_cache(maxsize=len(EventProducerKafkaTopic))
+def _get_topic(topic_type: EventProducerKafkaTopic) -> str:
+ topic = conf.get(CONFIG_SECTION, "topic", fallback=None)
+ if topic:
+ warnings.warn(
+ f"""The ``topic`` option in [{CONFIG_SECTION}] has been split into
``dagrun_topic`` and ``task_instance_topic`` -
+ please update your config.""",
+ AirflowProviderDeprecationWarning,
+ stacklevel=2,
+ )
+ return topic
+ return conf.get(CONFIG_SECTION, TOPIC_CONFIG_MAP[topic_type],
fallback=DEFAULT_TOPIC)
@lru_cache(maxsize=1)
@@ -157,8 +183,14 @@ def _task_instance_event_allowed(dag_id: str, task_id:
str) -> bool:
# the topic flags track whether the topic exists on the broker and whether
we're
# currently in a back-off window after a failed topic check.
_producer: Producer | None = None
-_topic_exists: bool = False
-_topic_check_retry_after: float = 0.0
+_topic_check_retry_after: dict[EventProducerKafkaTopic, float] = {
+ EventProducerKafkaTopic.DAG_RUN: 0.0,
+ EventProducerKafkaTopic.TASK_INSTANCE: 0.0,
+}
+_topic_existence_map: dict[EventProducerKafkaTopic, bool] = {
+ EventProducerKafkaTopic.DAG_RUN: False,
+ EventProducerKafkaTopic.TASK_INSTANCE: False,
+}
def _reset_state_after_fork() -> None:
@@ -169,10 +201,16 @@ def _reset_state_after_fork() -> None:
do not survive ``os.fork``. The child re-initializes its own producer on
first use
and re-verifies the topic.
"""
- global _producer, _topic_exists, _topic_check_retry_after
+ global _producer, _topic_existence_map, _topic_check_retry_after
_producer = None
- _topic_exists = False
- _topic_check_retry_after = 0.0
+ _topic_existence_map = {
+ EventProducerKafkaTopic.DAG_RUN: False,
+ EventProducerKafkaTopic.TASK_INSTANCE: False,
+ }
+ _topic_check_retry_after = {
+ EventProducerKafkaTopic.DAG_RUN: 0.0,
+ EventProducerKafkaTopic.TASK_INSTANCE: 0.0,
+ }
os.register_at_fork(after_in_child=_reset_state_after_fork)
@@ -202,22 +240,22 @@ def _get_producer() -> Producer | None:
return _producer
-def _check_topic_exists() -> bool:
+def _check_topic_exists(topic_type: EventProducerKafkaTopic) -> bool:
"""
Verify the configured topic exists on the broker, with a
retry-after-failure cooldown.
Once the topic has been confirmed, the result is kept for the process
lifetime; until
then, failed checks are retried on a configured interval.
"""
- global _topic_exists, _topic_check_retry_after
- if _topic_exists:
+ global _topic_existence_map, _topic_check_retry_after # noqa: PLW0602
+ if _topic_existence_map[topic_type]:
return True
- if time.monotonic() < _topic_check_retry_after:
+ if time.monotonic() < _topic_check_retry_after[topic_type]:
return False
producer = _get_producer()
if producer is None:
- _topic_check_retry_after = time.monotonic() +
_get_topic_check_retry_interval()
+ _topic_check_retry_after[topic_type] = time.monotonic() +
_get_topic_check_retry_interval()
return False
try:
@@ -228,26 +266,26 @@ def _check_topic_exists() -> bool:
exc,
_get_topic_check_retry_interval(),
)
- _topic_check_retry_after = time.monotonic() +
_get_topic_check_retry_interval()
+ _topic_check_retry_after[topic_type] = time.monotonic() +
_get_topic_check_retry_interval()
return False
- if _get_topic() not in topics:
+ if _get_topic(topic_type) not in topics:
log.warning(
"Kafka event producer: topic %r not found on the broker. Will
retry after %ds. "
"Create the topic on the broker to enable publishing.",
- _get_topic(),
+ _get_topic(topic_type),
_get_topic_check_retry_interval(),
)
- _topic_check_retry_after = time.monotonic() +
_get_topic_check_retry_interval()
+ _topic_check_retry_after[topic_type] = time.monotonic() +
_get_topic_check_retry_interval()
return False
log.info(
"Kafka event producer attached: pid=%s source=%r topic=%r",
os.getpid(),
_get_source(),
- _get_topic(),
+ _get_topic(topic_type),
)
- _topic_exists = True
+ _topic_existence_map[topic_type] = True
return True
@@ -258,7 +296,7 @@ def _flush_producer_at_exit(producer: Producer) -> None:
log.debug("Kafka event producer: error flushing producer on exit",
exc_info=True)
-def _on_delivery(err, _msg) -> None:
+def _on_delivery(topic_type: EventProducerKafkaTopic, err, _msg) -> None:
if err is None:
return
log.warning("Kafka event producer: delivery failed: %s", err)
@@ -269,9 +307,9 @@ def _on_delivery(err, _msg) -> None:
from confluent_kafka import KafkaError
if err.code() in (KafkaError.UNKNOWN_TOPIC_OR_PART,
KafkaError._UNKNOWN_TOPIC):
- global _topic_exists, _topic_check_retry_after
- _topic_exists = False
- _topic_check_retry_after = time.monotonic() +
_get_topic_check_retry_interval()
+ global _topic_existence_map, _topic_check_retry_after # noqa: PLW0602
+ _topic_existence_map[topic_type] = False
+ _topic_check_retry_after[topic_type] = time.monotonic() +
_get_topic_check_retry_interval()
def _now_iso() -> str:
@@ -290,6 +328,7 @@ def _produce_dr_message(event: str, dag_run: DagRun, msg:
str) -> None:
return
try:
_produce_message(
+ EventProducerKafkaTopic.DAG_RUN,
event,
dag_id,
dag_run.run_id,
@@ -324,6 +363,7 @@ def _produce_ti_message(
return
try:
_produce_message(
+ EventProducerKafkaTopic.TASK_INSTANCE,
event,
dag_id,
task_instance.run_id,
@@ -347,10 +387,18 @@ def _get_ti_payload(ti, previous_state, error=None) ->
dict[str, Any]:
return payload
-def _produce_message(event: str, dag_id: str, run_id: str, payload: dict[str,
Any]) -> None:
- if not _dag_run_events_enabled() and not _task_instance_events_enabled():
- return
- if not _check_topic_exists():
+def _produce_message(
+ topic_type: EventProducerKafkaTopic, event: str, dag_id: str, run_id: str,
payload: dict[str, Any]
+) -> None:
+ if topic_type == EventProducerKafkaTopic.DAG_RUN:
+ if not _dag_run_events_enabled():
+ return
+ elif topic_type == EventProducerKafkaTopic.TASK_INSTANCE:
+ if not _task_instance_events_enabled():
+ return
+ else:
+ raise ValueError(f"Invalid topic type: {topic_type}")
+ if not _check_topic_exists(topic_type):
return
producer = _get_producer()
if producer is None:
@@ -371,10 +419,10 @@ def _produce_message(event: str, dag_id: str, run_id:
str, payload: dict[str, An
key = f"{dag_id}/{run_id}".encode()
try:
producer.produce(
- _get_topic(),
+ _get_topic(topic_type),
key=key,
value=json.dumps(body, default=str).encode("utf-8"),
- on_delivery=_on_delivery,
+ on_delivery=partial(_on_delivery, topic_type),
)
producer.poll(0)
except Exception as ex:
diff --git
a/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
b/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
index 057727706d1..aadca111e69 100644
---
a/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
+++
b/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
@@ -22,6 +22,7 @@ import os
import subprocess
import time
import uuid
+from typing import cast
import pytest
@@ -66,7 +67,8 @@ class TestEventProducer:
KAFKA_CONFIG_ID = "kafka_default"
# Use a unique topic per run to avoid errors on a re-run, in case
# the previous teardown hasn't finished with the topic deletion.
- TOPIC = f"airflow.events.itest.{uuid.uuid4().hex[:8]}"
+ DAGRUN_TOPIC = f"airflow.dagrun.itest.{uuid.uuid4().hex[:8]}"
+ TASK_INSTANCE_TOPIC = f"airflow.task_instance.itest.{uuid.uuid4().hex[:8]}"
@classmethod
def setup_class(cls):
@@ -85,7 +87,8 @@ class TestEventProducer:
os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__DAG_RUN_EVENTS_ENABLED"] =
"True"
os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__TASK_INSTANCE_EVENTS_ENABLED"] =
"True"
- os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__TOPIC"] = cls.TOPIC
+ os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__DAGRUN_TOPIC"] =
cls.DAGRUN_TOPIC
+ os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__TASK_INSTANCE_TOPIC"] =
cls.TASK_INSTANCE_TOPIC
os.environ["AIRFLOW__KAFKA_EVENT_PRODUCER__SOURCE"] = "dev-breeze"
# Shared Kafka connection: used by the event producer plugin, the topic
@@ -107,15 +110,17 @@ class TestEventProducer:
cls._admin = KafkaAdminClientHook(kafka_config_id=cls.KAFKA_CONFIG_ID)
# Tuple positions are (name, partition, replication).
- cls._admin.create_topic([(cls.TOPIC, 1, 1)])
+ cls._admin.create_topic([(cls.DAGRUN_TOPIC, 1, 1),
(cls.TASK_INSTANCE_TOPIC, 1, 1)])
@classmethod
def teardown_class(cls):
try:
- cls._admin.delete_topic([cls.TOPIC])
+ cls._admin.delete_topic([cls.DAGRUN_TOPIC,
cls.TASK_INSTANCE_TOPIC])
time.sleep(2) # let the broker finish the async delete
except Exception as exc:
- log.warning("teardown: failed to delete topic %r: %s", cls.TOPIC,
exc)
+ log.warning(
+ "teardown: failed to delete topics %r, %r: %s",
cls.DAGRUN_TOPIC, cls.TASK_INSTANCE_TOPIC, exc
+ )
@pytest.fixture
def start_components(self):
@@ -130,7 +135,9 @@ class TestEventProducer:
@pytest.mark.execution_timeout(90)
def test_dag_run_produces_event_messages(self, start_components):
- consumer = KafkaConsumerHook(topics=[self.TOPIC],
kafka_config_id=self.KAFKA_CONFIG_ID).get_consumer()
+ consumer = KafkaConsumerHook(
+ topics=[self.DAGRUN_TOPIC, self.TASK_INSTANCE_TOPIC],
kafka_config_id=self.KAFKA_CONFIG_ID
+ ).get_consumer()
_wait_for_assignment(consumer)
dag_id = "demo_dag"
@@ -151,17 +158,23 @@ class TestEventProducer:
finally:
consumer.close()
- topic_msg_bodies: list[dict] = []
+ topic_msg_bodies: list[tuple[str, dict]] = []
for message in messages:
- topic_msg_bodies.append(json.loads(message.value()))
+ topic = cast("str", message.topic())
+ value = json.loads(cast("str | bytes", message.value()))
+ topic_msg_bodies.append((topic, value))
assert len(topic_msg_bodies) == len(expected_events)
- for body in topic_msg_bodies:
+ for topic, body in topic_msg_bodies:
assert body["dag_id"] == dag_id
assert body["run_id"] == run_id
if body["event"].startswith("task_instance."):
assert body["task_id"] == "task1"
+ assert topic == self.TASK_INSTANCE_TOPIC
+ if body["event"].startswith("dag_run."):
+ assert body["dag_id"] == "demo_dag"
+ assert topic == self.DAGRUN_TOPIC
- received_events = [body["event"] for body in topic_msg_bodies]
+ received_events = [body["event"] for _topic, body in topic_msg_bodies]
assert sorted(received_events) == sorted(expected_events)
diff --git
a/providers/apache/kafka/tests/unit/apache/kafka/plugins/test_event_producer.py
b/providers/apache/kafka/tests/unit/apache/kafka/plugins/test_event_producer.py
index 99de98afda2..f02266f2070 100644
---
a/providers/apache/kafka/tests/unit/apache/kafka/plugins/test_event_producer.py
+++
b/providers/apache/kafka/tests/unit/apache/kafka/plugins/test_event_producer.py
@@ -16,6 +16,8 @@
# under the License.
from __future__ import annotations
+import contextlib
+import importlib
import json
from collections.abc import Callable
from datetime import UTC, datetime
@@ -24,6 +26,7 @@ from unittest.mock import MagicMock, patch
import pytest
from confluent_kafka import KafkaError
+from airflow.exceptions import AirflowProviderDeprecationWarning
from airflow.models import Connection
from airflow.providers.apache.kafka.plugins import event_producer
from airflow.providers.apache.kafka.plugins.event_producer import
DagRunListener, TaskListener
@@ -40,6 +43,8 @@ _TASK_ID = "test_task1"
_RUN_TYPE = "manual"
_KAFKA_TOPIC = "airflow.events"
+_DAGRUN_TOPIC = "airflow.dagrun"
+_TASK_INSTANCE_TOPIC = "airflow.task_instance"
_SOURCE = "af-dev-env"
# The hook binds these names in its own namespace, so patch them there.
@@ -80,8 +85,51 @@ def _clear_cached_values():
# Reset the module-level producer and topic state.
event_producer._producer = None
- event_producer._topic_exists = False
- event_producer._topic_check_retry_after = 0.0
+ event_producer._topic_existence_map = {
+ event_producer.EventProducerKafkaTopic.DAG_RUN: False,
+ event_producer.EventProducerKafkaTopic.TASK_INSTANCE: False,
+ }
+ event_producer._topic_check_retry_after = {
+ event_producer.EventProducerKafkaTopic.DAG_RUN: 0.0,
+ event_producer.EventProducerKafkaTopic.TASK_INSTANCE: 0.0,
+ }
+
+
+def pytest_generate_tests(metafunc):
+ if "topic_type" in metafunc.fixturenames:
+ metafunc.parametrize(
+ "topic_type",
+ [
+ event_producer.EventProducerKafkaTopic.DAG_RUN,
+ event_producer.EventProducerKafkaTopic.TASK_INSTANCE,
+ ],
+ indirect=True,
+ )
+ if "separate_topics" in metafunc.fixturenames:
+ metafunc.parametrize(
+ "separate_topics",
+ [pytest.param(True, id="separate_topics"), pytest.param(False,
id="same_topic")],
+ indirect=True,
+ )
+
+
[email protected]
+def separate_topics(request) -> bool:
+ return request.param
+
+
[email protected]
+def dagrun_topic(separate_topics):
+ if separate_topics:
+ return _DAGRUN_TOPIC
+ return _KAFKA_TOPIC
+
+
[email protected]
+def task_instance_topic(separate_topics):
+ if separate_topics:
+ return _TASK_INSTANCE_TOPIC
+ return _KAFKA_TOPIC
@pytest.fixture
@@ -117,13 +165,13 @@ def kafka_producer_mock():
yield mock
-def _assert_common_message_fields(kafka_producer_mock, expected_event: str) ->
dict:
+def _assert_common_message_fields(kafka_producer_mock, topic: str,
expected_event: str) -> dict:
kafka_producer_mock.list_topics.assert_called_once()
kafka_producer_mock.produce.assert_called_once()
args = kafka_producer_mock.produce.call_args.args
kwargs = kafka_producer_mock.produce.call_args.kwargs
- assert args == (_KAFKA_TOPIC,)
+ assert args == (topic,)
assert kwargs["key"] == f"{_DAG_ID}/{_DAG_RUN_ID}".encode()
body = json.loads(kwargs["value"].decode("utf-8"))
@@ -189,7 +237,7 @@ def test_get_enabled_listeners(configs,
expected_listener_classes):
@conf_vars(
{
("kafka_event_producer", "dag_run_events_enabled"): "True",
- ("kafka_event_producer", "topic"): _KAFKA_TOPIC,
+ ("kafka_event_producer", "dagrun_topic"): _DAGRUN_TOPIC,
("kafka_event_producer", "source"): _SOURCE,
}
)
@@ -201,7 +249,7 @@ def test_produce_dr_message(
):
dr_event_function(DagRunListener(), dag_run=dr_mock, msg=None)
- body = _assert_common_message_fields(kafka_producer_mock, expected_event)
+ body = _assert_common_message_fields(kafka_producer_mock, _DAGRUN_TOPIC,
expected_event)
assert body["run_type"] == _RUN_TYPE
assert body["logical_date"] is None
assert body["start_date"] is None
@@ -212,7 +260,7 @@ def test_produce_dr_message(
@conf_vars(
{
("kafka_event_producer", "dag_run_events_enabled"): "True",
- ("kafka_event_producer", "topic"): _KAFKA_TOPIC,
+ ("kafka_event_producer", "dagrun_topic"): _DAGRUN_TOPIC,
("kafka_event_producer", "source"): _SOURCE,
}
)
@@ -222,7 +270,7 @@ def
test_produce_dr_message_formats_dates_as_iso8601(dr_mock, kafka_producer_moc
DagRunListener().on_dag_run_running(dag_run=dr_mock, msg="")
- body = _assert_common_message_fields(kafka_producer_mock,
"dag_run.running")
+ body = _assert_common_message_fields(kafka_producer_mock, _DAGRUN_TOPIC,
"dag_run.running")
assert body["logical_date"] is None
assert body["start_date"] == "2026-10-30T14:40:05.123456+00:00"
assert body["end_date"] is None
@@ -245,7 +293,7 @@ def
test_produce_dr_message_formats_dates_as_iso8601(dr_mock, kafka_producer_moc
@conf_vars(
{
("kafka_event_producer", "task_instance_events_enabled"): "True",
- ("kafka_event_producer", "topic"): _KAFKA_TOPIC,
+ ("kafka_event_producer", "task_instance_topic"): _TASK_INSTANCE_TOPIC,
("kafka_event_producer", "source"): _SOURCE,
}
)
@@ -264,7 +312,7 @@ def test_produce_ti_message(
**_TI_SESSION_KWARG,
)
- body = _assert_common_message_fields(kafka_producer_mock, expected_event)
+ body = _assert_common_message_fields(kafka_producer_mock,
_TASK_INSTANCE_TOPIC, expected_event)
assert body["task_id"] == _TASK_ID
assert body["try_number"] == 2
assert body["map_index"] == -1
@@ -280,8 +328,13 @@ class TestGetProducer:
"""Tests for the lifecycle and caching behavior of `_get_producer`."""
@pytest.fixture(autouse=True)
- def _producer_conf(self):
- with conf_vars({("kafka_event_producer", "topic"): _KAFKA_TOPIC}):
+ def _producer_conf(self, dagrun_topic, task_instance_topic):
+ with conf_vars(
+ {
+ ("kafka_event_producer", "dagrun_topic"): dagrun_topic,
+ ("kafka_event_producer", "task_instance_topic"):
task_instance_topic,
+ }
+ ):
yield
def test_producer_cached_on_success(self):
@@ -346,23 +399,32 @@ class TestGetProducer:
class TestCheckTopicExists:
"""Tests for the topic check and its retry-after-failure cooldown."""
+ @pytest.fixture
+ def topic_type(self, request) -> event_producer.EventProducerKafkaTopic:
+ return request.param
+
@pytest.fixture(autouse=True)
- def _topic_conf(self):
- with conf_vars({("kafka_event_producer", "topic"): _KAFKA_TOPIC}):
+ def _topic_conf(self, dagrun_topic, task_instance_topic):
+ with conf_vars(
+ {
+ ("kafka_event_producer", "dagrun_topic"): dagrun_topic,
+ ("kafka_event_producer", "task_instance_topic"):
task_instance_topic,
+ }
+ ):
yield
- def test_topic_exists_kept_for_process_lifetime(self):
+ def test_topic_exists_kept_for_process_lifetime(self, topic_type):
kafka_producer_mock = MagicMock()
kafka_producer_mock.list_topics.return_value.topics.__contains__.return_value =
True
with patch(_PRODUCER_CLS, return_value=kafka_producer_mock):
- assert event_producer._check_topic_exists() is True
+ assert event_producer._check_topic_exists(topic_type) is True
# Once confirmed, the broker is not queried again.
- assert event_producer._check_topic_exists() is True
+ assert event_producer._check_topic_exists(topic_type) is True
kafka_producer_mock.list_topics.assert_called_once()
- def test_topic_doesnt_exist(self, monkeypatch):
+ def test_topic_doesnt_exist(self, monkeypatch, topic_type, dagrun_topic,
task_instance_topic):
kafka_producer_mock = MagicMock()
kafka_producer_mock.list_topics.return_value.topics.__contains__.return_value =
False
@@ -370,16 +432,60 @@ class TestCheckTopicExists:
monkeypatch.setattr(event_producer.log, "warning", log_warning_mock)
with patch(_PRODUCER_CLS, return_value=kafka_producer_mock):
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
+
+ log_warning_mock.assert_called_once()
+ # Format string + the two formatting args are passed positionally to
log.warning.
+ warning_format, topic_arg, retry_interval_arg =
log_warning_mock.call_args.args
+ assert "topic %r not found on the broker" in warning_format
+ if topic_type == event_producer.EventProducerKafkaTopic.DAG_RUN:
+ assert topic_arg == dagrun_topic
+ elif topic_type ==
event_producer.EventProducerKafkaTopic.TASK_INSTANCE:
+ assert topic_arg == task_instance_topic
+ assert retry_interval_arg ==
event_producer._get_topic_check_retry_interval()
+
+ @conf_vars(
+ {
+ ("kafka_event_producer", "dagrun_topic"): _DAGRUN_TOPIC,
+ ("kafka_event_producer", "task_instance_topic"):
_TASK_INSTANCE_TOPIC,
+ }
+ )
+ def test_one_topic_doesnt_exist(self, monkeypatch):
+ def _mock_topic_exists(topic):
+ return topic == _TASK_INSTANCE_TOPIC
+
+ kafka_producer_mock = MagicMock()
+
kafka_producer_mock.list_topics.return_value.topics.__contains__.side_effect =
_mock_topic_exists
+
+ log_warning_mock = MagicMock()
+ monkeypatch.setattr(event_producer.log, "warning", log_warning_mock)
+
+ with (
+ patch(_PRODUCER_CLS, return_value=kafka_producer_mock),
+
patch("airflow.providers.apache.kafka.plugins.event_producer.time.monotonic",
return_value=60.0),
+ ):
+ assert
event_producer._check_topic_exists(event_producer.EventProducerKafkaTopic.DAG_RUN)
is False
+ assert
event_producer._check_topic_exists(event_producer.EventProducerKafkaTopic.TASK_INSTANCE)
+ assert
event_producer._check_topic_exists(event_producer.EventProducerKafkaTopic.DAG_RUN)
is False
+ assert
event_producer._check_topic_exists(event_producer.EventProducerKafkaTopic.TASK_INSTANCE)
+ assert event_producer._topic_existence_map == {
+ event_producer.EventProducerKafkaTopic.DAG_RUN: False,
+ event_producer.EventProducerKafkaTopic.TASK_INSTANCE: True,
+ }
+ assert event_producer._topic_check_retry_after == {
+ event_producer.EventProducerKafkaTopic.DAG_RUN: 60.0
+ + event_producer._get_topic_check_retry_interval(),
+ event_producer.EventProducerKafkaTopic.TASK_INSTANCE: 0.0,
+ }
log_warning_mock.assert_called_once()
# Format string + the two formatting args are passed positionally to
log.warning.
warning_format, topic_arg, retry_interval_arg =
log_warning_mock.call_args.args
assert "topic %r not found on the broker" in warning_format
- assert topic_arg == _KAFKA_TOPIC
+ assert topic_arg == _DAGRUN_TOPIC
assert retry_interval_arg ==
event_producer._get_topic_check_retry_interval()
- def test_list_topics_failure_warns_and_sets_cooldown(self, monkeypatch):
+ def test_list_topics_failure_warns_and_sets_cooldown(self, monkeypatch,
topic_type):
kafka_producer_mock = MagicMock()
kafka_producer_mock.list_topics.side_effect = ValueError("broker down")
@@ -387,15 +493,15 @@ class TestCheckTopicExists:
monkeypatch.setattr(event_producer.log, "warning", log_warning_mock)
with patch(_PRODUCER_CLS, return_value=kafka_producer_mock):
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
# Within the cooldown window the check is not retried.
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
kafka_producer_mock.list_topics.assert_called_once()
log_warning_mock.assert_called_once()
assert "topic check failed" in log_warning_mock.call_args.args[0]
- def test_retried_after_failure_cooldown(self, monkeypatch):
+ def test_retried_after_failure_cooldown(self, monkeypatch, topic_type):
time_now = [1000.0]
monkeypatch.setattr(event_producer.time, "monotonic", lambda:
time_now[0])
@@ -405,36 +511,36 @@ class TestCheckTopicExists:
with patch(_PRODUCER_CLS, return_value=kafka_producer_mock):
# First check fails: the topic is missing.
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
assert kafka_producer_mock.list_topics.call_count == 1
# The interval hasn't passed and the check isn't retried.
time_now[0] += 1
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
assert kafka_producer_mock.list_topics.call_count == 1
# Past the interval. The check is retried and succeeds this time.
kafka_producer_mock.list_topics.return_value.topics.__contains__.return_value =
True
time_now[0] += event_producer._get_topic_check_retry_interval() + 1
- assert event_producer._check_topic_exists() is True
+ assert event_producer._check_topic_exists(topic_type) is True
assert kafka_producer_mock.list_topics.call_count == 2
- def test_producer_init_failure_sets_cooldown(self, monkeypatch):
+ def test_producer_init_failure_sets_cooldown(self, monkeypatch,
topic_type):
time_now = [1000.0]
monkeypatch.setattr(event_producer.time, "monotonic", lambda:
time_now[0])
with patch(_PRODUCER_CLS, side_effect=ValueError("boom")) as
producer_cls_mock:
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
assert producer_cls_mock.call_count == 1
# The interval hasn't passed and the producer initialization isn't
retried.
time_now[0] += 1
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
assert producer_cls_mock.call_count == 1
# Past the interval. The producer initialization is retried.
time_now[0] += event_producer._get_topic_check_retry_interval() + 1
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
assert producer_cls_mock.call_count == 2
@pytest.mark.parametrize(
@@ -446,7 +552,7 @@ class TestCheckTopicExists:
],
)
def
test_delivery_report_invalidates_topic_confirmation_only_on_missing_topic(
- self, monkeypatch, kafka_error, topic_exists_expected
+ self, monkeypatch, kafka_error, topic_exists_expected, topic_type
):
"""
If the delivery report failed and the topic is gone, ``_topic_exists``
must be reset so that the
@@ -459,34 +565,90 @@ class TestCheckTopicExists:
kafka_producer_mock = MagicMock()
kafka_producer_mock.list_topics.return_value.topics.__contains__.return_value =
True
with patch(_PRODUCER_CLS, return_value=kafka_producer_mock):
- assert event_producer._check_topic_exists() is True
- assert event_producer._topic_exists is True
+ assert event_producer._check_topic_exists(topic_type) is True
+ assert event_producer._topic_existence_map[topic_type] is True
err = MagicMock()
err.code.return_value = kafka_error
- event_producer._on_delivery(err, MagicMock())
+ event_producer._on_delivery(topic_type, err, MagicMock())
- assert event_producer._topic_exists is topic_exists_expected
+ assert event_producer._topic_existence_map[topic_type] is
topic_exists_expected
if not topic_exists_expected:
# Cooldown holds off the immediate re-check.
- assert event_producer._check_topic_exists() is False
+ assert event_producer._check_topic_exists(topic_type) is False
# After the cooldown, the check re-verifies; the topic is
still on the broker,
# so confirmation is restored.
time_now[0] +=
event_producer._get_topic_check_retry_interval() + 1
- assert event_producer._check_topic_exists() is True
+ assert event_producer._check_topic_exists(topic_type) is True
+
+
[email protected](
+ (
+ "topic",
+ "dagrun_topic_setting",
+ "task_instance_topic_setting",
+ "dagrun_expected",
+ "task_instance_expected",
+ ),
+ [
+ pytest.param(
+ "airflow.events",
+ "airflow.dagrun",
+ "airflow.task",
+ "airflow.events",
+ "airflow.events",
+ id="default_to_topic",
+ ),
+ pytest.param(None, None, None, "airflow.events", "airflow.events",
id="fallback_to_default"),
+ pytest.param(
+ None, "airflow.dagrun", "airflow.task", "airflow.dagrun",
"airflow.task", id="new_settings"
+ ),
+ pytest.param("airflow.foo", None, None, "airflow.foo", "airflow.foo",
id="old_setting"),
+ ],
+)
+def test_get_topic(
+ topic, dagrun_topic_setting, task_instance_topic_setting, dagrun_expected,
task_instance_expected
+):
+ # Check that ``topic`` is properly deprecated
+ ctxt = (
+ pytest.warns(
+ AirflowProviderDeprecationWarning,
+ match=r"""The ``topic`` option in \[kafka_event_producer\] has
been split into ``dagrun_topic`` and ``task_instance_topic`` -
+ please update your config\.""",
+ )
+ if topic is not None
+ else contextlib.nullcontext()
+ )
+ with (
+ conf_vars(
+ {
+ (event_producer.CONFIG_SECTION, "topic"): topic,
+ (event_producer.CONFIG_SECTION, "dagrun_topic"):
dagrun_topic_setting,
+ (event_producer.CONFIG_SECTION, "task_instance_topic"):
task_instance_topic_setting,
+ }
+ ),
+ ctxt,
+ ):
+ importlib.reload(event_producer)
+ assert
event_producer._get_topic(event_producer.EventProducerKafkaTopic.DAG_RUN) ==
dagrun_expected
+ assert (
+
event_producer._get_topic(event_producer.EventProducerKafkaTopic.TASK_INSTANCE)
+ == task_instance_expected
+ )
class TestFilters:
"""Tests for the allowlist/denylist behavior of both DagRun and
TaskInstance events."""
@pytest.fixture(autouse=True)
- def _filters_conf(self):
+ def _filters_conf(self, dagrun_topic, task_instance_topic):
with conf_vars(
{
("kafka_event_producer", "dag_run_events_enabled"): "True",
("kafka_event_producer", "task_instance_events_enabled"):
"True",
- ("kafka_event_producer", "topic"): _KAFKA_TOPIC,
+ ("kafka_event_producer", "dagrun_topic"): dagrun_topic,
+ ("kafka_event_producer", "task_instance_topic"):
task_instance_topic,
}
):
yield