Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

24.4 KB
Raw Blame
"""Tests for Kafka source connector: offset tracking and watch behavior.

These tests mock the AIOConsumer to verify behavior without a real Kafka broker.
"""

from __future__ import annotations

import asyncio
import warnings
from typing import Any
from unittest.mock import MagicMock

import pytest

from tests.common.kafka_stub import MockAIOConsumer, MockMessage, MockTopicPartition

# ``tests.common.kafka_stub`` must be imported before the connector so that the
# connector binds the stub SDK.
from cocoindex._internal.live_component import _IMMEDIATE_READY
from cocoindex.connectors.kafka._source import (
    TopicStream,
    _PartitionState,
    _TopicMapFeed,
    topic_as_map,
    topic_as_stream,
)


class MockComponentMountHandle:
    """Mock ComponentMountHandle with controllable readiness."""

    def __init__(self) -> None:
        self._ready_event = asyncio.Event()

    async def ready(self) -> None:
        await self._ready_event.wait()

    def set_ready(self) -> None:
        self._ready_event.set()


# ============================================================================
# Unit tests: _PartitionState offset tracking
# ============================================================================


class TestPartitionStateOffsetTracking:
    """Tests for per-partition offset tracking and commit logic."""

    @pytest.mark.asyncio
    async def test_in_order_completion(self) -> None:
        """Offsets completing in consumption order are committed immediately."""
        consumer = MockAIOConsumer()
        state = _PartitionState(
            consumer,  # type: ignore[arg-type]
            "t",
            0,
            high_watermark=0,
            committed_offset=0,
            on_commit=lambda: None,
        )

        handles = [MockComponentMountHandle() for _ in range(3)]
        for i, h in enumerate(handles):
            state.track(i, h)

        # Complete in order: 0, 1, 2
        for h in handles:
            h.set_ready()
            await asyncio.sleep(0)  # let task run

        await asyncio.sleep(0.05)  # let commit propagate

        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 3  # offset 2 + 1

    @pytest.mark.asyncio
    async def test_out_of_order_completion(self) -> None:
        """Later offsets completing first don't trigger commit until front drains."""
        consumer = MockAIOConsumer()
        state = _PartitionState(
            consumer,  # type: ignore[arg-type]
            "t",
            0,
            high_watermark=0,
            committed_offset=0,
            on_commit=lambda: None,
        )

        handles = [MockComponentMountHandle() for _ in range(3)]
        for i, h in enumerate(handles):
            state.track(i, h)

        # Complete offset 2 first
        handles[2].set_ready()
        await asyncio.sleep(0.05)
        assert len(consumer._committed) == 0  # nothing committable yet

        # Complete offset 1
        handles[1].set_ready()
        await asyncio.sleep(0.05)
        assert len(consumer._committed) == 0  # still blocked on offset 0

        # Complete offset 0 β€” all three drain
        handles[0].set_ready()
        await asyncio.sleep(0.05)
        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 3

    @pytest.mark.asyncio
    async def test_partial_drain(self) -> None:
        """Only contiguous completed offsets from the front drain."""
        consumer = MockAIOConsumer()
        state = _PartitionState(
            consumer,  # type: ignore[arg-type]
            "t",
            0,
            high_watermark=0,
            committed_offset=0,
            on_commit=lambda: None,
        )

        handles = [MockComponentMountHandle() for _ in range(4)]
        for i, h in enumerate(handles):
            state.track(i, h)

        # Complete 0 and 1, leave 2 pending, complete 3
        handles[0].set_ready()
        handles[1].set_ready()
        handles[3].set_ready()
        await asyncio.sleep(0.05)

        # Should commit offset 2 (after draining 0, 1)
        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 2

        # Now complete 2 β€” should drain 2 and 3, commit 4
        handles[2].set_ready()
        await asyncio.sleep(0.05)
        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 4

    @pytest.mark.asyncio
    async def test_skip_null_key(self) -> None:
        """Skipped offsets (null key) are immediately completed."""
        consumer = MockAIOConsumer()
        state = _PartitionState(
            consumer,  # type: ignore[arg-type]
            "t",
            0,
            high_watermark=0,
            committed_offset=0,
            on_commit=lambda: None,
        )

        h0 = MockComponentMountHandle()
        state.track(0, h0)
        state.track(1, _IMMEDIATE_READY)  # null-key fast path

        # Complete offset 0 β€” should drain 0 and 1
        h0.set_ready()
        await asyncio.sleep(0.05)

        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 2

        # Add and complete offset 2
        h2 = MockComponentMountHandle()
        state.track(2, h2)
        h2.set_ready()
        await asyncio.sleep(0.05)
        committed_offsets = [tp.offset for tp in consumer._committed]
        assert committed_offsets[-1] == 3


