Skip to content

Date race: access actor-isolated property (of a Sendable type) from within nonisolated method #82230

Open
@rayx

Description

@rayx

Description

I find the following code compiles but I think it shouldn't:

@MainActor
struct S1 {
    var value: Int = 0
    nonisolated var id: Int { value } // This compiles. Should it?
}

This makes it possible to access value concurrently from different domains. Example:

nonisolated func test() {
    var s = S1()
    // 1) modifying the value in MainActor
    Task { @MainActor  in
        s.value += 1
    }
    // 2) reading the value from caller's isolation domain currently
    print(s.id)
}

I think the root cause is non-isolated function shouldn't be allowed to access mutable properties of actor, because that opens the possibility to access them from within a different isolation domain.

It appears that global actor doesn't have this issue:

@MainActor var globalCounter = 0

nonisolated func incrementCounter() {
    globalCounter += 1 // Error (as expected)
}

Reproduction

See above

Expected behavior

The example code shouldn't compile.

Environment

$ swift --version
Swift version 6.1.2 (swift-6.1.2-RELEASE)
Target: x86_64-unknown-linux-gnu

Additional information

Compiler works correctly (producing error) if the value is of non-Sendable type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.triage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions