'Find the stream_ordering of the first event that was received after
a given timestamp. This is relatively slow as there is no index on
received_ts but we can then use this to delete push actions before
this.
received_ts must necessarily be in the same order as stream_ordering
and stream_ordering is indexed, so we manually binary search using
stream_ordering'

def _find_first_stream_ordering_after_ts_txn(self, txn, ts):

    txn.execute('SELECT    MAX(stream_ordering)    FROM    events')
    max_stream_ordering = txn.fetchone()[0]
    if (max_stream_ordering is None):
        return 0
    range_start = 0
    range_end = max_stream_ordering
    sql = 'SELECT    received_ts    FROM    events    WHERE    stream_ordering    >    ?    ORDER    BY    stream_ordering    LIMIT    1'
    while ((range_end - range_start) > 1):
        middle = int(((range_end + range_start) / 2))
        txn.execute(sql, (middle,))
        middle_ts = txn.fetchone()[0]
        if (ts > middle_ts):
            range_start = middle
        else:
            range_end = middle
    return range_end
