)
        if result or as_pk_tuple:
            
            if as_pk_tuple:
                result.update(TaskInstanceKey(**cols._mapping) for cols in tis.all())
            else:
                result.update(ti.key for ti in tis)
            if exclude_task_ids is not None:
                result = {
                    task
                    for task in result
                    if task.task_id not in exclude_task_ids
                    and (task.task_id, task.map_index) not in exclude_task_ids
                }
        if as_pk_tuple:
            return result
        if result:
            
            ti_filters = TI.filter_for_tis(result)
            if ti_filters is not None:
                tis = session.query(TI).filter(ti_filters)
        elif exclude_task_ids is None:
            pass  
        elif isinstance(next(iter(exclude_task_ids), None), str):
            tis = tis.filter(TI.task_id.notin_(exclude_task_ids))
        else:
            tis = tis.filter(not_(tuple_in_condition((TI.task_id, TI.map_index), exclude_task_ids)))
        return tis
    @provide_session
    def set_task_instance_state(