Skip to content

Commit 410aece

Browse files
committed
[Concurrency] Further test cleanups, making sure modes interop properly
1 parent e559620 commit 410aece

12 files changed

+397
-87
lines changed

stdlib/public/Concurrency/Actor.cpp

Lines changed: 80 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ bool _task_serialExecutor_isSameExclusiveExecutionContext(
324324
enum IsCurrentExecutorCheckMode: unsigned {
325325
/// The default mode when an app was compiled against "new" enough SDK.
326326
/// It allows crashing in isCurrentExecutor, and calls into `checkIsolated`.
327-
Default_UseCheckIsolated_AllowCrash,
327+
Swift6_UseCheckIsolated_AllowCrash,
328328
/// Legacy mode; Primarily to support old applications which used data race
329329
/// detector with "warning" mode, which is no longer supported. When such app
330330
/// is re-compiled against a new SDK, it will see crashes in what was
@@ -333,17 +333,18 @@ enum IsCurrentExecutorCheckMode: unsigned {
333333
Legacy_NoCheckIsolated_NonCrashing,
334334
};
335335
static IsCurrentExecutorCheckMode isCurrentExecutorMode =
336-
Default_UseCheckIsolated_AllowCrash;
336+
Swift6_UseCheckIsolated_AllowCrash;
337337

338338

339339
// Shimming call to Swift runtime because Swift Embedded does not have
340-
// these symbols defined
340+
// these symbols defined.
341341
bool swift_bincompat_useLegacyNonCrashingExecutorChecks() {
342342
#if !SWIFT_CONCURRENCY_EMBEDDED
343343
return swift::runtime::bincompat::
344344
swift_bincompat_useLegacyNonCrashingExecutorChecks();
345-
#endif
345+
#else
346346
return false;
347+
#endif
347348
}
348349

349350
// Check override of executor checking mode.
@@ -353,19 +354,17 @@ static void checkIsCurrentExecutorMode(void *context) {
353354

354355
// Potentially, override the platform detected mode, primarily used in tests.
355356
#if SWIFT_STDLIB_HAS_ENVIRON
356-
if (const char *modeStr =
357-
runtime::environment::concurrencyIsCurrentExecutorLegacyModeOverride()) {
358-
if (modeStr) {
359-
if (strcmp(modeStr, "nocrash") == 0) {
360-
useLegacyMode = true;
361-
} else if (strcmp(modeStr, "crash") == 0) {
362-
useLegacyMode = false;
363-
} // else, just use the platform detected mode
364-
}
357+
if (const char *modeStr = runtime::environment::concurrencyIsCurrentExecutorLegacyModeOverride()) {
358+
if (strcmp(modeStr, "nocrash") == 0 || strcmp(modeStr, "legacy") == 0) {
359+
useLegacyMode = true;
360+
} else if (strcmp(modeStr, "crash") == 0 || strcmp(modeStr, "swift6") == 0) {
361+
useLegacyMode = false;
362+
} // else, just use the platform detected mode
365363
}
366364
#endif // SWIFT_STDLIB_HAS_ENVIRON
365+
367366
isCurrentExecutorMode = useLegacyMode ? Legacy_NoCheckIsolated_NonCrashing
368-
: Default_UseCheckIsolated_AllowCrash;
367+
: Swift6_UseCheckIsolated_AllowCrash;
369368
}
370369

371370
SWIFT_CC(swift)
@@ -389,20 +388,27 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
389388
// the expected executor however, so we need to try a bit harder before
390389
// we fail.
391390

392-
// Are we expecting the main executor and are using the main thread?
393-
if (expectedExecutor.isMainExecutor() && isExecutingOnMainThread()) {
394-
// Due to compatibility with pre-checkIsolated code, we cannot remove
395-
// this special handling. CheckIsolated can handle this if the expected
396-
// executor is the main queue / main executor, however, if we cannot call
397-
// checkIsolated we cannot rely on it to handle this.
398-
// TODO: consider removing this branch when `useCrashingCheckIsolated=true`
399-
return true;
391+
// Legacy special handling the main executor by detecting the main thread.
392+
//
393+
// When 'checkIsolated' is available it will perform a dispatch queue assertion
394+
// against the main queue, potentially resulting in a crash (expected).
395+
//
396+
// In legacy mode, we cannot allow crashes here, and therefore we keep the
397+
// special best-effort handling of the "main thread".
398+
if (isCurrentExecutorMode == Legacy_NoCheckIsolated_NonCrashing) {
399+
if (expectedExecutor.isMainExecutor() && isExecutingOnMainThread()) {
400+
return true;
401+
}
400402
}
401403

404+
// We cannot use 'complexEquality' as it requires two executor instances,
405+
// and we do not have a 'current' executor here.
406+
402407
// Otherwise, as last resort, let the expected executor check using
403408
// external means, as it may "know" this thread is managed by it etc.
404-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
405-
swift_task_checkIsolated(expectedExecutor);
409+
if (isCurrentExecutorMode == Swift6_UseCheckIsolated_AllowCrash) {
410+
swift_task_checkIsolated(expectedExecutor); // will crash if not same context
411+
406412
// checkIsolated did not crash, so we are on the right executor, after all!
407413
return true;
408414
}
@@ -425,34 +431,31 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
425431
return true;
426432
}
427433

428-
// If the expected executor is "default" then we should have matched
429-
// by pointer equality already with the current executor.
430-
if (expectedExecutor.isDefaultActor()) {
431-
// If the expected executor is a default actor, it makes no sense to try
432-
// the 'checkIsolated' call, it must be equal to the other actor, or it is
433-
// not the same isolation domain.
434-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
435-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption");
436-
}
437-
return false;
438-
}
439-
440-
if (expectedExecutor.isMainExecutor() && !currentExecutor.isMainExecutor()) {
441-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
442-
// TODO: Invoke checkIsolated() on "main" SerialQueue once it implements `checkIsolated`, for potentially better/more consistent error messages
443-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption; Expected MainActor executor");
444-
}
445-
return false;
446-
} else if (!expectedExecutor.isMainExecutor() && currentExecutor.isMainExecutor()) {
447-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
448-
// TODO: Invoke checkIsolated() on "main" SerialQueue once it implements `checkIsolated`, for potentially better/more consistent error messages
449-
swift_Concurrency_fatalError(0, "Incorrect actor executor assumption; Expected not-MainActor executor");
434+
// Only in legacy mode:
435+
// We check if the current xor expected executor are the main executor.
436+
// If so only one of them is, we know that WITHOUT 'checkIsolated' or invoking
437+
// 'dispatch_assert_queue' we cannot be truly sure the expected/current truly
438+
// are "on the same queue". There exists no non-crashing API to check this,
439+
// so we PESSIMISTICALLY return false here.
440+
//
441+
// In Swift6 mode:
442+
// We don't do this naive check, because we'll fall back to
443+
// `expected.checkIsolated()` which, if it is the main executor, will invoke
444+
// the crashing 'dispatch_assert_queue(main queue)' which will either crash
445+
// or confirm we actually are on the main queue; or the custom expected
446+
// executor has a chance to implement a similar queue check.
447+
if (isCurrentExecutorMode == Legacy_NoCheckIsolated_NonCrashing) {
448+
if ((expectedExecutor.isMainExecutor() && !currentExecutor.isMainExecutor()) ||
449+
(!expectedExecutor.isMainExecutor() && currentExecutor.isMainExecutor())) {
450+
return false;
450451
}
451-
return false;
452452
}
453453

454+
// Complex equality means that if two executors of the same type have some
455+
// special logic to check if they are "actually the same".
454456
if (expectedExecutor.isComplexEquality()) {
455-
if (currentExecutor.getIdentity() && expectedExecutor.getIdentity() &&
457+
if (currentExecutor.getIdentity() &&
458+
expectedExecutor.getIdentity() &&
456459
swift_compareWitnessTables(
457460
reinterpret_cast<const WitnessTable *>(
458461
currentExecutor.getSerialExecutorWitnessTable()),
@@ -470,7 +473,7 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
470473
// chance to check.
471474
if (isSameExclusiveExecutionContextResult) {
472475
return true;
473-
}
476+
} // else, we must give 'checkIsolated' a last chance to verify isolation
474477
}
475478
}
476479

@@ -494,20 +497,22 @@ static bool swift_task_isCurrentExecutorImpl(SerialExecutorRef expectedExecutor)
494497
// Note that this only works because the closure in assumeIsolated is
495498
// synchronous, and will not cause suspensions, as that would require the
496499
// presence of a Task.
497-
// compat_invoke_swift_task_checkIsolated(expectedExecutor);
498-
if (isCurrentExecutorMode == Default_UseCheckIsolated_AllowCrash) {
499-
swift_task_checkIsolated(expectedExecutor);
500+
if (isCurrentExecutorMode == Swift6_UseCheckIsolated_AllowCrash) {
501+
swift_task_checkIsolated(expectedExecutor); // will crash if not same context
502+
500503
// The checkIsolated call did not crash, so we are on the right executor.
501504
return true;
502505
}
503506

507+
// In the end, since 'checkIsolated' could not be used, so we must assume
508+
// that the executors are not the same context.
504509
assert(isCurrentExecutorMode == Legacy_NoCheckIsolated_NonCrashing);
505510
return false;
506511
}
507512

508513
/// Logging level for unexpected executors:
509-
/// 0 - no logging
510-
/// 1 - warn on each instance
514+
/// 0 - no logging -- will be IGNORED when Swift6 mode of isCurrentExecutor is used
515+
/// 1 - warn on each instance -- will be IGNORED when Swift6 mode of isCurrentExecutor is used
511516
/// 2 - fatal error
512517
///
513518
/// NOTE: The default behavior on Apple platforms depends on the SDK version
@@ -524,9 +529,28 @@ static void checkUnexpectedExecutorLogLevel(void *context) {
524529
if (!levelStr)
525530
return;
526531

532+
auto isCurrentExecutorLegacyMode =
533+
swift_bincompat_useLegacyNonCrashingExecutorChecks();
534+
527535
long level = strtol(levelStr, nullptr, 0);
528-
if (level >= 0 && level < 3)
529-
unexpectedExecutorLogLevel = level;
536+
if (level >= 0 && level < 3) {
537+
if (isCurrentExecutorLegacyMode) {
538+
// legacy mode permits doing nothing or just logging, since the method
539+
// used to perform the check itself is not going to crash:
540+
unexpectedExecutorLogLevel = level;
541+
} else {
542+
// We are in swift6/crash mode of isCurrentExecutor which means that
543+
// rather than returning false, that method will always CRASH when an
544+
// executor mismatch is discovered.
545+
//
546+
// Thus, for clarity, we set this mode also to crashing, as runtime should
547+
// not expect to be able to get any logging or ignoring done. In practice,
548+
// the crash would happen before logging or "ignoring", but this should
549+
// help avoid confusing situations like "I thought it should log" when
550+
// debugging the runtime.
551+
unexpectedExecutorLogLevel = 2;
552+
}
553+
}
530554
#endif // SWIFT_STDLIB_HAS_ENVIRON
531555
}
532556

stdlib/public/runtime/Bincompat.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,19 @@ bool useLegacySwiftObjCHashing() {
255255
#endif
256256
}
257257

258+
// Controls legacy mode for the 'swift_task_isCurrentExecutorImpl' runtime function.
259+
//
260+
// In "legacy" / "no crash" mode:
261+
// * The `swift_task_isCurrentExecutorImpl` cannot crash
262+
// * This means cases where no "current" executor is present cannot be diagnosed correctly
263+
// * The runtime can NOT use 'SerialExecutor/checkIsolated'
264+
// * The runtime can NOT use 'dispatch_precondition' which is able ot handle some dispatch and main actor edge cases
265+
//
266+
// New behavior in "swift6" "crash" mode:
267+
// * The 'swift_task_isCurrentExecutorImpl' will CRASH rather than return 'false'
268+
// * This allows the method to invoke 'SerialExecutor/checkIsolated'
269+
// * Which is allowed to call 'dispatch_precondition' and handle "on dispatch queue but not on Swift executor" cases
270+
//
258271
// FIXME(concurrency): Once the release is announced, adjust the logic detecting the SDKs
259272
bool swift_bincompat_useLegacyNonCrashingExecutorChecks() {
260273
#if BINARY_COMPATIBILITY_APPLE

stdlib/public/runtime/EnvironmentVariables.def

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ VARIABLE(SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE, string, "",
121121
"non-crashing behavior. This flag enables temporarily restoring the "
122122
"legacy 'nocrash' behavior until adopting code has been adjusted. "
123123
"Legal values are: "
124-
" 'nocrash' (Legacy behavior), "
125-
" 'crash' (Swift 6.0+ behavior)")
124+
" 'legacy' (Legacy behavior), "
125+
" 'swift6' (Swift 6.0+ behavior)")
126126

127127
#undef VARIABLE

test/Concurrency/Runtime/actor_assert_precondition_executor_checkIsolated_bincompat.swift renamed to test/Concurrency/Runtime/actor_assert_precondition_executor_checkIsolated_bincompat_crash_swift_6_mode.swift

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
// RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-build-swift -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library %s -o %t/a.out
3+
// RUN: %target-codesign %t/a.out
4+
// RUN: %env-SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE=swift6 %target-run %t/a.out
25

36
// REQUIRES: executable_test
47
// REQUIRES: concurrency
@@ -11,6 +14,8 @@
1114
// UNSUPPORTED: use_os_stdlib
1215
// UNSUPPORTED: freestanding
1316

17+
import StdlibUnittest
18+
1419
final class NaiveQueueExecutor: SerialExecutor {
1520
init() {}
1621

@@ -38,32 +43,26 @@ actor ActorOnNaiveQueueExecutor {
3843
self.executor.asUnownedSerialExecutor()
3944
}
4045

46+
// Executes on global pool, but our `checkIsolated` impl pretends
47+
// that it is the same executor by never crashing.
4148
nonisolated func checkPreconditionIsolated() async {
4249
print("Before preconditionIsolated")
4350
self.preconditionIsolated()
4451
print("After preconditionIsolated")
45-
46-
print("Before assumeIsolated")
47-
self.assumeIsolated { iso in
48-
print("Inside assumeIsolated")
49-
}
50-
print("After assumeIsolated")
5152
}
5253
}
5354

5455
@main struct Main {
5556
static func main() async {
56-
if #available(SwiftStdlib 6.0, *) {
57-
let actor = ActorOnNaiveQueueExecutor()
58-
await actor.checkPreconditionIsolated()
59-
// CHECK: Before preconditionIsolated
60-
// CHECK-NEXT: checkIsolated: pretend it is ok!
61-
// CHECK-NEXT: After preconditionIsolated
57+
let tests = TestSuite("AssertPreconditionIsolationTests")
6258

63-
// CHECK-NEXT: Before assumeIsolated
64-
// CHECK-NEXT: checkIsolated: pretend it is ok!
65-
// CHECK-NEXT: Inside assumeIsolated
66-
// CHECK-NEXT: After assumeIsolated
59+
if #available(SwiftStdlib 6.0, *) {
60+
tests.test("[swift6+checkIsolated] Isolation assured by invoking 'checkIsolated'") {
61+
let actor = ActorOnNaiveQueueExecutor()
62+
await actor.checkPreconditionIsolated()
63+
}
6764
}
65+
66+
await runAllTestsAsync()
6867
}
6968
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-build-swift -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library %s -o %t/a.out
3+
// RUN: %target-codesign %t/a.out
4+
// RUN: %env-SWIFT_IS_CURRENT_EXECUTOR_LEGACY_MODE_OVERRIDE=legacy %target-run %t/a.out
5+
6+
// REQUIRES: executable_test
7+
// REQUIRES: concurrency
8+
// REQUIRES: concurrency_runtime
9+
10+
// REQUIRES: libdispatch
11+
12+
// UNSUPPORTED: back_deployment_runtime
13+
// UNSUPPORTED: back_deploy_concurrency
14+
// UNSUPPORTED: use_os_stdlib
15+
// UNSUPPORTED: freestanding
16+
17+
import StdlibUnittest
18+
19+
final class NaiveQueueExecutor: SerialExecutor {
20+
init() {}
21+
22+
public func enqueue(_ job: consuming ExecutorJob) {
23+
job.runSynchronously(on: self.asUnownedSerialExecutor())
24+
}
25+
26+
public func asUnownedSerialExecutor() -> UnownedSerialExecutor {
27+
UnownedSerialExecutor(ordinary: self)
28+
}
29+
30+
func checkIsolated() {
31+
print("checkIsolated: pretend it is ok!")
32+
}
33+
}
34+
35+
actor ActorOnNaiveQueueExecutor {
36+
let executor: NaiveQueueExecutor
37+
38+
init() {
39+
self.executor = NaiveQueueExecutor()
40+
}
41+
42+
nonisolated var unownedExecutor: UnownedSerialExecutor {
43+
self.executor.asUnownedSerialExecutor()
44+
}
45+
46+
// Executes on global pool, but our `checkIsolated` impl pretends
47+
// that it is the same executor by never crashing.
48+
nonisolated func checkPreconditionIsolated() async {
49+
print("Before preconditionIsolated")
50+
self.preconditionIsolated()
51+
print("After preconditionIsolated")
52+
}
53+
}
54+
55+
@main struct Main {
56+
static func main() async {
57+
let tests = TestSuite("AssertPreconditionIsolationTests")
58+
59+
if #available(SwiftStdlib 6.0, *) {
60+
tests.test("[legacy mode] expect crash since unable to invoke 'checkIsolated'") {
61+
expectCrashLater() // In legacy mode we do NOT invoke 'checkIsolated' and therefore will crash
62+
63+
let actor = ActorOnNaiveQueueExecutor()
64+
await actor.checkPreconditionIsolated()
65+
}
66+
}
67+
68+
await runAllTestsAsync()
69+
}
70+
}

0 commit comments

Comments
 (0)