rudder-sdk-ios icon indicating copy to clipboard operation
rudder-sdk-ios copied to clipboard

BUG : `RSAtomic` implementation is flawed

Open TizianoCoroneo opened this issue 2 years ago • 1 comments

Describe the bug

The current implementation of RSAtomic does not guarantee atomicity. This is because of a couple reasons:

  • it is implemented as a struct property wrapper, which could incur additional copies of the internal state of the atomic wrapper, breaking atomicity.
  • hiding the load and store operations in a getter/setter allows obvious race conditions like value += 1 that will expanded to two separate load and store operations, while it should be implemented as a CAS.

More in-detail explanation here: https://github.com/apple/swift-evolution/pull/1387

To Reproduce Try this in a playground:

import Foundation

var atomicCounter = RSAtomic(wrappedValue: 0)

DispatchQueue.concurrentPerform(iterations: 1000) { _ in
    atomicCounter.value += 1
}

print(atomicCounter.value)

The result will most often be less than 1000, like in this screenshot: Screenshot 2024-04-19 at 3 23 32 PM

You should either use DispatchQueues, or actors, or the official Swift Atomics package instead.

Expected behavior RSAtomic should be atomic.

Version of the iOS SDK Swift SDK 1.26.2, latest.

SDK initialisation snippet Irrelevant.

Check for Correct Usage of writeKey and dataPlaneUrl Irrelevant.

TizianoCoroneo avatar Apr 19 '24 13:04 TizianoCoroneo

Hey @TizianoCoroneo, Thank you for bringing this to our attention. We will investigate the matter and get back to you.

1abhishekpandey avatar Apr 19 '24 13:04 1abhishekpandey