Fix the fold experience: honest actions, matched state, action identity

Reported as "folding looks broken". It was five separate defects.

1. Fold silently became Check. sanitise() rewrote FOLD to CHECK whenever
   checking was free, so a UI showing a Fold button folded nothing and the
   player kept being asked to act. Folding is legal at any turn — it simply
   mucks — so FOLD is now honoured literally. The engine must never substitute a
   different action than the caller asked for. The reverse rewrite (an illegal
   CHECK facing a bet becoming FOLD) is legitimate and stays.

   Safe by construction: no bot emits FOLD when it can check, and the 20k-hand
   simulation reproduces byte-identical numbers (289.12 / 113.19 / -195.64).

2. Snapshot and offer could describe different moments. The 32-deep frame
   channel let the engine race far ahead of the animation, so the action on
   offer could belong to a later street, or another hand. The channel is now
   RENDEZVOUS, capping the engine at one frame ahead, and UiState.liveOffer()
   only surfaces an offer whose hand and street match the table on screen.

3. Stale and double taps could act on a later decision. DecisionOffer now
   carries a token; submit() requires it and rejects anything stale, so a second
   tap is dropped rather than applied to whatever comes next.

4. A real fold was invisible. The hero kept normal cards and no folded state, so
   a correctly processed fold looked like a bug. Cards now dim, FOLDED shows in
   red, and the action bar explains the player is sitting out.

5. Non-atomic UiState updates from two coroutines now use update {}.

Also: Fold is hidden when checking is free (folding a free hand is never
correct, and offering it invites an accidental muck), and onCleared no longer
calls human.cancel() — viewModelScope is already cancelled by then so the launch
never ran; scope cancellation already propagates into act()'s finally.

The delivery tests were weak as charged: no slow consumer, and not the app's
capacity. Replaced with a genuinely slow consumer measuring how far the engine
runs ahead — asserting <= 1 on RENDEZVOUS, and > 1 on a 32-deep buffer to
document why the buffer was removed.

Verified on the emulator (physical device untouched): folded facing a bet, hero
showed FOLDED, was never asked again that hand, and play advanced to hand 2.

