def pick_task(self) -> Tuple[Optional[int], Optional[PgDistTask]]:
        """Returns the tuple(i, task), where `i` - is the task index in the self._tasks list

        Tasks are picked by following priorities:

        1. If there is already a transaction in progress, pick a task
           that that will change already affected worker primary.
        2. If the coordinator address should be changed - pick a task
           with groupid=0 (coordinators are always in groupid 0).
        3. Pick a task that is the oldest (first from the self._tasks)
        """

        with self._condition:
            if self._in_flight:
                i = self.find_task_by_groupid(self._in_flight.groupid)
            else:
                while True:
                    i = self.find_task_by_groupid(CITUS_COORDINATOR_GROUP_ID)  # set_coordinator
                    if i is None and self._tasks:
                        i = 0
                    if i is None:
                        break
                    task = self._tasks[i]
                    if task == self._pg_dist_group.get(task.groupid):
                        self._tasks.pop(i)  # nothing to do because cached version of pg_dist_group already matches
                    else:
                        break
            task = self._tasks[i] if i is not None else None

            return i, task
Returns the tuple(i, task), where `i` - is the task index in the self._tasks list

        Tasks are picked by following priorities:

        1. If there is already a transaction in progress, pick a task
           that that will change already affected worker primary.
        2. If the coordinator address should be changed - pick a task
           with groupid=0 (coordinators are always in groupid 0).
        3. Pick a task that is the oldest (first from the self._tasks)
        
patroni/postgresql/mpp/citus.py