Skip to content

Reading from multiple changefeeds in Python #3298

Closed

Description

@AtnNn

The next operation in Python on cursors is a blocking operation, making it impossible to read from multiple changefeeds at once. This makes it very hard to take full advantage of changefeeds in Python.

Activity

  1. added this to the subsequent milestone on Nov 6, 2014
  2. mlucy commented on Nov 6, 2014

    @mlucy
    Member

    What would we do to improve this? Add a way to have a callback be called whenever there's a new change?

  3. AtnNn commented on Nov 6, 2014

    @AtnNn
    MemberAuthor

    I believe callbacks would solve the problem nicely. We could have some sort of Deferred objects à la twisted, but I personally don't like that API. I am not familiar with what other Python libraries do.

  4. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    The closest match in the general library are the Queue classes, and they provide methods like Queue.get_nowait() or Queue.get(block=True, timeout=x) which raise a Queue.Empty if there is nothing available. It is too bad that the Queue classes are not a subclass of iterables because that would make a great model for us.

    Alternately we could forge a new path and have next raise StopIteration when there is nothing available without closing the cursor. That would be really non-standard, but make for clean-looking code and would probably require an opt-arg to not break existing code.

    I think the best is probably to emulate Queue for this type of behavior.

  5. AtnNn commented on Nov 7, 2014

    @AtnNn
    MemberAuthor

    I would not use Queue. It is very heavyweight and is designed to be used in multi-threaded code, which the driver doesn't support. It would not work in single-threaded code because both put and get could block the thread indefinitely.

    @mlucy's idea of using callbacks seems best to me. It is the most general. Users could easily use a queue by adding q.put as a callback.

  6. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    @AtnNn You are mistaking my suggestion: I was suggesting that if we are looking for a model that we emulate the interface of Queue. It is not the cleanest out there, but it is one that Python programmers trying to do this sort of thing are already accustomed to. We don't really need normal get or put since we already have that (hence my comment about Queue not having been modeled as an extension of iterables), but the get_nowait() call is essentially what you are asking for. Extending cursors this way would be a clean way of getting this model.

    Callbacks are not often used in Python outside a few packages and so are a poor choice.

  7. AtnNn commented on Nov 7, 2014

    @AtnNn
    MemberAuthor

    Sorry, I did misunderstand your proposal. It would be nice to have next_nowait, but I don't see how it would solve this issue. I have realised callbacks would not work either without an event loop.

    asyncio seems to be Python's answer to this issue, as discussed in #2622. We could bite the bullet and rewrite the driver to use that model.

    The Ruby driver also has the limitation described in this issue.

  8. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    asyncio is new in Python3.4, and is subject to much change even there. Additionally it is an event-loop based system, so would be a very different model than our current driver. If that was the direction we want to go then we would be better off going with something that is more portable like twisted (call back based) or greenlets(would non standard package with monkey-patching). But either of those would be almost complete driver re-writes, and so would be better to have a either community or secondary drivers.

    But I don't see how the get_nowait() method does not solve the problem blocking operations. To illustrate...

    Current version:

    feedA = r.table('a').changes().run(conn)
    feedB = r.table('b').changes().run(conn)
    print(next(a))
    print(next(b))

    So the problem illustrated is that with the next/iterator model you will not see any change in b until you see one in a. This is of course a problem.

    With a get_nowait():

    feedA = r.table('a').changes().run(conn)
    feedB = r.table('b').changes().run(conn)
    try:
        print(a.get_nowait())
    except Empty: pass
    try:
        print(b.get_nowait())
    except Empty: pass

    Here you will see a value from either, both, or neither depending on what is already available. In a real example you would wrap this in a while block with some appropriate sleeps depending on where you got data.

    Now I believe that there are more problems lurking below the surface in how the server actually fulfills these requests, but am a little foggy about the conversation I had with @mlucy about that a while ago.

  9. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    Oh, and to add the example for the second possible solution that I posted earlier:

    feedA = r.table('a').changes(someFlag=True).run(conn)
    feedB = r.table('b').changes(someFlag=True).run(conn)
    while True:
        for a in feedA: # would get StopIteration error if there is nothing available at that moment
            print(a)
        for b in feedB: # would get StopIteration error if there is nothing available at that moment
            print(b)

    Important to note here is that even though they emit StopIteration errors (how iterators signal they are done), both feedA and feedB would still be capable of returning further results. This would be very non-standard behavior in Python, but it is an elegant solution.

    Edit: the major problem here is how do we signal when a changefeed is satisfied? (e.g.: one with a limit)

  10. AtnNn commented on Nov 7, 2014

    @AtnNn
    MemberAuthor

    A get_nowait operation would still have to block while asking the server if there are any more available documents. I would prefer a solution that does not block.

    wrap this in a while block with some appropriate sleeps

    That would be ugly and would work in some cases, but when reading from a real-time feed, any form of sleep is inappropriate.

  11. danielmewes commented on Nov 7, 2014

    @danielmewes
    Member

    I think get_nowait() solves the problem. We could add a conn.wait_any() function on the connection, that would wait until there's new data for any of the active queries to avoid the constant sleep in the outer loop.

    One thing that might make callbacks slightly nicer is that code that uses change feeds can be decoupled better.
    With the get_nowait(), you need some kind of central place that repeatedly calls everything that might have a change feed open. With a callback, the connection is the only thing in your application that has to keep track of who currently has changefeeds running.
    So I imagine that callbacks could be easier to use if you have many different components in your application accessing RethinkDB, and not one place that coordinates all of them.

    Could be support both interfaces? A Queue-like one, and a callback one?

  12. danielmewes commented on Nov 7, 2014

    @danielmewes
    Member

    (...we could internally implement the Queue interface on top of the callback interface presumably)

  13. VeXocide commented on Nov 7, 2014

    @VeXocide
    Member

    Solving this through StopIteration is not only non-standard but it would prevent these iterators being used in conjunction with the itertools module for example, we really shouldn't go down that path.

  14. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    I don't think that that is a requirement. Rather get_nowait() would only check if there were already received responses. In this model we would have outstanding requests for any active changefeeds and either use any call (e.g.: next or get_nowait) as a chance to do general housekeeping work such as processing arrived packets and then do the check in the cursor. Or we separate that into its own background thread simplifying some parts and complicating others. But in either case it would still solve the presented problem.

  15. larkost commented on Nov 7, 2014

    @larkost
    Collaborator

    @danielmewes I am not sure what you mean. So far I think that the Queue-like idea is completely orthogonal to callbacks, which would require a runloop.

    Edit: sorry... missed one message.

  16. 77 remaining items

  17. gchpaco commented on Feb 5, 2015

    @gchpaco
    Contributor

    If we rebase the Python driver onto asyncio then run, connect and probably cursors would become something like this:

    def run(*args, *kwargs):
        loop = asyncio.get_event_loop()
        result = arun(*args, *kwargs)
        loop.run_until_complete(result)
        return result.result()
    

    and similarly for the others. That is, they will automatically play nice with async stuff under the scenes, so you don't need to use arun and aconnect and the like unless actually necessary.

  18. timmaxw commented on Feb 5, 2015

    @timmaxw
    Member

    If we implement query.run() as @gchpaco suggested, we wouldn't even need a conn.loop_forever() method. Instead, it would just be:

    import rethinkdb as r
    conn = r.connect()
    def callback(change):
        print change
    r.table("foo").changes().run().on(callback)
    import asyncio
    asyncio.get_event_loop().run_forever()
  19. deontologician commented on Feb 5, 2015

    @deontologician
    Contributor

    Count me onboard for the callbacks for changefeeds option. I'm concerned about making the basic "just get started" version significantly different than the code you'd need to write real applications in. It seems the r.join syntax does force the user to write a select loop which is annoying and handled by all of these async libraries already.

    Ultimately, the users and the driver will be gravitating towards asyncio over time, so it makes sense to align the driver with that api vs. inventing something specific for our needs. A lot of time and thought went into the asyncio interface, and we probably shouldn't waste time coming up with something unique.

  20. gchpaco commented on Feb 5, 2015

    @gchpaco
    Contributor

    I would make conn.loop_forever() exist, but be a direct call into run_forever() on the associated event loop. Easier to explain to new users, does the same thing.

  21. coffeemug commented on Feb 6, 2015

    @coffeemug
    Contributor
    r.union(
        feedA.map(r.row.merge({feedIndex: 0})),
        feedB.map(r.row.merge({feedIndex: 1}))
      ).changes()

    Friendly reminder -- you can run merge on streams (and feeds) today. So the above code could be written like this:

    r.union(
        feedA.merge({feedIndex: 0}),
        feedB.merge({feedIndex: 1})
      ).changes()

    Or better yet:

    r.union(
        feedA.merge({source: 'feedA'}),
        feedB.merge({source: 'feedB'})
      ).changes()

    WRT to the API:

    • it sounds like we're in agreement that we shouldn't bother with asyncio in v1.
    • I'd like to spend 10m with @mglukhovsky tomorrow before we proceed. He tends to have really good feedback for things like these.
  22. danielmewes commented on Feb 10, 2015

    @danielmewes
    Member

    In an offline discussion with @larkost , @coffeemug , @timmaxw and @mlucy , we decided to provide an event-loop integration already in 2.0.

    Apart from #3529 , this is going to be the only way to read from multiple changefeeds at the same time in Python.

    We will be providing an on(cb) function on cursors, and integrate with the framework's event loop to call the callback once we get a response.

    An open question was which frameworks we should support first.

    Twisted seems to be very widely used and easily available, so I think we should definitely support that.

    As a second one @gchpaco suggested asyncio for Python >= 3.4 and the similar Trollius for older versions of Python. It probably makes sense to support that second.

  23. danielmewes commented on Feb 10, 2015

    @danielmewes
    Member

    @gchpaco said he would start looking into a Twisted integration.

  24. danielmewes commented on Feb 16, 2015

    @danielmewes
    Member

    Marking as settled. We can discuss details in follow-up issues for specific async / event libraries.

  25. danielmewes commented on Feb 27, 2015

    @danielmewes
    Member

    Closing this.

    It will be solved by either of
    #2622
    #3529
    #3785
    (and further ports we might do in the future)

  26. modified the milestones: duplicate, 2.0 on Mar 19, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions