'Args:
last_pos(int):
current_pos(int):
limit(int):
Returns:
A deferred list of rows from the device inbox'

def get_all_new_device_messages(self, last_pos, current_pos, limit):

    if (last_pos == current_pos):
        return defer.succeed([])
    def get_all_new_device_messages_txn(txn):
        upper_pos = min(current_pos, (last_pos + limit))
        sql = 'SELECT    max(stream_id),    user_id    FROM    device_inbox    WHERE    ?    <    stream_id    AND    stream_id    <=    ?    GROUP    BY    user_id'
        txn.execute(sql, (last_pos, upper_pos))
        rows = txn.fetchall()
        sql = 'SELECT    max(stream_id),    destination    FROM    device_federation_outbox    WHERE    ?    <    stream_id    AND    stream_id    <=    ?    GROUP    BY    destination'
        txn.execute(sql, (last_pos, upper_pos))
        rows.extend(txn)
        rows.sort()
        return rows
    return self.runInteraction('get_all_new_device_messages', get_all_new_device_messages_txn)
