diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt index 1481442f4..ac0977e6f 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt @@ -45,9 +45,7 @@ import dev.stapler.stelekit.model.RepoRoot import dev.stapler.stelekit.platform.PlatformSettings import dev.stapler.stelekit.platform.SteleKitContext import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first -import kotlinx.coroutines.withContext /** * Legacy Android entry point for [BackgroundSyncScheduler], now a shim over [WorkManagerTaskScheduler] @@ -113,8 +111,7 @@ class WorkManagerSyncScheduler( * stays off. */ suspend fun resumeFor(context: Context, graphId: String) { - // NonCancellable: resume consumes the paused snapshot before it enqueues, so a cancel in between loses the job. - withContext(NonCancellable) { legacyAdapter(context).resume(TaskScope(graphId)) } + legacyAdapter(context).resume(TaskScope(graphId)) } /** The port adapter built from a [Context] and process statics alone (no UI state); also what a cold process can build. */ diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskScheduler.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskScheduler.kt index b3c54d986..735d58aa3 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskScheduler.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskScheduler.kt @@ -17,6 +17,7 @@ import dev.stapler.stelekit.coroutines.PlatformDispatcher import kotlinx.coroutines.CancellationException import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit @@ -106,7 +107,10 @@ class WorkManagerTaskScheduler( } } - override suspend fun resume(scope: TaskScope) = guarded("resume ${scope.value}") { + // NonCancellable: the paused snapshot is consumed before the enqueue, so a cancel in between loses the job. + override suspend fun resume(scope: TaskScope) = withContext(NonCancellable) { resumeScope(scope) } + + private suspend fun resumeScope(scope: TaskScope) = guarded("resume ${scope.value}") { val candidates = (pausedKeys.filter { it.scope == scope } + defaultKeys(scope)).toSet() for (key in candidates) { val snapshot = ledger.pausedSnapshot(key) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt index c4697a8ef..15c6df24e 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt @@ -284,7 +284,7 @@ class AndroidGraphMoveQuiesceStrategyTest { withTimeout(5_000) { while (!condition()) yield() } // real-clock hang guard: awaits real threads } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: the real-time withTimeout/polling guards would expire early on virtual time @Test fun quiesce_should_WaitForGateWithoutHoldingWorktreeLock_AndCompleteAfterSync() = runBlocking { val gate = RepoOpGate() @@ -329,7 +329,7 @@ class AndroidGraphMoveQuiesceStrategyTest { assertEquals(null, gate.releaseOrHandOff(checkNotNull(gate.tryAcquire(gateKey, SyncOrigin.UiPress))), "no follow-up fires after release") } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: the real-time withTimeout/polling guards would expire early on virtual time @Test fun quiesce_should_ReleaseLease_When_CancelledWhileWaitingForWorktreeMutex() = runBlocking { val gate = RepoOpGate() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt index c0db05789..1420b0931 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt @@ -66,7 +66,7 @@ class QuiesceRealFlushTest { deleteSourceAfterVerify = true, ) - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: the real-time withTimeout/polling guards would expire early on virtual time @Test fun quiesce_should_NotSelfDeadlock_When_RealGitShadowFlushActorFlushRunsInDrain() = runBlocking { val worktree = GitShadowWorktree(context, "quiesce-real-${System.nanoTime()}", safRoot) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderTest.kt index 33729876f..a3177009e 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderTest.kt @@ -52,10 +52,6 @@ class DepthModelDownloaderTest { private fun jobs() = WorkManager.getInstance(context).getWorkInfosForUniqueWork(DepthModelDownloader.UNIQUE_WORK_NAME).get() - private suspend fun DepthModelDownloader.awaitDownloading() { - modelState.first { it is DepthModelDownloader.ModelState.Downloading } - } - @Test fun `a ready model short-circuits without enqueueing`() = runTest { val file = DepthModelStorage.modelFile(context).also { it.parentFile!!.mkdirs() } @@ -69,7 +65,7 @@ class DepthModelDownloaderTest { fun `a second caller re-attaches to the queued job instead of enqueueing another`() = runTest { val downloader = DepthModelDownloader(context) val first = async { downloader.downloadModel() } - downloader.awaitDownloading() + downloader.awaitDownloadingState() val second = async { downloader.downloadModel() } repeat(SETTLE_YIELDS) { yield() } @@ -83,10 +79,10 @@ class DepthModelDownloaderTest { fun `a fresh instance after a restart sees the job that is still queued`() = runTest { val before = DepthModelDownloader(context) val waiting = async { before.downloadModel() } - before.awaitDownloading() + before.awaitDownloadingState() val afterRestart = DepthModelDownloader(context) - afterRestart.awaitDownloading() + afterRestart.awaitDownloadingState() assertTrue(jobs().single().state in setOf(WorkInfo.State.ENQUEUED, WorkInfo.State.BLOCKED, WorkInfo.State.RUNNING)) before.cancelDownload() @@ -97,7 +93,7 @@ class DepthModelDownloaderTest { fun `cancel resolves a waiting caller and surfaces Cancelled`() = runTest { val downloader = DepthModelDownloader(context) val waiting = async { downloader.downloadModel() } - downloader.awaitDownloading() + downloader.awaitDownloadingState() downloader.cancelDownload() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt index 6f6ef9cc6..dc3362465 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt @@ -93,7 +93,7 @@ class RepoGateSharedEntryPointTest { } } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: the real-time withTimeout/polling guards would expire early on virtual time @Test fun a_quiesce_hold_on_the_shared_gate_makes_the_cold_run_skip_as_busy() = runBlocking { val f = WiredAppFixture.android(context, dataDir).also { fixture = it } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/AllBusinessTests.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/AllBusinessTests.kt index f48bd6cdb..6df3cc52a 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/AllBusinessTests.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/AllBusinessTests.kt @@ -76,6 +76,7 @@ import dev.stapler.stelekit.asset.pipeline.CloudStructuralAuditTest import dev.stapler.stelekit.asset.pipeline.GrantedConsentMintSiteAuditTest import dev.stapler.stelekit.audit.EgressSurfaceAuditTest import dev.stapler.stelekit.audit.NonCancellableReturnAuditTest +import dev.stapler.stelekit.audit.SchedulingNoRunBlockingAuditTest import dev.stapler.stelekit.llm.AnthropicMessagesClientCharacterizationTest import dev.stapler.stelekit.asset.pipeline.AssetPluginsControllerTest import dev.stapler.stelekit.asset.pipeline.PluginRegistryTest @@ -298,6 +299,7 @@ import org.junit.runners.Suite GateBeforeWorktreeOrderTest::class, SyncInProgressUiConsumersTest::class, GitSyncOneShotConflictAuditTest::class, + SchedulingNoRunBlockingAuditTest::class, NoGateFallbackAuditTest::class, GitGateAuditTest::class, NewCodeAuditTest::class, diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt new file mode 100644 index 000000000..c2c3c1ced --- /dev/null +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt @@ -0,0 +1,47 @@ +// Copyright (c) 2026 Tyler Stapler +// SPDX-License-Identifier: Elastic-2.0 + +package dev.stapler.stelekit.audit + +import dev.stapler.stelekit.wiring.WiringAudit +import dev.stapler.stelekit.wiring.WiringInputs +import kotlin.test.Test +import kotlin.test.assertEquals + +/** Production scheduling and worker code must not hold a WorkManager or main thread with `runBlocking`. */ +class SchedulingNoRunBlockingAuditTest { + private val scoped = Regex( + """(androidMain|commonMain|jvmCommonMain)/.*/(jobs/schedule/.*""" + + """|git/(GitSync|GitCloneWorker|AndroidGitCloneWorkerLauncher|AndroidColdPathRunner|ColdSyncRunner|ScheduledSyncRunner""" + + """|PeriodicSyncDriver|WorkManagerSyncScheduler|BackgroundSyncScheduler)[^/]*""" + + """|platform/ml/(DepthModelDownload|ModelDownload)[^/]*|db/GraphMoveQuiesceStrategy[^/]*)""", + ) + + private val mustBeCovered = listOf( + "TaskWorker.kt", "ScheduleStartup.kt", "WorkManagerSyncScheduler.kt", "GitCloneWorker.kt", "GitSyncTask.kt", + "ColdSyncRunner.kt", "DepthModelDownloadWorker.kt", "ModelDownloadTask.kt", "GraphMoveQuiesceStrategy.android.kt", + ) + + private fun violations(sources: Map): List = sources + .filter { (path, text) -> scoped.matches(path) && "runBlocking" in WiringAudit.stripCommentsAndStrings(text) } + .keys.toList() + + @Test + fun plantedRunBlockingInAWorkerIsReported() { + val planted = mapOf( + "androidMain/x/jobs/schedule/Bad.kt" to "fun f() = runBlocking { }", + "androidMain/x/git/GitSyncWorker.kt" to "fun f() = runBlocking { }", + "androidMain/x/jobs/schedule/Ok.kt" to "// runBlocking is forbidden here", + "androidMain/x/db/DriverFactory.android.kt" to "fun f() = runBlocking { }", + ) + assertEquals(listOf("androidMain/x/jobs/schedule/Bad.kt", "androidMain/x/git/GitSyncWorker.kt"), violations(planted)) + } + + @Test + fun noProductionSchedulingSourceUsesRunBlocking() { + val sources = WiringInputs.productionSources + val covered = sources.keys.filter(scoped::matches).map { it.substringAfterLast('/') }.toSet() + assertEquals(emptyList(), mustBeCovered - covered, "scope misses these files, so the audit would pass vacuously") + assertEquals(emptyList(), violations(sources)) + } +} diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/FakeGraphMoveQuiesceStrategy.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/FakeGraphMoveQuiesceStrategy.kt index 585e651bc..b62b4fce3 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/FakeGraphMoveQuiesceStrategy.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/FakeGraphMoveQuiesceStrategy.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.awaitCancellation class FakeGraphMoveQuiesceStrategy( private val neverCompletes: Boolean = false, private val throwOnQuiesce: Throwable? = null, + private val onRelease: suspend () -> Unit = {}, ) : GraphMoveQuiesceStrategy { val quiesceCalls = mutableListOf() val releaseCalls = mutableListOf() @@ -36,6 +37,7 @@ class FakeGraphMoveQuiesceStrategy( override suspend fun release(op: StorageMoveOperation) { releaseCalls += op + onRelease() } override suspend fun releaseSourceGrant(source: StorageLocation) { diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorCancellationTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorCancellationTest.kt index ee9aedb93..453237729 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorCancellationTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorCancellationTest.kt @@ -124,4 +124,27 @@ class GraphRelocationCoordinatorCancellationTest : RelocationCoordinatorTestSupp // addGraph() left it: registered but never switched to. assertNull(graphManager.activeRepositorySet.value) } + + @Test + fun `relocate should ClearFlag When CancelledDuringRelease`() = runBlocking { + val graphManager = newGraphManager() + val graphId = graphManager.addGraph("/test/cancel-release-${System.nanoTime()}") + val enteredRelease = CompletableDeferred() + val finishRelease = CompletableDeferred() + // A failing quiesce takes the normal-exit release path; the cancel lands while release is suspended. + val quiesce = FakeGraphMoveQuiesceStrategy(throwOnQuiesce = IllegalStateException("boom")) { + enteredRelease.complete(Unit) + finishRelease.await() + } + val coordinator = GraphRelocationCoordinator(graphManager, FakeRelocationFileSystem(), quiesce) + + val collectJob = launch { coordinator.relocate(operationFor(graphId)).collect { } } + withTimeout(5_000) { enteredRelease.await() } + collectJob.cancel() + finishRelease.complete(Unit) + collectJob.join() + + assertFalse(MoveInProgressFlag.isMoveInProgress(graphId.value)) + graphManager.shutdown() + } } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorLinkTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorLinkTest.kt index d195bdc31..a00aada97 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorLinkTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinatorLinkTest.kt @@ -14,6 +14,10 @@ import dev.stapler.stelekit.error.DomainError import dev.stapler.stelekit.model.StorageLocation import dev.stapler.stelekit.model.StorageMoveOperation import kotlin.test.Test +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.launch +import kotlinx.coroutines.CompletableDeferred +import kotlin.test.assertFalse import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue @@ -275,4 +279,38 @@ class GraphRelocationCoordinatorLinkTest : RelocationCoordinatorTestSupport() { graphManager.shutdown() } + + @Test + fun `link should ClearFlag When CancelledDuringRelease`() = runBlocking { + val graphManager = newGraphManager() + graphManager.openGraph("/test/link-cancel-release-${System.nanoTime()}") + val graphId = graphManager.getActiveGraphId()!! + val enteredRelease = CompletableDeferred() + val finishRelease = CompletableDeferred() + val quiesce = FakeGraphMoveQuiesceStrategy(throwOnQuiesce = IllegalStateException("boom")) { + enteredRelease.complete(Unit) + finishRelease.await() + } + val coordinator = GraphRelocationCoordinator( + graphManager, + FakeRelocationFileSystem(), + quiesce, + hostLinkStep = FakeHostLinkStep(), + ) + val operation = StorageMoveOperation.Link( + graphId = graphId.value, + source = StorageLocation.AppOwned(graphId.value), + destination = StorageLocation.HostFolder(graphId.value, "Documents"), + ) + + val collectJob = launch { coordinator.link(operation).collect { } } + withTimeout(5_000) { enteredRelease.await() } // real-clock hang guard: awaits real threads + collectJob.cancel() + finishRelease.complete(Unit) + collectJob.join() + + assertFalse(MoveInProgressFlag.isMoveInProgress(graphId.value)) + graphManager.shutdown() + } } + diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt index 549ab6453..fcb38b2ed 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt @@ -28,6 +28,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import java.io.File import java.nio.file.Files @@ -115,7 +116,7 @@ class GitSyncCancelBoundaryTest { latch.await() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun cancelDuringFetch_should_NotMerge_AndCancelBeforeCommitShouldNotCommit() = runBlocking { val entered = CompletableDeferred() @@ -148,7 +149,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun cancelThenImmediateRepress_should_NotOverlap_When_BlockingCallStillRunning() = runBlocking { val entered = CompletableDeferred() @@ -174,7 +175,7 @@ class GitSyncCancelBoundaryTest { assertEquals(0, git.count("fetch"), "the pipeline stops before fetch after the cancel") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun commit_should_CompleteAndPipelineStopBeforeFetch_When_CancelRequestedDuringCommit() = runBlocking { val entered = CompletableDeferred() @@ -201,9 +202,8 @@ class GitSyncCancelBoundaryTest { rawContent = "<<<<<<< LOCAL\n- a\n=======\n- b\n>>>>>>> REMOTE\n", ) - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun mergeUnit_should_NotFallThroughToPush_When_ConflictOrCommitFailureExitsInsideNonCancellable() = runBlocking { + fun mergeUnit_should_NotFallThroughToPush_When_ConflictOrCommitFailureExitsInsideNonCancellable() = runTest { val conflicted = Repo(remoteChanges = true).apply { mergeResult = MergeResult(true, listOf(realConflict), emptyList(), 1) } @@ -222,9 +222,8 @@ class GitSyncCancelBoundaryTest { assertEquals(1, failing.count("abort")) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun mergeUnit_should_ReloadEveryChangedPathBeforeStopping_When_CancelArrivesRightAfterMerge() = runBlocking { + fun mergeUnit_should_ReloadEveryChangedPathBeforeStopping_When_CancelArrivesRightAfterMerge() = runTest { val reloaded = CopyOnWriteArrayList() val fs = object : StubFileSystem() { override fun invalidateShadow(path: String) { reloaded += path } @@ -257,9 +256,8 @@ class GitSyncCancelBoundaryTest { return reloaded to (GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()) to fs) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveConflicts_should_ReloadResolvedFiles_When_CancelArrivesRightAfterCommit() = runBlocking { + fun resolveConflicts_should_ReloadResolvedFiles_When_CancelArrivesRightAfterCommit() = runTest { val (reloaded, loaderAndFs) = reloadingFixture() val jobRef = AtomicReference() val git = Repo().apply { onCommit = { jobRef.get().cancel() } } @@ -278,9 +276,8 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun applyJournalMerge_should_ReloadTheFile_When_CancelArrivesRightAfterCommit() = runBlocking { + fun applyJournalMerge_should_ReloadTheFile_When_CancelArrivesRightAfterCommit() = runTest { val (reloaded, loaderAndFs) = reloadingFixture() val jobRef = AtomicReference() val git = Repo().apply { onCommit = { jobRef.get().cancel() } } @@ -295,7 +292,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun commitLocalChanges_should_FinishTheCommit_When_CancelRequestedDuringIt() = runBlocking { val entered = CompletableDeferred() @@ -313,9 +310,8 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun reloadMergedFiles_should_FlagReloadIncomplete_When_CancelledMidReload() = runBlocking { + fun reloadMergedFiles_should_FlagReloadIncomplete_When_CancelledMidReload() = runTest { val fs = object : StubFileSystem() { override fun invalidateShadow(path: String) { throw CancellationException("cancelled mid reload") } } @@ -329,7 +325,7 @@ class GitSyncCancelBoundaryTest { } // PR #683 round 2 (C1): only the caller's wait is bounded; the lease and record stay until the unit really ends. - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun resolveConflicts_should_KeepTheLease_UntilALateCommitFinishes_ThenReleaseAndClearTheFlag() = runBlocking { val late = CompletableDeferred() @@ -354,7 +350,7 @@ class GitSyncCancelBoundaryTest { assertFalse(svc.reloadIncomplete.value, "the sentinel clears when the abandoned unit ends") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun sync_should_KeepTheLeaseAndNotFlagReload_When_TheMainCommitOutlivesTheWait() = runBlocking { val late = CompletableDeferred() @@ -373,9 +369,8 @@ class GitSyncCancelBoundaryTest { } // PR #683 review m1: a later complete reload of other files must not clear an earlier incomplete one. - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun reloadIncomplete_should_StaySticky_UntilTheFailedPathsReloadCompletely() = runBlocking { + fun reloadIncomplete_should_StaySticky_UntilTheFailedPathsReloadCompletely() = runTest { val failing = java.util.concurrent.atomic.AtomicBoolean(true) val fs = object : StubFileSystem() { override fun invalidateShadow(path: String) { if (failing.get() && path == "/repo/a.md") throw CancellationException("reload interrupted") } @@ -416,7 +411,7 @@ class GitSyncCancelBoundaryTest { override fun observeConfig(graphId: String) = kotlinx.coroutines.flow.flowOf>(Either.Right(byGraph[graphId])) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun abandonedUnit_should_HoldOnlyItsOwnRunsLease_AndEndEverythingExactlyOnce() = runBlocking { val dirB = Files.createTempDirectory("cancel_boundary_b_").toFile() diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt index 731cb07cd..61cd32b54 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt @@ -16,7 +16,6 @@ import dev.stapler.stelekit.logging.LogManager import dev.stapler.stelekit.logging.LogSink import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicInteger import kotlin.test.AfterTest @@ -24,6 +23,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** Task 1.5b: the merge unit's reload is chunked, observable, and contains any non-cancellation failure. */ class GitSyncMergeUnitContainmentTest { @@ -61,9 +61,8 @@ class GitSyncMergeUnitContainmentTest { graphLoader = GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()), ) - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun reload_should_ChunkAtMost200AndSetReloadIncomplete_When_BeginGitMergeThrows() = runBlocking { + fun reload_should_ChunkAtMost200AndSetReloadIncomplete_When_BeginGitMergeThrows() = runTest { val seen = AtomicInteger() val fs = object : StubFileSystem() { // An Error is not an Exception, so reloadFiles' per-file guard lets it through, as a closed driver would. @@ -85,9 +84,8 @@ class GitSyncMergeUnitContainmentTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun reload_should_LogProgressPerChunkAndStayComplete_When_ThousandPathsReload() = runBlocking { + fun reload_should_LogProgressPerChunkAndStayComplete_When_ThousandPathsReload() = runTest { val svc = service(pages(1000), StubFileSystem()) svc.sync("g") diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt index 263941130..260faf0b4 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt @@ -17,11 +17,11 @@ import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue +import kotlinx.coroutines.runBlocking /** Task 2.4d: a manual `sync()` honors `GitConfig.autoCommit`; with it off, a dirty tree is fetched but never committed or merged. */ class GitSyncServiceAutoCommitTest { @@ -74,7 +74,7 @@ class GitSyncServiceAutoCommitTest { ) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: non-test helper that bridges a suspend call for its callers private fun GitSyncService.syncOnce(): Either = runBlocking { sync("test-graph") } @Test diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt index 86e91617a..cc26449d1 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt @@ -19,10 +19,10 @@ import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlinx.coroutines.test.runTest /** "Change back" must re-check the remote instead of trusting that the previous branch exists. */ class GitSyncServiceChangeBackTest { @@ -71,9 +71,8 @@ class GitSyncServiceChangeBackTest { return service to configRepo } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `change back is refused when the previous branch is still not on the remote`() = runBlocking { + fun `change back is refused when the previous branch is still not on the remote`() = runTest { val (service, configRepo) = repairedService(remoteBranches = listOf("master")) val result = service.changeBackBranch() @@ -83,9 +82,8 @@ class GitSyncServiceChangeBackTest { service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `change back succeeds once the previous branch exists on the remote`() = runBlocking { + fun `change back succeeds once the previous branch exists on the remote`() = runTest { val (service, configRepo) = repairedService(remoteBranches = listOf("master", "main")) val result = service.changeBackBranch() diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt index 079a25078..090b241b5 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt @@ -18,12 +18,12 @@ import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.platform.Settings import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** Repository-state, conflict-marker and mass-change guards on every commit and push path (dev plan Tasks 2.3e, 2.3f). */ class GitSyncServiceChangeGuardsTest { @@ -103,9 +103,8 @@ class GitSyncServiceChangeGuardsTest { private val mutating = setOf("stage", "commit", "merge", "push") - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `sync in MERGING state returns RepairNeeded before any stage commit merge or push`() = runBlocking { + fun `sync in MERGING state returns RepairNeeded before any stage commit merge or push`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING")) val svc = service(spy) @@ -117,9 +116,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a service built over an unsafe repository refuses even as a fresh instance`() = runBlocking { + fun `a service built over an unsafe repository refuses even as a fresh instance`() = runTest { val spy = Spy(health = RepositoryHealth(false, "UNMERGED_PATHS")) val first = service(spy).also { it.shutdown() } val fresh = service(spy) @@ -129,9 +127,8 @@ class GitSyncServiceChangeGuardsTest { fresh.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `staged conflict markers refuse the commit and nothing is committed or pushed`() = runBlocking { + fun `staged conflict markers refuse the commit and nothing is committed or pushed`() = runTest { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("journals/2026_10_08.md")))) val svc = service(spy) @@ -145,9 +142,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `an incomplete marker scan fails closed`() = runBlocking { + fun `an incomplete marker scan fails closed`() = runTest { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Incomplete("big.md is larger than 2048 KiB"))) val svc = service(spy) @@ -156,9 +152,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `markers in an existing local commit refuse the push even with a clean tree`() = runBlocking { + fun `markers in an existing local commit refuse the push even with a clean tree`() = runTest { val spy = Spy(dirty = false, markers = mutableMapOf(GuardScope.NetPush to MarkerScan.Found(listOf("a.md")))) val svc = service(spy) @@ -169,9 +164,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a clean scan lets sync commit and push`() = runBlocking { + fun `a clean scan lets sync commit and push`() = runTest { val spy = Spy() val svc = service(spy) @@ -180,9 +174,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `mass deletion above the default threshold blocks the commit`() = runBlocking { + fun `mass deletion above the default threshold blocks the commit`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(21, treeSize = 100))) val svc = service(spy) @@ -194,9 +187,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `mass deletion at the push step blocks the push`() = runBlocking { + fun `mass deletion at the push step blocks the push`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.NetPush to deletions(30, treeSize = 100))) val svc = service(spy) @@ -205,9 +197,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `deletions within the threshold pass`() = runBlocking { + fun `deletions within the threshold pass`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(20, treeSize = 100))) val svc = service(spy) @@ -229,9 +220,8 @@ class GitSyncServiceChangeGuardsTest { assertEquals(10, blocked?.threshold) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `overridden thresholds change the verdict in both directions`() = runBlocking { + fun `overridden thresholds change the verdict in both directions`() = runTest { val lowered = MapSettings().apply { putString(MassChangeThresholds.KEY_MIN_FILES, "3"); putString(MassChangeThresholds.KEY_PERCENT, "1") } val blockedSpy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(5, treeSize = 100))) val blockedSvc = service(blockedSpy, lowered) @@ -254,9 +244,8 @@ class GitSyncServiceChangeGuardsTest { assertEquals(MassChangeThresholds(), MassChangeThresholds.from(settings)) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a foreground confirm lifts the mass-change guard once and a scheduled run cannot`() = runBlocking { + fun `a foreground confirm lifts the mass-change guard once and a scheduled run cannot`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(40, treeSize = 100))) val svc = service(spy) @@ -270,9 +259,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `commitLocalChanges is guarded by state markers and mass change`() = runBlocking { + fun `commitLocalChanges is guarded by state markers and mass change`() = runTest { val unsafe = Spy(health = RepositoryHealth(false, "MERGING")) val unsafeSvc = service(unsafe) assertIs((unsafeSvc.commitLocalChanges("test-graph") as Either.Left).value) @@ -292,9 +280,8 @@ class GitSyncServiceChangeGuardsTest { massSvc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `resolveConflicts refuses to commit staged markers and still runs in MERGING`() = runBlocking { + fun `resolveConflicts refuses to commit staged markers and still runs in MERGING`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING"), markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("x.md")))) val svc = service(spy) @@ -305,9 +292,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `resolveConflicts commits in MERGING when the staged diff is clean`() = runBlocking { + fun `resolveConflicts commits in MERGING when the staged diff is clean`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING")) val svc = service(spy) @@ -316,9 +302,8 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `applyJournalMerge guards the commit and the push`() = runBlocking { + fun `applyJournalMerge guards the commit and the push`() = runTest { val commitBlocked = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("j.md")))) val commitSvc = service(commitBlocked) assertIs( diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt index 13cea9ef9..aab3b1c61 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt @@ -18,12 +18,12 @@ import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue import org.junit.Assume.assumeTrue +import kotlinx.coroutines.test.runTest /** A tree left half-merged must never be committed: that pushed `<<<<<<<` into the remote wiki. */ class GitSyncServiceConflictMarkerGuardTest { @@ -74,9 +74,8 @@ class GitSyncServiceConflictMarkerGuardTest { ) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `sync refuses to commit or push a file that still has conflict markers`() = runBlocking { + fun `sync refuses to commit or push a file that still has conflict markers`() = runTest { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) val calls = mutableListOf() val svc = service(markered, calls) @@ -89,9 +88,8 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `sync commits normally when the changed file has no conflict markers`() = runBlocking { + fun `sync commits normally when the changed file has no conflict markers`() = runTest { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) val calls = mutableListOf() val svc = service("- clean\n", calls) @@ -123,9 +121,8 @@ class GitSyncServiceConflictMarkerGuardTest { assertEquals(null, clean.findUnresolved(sampleConfig, status)) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `applyJournalMerge refuses merged content that still has conflict markers`() = runBlocking { + fun `applyJournalMerge refuses merged content that still has conflict markers`() = runTest { val calls = mutableListOf() val svc = service("", calls) @@ -136,9 +133,8 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `resolveConflicts refuses to commit when a resolved file still has conflict markers`() = runBlocking { + fun `resolveConflicts refuses to commit when a resolved file still has conflict markers`() = runTest { val calls = mutableListOf() val svc = service(markered, calls) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt index c1d2ea22d..571a78ce2 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt @@ -17,12 +17,12 @@ import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.platform.Settings import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** The "review first sync" gate: automatic triggers wait for consent, manual sync is the consent. */ class GitSyncServiceFirstSyncGateTest { @@ -71,9 +71,8 @@ class GitSyncServiceFirstSyncGateTest { return Fixture(service, firstSync, fetchCalls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `automatic sync is skipped while a first-sync review is pending and leaves state untouched`() = runBlocking { + fun `automatic sync is skipped while a first-sync review is pending and leaves state untouched`() = runTest { val f = fixture(reviewPending = true) val before = f.service.syncState.value @@ -86,9 +85,8 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `manual sync is not blocked by a pending review`() = runBlocking { + fun `manual sync is not blocked by a pending review`() = runTest { val f = fixture(reviewPending = true) val result = f.service.sync(graphId) @@ -98,9 +96,8 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `automatic sync resumes once the review is confirmed`() = runBlocking { + fun `automatic sync resumes once the review is confirmed`() = runTest { val f = fixture(reviewPending = true) f.firstSync.confirm(graphId, sampleConfig.remoteName, sampleConfig.remoteBranch) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt index d2869491f..9f49cff5d 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt @@ -30,12 +30,12 @@ import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.platform.Settings import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** * The LFS safety floor at the service level: on every staging entry point of [GitSyncService] a raw binary at a @@ -133,9 +133,8 @@ class GitSyncServiceLfsGuardTest { return Fixture(service, repo, fs, settings) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldRawBinaryAndCommitTheRest_When_AssetsAreLfsTracked() = runBlocking { + fun sync_should_HoldRawBinaryAndCommitTheRest_When_AssetsAreLfsTracked() = runTest { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf("pages/a.md" to "# a".encodeToByteArray(), photo to png)) val result = f.service.sync(graphId) @@ -150,9 +149,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldUntrackedRawBinaryToo_When_FileIsNew() = runBlocking { + fun sync_should_HoldUntrackedRawBinaryToo_When_FileIsNew() = runTest { val f = fixture(untracked = listOf(photo), modified = listOf("pages/a.md"), files = mapOf(photo to png)) f.service.sync(graphId) @@ -161,9 +159,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldNothing_When_TrackedFileIsAValidPointer() = runBlocking { + fun sync_should_HoldNothing_When_TrackedFileIsAValidPointer() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to pointer)) f.service.sync(graphId) @@ -174,9 +171,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldNothing_When_TrackedFileIsEmpty() = runBlocking { + fun sync_should_HoldNothing_When_TrackedFileIsEmpty() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to ByteArray(0))) f.service.sync(graphId) @@ -185,9 +181,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_SkipTheCommit_When_EverythingStagedWasHeld() = runBlocking { + fun sync_should_SkipTheCommit_When_EverythingStagedWasHeld() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) val result = f.service.sync(graphId) @@ -199,9 +194,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_NotConsultTheIndexForCommitNeed_When_NothingWasHeld() = runBlocking { + fun sync_should_NotConsultTheIndexForCommitNeed_When_NothingWasHeld() = runTest { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.anythingStaged = false }) f.service.sync(graphId) @@ -210,9 +204,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HonourNestedGitattributes_When_RuleLivesInASubdirectory() = runBlocking { + fun sync_should_HonourNestedGitattributes_When_RuleLivesInASubdirectory() = runTest { val f = fixture( modified = listOf("pages/img/x.png", "pages/y.png"), files = mapOf( @@ -229,9 +222,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_SeeAnUncommittedGitattributesEdit_When_TheWorkingTreeFileChanged() = runBlocking { + fun sync_should_SeeAnUncommittedGitattributesEdit_When_TheWorkingTreeFileChanged() = runTest { val f = fixture(modified = listOf(".gitattributes", "x.png"), files = mapOf("x.png" to png), gitattributes = "*.png filter=lfs\n") f.service.sync(graphId) @@ -240,9 +232,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_RefuseTheWholeCommit_When_HoldBackIsFlippedOff() = runBlocking { + fun sync_should_RefuseTheWholeCommit_When_HoldBackIsFlippedOff() = runTest { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { fs -> fs.files["/repo/.gitattributes"] = "assets/** filter=lfs\n".encodeToByteArray() fs.files["/repo/$photo"] = png @@ -259,9 +250,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_JudgeNothing_When_ThePlatformGuardsInItsOwnWritePath() = runBlocking { + fun sync_should_JudgeNothing_When_ThePlatformGuardsInItsOwnWritePath() = runTest { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { it.files["/repo/.gitattributes"] = "* filter=lfs\n".encodeToByteArray() }, delegated = true) val f = fixture(modified = listOf(photo), coordinator = coordinator, files = mapOf(photo to png)) @@ -271,9 +261,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_NotJudgeTheWorkingFile_When_AutoModeAndACleanFilterIsActive() = runBlocking { + fun sync_should_NotJudgeTheWorkingFile_When_AutoModeAndACleanFilterIsActive() = runTest { val f = fixture( modified = listOf("assets/b.bin"), files = mapOf("assets/b.bin" to ByteArray(3_000)), @@ -289,9 +278,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldAndUnstage_When_AutoModeFilterLeftRawBytesInTheIndex() = runBlocking { + fun sync_should_HoldAndUnstage_When_AutoModeFilterLeftRawBytesInTheIndex() = runTest { val escaped = LfsViolation("assets/b.bin", LfsViolationReason.RawBinary, ".gitattributes:1") val f = fixture( modified = listOf("assets/b.bin"), @@ -307,9 +295,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_HoldTheWorkingFile_When_ModeIsGuardOnlyEvenIfACleanFilterIsReported() = runBlocking { + fun sync_should_HoldTheWorkingFile_When_ModeIsGuardOnlyEvenIfACleanFilterIsReported() = runTest { val f = fixture( modified = listOf("assets/b.bin"), files = mapOf("assets/b.bin" to ByteArray(3_000)), @@ -324,9 +311,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_FailClosed_When_TheIndexCannotBeVerified() = runBlocking { + fun sync_should_FailClosed_When_TheIndexCannotBeVerified() = runTest { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.stagedThrows = true }) val result = f.service.sync(graphId) @@ -336,9 +322,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun commitLocalChanges_should_HoldRawBinaryAndStillCommit_When_AssetsAreLfsTracked() = runBlocking { + fun commitLocalChanges_should_HoldRawBinaryAndStillCommit_When_AssetsAreLfsTracked() = runTest { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf(photo to png)) val result = f.service.commitLocalChanges(graphId) @@ -349,9 +334,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun commitLocalChanges_should_ReturnNullWithoutCommitting_When_OnlyHeldFilesChanged() = runBlocking { + fun commitLocalChanges_should_ReturnNullWithoutCommitting_When_OnlyHeldFilesChanged() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) val result = f.service.commitLocalChanges(graphId) @@ -361,9 +345,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveConflicts_should_RefuseBeforeMarkResolved_When_SideResolutionLeavesRawBinary() = runBlocking { + fun resolveConflicts_should_RefuseBeforeMarkResolved_When_SideResolutionLeavesRawBinary() = runTest { val f = fixture(files = mapOf(photo to png)) val result = f.service.resolveConflicts( @@ -378,9 +361,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveConflicts_should_RefuseBeforeMarkResolved_When_HunkResolutionWritesRawText() = runBlocking { + fun resolveConflicts_should_RefuseBeforeMarkResolved_When_HunkResolutionWritesRawText() = runTest { val f = fixture(files = mapOf(photo to png)) val result = f.service.resolveConflicts( @@ -394,9 +376,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveConflicts_should_StageAValidPointer_When_ResolvedSideIsAPointer() = runBlocking { + fun resolveConflicts_should_StageAValidPointer_When_ResolvedSideIsAPointer() = runTest { val f = fixture(files = mapOf(photo to pointer)) val result = f.service.resolveConflicts( @@ -410,9 +391,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun applyJournalMerge_should_RefuseBeforeMarkResolved_When_MergedContentLandsAtATrackedPath() = runBlocking { + fun applyJournalMerge_should_RefuseBeforeMarkResolved_When_MergedContentLandsAtATrackedPath() = runTest { val f = fixture(gitattributes = "journals/** filter=lfs\n") val result = f.service.applyJournalMerge(graphId, "/repo/journals/2026_01_01.md", "- merged\n") @@ -423,9 +403,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_SurfaceRawBlobsThatWerePushedOutsideTheGuard_When_ThePushAuditFindsThem() = runBlocking { + fun sync_should_SurfaceRawBlobsThatWerePushedOutsideTheGuard_When_ThePushAuditFindsThem() = runTest { val pushed = LfsViolation("assets/sneaky.bin", LfsViolationReason.RawBinaryPushed, ".gitattributes:1") val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "# a".encodeToByteArray()), configure = { it.pushedViolations = listOf(pushed) }) @@ -436,9 +415,8 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun syncState_should_ReturnToSuccess_When_TheHeldFileIsFixedBeforeTheNextSync() = runBlocking { + fun syncState_should_ReturnToSuccess_When_TheHeldFileIsFixedBeforeTheNextSync() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png)) f.service.sync(graphId) assertIs(f.service.syncState.value) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt index dac7ba347..095eacf5c 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt @@ -19,9 +19,10 @@ import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest /** How a failed git step reaches [GitSyncService.syncState]: rate limit, expired credentials, or the plain error. */ class GitSyncServicePublishFailureTest { @@ -63,7 +64,7 @@ class GitSyncServicePublishFailureTest { ) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: non-test helper that bridges a suspend call for its callers private fun stateAfter(step: Step, error: DomainError.GitError, config: GitConfig = sampleConfig): SyncState = runBlocking { val svc = service(FailingAt(step, error), config) svc.sync("test-graph") @@ -104,9 +105,8 @@ class GitSyncServicePublishFailureTest { assertEquals(listOf("a.md"), (state as SyncState.ConflictPending).conflicts.map { it.filePath }) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `fetchOnly publishes rate limit and expiry the same way`() = runBlocking { + fun `fetchOnly publishes rate limit and expiry the same way`() = runTest { val limited = service(FailingAt(Step.Fetch, DomainError.GitError.RateLimited(3600))) limited.fetchOnly("test-graph") assertEquals(SyncState.RateLimited(3600), limited.syncState.value) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt index c0d1cb0c3..4bbae2e6c 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt @@ -97,7 +97,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `scheduleRateLimitRetry does not re-invoke fetchOnly before retryAfterSeconds elapses, then fires exactly once`() { requireOnline() - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it runBlocking { val counter = CallCounter() val repo = countingFetchRepo(counter) { count -> @@ -140,7 +140,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `shutdown cancels a pending scheduled retry before it fires`() { requireOnline() - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it runBlocking { val counter = CallCounter() val repo = countingFetchRepo(counter) { DomainError.GitError.RateLimited(retryAfterSeconds = 1).left() } @@ -162,7 +162,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `a manual fetchOnly call before the delay elapses cancels the pending scheduled retry - no double-fire`() { requireOnline() - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it runBlocking { val counter = CallCounter() // First call: rate limited (schedules a retry). Every subsequent call: success. @@ -196,7 +196,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `sync when commit returns RateLimited schedules a retry that re-invokes sync, reaching commit again`() { requireOnline() - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it runBlocking { var commitCallCount = 0 val repo = object : StubGitRepository() { diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt index 7407f97b7..11c67a156 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt @@ -23,11 +23,11 @@ import dev.stapler.stelekit.platform.security.CredentialAccess import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** [GitSyncService.runScheduledSync]: policy plus sync or fetch, against a call-recording fake repository. */ class GitSyncServiceScheduledSyncTest { @@ -144,9 +144,8 @@ class GitSyncServiceScheduledSyncTest { private fun policySkip(reason: ScheduledSkipReason) = TickOutcome.Skip(SkipReason.Policy(reason)) - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a held EditLock skips the tick with no repository call`() = runBlocking { + fun `a held EditLock skips the tick with no repository call`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.editLock.beginEdit() val svc = h.service() @@ -158,9 +157,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a busy counter, a locked vault and being offline each skip with no repository call`() = runBlocking { + fun `a busy counter, a locked vault and being offline each skip with no repository call`() = runTest { val busy = Harness().also { it.confirmFirstSync(); it.busy.begin() } val busySvc = busy.service() assertEquals(TickOutcome.Skip(SkipReason.Busy), busySvc.scheduled.run("test-graph")) @@ -180,9 +178,8 @@ class GitSyncServiceScheduledSyncTest { offlineSvc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `an in-memory conflict skips further ticks without touching the repository`() = runBlocking { + fun `an in-memory conflict skips further ticks without touching the repository`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.remoteChanges = true h.spy.mergeConflicts = listOf(ConflictFile("/repo/journals/a.md", "journals/a.md", emptyList(), rawContent = "x")) @@ -198,9 +195,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a fresh service over a MERGING repository skips with only a fetch`() = runBlocking { + fun `a fresh service over a MERGING repository skips with only a fetch`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.health = RepositoryHealth(false, "MERGING") val svc = h.service() @@ -213,9 +209,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a fetch error while skipping for repo state is reported as a failure`() = runBlocking { + fun `a fetch error while skipping for repo state is reported as a failure`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.health = RepositoryHealth(false, "MERGING") h.spy.fetchResult = DomainError.GitError.FetchFailed("boom").left() @@ -225,9 +220,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `an unconfirmed first sync fetches only and never merges commits or pushes`() = runBlocking { + fun `an unconfirmed first sync fetches only and never merges commits or pushes`() = runTest { val h = Harness() h.spy.dirty = true val svc = h.service() @@ -240,9 +234,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a confirmation stored by an earlier build is read unchanged and the next tick runs`() = runBlocking { + fun `a confirmation stored by an earlier build is read unchanged and the next tick runs`() = runTest { val h = Harness() h.settings.putString("git_first_sync_confirmed_test-graph", "origin/main") val svc = h.service() @@ -252,9 +245,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `changing the branch re-arms the first sync gate`() = runBlocking { + fun `changing the branch re-arms the first sync gate`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.config = h.config.copy(remoteBranch = "master") val svc = h.service() @@ -264,9 +256,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a pending first-sync review blocks even a matching confirmation`() = runBlocking { + fun `a pending first-sync review blocks even a matching confirmation`() = runTest { val h = Harness().also { it.confirmFirstSync() } FirstSyncConfirmation(h.settings).markReviewPending("test-graph", "main") val svc = h.service() @@ -275,9 +266,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a SAF graph, or one whose predicate throws, gets exactly one fetch`() = runBlocking { + fun `a SAF graph, or one whose predicate throws, gets exactly one fetch`() = runTest { for (predicate in listOf<(RepoRoot) -> Boolean>({ false }, { error("unresolvable saf uri") })) { val h = Harness(appOwned = predicate).also { it.confirmFirstSync() } h.spy.dirty = true @@ -293,9 +283,8 @@ class GitSyncServiceScheduledSyncTest { } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `the default path predicate treats saf and content uris as not app-owned`() = runBlocking { + fun `the default path predicate treats saf and content uris as not app-owned`() = runTest { for (root in listOf("saf://tree/notes", "content://com.android/tree/x")) { val h = Harness(config = sampleConfig.copy(repoRoot = RepoRoot(root))).also { it.confirmFirstSync() } val svc = GitSyncService( @@ -317,9 +306,8 @@ class GitSyncServiceScheduledSyncTest { } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `all clear runs sync once and merges the remote commits`() = runBlocking { + fun `all clear runs sync once and merges the remote commits`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.remoteChanges = true val svc = h.service() @@ -334,9 +322,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a merged sync records lastMerged and zero behind while a fetch-only tick records only the fetch`() = runBlocking { + fun `a merged sync records lastMerged and zero behind while a fetch-only tick records only the fetch`() = runTest { val h = Harness(appOwned = { false }).also { it.confirmFirstSync() } h.spy.remoteChanges = true val saf = h.service() @@ -360,9 +347,8 @@ class GitSyncServiceScheduledSyncTest { live.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `an app-closed marker left by the worker is cleared when the service starts`() = runBlocking { + fun `an app-closed marker left by the worker is cleared when the service starts`() = runTest { val h = Harness() SyncStalenessStore(h.settings).setFetchOnlyReason("test-graph", FetchOnlyReason.AppClosed) val svc = h.service() @@ -370,9 +356,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `the review badge covers every unconfirmed config, not only a pending repair`() = runBlocking { + fun `the review badge covers every unconfirmed config, not only a pending repair`() = runTest { val unconfirmed = Harness().service() unconfirmed.refreshLocalStatus("test-graph") assertTrue(unconfirmed.firstSyncReviewPending.value, "first run after upgrade has no confirmation") @@ -391,9 +376,8 @@ class GitSyncServiceScheduledSyncTest { rebranched.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `autoCommit off with a dirty tree fetches only and commits nothing`() = runBlocking { + fun `autoCommit off with a dirty tree fetches only and commits nothing`() = runTest { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } h.spy.dirty = true val svc = h.service() @@ -404,9 +388,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `autoCommit off with a clean tree still syncs`() = runBlocking { + fun `autoCommit off with a clean tree still syncs`() = runTest { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } val svc = h.service() @@ -415,9 +398,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a failed sync backs off the next ticks and the delay doubles`() = runBlocking { + fun `a failed sync backs off the next ticks and the delay doubles`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.pushResult = DomainError.GitError.PushFailed("rejected").left() val svc = h.service() @@ -442,9 +424,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a scheduled run can never lift the mass-change guard`() = runBlocking { + fun `a scheduled run can never lift the mass-change guard`() = runTest { val h = Harness().also { it.confirmFirstSync() } h.spy.dirty = true h.spy.deletions = DeletionSummary((1..40).map { "notes/$it.md" }, previousTreeSize = 100) @@ -458,9 +439,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a missing git config falls back to a harmless fetch tick`() = runBlocking { + fun `a missing git config falls back to a harmless fetch tick`() = runTest { val spy = Spy() val fs = StubFileSystem() val svc = GitSyncService( @@ -481,9 +461,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a vault provider that throws counts as available, like sync`() = runBlocking { + fun `a vault provider that throws counts as available, like sync`() = runTest { val h = Harness(vaultProvider = { error("keystore unavailable") }).also { it.confirmFirstSync() } val svc = h.service() @@ -492,9 +471,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `going offline between the policy check and the sync is a skip, not a failure`() = runBlocking { + fun `going offline between the policy check and the sync is a skip, not a failure`() = runTest { val answers = ArrayDeque(listOf(true, true)) val h = Harness(isOnline = { answers.removeFirstOrNull() ?: false }).also { it.confirmFirstSync() } val svc = h.service() @@ -504,9 +482,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun `a review that becomes pending between the policy check and the sync is a first-sync skip`() = runBlocking { + fun `a review that becomes pending between the policy check and the sync is a first-sync skip`() = runTest { val gate = object : MapSettings() { var pendingReads = 0 override fun getBoolean(key: String, defaultValue: Boolean): Boolean = diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt index a18cb5417..4954241b1 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt @@ -92,9 +92,8 @@ class GitSyncServiceSingleFlightTest { override suspend fun abortMerge(config: GitConfig) = Unit.right().also { calls += "abort" } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun everyMutatingEntryPoint_should_RunWithTheGateHeld_When_RepositoryAssertsIt() = runBlocking { + fun everyMutatingEntryPoint_should_RunWithTheGateHeld_When_RepositoryAssertsIt() = runTest { val git = GateAssertingGitRepository(OkRepository(), gate, keyFor = { c -> checkNotNull(RepoOpGate.keyForOrNull("${c.repoRoot.value}/.git") { File(it).canonicalFile.path }) }) val svc = service(git) suspend fun noGateViolation(name: String, call: suspend () -> Any?) { @@ -120,9 +119,8 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key()), "every entry point must release") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun gate_should_BeFreeAndSyncRunnable_When_BeginOwnedOperationThrows() = runBlocking { + fun gate_should_BeFreeAndSyncRunnable_When_BeginOwnedOperationThrows() = runTest { val git = OkRepository().apply { onBegin = { throw IllegalStateException("record write failed") } } val svc = service(git) @@ -134,9 +132,8 @@ class GitSyncServiceSingleFlightTest { assertTrue(svc.sync("g").isRight(), "a fresh sync must acquire and run") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun gate_should_BeFree_When_EndOwnedOperationThrowsAnything() = runBlocking { + fun gate_should_BeFree_When_EndOwnedOperationThrowsAnything() = runTest { for (failure in listOf<() -> Throwable>({ RuntimeException("boom") }, { CancellationException("cancelled") })) { val git = OkRepository().apply { onEnd = { throw failure() } } val svc = service(git) @@ -149,7 +146,7 @@ class GitSyncServiceSingleFlightTest { } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun gate_should_BeFreeAndSyncRunnable_When_RunIsCancelledMidCommit() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -170,7 +167,7 @@ class GitSyncServiceSingleFlightTest { assertTrue(withTimeout(20_000) { svc.sync("g") }.isRight()) // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun secondPress_should_LeaveInFlightAndStateUnchanged_When_FirstIsCommitting() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -206,7 +203,7 @@ class GitSyncServiceSingleFlightTest { git, StubConfigRepository(Either.Right(config)), SyncStalenessStore(MapSettings()), gate, { key() }, { 1L }, ) - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun servicePress_should_CoalesceAndNotInterruptTheFetch_When_AColdRunHoldsTheGate() = runBlocking { val cold = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } @@ -225,7 +222,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(listOf("fetch"), cold.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun coldRun_should_ReturnBusyWithoutWaiting_When_ALiveSyncHoldsTheGate() = runBlocking { val live = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } @@ -242,9 +239,8 @@ class GitSyncServiceSingleFlightTest { withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun claim_should_RefuseWithSyncInProgressAndRunNothing_When_OwnerAlive() = runBlocking { + fun claim_should_RefuseWithSyncInProgressAndRunNothing_When_OwnerAlive() = runTest { val git = OkRepository().apply { verdict = LockVerdict.OwnerAlive } val svc = service(git) @@ -257,9 +253,8 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun claim_should_PublishStaleLockFileWithVerdictAndDeleteNothing_When_OwnerUnknown() = runBlocking { + fun claim_should_PublishStaleLockFileWithVerdictAndDeleteNothing_When_OwnerUnknown() = runTest { val verdict = LockVerdict.OwnerUnknown(UnknownReason.RecoveryLockUnsupported) val git = OkRepository().apply { this.verdict = verdict } val svc = service(git) @@ -273,9 +268,8 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun record_should_BeEndedExactlyOncePerClaimedRun_AndNeverForACoalescedCall() = runBlocking { + fun record_should_BeEndedExactlyOncePerClaimedRun_AndNeverForACoalescedCall() = runTest { val git = OkRepository() val svc = service(git) @@ -302,7 +296,7 @@ class GitSyncServiceSingleFlightTest { return first } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun threeUiPresses_should_YieldExactlyOneFollowUp_AndScheduledIsDropped() = runBlocking { val git = OkRepository() @@ -321,7 +315,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun scheduledAlone_should_NotQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -336,7 +330,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, git.calls.count { it == "fetch" }) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun liftedPress_should_BeRefusedAndNeverQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -352,7 +346,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, git.calls.count { it == "fetch" }, "the lift flag must not ride a rerun") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun pressAgainstQuiesceHold_should_NeverSetTheRerunBit() = runBlocking { val git = OkRepository() @@ -393,7 +387,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, events.count { it == "end" }) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun inFlight_should_CarryFollowUpQueuedOnlyForAQueuedUiPress() = runBlocking { val git = OkRepository() @@ -456,7 +450,7 @@ class GitSyncServiceSingleFlightTest { gate = gate, ).also { services += it } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun confirmDialog_should_NotHoldGate_When_AwaitingUserConfirm() = runBlocking { val git = AbortRepository() @@ -476,9 +470,8 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun abort_should_RefuseAndResetNothing_When_FilesChangeWhileTheDialogIsOpen() = runBlocking { + fun abort_should_RefuseAndResetNothing_When_FilesChangeWhileTheDialogIsOpen() = runTest { val git = AbortRepository() val svc = abortService(git) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt index 7615b23a3..a3bbd99de 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt @@ -227,7 +227,7 @@ class PausedRetryNowAndDurabilityTest { private suspend fun until(check: () -> Boolean) = withTimeout(20_000) { while (!check()) delay(10) } // real-clock hang guard: awaits real threads - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun service_should_RetryTwiceAutomaticallyThenStayFailedWithTheLockError() = runBlocking { val repo = Repo() @@ -243,7 +243,7 @@ class PausedRetryNowAndDurabilityTest { assertIs(svc.syncState.value) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: until's withTimeout must run on the real clock while the retry fires on a real dispatcher @Test fun service_should_ClearPausedAndSync_When_TheOwnerBecomesKnownBeforeTheRetry() = runBlocking { val repo = Repo() @@ -254,7 +254,7 @@ class PausedRetryNowAndDurabilityTest { until { svc.pausedRetry.value == null && svc.syncState.value !is SyncState.Error } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun retryNow_should_RunExtraAttemptsWithoutMovingTheTryNumber() = runBlocking { val repo = Repo() @@ -272,9 +272,8 @@ class PausedRetryNowAndDurabilityTest { assertIs((svc.syncState.value as SyncState.Error).error) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun rebuiltService_should_HaveNoPausedStateAndClaimAgain() = runBlocking { + fun rebuiltService_should_HaveNoPausedStateAndClaimAgain() = runTest { val repo = Repo() val dead = service(repo, 60_000, 120_000) dead.sync("g") diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt index 501719827..55a5561e7 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import java.io.File import java.nio.file.Files @@ -79,9 +80,8 @@ class ResolveGateKeyFailureTest { private fun repoKey(): String = checkNotNull(RepoOpGate.keyForOrNull("${gitDir.absolutePath}/.git") { File(it).canonicalFile.path }) - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_ConfigReadThrowsTwice() = runBlocking { + fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_ConfigReadThrowsTwice() = runTest { val git = RecordingRepository { repoKey() } val configs = FlakyConfigRepository(config, failures = 2) { IllegalStateException("db exploded") } val gate = RepoOpGate() @@ -97,9 +97,8 @@ class ResolveGateKeyFailureTest { gate.releaseOrHandOff(holder) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_FailClosed_When_ConfigReadReturnsLeftTwice() = runBlocking { + fun resolveGateKey_should_FailClosed_When_ConfigReadReturnsLeftTwice() = runTest { val git = RecordingRepository { repoKey() } val configs = FlakyConfigRepository(config, failures = 2) { null } val svc = service(configs, git) @@ -112,9 +111,8 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_Resolve_When_OnlyTheFirstReadFails() = runBlocking { + fun resolveGateKey_should_Resolve_When_OnlyTheFirstReadFails() = runTest { val git = RecordingRepository { repoKey() } val configs = FlakyConfigRepository(config, failures = 1) { IllegalStateException("transient") } val svc = service(configs, git) @@ -123,9 +121,8 @@ class ResolveGateKeyFailureTest { assertTrue("fetch" in git.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_GitDirCannotBeCanonicalised() = runBlocking { + fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_GitDirCannotBeCanonicalised() = runTest { val git = RecordingRepository { null } val svc = service(StubConfigRepository(Either.Right(config)), git) @@ -135,9 +132,8 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_CanonicalisationThrows() = runBlocking { + fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_CanonicalisationThrows() = runTest { val git = RecordingRepository { throw java.io.IOException("canonicalisation failed") } val svc = service(StubConfigRepository(Either.Right(config)), git) @@ -145,7 +141,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun resolveGateKey_should_Coalesce_When_ServiceIsRunningAndConfigBecomesUnreadable() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -166,9 +162,8 @@ class ResolveGateKeyFailureTest { svc.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun resolveGateKey_should_RethrowCancellation_When_ConfigReadIsCancelled() = runBlocking { + fun resolveGateKey_should_RethrowCancellation_When_ConfigReadIsCancelled() = runTest { val git = RecordingRepository { repoKey() } val configs = FlakyConfigRepository(config, failures = 1) { CancellationException("cancelled") } val svc = service(configs, git) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt index 1485194e3..2b46c9a33 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt @@ -15,7 +15,6 @@ import dev.stapler.stelekit.logging.LogEntry import dev.stapler.stelekit.logging.LogManager import dev.stapler.stelekit.logging.LogSink import dev.stapler.stelekit.model.RepoRoot -import kotlinx.coroutines.runBlocking import java.io.File import java.nio.file.Files import java.util.concurrent.CopyOnWriteArrayList @@ -24,6 +23,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** Story 1.8 AC "Log lines present": every sync decision and every lock verdict reaches the Logs sink as one line. */ class SyncObservabilityLogTest { @@ -67,9 +67,8 @@ class SyncObservabilityLogTest { private fun logged(fragment: String) = lines.any { fragment in it } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun everyLockVerdict_should_LogOneLockVerdictLine() = runBlocking { + fun everyLockVerdict_should_LogOneLockVerdictLine() = runTest { val verdicts = listOf( LockVerdict.NoLock, LockVerdict.ClearedOwn, LockVerdict.ClearedDeadOwner, LockVerdict.OwnerAlive, LockVerdict.OwnerUnknown(UnknownReason.TornRecord), LockVerdict.NoRecord, @@ -83,24 +82,21 @@ class SyncObservabilityLogTest { } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun startedDecision_should_BeLogged_When_TheClaimSucceeds() = runBlocking { + fun startedDecision_should_BeLogged_When_TheClaimSucceeds() = runTest { service(ScriptedRepository(LockVerdict.NoLock)).sync("g") assertTrue(logged("sync origin=UiPress decision=started"), "$lines") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun skippedDecision_should_BeLogged_When_TheOwnerIsUnknown() = runBlocking { + fun skippedDecision_should_BeLogged_When_TheOwnerIsUnknown() = runTest { val result = service(ScriptedRepository(LockVerdict.OwnerUnknown(UnknownReason.TornRecord))).sync("g") assertIs>(result) assertTrue(logged("sync origin=UiPress decision=skipped reason=StaleLockFile"), "$lines") } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun coalescedDecision_should_BeLogged_When_AnotherRunHoldsTheGate() = runBlocking { + fun coalescedDecision_should_BeLogged_When_AnotherRunHoldsTheGate() = runTest { val repo = ScriptedRepository(LockVerdict.NoLock) val svc = service(repo) val key = checkNotNull(repo.gateKeyFor(config)) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt index 187e73fad..f9ba1049e 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt @@ -10,7 +10,6 @@ import dev.stapler.stelekit.git.model.SyncState import dev.stapler.stelekit.git.testsupport.StubConfigRepository import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.model.RepoRoot -import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking @@ -64,15 +63,14 @@ class SyncSingleFlightRegressionTest { r.leftOrNull() is DomainError.GitError.SyncInProgress private fun startFirstSync(): Deferred> = - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive - runBlocking { CoroutineScopeHolder.scope.async(start = CoroutineStart.DEFAULT) { service.sync("g", SyncTrigger.Manual) } } + CoroutineScopeHolder.scope.async { service.sync("g", SyncTrigger.Manual) } private fun recordStates(): () -> List { val collector = CoroutineScopeHolder.scope.async { service.syncState.collect { states += it } } return { collector.cancel(); states.toList() } } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun secondManualSync_should_ReturnSyncInProgress_AndCreateNoLock_When_FirstBlockedInCommit() = runBlocking { repo.blockAt(FakeGitOp.Commit) @@ -92,7 +90,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun liveLockOlderThan60s_should_NotBeDeleted_When_HeldByInFlightRun() = runBlocking { repo.blockAt(FakeGitOp.Commit) @@ -107,7 +105,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstIsMergingAndRepositoryMidMerge() = runBlocking { repo.hasRemoteChanges = true @@ -125,7 +123,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstFetchingAndOfflineAndVaultLocked() = runBlocking { repo.blockAt(FakeGitOp.Fetch) diff --git a/kmp/src/commonMain/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinator.kt b/kmp/src/commonMain/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinator.kt index faab7ee6c..5374107ce 100644 --- a/kmp/src/commonMain/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinator.kt +++ b/kmp/src/commonMain/kotlin/dev/stapler/stelekit/db/GraphRelocationCoordinator.kt @@ -236,8 +236,11 @@ class GraphRelocationCoordinator( suspend fun releaseOnce() { if (released) return released = true - quiesceStrategy.release(operation) - MoveInProgressFlag.setMoveInProgress(graphIdValue, false) + // NonCancellable: a cancel here would skip the flag clear, and `released` stops finally from retrying. + withContext(NonCancellable) { + quiesceStrategy.release(operation) + MoveInProgressFlag.setMoveInProgress(graphIdValue, false) + } } logMoveStarted(operation) @@ -387,8 +390,11 @@ class GraphRelocationCoordinator( suspend fun releaseOnce() { if (released) return released = true - quiesceStrategy.release(operation) - MoveInProgressFlag.setMoveInProgress(graphIdValue, false) + // NonCancellable: a cancel here would skip the flag clear, and `released` stops finally from retrying. + withContext(NonCancellable) { + quiesceStrategy.release(operation) + MoveInProgressFlag.setMoveInProgress(graphIdValue, false) + } } MoveInProgressFlag.setMoveInProgress(graphIdValue, true) diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt index 88f6b735b..c206a6211 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt @@ -22,7 +22,6 @@ import dev.stapler.stelekit.git.testsupport.StubFileSystem import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.revwalk.RevWalk @@ -37,6 +36,7 @@ import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest /** * End to end on the JVM sync path: real [GitSyncService] + real [JvmGitRepository] + a real bare origin. @@ -129,9 +129,8 @@ class GitSyncServiceLfsJvmTest { private fun remoteCommitCount(): Int = Git.open(origin).use { git -> git.log().call().count() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_PushTextNotesAndNeverTheRawBinary_When_AssetsAreLfsTracked() = runBlocking { + fun sync_should_PushTextNotesAndNeverTheRawBinary_When_AssetsAreLfsTracked() = runTest { File(work, "pages").mkdirs() File(work, "assets").mkdirs() File(work, "pages/a.md").writeText("- a note\n") @@ -156,9 +155,8 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_NotCreateEmptyCommits_When_OnlyAHeldFileIsPending() = runBlocking { + fun sync_should_NotCreateEmptyCommits_When_OnlyAHeldFileIsPending() = runTest { File(work, "assets").mkdirs() File(work, "assets/photo.png").writeBytes(png) val service = service() @@ -172,9 +170,8 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test - fun sync_should_PushTheFileAsAPointer_OnceTheRawFileIsReplaced() = runBlocking { + fun sync_should_PushTheFileAsAPointer_OnceTheRawFileIsReplaced() = runTest { File(work, "assets").mkdirs() File(work, "assets/photo.png").writeBytes(png) val service = service() diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt index 99b525147..cc8d2652f 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt @@ -28,6 +28,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs @@ -91,9 +92,8 @@ class StelekitViewModelSyncStateTest { assertEquals(SyncState.LocalChangesPending(3), observed) } - // runBlocking: StelekitViewModel runs on its own real-dispatcher scope that virtual time cannot drive @Test - fun `TC-4_3_2-A syncState stays Idle when count is zero`() = runBlocking { + fun `TC-4_3_2-A syncState stays Idle when count is zero`() = runTest { val countFlow = MutableStateFlow(0) val vm = makeViewModel( activeGitSyncService = MutableStateFlow(null),