Are concurrent methods on isolated conformances actually safe?

I've come across a problem with isolated conformances that I cannot quite understand. The original issue was related to AsyncIterator, which is a non-trivial protocol. However, I think I have simplified the issue without removing the essential aspect.

protocol AsyncRequirement {
  @concurrent func work() async
}

@MainActor
class ConformingType: @MainActor AsyncRequirement {
  func work() async {
  }
}

nonisolated(nonsending) func useThem() async {
  let value: some AsyncRequirement = ConformingType()

  // warning: Conformance of underlying type of 'some AsyncRequirement' to protocol 'AsyncRequirement' may be isolated and cannot be passed to @concurrent context
  await value.work()
}

Conformance of underlying type of 'some AsyncRequirement' to protocol 'AsyncRequirement' may be isolated and cannot be passed to @concurrent context

It is true that ConformingType uses an isolated conformance here. But, the protocol's requirement is asynchronous and isolated conformances are only supported for global actor isolated types. When the concurrent call is to a method on the protocol itself, I do not see how this could be unsafe.

What am I missing?

5 Likes

When the concurrent call is to a method on the protocol itself, I do not see how this could be unsafe.

Per my understanding (which, admittedly, may be flawed here): the combination of a main actor isolated conformance + nonisolated(nonsending) is the dealbreaker here. As the useThem method is isolated to the callers isolation domain, the compiler simply cannot guarantee that some AsyncRequirement resolves in a main actor context (which you're enforcing via class ConformingType: @MainActor AsyncRequirement).

Simply replacing nonisolated(nonsending) with @MainActor makes your example compile for me. Though, as previously stated, I'm not 100% certain that there's not something else also at play here.

2 Likes

You are right that the isolation of the useThem function matters here.

But I think the compiler actually can guarantee that the conforming type's isolation is respected. That await allows an actor hop. And async protocol requirement rely on exactly this to relax constraints.

However, this stuff can be quite subtle. There definitely is a race here if the @concurrent function is not a member of the protocol itself. My theory is this warning is overly-conservative.

1 Like

I think the actor hop itself is fine, but passing potentially non-Sendable values across isolation domains is not. The protocol method in your example has no parameters and no return value, but it still has an implicit self parameter that needs to be passed across isolation domains.

(Note: This might be totally wrong. I haven't used isolated conformances much.)

1 Like

Hmm, but in order for this hop to materialize I presume we'd need to introduce a suspension point right in front of the instantiation of ConformingType:

let value: some AsyncRequirement = await ConformingType()

Attempting to do so yields an additional compiler diagnostic:

No 'async' operations occur within 'await' expression

Though I suspect you're right that compiler might be overly conservative here, as hopping to the main actor appears both feasible and desirable in this scenario.

Correct. However, the self for an isolated conformance by definition must be a global actor isolated type, which makes it Sendable. And I don't think this is relevant anyways, because the calling method is on self and that await is there to change to the needed isolation.

Yeah, this is tricky. Doubly-so because the ConformingType here has a nonisolated init.

The isolated conformances feature does have to verify that all conversions are safe. But it only has to do that when the conversion may also involve crossing an isolation boundary. And that cannot happen in a synchronous context.

I don't think there is a race in this very specific situation. But, a counter-example might exist and that's what I'm looking for.

2 Likes

Is this correct though? I'd assume annotating ConformingType with @MainActor also implicitly makes its init main actor isolated. It has been a while since I read up on initialization and isolation rules, so I may be way off base here.

It is. An implicit init for a global actor isolated type is nonisolated, because it is strictly more flexible and just generally useful. But explicit inits are subject to the same isolation inference rules as all other type members.

1 Like

While messing around here, I found something else related that I think is a bug. It doesn't appear to be possible to avoid this by composing the protocol with SendableMetatype.

1 Like

Ah, you're right. I missed this in your first post. Thanks.

1 Like

IMO the code shouldn't compile in the first place, because it's inherently conflicting to isolated conform to a protocol containing async methods:

  • Isolated conformance requires that an isolated type should conform to a protocol's requirements in that type's isolation. That is, the protocol's methods should be executed in that type's isolation.
  • On the other hand, async methods of a protocol have their own requirements about where they should be executed.

These two requirements conflict in general.

Also, why would one want to mix them? I can't think of any valid scenario. Take above code as an example,

  • If ConformingType.work() doesn't access the type's non-Sendable properties, there is no need to use isolated conformance.
  • If ConformingType.work() accesses the type's non-Sendable properties, it would cause data race if the code compiled (it doesn't).
1 Like

This is an interesting point and I think you may be onto something.

This issue was discovered while interacting with AsyncIteratorProtocol. Its function signatures are nonisolated, but I originally thought that meant @concurrent. And this is why I made my annotations explicit.

But it also did not occur to me to actually verify that the isolated conformance I was experimenting with worked as expected. And it does not! If you do not get access to the type's non-sendable state, I don't think it is particularly helpful. You pointed this out and I agree.

However, I'm not willing to go so far as to say this should fail to compile. Because a protocol could be composed of requirements with non-uniform isolation. And, in general, I'm in favor of accepting as much code as possible, and showing targeted errors at exactly the spots that cannot work. This happens here, though I think the diagnostics leave some things to be desired.

That said, this changes my understanding of the problem. The behaviors of isolated conformances for nonisolated(nonsending) are not the same as for @concurrent. The warning is correct, as is the inability to suppress the warning with SendableMetatype.

Thanks so much @rayx !

1 Like

I did more experiments on this issue. Below is my summary.

TLDR: the behavior is inconsistent between Swift 6.3.3 and nightly; changing code slightly causes inconsistent behaviors in nightly too.

(Note: I didn't use 6.4 because it's not available on compiler explorer).

The setup:

protocol AsyncRequirement {
  @concurrent func work() async
}

@MainActor
class ConformingType: @MainActor AsyncRequirement {
  func work() async {
  }
}

func test1() -> some AsyncRequirement {
  ConformingType()
}

func test2() {
  let value: some AsyncRequirement = ConformingType()
  _ = value
}

@MainActor
func test3() {
  let value: some AsyncRequirement = ConformingType()
  _ = value
}

nonisolated(nonsending)
func test4() async {
  let value: some AsyncRequirement = ConformingType()
  _ = value
}

nonisolated(nonsending)
func test5() async {
  let value: some AsyncRequirement = ConformingType()
  await value.work()
}

Test results:

  1. test3 compiles in all Swift versions. This is as expected.

  2. Swift 6.3.3: All tests except test3 fail to compile and ouput the same error.

    error: main actor-isolated conformance of 'ConformingType' to 'AsyncRequirement' cannot be used in caller isolation ... context [#IsolatedConformances]
    

    I think the behavior is simple, consistent, and easy to understand.

  3. Nightly: tests have different behaviors

    • test1 and test2: fail with the same error as in Swift 6.3.3.
    • test4: it compiles. No warning or error.
    • test5: it compiles with a warning (the one @mattie mentioned in the original post)

    I probably understand the different behaviors of test4 and test5. It appears that isolated conformance implementation in recent releases is different from what's proposed in the original proposal. Compiler produces diagnostic only when the code would actually call methods of isolated confomrance in a different isolation (see my earlier question about this). But if test4 compiles, I think test1 and test2 should compile too?

Another test. It does the same as test5 but uses generic function. It fails to compile in nightly. Note the "cannot satisfy conformance requirement for a 'Sendable' type parameter" part in the error message. I don't quite understand what it meant.

nonisolated(nonsending) func useThem<T: AsyncRequirement & Sendable>(value: T) async {
  await value.work()
}

nonisolated(nonsending) func test6() async {
    useThem(value: ConformingType()) // error: main actor-isolated conformance of 'ConformingType' to 'AsyncRequirement' cannot satisfy conformance requirement for a 'Sendable' type parameter  [#IsolatedConformances]
}

I'd appreciate if anyone in Swift team can clarify if the behaviors in nightly is by design or a regression.

1 Like