games: play sessions reported already-completed count toward playtime
- Commit
d50bbb36e79089dc21560b36c849074ed9bb41b3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 14:05 UTC (4 days ago)
- Parents
c40ca9c
insertSession accepted end_time/duration_ms, but only markPlayed ran on insert; the sole addPlaytime caller (updateSession) early-returns when endTime is already set, so a session reported already-completed in one insert never counted toward per-game playtime โ detail Playtime stat, game cards and the MOST_PLAYED sort undercounted it (and the bulk insert also stored durationMs=null, so the two aggregates disagreed). Both insert paths now share insertSessionInternal: under the existing new-session guard (the landed dedupe, unchanged), a completed insert adds playtime (explicit duration, else derived end-start clamped >= 0) and the derived duration is stored on the row so both aggregates agree; ending via update still counts exactly once. Three regression tests (completed item insert counted once across a retry, bulk derives/stores duration, in-progress counts only at update-end) failed 2/3 pre-fix. Verified: :games:hub:testDevUnitTest and lint BUILD SUCCESSFUL.
Diff
games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubInsertHandlers.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubInsertHandlers.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubInsertHandlers.ktindex 55be453567..419aced493 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubInsertHandlers.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubInsertHandlers.kt@@ -6,6 +6,7 @@ import com.vayunmathur.games.hub.data.GamesHubRepository import com.vayunmathur.games.hub.data.entities.AchievementDefEntity import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.PlaySessionEntity internal suspend fun GamesHubProvider.insertGame( uri: Uri,@@ -130,13 +131,9 @@ internal suspend fun GamesHubProvider.insertSession( database: com.vayunmathur.games.hub.data.GamesHubDatabase, ): Uri? { val session = valuesToSession(v, uri)- ensureGameExists(session.gameId, repo) // Same dedup as the per-item insert: a retried session start must not // count one play twice in totalSessions (or rewind lastPlayedAt).- if (repo.sessions.getSessionById(session.sessionId) == null) {- database.gameDao().markPlayed(session.gameId, session.startTime)- }- repo.sessions.upsertSession(session)+ insertSessionInternal(session, repo, database) return uri } @@ -147,12 +144,41 @@ internal suspend fun GamesHubProvider.insertSessionItem( database: com.vayunmathur.games.hub.data.GamesHubDatabase, ): Uri? { val session = valuesToSession(v, uri)+ insertSessionInternal(session, repo, database)+ return uri+}++private suspend fun insertSessionInternal(+ session: PlaySessionEntity,+ repo: GamesHubRepository,+ database: com.vayunmathur.games.hub.data.GamesHubDatabase,+) { ensureGameExists(session.gameId, repo)+ // A session reported already-completed in one insert (endTime present)+ // never passes through updateSession โ which early-returns on an ended+ // session โ so its playtime must land on the per-game aggregate here,+ // under the same new-session guard as markPlayed, or hub_games+ // totalPlaytimeMs (GameDetail/GameCard playtime, MOST_PLAYED sort)+ // undercounts every such session while the session row itself exists.+ val completedDuration = session.completedDurationMs()+ val toStore = if (completedDuration != null && session.durationMs == null) {+ // Store the derived duration so SUM(durationMs) over sessions agrees+ // with the per-game aggregate.+ session.copy(durationMs = completedDuration)+ } else {+ session+ } if (repo.sessions.getSessionById(session.sessionId) == null) { database.gameDao().markPlayed(session.gameId, session.startTime)+ completedDuration?.let { database.gameDao().addPlaytime(session.gameId, it) } }- repo.sessions.upsertSession(session)- return uri+ repo.sessions.upsertSession(toStore)+}++/** Playtime of an already-ended session, or null while it is still running. */+private fun PlaySessionEntity.completedDurationMs(): Long? {+ val end = endTime ?: return null+ return (durationMs ?: (end - startTime)).coerceAtLeast(0L) } internal suspend fun GamesHubProvider.insertStreak(
games/hub/src/test/java/com/vayunmathur/games/hub/provider/HubCompletedSessionInsertTest.kt
diff --git a/games/hub/src/test/java/com/vayunmathur/games/hub/provider/HubCompletedSessionInsertTest.kt b/games/hub/src/test/java/com/vayunmathur/games/hub/provider/HubCompletedSessionInsertTest.ktnew file mode 100644index 0000000000..bebe3185ea--- /dev/null+++ b/games/hub/src/test/java/com/vayunmathur/games/hub/provider/HubCompletedSessionInsertTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.games.hub.provider++import android.app.Application+import android.content.ContentValues+import android.net.Uri+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.hub.data.GamesHubDatabase+import com.vayunmathur.games.hub.data.GamesHubRepository+import com.vayunmathur.library.util.databases+import com.vayunmathur.sdk.games.GameHubContract+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Regression: a session reported already-completed in a single insert+ * (end_time/duration_ms present) must count toward the per-game playtime+ * aggregate on hub_games, exactly as a session ended via update does.+ */+@RunWith(RobolectricTestRunner::class)+class HubCompletedSessionInsertTest {+ companion object { private var sharedDb: GamesHubDatabase? = null }+ private lateinit var repo: GamesHubRepository+ private lateinit var provider: GamesHubProvider++ @BeforeTest fun setUp() {+ val app = ApplicationProvider.getApplicationContext<Application>()+ val mem = sharedDb ?: Room.inMemoryDatabaseBuilder(app, GamesHubDatabase::class.java)+ .setSingleConnectionPool().allowMainThreadQueries().build().also { sharedDb = it }+ synchronized(databases) { databases[GamesHubDatabase::class] = mem }+ repo = GamesHubRepository.get(app)+ provider = GamesHubProvider()+ }++ private fun v(block: ContentValues.() -> Unit) = ContentValues().apply(block)+ private fun uri(path: String) = Uri.parse("content://${GameHubContract.AUTHORITY}/$path")++ @Test fun completedItemInsertCountsPerGamePlaytimeOnce() = runBlocking {+ val gameId = "completed-item-game"+ val sessionUri = uri("sessions/$gameId/done-1")+ val values = v {+ put(GameHubContract.Sessions.START_TIME, 1_000_000L)+ put(GameHubContract.Sessions.END_TIME, 1_060_000L)+ put(GameHubContract.Sessions.DURATION_MS, 60_000L)+ }+ with(provider) { insertSessionItem(sessionUri, values, repo, repo.database) }+ val game = repo.games.getGame(gameId)!!+ assertEquals(1, game.totalSessions)+ assertEquals(60_000L, game.totalPlaytimeMs)+ // A retried completed insert must not add the playtime (or session) twice.+ with(provider) { insertSessionItem(sessionUri, values, repo, repo.database) }+ val afterRetry = repo.games.getGame(gameId)!!+ assertEquals(1, afterRetry.totalSessions)+ assertEquals(60_000L, afterRetry.totalPlaytimeMs)+ }++ @Test fun completedBulkInsertDerivesDurationFromEndTime() = runBlocking {+ val gameId = "completed-bulk-game"+ with(provider) {+ insertSession(+ uri("sessions/$gameId"),+ v {+ put(GameHubContract.Sessions.SESSION_ID, "done-bulk-1")+ put(GameHubContract.Sessions.START_TIME, 2_000_000L)+ put(GameHubContract.Sessions.END_TIME, 2_060_000L)+ },+ repo,+ repo.database,+ )+ }+ assertEquals(60_000L, repo.games.getGame(gameId)?.totalPlaytimeMs)+ // The stored row carries the derived duration, so the sessions-side+ // aggregate (SUM(durationMs)) agrees with the per-game aggregate.+ val stored = repo.sessions.getSessionById("done-bulk-1")!!+ assertEquals(60_000L, stored.durationMs)+ assertEquals(+ 60_000L,+ repo.sessions.sessionsByGameFlow(gameId).first().sumOf { it.durationMs ?: 0L },+ )+ }++ @Test fun inProgressInsertStillCountsPlaytimeOnlyOnUpdateEnd() = runBlocking {+ val gameId = "inprogress-then-end-game"+ val sessionUri = uri("sessions/$gameId/live-1")+ with(provider) {+ insertSessionItem(+ sessionUri,+ v { put(GameHubContract.Sessions.START_TIME, 3_000_000L) },+ repo,+ repo.database,+ )+ }+ assertEquals(0L, repo.games.getGame(gameId)?.totalPlaytimeMs)+ with(provider) {+ updateSession(+ sessionUri,+ v { put(GameHubContract.Sessions.END_TIME, 3_060_000L) },+ repo,+ repo.database,+ )+ }+ assertEquals(60_000L, repo.games.getGame(gameId)?.totalPlaytimeMs)+ }+}