# ============================================================================
# E2E tests: watch behavior
# ============================================================================


class MockSubscriber:
    """Mock LiveMapSubscriber that records calls and returns controllable handles."""

    def __init__(self, *, auto_ready: bool = True) -> None:
        self.updates: list[tuple[bytes | str, MockMessage]] = []
        self.deletes: list[bytes | str] = []
        self.ready_called = False
        self.update_all_called = False
        self._auto_ready = auto_ready

    async def update(
        self, key: bytes | str, value: MockMessage
    ) -> MockComponentMountHandle:
        self.updates.append((key, value))
        h = MockComponentMountHandle()
        if self._auto_ready:
            h.set_ready()
        return h

    async def delete(self, key: bytes | str) -> MockComponentMountHandle:
        self.deletes.append(key)
        h = MockComponentMountHandle()
        if self._auto_ready:
            h.set_ready()
        return h

    async def update_all(self) -> None:
        self.update_all_called = True

    async def mark_ready(self) -> None:
        self.ready_called = True


async def _watch_until_done(feed: _TopicMapFeed, sub: MockSubscriber) -> None:
    """Run watch() and suppress CancelledError (raised by mock when messages are exhausted)."""
    try:
        await feed.watch(sub)  # type: ignore[arg-type]
    except asyncio.CancelledError:
        pass


