Modern Apps git

← Modern-Apps.git

developer: a slow branch's commits can no longer land in another branch's list

Commit
3ccbfef2ebc53377854fe856f0fdbaffa07afb8d
Author
Vayun Mathur <[email protected]>
When
2026-12-01 04:58 UTC (5 days ago)
Parents
3be8f97
loadCommits captured the browser (branch + cursor) and
applied its page to whatever state was current on completion,
with no request identity. Switch branches while a page was
slow and the late response for branch A was commitsLoaded/
commitsAppended into branch B's browser: the selector says B
while the commits are A's, CommitsScreen titles them
'Commits on B', and tapping one opens Commit(repo, B,
sha-from-A). The same race appended a stale load-more page
onto a new branch, and a superseded request's failure flagged
repoError on the repo the user had already left.

The ViewModel now captures requestedBranch plus a per-repo
generation: a success applies only if still the newest
request and still on the requested branch, and IOException
sets repoError under the same guard. RepoBrowser's reset
semantics are unchanged. Two gated-fake regression tests
reproduce the switch/load-more races deterministically (both
failed pre-fix). Pairing, push installs with SHA-256
verification, last-good staleness and cache keys were audited
and cleared. Verified: :madeveloper:testDevUnitTest 57 tests
pass; lint errors are pre-existing on untouched files.

Diff

madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktindex 4b189c7608..58cfc70dbc 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -107,6 +107,9 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {     private var transport: DevSocketTransport? = null     private var reconnectAttempt = 0 +    /** Newest commits-request generation per repo; see [loadCommits]. */+    private var commitsGenerations: Map<String, Int> = emptyMap()+     // Paired stays false until the socket actually connects: holding a token     // only proves registration, not that the owner approved this device.     var state by mutableStateOf(MaDevUiState(pairingCode = pairing.pairingCode() ?: ""))@@ -226,17 +229,34 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {         updateBrowser(RepoBrowser.navigateTo(current, path))     } -    /** Loads the first commits page, or appends the next when [loadMore]. */+    /**+     * Loads the first commits page, or appends the next when [loadMore].+     *+     * The page is fetched for the branch (and cursor) captured here; several+     * requests for one repo can be in flight at once (a branch switch starts+     * a fresh load while a slow earlier page — or a load-more — is still+     * out). Each request takes the next per-repo generation, and a result is+     * applied only while it is still the newest request for that repo and+     * the browser is still on the branch it was fetched for: a late page for+     * a previous branch must never land in the current branch's list, and a+     * superseded failure must not flag the repo the user has moved to.+     */     fun loadCommits(name: String, loadMore: Boolean) {         val browser = state.browsers[name] ?: return         if (loadMore && browser.commitsExhausted) return+        val requestedBranch = browser.branch+        val generation = (commitsGenerations[name] ?: 0) + 1+        commitsGenerations = commitsGenerations + (name to generation)         viewModelScope.launch {             try {                 val page = repo.commits(-                    name, browser.branch, GitHostRepository.COMMITS_PAGE_SIZE,+                    name, requestedBranch, GitHostRepository.COMMITS_PAGE_SIZE,                     if (loadMore) browser.nextCommitCursor else null,                 )                 val current = state.browsers[name] ?: return@launch+                if (commitsGenerations[name] != generation || current.branch != requestedBranch) {+                    return@launch+                }                 updateBrowser(                     if (loadMore) {                         RepoBrowser.commitsAppended(current, page, GitHostRepository.COMMITS_PAGE_SIZE)@@ -245,7 +265,11 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {                     },                 )             } catch (e: java.io.IOException) {-                state = state.copy(repoError = getApplication<Application>().friendlyError(e))+                if (commitsGenerations[name] == generation &&+                    state.browsers[name]?.branch == requestedBranch+                ) {+                    state = state.copy(repoError = getApplication<Application>().friendlyError(e))+                }             }         }     }
madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.ktindex 0b6b4ecc09..bc16d1b4be 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt@@ -68,6 +68,40 @@ class FakeGitHost {     } } +/**+ * Git-host fake whose commits pages are labelled by the `branch=` query value,+ * and whose page for one chosen request shape is held back until [gate] opens.+ * This makes an in-flight page arrive strictly after a later request settled:+ * the ordering a slow network gives branch switching in production.+ */+class BranchGatedGitHost(+    private val gatedBranch: String,+    private val gateLoadMore: Boolean,+) {+    val gate = kotlinx.coroutines.CompletableDeferred<Unit>()+    val requested = mutableListOf<String>()++    private fun commitsJson(branch: String, start: Int, count: Int): String =+        (start until start + count).joinToString(",", "[", "]") { i ->+            """{"sha":"$branch-sha-$i-${"x".repeat(24)}","author":"vayun","time":"2026-11-16T00:00:00Z","subject":"on $branch $i","body":""}"""+        }++    val fetcher: suspend (String) -> String = { url ->+        synchronized(requested) { requested += url }+        when {+            url.contains("/commits") -> {+                val branch = url.substringAfter("branch=").substringBefore("&")+                val loadMore = url.contains("after=")+                if (branch == gatedBranch && loadMore == gateLoadMore) gate.await()+                if (loadMore) commitsJson(branch, 30, 2) else commitsJson(branch, 0, 30)+            }+            url.endsWith("/api/repos/Modern-Apps") ->+                """{"name":"Modern-Apps","defaultBranch":"main","branches":[{"name":"main","sha":"11111111aaaa"},{"name":"dev","sha":"22222222bbbb"}],"recentCommits":[{"sha":"recent0001aaaa","author":"vayun","time":"2026-11-15T01:00:00Z","subject":"recent work","body":""}]}"""+            else -> throw IOException("unexpected url: $url")+        }+    }+}+ /** In-memory push socket: the test emits server messages and reads replies. */ class FakeTransport : DevSocketTransport {     val incoming = MutableSharedFlow<DevMessage>(extraBufferCapacity = 16)@@ -197,6 +231,60 @@ class MaDevViewModelTest {         viewModel.loadCommits("nope", loadMore = false)     } +    @Test fun branchSwitchDropsStaleFirstPageResponse() {+        // The dev page is held back; the user switches dev -> main before it lands.+        val gated = BranchGatedGitHost(gatedBranch = "dev", gateLoadMore = false)+        val viewModel = MaDevViewModel(app)+        viewModel.repo = GitHostRepository(gated.fetcher)+        viewModel.loadRepo("Modern-Apps")+        await("browser open") { viewModel.browser("Modern-Apps") != null }++        viewModel.selectBranch("Modern-Apps", "dev")+        viewModel.selectBranch("Modern-Apps", "main")+        await("main page loaded") {+            viewModel.browser("Modern-Apps")!!.commits.firstOrNull()?.subject == "on main 0"+        }+        gated.gate.complete(Unit)+        // Give the stale dev response every chance to land.+        Thread.sleep(750)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++        val browser = viewModel.browser("Modern-Apps")!!+        assertEquals("main", browser.branch)+        assertTrue(+            browser.commits.all { it.subject.startsWith("on main") },+            "commits of the previous branch leaked onto main: ${browser.commits.map { it.subject }}",+        )+    }++    @Test fun branchSwitchDropsStaleLoadMoreResponse() {+        // The main load-more page is held back; the user switches to dev before it lands.+        val gated = BranchGatedGitHost(gatedBranch = "main", gateLoadMore = true)+        val viewModel = MaDevViewModel(app)+        viewModel.repo = GitHostRepository(gated.fetcher)+        viewModel.loadRepo("Modern-Apps")+        await("browser open") { viewModel.browser("Modern-Apps") != null }+        viewModel.loadCommits("Modern-Apps", loadMore = false)+        await("first page") { viewModel.browser("Modern-Apps")!!.commits.size == 30 }++        viewModel.loadCommits("Modern-Apps", loadMore = true)+        viewModel.selectBranch("Modern-Apps", "dev")+        await("dev page loaded") {+            viewModel.browser("Modern-Apps")!!.commits.firstOrNull()?.subject == "on dev 0"+        }+        gated.gate.complete(Unit)+        Thread.sleep(750)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++        val browser = viewModel.browser("Modern-Apps")!!+        assertEquals("dev", browser.branch)+        assertEquals(30, browser.commits.size)+        assertTrue(+            browser.commits.all { it.subject.startsWith("on dev") },+            "stale main page was appended onto dev: ${browser.commits.map { it.subject }}",+        )+    }+     @Test fun repoLoadFailureSetsRepoError() {         host.failWith = IOException("HTTP 404 for repo")         val viewModel = vm()