Skip to content

[Concurrency] Fix Task.sleep on values greater than Int64.max. #78817

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions stdlib/public/Concurrency/DispatchGlobalExecutor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,13 @@ void swift_task_enqueueGlobalWithDelayImpl(SwiftJobDelay delay,
job->schedulerPrivate[SwiftJobDispatchQueueIndex] =
DISPATCH_QUEUE_GLOBAL_EXECUTOR;

// dispatch_time takes a signed int64_t. SwiftJobDelay is unsigned, so
// extremely large values get interpreted as negative numbers, which results
// in zero delay. Clamp the value to INT64_MAX. That's about 292 years, so
// there should be no noticeable difference.
if (delay > (SwiftJobDelay)INT64_MAX)
delay = INT64_MAX;

dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, delay);
dispatch_after_f(when, queue, dispatchContext, dispatchFunction);
}
Expand Down
28 changes: 28 additions & 0 deletions test/Concurrency/Runtime/async_task_sleep.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import Dispatch
static func main() async {
await testSleepDuration()
await testSleepDoesNotBlock()
await testSleepHuge()
}

static func testSleepDuration() async {
Expand Down Expand Up @@ -45,4 +46,31 @@ import Dispatch
// CHECK: Run second
await task.get()
}

static func testSleepHuge() async {
// Make sure nanoseconds values about Int64.max don't get interpreted as
// negative and fail to sleep.
let task1 = detach {
try await Task.sleep(nanoseconds: UInt64(Int64.max) + 1)
}
let task2 = detach {
try await Task.sleep(nanoseconds: UInt64.max)
}

try! await Task.sleep(nanoseconds: UInt64(pause))

task1.cancel()
task2.cancel()

// These should throw due to being canceled. If the sleeps completed then
// the cancellation will do nothing and we won't throw, which is a failure.
do {
_ = try await task1.value
fatalError("Sleep 1 completed early.")
} catch {}
do {
_ = try await task2.value
fatalError("Sleep 2 completed early.")
} catch {}
}
}