class TestWatchBehavior:
    """E2E tests for _TopicMapFeed.watch()."""

    @pytest.mark.asyncio
    async def test_basic_consumption(self) -> None:
        """Messages are delivered as subscriber.update() calls."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 3)
        consumer.enqueue(
            MockMessage(key=b"k1", value=b"v1", offset=0),
            MockMessage(key=b"k2", value=b"v2", offset=1),
            MockMessage(key=b"k3", value=b"v3", offset=2),
        )

        feed = _TopicMapFeed(TopicStream(consumer, ["test-topic"]), None)  # type: ignore[arg-type]
        sub = MockSubscriber()

        # Trigger assign manually since subscribe is called inside watch
        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert [(k, m.value()) for k, m in sub.updates] == [
            (b"k1", b"v1"),
            (b"k2", b"v2"),
            (b"k3", b"v3"),
        ]
        assert sub.ready_called

    @pytest.mark.asyncio
    async def test_tombstone_deletion(self) -> None:
        """Messages with None value trigger subscriber.delete()."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 2)
        consumer.enqueue(
            MockMessage(key=b"k1", value=b"v1", offset=0),
            MockMessage(key=b"k1", value=None, offset=1),
        )

        feed = _TopicMapFeed(TopicStream(consumer, ["test-topic"]), None)  # type: ignore[arg-type]
        sub = MockSubscriber()

        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert [(k, m.value()) for k, m in sub.updates] == [(b"k1", b"v1")]
        assert sub.deletes == [b"k1"]

    @pytest.mark.asyncio
    async def test_custom_is_deletion(self) -> None:
        """Custom is_deletion predicate triggers subscriber.delete()."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 2)
        consumer.enqueue(
            MockMessage(key=b"k1", value=b"DELETED", offset=0),
            MockMessage(key=b"k2", value=b"normal", offset=1),
        )

        feed = _TopicMapFeed(
            TopicStream(consumer, ["test-topic"]),  # type: ignore[arg-type]
            is_deletion=lambda msg: msg.value() == b"DELETED",
        )
        sub = MockSubscriber()

        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert sub.deletes == [b"k1"]
        assert [(k, m.value()) for k, m in sub.updates] == [(b"k2", b"normal")]

    @pytest.mark.asyncio
    async def test_null_key_skipped(self) -> None:
        """Messages with None key are skipped."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 2)
        consumer.enqueue(
            MockMessage(key=None, value=b"v1", offset=0),
            MockMessage(key=b"k2", value=b"v2", offset=1),
        )

        feed = _TopicMapFeed(TopicStream(consumer, ["test-topic"]), None)  # type: ignore[arg-type]
        sub = MockSubscriber()

        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert [(k, m.value()) for k, m in sub.updates] == [(b"k2", b"v2")]
        assert len(sub.deletes) == 0

    @pytest.mark.asyncio
    async def test_readiness_after_watermark(self) -> None:
        """mark_ready() called only after all partitions reach watermarks."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 2)
        consumer.set_watermarks("test-topic", 1, 0, 1)

        ready_at_offset: list[int] = []

        class TrackingSubscriber(MockSubscriber):
            async def update(
                self, key: bytes | str, value: MockMessage
            ) -> MockComponentMountHandle:
                h = await super().update(key, value)
                return h

            async def mark_ready(self) -> None:
                ready_at_offset.append(len(self.updates) + len(self.deletes))
                await super().mark_ready()

        consumer.enqueue(
            MockMessage(
                topic="test-topic", partition=0, key=b"k1", value=b"v1", offset=0
            ),
            MockMessage(
                topic="test-topic", partition=1, key=b"k2", value=b"v2", offset=0
            ),
            MockMessage(
                topic="test-topic", partition=0, key=b"k3", value=b"v3", offset=1
            ),
        )

        feed = _TopicMapFeed(TopicStream(consumer, ["test-topic"]), None)  # type: ignore[arg-type]
        sub = TrackingSubscriber()

        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign(
                [
                    MockTopicPartition("test-topic", 0),
                    MockTopicPartition("test-topic", 1),
                ]
            )

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert sub.ready_called
        # Ready should be called after all 3 messages (both partitions caught up)
        assert ready_at_offset == [3]

    @pytest.mark.asyncio
    async def test_partition_rebalance_discards_state(self) -> None:
        """Partition revoke discards tracking state."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 0)

        feed = _TopicMapFeed(TopicStream(consumer, ["test-topic"]), None)  # type: ignore[arg-type]
        sub = MockSubscriber()

        # We need to test rebalance during consumption.
        # Inject messages that trigger a rebalance mid-stream.
        msg_count = 0

        async def patched_poll(timeout: float = 1.0) -> MockMessage | None:
            nonlocal msg_count
            msg_count += 1
            if msg_count == 1:
                # First: assign partition 0
                await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])
                return MockMessage(key=b"k1", value=b"v1", partition=0, offset=0)
            elif msg_count == 2:
                # Revoke partition 0, assign partition 1
                await consumer.trigger_revoke([MockTopicPartition("test-topic", 0)])
                consumer.set_watermarks("test-topic", 1, 0, 1)
                await consumer.trigger_assign([MockTopicPartition("test-topic", 1)])
                return MockMessage(key=b"k2", value=b"v2", partition=1, offset=0)
            else:
                raise asyncio.CancelledError

        consumer.poll = patched_poll  # type: ignore[assignment]

        # Don't auto-trigger assign from subscribe
        await _watch_until_done(feed, sub)

        update_kvs = [(k, m.value()) for k, m in sub.updates]
        assert (b"k1", b"v1") in update_kvs
        assert (b"k2", b"v2") in update_kvs

    @pytest.mark.asyncio
    async def test_tombstone_always_deletion_even_with_custom_predicate(self) -> None:
        """None value is always deletion even when is_deletion returns False."""
        consumer = MockAIOConsumer()
        consumer.set_watermarks("test-topic", 0, 0, 1)
        consumer.enqueue(
            MockMessage(key=b"k1", value=None, offset=0),
        )

        # is_deletion always returns False, but None value should still be deletion
        feed = _TopicMapFeed(
            TopicStream(consumer, ["test-topic"]),  # type: ignore[arg-type]
            is_deletion=lambda msg: False,  # noqa: ARG005
        )
        sub = MockSubscriber()

        original_subscribe = consumer.subscribe

        async def patched_subscribe(topics: list[str], **kw: Any) -> None:
            await original_subscribe(topics, **kw)
            await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

        consumer.subscribe = patched_subscribe  # type: ignore[assignment]

        await _watch_until_done(feed, sub)

        assert sub.deletes == [b"k1"]
        assert len(sub.updates) == 0


# ============================================================================
# topic_as_map(): one topic, and the deprecated list form
# ============================================================================