Tests: 55 -> 62, green on jvmTest and testAndroidHostTest.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jay
2026-07-25 21:04:44 -04:00
parent 950c7ceb57
commit 7382bc8638
9 changed files with 341 additions and 43 deletions
@@ -9,6 +9,14 @@ package com.jsjdesigns.poker.game
* is needed to render an action bar.
*/
data class DecisionOffer(
/**
* Identifies this specific decision.
*
* Submissions carry it back so a stale or double tap cannot be applied to a
* later decision — a second tap landing after the turn moved on would
* otherwise act on the next street, or even the next hand.
*/
val token: Long,
val handNumber: Int,
val street: Street,
val seat: Int,
@@ -26,7 +34,8 @@ data class DecisionOffer(
val callAmount: Int get() = toCall
}
fun DecisionContext.toOffer(): DecisionOffer = DecisionOffer(
fun DecisionContext.toOffer(token: Long): DecisionOffer = DecisionOffer(
token = token,
handNumber = handNumber,
street = street,
seat = seat.index,
@@ -23,6 +23,8 @@ class HumanAgent : PlayerAgent {
private val lock = Mutex()
private var pending: CompletableDeferred<Action>? = null
private var pendingToken = 0L
private var nextToken = 1L
private val _offer = MutableStateFlow<DecisionOffer?>(null)
@@ -33,13 +35,16 @@ class HumanAgent : PlayerAgent {
override suspend fun act(ctx: DecisionContext): Action {
val deferred = CompletableDeferred<Action>()
val token: Long
lock.withLock {
check(pending == null) { "already awaiting a decision for this agent" }
pending = deferred
token = nextToken++
pendingToken = token
}
// Published after the deferred is installed, so a UI that reacts instantly
// to the offer always finds something able to receive its submission.
_offer.value = ctx.toOffer()
_offer.value = ctx.toOffer(token)
return try {
deferred.await()
@@ -52,11 +57,16 @@ class HumanAgent : PlayerAgent {
}
/**
* Supplies the player's choice. Returns false when nothing was waiting, which
* makes a double-tap or a stale click harmless rather than a crash.
* Supplies the player's choice for the decision identified by [token].
*
* Returns false when nothing is waiting or when [token] is stale. Requiring
* the token is what stops a double tap, or a tap that lands just after the
* turn moved on, from being applied to the *next* decision — which could be a
* different street or an entirely different hand.
*/
suspend fun submit(action: Action): Boolean = lock.withLock {
suspend fun submit(token: Long, action: Action): Boolean = lock.withLock {
val deferred = pending ?: return@withLock false
if (token != pendingToken) return@withLock false
deferred.complete(action)
}
@@ -460,7 +460,11 @@ class Table(
/** Clamps whatever an agent returns into something legal. */
private fun sanitise(seat: Seat, toCall: Int, action: Action): Action {
return when (action.type) {
ActionType.FOLD -> if (toCall == 0) Action(ActionType.CHECK) else action
// Folding is legal at any turn, including when checking is free — it
// simply mucks. Rewriting it to CHECK was a lie to the caller: a UI
// showing a Fold button would fold, and the player would keep getting
// asked to act. Never silently substitute a different action.
ActionType.FOLD -> action
ActionType.CHECK -> if (toCall > 0) Action(ActionType.FOLD) else action
ActionType.CALL -> if (toCall == 0) Action(ActionType.CHECK) else action
ActionType.BET, ActionType.RAISE -> {
@@ -0,0 +1,165 @@
package com.jsjdesigns.poker.game
import com.jsjdesigns.poker.core.StackedDeck
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
private class AlwaysChecks : PlayerAgent {
override suspend fun act(ctx: DecisionContext): Action =
if (ctx.canCheck) Action(ActionType.CHECK) else Action(ActionType.CALL, ctx.toCall)
}
/** Folds the first time it acts, whatever the situation. */
private class FoldsOnce : PlayerAgent {
var timesAsked = 0
private set
private var folded = false
override suspend fun act(ctx: DecisionContext): Action {
timesAsked++
return if (!folded) {
folded = true
Action(ActionType.FOLD)
} else if (ctx.canCheck) Action(ActionType.CHECK) else Action(ActionType.CALL, ctx.toCall)
}
}
class FoldAndTokenTest {
private fun context(seat: Seat, canCheck: Boolean = false) = DecisionContext(
street = Street.FLOP,
seat = seat,
board = IntArray(0),
pot = 20,
toCall = if (canCheck) 0 else 10,
minRaiseTo = 20,
maxRaiseTo = 500,
activeOpponents = 1,
seatsActingAfter = 0,
bigBlind = 10,
history = emptyList(),
handNumber = 1,
bettingReopened = true,
)
// ---------- fold is honoured, never silently substituted ----------
/**
* The engine used to rewrite FOLD to CHECK whenever checking was free. A UI
* showing a Fold button would then fold, and the player would be asked to act
* again on the next street — which is exactly what it looked like: a bug.
*/
@Test
fun `folding when checking is free actually folds`() = runTest {
val folder = FoldsOnce()
val seats = listOf(Seat(0, "A", 500, folder), Seat(1, "B", 500, AlwaysChecks()))
val result = Table(
seats, 5, 10, Random(1),
StackedDeck.of(listOf("Ah Ad", "Kh Kd"), "2c 7d 9s Jc 3h"),
).playHand()
assertTrue(seats[0].folded, "a fold must fold, even when checking was free")
assertEquals(listOf(1), result.winners, "the other player takes it uncontested")
}
@Test
fun `a folded player is never asked to act again that hand`() = runTest {
val folder = FoldsOnce()
val seats = listOf(
Seat(0, "A", 500, folder),
Seat(1, "B", 500, AlwaysChecks()),
Seat(2, "C", 500, AlwaysChecks()),
)
Table(
seats, 5, 10, Random(1),
StackedDeck.of(listOf("Ah Ad", "Kh Kd", "Qh Qd"), "2c 7d 9s Jc 3h"),
).playHand()
assertTrue(seats[0].folded)
assertEquals(
1, folder.timesAsked,
"a player who folded must not be offered another decision this hand",
)
}
@Test
fun `checking into a bet is still downgraded to a fold`() = runTest {
// The reverse substitution is legitimate: CHECK is simply illegal there.
val seats = listOf(
Seat(0, "A", 500, PlayerAgent { Action(ActionType.RAISE, 100) }),
Seat(1, "B", 500, PlayerAgent { Action(ActionType.CHECK) }),
)
val result = Table(
seats, 5, 10, Random(1),
StackedDeck.of(listOf("Ah Ad", "Kh Kd"), "2c 7d 9s Jc 3h"),
).playHand()
assertTrue(seats[1].folded, "an illegal check becomes a fold")
assertEquals(0, result.net.sum())
}
// ---------- decision tokens ----------
@Test
fun `a stale token is rejected`() = runTest {
val human = HumanAgent()
val seat = Seat(0, "You", 500, human)
val first = async { human.act(context(seat)) }
while (!human.isAwaitingInput) yield()
val staleToken = human.offer.value!!.token
assertTrue(human.submit(staleToken, Action(ActionType.FOLD)))
first.await()
// A second decision arrives with a new token.
val second = async { human.act(context(seat)) }
while (!human.isAwaitingInput) yield()
val freshToken = human.offer.value!!.token
assertNotEquals(staleToken, freshToken, "each decision gets its own token")
assertFalse(
human.submit(staleToken, Action(ActionType.FOLD)),
"a tap left over from the previous decision must not be applied here",
)
assertTrue(human.submit(freshToken, Action(ActionType.CHECK)))
assertEquals(ActionType.CHECK, second.await().type)
}
@Test
fun `a double tap does not act twice`() = runTest {
val human = HumanAgent()
val seat = Seat(0, "You", 500, human)
val decision = async { human.act(context(seat)) }
while (!human.isAwaitingInput) yield()
val token = human.offer.value!!.token
assertTrue(human.submit(token, Action(ActionType.FOLD)), "first tap lands")
assertFalse(human.submit(token, Action(ActionType.CALL, 10)), "second tap is dropped")
assertEquals(ActionType.FOLD, decision.await().type)
}
@Test
fun `tokens keep advancing across decisions`() = runTest {
val human = HumanAgent()
val seat = Seat(0, "You", 500, human)
val seen = mutableListOf<Long>()
repeat(3) {
val d = async { human.act(context(seat)) }
while (!human.isAwaitingInput) yield()
val t = human.offer.value!!.token
seen += t
human.submit(t, Action(ActionType.CHECK))
d.await()
}
assertEquals(seen.distinct(), seen, "tokens must never repeat")
assertEquals(seen.sorted(), seen, "and should advance monotonically")
}
}
@@ -142,7 +142,7 @@ class SnapshotAndHumanAgentTest {
while (!human.isAwaitingInput) yield()
assertNotNull(human.offer.value, "the UI must be able to see what is on offer")
assertTrue(human.submit(Action(ActionType.CALL, 10)))
assertTrue(human.submit(human.offer.value!!.token, Action(ActionType.CALL, 10)))
assertEquals(ActionType.CALL, decision.await().type)
assertFalse(human.isAwaitingInput, "the wait must clear once answered")
@@ -151,7 +151,7 @@ class SnapshotAndHumanAgentTest {
@Test
fun `submitting when nothing is pending is harmless`() = runTest {
val human = HumanAgent()
assertFalse(human.submit(Action(ActionType.FOLD)), "a stale tap must not crash")
assertFalse(human.submit(1L, Action(ActionType.FOLD)), "a stale tap must not crash")
}
@Test
@@ -171,7 +171,7 @@ class SnapshotAndHumanAgentTest {
// The agent is reusable afterwards.
val next = async { human.act(context(seat)) }
while (!human.isAwaitingInput) yield()
assertTrue(human.submit(Action(ActionType.FOLD)))
assertTrue(human.submit(human.offer.value!!.token, Action(ActionType.FOLD)))
assertEquals(ActionType.FOLD, next.await().type)
}
@@ -189,7 +189,7 @@ class SnapshotAndHumanAgentTest {
val hand = async { table.playHand() }
// Fold at the first opportunity.
while (!human.isAwaitingInput) yield()
human.submit(Action(ActionType.FOLD))
human.submit(human.offer.value!!.token, Action(ActionType.FOLD))
val result = hand.await()
assertEquals(0, result.net.sum(), "chips conserved through a human-driven hand")
@@ -250,7 +250,7 @@ class HumanOfferAndStreetStateTest {
assertEquals(500, offer.stack, "offer must not alias live seat state")
assertEquals(listOf(0, 5), offer.hole)
human.submit(Action(ActionType.FOLD))
human.submit(human.offer.value!!.token, Action(ActionType.FOLD))
decision.await()
}
@@ -2,6 +2,7 @@ package com.jsjdesigns.poker.game
import com.jsjdesigns.poker.core.StackedDeck
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
@@ -81,24 +82,79 @@ class SnapshotDeliveryTest {
)
}
/**
* A genuinely slow consumer, on a RENDEZVOUS channel — what the app uses.
* The engine must never be more than one frame ahead of what has been shown.
*/
@Test
fun `backpressure lets a slow consumer keep up without dropping frames`() = runTest {
fun `a rendezvous channel keeps the engine within one frame of a slow consumer`() = runTest {
val received = mutableListOf<TableSnapshot>()
// Capacity 1 forces the engine to wait on nearly every emission.
val channel = Channel<TableSnapshot>(capacity = 1)
var sent = 0
var maxLead = 0
val channel = Channel<TableSnapshot>(capacity = Channel.RENDEZVOUS)
val consumer = launch {
for (frame in channel) received += frame
for (frame in channel) {
received += frame
delay(50) // pretend to animate
}
}
val seats = listOf(Seat(0, "A", 100, Shoves()), Seat(1, "B", 100, Shoves()))
table({ channel.send(it) }, seats).playHand()
table(
observer = {
sent++
channel.send(it)
maxLead = maxOf(maxLead, sent - received.size)
},
seats = seats,
).playHand()
channel.close()
consumer.join()
assertEquals(
listOf(0, 3, 4, 5), received.map { it.board.size }.distinct().sorted(),
"a suspending observer means the engine cannot outrun the UI",
"no frame may be dropped no matter how slow the consumer",
)
assertTrue(
maxLead <= 1,
"engine ran $maxLead frames ahead of the display; rendezvous should cap it at 1",
)
}
/**
* Why the buffer was removed: with depth, the engine races ahead and the
* action on offer can belong to a later moment than the table on screen.
*/
@Test
fun `a deep buffer lets the engine run far ahead of the display`() = runTest {
val received = mutableListOf<TableSnapshot>()
var sent = 0
var maxLead = 0
val channel = Channel<TableSnapshot>(capacity = 32)
val consumer = launch {
for (frame in channel) {
received += frame
delay(50)
}
}
val seats = listOf(Seat(0, "A", 100, Shoves()), Seat(1, "B", 100, Shoves()))
table(
observer = {
sent++
channel.send(it)
maxLead = maxOf(maxLead, sent - received.size)
},
seats = seats,
).playHand()
channel.close()
consumer.join()
assertTrue(
maxLead > 1,
"a 32-deep buffer should let the engine outrun the display, saw lead of $maxLead",
)
}
}