From 75d79bc4f76f1593efa9b7db96d239c8ce50d019 Mon Sep 17 00:00:00 2001 From: Jason Monk Date: Sun, 19 Apr 2026 16:55:11 -0400 Subject: [PATCH] Fix #269: Internally synchronize ConnectionStateMachine.transition() (#296) Move the read-check-write of transition() inside a private monitor so concurrent callers can't both observe the same "from" state, both pass the transition-matrix check, and both write. Remove the now-redundant synchronized(stateMachine) wrapper around the streamCountJob check-and-call: with internal locking, a racing disconnect just causes the follow-up transition to be rejected as invalid and logged, which is the correct outcome. Adds a stress test that races CONNECTING -> CONNECTED and CONNECTING -> DISCONNECTED across 2000 rounds and asserts the end state is consistent with the winners returned by transition(). The test fails against the pre-fix implementation. Co-authored-by: Claude Opus 4 (1M context) --- .../tunnel/ConnectionStateMachine.kt | 11 +- .../rousecontext/tunnel/TunnelClientImpl.kt | 19 ++-- .../tunnel/ConnectionStateMachineTest.kt | 100 ++++++++++++++++++ 3 files changed, 118 insertions(+), 12 deletions(-) diff --git a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt index fac22f17..c4b09d33 100644 --- a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt +++ b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.flow.asStateFlow */ class ConnectionStateMachine(private val log: (LogLevel, String) -> Unit = { _, _ -> }) { + private val lock = Any() private val _state = MutableStateFlow(TunnelState.DISCONNECTED) /** @@ -28,21 +29,23 @@ class ConnectionStateMachine(private val log: (LogLevel, String) -> Unit = { _, get() = _state.asStateFlow() /** - * Attempt a state transition. + * Attempt a state transition. Internally synchronized so the + * read-check-write sequence is atomic with respect to other concurrent + * `transition()` callers; see #269. * * @return true if the transition was valid and applied, false if invalid (logged as warning) */ - fun transition(to: TunnelState): Boolean { + fun transition(to: TunnelState): Boolean = synchronized(lock) { val from = _state.value if (!isValidTransition(from, to)) { log( LogLevel.WARN, "ConnectionStateMachine: ignoring invalid transition from $from to $to" ) - return false + return@synchronized false } _state.value = to - return true + true } private fun isValidTransition(from: TunnelState, to: TunnelState): Boolean = when (from) { diff --git a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt index 9ee8f0af..7dc05eb3 100644 --- a/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt +++ b/core/tunnel/src/jvmMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt @@ -135,14 +135,17 @@ class TunnelClientImpl( demux.activeStreamCount .drop(1) .collect { count -> - synchronized(stateMachine) { - when { - count > 0 && stateMachine.state.value == TunnelState.CONNECTED -> { - stateMachine.transition(TunnelState.ACTIVE) - } - count == 0 && stateMachine.state.value == TunnelState.ACTIVE -> { - stateMachine.transition(TunnelState.CONNECTED) - } + // transition() is internally synchronized (#269), so the + // read-check-call pattern here is safe: a racing + // disconnect() that invalidates the read will cause the + // transition() below to be rejected as invalid and + // logged, which is the correct outcome. + when { + count > 0 && stateMachine.state.value == TunnelState.CONNECTED -> { + stateMachine.transition(TunnelState.ACTIVE) + } + count == 0 && stateMachine.state.value == TunnelState.ACTIVE -> { + stateMachine.transition(TunnelState.CONNECTED) } } } diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt index 751c2d51..69285212 100644 --- a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt @@ -1,5 +1,8 @@ package com.rousecontext.tunnel +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -156,6 +159,103 @@ class ConnectionStateMachineTest { assertEquals(TunnelState.DISCONNECTED, sm.state.value) } + /** + * Regression test for #269: `transition()` must be internally atomic. + * + * Without internal synchronization, two threads racing to transition + * from the same "from" state to two different legal "to" states could + * both observe the same "from" value, both pass the matrix check, and + * both write — leaving the state machine in whichever state lost the + * publication race, without the "invalid transition" path being hit. + * + * Under the fix, exactly one `transition()` call returns `true`; the + * other sees the already-updated state and either rejects the + * transition (returns `false`) or accepts it as a valid follow-on + * transition. Either way, the final state is well-defined and the + * total number of "winners" matches the number of state writes. + * + * The test fires many rounds from a fresh CONNECTING state, with two + * racers trying CONNECTED vs DISCONNECTED. Both are legal from + * CONNECTING, but only one can be "first", and the second must see + * the result of the first (CONNECTED -> DISCONNECTED is valid; + * DISCONNECTED -> CONNECTED is NOT valid without going through + * CONNECTING first). So if both racers succeed in a round, the only + * legal end state is DISCONNECTED. If only one succeeds, the end + * state matches that racer's target. + */ + @Test + fun concurrentTransitionsAreAtomic() { + val rounds = 2000 + val corruptionDetected = AtomicInteger(0) + repeat(rounds) { + val sm = ConnectionStateMachine() + sm.transition(TunnelState.CONNECTING) + + val start = CountDownLatch(1) + val done = CountDownLatch(2) + val winnerToConnected = AtomicInteger(0) + val winnerToDisconnected = AtomicInteger(0) + + val t1 = Thread { + start.await() + if (sm.transition(TunnelState.CONNECTED)) { + winnerToConnected.incrementAndGet() + } + done.countDown() + } + val t2 = Thread { + start.await() + if (sm.transition(TunnelState.DISCONNECTED)) { + winnerToDisconnected.incrementAndGet() + } + done.countDown() + } + t1.start() + t2.start() + start.countDown() + assertTrue(done.await(5, TimeUnit.SECONDS), "threads did not complete in time") + + val finalState = sm.state.value + val cWins = winnerToConnected.get() + val dWins = winnerToDisconnected.get() + + when { + // Both threads think they won. + // CONNECTING -> CONNECTED is valid, and CONNECTED -> DISCONNECTED is valid, + // so if the CONNECTED writer ran first the DISCONNECTED writer sees CONNECTED + // and legally transitions to DISCONNECTED. + // If the DISCONNECTED writer ran first, the CONNECTED writer sees + // DISCONNECTED and MUST be rejected (DISCONNECTED -> CONNECTED is invalid). + // So "both won" can only happen in the first ordering, end state DISCONNECTED. + cWins == 1 && dWins == 1 -> { + if (finalState != TunnelState.DISCONNECTED) { + corruptionDetected.incrementAndGet() + } + } + cWins == 1 && dWins == 0 -> { + if (finalState != TunnelState.CONNECTED) { + corruptionDetected.incrementAndGet() + } + } + cWins == 0 && dWins == 1 -> { + if (finalState != TunnelState.DISCONNECTED) { + corruptionDetected.incrementAndGet() + } + } + else -> { + // Neither won: impossible if state machine is correct, since + // both transitions are valid from CONNECTING. + corruptionDetected.incrementAndGet() + } + } + } + assertEquals( + 0, + corruptionDetected.get(), + "state machine corruption detected in concurrent transitions" + ) + } + @Test fun invalidTransitionInvokesLogLambda() { val captured = mutableListOf>()