def _auto_assigning_consumer(
    *messages: MockMessage,
) -> tuple[MockAIOConsumer, list[list[str]]]:
    """A consumer holding *messages* that assigns partition 0 of every topic it
    subscribes to, plus the list of subscriptions it receives."""
    consumer = MockAIOConsumer()
    high_watermarks: dict[str, int] = {}
    for m in messages:
        high_watermarks[m.topic()] = max(
            high_watermarks.get(m.topic(), 0), m.offset() + 1
        )
    for topic, high in high_watermarks.items():
        consumer.set_watermarks(topic, 0, 0, high)
    consumer.enqueue(*messages)
    subscriptions: list[list[str]] = []
    original_subscribe = consumer.subscribe

    async def patched_subscribe(topics: list[str], **kw: Any) -> None:
        subscriptions.append(list(topics))
        await original_subscribe(topics, **kw)
        await consumer.trigger_assign([MockTopicPartition(t, 0) for t in topics])

    consumer.subscribe = patched_subscribe  # type: ignore[assignment]
    return consumer, subscriptions


def _users_messages() -> list[MockMessage]:
    return [
        MockMessage(topic="users", key=b"42", value=b"alice", offset=0),
        MockMessage(topic="users", key=b"7", value=b"bob", offset=1),
        MockMessage(topic="users", key=b"42", value=None, offset=2),
    ]


class TestTopicAsMap:
    @pytest.mark.asyncio
    async def test_single_topic_keys_items_by_message_key(self) -> None:
        consumer, subscriptions = _auto_assigning_consumer(*_users_messages())
        with warnings.catch_warnings():
            warnings.simplefilter("error")
            feed = topic_as_map(consumer, "users")  # type: ignore[call-overload]
        sub = MockSubscriber()
        await _watch_until_done(feed, sub)

        assert subscriptions == [["users"]]
        assert [(k, m.value()) for k, m in sub.updates] == [
            (b"42", b"alice"),
            (b"7", b"bob"),
        ]
        assert sub.deletes == [b"42"]
        assert sub.ready_called

    @pytest.mark.asyncio
    @pytest.mark.parametrize("as_keyword", [False, True])
    async def test_one_item_list_is_deprecated_and_keeps_keys(
        self, as_keyword: bool
    ) -> None:
        consumer, subscriptions = _auto_assigning_consumer(*_users_messages())
        with pytest.warns(DeprecationWarning, match="pass a single topic"):
            if as_keyword:
                feed = topic_as_map(consumer, topics=["users"])  # type: ignore[call-overload]
            else:
                feed = topic_as_map(consumer, ["users"])  # type: ignore[call-overload]
        sub = MockSubscriber()
        await _watch_until_done(feed, sub)

        # The same subscription and item keys as topic_as_map(consumer, "users").
        assert subscriptions == [["users"]]
        assert [(k, m.value()) for k, m in sub.updates] == [
            (b"42", b"alice"),
            (b"7", b"bob"),
        ]
        assert sub.deletes == [b"42"]

    @pytest.mark.asyncio
    async def test_multi_topic_list_warns_that_keys_collide(self) -> None:
        consumer, subscriptions = _auto_assigning_consumer(
            MockMessage(topic="users", key=b"42", value=b"alice", offset=0),
            MockMessage(topic="orders", key=b"42", value=None, offset=0),
        )
        with pytest.warns(DeprecationWarning, match="several topics"):
            feed = topic_as_map(consumer, ["users", "orders"])  # type: ignore[call-overload]
        sub = MockSubscriber()
        await _watch_until_done(feed, sub)

        # Behavior is unchanged: both topics key by the bare message key, so
        # the tombstone on "orders" deletes the item "users" produced.
        assert subscriptions == [["users", "orders"]]
        assert [(k, m.value()) for k, m in sub.updates] == [(b"42", b"alice")]
        assert sub.deletes == [b"42"]
        assert sub.ready_called

    def test_topic_and_topics_together_raise(self) -> None:
        with pytest.raises(TypeError, match="not both"):
            topic_as_map(MockAIOConsumer(), "users", topics=["orders"])  # type: ignore[call-overload]


# ============================================================================
# Fast path: _IMMEDIATE_READY in track()
# ============================================================================


