Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
4637e03
chore(sdd): planning artifacts for scheduling-hygiene
tstapler Nov 26, 2026
618adf1
Merge remote-tracking branch 'origin/main' into backlog/stelekit-sche…
tstapler Nov 26, 2026
80da823
test(ui): hold the thumbnail lookup so the pending assertion cannot r…
tstapler Nov 26, 2026
72d96fc
fix(scheduling): remove runBlocking from sync scheduler and make sche…
tstapler Nov 26, 2026
b5dd14e
fix(scheduling): keep resumeFor non-cancellable so a cancelled caller…
tstapler Nov 26, 2026
cf7667b
test(scheduling): annotate or convert the remaining runBlocking calls…
tstapler Nov 26, 2026
7efce51
test(scheduling): cover the remaining test files from #642
tstapler Nov 26, 2026
2489974
Merge remote-tracking branch 'origin/main' into backlog/stelekit-sche…
tstapler Nov 26, 2026
b7b4c3e
test(scheduling): correct runBlocking reasons, convert more to runTes…
tstapler Nov 26, 2026
59bb6b4
[claudesquad] work complete for "Scheduling hygiene: runBlocking audi…
tstapler Nov 26, 2026
7edd9e5
fix(storage-move): clear move-in-progress flag when cancelled during …
tstapler Nov 26, 2026
b776b06
fix(scheduling): make the scheduler adapter's resume non-cancellable
tstapler Nov 26, 2026
32ffb0c
test(scheduling): runTest where nothing needs real time, guard produc…
tstapler Nov 26, 2026
32d6cfa
Merge remote-tracking branch 'origin/main' into backlog/stelekit-sche…
tstapler Nov 26, 2026
08bcaf0
test(scheduling): restore runTest conversions lost in the main merge,…
tstapler Nov 26, 2026
b419920
test(scheduling): widen the runBlocking guard's scope and cover link(…
tstapler Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
Expand All @@ -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() }

Expand All @@ -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()
Expand All @@ -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()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -298,6 +299,7 @@ import org.junit.runners.Suite
GateBeforeWorktreeOrderTest::class,
SyncInProgressUiConsumersTest::class,
GitSyncOneShotConflictAuditTest::class,
SchedulingNoRunBlockingAuditTest::class,
NoGateFallbackAuditTest::class,
GitGateAuditTest::class,
NewCodeAuditTest::class,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String, String>): List<String> = 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<Unit> { }",
"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))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<StorageMoveOperation>()
val releaseCalls = mutableListOf<StorageMoveOperation>()
Expand All @@ -36,6 +37,7 @@ class FakeGraphMoveQuiesceStrategy(

override suspend fun release(op: StorageMoveOperation) {
releaseCalls += op
onRelease()
}

override suspend fun releaseSourceGrant(source: StorageLocation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Unit>()
val finishRelease = CompletableDeferred<Unit>()
// 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()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<Unit>()
val finishRelease = CompletableDeferred<Unit>()
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()
}
}

Loading
Loading