Fix reordering/reentrancy bug in NIOAsyncWriter + NIOAsyncChannel (#2587)

* Fix reordering/reentrancy bug in `NIOAsyncWriter` + `NIOAsyncChannel`

# Motivation
While testing the latest async interfaces we found a potential reordering/reentrancy bug in the `NIOAsyncWriter`. This was caused due to our latest performance changes where we fast-pathed calls in `didYield` to not hop. The problem was in the following flow:

1. Task 1: Calls `outbound.write()` -> which led an `EventLoop` enqueue with `didYield`
2. Task 1: Calls `outbound.write()` -> which led an `EventLoop` enqueue with `didYield`
3. EventLoop: While processing the write from 1. the channel became **not** writable
4. Task 1: Calls `outbound.write()` -> which lead to buffering the write in the writer's state machine since we are **not** writable
5. EventLoop: While still processing the write from 1. the channel became writable again -> We informed the `NIOAsyncWriter` about this which unbuffered the write in 4. that was stored in the state machine and call `didYield`. Since, we are on the EventLoop already we processed the write right away

The above flow show-cases a flow where we reordered the write in 2. and 4.

# Modification
This PR fixes the above issue while upholding a few constraints:

1. Produce as few context switches as possible
2. Minimize allocations

I tried different approaches but in the end decided to do the following:
1. Make sure to never call `didYield/didTerminate` from calls on the `NIOAsyncWriter.Sink`
2. Don't coalesce the elements of different writes in the `NIOAsyncWriter` but rather use the suspended tasks to retry a write after they were suspended. I choose to do this since I wanted to avoid any allocation (remember writers are `some Sequence`) and because we assume that continuous contention in a multi producer pattern is low.
3. Make sure that `Sink.finish()` is terminal and does not lead to a `didTerminate` event. This is in line with 1.

One important thing to call out, our `writer.finish()` method is not `async` we have to buffer the finish event and deliver it with the yield that got buffered before we transitioned to `writerFinished`.

# Result
No more reordering/reentrancy problems in `NIOAsyncWriter` or `NIOAsyncChannel`.

* Code review
This commit is contained in:
Franz Busch authored and GitHub committed 2023-11-08 10:38:49 +00:00
1 parent 23977a932f
commit 035141dddb
2 files changed
+329 -419

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -126,36 +126,6 @@ final class NIOAsyncWriterTests: XCTestCase {
XCTAssertEqual(elements, 60)
}
func testWriterCoalescesWrites() async throws {
var writes = [Deque<String>]()
self.delegate.didYieldHandler = {
writes.append($0)
}
self.sink.setWritability(to: false)
let task1 = Task { [writer] in
try await writer!.yield("message1")
}
task1.cancel()
try await task1.value
let task2 = Task { [writer] in
try await writer!.yield("message2")
}
task2.cancel()
try await task2.value
let task3 = Task { [writer] in
try await writer!.yield("message3")
}
task3.cancel()
try await task3.value
self.sink.setWritability(to: true)
XCTAssertEqual(writes, [Deque(["message1", "message2", "message3"])])
}
// MARK: - WriterDeinitialized
func testWriterDeinitialized_whenInitial() async throws {
@@ -183,11 +153,11 @@ final class NIOAsyncWriterTests: XCTestCase {
func testWriterDeinitialized_whenFinished() async throws {
self.sink.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
self.writer = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
// MARK: - ToggleWritability
@@ -235,6 +205,9 @@ final class NIOAsyncWriterTests: XCTestCase {
self.sink.setWritability(to: true)
// Sleep a bit so that the other Task can retry the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
@@ -273,6 +246,9 @@ final class NIOAsyncWriterTests: XCTestCase {
self.sink.setWritability(to: true)
// Sleep a bit so that the other Task can retry the yield
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
@@ -282,7 +258,7 @@ final class NIOAsyncWriterTests: XCTestCase {
self.sink.setWritability(to: false)
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
// MARK: - Yield
@@ -348,8 +324,10 @@ final class NIOAsyncWriterTests: XCTestCase {
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
await XCTAssertThrowsError(try await task.value) { error in
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
}
func testYield_whenWriterFinished() async throws {
@@ -376,7 +354,7 @@ final class NIOAsyncWriterTests: XCTestCase {
await XCTAssertThrowsError(try await self.writer.yield("message1")) { error in
XCTAssertEqual(error as? NIOAsyncWriterError, .alreadyFinished())
}
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testYield_whenFinishedError() async throws {
@@ -385,7 +363,7 @@ final class NIOAsyncWriterTests: XCTestCase {
await XCTAssertThrowsError(try await self.writer.yield("message1")) { error in
XCTAssertTrue(error is SomeError)
}
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
// MARK: - Cancel
@@ -401,8 +379,10 @@ final class NIOAsyncWriterTests: XCTestCase {
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
await XCTAssertThrowsError(try await task.value) { error in
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(self.delegate.didYieldCallCount, 0)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
@@ -421,8 +401,10 @@ final class NIOAsyncWriterTests: XCTestCase {
task.cancel()
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
await XCTAssertThrowsError(try await task.value) { error in
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
@@ -442,12 +424,14 @@ final class NIOAsyncWriterTests: XCTestCase {
task.cancel()
await XCTAssertNoThrow(try await task.value)
await XCTAssertThrowsError(try await task.value) { error in
XCTAssertTrue(error is CancellationError)
}
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
self.sink.setWritability(to: true)
XCTAssertEqual(self.delegate.didYieldCallCount, 2)
XCTAssertEqual(self.delegate.didYieldCallCount, 1)
}
func testCancel_whenFinished() async throws {
@@ -510,7 +494,12 @@ final class NIOAsyncWriterTests: XCTestCase {
self.writer.finish()
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
// We have to become writable again to unbuffer the yield
self.sink.setWritability(to: true)
await XCTAssertNoThrow(try await task.value)
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
}
func testWriterFinish_whenFinished() {
@@ -527,7 +516,7 @@ final class NIOAsyncWriterTests: XCTestCase {
func testSinkFinish_whenInitial() async throws {
self.sink = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSinkFinish_whenStreaming() async throws {
@@ -539,7 +528,7 @@ final class NIOAsyncWriterTests: XCTestCase {
self.sink = nil
XCTAssertEqual(self.delegate.didTerminateCallCount, 1)
XCTAssertEqual(self.delegate.didTerminateCallCount, 0)
}
func testSinkFinish_whenFinished() async throws {