numaflow-python icon indicating copy to clipboard operation
numaflow-python copied to clipboard

[Regression?] MapStreamAsyncServer not streaming

Open niall-nai opened this issue 8 months ago • 13 comments

Describe the bug As the title says, MapStreamAsyncServer doesn't seem to be streaming data out as it's received. This seems to be a regression; a pipeline that was streaming around October last year (on pynumaflow v0.9.0 and numaflow v1.4.2) is now waiting for all processing to be completed before outputting- this is a problem for sufficiently large jobs as data is stored in memory until outputted

We've managed to trace this to the MapStreamAsyncServer call - running an equivalent function via the asyncio library instead of via pynumaflow functions results in messages being yielded as expected.

In particular this seems to be related to the underlying gRPC EoT call not being respected; during the course of recovering from this issue we cleared the isbsvc (in effect clearing the incoming buffer), and messages were yielded as expected

To Reproduce Steps to reproduce the behavior:

  1. Create a basic source->async map stream->sink pipeline
  2. Start a job which will cause significant memory inflation - in our case, this is one which downloads a file and splits it into chunks. These chunks should be yielded and therefore pushed onto the sink as they're created
  3. Note that the stream UDF grows in memory usage during processing (indicating data is being "stored")
  4. Note that the stream UDF reduces in memory usage once processing has finished (indicating data is being outputted)

In our case specifically we run the pipeline in two threads, one which has a dequeue storing messages, and the other (main thread) which poplefts messages from that dequeue and yields them

Messages are not being sent to the sink at all (buffer shows 0 messages, sink shows a processing rate of 0), indicating they are being held by the server call. Nor is this a case of a yield being blocked (as searches online might suggest), as a logging call immediately after the yield is being respected

Expected behavior Messages which are yielded before processing completes are passed on

Environment (please complete the following information):

  • Numaflow: [v1.7.0]
  • Numaflow-python: [v0.12.1]

Message from the maintainers:

Impacted by this bug? Give it a 👍. We often sort issues this way to know what to prioritize.

niall-nai avatar Mar 23 '26 14:03 niall-nai

I'm checking this. @niall-nai would it be possible for you to provide a minimal example code to reproduce the issue ?

Also, if possible please try using the current main. A lot of refactoring and fixes were merged recently.

# uv
uv add "pynumaflow @ git+https://github.com/numaproj/numaflow-python.git@f894c01173a207a88adfea6b2b3dc8de71369ebc#subdirectory=packages/pynumaflow"

# or poetry
poetry add "git+https://github.com/numaproj/numaflow-python.git@f894c01173a207a88adfea6b2b3dc8de71369ebc#subdirectory=packages/pynumaflow"

BulkBeing avatar Mar 23 '26 15:03 BulkBeing

Hi @BulkBeing it probably won't be today due to other commitments, but I can definitely look at getting that sorted for tomorrow, thanks for looking into this

niall-nai avatar Mar 23 '26 15:03 niall-nai

Thanks! Meanwhile, I will also try to reproduce the issue from my side.

BulkBeing avatar Mar 23 '26 16:03 BulkBeing

Just for completeness, I should note that we've ruled out the following so far:

  • Hitting a thread limit (setting max_threads to 4 gives same result as 16)
  • Hitting a CPU limit (sitting tidy on ~0.2vcpu)
  • Issues caused by kubectl evictions vs a defined memory limit (setting memory limit to 500Mi on a task which was hitting 1.3Gi hit the same issue)
  • Use of a dequeue possibly causing thread locking issues (switching to a (unreliable) version with list instead of dequeue had the same issues)

niall-nai avatar Mar 23 '26 16:03 niall-nai

Just to confirm for my understanding @niall-nai, you mean instead of streaming they are doing a wait on the whole batch before releasing the messages to the next vertex right?

kohlisid avatar Mar 23 '26 18:03 kohlisid

Exactly that @kohlisid, only when the handler function completes are any yielded messages actually leaving the python process

niall-nai avatar Mar 24 '26 08:03 niall-nai

Sorry for the delay, the following should be a MRE for the Python Map Processor:

import asyncio
from collections import deque
from collections.abc import Callable
import json
import threading
from typing import AsyncIterable
from uuid import uuid4
from pynumaflow.mapstreamer import Datum, MapStreamAsyncServer, Message

