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) <noreply@anthropic.com>
This commit is contained in:
Jason Monk 2026-04-19 16:55:11 -04:00 • committed by GitHub
parent 250fe1ff60
commit 75d79bc4f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 118 additions and 12 deletions

View file

@ -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) {

View file

@ -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)
}
}
}

View file

@ -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<Pair<LogLevel, String>>()