SE-0469: Task Naming

Big +1 on this feature. While it might look simple on the surface it will enable us to improve our debugging and testing experience tremendously.
For me the biggest reason why we should do this is that it allows us to write deterministic tests for our code. Something that has come up in those forums previously here and here. Right now it is impossible to test certain scenarios where we need specific job ordering to hit certain branches of our code.

I have been experimenting with various ways how to do this in the past and I think this proposal is the missing piece. Below is a snippet showing how we could write a deterministic task executor using task names.

DeterministicTestExecutor
import Dispatch

final class DeterministicTestExecutor: TaskExecutor, @unchecked Sendable {
    private let queue = DispatchSerialQueue(label: "queue")

    private var order = [String]()
    private var jobs = [String: UnownedJob]()

    init(taskNameOrder: [String]) {
        self.order = Array(taskNameOrder.reversed())
    }

    func enqueue(_ job: consuming ExecutorJob) {
        let unownedJob = UnownedJob(job)
        guard let taskName = job?.unsafeCurrentTask?.name else {
            fatalError("All jobs need to be name for deterministic scheduling")
        }
        queue.async {
            if self.order.last == taskName {
                self.order.removeLast()
                unownedJob.runSynchronously(on: self.asUnownedTaskExecutor())

                while let nextTaskName = self.order.last, let nextJob = self.jobs[taskName] {
                    self.order.removeLast()
                    self.jobs.removeValue(forKey: nextTaskName)

                    nextJob.runSynchronously(on: self.asUnownedTaskExecutor())
                }
            } else {
                self.jobs[taskName] = unownedJob
            }
        }
    }
}

I personally think that we will end up with naming a lot of tasks to make testing and debugging easier. There are so many scenarios where it would have been helpful understanding which one of my child tasks finished or which one got cancellation triggered on them.

4 Likes