class Processor():
    def __init__(self):
        self.msg_callback: Callable[[str, any, dict[str, any]], None] = None

    def run(self, attributes: dict[str, any]):
        self.attributes = attributes

    def add_to_messages(self, topic_name: str, data: any):
        if(self.msg_callback is not None):
            self.msg_callback(topic_name, data)

    def set_msg_callback(self, msg_callback: Callable[[str, any, dict[str, any]], None]):
        self.msg_callback = msg_callback

class Monitor():
    def __init__(self, gen: type[Processor], tag_prefix: str, uuid: str):
        self.num_messages: dict[str, float] = {}
        self.messages: deque[Message] = deque()
        self.tag_prefix = tag_prefix
        self.uuid = uuid

        self.gen = gen
        self.gen.set_msg_callback(self.add_to_messages)

    def add_to_messages(self, topic_name: str, data: any):
        output_tags = [f'{self.tag_prefix}.{topic_name}']
        message_data = json.dumps(data, indent=4, default=str)

        self.messages.append(Message(str.encode(message_data), keys=[self.uuid], tags=output_tags))

        if(topic_name not in self.num_messages):
            self.num_messages[topic_name] = 1
        else:
            self.num_messages[topic_name] += 1

    def get_messages(self) -> list:
        out = []
        while self.messages:
            out.append(self.messages.popleft())

class MsgProcessor(Processor):
    def run(self):
        with open('some_arbitrary_large_list_file.json', 'r') as f:
            for entry in json.load(f):
                self.add_to_messages('fake.topic', entry)

async def numa_handler(keys: list[str], _: Datum) -> AsyncIterable[Message]:
    if(len(keys) > 0 and keys[0]):
        uuid = keys[0]
    else:
        uuid = uuid4()

    msg_processor = MsgProcessor()
    processor_monitor = Monitor(msg_processor, '', uuid)
    processing_thread = threading.Thread(target=msg_processor.run)
    processing_thread.start()
    while(processing_thread.is_alive()):
        for msg in processor_monitor.get_messages():
            yield msg

    processing_thread.join()

    leftover = processor_monitor.get_messages()
    if(len(leftover) > 0):
        for msg in leftover:
            yield msg

async def test_handler():
    gathered_messages = []
    async for i in numa_handler([], None):
        gathered_messages.append(i)
    
    print(len(i))

if __name__ == "__main__":
    # SERVER TESTING
    grpc_server = MapStreamAsyncServer(numa_handler, max_threads=16)
    grpc_server.start()

    # INBUILT TESTING
    asyncio.run(test_handler)

while the following is a MRE of the pipeline, assuming a kafka broke available in localhost docker @ 9092 and the above script loaded as an image labelled test-pipline:0.0.1 store in a local docker register @ 5000

apiVersion: numaflow.numaproj.io/v1alpha1
kind: Pipeline
metadata:
  name: cellebrite-sheet
spec:
  vertices:
  - name: kafka-input
    scale:
      min: 1
    source:
      kafka:
        brokers:
        - host.docker.internal:9092
        topic: test.in
        consumerGroup: numa-group
  - name: test-proc
    limits:
      readBatchSize: 1
    scale:
      min: 1
    containerTemplate:
      resources:
        requests:
          memory: 1Gi
    udf:
      container:
        args:
        - python
        - src/test.py
        image: localhost:5000/test-pipeline:0.0.1
        imagePullPolicy: Always
  - name: kafka-out
    sink:
      kafka:
        brokers:
        - host.docker.internal:9092
        topic: fake.topic
        setKey: true
  edges:
    - from: kafka-input
      to: test-proc
    - from: test-proc
      to: kafka-out
      conditions:
        tags:
          values:
            - fake.topic

Please let me know if I can provide anything else :)

niall-nai avatar Mar 31 '26 14:03 niall-nai

Thanks @niall-nai . I'm working on this.

BulkBeing avatar Apr 02 '26 12:04 BulkBeing