@pytest.mark.asyncio
async def test_track_immediate_ready_fast_path() -> None:
    """track(offset, _IMMEDIATE_READY) advances commit synchronously, no task spawn."""
    consumer = MockAIOConsumer()
    state = _PartitionState(
        consumer,  # type: ignore[arg-type]
        "t",
        0,
        high_watermark=0,
        committed_offset=0,
        on_commit=lambda: None,
    )

    state.track(0, _IMMEDIATE_READY)
    state.track(1, _IMMEDIATE_READY)
    state.track(2, _IMMEDIATE_READY)

    # No task spawn β€” verify immediately, before any sleep.
    assert len(state._tasks) == 0
    # Drain happens synchronously, but commit is dispatched via ensure_future.
    await asyncio.sleep(0.05)

    committed_offsets = [tp.offset for tp in consumer._committed]
    assert committed_offsets[-1] == 3


# ============================================================================
# topic_as_stream + payloads()
# ============================================================================


class _StreamSubscriber:
    """Mock LiveStreamSubscriber recording received messages."""

    def __init__(self) -> None:
        self.messages: list[Any] = []
        self.ready_called = False

    async def send(self, message: Any) -> Any:
        self.messages.append(message)
        return _IMMEDIATE_READY

    async def mark_ready(self) -> None:
        self.ready_called = True


async def _watch_stream_until_done(stream: Any, sub: _StreamSubscriber) -> None:
    try:
        await stream.watch(sub)
    except asyncio.CancelledError:
        pass


@pytest.mark.asyncio
async def test_topic_as_stream_basic_consumption() -> None:
    """topic_as_stream forwards every valid message to subscriber.send()."""
    consumer = MockAIOConsumer()
    consumer.set_watermarks("test-topic", 0, 0, 3)
    msgs = [
        MockMessage(key=b"k1", value=b"v1", offset=0),
        MockMessage(key=b"k2", value=b"v2", offset=1),
        MockMessage(key=b"k3", value=b"v3", offset=2),
    ]
    consumer.enqueue(*msgs)

    original_subscribe = consumer.subscribe

    async def patched_subscribe(topics: list[str], **kw: Any) -> None:
        await original_subscribe(topics, **kw)
        await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

    consumer.subscribe = patched_subscribe  # type: ignore[assignment]

    stream = topic_as_stream(consumer, ["test-topic"])  # type: ignore[arg-type]
    sub = _StreamSubscriber()
    await _watch_stream_until_done(stream, sub)

    assert [m.value() for m in sub.messages] == [b"v1", b"v2", b"v3"]
    assert sub.ready_called


@pytest.mark.asyncio
async def test_topic_stream_payloads_filters_null_values() -> None:
    """payloads() unwraps Message.value() and filters None values."""
    consumer = MockAIOConsumer()
    consumer.set_watermarks("test-topic", 0, 0, 3)
    consumer.enqueue(
        MockMessage(key=b"k1", value=b"a", offset=0),
        MockMessage(key=b"k2", value=None, offset=1),
        MockMessage(key=b"k3", value=b"c", offset=2),
    )

    original_subscribe = consumer.subscribe

    async def patched_subscribe(topics: list[str], **kw: Any) -> None:
        await original_subscribe(topics, **kw)
        await consumer.trigger_assign([MockTopicPartition("test-topic", 0)])

    consumer.subscribe = patched_subscribe  # type: ignore[assignment]

    payloads_stream = topic_as_stream(consumer, ["test-topic"]).payloads()  # type: ignore[arg-type]
    sub = _StreamSubscriber()
    await _watch_stream_until_done(payloads_stream, sub)

    # Only non-null values reach the bytes subscriber.
    assert sub.messages == [b"a", b"c"]
    # All offsets advance β€” the null-value message acks via _IMMEDIATE_READY.
    await asyncio.sleep(0.05)
    final_committed = max((tp.offset for tp in consumer._committed), default=-1)
    assert final_committed == 3


@pytest.mark.asyncio
async def test_single_watcher_raises() -> None:
    """A second concurrent watch() on one TopicStream fails loudly."""
    stream = TopicStream(MockAIOConsumer(), ["test-topic"])  # type: ignore[arg-type]
    with stream._watch_guard:  # simulate an already-active watch
        with pytest.raises(RuntimeError, match="single active watch"):
            await stream.watch(MagicMock())  # type: ignore[arg-type]