I was able to reproduce the issue. Also, I think I found the reason. In 0.9.0, we were not using asyncio.AsyncQueue for storing messages yielded from UDF code:

  • v0.9.0: https://github.com/numaproj/numaflow-python/blob/780652544c479a777830f93ab710da0fe159a65c/pynumaflow/mapstreamer/servicer/async_servicer.py#L45-L59
  • v0.12.1: https://github.com/numaproj/numaflow-python/blob/a2a2d5651b4fbefdb1d77dda0ff926fb36c81d59/packages/pynumaflow/pynumaflow/mapstreamer/servicer/async_servicer.py#L115-L117

User's code that yields messages doesn't have any await points:

    while(processing_thread.is_alive()):
        for msg in processor_monitor.get_messages():
            yield msg

The only await point is in our SDK code while putting message to the async queue:

async for msg in self.__map_stream_handler(list(req.request.keys), datum):
                res = map_pb2.MapResponse.Result(keys=msg.keys, value=msg.value, tags=msg.tags)
                await result_queue.put(map_pb2.MapResponse(results=[res], id=req.id))

When you inspect theasyncio.Queue.put code, there is no await point if the queue is not full:

➜  python3.13 -c "import asyncio, inspect; print(inspect.getsource(asyncio.Queue.put))"
    async def put(self, item):
        """Put an item into the queue.

        Put an item into the queue. If the queue is full, wait until a free
        slot is available before adding item.

        Raises QueueShutDown if the queue has been shut down.
        """
        while self.full():
            if self._is_shutdown:
                raise QueueShutDown
            putter = self._get_loop().create_future()
            self._putters.append(putter)
            try:
                await putter
            except:
                putter.cancel()  # Just in case putter is not done yet.
                try:
                    # Clean self._putters from canceled putters.
                    self._putters.remove(putter)
                except ValueError:
                    # The putter could be removed from self._putters by a
                    # previous get_nowait call or a shutdown call.
                    pass
                if not self.full() and not putter.cancelled():
                    # We were woken up by get_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._putters)
                raise
        return self.put_nowait(item)

https://github.com/python/cpython/blob/f4c9bc899b982b9742b45cff0643fa34de3dc84d/Lib/asyncio/queues.py#L125-L154 It simply calls the regular function self.put_nowait(item). Also, we use an unbounded queue, so queue will never be full.

This results in making the SDK's async for msg in loop that collects messages from UDF and putting in the queue to be a tight loop starving the eventloop from proceeding other tasks, like the one that reads from queue and sends to back to numa. This results in all messages getting delivered at the same time once this tight for loop completes.

The solution would be to yield to the event loop after putting each message in the queue by calling await asyncio.sleep(0).

BulkBeing avatar Apr 04 '26 01:04 BulkBeing

Thanks so much for looking into this @BulkBeing and for the quick resolution! My understanding is that the method we're using will now work with this fix, but that ideally we should be/ should have been using an async for with an await instead of a standard sync for?

Thanks again for all your help guys!

niall-nai avatar Apr 07 '26 09:04 niall-nai

Oh, I should note, I've encountered a similar behaviour using the ReduceStreamer, but that was resolved by converting to async as detailed in the PR, so thank you for that

niall-nai avatar Apr 07 '26 15:04 niall-nai

Yes @niall-nai always recommended to use async methods within an even loop. If you want to use blocking methods they should be done in the run in executor methods

kohlisid avatar Apr 07 '26 19:04 kohlisid

Thanks so much for looking into this @BulkBeing and for the quick resolution! My understanding is that the method we're using will now work with this fix, but that ideally we should be/ should have been using an async for with an await instead of a standard sync for?

Yes, your existing code should work with the fix. You may see warnings from Python like this:

2026-04-03 10:49:50,256 asyncio WARNING Executing <Task finished name='Task-75' coro=<AsyncMapStreamServicer._invoke_map_stream() done, defined at /app/.venv/lib/python3.13/site-packages/pynumaflow/mapstreamer/servicer/async_servicer.py:118> result=None created at /usr/local/lib/python3.13/asyncio/tasks.py:410> took 1.143 seconds

Ideally, when you use async, you should not block the Python's event loop for more than a few milliseconds. If you need to run a persistent background thread and communicate between that thread, you may use third party libraries like https://github.com/aio-libs/janus In most cases, the need for a native thread can be avoided, and use task abstraction in Python's async world for such background works https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task

BulkBeing avatar Apr 08 '26 02:04 BulkBeing