From 4637e034f737551baafcc87200ebf5975f21ae7f Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 09:35:13 -0800 Subject: [PATCH 01/13] chore(sdd): planning artifacts for scheduling-hygiene --- project_plans/scheduling-hygiene/plan.md | 153 ++++++++++++++++++ .../scheduling-hygiene/requirements.md | 74 +++++++++ project_plans/scheduling-hygiene/research.md | 104 ++++++++++++ project_plans/scheduling-hygiene/validate.md | 90 +++++++++++ 4 files changed, 421 insertions(+) create mode 100644 project_plans/scheduling-hygiene/plan.md create mode 100644 project_plans/scheduling-hygiene/requirements.md create mode 100644 project_plans/scheduling-hygiene/research.md create mode 100644 project_plans/scheduling-hygiene/validate.md diff --git a/project_plans/scheduling-hygiene/plan.md b/project_plans/scheduling-hygiene/plan.md new file mode 100644 index 000000000..2097a80aa --- /dev/null +++ b/project_plans/scheduling-hygiene/plan.md @@ -0,0 +1,153 @@ +# Implementation Plan: Scheduling Hygiene + +**Date:** 2026-11-26 +**Depends on:** research.md findings + +## Summary + +Production scheduling code has no `runBlocking` — that half of the audit is complete and needs +only a brief confirmation comment in the PR. The work is entirely in the test layer: + +- Migrate Category A `runBlocking` tests to `runTest`. +- Replace the 30-second `withTimeout` in `OneShotSkipTest` with a deterministic signal. +- Justify and annotate the remaining real-clock waits that cannot be removed. + +## Tasks + +### Task 1 — Confirm and document production-code audit result (0.5 h, test) + +Add a one-line comment in `TaskWorker.kt` and `ScheduleStartup.kt` confirming the absence of +`runBlocking`. + +Alternatively, add a `ProductionSchedulingNoBlockingTest` (businessTest or androidUnitTest) +that greps the source files to assert no `runBlocking` call appears in the production +scheduling package. A source-text guard in a `@Test` enforces this permanently. + +**Acceptance check:** AC-1 satisfied. + +### Task 2 — Migrate ScheduleStartupTest to runTest (1 h, test) + +Replace all 11 `= runBlocking {` bodies with `= runTest {`. Verify no `CountDownLatch` or +blocking thread-synchronization is present. Add `kotlinx-coroutines-test` import where needed. + +**Acceptance check:** AC-2a for ScheduleStartupTest. + +### Task 3 — Migrate TaskWorkerTest to runTest (1 h, test) + +Replace the helper `private fun run(...): Result = runBlocking {` with +`private suspend fun run(...): Result` and call it from `runTest` bodies. Migrate all ~20 test +methods from `runBlocking` to `runTest`. + +**Acceptance check:** AC-2a for TaskWorkerTest. + +### Task 4 — Migrate WorkManagerTaskScheduler constraint/pause tests to runTest (1 h, test) + +`WorkManagerTaskSchedulerConstraintsTest.kt` (13 occurrences) and +`WorkManagerTaskSchedulerPauseResumeTest.kt` (14 occurrences) have no real-thread sync — they +use `SynchronousExecutor`-backed WorkManager which runs everything on the test thread. Replace +`runBlocking` with `runTest` throughout. + +**Acceptance check:** AC-2a for both files. + +### Task 5 — Migrate ScheduledTaskReconcilerTest and LegacyWorkUpgradeTest (0.5 h, test) + +Both files have simple `runBlocking` test bodies (4 and 3 occurrences respectively). Replace +with `runTest`. + +**Acceptance check:** AC-2a for both files. + +### Task 6 — Fix OneShotSkipTest: replace 30-second timeout with deterministic signal (2 h, test) + +**Root cause:** `assertDownloadResolvesFailed` awaits `f.downloader.downloadModel()` with a +30-second real-clock guard. The fix has two parts: + +1. **Expose a deterministic terminal signal from `DepthModelDownloader`.** The `modelState` + `StateFlow` already carries `ModelState.Failed` / `ModelState.Downloaded`. Change + `assertDownloadResolvesFailed` to use: + ```kotlin + val outcome = scope.async { f.downloader.downloadModel() } + // ... trigger WorkManager ... + f.downloader.modelState.first { it is ModelState.Failed || it is ModelState.Downloaded } + assertEquals(DepthModelDownloader.ModelState.Failed(expectedReason), f.downloader.modelState.value) + ``` + This eliminates the timeout entirely; resolution is event-driven. + +2. **Or, if the async/await shape must be kept**, replace `withTimeout(30_000)` with + `withTimeout(5_000)` and add a comment explaining the ceiling exists only for CI + safety, not normal execution. This is the minimum fix if the full refactor is deferred. + +Preferred: approach 1. The `workerRun` helper in the same file should also be migrated from +`runBlocking` to `suspend fun` (called via `runTest`). + +**Acceptance check:** AC-3. + +### Task 7 — Annotate justified real-clock waits (0.5 h, test) + +Add `// runBlocking: real-thread concurrency test — CountDownLatch blocks; runTest cannot reproduce thread interleaving` above the `runBlocking` in `WorkManagerTaskSchedulerConcurrencyTest.kt`. + +Add a similar comment above `withTimeoutOrNull(1_500)` in the same file: `// bounded negative assertion: checks second did NOT complete before first's lock was released`. + +For `AndroidGitCloneWorkerLauncherTest.kt`'s `Thread.sleep(25)` loop: add +`// polling loop in fake worker body — real sleep, bounded to 200×25ms = 5s`. + +For `GitSyncWorkerGateAndRecordTest.kt`'s `withTimeout(10_000)`: annotate with the reason (WorkManager state machine; synchronous executor should make this resolve in <1 s, timeout is a CI safety ceiling). + +**Acceptance check:** AC-2b and AC-4. + +### Task 8 — Verify test-hygiene-baseline.txt does not grow (0.5 h, test) + +After all changes, run `./gradlew testDebugUnitTest` and confirm: +- `TestHygieneAuditTest` passes. +- `test-hygiene-baseline.txt` has no new entries. +- If any addressed items were previously in the baseline (unlikely, since these are test-only patterns), remove them. + +**Acceptance check:** AC-5. + +### Task 9 — Full test run verification (0.5 h, test) + +Run `./gradlew testDebugUnitTest` (or `bazel test //kmp/modules:...` for affected modules) and +confirm no regressions. + +**Acceptance check:** AC-6. + +## Risk Assessment + +| Risk | Likelihood | Impact | Mitigation | +|------|-----------|--------|------------| +| `runTest` changes virtual-time semantics and breaks a timing-sensitive test | Medium | Low | Run tests after each migration task; revert to `runBlocking` + justify if a test fails | +| `OneShotSkipTest` refactor exposes a real bug in `DepthModelDownloader` state machine | Low | Medium | Add the 5-second fallback timeout as a safety ceiling; investigate if hit | +| `WorkManagerTaskSchedulerConcurrencyTest` concurrency test becomes flaky after `runBlocking → runTest` (it should stay as `runBlocking`) | Low | Low | Category B — this test is explicitly excluded from migration | + +## Adversarial Review Notes + +**Q: Is the `runBlocking` in Robolectric tests truly harmful?** +A: Not to the test process's correctness — Robolectric tests run on a single test thread, +so `runBlocking` there is not an ANR risk. The issue is determinism and speed: `runBlocking` +in a test does not let `kotlinx-coroutines-test` control time, so any `delay()` or +`withTimeout()` inside runs on the real clock. Migrating to `runTest` enables virtual time for +free and removes the dependency on wall-clock speed. + +**Q: Can `runTest` be used with `SynchronousExecutor`-backed WorkManager?** +A: Yes — `WorkManagerTestInitHelper` with `SynchronousExecutor` runs workers on the calling +thread synchronously. Inside `runTest`, calling `doWork()` is equivalent to calling any +suspending function. No additional wiring needed. + +**Q: What if `DepthModelDownloader.modelState` doesn't expose a signal early enough?** +A: `modelState` is a `StateFlow` that is updated before `downloadModel()` resolves, by design +(the caller reads state separately from the return value). The `first { ... }` collector will +see the terminal state as soon as the worker emits it. + +## Estimated Cost + +| Task | Category | Estimate | +|------|----------|----------| +| 1 — Confirm production audit | test | 0.5 h | +| 2 — ScheduleStartupTest → runTest | test | 1 h | +| 3 — TaskWorkerTest → runTest | test | 1 h | +| 4 — Constraints + PauseResume → runTest | test | 1 h | +| 5 — Reconciler + Legacy → runTest | test | 0.5 h | +| 6 — OneShotSkipTest deterministic signal | test | 2 h | +| 7 — Annotate justified waits | test | 0.5 h | +| 8 — Hygiene baseline check | test | 0.5 h | +| 9 — Full test run | test | 0.5 h | +| **Total** | | **~7.5 h** | diff --git a/project_plans/scheduling-hygiene/requirements.md b/project_plans/scheduling-hygiene/requirements.md new file mode 100644 index 000000000..932d1de5c --- /dev/null +++ b/project_plans/scheduling-hygiene/requirements.md @@ -0,0 +1,74 @@ +# Scheduling Hygiene: runBlocking Audit and Real-Clock Test Polling + +**Item:** b9823895-f00e-4172-9672-931c0796ad53 +**Follow-up from:** #642 (merged as 9656e5e3f6) +**Date:** 2026-11-26 + +## Background + +PR #642 introduced the background task scheduling subsystem (`jobs/schedule/`). Two hygiene +items were deferred from that review: + +1. **`runBlocking` audit** — confirm that scheduling workers and `ScheduleStartup` do not call + `runBlocking` on a main thread or WorkManager worker thread, blocking the platform from + making forward progress. +2. **Real-clock test polling** — test cases that sit on `withTimeout(30_000)` or similar + real-wall-clock waits inflate CI time and are fragile under load. The named example is + `OneShotSkipTest`, which uses a 30-second `withTimeout` guard. + +## Problem Statement + +### runBlocking audit + +`runBlocking` on a WorkManager worker thread is a correctness issue: WorkManager caps the +thread pool and will starve other work if a `runBlocking` call holds a thread while suspended. +On the main thread it causes an ANR. The audit must confirm that no production path in the +scheduling subsystem (`jobs/schedule/`, `ScheduleStartup`, `TaskWorker`, `GitSyncWorker`, +`DepthModelDownloadWorker`) contains a `runBlocking` that could block a constrained thread. +Test uses of `runBlocking` must also be classified: justified (real-thread concurrency tests) +or should-be-`runTest` (ordinary coroutine tests that happen to use `runBlocking`). + +### Real-clock test polling + +`withTimeout(30_000)` in a Robolectric test adds up to 30 real seconds to CI if the condition +is never met. Even when it succeeds quickly, the existence of a 30s timeout makes the test +appear to hang until the deferred resolves, which is nondeterministic under CI load. The same +pattern appears in `GitSyncWorkerGateAndRecordTest` (10 s) and +`WorkManagerTaskSchedulerConcurrencyTest` (1.5 s). + +## Scope + +### In scope +- All files under `kmp/src/*/kotlin/**/jobs/schedule/` +- `ScheduleStartup.kt` and its test `ScheduleStartupTest.kt` +- `TaskWorker.kt` and `TaskWorkerTest.kt` +- Worker bindings: `GitSyncWorkerBinding`, `DepthModelDownloadWorker`, + `GitCloneWorker`, `AndroidGitCloneWorkerLauncher` +- `OneShotSkipTest.kt` (platform/ml, but exercises the scheduling path) +- `GitSyncWorkerGateAndRecordTest.kt`, `WorkManagerTaskSchedulerConcurrencyTest.kt` + +### Out of scope +- Non-scheduling coroutine uses of `runBlocking` elsewhere in the codebase +- Robolectric test configuration or WorkManager test harness rewrites + +## Acceptance Criteria + +1. No `runBlocking` exists in any production scheduling/worker source file + (`androidMain/jobs/schedule/`, `androidMain/git/GitSyncWorker*`, + `androidMain/platform/ml/DepthModelDownloadWorker*`). +2. Every `runBlocking` in scheduling and worker **test** files is either: + (a) replaced with `runTest` where the body is a simple coroutine with no real-thread + synchronization, or + (b) annotated with an inline comment explaining why real-thread blocking is required + (e.g., `CountDownLatch`-based concurrency checks). +3. `OneShotSkipTest.assertDownloadResolvesFailed` replaces `withTimeout(30_000)` with a + deterministic signal — either a `CompletableDeferred`-backed gate on the downloader or a + `runTest`-compatible virtual-time advance — such that the test does not wait more than a + few virtual milliseconds. +4. Any remaining real-clock waits > 2 s in scheduling tests are documented with an inline + comment explaining why virtual time or a deterministic handshake cannot be used, plus a + `test-hygiene-baseline.txt` entry if the case is temporarily accepted rather than fixed. +5. The `test-hygiene-baseline.txt` file does not grow as a result of this change (all + addressed items are removed or never added). +6. `bazel test //kmp:business_tests` (or `./gradlew testDebugUnitTest`) passes with no new + failures after all changes. diff --git a/project_plans/scheduling-hygiene/research.md b/project_plans/scheduling-hygiene/research.md new file mode 100644 index 000000000..d68856715 --- /dev/null +++ b/project_plans/scheduling-hygiene/research.md @@ -0,0 +1,104 @@ +# Research: Scheduling Hygiene Audit + +**Date:** 2026-11-26 +**Codebase ref:** worktree triage-b9823895 (post-#642 merge, 9656e5e3f6) + +## 1. runBlocking in Production Scheduling Code + +**Finding: CLEAN — no `runBlocking` in production scheduling source.** + +| File | Result | +|------|--------| +| `androidMain/jobs/schedule/ScheduleStartup.kt` | No `runBlocking`. `run()` is `suspend fun`. | +| `androidMain/jobs/schedule/TaskWorker.kt` | No `runBlocking`. `doWork()` is `suspend fun` (CoroutineWorker). | +| `androidMain/jobs/schedule/TaskWorkRunner.kt` | No `runBlocking` found. | +| `androidMain/git/GitSyncWorkerBinding.kt` | No `runBlocking`. | +| `androidMain/platform/ml/DepthModelDownloadWorker.kt` | No `runBlocking` found. | +| `androidMain/git/GitCloneWorker.kt` | No `runBlocking` found. | +| `androidMain/git/AndroidGitCloneWorkerLauncher.kt` | No `runBlocking` found. | + +The production scheduling code is correct: `TaskWorker` extends `CoroutineWorker` whose `doWork()` is already a suspend function, so there is no need to bridge to coroutines with `runBlocking`. + +## 2. runBlocking in Test Code (Classification) + +### Category A: Should be `runTest` (ordinary coroutine tests) + +These files use `= runBlocking {` as a test body bridge where there is no real-thread +synchronization. The standard replacement is `runTest { }` from `kotlinx-coroutines-test`, +which uses a `StandardTestDispatcher` and virtual time by default. + +| File | Occurrences | Notes | +|------|-------------|-------| +| `ScheduleStartupTest.kt` | 11 | All test methods; no CountDownLatch or real-thread sync | +| `TaskWorkerTest.kt` | ~20 | Most test methods; helper `run()` also uses `runBlocking` | +| `ScheduledTaskReconcilerTest.kt` | 4 | Simple coroutine tests | +| `LegacyWorkUpgradeTest.kt` | 3 | Simple coroutine tests | +| `WorkManagerTaskSchedulerConstraintsTest.kt` | 13 | Constraint-setting tests with no cross-thread deps | +| `WorkManagerTaskSchedulerPauseResumeTest.kt` | 14 | Pause/resume state machine tests | +| `OneShotSkipTest.kt` | 2 | `workerRun` helper + `assertDownloadResolvesFailed` | + +### Category B: Justified `runBlocking` (real-thread concurrency tests) + +These tests deliberately use real threads and thread-synchronization primitives. Using +`runTest` here would not reproduce the race condition being tested. + +| File | Occurrences | Justification | +|------|-------------|---------------| +| `WorkManagerTaskSchedulerConcurrencyTest.kt` | 1 | Uses `ParkingSettings` (a `CountDownLatch`-backed Settings mock) + two `Dispatchers.Default` async coroutines to verify that the check-then-act sequence is atomic. Virtual time cannot reproduce thread interleaving. | +| `GitSyncWorkerGateAndRecordTest.kt` | Several helpers | Helper `run()` calls `doWork()` via TestListenableWorkerBuilder. Some test methods need a real executor for WorkManager state transitions. | +| `GitSyncWorkerStaleGateTest.kt` | Several | Real-thread WorkManager helpers. | +| `AndroidGitCloneWorkerLauncherTest.kt` | 5 | Launches real coroutines on `Dispatchers.Default`; fake worker polls with `Thread.sleep(25)`. | + +**Note on `WorkManagerTaskSchedulerConcurrencyTest`:** The `withTimeoutOrNull(1_500)` at line 84 +is a *bounded negative wait* — it checks that `second` did NOT complete before `first` was +released. Replacing it requires either a signal from the scheduling code that the critical +section was entered (not currently exposed) or a redesigned probe. This should be commented as +justified rather than removed, unless a better deterministic signal can be injected. + +## 3. Real-Clock Waits (Full Inventory) + +| File | Line | Timeout | Type | Verdict | +|------|------|---------|------|---------| +| `OneShotSkipTest.kt` | 103 | 30 000 ms | `withTimeout` | **Fix** — replace with deterministic downloader signal | +| `GitSyncWorkerGateAndRecordTest.kt` | 316 | 10 000 ms | `withTimeout` | **Fix if possible** — waits for WorkManager state; use `SynchronousExecutor` + explicit trigger instead | +| `WorkManagerTaskSchedulerConcurrencyTest.kt` | 84 | 1 500 ms | `withTimeoutOrNull` | **Comment + justify** — bounded negative assertion for concurrency correctness; cannot easily remove | +| `AndroidGitCloneWorkerLauncherTest.kt` | 188 | Polling | `Thread.sleep(25)` × 200 | **Comment + justify** — fake worker stopping loop; bounded to 5 s max | +| `JvmGitCloneWorkerLauncherTest.kt` | 98, 101 | 5 000 ms ×2 | `withTimeout` | **Fix if possible** — replace with `CompletableDeferred` signals from fake launcher | + +## 4. OneShotSkipTest Root Cause + +The 30-second timeout guard in `assertDownloadResolvesFailed` is protecting an `async { f.downloader.downloadModel() }` call. The `downloadModel()` suspend function is waiting for an internal state channel to emit a terminal state (`Failed` or `Downloaded`). The sequence is: + +1. Enqueue a one-shot WorkManager request. +2. `awaitDownloadingState()` — waits for the downloader's state to reach `Downloading`. +3. `setAllConstraintsMet(id)` — signals WorkManager's test driver to run the worker. +4. `withTimeout(30_000) { result.await() }` — waits for the coroutine to resolve. + +The 30s timeout is a defensive ceiling, not a real wait — in a healthy run this resolves in +< 100 ms because `SynchronousExecutor` runs WorkManager on the test thread. The risk is that +under CI load, the `downloadModel()` state machine never reaches `Failed` (the deferred hangs), +and the test hangs for 30 real seconds before the timeout fires and the test fails. + +**Fix approach:** `DepthModelDownloader.modelState` is already a `StateFlow`. Instead of a +raw `withTimeout`, use `modelState.first { it is ModelState.Failed }` or expose a +`CompletableDeferred` that is completed when the terminal state arrives. Combined +with `runTest`, this gives deterministic resolution without any wall-clock timeout. + +## 5. Relationship to TestHygieneAuditTest + +`TestHygieneAuditTest` forbids new `Thread.sleep`, `GlobalScope`, uncancelled +`Dispatchers.IO` scopes, and real-clock `delay` in production. It also tracks offenders in +`test-hygiene-baseline.txt`. + +The `withTimeout` / `withTimeoutOrNull` calls in test code are not currently flagged by this +audit (it only checks production code patterns). The item's spirit — deterministic tests — +is nonetheless aligned with that gate's intent. + +## 6. Test Infrastructure Already In Place + +- `InProcessTaskSchedulerContractTest.kt` uses `TestScope` + `advanceTimeBy` — confirming + virtual-time testing is already adopted for the in-process scheduler. This is the right + pattern to replicate in the Android scheduler tests. +- `WorkManagerTestInitHelper` with `SynchronousExecutor` is already the harness for + WorkManager tests — it runs worker `doWork()` synchronously on the test thread, which + makes most real-clock waits unnecessary. diff --git a/project_plans/scheduling-hygiene/validate.md b/project_plans/scheduling-hygiene/validate.md new file mode 100644 index 000000000..de4c90114 --- /dev/null +++ b/project_plans/scheduling-hygiene/validate.md @@ -0,0 +1,90 @@ +# Validation: Scheduling Hygiene Plan + +**Date:** 2026-11-26 + +## Validation Checks + +### AC-1: Production code has no runBlocking + +VERIFIED by search: +- `ScheduleStartup.run()` is `suspend fun` — no `runBlocking`. +- `TaskWorker.doWork()` is a suspend function (`CoroutineWorker`) — no `runBlocking`. +- `GitSyncWorkerBinding`, `DepthModelDownloadWorker`, `GitCloneWorker`, + `AndroidGitCloneWorkerLauncher` — no `runBlocking` found in any production file. + +The plan correctly identifies this as already clean and proposes a lightweight enforcement +gate (source-text check test) to prevent regression. + +### AC-2: runBlocking classification is sound + +The Category A / Category B split is based on direct inspection of each file: + +- **Category A** files (`ScheduleStartupTest`, `TaskWorkerTest`, constraints/pause-resume tests, + `OneShotSkipTest`) have no `CountDownLatch`, `Semaphore`, or thread-creation calls. Their + `runBlocking` bodies are plain coroutine functions — `runTest` is a direct drop-in. +- **Category B** files (`WorkManagerTaskSchedulerConcurrencyTest`) explicitly construct + `ParkingSettings` with a `CountDownLatch(1)` that blocks the coroutine's underlying thread. + Running this inside `runTest` would deadlock: `runTest` uses `StandardTestDispatcher` which + runs coroutines in-order on the test thread; `CountDownLatch.await()` on that same thread + would never be released because the coroutine that calls `release.countDown()` is queued + behind the blocked one. + +Classification is correct. + +### AC-3: OneShotSkipTest fix is feasible + +`DepthModelDownloader.modelState: StateFlow` is confirmed to exist. The terminal +states `ModelState.Failed` and `ModelState.Downloaded` are distinct sealed variants. The +`downloadModel()` function drives the state machine; `modelState` will reach a terminal state +before the coroutine returns. Collecting `modelState.first { terminal }` is a valid +deterministic replacement for the 30-second timeout. + +One risk: if `downloadModel()` and `modelState` share a single `MutableStateFlow`, there is a +potential ordering issue where `downloadModel()` returns before the collector sees the update. +Mitigation: collect `modelState` before launching the `async` block, or confirm that +`awaitDownloadingState()` and `setAllConstraintsMet()` both flush their state synchronously +before the `result.await()` call. This should be verified during implementation. + +### AC-4: Remaining justified waits are bounded + +| Wait | Bound | Verdict | +|------|-------|---------| +| `withTimeoutOrNull(1_500)` in concurrency test | 1.5 s | Acceptable for a mutex-correctness test | +| `withTimeout(10_000)` in git worker test | 10 s | Acceptable; `SynchronousExecutor` makes this resolve in <1 s normally | +| `Thread.sleep(25)` × 200 in clone launcher test | 5 s | Acceptable; bounded polling loop in fake body | +| `withTimeout(5_000)` × 2 in JVM git tests | 5 s each | Acceptable; `CompletableDeferred` signals | + +All are bounded, not unbounded waits. The 10-second and 30-second (post-fix) timeouts become +annotation candidates if the fix is not feasible, not baseline additions. + +### AC-5 and AC-6: No baseline growth, tests pass + +The plan proposes migrating tests that currently have no baseline entry — they were not +previously flagged. Post-migration, `TestHygieneAuditTest` should pass unchanged (the audit +does not scan for `withTimeout` in test code). Full test run verification is the final task. + +## Open Questions / Risks + +1. **OrderDependent: does `downloadModel()` observe its own state transition?** If the state + machine for `DepthModelDownloader` completes the coroutine return before updating + `modelState`, the `first { terminal }` collector could hang. Implementation should check + the state machine order and add a brief inline note confirming it. + +2. **`runTest` and `SynchronousExecutor` combination**: while expected to work, this + combination should be tested for the first migration (e.g., `ScheduleStartupTest`) before + converting all files. If a test fails non-obviously, the root cause is likely a + `coroutineScope` or `launch` that `runTest` advances past before WorkManager processes + its queue. The fix is `testScheduler.advanceUntilIdle()`. + +3. **`GitSyncWorkerGateAndRecordTest.kt` line 316**: the 10s guard waits for a WorkManager + `WorkInfo.State.RUNNING` emission on a live `Flow`. With `SynchronousExecutor`, the work + runs synchronously and never enters `RUNNING` as an observable state — it goes directly + to `SUCCEEDED`. This test may need a different approach (e.g., a synchronous check after + `enqueue`, or removal of the state-wait entirely). Flag this as an implementation decision + point. + +## Validation Verdict + +The plan is sound. All ACs are achievable with the described approach. The two open questions +above (state-machine ordering, 10-second git-worker state wait) require implementation-time +investigation but do not block the plan from proceeding. From 80da8233913ab89fbd6ff50dd6a98c5e098872ce Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 11:02:14 -0800 Subject: [PATCH 02/13] test(ui): hold the thumbnail lookup so the pending assertion cannot race generation --- .../stapler/stelekit/ui/components/TieredImageModelTest.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/TieredImageModelTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/TieredImageModelTest.kt index 011451d6c..5d2f11573 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/TieredImageModelTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/TieredImageModelTest.kt @@ -11,6 +11,7 @@ import androidx.compose.ui.test.junit4.createComposeRule import dev.stapler.stelekit.model.EffectiveNotesPath import dev.stapler.stelekit.platform.FileSystem import dev.stapler.stelekit.platform.image.ImageTier +import dev.stapler.stelekit.platform.image.ImageDerivativePaths import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -102,8 +103,14 @@ class TieredImageModelTest { @Test fun `thumbnail tier waits for a generated thumbnail instead of loading the original`() { fs.files["/graph/assets/thumb.png"] = png(600, 400) + // Hold the thumbnail lookup so "pending" cannot race the background generation. + val gate = CountDownLatch(1) + fs.gate = gate + fs.blockedPath = ImageDerivativePaths.pathFor(graph, "/graph/assets/thumb.png", ImageTier.THUMBNAIL) val state = modelFor("../assets/thumb.png", ImageTier.THUMBNAIL) + rule.waitForIdle() assertNull(state.value.model, "original must not be handed to Coil while the thumbnail is pending") + gate.countDown() rule.waitUntil(timeoutMillis = 10_000) { state.value.model != null } assertTrue(assertNotNull(state.value.model).endsWith(".thumb.jpg"), state.value.toString()) From 72d96fcbeccf2248a8659ebdc2f00b8717632ea6 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 11:02:14 -0800 Subject: [PATCH 03/13] fix(scheduling): remove runBlocking from sync scheduler and make scheduling tests deterministic WorkManagerSyncScheduler's schedule/cancel/pauseFor/resumeFor are now suspend. Scheduling tests move to runTest where nothing needs real time; the rest say why. --- .../stelekit/db/DriverFactory.android.kt | 2 + .../db/GraphMoveQuiesceStrategy.android.kt | 6 +- .../stelekit/git/WorkManagerSyncScheduler.kt | 33 ++++---- .../git/AndroidGitCloneWorkerLauncherTest.kt | 9 +++ .../GitCloneWorkerFastFailIntegrationTest.kt | 1 + .../git/GitCloneWorkerNotificationTest.kt | 12 +-- .../stelekit/git/GitCloneWorkerTest.kt | 18 ++--- .../git/GitCloneWorkerThrowableSafetyTest.kt | 10 +-- .../git/GitSyncSchedulingEntryPointTest.kt | 5 ++ .../git/GitSyncWorkerGateAndRecordTest.kt | 54 ++++++------- .../git/GitSyncWorkerStaleGateTest.kt | 25 +++--- .../git/WorkManagerSyncSchedulerPauseTest.kt | 7 +- .../WorkManagerSyncSchedulerRetryOwnerTest.kt | 69 ++++++++--------- .../WorkManagerSyncSchedulerUniqueWorkTest.kt | 4 +- .../jobs/WorkManagerJobRegistryTest.kt | 27 ++++--- .../jobs/schedule/LegacyWorkUpgradeTest.kt | 8 +- .../jobs/schedule/ScheduleStartupTest.kt | 24 +++--- .../schedule/ScheduledTaskReconcilerTest.kt | 10 +-- .../stelekit/jobs/schedule/TaskWorkerTest.kt | 77 +++++++++---------- .../schedule/WorkManagerJitterSpikeTest.kt | 2 + ...WorkManagerTaskSchedulerConcurrencyTest.kt | 2 + ...WorkManagerTaskSchedulerConstraintsTest.kt | 26 +++---- ...WorkManagerTaskSchedulerPauseResumeTest.kt | 30 ++++---- .../ml/DepthModelDownloadWorkerTest.kt | 8 +- .../ml/DepthModelDownloaderAbsentRaceTest.kt | 11 ++- .../ml/DepthModelDownloaderRaceTest.kt | 11 ++- .../platform/ml/DepthModelDownloaderTest.kt | 19 +++-- .../platform/ml/ModelDownloadEndToEndTest.kt | 13 ++-- .../platform/ml/ModelDownloadTaskTest.kt | 29 ++++--- .../stelekit/platform/ml/OneShotSkipTest.kt | 21 ++--- .../stapler/stelekit/platform/ml/WorkAwait.kt | 18 ++--- .../settings/ScheduledSyncSettingsTest.kt | 9 +++ .../TaskSettingsAccessibilityAndErrorsTest.kt | 1 + .../stelekit/ui/ModelDownloadUiTest.kt | 3 + .../ui/ScheduledSyncControlsApplyTest.kt | 6 ++ .../TaskSchedulerAndroidEntryPointTest.kt | 8 ++ .../resources/test-hygiene-baseline.txt | 1 - .../stelekit/git/BackgroundSyncScheduler.kt | 4 +- .../git/JvmGitCloneWorkerLauncherTest.kt | 8 +- .../wiring/ScheduledSyncOriginE2ETest.kt | 5 ++ .../TaskSchedulerDesktopEntryPointTest.kt | 7 ++ project_plans/scheduling-hygiene/research.md | 7 +- 42 files changed, 348 insertions(+), 302 deletions(-) diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt index 24fbd2a62..bc41c4ea4 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt @@ -166,6 +166,8 @@ actual class DriverFactory actual constructor() { ) // Apply incremental DDL migrations (idempotent, hash-tracked). + // runBlocking: createDriver is a non-suspend expect API and the driver must not be returned unmigrated. + // Also reached from the cold git-sync worker (loadGitConfigFromDb), where it holds that worker's thread. runBlocking { MigrationRunner.applyAll(driver) } return driver diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt index e6e4155b3..467ab91ca 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt @@ -90,8 +90,8 @@ class AndroidGraphMoveQuiesceStrategy( private val gate: RepoOpGate, private val gateKeyFor: suspend (StorageMoveOperation) -> String?, private val shadowWorktreeTarget: (StorageMoveOperation) -> ShadowWorktreeQuiesceTarget?, - private val pauseBackgroundSync: (graphId: String) -> Unit = {}, - private val resumeBackgroundSync: (graphId: String) -> Unit = {}, + private val pauseBackgroundSync: suspend (graphId: String) -> Unit = {}, + private val resumeBackgroundSync: suspend (graphId: String) -> Unit = {}, private val releaseUriPermission: (treeUri: String) -> Unit = {}, ) : GraphMoveQuiesceStrategy { @@ -112,7 +112,7 @@ class AndroidGraphMoveQuiesceStrategy( private val holds = ConcurrentHashMap() override suspend fun quiesce(op: StorageMoveOperation): Either { - // The lambda reads WorkInfo with a blocking get(); keep it off the caller's (possibly main) dispatcher. + // The lambda touches settings and WorkManager; keep it off the caller's (possibly main) dispatcher. withContext(Dispatchers.IO) { pauseBackgroundSync(op.graphId) } val target = shadowWorktreeTarget(op) 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 1b3f7514d..f564fdf6e 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt @@ -46,7 +46,6 @@ import dev.stapler.stelekit.platform.PlatformSettings import dev.stapler.stelekit.platform.SteleKitContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking /** * Legacy Android entry point for [BackgroundSyncScheduler], now a shim over [WorkManagerTaskScheduler] @@ -66,24 +65,22 @@ class WorkManagerSyncScheduler( /** * Persists intent through the port: jitter and constraints come from [TaskSettingsStore] (the spec - * defaults when nothing is stored), the interval is the caller's. Blocks briefly on the adapter, which - * guards every WorkManager failure itself, so this never throws. + * defaults when nothing is stored), the interval is the caller's. The adapter guards every WorkManager + * failure itself, so this never throws. */ @Deprecated("Use BackgroundTaskScheduler.apply(TaskKey(git-sync, graphId), config); kept for one release.") - override fun schedule(intervalMinutes: Int) { - runBlocking { - val adapter = legacyAdapter(context) - val stored = legacyStore(context).read(key) - adapter.apply( - key, - TaskConfig(enabled = true, schedule = Schedule.coerce(intervalMinutes, stored.schedule.jitterMinutes), constraints = stored.constraints), - ) - } + override suspend fun schedule(intervalMinutes: Int) { + val adapter = legacyAdapter(context) + val stored = legacyStore(context).read(key) + adapter.apply( + key, + TaskConfig(enabled = true, schedule = Schedule.coerce(intervalMinutes, stored.schedule.jitterMinutes), constraints = stored.constraints), + ) } @Deprecated("Use BackgroundTaskScheduler.cancel(TaskKey(git-sync, graphId)); kept for one release.") - override fun cancel() { - runBlocking { legacyAdapter(context).cancel(key) } + override suspend fun cancel() { + legacyAdapter(context).cancel(key) } companion object { @@ -104,8 +101,8 @@ class WorkManagerSyncScheduler( * [dev.stapler.stelekit.model.StorageMoveOperation], not necessarily one it already holds * a per-graph [WorkManagerSyncScheduler] instance for. */ - fun pauseFor(context: Context, graphId: String) { - runBlocking { legacyAdapter(context).pause(TaskScope(graphId)) } + suspend fun pauseFor(context: Context, graphId: String) { + legacyAdapter(context).pause(TaskScope(graphId)) } /** @@ -113,8 +110,8 @@ class WorkManagerSyncScheduler( * (falling back to the last applied config, then the store). A graph the user disabled meanwhile * stays off. */ - fun resumeFor(context: Context, graphId: String) { - runBlocking { legacyAdapter(context).resume(TaskScope(graphId)) } + suspend fun resumeFor(context: Context, graphId: String) { + 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/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitCloneWorkerLauncherTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitCloneWorkerLauncherTest.kt index 0727c9230..ca84f6705 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitCloneWorkerLauncherTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitCloneWorkerLauncherTest.kt @@ -68,6 +68,7 @@ class AndroidGitCloneWorkerLauncherTest { WorkManagerTestInitHelper.initializeTestWorkManager(context, config) } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() enqueues a GitCloneWorker one-off request and suspends until WorkInfo reaches SUCCEEDED`() = runBlocking { initTestWorkManager { ListenableWorker.Result.success() } @@ -87,6 +88,7 @@ class AndroidGitCloneWorkerLauncherTest { Unit } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() translates a WorkInfo State FAILED terminal state into Left rather than hanging or throwing`() = runBlocking { initTestWorkManager { ListenableWorker.Result.failure() } @@ -106,6 +108,7 @@ class AndroidGitCloneWorkerLauncherTest { Unit } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() decodes an auth failure payload into AuthFailed and a NonRetryableFailure state`() = runBlocking { val payload = GitCloneWorkerData.encodeFailure(DomainError.GitError.AuthFailed("bad token"), NonRetryableReason.AUTH) @@ -120,6 +123,7 @@ class AndroidGitCloneWorkerLauncherTest { assertEquals(listOf(GitTransportRetryState.NonRetryableFailure(NonRetryableReason.AUTH)), states) } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() decodes a retry-exhausted payload into RetryExhausted and an Exhausted state`() = runBlocking { val error = DomainError.GitError.RetryExhausted(5, DomainError.GitError.CloneFailed("net down")) @@ -136,6 +140,7 @@ class AndroidGitCloneWorkerLauncherTest { assertEquals(5, (states.single() as GitTransportRetryState.Exhausted).maxAttempts) } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() removes transient credentials once the clone terminates`() = runBlocking { initTestWorkManager { ListenableWorker.Result.success() } @@ -152,6 +157,7 @@ class AndroidGitCloneWorkerLauncherTest { Unit } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() displaces a never-finishing same-name predecessor via REPLACE instead of blocking behind it`() = runBlocking { initTestWorkManager { ListenableWorker.Result.success() } @@ -171,6 +177,7 @@ class AndroidGitCloneWorkerLauncherTest { Unit } + // runBlocking: the launcher's BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone() cancels the enqueued worker when the caller is cancelled`() = runBlocking { // Real (non-synchronous) executor so the slow worker leaves launchClone suspended. @@ -185,6 +192,7 @@ class AndroidGitCloneWorkerLauncherTest { ): ListenableWorker? = object : Worker(appContext, workerParameters) { override fun doWork(): Result { started.countDown() + // Real sleep (5 s cap): a non-suspend Worker on a real executor can only poll isStopped. repeat(200) { if (isStopped) return Result.success(); Thread.sleep(25) } return Result.success() } @@ -200,6 +208,7 @@ class AndroidGitCloneWorkerLauncherTest { graphId, "https://example.invalid/g.git", "/tmp/g", GitAuth.None, {}, {}, null, ) } + // Real 10 s ceiling: the latch is the signal; the worker starts on a real executor thread. assertTrue(started.await(10, java.util.concurrent.TimeUnit.SECONDS), "worker should start") job.cancelAndJoin() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerFastFailIntegrationTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerFastFailIntegrationTest.kt index 153f2adf6..79b72bf61 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerFastFailIntegrationTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerFastFailIntegrationTest.kt @@ -96,6 +96,7 @@ class GitCloneWorkerFastFailIntegrationTest { // "Permission denied" on the generated .class file, not a length-related error. @Test fun `doWork() against an auth-always-failing FailureSequenceGitRepository fails after exactly one attempt with no backoff delay`() = + // runBlocking: asserts wall-clock elapsed time to prove no backoff; runTest would skip the delays runBlocking { // "Always fails" is modeled via FailureSequence's onSuccess (not its `failures` list, // which is for a bounded "fail N times then succeed" sequence) returning a Left on diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerNotificationTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerNotificationTest.kt index 17e1cf522..675b97065 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerNotificationTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerNotificationTest.kt @@ -22,7 +22,7 @@ import arrow.core.right import com.google.common.util.concurrent.ListenableFuture import dev.stapler.stelekit.error.DomainError import dev.stapler.stelekit.git.testsupport.StubGitRepository -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -110,7 +110,7 @@ class GitCloneWorkerNotificationTest { } @Test - fun `getForegroundInfo() builds a notification titled Syncing graph display name`() = runBlocking { + fun `getForegroundInfo() builds a notification titled Syncing graph display name`() = runTest { val worker = buildWorker(StubGitRepository()) val info = worker.getForegroundInfo() @@ -120,7 +120,7 @@ class GitCloneWorkerNotificationTest { } @Test - fun `getForegroundInfo() falls back to your graph when no display name is provided`() = runBlocking { + fun `getForegroundInfo() falls back to your graph when no display name is provided`() = runTest { val worker = buildWorker(StubGitRepository(), inputData = defaultInputData(graphDisplayName = null)) val info = worker.getForegroundInfo() @@ -130,7 +130,7 @@ class GitCloneWorkerNotificationTest { } @Test - fun `a Retrying state's notification body matches notificationBodyFor exactly`() = runBlocking { + fun `a Retrying state's notification body matches notificationBodyFor exactly`() = runTest { var captured: Pair? = null val repo = statefulCloningStub { onStateChange -> onStateChange(GitTransportRetryState.Retrying(attempt = 2, max = 4, progress = null)) @@ -146,7 +146,7 @@ class GitCloneWorkerNotificationTest { } @Test - fun `a terminal Exhausted notification is rebuilt as dismissible tap-to-retry, not staying ongoing`() = runBlocking { + fun `a terminal Exhausted notification is rebuilt as dismissible tap-to-retry, not staying ongoing`() = runTest { val repo = statefulCloningStub { onStateChange -> onStateChange(GitTransportRetryState.Exhausted("network down")) DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("net down")).left() @@ -161,7 +161,7 @@ class GitCloneWorkerNotificationTest { } @Test - fun `a stable notification ID is used across multiple GitTransportRetryState transitions, not a new notification per event`() = runBlocking { + fun `a stable notification ID is used across multiple GitTransportRetryState transitions, not a new notification per event`() = runTest { val seenIds = mutableSetOf() val repo = statefulCloningStub { onStateChange -> onStateChange(GitTransportRetryState.Attempting(CloneProgress("Receiving objects", 10, 100))) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerTest.kt index b7f1994ae..d929ba530 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerTest.kt @@ -22,7 +22,7 @@ import com.google.common.util.concurrent.ListenableFuture import dev.stapler.stelekit.error.DomainError import dev.stapler.stelekit.error.SyncOrigin import dev.stapler.stelekit.git.testsupport.cloningStub -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -97,7 +97,7 @@ class GitCloneWorkerTest { .build() @Test - fun `doWork() calls setForeground() with a dataSync-typed ForegroundInfo before invoking clone()`() = runBlocking { + fun `doWork() calls setForeground() with a dataSync-typed ForegroundInfo before invoking clone()`() = runTest { var setForegroundCalledBeforeClone = false val foregroundUpdater = RecordingForegroundUpdater() var cloneInvoked = false @@ -118,7 +118,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() logs the denial, proceeds without foreground promotion, and still completes the clone when setForeground() throws ForegroundServiceStartNotAllowedException`() = runBlocking { + fun `doWork() logs the denial, proceeds without foreground promotion, and still completes the clone when setForeground() throws ForegroundServiceStartNotAllowedException`() = runTest { var cloneInvoked = false val repo = cloningStub { _, _, _, _ -> cloneInvoked = true; Unit.right() } val denyingUpdater = DenyingForegroundUpdater(ForegroundServiceStartNotAllowedException("denied")) @@ -131,7 +131,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() takes the gate for the destination and does not clone when it is already held`() = runBlocking { + fun `doWork() takes the gate for the destination and does not clone when it is already held`() = runTest { var cloneInvoked = false val repo = cloningStub { _, _, _, _ -> cloneInvoked = true; Unit.right() } val gate = RepoOpGate() @@ -148,7 +148,7 @@ class GitCloneWorkerTest { } @Test - fun `built via TestListenableWorkerBuilder against a StubGitRepository, doWork() completes end-to-end and returns Result success`() = runBlocking { + fun `built via TestListenableWorkerBuilder against a StubGitRepository, doWork() completes end-to-end and returns Result success`() = runTest { val worker = buildWorker(cloningStub { _, _, _, onProgress -> onProgress(CloneProgress("Receiving objects", 0, 0)); Unit.right() }) val result = worker.doWork() @@ -157,7 +157,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() returns Result failure, never Result retry, when clone() returns a Left`() = runBlocking { + fun `doWork() returns Result failure, never Result retry, when clone() returns a Left`() = runTest { val repo = cloningStub { _, _, _, _ -> DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("net down")).left() } @@ -170,7 +170,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() returns Result failure, not Result retry, for a non-retryable Left on the very first attempt too`() = runBlocking { + fun `doWork() returns Result failure, not Result retry, for a non-retryable Left on the very first attempt too`() = runTest { val repo = cloningStub { _, _, _, _ -> DomainError.GitError.AuthFailed("bad token").left() } val worker = buildWorker(repo) @@ -181,7 +181,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() removes the transient clone credentials on every terminal path`() = runBlocking { + fun `doWork() removes the transient clone credentials on every terminal path`() = runTest { val store = InMemoryCredentialAccess() val key = GitCloneWorker.httpsTokenCredentialKey("graph-1") store.store(key, "secret-pat") @@ -197,7 +197,7 @@ class GitCloneWorkerTest { } @Test - fun `doWork() converts its foreground notification to a dismissible tap-to-retry one on a failed clone, rather than lingering as in-progress`() = runBlocking { + fun `doWork() converts its foreground notification to a dismissible tap-to-retry one on a failed clone, rather than lingering as in-progress`() = runTest { // Superseded by git-sync-resilience Task 4.1.5c: a terminal failure no longer tears the // notification down outright (this test's pre-Epic-4.1 name/assertion) — it rebuilds it as // dismissible ("tap to retry" content, setOngoing(false)) instead, per plan.md Story 4.1.5's diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerThrowableSafetyTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerThrowableSafetyTest.kt index 8caca8f74..a580b42d0 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerThrowableSafetyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitCloneWorkerThrowableSafetyTest.kt @@ -18,7 +18,7 @@ import arrow.core.right import com.google.common.util.concurrent.ListenableFuture import dev.stapler.stelekit.git.testsupport.cloningStub import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -81,7 +81,7 @@ class GitCloneWorkerThrowableSafetyTest { .build() @Test - fun `doWork() returns Result failure and tears down the foreground notification when the wrapped clone delegate throws OutOfMemoryError`() = runBlocking { + fun `doWork() returns Result failure and tears down the foreground notification when the wrapped clone delegate throws OutOfMemoryError`() = runTest { val repo = cloningStub { _, _, _, _ -> throw OutOfMemoryError("simulated JGit pack-parsing OOM") } val worker = buildWorker(repo) @@ -96,7 +96,7 @@ class GitCloneWorkerThrowableSafetyTest { } @Test - fun `doWork() rethrows CancellationException rather than converting it to Result failure when the wrapped clone delegate is cancelled`() = runBlocking { + fun `doWork() rethrows CancellationException rather than converting it to Result failure when the wrapped clone delegate is cancelled`() = runTest { val repo = cloningStub { _, _, _, _ -> throw CancellationException("worker stopped") } val worker = buildWorker(repo) @@ -105,7 +105,7 @@ class GitCloneWorkerThrowableSafetyTest { } @Test - fun `doWork() tears down the foreground notification on the CancellationException path too`() = runBlocking { + fun `doWork() tears down the foreground notification on the CancellationException path too`() = runTest { val foregroundUpdater = RecordingForegroundUpdater() val repo = cloningStub { _, _, _, _ -> throw CancellationException("worker stopped") } val worker = buildWorker(repo, foregroundUpdater) @@ -121,7 +121,7 @@ class GitCloneWorkerThrowableSafetyTest { } @Test - fun `a successful clone never throws and returns Result success`() = runBlocking { + fun `a successful clone never throws and returns Result success`() = runTest { val repo = cloningStub { _, _, _, _ -> Unit.right() } val worker = buildWorker(repo) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt index 0aad1b729..dbb0a7365 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt @@ -57,6 +57,7 @@ class GitSyncSchedulingEntryPointTest { @After fun tearDown() { + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -86,6 +87,7 @@ class GitSyncSchedulingEntryPointTest { Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val wired = runBlocking { WiredAppFixture.android( context, @@ -104,6 +106,7 @@ class GitSyncSchedulingEntryPointTest { composeRule.setContent { controls = rememberGraphContentScheduledSyncControls(wired.deps, null, configRepo, graphId) } composeRule.waitForIdle() // The port adapter enqueues from a coroutine launched by the glue, so wait for the work rather than the frame. + // Real-clock ceiling: WorkManager and the glue coroutine run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { workInfos().isNotEmpty() } ObservableEffect.assert("periodic-work-enqueued") { @@ -117,6 +120,7 @@ class GitSyncSchedulingEntryPointTest { assertEquals(15, controls?.minimumIntervalMinutes) composeRule.runOnIdle { controls!!.setEnabled(false) } + // Real-clock ceiling: WorkManager and the glue coroutine run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { workInfos().single().state == WorkInfo.State.CANCELLED } assertEquals(WorkInfo.State.CANCELLED, workInfos().single().state, "turning the switch off cancels the job") } @@ -127,6 +131,7 @@ class GitSyncSchedulingEntryPointTest { context, Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val wired = runBlocking { WiredAppFixture.android( context, diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerGateAndRecordTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerGateAndRecordTest.kt index 844d75e6b..33f9a38df 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerGateAndRecordTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerGateAndRecordTest.kt @@ -39,8 +39,7 @@ import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -163,14 +162,14 @@ class GitSyncWorkerGateAndRecordTest { override fun containsKey(key: String) = store.containsKey(key) } - private fun run(policy: String? = null, interval: Long? = null): ListenableWorker.Result { + private suspend fun run(policy: String? = null, interval: Long? = null): ListenableWorker.Result { val data = buildList { add(GitSyncWorker.KEY_GRAPH_ID to graphId) if (policy != null) add(GitSyncWorker.KEY_NETWORK_POLICY to policy) if (interval != null) add(GitSyncWorker.KEY_INTERVAL_MINUTES to interval) } val worker = TestListenableWorkerBuilder(context).setInputData(workDataOf(*data.toTypedArray())).build() - return runBlocking { worker.doWork() } + return worker.doWork() } private fun onlyRecord(): TaskRunRecord { @@ -182,7 +181,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_skipMeteredAndLogOneRecord_When_UnmeteredPolicyOnMeteredNetwork() { + fun doWork_should_skipMeteredAndLogOneRecord_When_UnmeteredPolicyOnMeteredNetwork() = runTest { registerService(); provider(metered = true) val result = run(policy = "unmetered") @@ -193,7 +192,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_skipUnknownNetwork_When_UnmeteredPolicyAndMeteringUnknown() { + fun doWork_should_skipUnknownNetwork_When_UnmeteredPolicyAndMeteringUnknown() = runTest { registerService(); provider(metered = null) assertIs(run(policy = "unmetered")) assertEquals(TaskRunResult.Skipped("unknown-network"), onlyRecord().result) @@ -201,7 +200,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_skipUnknownNetwork_When_UnmeteredPolicyAndProviderThrows() { + fun doWork_should_skipUnknownNetwork_When_UnmeteredPolicyAndProviderThrows() = runTest { registerService(); throwingProvider() assertIs(run(policy = "unmetered")) assertEquals(TaskRunResult.Skipped("unknown-network"), onlyRecord().result) @@ -209,7 +208,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_skipOffline_When_ProviderExplicitlyReportsOffline() { + fun doWork_should_skipOffline_When_ProviderExplicitlyReportsOffline() = runTest { registerService(); provider(online = false, metered = null) assertIs(run(policy = "any")) assertEquals(TaskRunResult.Skipped("offline"), onlyRecord().result) @@ -217,7 +216,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_proceed_When_PolicyAnyAndNetworkMetered() { + fun doWork_should_proceed_When_PolicyAnyAndNetworkMetered() = runTest { registerService(); provider(metered = true) assertIs(run(policy = "any")) assertEquals(1, fetches) @@ -225,7 +224,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_proceed_When_PolicyKeyAbsentAsInAPreUpgradeJob() { + fun doWork_should_proceed_When_PolicyKeyAbsentAsInAPreUpgradeJob() = runTest { registerService(); provider(metered = true) assertIs(run(policy = null)) assertEquals(1, fetches) @@ -233,7 +232,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_proceed_When_PolicyAnyAndProviderThrows() { + fun doWork_should_proceed_When_PolicyAnyAndProviderThrows() = runTest { registerService(); throwingProvider() assertIs(run(policy = null)) assertEquals(1, fetches, "WorkManager's CONNECTED constraint already held, so an unreadable provider proceeds for Any") @@ -241,7 +240,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_logFailedAndReturnFailure_When_FetchFails() { + fun doWork_should_logFailedAndReturnFailure_When_FetchFails() = runTest { registerService(DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("boom")).left()) provider(metered = false) @@ -252,7 +251,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_recordConstraintStateReadAtRunStart_When_Run() { + fun doWork_should_recordConstraintStateReadAtRunStart_When_Run() = runTest { registerService(); provider(online = true, metered = false) run() val state = onlyRecord().constraintState @@ -261,7 +260,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_keepResultUnchanged_When_RunLogWriteThrows() { + fun doWork_should_keepResultUnchanged_When_RunLogWriteThrows() = runTest { registerService(); provider(metered = false) GitSyncWorker.runLogOverride = { object : TaskRunLog { @@ -276,14 +275,14 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_keepResultUnchanged_When_RunLogCannotBeBuilt() { + fun doWork_should_keepResultUnchanged_When_RunLogCannotBeBuilt() = runTest { registerService(); provider(metered = false) GitSyncWorker.runLogOverride = { throw IllegalStateException("settings unavailable") } assertIs(run()) } @Test - fun doWork_should_appendExactlyOneRecord_When_SuccessSkipOrFailure() { + fun doWork_should_appendExactlyOneRecord_When_SuccessSkipOrFailure() = runTest { provider(metered = false) registerService() run() @@ -303,7 +302,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_runPreRunGateYieldBodyPostRunInOrder_When_CloneRunning() { + fun doWork_should_runPreRunGateYieldBodyPostRunInOrder_When_CloneRunning() = runTest { WorkManagerTestInitHelper.initializeTestWorkManager( context, Configuration.Builder().setExecutor(Executors.newCachedThreadPool()).build(), @@ -312,11 +311,8 @@ class GitSyncWorkerGateAndRecordTest { val clone = OneTimeWorkRequestBuilder().build() try { WorkManager.getInstance(context).enqueue(clone) - runBlocking { - withTimeout(CLONE_RUNNING_TIMEOUT_MS) { - WorkManager.getInstance(context).getWorkInfoByIdFlow(clone.id).first { it?.state == WorkInfo.State.RUNNING } - } - } + // No withTimeout: it would run on virtual time while the clone starts on a real thread. + WorkManager.getInstance(context).getWorkInfoByIdFlow(clone.id).first { it?.state == WorkInfo.State.RUNNING } GitCloneWorkTracker.recordStart(context, graphId, clone.id, System.currentTimeMillis()) provider(metered = true) @@ -332,7 +328,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_runWatchdogThenBodyThenPostRun_When_FetchSucceeds() { + fun doWork_should_runWatchdogThenBodyThenPostRun_When_FetchSucceeds() = runTest { registerService(); provider(metered = false); recordingHooks() assertIs(run()) @@ -343,7 +339,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_runWatchdogButSkipPostRun_When_NetworkGateSkips() { + fun doWork_should_runWatchdogButSkipPostRun_When_NetworkGateSkips() = runTest { registerService(); provider(metered = true); recordingHooks() assertIs(run(policy = "unmetered")) @@ -353,7 +349,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_skipPostRun_When_CloneYieldSkips() { + fun doWork_should_skipPostRun_When_CloneYieldSkips() = runTest { provider(metered = false); recordingHooks(yield = true) assertIs(run()) @@ -364,7 +360,7 @@ class GitSyncWorkerGateAndRecordTest { } @Test - fun doWork_should_stayRecordedSuccessAndSucceed_When_PostRunThrowsAfterGoodFetch() { + fun doWork_should_stayRecordedSuccessAndSucceed_When_PostRunThrowsAfterGoodFetch() = runTest { registerService(); provider(metered = false); recordingHooks(postRunFails = true) val result = run() @@ -375,13 +371,9 @@ class GitSyncWorkerGateAndRecordTest { } /** Runs the worker with no live service and returns the cumulative record count after asserting the newest skip reason. */ - private fun runGated(policy: String, expectedReason: String): Int { + private suspend fun runGated(policy: String, expectedReason: String): Int { assertIs(run(policy = policy)) assertEquals(TaskRunResult.Skipped(expectedReason), log.records.last().result) return log.records.size } - - private companion object { - const val CLONE_RUNNING_TIMEOUT_MS = 10_000L - } } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerStaleGateTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerStaleGateTest.kt index 4a401318f..2a6784e25 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerStaleGateTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncWorkerStaleGateTest.kt @@ -40,7 +40,7 @@ import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -93,6 +93,7 @@ class GitSyncWorkerStaleGateTest { GitSyncAdapterHooks.staleJobReason(graphId, periodic) } TaskWorkerRuntime.knownScopes = KnownScopes { KnownScopesResult.Unknown } + // runBlocking: JUnit @Before is not a coroutine, and nothing here waits on time runBlocking { store.write(key, TaskEntry(enabled = true, overrides = null)) } registerService() } @@ -141,13 +142,13 @@ class GitSyncWorkerStaleGateTest { override fun containsKey(key: String) = store.containsKey(key) } - private fun run(periodic: Boolean = true): ListenableWorker.Result { + private suspend fun run(periodic: Boolean = true): ListenableWorker.Result { val data = buildList { add(GitSyncWorker.KEY_GRAPH_ID to graphId) if (periodic) add(GitSyncWorker.KEY_INTERVAL_MINUTES to 15L) } val worker = TestListenableWorkerBuilder(context).setInputData(workDataOf(*data.toTypedArray())).build() - return runBlocking { worker.doWork() } + return worker.doWork() } private fun assertSkipped(reason: String) { @@ -156,43 +157,43 @@ class GitSyncWorkerStaleGateTest { } @Test - fun doWork_should_skipWithoutSync_When_PeriodicTaskDisabled() { - runBlocking { store.write(key, TaskEntry(enabled = false, overrides = null)) } + fun doWork_should_skipWithoutSync_When_PeriodicTaskDisabled() = runTest { + store.write(key, TaskEntry(enabled = false, overrides = null)) assertIs(run()) assertSkipped("disabled") } @Test - fun doWork_should_skipWithoutSync_When_GraphTombstoned() { - runBlocking { store.tombstone(key) } + fun doWork_should_skipWithoutSync_When_GraphTombstoned() = runTest { + store.tombstone(key) assertIs(run()) assertSkipped("disabled") } @Test - fun doWork_should_skipWithoutSync_When_GraphMissingFromKnownScopes() { + fun doWork_should_skipWithoutSync_When_GraphMissingFromKnownScopes() = runTest { TaskWorkerRuntime.knownScopes = KnownScopes { KnownScopesResult.Known(setOf(TaskScope("other"))) } assertIs(run()) assertSkipped("graph-removed") } @Test - fun doWork_should_run_When_KnownScopesUnknown() { + fun doWork_should_run_When_KnownScopesUnknown() = runTest { assertIs(run()) assertEquals(1, fetches) assertTrue(log.records.single().result !is TaskRunResult.Skipped) } @Test - fun doWork_should_run_When_EnabledAndGraphKnown() { + fun doWork_should_run_When_EnabledAndGraphKnown() = runTest { TaskWorkerRuntime.knownScopes = KnownScopes { KnownScopesResult.Known(setOf(TaskScope(graphId))) } assertIs(run()) assertEquals(1, fetches) } @Test - fun doWork_should_run_When_ExplicitOneShotAndTaskDisabled() { - runBlocking { store.write(key, TaskEntry(enabled = false, overrides = null)) } + fun doWork_should_run_When_ExplicitOneShotAndTaskDisabled() = runTest { + store.write(key, TaskEntry(enabled = false, overrides = null)) assertIs(run(periodic = false)) assertEquals(1, fetches) } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt index 01393f9a0..27cdbfa8b 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt @@ -8,6 +8,7 @@ import androidx.test.core.app.ApplicationProvider import androidx.work.Configuration import androidx.work.WorkInfo import androidx.work.WorkManager +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -57,7 +58,7 @@ class WorkManagerSyncSchedulerPauseTest { .any { it.state == WorkInfo.State.ENQUEUED } @Test - fun pauseFor_should_CancelPeriodicJobBeforeCopyBegins_When_RelocateStarts() { + fun pauseFor_should_CancelPeriodicJobBeforeCopyBegins_When_RelocateStarts() = runTest { WorkManagerSyncScheduler(context, graphId).schedule(intervalMinutes = 15) assertTrue(enqueuedWorkExists(), "sanity check: job should be enqueued before pauseFor runs") @@ -67,7 +68,7 @@ class WorkManagerSyncSchedulerPauseTest { } @Test - fun resumeFor_should_RescheduleThePeriodicJob_When_SwitchGraphCompletes() { + fun resumeFor_should_RescheduleThePeriodicJob_When_SwitchGraphCompletes() = runTest { WorkManagerSyncScheduler(context, graphId).schedule(intervalMinutes = 15) WorkManagerSyncScheduler.pauseFor(context, graphId) assertFalse(enqueuedWorkExists(), "sanity check: job should be paused before resumeFor runs") @@ -78,7 +79,7 @@ class WorkManagerSyncSchedulerPauseTest { } @Test - fun pauseFor_should_NotAffectAnotherGraphsScheduledJob_When_OnlyOneGraphIsRelocating() { + fun pauseFor_should_NotAffectAnotherGraphsScheduledJob_When_OnlyOneGraphIsRelocating() = runTest { val otherGraphId = "g2" WorkManagerSyncScheduler(context, graphId).schedule(intervalMinutes = 15) WorkManagerSyncScheduler(context, otherGraphId).schedule(intervalMinutes = 15) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerRetryOwnerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerRetryOwnerTest.kt index 170d8bb2e..f5e120461 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerRetryOwnerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerRetryOwnerTest.kt @@ -34,7 +34,10 @@ import dev.stapler.stelekit.jobs.schedule.NetworkSnapshotProvider import dev.stapler.stelekit.platform.NetworkMonitor import dev.stapler.stelekit.repository.InMemoryBlockRepository import dev.stapler.stelekit.repository.InMemoryPageRepository -import kotlinx.coroutines.runBlocking +import java.util.UUID +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.mapNotNull +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -131,16 +134,13 @@ class WorkManagerSyncSchedulerRetryOwnerTest { .build() @Test - fun `GitSyncWorker doWork() fast path returns Result failure(), not Result retry(), when fetchOnly() returns Left(RetryExhausted)`() { + fun `GitSyncWorker doWork() fast path returns Result failure(), not Result retry(), when fetchOnly() returns Left(RetryExhausted)`() = runTest { registerFastPathService( FAST_PATH_GRAPH_ID, DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("boom")).left(), ) - // Block body (not `= runBlocking { ... }`): JUnit4's method validator requires a `void` - // (Unit) return type, but `runBlocking`'s generic `T` would otherwise be inferred from - // `assertIs`'s own return value (it returns the narrowed type, not Unit). - val result = runBlocking { buildWorker(FAST_PATH_GRAPH_ID).doWork() } + val result = buildWorker(FAST_PATH_GRAPH_ID).doWork() assertIs(result) } @@ -155,7 +155,7 @@ class WorkManagerSyncSchedulerRetryOwnerTest { } @Test - fun `fast path runs the policy-gated scheduled tick, not a bare fetchOnly`() { + fun `fast path runs the policy-gated scheduled tick, not a bare fetchOnly`() = runTest { val settings = MapSettings() val stubFs = StubFileSystem() val service = GitSyncService( @@ -177,7 +177,7 @@ class WorkManagerSyncSchedulerRetryOwnerTest { ) GitSyncServiceRegistry.register(FAST_PATH_GRAPH_ID, service) - val result = runBlocking { buildWorker(FAST_PATH_GRAPH_ID).doWork() } + val result = buildWorker(FAST_PATH_GRAPH_ID).doWork() assertIs(result) assertEquals(FetchOnlyReason.Saf, SyncStalenessStore(settings).read(FAST_PATH_GRAPH_ID).fetchOnlyReason) @@ -186,12 +186,10 @@ class WorkManagerSyncSchedulerRetryOwnerTest { } @Test - fun `slow path hands the single fetch to the cold runner and records the behind count`() { + fun `slow path hands the single fetch to the cold runner and records the behind count`() = runTest { val settings = MapSettings() val staleness = SyncStalenessStore(settings) - val result = runBlocking { - runSlowPathFetch({ sampleConfig }, repoReturning(FetchResult(true, 4).right()), RepoOpGate(), { "k" }, staleness, clock = { 9L }) - } + val result = runSlowPathFetch({ sampleConfig }, repoReturning(FetchResult(true, 4).right()), RepoOpGate(), { "k" }, staleness, clock = { 9L }) assertIs(result) val stored = staleness.read(sampleConfig.graphId) assertEquals(4, stored.behindCount) @@ -199,10 +197,10 @@ class WorkManagerSyncSchedulerRetryOwnerTest { } @Test - fun `slow path records a typed fetch error as the outcome and fails`() { + fun `slow path records a typed fetch error as the outcome and fails`() = runTest { val staleness = SyncStalenessStore(MapSettings()) val error = DomainError.GitError.RemoteBranchNotFound("origin", "main", emptyList()) - val result = runBlocking { runSlowPathFetch({ sampleConfig }, repoReturning(error.left()), RepoOpGate(), { "k" }, staleness, clock = { 9L }) } + val result = runSlowPathFetch({ sampleConfig }, repoReturning(error.left()), RepoOpGate(), { "k" }, staleness, clock = { 9L }) assertIs(result) assertEquals("RemoteBranchNotFound", staleness.read(sampleConfig.graphId).history.last().detail) } @@ -215,30 +213,28 @@ class WorkManagerSyncSchedulerRetryOwnerTest { } @Test - fun `slow path returns Result failure(), not retry(), when fetch() returns Left(RetryExhausted)`() { - val result = runBlocking { - runSlowPathFetch( - loadConfig = { sampleConfig }, - gitRepository = repoReturning( - DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("boom")).left(), - ), - gate = RepoOpGate(), - gateKeyFor = { "k" }, - ) - } + fun `slow path returns Result failure(), not retry(), when fetch() returns Left(RetryExhausted)`() = runTest { + val result = runSlowPathFetch( + loadConfig = { sampleConfig }, + gitRepository = repoReturning( + DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("boom")).left(), + ), + gate = RepoOpGate(), + gateKeyFor = { "k" }, + ) assertIs(result) } @Test - fun `slow path returns success when fetch() succeeds, and success when no config row exists`() { - val ok = runBlocking { runSlowPathFetch({ sampleConfig }, repoReturning(FetchResult(false, 0).right()), RepoOpGate(), { "k" }) } + fun `slow path returns success when fetch() succeeds, and success when no config row exists`() = runTest { + val ok = runSlowPathFetch({ sampleConfig }, repoReturning(FetchResult(false, 0).right()), RepoOpGate(), { "k" }) assertIs(ok) - val noRow = runBlocking { runSlowPathFetch({ null }, repoReturning(FetchResult(false, 0).right()), RepoOpGate(), { "k" }) } + val noRow = runSlowPathFetch({ null }, repoReturning(FetchResult(false, 0).right()), RepoOpGate(), { "k" }) assertIs(noRow) } @Test - fun `slow path skips without fetching when the shared gate is held`() { + fun `slow path skips without fetching when the shared gate is held`() = runTest { val gate = RepoOpGate() gate.tryAcquire("k", SyncOrigin.UiPress)!! var fetched = false @@ -248,7 +244,7 @@ class WorkManagerSyncSchedulerRetryOwnerTest { return FetchResult(false, 0).right() } } - val result = runBlocking { runSlowPathFetch({ sampleConfig }, repo, gate, { "k" }) } + val result = runSlowPathFetch({ sampleConfig }, repo, gate, { "k" }) assertIs(result) assertEquals(false, fetched) assertEquals( @@ -266,7 +262,7 @@ class WorkManagerSyncSchedulerRetryOwnerTest { * `GitTransportRetryTest`'s exhaustion test). */ @Test - fun `a GitSyncWorker built via TestListenableWorkerBuilder against a retry-exhausting StubGitRepository returns Result failure() and is not re-enqueued by WorkManager's own retry mechanism`() { + fun `a GitSyncWorker built via TestListenableWorkerBuilder against a retry-exhausting StubGitRepository returns Result failure() and is not re-enqueued by WorkManager's own retry mechanism`() = runTest { registerFastPathService( WORK_MANAGER_GRAPH_ID, DomainError.GitError.RetryExhausted(5, DomainError.GitError.FetchFailed("boom")).left(), @@ -281,15 +277,14 @@ class WorkManagerSyncSchedulerRetryOwnerTest { // GitSyncWorker is a CoroutineWorker: it runs on a coroutine dispatcher, not the test // SynchronousExecutor, so the state right after enqueue can still be RUNNING. Wait for a // terminal state; a Result.retry() would surface as ENQUEUED and never terminate. - val deadline = System.nanoTime() + 10_000_000_000L - var state = workManager.getWorkInfoById(request.id).get().state - while (!state.isFinished && state != WorkInfo.State.ENQUEUED && System.nanoTime() < deadline) { - Thread.sleep(25) - state = workManager.getWorkInfoById(request.id).get().state - } + val state = awaitSettledState(workManager, request.id) assertEquals(WorkInfo.State.FAILED, state, "must not be re-enqueued (ENQUEUED/RUNNING) after Result.failure()") } + // A separate function keeps the generated lambda class name under the filesystem's filename limit. + private suspend fun awaitSettledState(workManager: WorkManager, id: UUID): WorkInfo.State = + workManager.getWorkInfoByIdFlow(id).mapNotNull { it?.state }.first { it.isFinished || it == WorkInfo.State.ENQUEUED } + companion object { private const val FAST_PATH_GRAPH_ID = "retry-owner-fast-path" private const val WORK_MANAGER_GRAPH_ID = "retry-owner-workmanager" diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerUniqueWorkTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerUniqueWorkTest.kt index c0288ef6b..5bf294eda 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerUniqueWorkTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerUniqueWorkTest.kt @@ -20,6 +20,7 @@ import androidx.work.testing.SynchronousExecutor import androidx.work.testing.WorkManagerTestInitHelper import androidx.work.workDataOf import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -77,7 +78,7 @@ class WorkManagerSyncSchedulerUniqueWorkTest { } @Test - fun `AndroidGitCloneWorkerLauncher computes the same workNameFor(graphId) as WorkManagerSyncScheduler's periodic job`() { + fun `AndroidGitCloneWorkerLauncher computes the same workNameFor(graphId) as WorkManagerSyncScheduler's periodic job`() = runTest { initTestWorkManager() val graphId = "unique-work-happy-path" WorkManagerSyncScheduler(context, graphId).schedule(30) @@ -129,6 +130,7 @@ class WorkManagerSyncSchedulerUniqueWorkTest { * Non-blocking by design: the periodic job's initial delay keeps it `ENQUEUED` (never run) so * the test driver's serial executor is never held by a gated worker. */ + // runBlocking: launchClone()'s BLOCKED watchdog uses delay(), which runTest would skip @Test fun `launchClone over an existing periodic job reaches SUCCEEDED instead of being left BLOCKED, and restores the periodic job`() = runBlocking { val graphId = "unique-work-concurrency" diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/WorkManagerJobRegistryTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/WorkManagerJobRegistryTest.kt index 7011bfc1b..7b5094d47 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/WorkManagerJobRegistryTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/WorkManagerJobRegistryTest.kt @@ -35,8 +35,7 @@ import dev.stapler.stelekit.platform.ml.DepthModelDownloader import dev.stapler.stelekit.platform.ml.DepthModelStorage import kotlinx.coroutines.async import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -67,10 +66,10 @@ class WorkManagerJobRegistryTest { DepthModelStorage.modelFile(context).parentFile?.deleteRecursively() } - private suspend fun WorkManagerJobRegistry.firstJobs() = withTimeout(5_000) { jobs.first { it.isNotEmpty() } } + private suspend fun WorkManagerJobRegistry.firstJobs() = jobs.first { it.isNotEmpty() } @Test - fun `a queued depth model download is listed with its kind and title`() = runBlocking { + fun `a queued depth model download is listed with its kind and title`() = runTest { val waiter = async { DepthModelDownloader(context).downloadModel() } val registry = WorkManagerJobRegistry(context) @@ -83,44 +82,44 @@ class WorkManagerJobRegistryTest { } @Test - fun `cancelling a listed job marks it cancelled`() = runBlocking { + fun `cancelling a listed job marks it cancelled`() = runTest { val waiter = async { DepthModelDownloader(context).downloadModel() } val registry = WorkManagerJobRegistry(context) val id = registry.firstJobs().single().id registry.cancel(id) - val cancelled = withTimeout(5_000) { registry.jobs.first { list -> list.any { it.state is JobState.Cancelled } } } + val cancelled = registry.jobs.first { list -> list.any { it.state is JobState.Cancelled } } assertEquals(id, cancelled.single().id) waiter.cancel() } @Test - fun `clearFinished drops finished jobs from the list`() = runBlocking { + fun `clearFinished drops finished jobs from the list`() = runTest { val waiter = async { DepthModelDownloader(context).downloadModel() } val registry = WorkManagerJobRegistry(context) registry.cancel(registry.firstJobs().single().id) - withTimeout(5_000) { registry.jobs.first { list -> list.any { it.state is JobState.Cancelled } } } + registry.jobs.first { list -> list.any { it.state is JobState.Cancelled } } registry.clearFinished() - withTimeout(5_000) { registry.jobs.first { it.isEmpty() } } + registry.jobs.first { it.isEmpty() } waiter.cancel() } @Test - fun `work without a job kind tag is ignored`() = runBlocking { + fun `work without a job kind tag is ignored`() = runTest { val request = OneTimeWorkRequestBuilder().addTag(JobTags.ANY).build() WorkManager.getInstance(context).enqueue(request) val registry = WorkManagerJobRegistry(context) - assertTrue(withTimeout(5_000) { registry.jobs.first() }.isEmpty()) + assertTrue(registry.jobs.first().isEmpty()) assertNotNull(registry) } @Test - fun `an enabled periodic graph adds no job row but a one-shot does`() = runBlocking { + fun `an enabled periodic graph adds no job row but a one-shot does`() = runTest { val registry = TaskRegistry() val default = TaskConfig(true, Schedule.of(15, 0), TaskConstraints()) registry.register( @@ -133,10 +132,10 @@ class WorkManagerJobRegistryTest { val jobs = WorkManagerJobRegistry(context) scheduler.apply(TaskKey(TaskKind("git-sync"), TaskScope("g1")), TaskConfig(true, Schedule.of(60, 0), TaskConstraints())) - assertTrue(withTimeout(5_000) { jobs.jobs.first() }.isEmpty(), "periodic work carries no stelekit-job tag") + assertTrue(jobs.jobs.first().isEmpty(), "periodic work carries no stelekit-job tag") scheduler.runOnce(TaskKey(TaskKind("model-download"), TaskScope("")), TaskConstraints()) - val row = withTimeout(5_000) { jobs.jobs.first { it.isNotEmpty() } }.single() + val row = jobs.jobs.first { it.isNotEmpty() }.single() assertEquals(JobKind.ModelDownload, row.kind) assertEquals("Depth model download", row.title) } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/LegacyWorkUpgradeTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/LegacyWorkUpgradeTest.kt index db629883e..d9b759622 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/LegacyWorkUpgradeTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/LegacyWorkUpgradeTest.kt @@ -10,7 +10,7 @@ import androidx.work.workDataOf import dev.stapler.stelekit.git.GitSyncWorker import dev.stapler.stelekit.git.GitSyncWorkerBinding import dev.stapler.stelekit.jobs.JobKind -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -54,7 +54,7 @@ class LegacyWorkUpgradeTest { .build() @Test - fun apply_should_updateInPlaceKeepingIdPeriodicAndWorkerClass_When_PreUpgradeJobExists() = runBlocking { + fun apply_should_updateInPlaceKeepingIdPeriodicAndWorkerClass_When_PreUpgradeJobExists() = runTest { val legacy = legacyRequest(15) h.wm.enqueueUniquePeriodicWork(name, ExistingPeriodicWorkPolicy.UPDATE, legacy).result.get() assertTrue(assertNotNull(h.active(name)).tags.none { it.startsWith("stelekit-sched-scope:") }, "precondition: legacy job has no scope tag") @@ -74,7 +74,7 @@ class LegacyWorkUpgradeTest { } @Test - fun apply_should_replaceStaleInputInterval_When_StoredIntervalDiffers() = runBlocking { + fun apply_should_replaceStaleInputInterval_When_StoredIntervalDiffers() = runTest { val legacy = legacyRequest(15) h.wm.enqueueUniquePeriodicWork(name, ExistingPeriodicWorkPolicy.UPDATE, legacy).result.get() assertEquals(15L, h.spec(legacy.id).second.getLong(GitSyncWorker.KEY_INTERVAL_MINUTES, -1)) @@ -85,7 +85,7 @@ class LegacyWorkUpgradeTest { } @Test - fun apply_should_leaveJobEnqueued_When_ConvertingPreUpgradeJob() = runBlocking { + fun apply_should_leaveJobEnqueued_When_ConvertingPreUpgradeJob() = runTest { // The RUNNING-UPDATE outcome (ADR-002 outcome 5) is proven by WorkManagerJitterSpikeTest; here an ENQUEUED legacy job stays active. h.wm.enqueueUniquePeriodicWork(name, ExistingPeriodicWorkPolicy.UPDATE, legacyRequest(15)).result.get() scheduler.apply(key, TaskConfig(true, Schedule.of(45, 0), TaskConstraints())) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduleStartupTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduleStartupTest.kt index c9fe73845..d6bc5555e 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduleStartupTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduleStartupTest.kt @@ -5,10 +5,10 @@ package dev.stapler.stelekit.jobs.schedule import dev.stapler.stelekit.git.GitSyncWorkerBinding import dev.stapler.stelekit.jobs.JobKind -import kotlinx.coroutines.runBlocking import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequestBuilder import dev.stapler.stelekit.git.GitCloneWorker +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -78,7 +78,7 @@ class ScheduleStartupTest { private fun live(key: TaskKey) = h.active(key.workName()) @Test - fun run_should_migrateActiveGraphOnlyAndChangeNothingOnSecondStart_When_LegacyFlagTrue() = runBlocking { + fun run_should_migrateActiveGraphOnlyAndChangeNothingOnSecondStart_When_LegacyFlagTrue() = runTest { startup().run() assertEquals(listOf(g1), seededKeys, "only the active graph, only periodic kinds, are seeded") assertTrue(store().read(g1).enabled) @@ -97,7 +97,7 @@ class ScheduleStartupTest { } @Test - fun run_should_resumeStalePausedSnapshot_When_NoCloneWorkIsLive() = runBlocking { + fun run_should_resumeStalePausedSnapshot_When_NoCloneWorkIsLive() = runTest { val ledger = AppliedConfigLedger(settings) ledger.recordApplied(g1, cfg) ledger.snapshotPaused(g1, cfg) @@ -109,7 +109,7 @@ class ScheduleStartupTest { } @Test - fun run_should_stayPaused_When_CloneWorkIsLive() = runBlocking { + fun run_should_stayPaused_When_CloneWorkIsLive() = runTest { val ledger = AppliedConfigLedger(settings) ledger.recordApplied(g1, cfg) ledger.snapshotPaused(g1, cfg) @@ -121,7 +121,7 @@ class ScheduleStartupTest { } @Test - fun reapplyAll_should_enqueueFromLedger_When_ForceStopWipedWorkManager() = runBlocking { + fun reapplyAll_should_enqueueFromLedger_When_ForceStopWipedWorkManager() = runTest { AppliedConfigLedger(settings).recordApplied(g1, cfg) assertNull(live(g1)) val report = startup().run() @@ -131,7 +131,7 @@ class ScheduleStartupTest { } @Test - fun reapplyAll_should_leaveLiveWorkUntouched_When_AlreadyScheduled() = runBlocking { + fun reapplyAll_should_leaveLiveWorkUntouched_When_AlreadyScheduled() = runTest { scheduler().apply(g1, cfg) val before = live(g1)!!.id val report = startup().run() @@ -140,7 +140,7 @@ class ScheduleStartupTest { } @Test - fun reapplyAll_should_neverCallSeedOrOpenGraphDb_When_LedgerHasEntries() = runBlocking { + fun reapplyAll_should_neverCallSeedOrOpenGraphDb_When_LedgerHasEntries() = runTest { AppliedConfigLedger(settings).recordApplied(g2, cfg) startup(active = null).run() assertNotNull(live(g2)) @@ -148,7 +148,7 @@ class ScheduleStartupTest { } @Test - fun run_should_enqueueNothingAndNotCrash_When_KnownScopesUnknownOrSettingsThrow() = runBlocking { + fun run_should_enqueueNothingAndNotCrash_When_KnownScopesUnknownOrSettingsThrow() = runTest { AppliedConfigLedger(settings).recordApplied(g1, cfg) startup(known = KnownScopesResult.Unknown).run() assertNull(live(g1)) @@ -165,7 +165,7 @@ class ScheduleStartupTest { } @Test - fun run_should_runReconcileFailClosed_When_ReconcileThrows() = runBlocking { + fun run_should_runReconcileFailClosed_When_ReconcileThrows() = runTest { AppliedConfigLedger(settings).recordApplied(g1, cfg) val report = startup(reconcile = { error("boom") }).run() assertEquals(emptySet(), report.cancelledScopes) @@ -173,7 +173,7 @@ class ScheduleStartupTest { } @Test - fun run_should_cancelOrphansViaReconciler_When_KnownScopesKnown() = runBlocking { + fun run_should_cancelOrphansViaReconciler_When_KnownScopesKnown() = runTest { val s = scheduler() s.apply(g1, cfg) s.apply(TaskKey(kind, TaskScope("ghost")), cfg) @@ -185,7 +185,7 @@ class ScheduleStartupTest { } @Test - fun run_should_doNothing_When_WorkManagerNotReady() = runBlocking { + fun run_should_doNothing_When_WorkManagerNotReady() = runTest { AppliedConfigLedger(settings).recordApplied(g1, cfg) val report = startup(ready = false).run() assertEquals(ScheduleStartupReport(), report) @@ -194,7 +194,7 @@ class ScheduleStartupTest { } @Test - fun run_should_openNoNonActiveGraphDbAndMakeNoNetworkCall_When_StartupRuns() = runBlocking { + fun run_should_openNoNonActiveGraphDbAndMakeNoNetworkCall_When_StartupRuns() = runTest { // Startup only touches Settings, the ledger and WorkManager; its constructor takes no graph or network port. val report = startup(active = "g1").run() assertEquals(setOf(g1), report.migrated) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduledTaskReconcilerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduledTaskReconcilerTest.kt index f6ce1bc23..66d2376bb 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduledTaskReconcilerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/ScheduledTaskReconcilerTest.kt @@ -3,7 +3,7 @@ package dev.stapler.stelekit.jobs.schedule -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -43,7 +43,7 @@ class ScheduledTaskReconcilerTest { private fun live(scope: String) = h.active(TaskKey(git, TaskScope(scope)).workName()) @Test - fun reconcile_should_cancelOnlyAbsentScopes_When_KnownNonEmpty() = runBlocking { + fun reconcile_should_cancelOnlyAbsentScopes_When_KnownNonEmpty() = runTest { seed("g1", "ghost") val cancelled = ScheduledTaskReconciler(h.context) { KnownScopesResult.Known(setOf(TaskScope("g1"))) }.reconcile() assertEquals(setOf(TaskScope("ghost")), cancelled) @@ -52,7 +52,7 @@ class ScheduledTaskReconcilerTest { } @Test - fun reconcile_should_cancelNothingAndWriteNoTombstone_When_Unknown() = runBlocking { + fun reconcile_should_cancelNothingAndWriteNoTombstone_When_Unknown() = runTest { seed("g1", "ghost") val cancelled = ScheduledTaskReconciler(h.context) { KnownScopesResult.Unknown }.reconcile() assertEquals(emptySet(), cancelled) @@ -62,7 +62,7 @@ class ScheduledTaskReconcilerTest { } @Test - fun reconcile_should_cancelNothing_When_KnownIsEmptyOrSourceThrows() = runBlocking { + fun reconcile_should_cancelNothing_When_KnownIsEmptyOrSourceThrows() = runTest { seed("ghost") assertEquals(emptySet(), ScheduledTaskReconciler(h.context) { KnownScopesResult.Known(emptySet()) }.reconcile()) assertEquals(emptySet(), ScheduledTaskReconciler(h.context) { error("unreadable") }.reconcile()) @@ -70,7 +70,7 @@ class ScheduledTaskReconcilerTest { } @Test - fun reconcile_should_neverCancelAppWideScope_When_ScopeEmpty() = runBlocking { + fun reconcile_should_neverCancelAppWideScope_When_ScopeEmpty() = runTest { scheduler().apply(TaskKey(TaskKind("model-download"), TaskScope("")), TaskConfig(true, Schedule.of(60, 0), TaskConstraints())) seed("g1") ScheduledTaskReconciler(h.context) { KnownScopesResult.Known(setOf(TaskScope("g1"))) }.reconcile() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt index 81a7f641f..d7ac037d3 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt @@ -11,7 +11,7 @@ import androidx.work.testing.TestListenableWorkerBuilder import androidx.work.workDataOf import dev.stapler.stelekit.platform.Settings import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -130,18 +130,17 @@ class TaskWorkerTest { *(if (policy != null) arrayOf(TaskWorkKeys.KEY_NETWORK_POLICY to policy) else emptyArray()), ) - private fun run(key: TaskKey, policy: String? = null, attempt: Int = 0): Result = runBlocking { + private suspend fun run(key: TaskKey, policy: String? = null, attempt: Int = 0): Result = TestListenableWorkerBuilder(context) .setInputData(input(key, policy)) .setRunAttemptCount(attempt) .build() .doWork() - } private fun Result.error(): String? = (this as? Result.Failure)?.outputData?.getString(TaskWorkKeys.KEY_ERROR) @Test - fun doWork_should_skipMeteredAndSucceed_When_periodicUnmeteredPolicyOnMeteredNetwork() = runBlocking { + fun doWork_should_skipMeteredAndSucceed_When_periodicUnmeteredPolicyOnMeteredNetwork() = runTest { registerPeriodic(); enablePeriodic(NetworkPolicy.Unmetered) network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = true) } assertEquals(Result.success(), run(periodicKey)) @@ -150,7 +149,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_skipUnknownNetwork_When_providerThrows() = runBlocking { + fun doWork_should_skipUnknownNetwork_When_providerThrows() = runTest { registerPeriodic(); enablePeriodic(NetworkPolicy.Unmetered) network = NetworkSnapshotProvider { throw IllegalStateException("no connectivity manager") } assertEquals(Result.success(), run(periodicKey)) @@ -159,7 +158,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_skipUnknownNetwork_When_isMeteredNull() = runBlocking { + fun doWork_should_skipUnknownNetwork_When_isMeteredNull() = runTest { registerPeriodic(); enablePeriodic(NetworkPolicy.Unmetered) network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = null) } assertEquals(Result.success(), run(periodicKey)) @@ -168,7 +167,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_retryBelowCapThenFailTerminal_When_oneShotSkippedForMetered() { + fun doWork_should_retryBelowCapThenFailTerminal_When_oneShotSkippedForMetered() = runTest { registerOneShot() network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = true) } assertEquals(Result.retry(), run(oneShotKey, "unmetered", attempt = 0)) @@ -180,7 +179,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_shareOneBudget_When_skipsThenTransientFailuresMix() { + fun doWork_should_shareOneBudget_When_skipsThenTransientFailuresMix() = runTest { registerOneShot() network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = true) } repeat(3) { assertEquals(Result.retry(), run(oneShotKey, "unmetered", attempt = it)) } @@ -193,7 +192,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_failClosed_When_oneShotMeteredUnknownEvenIfConstraintSatisfied() { + fun doWork_should_failClosed_When_oneShotMeteredUnknownEvenIfConstraintSatisfied() = runTest { registerOneShot() network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = null) } assertEquals(Result.retry(), run(oneShotKey, "unmetered", attempt = 0)) @@ -202,28 +201,28 @@ class TaskWorkerTest { } @Test - fun doWork_should_failWithoutRetry_When_failedNotRetryable() { + fun doWork_should_failWithoutRetry_When_failedNotRetryable() = runTest { registerOneShot() bodyResult = { TaskRunResult.Failed("auth", retryable = false) } assertEquals("auth", run(oneShotKey, "any").error()) } @Test - fun doWork_should_retry_When_oneShotFailedRetryable() { + fun doWork_should_retry_When_oneShotFailedRetryable() = runTest { registerOneShot() bodyResult = { TaskRunResult.Failed("net", retryable = true) } assertEquals(Result.retry(), run(oneShotKey, "any")) } @Test - fun doWork_should_neverRetry_When_periodicFailedEvenIfRetryable() = runBlocking { + fun doWork_should_neverRetry_When_periodicFailedEvenIfRetryable() = runTest { registerPeriodic(); enablePeriodic() bodyResult = { TaskRunResult.Failed("net", retryable = true) } assertTrue(run(periodicKey) is Result.Failure) } @Test - fun doWork_should_recordFailedAndReturnFailure_When_bodyThrowsOutOfMemoryError() = runBlocking { + fun doWork_should_recordFailedAndReturnFailure_When_bodyThrowsOutOfMemoryError() = runTest { registerPeriodic(); enablePeriodic() bodyResult = { throw OutOfMemoryError("boom") } assertTrue(run(periodicKey) is Result.Failure) @@ -231,7 +230,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_rethrow_When_bodyThrowsCancellationException() = runBlocking { + fun doWork_should_rethrow_When_bodyThrowsCancellationException() = runTest { registerPeriodic(); enablePeriodic() bodyResult = { throw CancellationException("cancelled") } assertFailsWith { run(periodicKey) } @@ -239,7 +238,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_recordCancelledRun_When_bodyThrowsCancellationException() = runBlocking { + fun doWork_should_recordCancelledRun_When_bodyThrowsCancellationException() = runTest { registerPeriodic(); enablePeriodic() bodyResult = { throw CancellationException("cancelled") } assertFailsWith { run(periodicKey) } @@ -247,7 +246,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_truncateErrorToWorkManagerDataLimit_When_failureMessageIsHuge() { + fun doWork_should_truncateErrorToWorkManagerDataLimit_When_failureMessageIsHuge() = runTest { registerOneShot(cap = 1) bodyResult = { TaskRunResult.Failed("x".repeat(50_000), retryable = false) } val result = run(oneShotKey, "unmetered") @@ -257,7 +256,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_redactCredentialsFromOutputAndRecord_When_bodyThrowsWithSecretInMessage() { + fun doWork_should_redactCredentialsFromOutputAndRecord_When_bodyThrowsWithSecretInMessage() = runTest { registerOneShot(cap = 1) bodyResult = { throw IllegalStateException("fetch https://user:hunter2pw@example.com/r.git ghp_AbCdEf0123456789xyz") } val result = run(oneShotKey, "unmetered") @@ -268,13 +267,13 @@ class TaskWorkerTest { } @Test - fun doWork_should_succeedWithNotRegisteredRecord_When_registryEmpty() { + fun doWork_should_succeedWithNotRegisteredRecord_When_registryEmpty() = runTest { assertEquals(Result.success(), run(periodicKey)) assertEquals(listOf(TaskRunResult.Skipped("task-not-registered")), runLog.results) } @Test - fun doWork_should_shortCircuitDisabledWithoutSeed_When_periodicEntryExists() = runBlocking { + fun doWork_should_shortCircuitDisabledWithoutSeed_When_periodicEntryExists() = runTest { registerPeriodic(); enablePeriodic(enabled = false) assertEquals(Result.success(), run(periodicKey)) assertEquals(0, bodyCalls) @@ -283,7 +282,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_neverCallSeedForExistingEntry_When_periodicRuns() = runBlocking { + fun doWork_should_neverCallSeedForExistingEntry_When_periodicRuns() = runTest { registerPeriodic(); enablePeriodic() assertEquals(Result.success(), run(periodicKey)) assertEquals(0, seedCalls) @@ -291,7 +290,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_callSeedOnce_When_entryAndMarkerBothAbsent() { + fun doWork_should_callSeedOnce_When_entryAndMarkerBothAbsent() = runTest { registerPeriodic() run(periodicKey) assertEquals(1, seedCalls) @@ -299,7 +298,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_runBody_When_oneShotHasNoStoreEntry() { + fun doWork_should_runBody_When_oneShotHasNoStoreEntry() = runTest { registerOneShot() assertEquals(Result.success(), run(oneShotKey, "unmetered")) assertEquals(1, bodyCalls) @@ -307,7 +306,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_runBody_When_oneShotEntryExplicitlyDisabled() = runBlocking { + fun doWork_should_runBody_When_oneShotEntryExplicitlyDisabled() = runTest { registerOneShot() TaskSettingsStore(settings, LegacyConfigSeed.None, registry) .write(oneShotKey, TaskEntry(false, TaskOverrides(null, TaskConstraints(NetworkPolicy.Unmetered)))) @@ -317,7 +316,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_useInputPolicyNotStore_When_oneShotInputAnyOverStoredUnmetered() = runBlocking { + fun doWork_should_useInputPolicyNotStore_When_oneShotInputAnyOverStoredUnmetered() = runTest { registerOneShot() TaskSettingsStore(settings, LegacyConfigSeed.None, registry) .write(oneShotKey, TaskEntry(true, TaskOverrides(null, TaskConstraints(NetworkPolicy.Unmetered)))) @@ -327,7 +326,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_failClosedToUnmetered_When_oneShotInputPolicyAbsent() { + fun doWork_should_failClosedToUnmetered_When_oneShotInputPolicyAbsent() = runTest { registerOneShot() network = NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = true) } assertEquals(Result.retry(), run(oneShotKey, policy = null)) @@ -335,7 +334,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_skipSettingsUnreadableAndSetHealth_When_periodicReadFails() = runBlocking { + fun doWork_should_skipSettingsUnreadableAndSetHealth_When_periodicReadFails() = runTest { registerPeriodic() settings.failReads = true assertEquals(Result.success(), run(periodicKey)) @@ -345,7 +344,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_clearHealth_When_nextPeriodicReadSucceeds() = runBlocking { + fun doWork_should_clearHealth_When_nextPeriodicReadSucceeds() = runTest { registerPeriodic(); enablePeriodic() health.recordFailure(5L) run(periodicKey) @@ -353,7 +352,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_skipColdPathNotAllowed_When_specDisallowsIt() = runBlocking { + fun doWork_should_skipColdPathNotAllowed_When_specDisallowsIt() = runTest { registerPeriodic(allowedInColdPath = false); enablePeriodic() assertEquals(Result.success(), run(periodicKey)) assertEquals(0, bodyCalls) @@ -361,7 +360,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_cancelOwnWorkAndSucceed_When_scopeAbsentFromKnownRegistry() = runBlocking { + fun doWork_should_cancelOwnWorkAndSucceed_When_scopeAbsentFromKnownRegistry() = runTest { registerPeriodic(); enablePeriodic() knownScopes = KnownScopes { KnownScopesResult.Known(setOf(TaskScope("other"))) } val ghost = TaskKey(periodicKind, TaskScope("ghost")) @@ -377,7 +376,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_runTask_When_knownScopesUnknownOrThrowing() = runBlocking { + fun doWork_should_runTask_When_knownScopesUnknownOrThrowing() = runTest { registerPeriodic() val ghost = TaskKey(periodicKind, TaskScope("ghost")) TaskSettingsStore(settings, LegacyConfigSeed.None, registry) @@ -390,7 +389,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_neverCancelAppWideScope_When_knownScopesKnown() { + fun doWork_should_neverCancelAppWideScope_When_knownScopesKnown() = runTest { registerOneShot() knownScopes = KnownScopes { KnownScopesResult.Known(setOf(TaskScope("g1"))) } assertEquals(Result.success(), run(oneShotKey, "any")) @@ -398,7 +397,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_runHooksInOrder_When_periodicKindHasHooks() = runBlocking { + fun doWork_should_runHooksInOrder_When_periodicKindHasHooks() = runTest { registerPeriodic(); enablePeriodic() val order = mutableListOf() bodyResult = { order += "body"; TaskRunResult.Success } @@ -412,7 +411,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_skipCloneRunning_When_preRunYields() = runBlocking { + fun doWork_should_skipCloneRunning_When_preRunYields() = runTest { registerPeriodic(); enablePeriodic() hooks[periodicKind] = object : TaskAdapterHooks { override suspend fun preRun(context: Context, key: TaskKey, input: Data): String? = "clone-running" @@ -423,7 +422,7 @@ class TaskWorkerTest { } @Test - fun doWork_should_neverPromoteToForeground_When_periodicRuns() = runBlocking { + fun doWork_should_neverPromoteToForeground_When_periodicRuns() = runTest { registerPeriodic(); enablePeriodic() val promoted = mutableListOf() val deps = TaskWorkerRuntime.depsOverride!!(context) @@ -433,7 +432,7 @@ class TaskWorkerTest { } @Test - fun runTaskWork_should_promoteToForeground_When_oneShotRuns() = runBlocking { + fun runTaskWork_should_promoteToForeground_When_oneShotRuns() = runTest { registerOneShot() val promoted = mutableListOf() val deps = TaskWorkerRuntime.depsOverride!!(context) @@ -442,7 +441,7 @@ class TaskWorkerTest { } @Test - fun recordRun_should_leaveResultUnchangedAndLog_When_runLogThrowsThrowable() = runBlocking { + fun recordRun_should_leaveResultUnchangedAndLog_When_runLogThrowsThrowable() = runTest { registerPeriodic(); enablePeriodic() logOverride = ThrowingLog(OutOfMemoryError("log full")) assertEquals(Result.success(), run(periodicKey)) @@ -450,7 +449,7 @@ class TaskWorkerTest { } @Test - fun recordRun_should_swallowThrowableButRethrowCancellation() = runBlocking { + fun recordRun_should_swallowThrowableButRethrowCancellation() = runTest { val record = TaskRunRecord(periodicKey, RunSource.Background, null, 1L, TaskRunResult.Success, ConstraintState(true, false, null)) recordRun(ThrowingLog(OutOfMemoryError("x")), record) assertFailsWith { recordRun(ThrowingLog(CancellationException("c")), record) } @@ -458,7 +457,7 @@ class TaskWorkerTest { } @Test - fun recordRun_should_leaveResultUnchanged_When_realSettingsWriteThrows() = runBlocking { + fun recordRun_should_leaveResultUnchanged_When_realSettingsWriteThrows() = runTest { registerPeriodic(); enablePeriodic() val throwingSettings = MapSettings().also { it.failWrites = true } logOverride = SettingsTaskRunLog(throwingSettings) @@ -467,7 +466,7 @@ class TaskWorkerTest { } @Test - fun decodePolicy_should_failClosed_When_ValueIsUnrecognised() { + fun decodePolicy_should_failClosed_When_ValueIsUnrecognised() = runTest { assertEquals(NetworkPolicy.Any, TaskWorkKeys.decode(null)) assertEquals(NetworkPolicy.Any, TaskWorkKeys.decode("any")) assertEquals(NetworkPolicy.Unmetered, TaskWorkKeys.decode("unmetered")) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt index 90f598bfe..d4741020a 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt @@ -75,6 +75,7 @@ class WorkManagerJitterSpikeTest { workerStoppedDuringRun.set(false) try { // Poll so a stop signal from WorkManager is observable. + // Real-clock ceiling: a spike worker parked on a real executor thread, released by latch. val deadline = System.currentTimeMillis() + 10_000 while (System.currentTimeMillis() < deadline && !release.await(20, TimeUnit.MILLISECONDS)) { if (isStopped) { @@ -230,6 +231,7 @@ class WorkManagerJitterSpikeTest { enqueue(first) driver.setAllConstraintsMet(first.id) driver.setInitialDelayMet(first.id) + // Real 5 s ceiling: the latch is the signal from a real executor thread. val ran = started.await(5, TimeUnit.SECONDS) val stateWhileRunning = wm.getWorkInfoById(first.id).get().state record("running.workerStarted", ran) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConcurrencyTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConcurrencyTest.kt index 7a8ec8314..66769cfa5 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConcurrencyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConcurrencyTest.kt @@ -42,6 +42,7 @@ class WorkManagerTaskSchedulerConcurrencyTest { delegate.putString(key, value) if (key.contains(armedFor) && armed.compareAndSet(true, false)) { entered.complete(Unit) + // Real 30 s ceiling only if the test fails: blocking the writer thread is the interleaving under test. release.await(30, TimeUnit.SECONDS) } } @@ -68,6 +69,7 @@ class WorkManagerTaskSchedulerConcurrencyTest { private fun cfg(interval: Int) = TaskConfig(true, Schedule.of(interval, 0), TaskConstraints()) + // runBlocking: two real threads and a CountDownLatch-parked write; virtual time cannot interleave them @Test fun apply_should_leaveLedgerAndLiveWorkInAgreement_When_TwoInstancesApplyConcurrently() = runBlocking { val shared = ContractSettings() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConstraintsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConstraintsTest.kt index 2703fd92b..31ea99737 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConstraintsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerConstraintsTest.kt @@ -9,7 +9,7 @@ import dev.stapler.stelekit.git.GitSyncWorkerBinding import dev.stapler.stelekit.jobs.JobKind import dev.stapler.stelekit.jobs.JobTags import dev.stapler.stelekit.platform.ml.DepthModelDownloader -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -63,7 +63,7 @@ class WorkManagerTaskSchedulerConstraintsTest { TaskConfig(enabled, Schedule.of(interval, jitter), c) @Test - fun apply_should_enqueuePeriodicWorkWithReadBackIntervalFlexAndUnmetered_When_ConfigApplied() = runBlocking { + fun apply_should_enqueuePeriodicWorkWithReadBackIntervalFlexAndUnmetered_When_ConfigApplied() = runTest { scheduler.apply(g1, cfg(60, 10, TaskConstraints(NetworkPolicy.Unmetered))) val infos = h.infos(gitName) assertEquals(1, infos.size) @@ -76,7 +76,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_mapChargingAndBatteryNotLowConstraints_When_Requested() = runBlocking { + fun apply_should_mapChargingAndBatteryNotLowConstraints_When_Requested() = runTest { scheduler.apply(g1, cfg(60, 0, TaskConstraints(NetworkPolicy.Any, requiresCharging = true, batteryNotLow = true))) val c = h.active(gitName)!!.constraints assertEquals(NetworkType.CONNECTED, c.requiredNetworkType) @@ -85,7 +85,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_keepWorkIdAndName_When_IntervalChanges() = runBlocking { + fun apply_should_keepWorkIdAndName_When_IntervalChanges() = runTest { scheduler.apply(g1, cfg(60, 10)) val id = h.active(gitName)!!.id scheduler.apply(g1, cfg(120, 10)) @@ -95,7 +95,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_setFlexFromJitterAndInitialDelayFromSeed_When_JitterConfigured() = runBlocking { + fun apply_should_setFlexFromJitterAndInitialDelayFromSeed_When_JitterConfigured() = runTest { scheduler.apply(g1, cfg(60, 6)) val info = h.active(gitName)!! assertEquals(TimeUnit.MINUTES.toMillis(6), info.periodicityInfo!!.flexIntervalMillis) @@ -109,7 +109,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_removeWorkAndClearLedger_When_Disabled() = runBlocking { + fun apply_should_removeWorkAndClearLedger_When_Disabled() = runTest { val ledger = AppliedConfigLedger(ContractSettings()) val s = WorkManagerTaskScheduler(h.context, registry, TaskSettingsStore(ContractSettings(), LegacyConfigSeed.None, registry), ledger, workers = GitSyncWorkerBinding.resolver) s.apply(g1, cfg(60)) @@ -124,7 +124,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_enqueueGitSyncWorkerWithNetworkPolicyInput_When_GitSyncApplied() = runBlocking { + fun apply_should_enqueueGitSyncWorkerWithNetworkPolicyInput_When_GitSyncApplied() = runTest { scheduler.apply(g1, cfg(60, 10, TaskConstraints(NetworkPolicy.Unmetered))) val id = h.active(gitName)!!.id val (cls, input) = h.spec(id) @@ -137,7 +137,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_enqueueTaskWorkerWithKindScopeAndPolicy_When_NonGitKindApplied() = runBlocking { + fun apply_should_enqueueTaskWorkerWithKindScopeAndPolicy_When_NonGitKindApplied() = runTest { scheduler.apply(other, cfg(60, 0, TaskConstraints(NetworkPolicy.Unmetered))) val info = h.active(other.workName())!! val (cls, input) = h.spec(info.id) @@ -148,7 +148,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun describe_should_reportFlexWindowAndUpdateImmediately_When_ApplyHasJitter() = runBlocking { + fun describe_should_reportFlexWindowAndUpdateImmediately_When_ApplyHasJitter() = runTest { scheduler.apply(g1, cfg(60, 6)) val d = scheduler.describe(g1)!! assertEquals(60, d.effectiveIntervalMinutes) @@ -160,7 +160,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun tags_should_excludeStelekitJobOnPeriodicAndIncludeOnOneShot_When_RequestsBuilt() = runBlocking { + fun tags_should_excludeStelekitJobOnPeriodicAndIncludeOnOneShot_When_RequestsBuilt() = runTest { scheduler.apply(g1, cfg(60)) val periodic = h.active(gitName)!!.tags assertTrue(SchedTags.ANY in periodic) @@ -186,7 +186,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun runOnce_should_keepOrReplacePendingRequest_By_ConflictPolicy() = runBlocking { + fun runOnce_should_keepOrReplacePendingRequest_By_ConflictPolicy() = runTest { val name = DepthModelDownloader.UNIQUE_WORK_NAME scheduler.runOnce(download, TaskConstraints(NetworkPolicy.Unmetered)) val first = h.active(name)!! @@ -206,7 +206,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun runOnce_should_setBackoffOnlyWhenSpecAllowsRetries() = runBlocking { + fun runOnce_should_setBackoffOnlyWhenSpecAllowsRetries() = runTest { scheduler.runOnce(download, TaskConstraints()) val withRetry = h.active(DepthModelDownloader.UNIQUE_WORK_NAME)!! scheduler.cancel(download) @@ -219,7 +219,7 @@ class WorkManagerTaskSchedulerConstraintsTest { } @Test - fun apply_should_skipWithoutCancelling_When_NonPeriodicWorkHoldsTheName() = runBlocking { + fun apply_should_skipWithoutCancelling_When_NonPeriodicWorkHoldsTheName() = runTest { scheduler.runOnce(g1, TaskConstraints()) // stands in for a clone worker under the shared name val held = h.active(gitName)!! scheduler.apply(g1, cfg(60)) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerPauseResumeTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerPauseResumeTest.kt index 25117d7c4..d91585667 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerPauseResumeTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerTaskSchedulerPauseResumeTest.kt @@ -19,7 +19,7 @@ import androidx.work.workDataOf import dev.stapler.stelekit.git.GitSyncWorker import dev.stapler.stelekit.git.GitSyncWorkerBinding import dev.stapler.stelekit.jobs.JobKind -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -73,7 +73,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { private fun minutes(info: WorkInfo) = TimeUnit.MILLISECONDS.toMinutes(info.periodicityInfo!!.repeatIntervalMillis) @Test - fun resume_should_restoreAppliedInterval_When_PausedAfterApply() = runBlocking { + fun resume_should_restoreAppliedInterval_When_PausedAfterApply() = runTest { scheduler.apply(g1, cfg(45, 0, TaskConstraints(NetworkPolicy.Unmetered))) scheduler.pause(g1.scope) assertNull(h.active(name1), "pause cancels the work") @@ -85,7 +85,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun pause_should_cancelOnlyNamedGraph() = runBlocking { + fun pause_should_cancelOnlyNamedGraph() = runTest { scheduler.apply(g1, cfg(45)) scheduler.apply(g2, cfg(60)) scheduler.pause(g1.scope) @@ -94,7 +94,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_reenqueueFromLiveWorkInfo_When_NoLedgerOrStoreEntry_PauseTestScenario() = runBlocking { + fun resume_should_reenqueueFromLiveWorkInfo_When_NoLedgerOrStoreEntry_PauseTestScenario() = runTest { h.wm // direct enqueue through the scheduler's seed hook: no ledger, no store entry, no scope tag scheduler.seedExternalPeriodic(g1, cfg(15)) scheduler.pause(g1.scope) @@ -104,7 +104,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_restorePreUpgradeJobWithOriginalIntervalAndConstraints_When_UnmigratedAndUnrecorded() = runBlocking { + fun resume_should_restorePreUpgradeJobWithOriginalIntervalAndConstraints_When_UnmigratedAndUnrecorded() = runTest { scheduler.seedExternalPeriodic(g1, cfg(90, 0, TaskConstraints(NetworkPolicy.Unmetered, requiresCharging = true))) scheduler.pause(g1.scope) scheduler.resume(g1.scope) @@ -115,7 +115,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_restoreDirectlyEnqueuedGitSyncWorkAsEnqueuedGitSyncWorker_UniqueWorkScenario() = runBlocking { + fun resume_should_restoreDirectlyEnqueuedGitSyncWorkAsEnqueuedGitSyncWorker_UniqueWorkScenario() = runTest { val config = Configuration.Builder() .setExecutor(SynchronousExecutor()) .setClock(FixedClock()) @@ -142,7 +142,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_enqueueFromStore_When_NoSnapshotAndNoLedger() = runBlocking { + fun resume_should_enqueueFromStore_When_NoSnapshotAndNoLedger() = runTest { store.write(g1, TaskEntry(true, TaskOverrides(Schedule.of(30, 0), TaskConstraints()))) scheduler.resume(g1.scope) // Nothing was paused: resume only restores what a pause took. @@ -150,7 +150,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_enqueueNothing_When_StoreSaysDisabledEvenWithSnapshot() = runBlocking { + fun resume_should_enqueueNothing_When_StoreSaysDisabledEvenWithSnapshot() = runTest { scheduler.apply(g1, cfg(45)) scheduler.pause(g1.scope) store.write(g1, TaskEntry(false, null)) @@ -159,7 +159,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_restoreSnapshot_When_StoreEntryEnabled() = runBlocking { + fun resume_should_restoreSnapshot_When_StoreEntryEnabled() = runTest { scheduler.apply(g1, cfg(45)) store.write(g1, TaskEntry(true, TaskOverrides(Schedule.of(120, 0), TaskConstraints()))) scheduler.pause(g1.scope) @@ -168,7 +168,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_consumeSnapshot_When_Restored() = runBlocking { + fun resume_should_consumeSnapshot_When_Restored() = runTest { scheduler.apply(g1, cfg(45)) scheduler.pause(g1.scope) scheduler.resume(g1.scope) @@ -179,7 +179,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun pause_should_notOverwriteSnapshot_When_SecondPauseFindsNonPeriodicWork() = runBlocking { + fun pause_should_notOverwriteSnapshot_When_SecondPauseFindsNonPeriodicWork() = runTest { scheduler.apply(g1, cfg(45)) scheduler.pause(g1.scope) val ledger = AppliedConfigLedger(ledgerSettings) @@ -194,7 +194,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun pause_should_cancelAndResumeFromMemory_When_SnapshotWriteThrows() = runBlocking { + fun pause_should_cancelAndResumeFromMemory_When_SnapshotWriteThrows() = runTest { scheduler.apply(g1, cfg(45)) ledgerSettings.failWrites = true scheduler.pause(g1.scope) @@ -204,7 +204,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun apply_should_updateSnapshotAndEnqueueNothing_When_PausedThenResumeRestoresNewConfig() = runBlocking { + fun apply_should_updateSnapshotAndEnqueueNothing_When_PausedThenResumeRestoresNewConfig() = runTest { scheduler.apply(g1, cfg(45)) scheduler.pause(g1.scope) scheduler.apply(g1, cfg(90)) @@ -214,7 +214,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun apply_should_clearSnapshot_When_DisabledDuringPause() = runBlocking { + fun apply_should_clearSnapshot_When_DisabledDuringPause() = runTest { scheduler.apply(g1, cfg(45)) scheduler.pause(g1.scope) scheduler.apply(g1, cfg(45).copy(enabled = false)) @@ -224,7 +224,7 @@ class WorkManagerTaskSchedulerPauseResumeTest { } @Test - fun resume_should_keepRemainingInitialDelayAndConstraints_When_JitteredWorkWasPaused() = runBlocking { + fun resume_should_keepRemainingInitialDelayAndConstraints_When_JitteredWorkWasPaused() = runTest { scheduler.apply(g1, cfg(60, 6, TaskConstraints(NetworkPolicy.Unmetered))) val originalDelay = h.active(name1)!!.initialDelayMillis assertTrue(originalDelay > 0, "seeded jitter offset gives an initial delay") diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloadWorkerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloadWorkerTest.kt index 8856a1f61..162aeba6a 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloadWorkerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloadWorkerTest.kt @@ -7,7 +7,7 @@ import androidx.work.ListenableWorker import androidx.work.testing.TestListenableWorkerBuilder import androidx.work.workDataOf import com.sun.net.httpserver.HttpServer -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Test import org.junit.runner.RunWith @@ -53,7 +53,7 @@ class DepthModelDownloadWorkerTest { .build() @Test - fun `a successful run puts a ready model file in place and clears the partial`() = runBlocking { + fun `a successful run puts a ready model file in place and clears the partial`() = runTest { val result = worker().doWork() assertTrue(result is ListenableWorker.Result.Success) @@ -62,7 +62,7 @@ class DepthModelDownloadWorkerTest { } @Test - fun `a server error retries early and fails with a message after the last attempt`() = runBlocking { + fun `a server error retries early and fails with a message after the last attempt`() = runTest { status = 503 assertTrue(worker(attempt = 0).doWork() is ListenableWorker.Result.Retry) @@ -72,7 +72,7 @@ class DepthModelDownloadWorkerTest { } @Test - fun `a model that is already present finishes without touching the network`() = runBlocking { + fun `a model that is already present finishes without touching the network`() = runTest { target.parentFile!!.mkdirs() target.writeBytes(ByteArray((DepthModelStorage.MIN_MODEL_BYTES + 1).toInt())) server.stop(0) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderAbsentRaceTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderAbsentRaceTest.kt index 3d7158b6f..6782f9706 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderAbsentRaceTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderAbsentRaceTest.kt @@ -16,8 +16,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -47,7 +46,7 @@ class DepthModelDownloaderAbsentRaceTest { } @Test - fun staleAbsentSnapshot_should_notOverwriteDownloading_When_downloadStartedAfterItWasComputed() = runBlocking { + fun staleAbsentSnapshot_should_notOverwriteDownloading_When_downloadStartedAfterItWasComputed() = runTest { val reached = CompletableDeferred() val release = CompletableDeferred() val written = CompletableDeferred() @@ -68,12 +67,12 @@ class DepthModelDownloaderAbsentRaceTest { }, afterStateWrite = { written.complete(Unit) }, ) - withTimeout(10_000) { reached.await() } // snapshot computed as Absent with inFlight == 0; write held + reached.await() // snapshot computed as Absent with inFlight == 0; write held val waiting = scope.async { downloader.downloadModel() } - withTimeout(10_000) { downloader.modelState.first { it is DepthModelDownloader.ModelState.Downloading } } + downloader.modelState.first { it is DepthModelDownloader.ModelState.Downloading } release.complete(Unit) - withTimeout(10_000) { written.await() } // the released stale write has been applied (or skipped) + written.await() // the released stale write has been applied (or skipped) assertEquals(DepthModelDownloader.ModelState.Downloading(progress = -1), downloader.modelState.value) waiting.cancel() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderRaceTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderRaceTest.kt index 351800751..f8eb1d628 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderRaceTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/DepthModelDownloaderRaceTest.kt @@ -9,8 +9,7 @@ import androidx.work.testing.WorkManagerTestInitHelper import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.async import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -55,24 +54,24 @@ class DepthModelDownloaderRaceTest { } @Test - fun `SUCCEEDED before the file is visible settles to Ready, never Failed`() = runBlocking { + fun `SUCCEEDED before the file is visible settles to Ready, never Failed`() = runTest { val d = downloader(falseCount = 3) val seen = mutableListOf() val collector = async(start = CoroutineStart.UNDISPATCHED) { d.modelState.collect { seen += it } } d.onWorkSucceeded() - withTimeout(5_000) { d.modelState.first { it is DepthModelDownloader.ModelState.Ready } } + d.modelState.first { it is DepthModelDownloader.ModelState.Ready } collector.cancel() assertTrue(seen.none { it is DepthModelDownloader.ModelState.Failed }, "emitted Failed during the race: $seen") } @Test - fun `SUCCEEDED with the file never appearing eventually emits Failed`() = runBlocking { + fun `SUCCEEDED with the file never appearing eventually emits Failed`() = runTest { val d = downloader(falseCount = 0, alwaysFalse = true) d.onWorkSucceeded() - val failed = withTimeout(5_000) { d.modelState.first { it is DepthModelDownloader.ModelState.Failed } } + val failed = d.modelState.first { it is DepthModelDownloader.ModelState.Failed } assertEquals("The model file went missing after downloading. Try again.", (failed as DepthModelDownloader.ModelState.Failed).reason) } 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 7da48d162..33729876f 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 @@ -16,9 +16,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.yield -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout import org.junit.After import org.junit.Before import org.junit.Test @@ -53,12 +52,12 @@ class DepthModelDownloaderTest { private fun jobs() = WorkManager.getInstance(context).getWorkInfosForUniqueWork(DepthModelDownloader.UNIQUE_WORK_NAME).get() - private suspend fun DepthModelDownloader.awaitDownloading() = withTimeout(5_000) { + private suspend fun DepthModelDownloader.awaitDownloading() { modelState.first { it is DepthModelDownloader.ModelState.Downloading } } @Test - fun `a ready model short-circuits without enqueueing`() = runBlocking { + fun `a ready model short-circuits without enqueueing`() = runTest { val file = DepthModelStorage.modelFile(context).also { it.parentFile!!.mkdirs() } file.writeBytes(ByteArray((DepthModelStorage.MIN_MODEL_BYTES + 1).toInt())) @@ -67,7 +66,7 @@ class DepthModelDownloaderTest { } @Test - fun `a second caller re-attaches to the queued job instead of enqueueing another`() = runBlocking { + 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() @@ -81,7 +80,7 @@ class DepthModelDownloaderTest { } @Test - fun `a fresh instance after a restart sees the job that is still queued`() = runBlocking { + 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() @@ -95,7 +94,7 @@ class DepthModelDownloaderTest { } @Test - fun `cancel resolves a waiting caller and surfaces Cancelled`() = runBlocking { + fun `cancel resolves a waiting caller and surfaces Cancelled`() = runTest { val downloader = DepthModelDownloader(context) val waiting = async { downloader.downloadModel() } downloader.awaitDownloading() @@ -109,7 +108,7 @@ class DepthModelDownloaderTest { } @Test - fun `a queued-state snapshot that finishes after cancel never shows Downloading again`() = runBlocking { + fun `a queued-state snapshot that finishes after cancel never shows Downloading again`() = runTest { val gate = CompletableDeferred() val entered = CompletableDeferred() val downloader = DepthModelDownloader( @@ -120,13 +119,13 @@ class DepthModelDownloaderTest { val recorder = launch(Dispatchers.Unconfined) { downloader.modelState.collect { seen += it } } val waiting = async { downloader.downloadModel() } // The ENQUEUED emission is now suspended inside the snapshot read: the stale write we guard against. - withTimeout(5_000) { entered.await() } + entered.await() downloader.cancelDownload() gate.complete(Unit) waiting.await() // WorkManager's CANCELLED emission is applied after the stale one (collect is sequential); wait for it. - withTimeout(5_000) { downloader.modelState.first { it is DepthModelDownloader.ModelState.Cancelled } } + downloader.modelState.first { it is DepthModelDownloader.ModelState.Cancelled } recorder.cancel() val afterCancel = seen.dropWhile { it !is DepthModelDownloader.ModelState.Cancelled } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadEndToEndTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadEndToEndTest.kt index 6fc246caa..550d07a3a 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadEndToEndTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadEndToEndTest.kt @@ -16,8 +16,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -56,27 +55,27 @@ class ModelDownloadEndToEndTest { fixture.uninstall() } - private fun downloadFromCurrentSettings() = runBlocking { + private suspend fun downloadFromCurrentSettings() { val result = scope.async { fixture.downloader.downloadModel() } val work = WorkManager.getInstance(context) val id: UUID = awaitActiveWorkId(work, DepthModelDownloader.UNIQUE_WORK_NAME) fixture.downloader.awaitDownloadingState() WorkManagerTestInitHelper.getTestDriver(context)!!.setAllConstraintsMet(id) - assertTrue(withTimeout(60_000) { result.await() }.isRight()) + assertTrue(result.await().isRight()) assertContentEquals(server.payload, target.readBytes()) assertEquals(DepthModelDownloader.ModelState.Ready, fixture.downloader.modelState.value) } @Test - fun downloadModel_should_endReady_When_settingsAreEmpty() { + fun downloadModel_should_endReady_When_settingsAreEmpty() = runTest { assertTrue(fixture.settings.store.keys.none { it.startsWith("task_entry_") }) downloadFromCurrentSettings() } @Test - fun downloadModel_should_endReady_When_storedEntryHasEnabledFalse() { - runBlocking { fixture.store.write(ModelDownloadTask.KEY, TaskEntry(enabled = false, overrides = null)) } + fun downloadModel_should_endReady_When_storedEntryHasEnabledFalse() = runTest { + fixture.store.write(ModelDownloadTask.KEY, TaskEntry(enabled = false, overrides = null)) downloadFromCurrentSettings() } } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadTaskTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadTaskTest.kt index 7bed78592..bd32f8fe2 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadTaskTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/ModelDownloadTaskTest.kt @@ -31,8 +31,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.first -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -73,14 +72,14 @@ class ModelDownloadTaskTest { private val scope = CoroutineScope(Dispatchers.Default) - private fun startDownload(downloader: DepthModelDownloader): Deferred<*> { + private suspend fun startDownload(downloader: DepthModelDownloader): Deferred<*> { val waiting = scope.async { downloader.downloadModel() } - runBlocking { withTimeout(5_000) { downloader.modelState.first { it is DepthModelDownloader.ModelState.Downloading } } } + downloader.awaitDownloadingState() return waiting } @Test - fun run_should_putReadyFileInPlaceAndReportProgress_When_serverServesModel() = runBlocking { + fun run_should_putReadyFileInPlaceAndReportProgress_When_serverServesModel() = runTest { val percents = mutableListOf() val result = ModelDownloadTask(context, server.url, server.sha256).run( ModelDownloadTask.KEY, ctx.copy(reportProgress = { percents += it }), @@ -93,28 +92,28 @@ class ModelDownloadTaskTest { } @Test - fun run_should_beRetryableFailure_When_serverErrors() = runBlocking { + fun run_should_beRetryableFailure_When_serverErrors() = runTest { server.status = 503 val result = ModelDownloadTask(context, server.url, server.sha256).run(ModelDownloadTask.KEY, ctx) assertTrue(result is TaskRunResult.Failed && result.retryable, "$result") } @Test - fun run_should_failTerminally_When_downloadedFileIsTooSmall() = runBlocking { + fun run_should_failTerminally_When_downloadedFileIsTooSmall() = runTest { server.body = ByteArray(1024) val result = ModelDownloadTask(context, server.url, server.sha256).run(ModelDownloadTask.KEY, ctx) assertTrue(result is TaskRunResult.Failed && !result.retryable, "$result") } @Test - fun run_should_installModel_When_checksumMatches() = runBlocking { + fun run_should_installModel_When_checksumMatches() = runTest { val result = ModelDownloadTask(context, server.url, server.sha256.uppercase()).run(ModelDownloadTask.KEY, ctx) assertEquals(TaskRunResult.Success, result) assertTrue(DepthModelStorage.isReady(target)) } @Test - fun run_should_failTerminallyAndLeaveNoFiles_When_checksumMismatches() = runBlocking { + fun run_should_failTerminallyAndLeaveNoFiles_When_checksumMismatches() = runTest { // Same size as a valid model, different bytes: only the checksum can catch it. server.body = ByteArray(server.payload.size) { 1 } val result = ModelDownloadTask(context, server.url, server.sha256).run(ModelDownloadTask.KEY, ctx) @@ -141,7 +140,7 @@ class ModelDownloadTaskTest { } @Test - fun register_should_beIdempotentAndSupplyDataSyncForeground_When_calledTwice() = runBlocking { + fun register_should_beIdempotentAndSupplyDataSyncForeground_When_calledTwice() = runTest { val registry = TaskRegistry() val foreground = TaskForegroundProvider() registerModelDownloadTask(registry, context, foreground) @@ -153,7 +152,7 @@ class ModelDownloadTaskTest { } @Test - fun downloadModel_should_tagRequestWithKindAndTitle_AndRequireStorageNotLow() { + fun downloadModel_should_tagRequestWithKindAndTitle_AndRequireStorageNotLow() = runTest { val downloader = fixture.downloader val waiting = startDownload(downloader) @@ -163,11 +162,11 @@ class ModelDownloadTaskTest { assertTrue(JobTags.ANY in request.tags) assertTrue(request.constraints.requiresStorageNotLow()) downloader.cancelDownload() - runBlocking { waiting.await() } + waiting.await() } @Test - fun downloadModel_should_useStoredConstraints_NotEnabled() = runBlocking { + fun downloadModel_should_useStoredConstraints_NotEnabled() = runTest { fixture.store.write( ModelDownloadTask.KEY, TaskEntry(enabled = false, TaskOverrides(schedule = null, constraints = TaskConstraints(NetworkPolicy.Any))), @@ -188,7 +187,7 @@ class ModelDownloadTaskTest { } @Test - fun runOnce_should_keepOrReplace_ByConflictPolicy() = runBlocking { + fun runOnce_should_keepOrReplace_ByConflictPolicy() = runTest { fixture.scheduler.runOnce(ModelDownloadTask.KEY, TaskConstraints(NetworkPolicy.Unmetered), OneShotConflict.Keep) val first = activeRequest() fixture.scheduler.runOnce(ModelDownloadTask.KEY, TaskConstraints(NetworkPolicy.Any), OneShotConflict.Keep) @@ -201,7 +200,7 @@ class ModelDownloadTaskTest { } @Test - fun downloadModel_should_defaultToUnmetered_When_storeIsEmptyOrUnreadable() = runBlocking { + fun downloadModel_should_defaultToUnmetered_When_storeIsEmptyOrUnreadable() = runTest { assertEquals(NetworkPolicy.Unmetered, ModelDownloadTask.defaultConfig.constraints.network) val empty = startDownload(fixture.downloader) assertEquals(NetworkType.UNMETERED, activeRequest().constraints.requiredNetworkType) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt index 336c83162..e4fdecba1 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt @@ -24,8 +24,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Test @@ -59,7 +59,7 @@ class OneShotSkipTest { fixture?.uninstall() } - private fun workerRun(attempt: Int): Result = runBlocking { + private suspend fun workerRun(attempt: Int): Result = TestListenableWorkerBuilder(context) .setInputData( workDataOf( @@ -71,10 +71,9 @@ class OneShotSkipTest { .setRunAttemptCount(attempt) .build() .doWork() - } @Test - fun worker_should_retryThenFailTerminalWithError_When_meteredSkipsShareTheFiveAttemptBudget() { + fun worker_should_retryThenFailTerminalWithError_When_meteredSkipsShareTheFiveAttemptBudget() = runTest { fixture = ModelDownloadFixture(context, server.url, network = NetworkSnapshot(online = true, isMetered = true)).also { it.install() } assertEquals(Result.retry(), workerRun(0)) @@ -85,7 +84,7 @@ class OneShotSkipTest { assertFalse(DepthModelStorage.modelFile(context).exists(), "the body must not run on a skip") } - private fun assertDownloadResolvesFailed(network: NetworkSnapshot, expectedReason: String) = runBlocking { + private suspend fun assertDownloadResolvesFailed(network: NetworkSnapshot, expectedReason: String) { // Cap 1 means the first skip is already terminal, so the real WorkManager chain ends without backoff timing. val f = ModelDownloadFixture(context, server.url, network = network, specTransform = { it.copy(oneShotRetryCap = 1) }) .also { it.install() } @@ -100,16 +99,20 @@ class OneShotSkipTest { f.downloader.awaitDownloadingState() WorkManagerTestInitHelper.getTestDriver(context)!!.setAllConstraintsMet(id) - val outcome = withTimeout(30_000) { result.await() } + // The terminal state is the signal; runTest's own timeout is the only wall-clock ceiling. + f.downloader.modelState.first { it is DepthModelDownloader.ModelState.Failed } + val outcome = result.await() assertTrue(outcome.isLeft()) assertEquals(DepthModelDownloader.ModelState.Failed(expectedReason), f.downloader.modelState.value) } @Test - fun downloadModel_should_resolveFailed_When_networkIsMetered() = + fun downloadModel_should_resolveFailed_When_networkIsMetered() = runTest { assertDownloadResolvesFailed(NetworkSnapshot(online = true, isMetered = true), "skipped: metered") + } @Test - fun downloadModel_should_resolveFailed_When_meteredStateIsUnknown() = + fun downloadModel_should_resolveFailed_When_meteredStateIsUnknown() = runTest { assertDownloadResolvesFailed(NetworkSnapshot(online = true, isMetered = null), "skipped: unknown-network") + } } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/WorkAwait.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/WorkAwait.kt index 205c8e74e..eb04643c2 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/WorkAwait.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/WorkAwait.kt @@ -2,20 +2,20 @@ package dev.stapler.stelekit.platform.ml import androidx.work.WorkManager import kotlinx.coroutines.flow.first -import kotlinx.coroutines.withTimeout import java.util.UUID -/** Suspends until WorkManager reports an unfinished work item under [uniqueName]; observes the DB, no polling delay. */ -internal suspend fun awaitActiveWorkId(work: WorkManager, uniqueName: String, timeoutMs: Long = 5_000): UUID = - withTimeout(timeoutMs) { - work.getWorkInfosForUniqueWorkFlow(uniqueName).first { infos -> infos.any { !it.state.isFinished } } - .first { !it.state.isFinished }.id - } +/** + * Suspends until WorkManager reports an unfinished work item under [uniqueName]; observes the DB, no polling delay. + * No `withTimeout`: under `runTest` it would expire on virtual time; the test's own timeout is the ceiling. + */ +internal suspend fun awaitActiveWorkId(work: WorkManager, uniqueName: String): UUID = + work.getWorkInfosForUniqueWorkFlow(uniqueName).first { infos -> infos.any { !it.state.isFinished } } + .first { !it.state.isFinished }.id /** * Suspends until the downloader reports `Downloading`. Release a job's constraints only after this: a job that * ends first can have its terminal state replaced by downloadModel's post-enqueue `Downloading` write. */ -internal suspend fun DepthModelDownloader.awaitDownloadingState(timeoutMs: Long = 5_000) { - withTimeout(timeoutMs) { modelState.first { it is DepthModelDownloader.ModelState.Downloading } } +internal suspend fun DepthModelDownloader.awaitDownloadingState() { + modelState.first { it is DepthModelDownloader.ModelState.Downloading } } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/ScheduledSyncSettingsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/ScheduledSyncSettingsTest.kt index 5ff691bc4..1680f2ac5 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/ScheduledSyncSettingsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/ScheduledSyncSettingsTest.kt @@ -344,6 +344,7 @@ class ScheduledSyncSettingsTest { composeTestRule.waitForIdle() } + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock private fun BackgroundTaskFixture.entryOf(graph: String = "g1") = runBlocking { store.readEntry(gitKey(graph)) } @Test @@ -388,6 +389,7 @@ class ScheduledSyncSettingsTest { composeTestRule.onNodeWithText("2 hours").performClick() composeTestRule.onNodeWithText("Unmetered networks only").performClick() composeTestRule.waitForIdle() + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock val stored = runBlocking { fixture.store.read(fixture.gitKey("g1")) } assertEquals(120, stored.schedule.intervalMinutes) assertEquals(12, stored.schedule.jitterMinutes) @@ -415,6 +417,7 @@ class ScheduledSyncSettingsTest { composeTestRule.waitForIdle() composeTestRule.onNodeWithText(COULDNT_SAVE).assertExists() composeTestRule.onNodeWithText("Any network").assertIsSelected() + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock assertEquals(NetworkPolicy.Any, runBlocking { fixture.store.read(fixture.gitKey("g1")) }.constraints.network) } @@ -433,6 +436,7 @@ class ScheduledSyncSettingsTest { @Test fun summary_should_useAdapterGapFieldsAndClamp_When_WorkManagerLikeAdapter() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock runBlocking { fixture.store.write( fixture.gitKey("g1"), @@ -505,6 +509,7 @@ class ScheduledSyncSettingsTest { @Test fun enable_should_announceFirstCheckInAboutNMin_When_SwitchTurnedOn() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock runBlocking { fixture.store.write(fixture.gitKey("g1"), TaskEntry(false, TaskOverrides(Schedule.of(5, 0), TaskConstraints()))) } showPanel(fixture) composeTestRule.onNodeWithText(SWITCH_LABEL).performClick() @@ -516,6 +521,7 @@ class ScheduledSyncSettingsTest { @Test fun switch_should_turnOffInOneTap_When_AlreadyOn() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock runBlocking { fixture.store.write(fixture.gitKey("g1"), TaskEntry(true, null)) } showPanel(fixture) composeTestRule.onNodeWithText(SWITCH_LABEL).assertIsEnabled().performClick() @@ -527,6 +533,7 @@ class ScheduledSyncSettingsTest { @Test fun resetToDefault_should_clearOverridesKeepEnabledAndApplyOnce_When_CustomRowTapped() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock runBlocking { fixture.store.write(fixture.gitKey("g1"), TaskEntry(true, TaskOverrides(Schedule.of(360, 36), TaskConstraints()))) } showPanel(fixture) composeTestRule.onNodeWithText("Reset to default").performClick() @@ -544,6 +551,7 @@ class ScheduledSyncSettingsTest { fun resetToDefault_should_keepOverridesAndShowCouldntSave_When_WriteThrows() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) val custom = TaskEntry(true, TaskOverrides(Schedule.of(360, 36), TaskConstraints())) + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock runBlocking { fixture.store.write(fixture.gitKey("g1"), custom) } showPanel(fixture) fixture.settings.failWrites = true @@ -560,6 +568,7 @@ class ScheduledSyncSettingsTest { composeTestRule.onNodeWithText(SWITCH_LABEL).assertDoesNotExist() composeTestRule.onNodeWithText("2 hours").performClick() composeTestRule.waitForIdle() + // runBlocking: seeds or reads state from a non-suspend Compose-rule test, outside any virtual clock assertEquals(120, runBlocking { fixture.store.readDefaults(GitSyncTask.KIND) }?.schedule?.intervalMinutes) assertTrue(fixture.settings.store.keys.none { it.contains("task_entry") }) assertTrue(fixture.scheduler.applied.isEmpty()) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/TaskSettingsAccessibilityAndErrorsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/TaskSettingsAccessibilityAndErrorsTest.kt index 992bab0ce..6e290cb70 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/TaskSettingsAccessibilityAndErrorsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/TaskSettingsAccessibilityAndErrorsTest.kt @@ -96,6 +96,7 @@ class TaskSettingsAccessibilityAndErrorsTest { @Test fun panel_should_keepAnAlreadyOnSwitchOperable_When_GateAppearsAfterEnabling() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: seeds state from a non-suspend Compose-rule test, outside any virtual clock kotlinx.coroutines.runBlocking { fixture.store.write(fixture.gitKey("g1"), dev.stapler.stelekit.jobs.schedule.TaskEntry(true, null)) } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ModelDownloadUiTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ModelDownloadUiTest.kt index a9a9d2a16..5165476ae 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ModelDownloadUiTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ModelDownloadUiTest.kt @@ -75,10 +75,12 @@ class ModelDownloadUiTest { private fun activeRequest() = WorkManager.getInstance(context) .getWorkInfosForUniqueWork(DepthModelDownloader.UNIQUE_WORK_NAME).get().first { !it.state.isFinished } + // runBlocking: drives a Compose rule and polls real WorkManager state, both on real time @Test fun waitingRow_should_offerDownloadNowAnywayAndReplaceWithAnyNetwork_When_networkIsMetered() = runBlocking { val downloader = fixture.downloader val waiting = scope.async { downloader.downloadModel() } + // Real 5 s ceiling: the downloader and WorkManager run on real threads alongside the Compose rule. val queued = withTimeout(5_000) { downloader.modelState.first { it is DepthModelDownloader.ModelState.Downloading && it.waitingMessage != null } } @@ -100,6 +102,7 @@ class ModelDownloadUiTest { rule.onNodeWithContentDescription("Cancel model download").assertExists() rule.onNodeWithText("Download now anyway").performClick() + // Real 5 s ceiling: the downloader and WorkManager run on real threads alongside the Compose rule. withTimeout(5_000) { while (activeRequest().id == first.id) kotlinx.coroutines.delay(20) } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt index 90a376a00..747956bf9 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt @@ -44,6 +44,7 @@ class ScheduledSyncControlsApplyTest { @After fun tearDown() { + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -51,6 +52,7 @@ class ScheduledSyncControlsApplyTest { @Test fun setEnabledFalse_should_PersistDisabledToTheGraphStoreEntry_AndLeaveLegacyFlagAlone() { val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val wired = runBlocking { WiredAppFixture.android(context, dataDir, ports = FakePlatformPorts(settings = settings)) } fixture = wired val graphId = "apply-graph" @@ -60,12 +62,16 @@ class ScheduledSyncControlsApplyTest { var controls: ScheduledSyncControls? = null composeRule.setContent { controls = rememberGraphContentScheduledSyncControls(wired.deps, null, configRepo, graphId) } + // Real-clock ceiling: the store write runs off the Compose clock, so there is no virtual signal. composeRule.waitUntil(5_000) { controls?.enabled == true } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread assertEquals(30, runBlocking { store.read(key) }.schedule.intervalMinutes, "the legacy flag and interval were migrated") composeRule.runOnIdle { controls!!.setEnabled(false) } + // Real-clock ceiling: the store write runs off the Compose clock, so there is no virtual signal. composeRule.waitUntil(5_000) { controls?.enabled == false } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread assertFalse(runBlocking { store.read(key) }.enabled, "the store entry is disabled") assertTrue(settings.getBoolean(SCHEDULED_SYNC_ENABLED_KEY, false), "the legacy flag is not rewritten") } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt index b4810fa00..36d61d5ef 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt @@ -71,6 +71,7 @@ class TaskSchedulerAndroidEntryPointTest { GitSyncWorker.runLogOverride = null GitSyncWorker.snapshotProviderOverride = null GitSyncWorker.coldPathOverride = null + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -96,6 +97,7 @@ class TaskSchedulerAndroidEntryPointTest { Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val wired = runBlocking { WiredAppFixture.android( context, @@ -109,6 +111,7 @@ class TaskSchedulerAndroidEntryPointTest { composeRule.setContent { rememberGraphContentScheduledSyncControls(wired.deps, null, configRepo, graphId) } composeRule.waitForIdle() + // Real-clock ceiling: WorkManager and the worker run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { workInfos().isNotEmpty() } ObservableEffect.assert("task-work-enqueued") { @@ -131,6 +134,7 @@ class TaskSchedulerAndroidEntryPointTest { GitSyncWorker.runLogOverride = { runLog } GitSyncWorker.snapshotProviderOverride = { NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = false) } } GitSyncWorker.coldPathOverride = ColdPathRunner { TickOutcome.Fetched } + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val wired = runBlocking { WiredAppFixture.android( context, @@ -143,6 +147,7 @@ class TaskSchedulerAndroidEntryPointTest { val configRepo = StubConfigRepository(Either.Right(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = 30))) composeRule.setContent { rememberGraphContentScheduledSyncControls(wired.deps, null, configRepo, graphId) } composeRule.waitForIdle() + // Real-clock ceiling: WorkManager and the worker run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { workInfos().isNotEmpty() } val workId = workInfos().single().id @@ -150,9 +155,12 @@ class TaskSchedulerAndroidEntryPointTest { driver.setAllConstraintsMet(workId) driver.setPeriodDelayMet(workId) val key = TaskKey(GitSyncTask.KIND, TaskScope(graphId)) + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // Real-clock ceiling: WorkManager and the worker run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { runBlocking { runLog.recent(key).isNotEmpty() } } ObservableEffect.assert("task-work-enqueued") { + // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread val record = runBlocking { runLog.recent(key) }.first() assertEquals(TaskRunResult.Partial("fetched"), record.result) assertEquals(graphId, record.key.scope.value) diff --git a/kmp/src/businessTest/resources/test-hygiene-baseline.txt b/kmp/src/businessTest/resources/test-hygiene-baseline.txt index 2e75d2bcb..34e8be73b 100644 --- a/kmp/src/businessTest/resources/test-hygiene-baseline.txt +++ b/kmp/src/businessTest/resources/test-hygiene-baseline.txt @@ -3,7 +3,6 @@ androidApp.test/dev/stapler/stelekit/CaptureActivityTargetTest.kt Thread.sleep 1 androidApp.test/dev/stapler/stelekit/CaptureViewModelTest.kt Thread.sleep 9 androidInstrumentedTest/dev/stapler/stelekit/console/spike/QueryCancelSpikeAndroidTest.kt Thread.sleep 4 androidUnitTest/dev/stapler/stelekit/git/AndroidGitCloneWorkerLauncherTest.kt Thread.sleep 1 -androidUnitTest/dev/stapler/stelekit/git/WorkManagerSyncSchedulerRetryOwnerTest.kt Thread.sleep 1 androidUnitTest/dev/stapler/stelekit/platform/SafChangeDetectorFileObserverTest.kt real-clock-delay 2 businessTest/dev/stapler/stelekit/asset/AssetIndexServiceTest.kt real-clock-delay 2 businessTest/dev/stapler/stelekit/capture/ShareInboxTest.kt Thread.sleep 4 diff --git a/kmp/src/commonMain/kotlin/dev/stapler/stelekit/git/BackgroundSyncScheduler.kt b/kmp/src/commonMain/kotlin/dev/stapler/stelekit/git/BackgroundSyncScheduler.kt index 72b8d77f2..6628a9b7f 100644 --- a/kmp/src/commonMain/kotlin/dev/stapler/stelekit/git/BackgroundSyncScheduler.kt +++ b/kmp/src/commonMain/kotlin/dev/stapler/stelekit/git/BackgroundSyncScheduler.kt @@ -8,10 +8,10 @@ package dev.stapler.stelekit.git */ interface BackgroundSyncScheduler { /** Schedule periodic sync at the given interval (minimum 15 minutes on Android). */ - fun schedule(intervalMinutes: Int) + suspend fun schedule(intervalMinutes: Int) /** Cancel any scheduled sync. */ - fun cancel() + suspend fun cancel() } /** diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/JvmGitCloneWorkerLauncherTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/JvmGitCloneWorkerLauncherTest.kt index b9a0c35ad..4f5b43e0c 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/JvmGitCloneWorkerLauncherTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/JvmGitCloneWorkerLauncherTest.kt @@ -11,9 +11,7 @@ import dev.stapler.stelekit.git.testsupport.cloningStub import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest -import kotlinx.coroutines.withTimeout import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs @@ -79,7 +77,7 @@ class JvmGitCloneWorkerLauncherTest { } @Test - fun `cancelling the launchClone() caller cancels the in-flight clone`() = runBlocking { + fun `cancelling the launchClone() caller cancels the in-flight clone`() = runTest { val started = CompletableDeferred() val cloneCancelled = CompletableDeferred() val fakeRepo = cloningStub { _, _, _, _ -> @@ -95,9 +93,9 @@ class JvmGitCloneWorkerLauncherTest { val caller = launch { launcher.launchClone("g", "https://example.invalid/g.git", "/tmp/g", GitAuth.None, {}, {}, null) } - withTimeout(5_000) { started.await() } + started.await() caller.cancel() - withTimeout(5_000) { cloneCancelled.await() } + cloneCancelled.await() } } diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt index 310d59af3..82c0d82a5 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt @@ -59,6 +59,7 @@ class ScheduledSyncOriginE2ETest { @AfterTest fun tearDown() { headless?.close() + // runBlocking: end-to-end over real git and real threads, polled on the wall clock fixture?.let { runBlocking { it.close() } } temps.forEach { it.deleteRecursively() } dataDir.deleteRecursively() @@ -69,6 +70,7 @@ class ScheduledSyncOriginE2ETest { private fun remoteTwoCommitsAhead(): Remote { val origin = BareOriginFixtures.createBareOrigin("scheduled_origin_remote_", "main").also { temps += it } val clone = File(createTempDirectory("scheduled_origin_clone_").toFile().also { temps += it }, "repo") + // runBlocking: end-to-end over real git and real threads, polled on the wall clock runBlocking { assertTrue(repository.clone(origin.absolutePath, RepoRoot(clone.absolutePath), GitAuth.None, onProgress = {}).isRight()) } Git.open(clone).use { BareOriginFixtures.setIdentity(it) } BareOriginFixtures.pushCommit(origin, "main", "journals/2026_10_08.md", "- remote one\n", "remote one") @@ -82,6 +84,7 @@ class ScheduledSyncOriginE2ETest { private fun open(remote: Remote, firstSyncConfirmed: Boolean) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) + // runBlocking: end-to-end over real git and real threads, polled on the wall clock val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -95,6 +98,7 @@ class ScheduledSyncOriginE2ETest { graphId = wired.graphManager.graphRegistry.value.activeGraphId!!.value if (firstSyncConfirmed) settings.putString("git_first_sync_confirmed_$graphId", "origin/main") val configRepo = wired.graphManager.createGitConfigRepository()!! + // runBlocking: end-to-end over real git and real threads, polled on the wall clock runBlocking { configRepo.saveConfig(remote.config.copy(graphId = graphId)) } headless = HeadlessComposition().also { composition -> composition.setContent { @@ -109,6 +113,7 @@ class ScheduledSyncOriginE2ETest { } } + // Real-clock ceiling: real git processes and scheduler threads give no virtual-time or completion signal. private fun awaitCondition(what: String, timeoutMs: Long = 60_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt index b30d267b0..2651da20c 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt @@ -71,12 +71,14 @@ class TaskSchedulerDesktopEntryPointTest { @AfterTest fun tearDown() { headless?.close() + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } private fun open(pollMinutes: Int, taskScheduler: dev.stapler.stelekit.jobs.schedule.BackgroundTaskScheduler? = null) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -89,6 +91,7 @@ class TaskSchedulerDesktopEntryPointTest { fixture = wired graphId = wired.graphManager.graphRegistry.value.activeGraphId!!.value val configRepo = wired.graphManager.createGitConfigRepository()!! + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock runBlocking { configRepo.saveConfig(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = pollMinutes)) } headless = HeadlessComposition().also { composition -> composition.setContent { @@ -102,6 +105,7 @@ class TaskSchedulerDesktopEntryPointTest { } } + // Real-clock ceiling: the scheduler loop runs on its own real dispatcher and exposes no completion signal. private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { @@ -142,6 +146,7 @@ class TaskSchedulerDesktopEntryPointTest { assertEquals(1, repo.fetches.get(), "PeriodicSyncDriver is the one tick source") assertEquals(emptyList(), counting.calls.filter { it.startsWith("apply:") }, "apply is reserved for schedulers that run when closed") + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock assertNull(runBlocking { counting.describe(TaskKey(GitSyncTask.KIND, TaskScope(graphId))) }) } @@ -149,6 +154,7 @@ class TaskSchedulerDesktopEntryPointTest { fun inProcessScheduler_should_HaveNoGitSyncWork_When_DesktopLoopRuns() { open(pollMinutes = 15) awaitCondition("the loop to start") { stack?.gitSyncService?.scheduledSyncStatus?.value?.running == true } + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock assertNull(runBlocking { fixture!!.backgroundTaskScheduler.describe(TaskKey(GitSyncTask.KIND, TaskScope(graphId))) }) } @@ -162,6 +168,7 @@ class TaskSchedulerDesktopEntryPointTest { val key = TaskKey(GitSyncTask.KIND, TaskScope(graphId)) ObservableEffect.assert("in-process-task-tick") { + // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock val records = runBlocking { SettingsTaskRunLog(settings).recent(key) } assertEquals(1, records.size, "the one in-app tick is the only run-log row") assertEquals(RunSource.Foreground, records.single().source) diff --git a/project_plans/scheduling-hygiene/research.md b/project_plans/scheduling-hygiene/research.md index d68856715..e48221594 100644 --- a/project_plans/scheduling-hygiene/research.md +++ b/project_plans/scheduling-hygiene/research.md @@ -5,7 +5,12 @@ ## 1. runBlocking in Production Scheduling Code -**Finding: CLEAN — no `runBlocking` in production scheduling source.** +**Correction (implementation): the finding below was wrong.** `androidMain/git/WorkManagerSyncScheduler.kt` +(which also defines `GitSyncWorker`) had four `runBlocking` calls; they were removed by making `schedule`, +`cancel`, `pauseFor` and `resumeFor` suspend. `DriverFactory.android.kt` also uses `runBlocking`, reached from +the cold git-sync worker; it stays, with its justification at the call site. + +~~Finding: CLEAN — no `runBlocking` in production scheduling source.~~ | File | Result | |------|--------| From b5dd14e7651a372b2128502f51673eba63e96c41 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 11:28:05 -0800 Subject: [PATCH 04/13] fix(scheduling): keep resumeFor non-cancellable so a cancelled caller cannot drop periodic sync Also corrects runBlocking justification comments found in review. --- .../stapler/stelekit/db/DriverFactory.android.kt | 1 + .../db/GraphMoveQuiesceStrategy.android.kt | 3 ++- .../stelekit/git/WorkManagerSyncScheduler.kt | 5 ++++- .../git/GitSyncSchedulingEntryPointTest.kt | 6 +++--- .../git/WorkManagerSyncSchedulerPauseTest.kt | 15 +++++++++++++++ .../stelekit/jobs/schedule/TaskWorkerTest.kt | 2 +- .../stelekit/platform/ml/OneShotSkipTest.kt | 4 +--- .../stelekit/ui/ScheduledSyncControlsApplyTest.kt | 8 ++++---- .../wiring/TaskSchedulerAndroidEntryPointTest.kt | 10 +++++----- .../stelekit/wiring/ScheduledSyncOriginE2ETest.kt | 8 ++++---- .../wiring/TaskSchedulerDesktopEntryPointTest.kt | 12 ++++++------ project_plans/scheduling-hygiene/plan.md | 2 ++ 12 files changed, 48 insertions(+), 28 deletions(-) diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt index bc41c4ea4..9bfe5bc4f 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt @@ -143,6 +143,7 @@ actual class DriverFactory actual constructor() { } if (useLibsql && dbName.startsWith("/")) { val driver = AndroidLibsqlDriver(dbName) + // runBlocking: same non-suspend createDriver constraint as the AndroidSqliteDriver path below. runBlocking { try { SteleDatabase.Schema.create(driver).await() } catch (e: CancellationException) { throw e } diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt index 467ab91ca..03803b705 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/GraphMoveQuiesceStrategy.android.kt @@ -22,6 +22,7 @@ import dev.stapler.stelekit.model.StorageMoveOperation import dev.stapler.stelekit.platform.GitWorktreeLocks import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex @@ -193,7 +194,7 @@ class AndroidGraphMoveQuiesceStrategy( override suspend fun release(op: StorageMoveOperation) { holds.remove(op.graphId)?.release() - withContext(Dispatchers.IO) { resumeBackgroundSync(op.graphId) } + withContext(NonCancellable + Dispatchers.IO) { resumeBackgroundSync(op.graphId) } } override suspend fun releaseSourceGrant(source: StorageLocation) { 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 f564fdf6e..16c66db72 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt @@ -45,7 +45,9 @@ 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] @@ -111,7 +113,8 @@ class WorkManagerSyncScheduler( * stays off. */ suspend fun resumeFor(context: Context, graphId: String) { - legacyAdapter(context).resume(TaskScope(graphId)) + // NonCancellable: resume consumes the paused snapshot before it enqueues, so a cancel in between loses the job. + withContext(NonCancellable) { 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/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt index dbb0a7365..14fb5eed8 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncSchedulingEntryPointTest.kt @@ -57,7 +57,7 @@ class GitSyncSchedulingEntryPointTest { @After fun tearDown() { - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -87,7 +87,7 @@ class GitSyncSchedulingEntryPointTest { Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android( context, @@ -131,7 +131,7 @@ class GitSyncSchedulingEntryPointTest { context, Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android( context, diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt index 27cdbfa8b..6fc10290e 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/WorkManagerSyncSchedulerPauseTest.kt @@ -8,6 +8,8 @@ import androidx.test.core.app.ApplicationProvider import androidx.work.Configuration import androidx.work.WorkInfo import androidx.work.WorkManager +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test @@ -78,6 +80,19 @@ class WorkManagerSyncSchedulerPauseTest { assertTrue(enqueuedWorkExists(), "resumeFor must re-schedule the periodic job after switchGraph() completes") } + @Test + fun resumeFor_should_RestoreThePeriodicJob_When_TheCallerIsAlreadyCancelled() = runTest { + WorkManagerSyncScheduler(context, graphId).schedule(intervalMinutes = 15) + WorkManagerSyncScheduler.pauseFor(context, graphId) + + launch { + cancel() + WorkManagerSyncScheduler.resumeFor(context, graphId) + }.join() + + assertTrue(enqueuedWorkExists(), "a cancelled caller must not leave periodic sync paused") + } + @Test fun pauseFor_should_NotAffectAnotherGraphsScheduledJob_When_OnlyOneGraphIsRelocating() = runTest { val otherGraphId = "g2" diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt index d7ac037d3..4f91b9357 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/TaskWorkerTest.kt @@ -466,7 +466,7 @@ class TaskWorkerTest { } @Test - fun decodePolicy_should_failClosed_When_ValueIsUnrecognised() = runTest { + fun decodePolicy_should_failClosed_When_ValueIsUnrecognised() { assertEquals(NetworkPolicy.Any, TaskWorkKeys.decode(null)) assertEquals(NetworkPolicy.Any, TaskWorkKeys.decode("any")) assertEquals(NetworkPolicy.Unmetered, TaskWorkKeys.decode("unmetered")) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt index e4fdecba1..cfac6564f 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/platform/ml/OneShotSkipTest.kt @@ -24,7 +24,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before @@ -99,8 +98,7 @@ class OneShotSkipTest { f.downloader.awaitDownloadingState() WorkManagerTestInitHelper.getTestDriver(context)!!.setAllConstraintsMet(id) - // The terminal state is the signal; runTest's own timeout is the only wall-clock ceiling. - f.downloader.modelState.first { it is DepthModelDownloader.ModelState.Failed } + // downloadModel() completes on the first terminal modelState, so no timeout of our own is needed. val outcome = result.await() assertTrue(outcome.isLeft()) assertEquals(DepthModelDownloader.ModelState.Failed(expectedReason), f.downloader.modelState.value) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt index 747956bf9..80b0d2ddb 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/ScheduledSyncControlsApplyTest.kt @@ -44,7 +44,7 @@ class ScheduledSyncControlsApplyTest { @After fun tearDown() { - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -52,7 +52,7 @@ class ScheduledSyncControlsApplyTest { @Test fun setEnabledFalse_should_PersistDisabledToTheGraphStoreEntry_AndLeaveLegacyFlagAlone() { val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android(context, dataDir, ports = FakePlatformPorts(settings = settings)) } fixture = wired val graphId = "apply-graph" @@ -64,14 +64,14 @@ class ScheduledSyncControlsApplyTest { composeRule.setContent { controls = rememberGraphContentScheduledSyncControls(wired.deps, null, configRepo, graphId) } // Real-clock ceiling: the store write runs off the Compose clock, so there is no virtual signal. composeRule.waitUntil(5_000) { controls?.enabled == true } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call assertEquals(30, runBlocking { store.read(key) }.schedule.intervalMinutes, "the legacy flag and interval were migrated") composeRule.runOnIdle { controls!!.setEnabled(false) } // Real-clock ceiling: the store write runs off the Compose clock, so there is no virtual signal. composeRule.waitUntil(5_000) { controls?.enabled == false } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call assertFalse(runBlocking { store.read(key) }.enabled, "the store entry is disabled") assertTrue(settings.getBoolean(SCHEDULED_SYNC_ENABLED_KEY, false), "the legacy flag is not rewritten") } diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt index 36d61d5ef..099f7a524 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerAndroidEntryPointTest.kt @@ -71,7 +71,7 @@ class TaskSchedulerAndroidEntryPointTest { GitSyncWorker.runLogOverride = null GitSyncWorker.snapshotProviderOverride = null GitSyncWorker.coldPathOverride = null - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -97,7 +97,7 @@ class TaskSchedulerAndroidEntryPointTest { Configuration.Builder().setExecutor(SynchronousExecutor()).build(), ) val settings = FakeSettings().also { it.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android( context, @@ -134,7 +134,7 @@ class TaskSchedulerAndroidEntryPointTest { GitSyncWorker.runLogOverride = { runLog } GitSyncWorker.snapshotProviderOverride = { NetworkSnapshotProvider { NetworkSnapshot(online = true, isMetered = false) } } GitSyncWorker.coldPathOverride = ColdPathRunner { TickOutcome.Fetched } - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android( context, @@ -155,12 +155,12 @@ class TaskSchedulerAndroidEntryPointTest { driver.setAllConstraintsMet(workId) driver.setPeriodDelayMet(workId) val key = TaskKey(GitSyncTask.KIND, TaskScope(graphId)) - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call // Real-clock ceiling: WorkManager and the worker run off the Compose clock, so there is no virtual signal. composeRule.waitUntil(10_000) { runBlocking { runLog.recent(key).isNotEmpty() } } ObservableEffect.assert("task-work-enqueued") { - // runBlocking: bridges a non-suspend Compose-rule test or @After; waitUntil needs the real thread + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val record = runBlocking { runLog.recent(key) }.first() assertEquals(TaskRunResult.Partial("fetched"), record.result) assertEquals(graphId, record.key.scope.value) diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt index 82c0d82a5..8aa5d1281 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt @@ -59,7 +59,7 @@ class ScheduledSyncOriginE2ETest { @AfterTest fun tearDown() { headless?.close() - // runBlocking: end-to-end over real git and real threads, polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } temps.forEach { it.deleteRecursively() } dataDir.deleteRecursively() @@ -70,7 +70,7 @@ class ScheduledSyncOriginE2ETest { private fun remoteTwoCommitsAhead(): Remote { val origin = BareOriginFixtures.createBareOrigin("scheduled_origin_remote_", "main").also { temps += it } val clone = File(createTempDirectory("scheduled_origin_clone_").toFile().also { temps += it }, "repo") - // runBlocking: end-to-end over real git and real threads, polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call runBlocking { assertTrue(repository.clone(origin.absolutePath, RepoRoot(clone.absolutePath), GitAuth.None, onProgress = {}).isRight()) } Git.open(clone).use { BareOriginFixtures.setIdentity(it) } BareOriginFixtures.pushCommit(origin, "main", "journals/2026_10_08.md", "- remote one\n", "remote one") @@ -84,7 +84,7 @@ class ScheduledSyncOriginE2ETest { private fun open(remote: Remote, firstSyncConfirmed: Boolean) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) - // runBlocking: end-to-end over real git and real threads, polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -98,7 +98,7 @@ class ScheduledSyncOriginE2ETest { graphId = wired.graphManager.graphRegistry.value.activeGraphId!!.value if (firstSyncConfirmed) settings.putString("git_first_sync_confirmed_$graphId", "origin/main") val configRepo = wired.graphManager.createGitConfigRepository()!! - // runBlocking: end-to-end over real git and real threads, polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call runBlocking { configRepo.saveConfig(remote.config.copy(graphId = graphId)) } headless = HeadlessComposition().also { composition -> composition.setContent { diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt index 2651da20c..0ebe3e464 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt @@ -71,14 +71,14 @@ class TaskSchedulerDesktopEntryPointTest { @AfterTest fun tearDown() { headless?.close() - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } private fun open(pollMinutes: Int, taskScheduler: dev.stapler.stelekit.jobs.schedule.BackgroundTaskScheduler? = null) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -91,7 +91,7 @@ class TaskSchedulerDesktopEntryPointTest { fixture = wired graphId = wired.graphManager.graphRegistry.value.activeGraphId!!.value val configRepo = wired.graphManager.createGitConfigRepository()!! - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call runBlocking { configRepo.saveConfig(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = pollMinutes)) } headless = HeadlessComposition().also { composition -> composition.setContent { @@ -146,7 +146,7 @@ class TaskSchedulerDesktopEntryPointTest { assertEquals(1, repo.fetches.get(), "PeriodicSyncDriver is the one tick source") assertEquals(emptyList(), counting.calls.filter { it.startsWith("apply:") }, "apply is reserved for schedulers that run when closed") - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call assertNull(runBlocking { counting.describe(TaskKey(GitSyncTask.KIND, TaskScope(graphId))) }) } @@ -154,7 +154,7 @@ class TaskSchedulerDesktopEntryPointTest { fun inProcessScheduler_should_HaveNoGitSyncWork_When_DesktopLoopRuns() { open(pollMinutes = 15) awaitCondition("the loop to start") { stack?.gitSyncService?.scheduledSyncStatus?.value?.running == true } - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call assertNull(runBlocking { fixture!!.backgroundTaskScheduler.describe(TaskKey(GitSyncTask.KIND, TaskScope(graphId))) }) } @@ -168,7 +168,7 @@ class TaskSchedulerDesktopEntryPointTest { val key = TaskKey(GitSyncTask.KIND, TaskScope(graphId)) ObservableEffect.assert("in-process-task-tick") { - // runBlocking: the real in-process scheduler runs on its own dispatcher and is polled on the wall clock + // runBlocking: non-suspend JUnit method; bridges a suspend setup, read or teardown call val records = runBlocking { SettingsTaskRunLog(settings).recent(key) } assertEquals(1, records.size, "the one in-app tick is the only run-log row") assertEquals(RunSource.Foreground, records.single().source) diff --git a/project_plans/scheduling-hygiene/plan.md b/project_plans/scheduling-hygiene/plan.md index 2097a80aa..943644efc 100644 --- a/project_plans/scheduling-hygiene/plan.md +++ b/project_plans/scheduling-hygiene/plan.md @@ -5,6 +5,8 @@ ## Summary +**Superseded in part:** the claim below that production code has no `runBlocking` was wrong; see the correction in research.md. + Production scheduling code has no `runBlocking` — that half of the audit is complete and needs only a brief confirmation comment in the PR. The work is entirely in the test layer: From cf7667bb73f0f7fd63bc005d3b3767babd0c6ad8 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 11:54:05 -0800 Subject: [PATCH 05/13] test(scheduling): annotate or convert the remaining runBlocking calls and long waits Sweeps every scheduling/worker test by content rather than by file name, and records the test scope in the requirements. --- .../db/AndroidGraphMoveQuiesceStrategyTest.kt | 13 +++-- .../stelekit/db/QuiesceRealFlushTest.kt | 3 +- .../git/GitSyncBusyCounterSharedWiringTest.kt | 7 ++- .../schedule/WorkManagerJitterSpikeTest.kt | 2 +- .../settings/BackgroundTasksSectionTest.kt | 6 ++ .../stapler/stelekit/ui/TaskRunLogRowsTest.kt | 2 + .../wiring/RepoGateSharedEntryPointTest.kt | 5 +- .../stelekit/wiring/WiredAppFixtureTest.kt | 2 + .../stelekit/git/ColdSyncRunnerTest.kt | 20 +++---- .../stelekit/git/EntryPointGateTest.kt | 10 ++-- .../stelekit/git/GateKeyResolutionTest.kt | 6 +- .../git/GitSyncBusyCounterFetchOnlyTest.kt | 6 +- .../stelekit/git/GitSyncCancelBoundaryTest.kt | 37 ++++++++---- .../git/GitSyncMergeUnitContainmentTest.kt | 2 + .../git/GitSyncServiceAutoCommitTest.kt | 1 + .../git/GitSyncServiceChangeBackTest.kt | 2 + .../git/GitSyncServiceChangeGuardsTest.kt | 15 +++++ .../GitSyncServiceConflictMarkerGuardTest.kt | 4 ++ .../git/GitSyncServiceFirstSyncGateTest.kt | 3 + .../git/GitSyncServiceLfsGuardTest.kt | 22 +++++++ .../git/GitSyncServicePeriodicTest.kt | 2 +- .../git/GitSyncServicePublishFailureTest.kt | 2 + .../git/GitSyncServiceRateLimitRetryTest.kt | 6 +- .../git/GitSyncServiceScheduledSyncTest.kt | 23 ++++++++ .../git/GitSyncServiceSingleFlightTest.kt | 57 ++++++++++++------- .../git/PausedRetryNowAndDurabilityTest.kt | 6 +- .../stelekit/git/ResolveGateKeyFailureTest.kt | 13 ++++- .../stelekit/git/ScheduledSyncStackE2ETest.kt | 4 +- .../git/StaleLockRecoveryFollowUpTest.kt | 8 ++- .../stelekit/git/SyncObservabilityLogTest.kt | 4 ++ .../git/SyncSingleFlightCancellationTest.kt | 12 ++-- .../stelekit/git/SyncSingleFlightModelTest.kt | 2 +- .../git/SyncSingleFlightRegressionTest.kt | 29 ++++++---- .../PostSyncProjectJobEntryPointTest.kt | 2 +- .../ui/GitSyncCoordinatorCoalesceTest.kt | 8 ++- .../stelekit/ui/GitSyncCoordinatorTest.kt | 9 ++- .../stapler/stelekit/cli/SyncMainClaimTest.kt | 6 +- .../stelekit/git/CloneEntryPointGateTest.kt | 6 +- .../stelekit/git/CrossProcessSyncChildMain.kt | 2 + .../stelekit/git/GitSyncServiceLfsJvmTest.kt | 3 + ...elekitViewModelSyncStateIntegrationTest.kt | 1 + .../ui/StelekitViewModelSyncStateTest.kt | 3 + .../wiring/DesktopTaskRootWiringTest.kt | 12 +++- .../wiring/DesktopWiredAppFixtureTest.kt | 2 + .../GitSyncServiceRegistryBalanceTest.kt | 4 ++ .../wiring/GitSyncStackEntryPointTest.kt | 3 + .../scheduling-hygiene/requirements.md | 7 +++ project_plans/scheduling-hygiene/validate.md | 3 + 48 files changed, 309 insertions(+), 98 deletions(-) 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 d47b053f5..149908a8b 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt @@ -261,9 +261,10 @@ class AndroidGraphMoveQuiesceStrategyTest { ) private suspend fun awaitCondition(what: String, condition: () -> Boolean) { - withTimeout(5_000) { while (!condition()) yield() } + 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 @Test fun quiesce_should_WaitForGateWithoutHoldingWorktreeLock_AndCompleteAfterSync() = runBlocking { val gate = RepoOpGate() @@ -283,7 +284,7 @@ class AndroidGraphMoveQuiesceStrategyTest { worktreeLock.unlock() gate.releaseOrHandOff(syncLease) - withTimeout(5_000) { job.join() } + withTimeout(5_000) { job.join() } // real-clock hang guard: awaits real threads assertTrue(done) assertEquals(SyncOrigin.Quiesce, gate.heldBy(gateKey)) assertTrue(worktreeLock.isLocked) @@ -293,6 +294,7 @@ class AndroidGraphMoveQuiesceStrategyTest { assertFalse(worktreeLock.isLocked, "release must free the worktree lock") } + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test fun quiesce_should_CoalesceTriggers_AndNeverSetRerun_While_QuiesceLeaseHeld() = runBlocking { val gate = RepoOpGate() @@ -308,6 +310,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 @Test fun quiesce_should_ReleaseLease_When_CancelledWhileWaitingForWorktreeMutex() = runBlocking { val gate = RepoOpGate() @@ -317,10 +320,10 @@ class AndroidGraphMoveQuiesceStrategyTest { val strategy = gatedStrategy(gate, target) val job = launch(Dispatchers.Default) { strategy.quiesce(op) } - withTimeout(5_000) { awaitCondition("lease taken") { gate.isHeld(gateKey) } } + withTimeout(5_000) { awaitCondition("lease taken") { gate.isHeld(gateKey) } } // real-clock hang guard: awaits real threads job.cancel(CancellationException("timeout")) - withTimeout(5_000) { job.join() } + withTimeout(5_000) { job.join() } // real-clock hang guard: awaits real threads assertFalse(gate.isHeld(gateKey), "the lease must be released when the mutex wait is cancelled") worktreeLock.unlock() @@ -328,6 +331,7 @@ class AndroidGraphMoveQuiesceStrategyTest { assertTrue(fresh != null, "a fresh sync must acquire after the cancelled quiesce") } + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test fun quiesce_should_ReleaseBothOnRelease_When_DrainReturnsError() = runBlocking { val gate = RepoOpGate() @@ -344,6 +348,7 @@ class AndroidGraphMoveQuiesceStrategyTest { assertFalse(GitWorktreeLocks.lockFor(target.shadowKey).isLocked) } + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test fun quiesce_should_UseNoGate_When_GateKeyUnresolvable() = 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 f35512396..c0db05789 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/QuiesceRealFlushTest.kt @@ -66,6 +66,7 @@ class QuiesceRealFlushTest { deleteSourceAfterVerify = true, ) + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test fun quiesce_should_NotSelfDeadlock_When_RealGitShadowFlushActorFlushRunsInDrain() = runBlocking { val worktree = GitShadowWorktree(context, "quiesce-real-${System.nanoTime()}", safRoot) @@ -85,7 +86,7 @@ class QuiesceRealFlushTest { }, ) - withTimeout(10_000) { strategy.quiesce(op) } + withTimeout(10_000) { strategy.quiesce(op) } // real-clock hang guard: awaits real threads assertTrue(queue.isEmpty(), "the drain must empty the write-back queue") assertEquals("shadow content", fs.written["$safRoot/pages/Foo.md"]) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterSharedWiringTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterSharedWiringTest.kt index 984119a04..218747788 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterSharedWiringTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterSharedWiringTest.kt @@ -160,6 +160,7 @@ class GitSyncBusyCounterSharedWiringTest { return QuiesceHarness(sharedCounter, service, strategy, entered, gate) } + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun quiesce_should_ObserveBusyState_When_SameGitSyncBusyCounterDrivesRealGitSyncServiceSync() = runBlocking { fakeOnlineNetworkMonitor() @@ -171,7 +172,7 @@ class GitSyncBusyCounterSharedWiringTest { assertTrue(!h.sharedCounter.isBusy.value, "precondition: counter starts idle") val syncJob = launch { h.service.sync("test-graph") } - withTimeout(5_000) { h.entered.await() } + withTimeout(5_000) { h.entered.await() } // real-clock hang guard: awaits real threads assertTrue(h.sharedCounter.isBusy.value, "sync() must mark the shared counter busy while in flight") var quiesceCompleted = false @@ -188,8 +189,8 @@ class GitSyncBusyCounterSharedWiringTest { // Release sync()'s suspension point — it completes via the DetachedHead error path, // decrementing the shared counter in its `finally` block exactly like a real sync. h.gate.complete(Unit) - withTimeout(5_000) { syncJob.join() } - withTimeout(5_000) { quiesceJob.join() } + withTimeout(5_000) { syncJob.join() } // real-clock hang guard: awaits real threads + withTimeout(5_000) { quiesceJob.join() } // real-clock hang guard: awaits real threads assertTrue(!h.sharedCounter.isBusy.value, "counter must be idle again once sync() finishes") assertTrue(quiesceCompleted, "quiesce() must complete once GitSyncService.sync() ends and decrements the SAME counter") diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt index d4741020a..125996131 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/jobs/schedule/WorkManagerJitterSpikeTest.kt @@ -305,7 +305,7 @@ class WorkManagerJitterSpikeTest { record("api.WorkInfo.periodicityInfo", "available (WorkInfo.periodicityInfo.repeatIntervalMillis/flexIntervalMillis)") record("api.WorkInfo.nextScheduleTimeMillis", "available") record("api.WorkInfo.initialDelayMillis", "available") - val target = clock.currentTimeMillis() + min(33) + val target = clock.currentTimeMillis() + min(33) // fake clock offset, not a wait overrideNext = target driver.setInitialDelayMet(id) driver.setAllConstraintsMet(id) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/BackgroundTasksSectionTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/BackgroundTasksSectionTest.kt index 219ca833a..260f53a55 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/BackgroundTasksSectionTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/settings/BackgroundTasksSectionTest.kt @@ -99,6 +99,7 @@ class BackgroundTasksSectionTest { fun list_should_showOneSummaryLinePerKindAndUsingDefaultOrCustomRows_When_25Graphs() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) val all = graphs(25) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { all.filterIndexed { i, _ -> i % 2 == 0 }.forEach { fixture.store.write(fixture.gitKey(it.id), TaskEntry(true, TaskOverrides(Schedule.of(360, 36), TaskConstraints()))) @@ -138,6 +139,7 @@ class BackgroundTasksSectionTest { @Test fun graphRow_should_exposeOneMergedNodeWithExactDescription_When_SemanticsRead() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { fixture.store.write(fixture.gitKey("g1"), TaskEntry(true, TaskOverrides(Schedule.of(60, 6), TaskConstraints(network = NetworkPolicy.Unmetered)))) } @@ -154,6 +156,7 @@ class BackgroundTasksSectionTest { @Test fun defaultRow_should_showAppliesToNGraphsAndWriteDefaultsNotAScope_When_Edited() { val fixture = BackgroundTaskFixture(BackgroundTaskFixture.ANDROID) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { fixture.store.write(fixture.gitKey("g2"), TaskEntry(true, TaskOverrides(Schedule.of(360, 36), TaskConstraints()))) } show(fixture, graphs(3)) rule.onNodeWithText("Git sync", substring = true).performClick() @@ -161,7 +164,9 @@ class BackgroundTasksSectionTest { rule.onNodeWithText("Default for new graphs", substring = true).performClick() rule.onNodeWithText("2 hours").performClick() rule.waitForIdle() + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call assertEquals(120, runBlocking { fixture.store.readDefaults(GitSyncTask.KIND) }?.schedule?.intervalMinutes) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call assertNull(runBlocking { fixture.store.readEntry(fixture.gitKey("g1")) }.overrides) } @@ -176,6 +181,7 @@ class BackgroundTasksSectionTest { rule.onNodeWithText("1 hour").assertDoesNotExist() rule.onNodeWithText("Any network").performClick() rule.waitForIdle() + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val entry = runBlocking { fixture.store.readEntry(BackgroundTaskFixture.MODEL_DOWNLOAD_KEY) } assertEquals(false, entry.enabled) assertNull(entry.overrides?.schedule) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt index 37eb24ba9..65268e5c4 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt @@ -82,6 +82,7 @@ class TaskRunLogRowsTest { key: TaskKey = gitKey, ) = TaskRunRecord(key, source, null, startedAtMs, result, ConstraintState(true, false, null)) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call private fun append(vararg records: TaskRunRecord) = runBlocking { records.forEach { runLog.append(it) } } private fun show(source: TaskRunLogSource, query: String = "") { @@ -207,6 +208,7 @@ class TaskRunLogRowsTest { rule.onNodeWithText("Git sync / Work notes / success").assertExists() } + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call @Test fun recentResult_should_beReadFailedWhileRecentStaysEmpty_When_SettingsReadThrows() = runBlocking { append(record(now - minute)) 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 b000f226d..ea1613dcd 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt @@ -52,6 +52,7 @@ class RepoGateSharedEntryPointTest { @After fun tearDown() { + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -83,6 +84,7 @@ class RepoGateSharedEntryPointTest { return outcome } + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test fun the_fixture_gate_is_the_one_in_the_platform_integrations() = runBlocking { val f = WiredAppFixture.android(context, dataDir).also { fixture = it } @@ -91,6 +93,7 @@ class RepoGateSharedEntryPointTest { } } + // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @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 } @@ -103,7 +106,7 @@ class RepoGateSharedEntryPointTest { ) val quiesce = async { strategy.quiesce(op) } f.repoOpGate.releaseOrHandOff(earlier) - withTimeout(QUIESCE_WAIT_MS) { quiesce.await() } + withTimeout(QUIESCE_WAIT_MS) { quiesce.await() } // real-clock hang guard: awaits real threads ObservableEffect.assert("repo-gate-shared") { assertEquals(SyncOrigin.Quiesce, f.repoOpGate.heldBy(key)) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/WiredAppFixtureTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/WiredAppFixtureTest.kt index 1cf375fd2..bc4dd901f 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/WiredAppFixtureTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/WiredAppFixtureTest.kt @@ -37,12 +37,14 @@ class WiredAppFixtureTest { @After fun tearDown() { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @Test fun wiredAppFixtureAndroid_should_ComposeRealStackFilesWithoutThrowing_And_LeaveNoServiceRegistered_When_BackendIsInMemory() { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { WiredAppFixture.android(ApplicationProvider.getApplicationContext(), dataDir) } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ColdSyncRunnerTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ColdSyncRunnerTest.kt index 2cc23f472..ae13499a6 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ColdSyncRunnerTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ColdSyncRunnerTest.kt @@ -15,7 +15,7 @@ import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.platform.Settings import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs @@ -60,7 +60,7 @@ class ColdSyncRunnerTest { ) = ColdSyncRunner(spy, StubConfigRepository(config.right()), staleness, gate, keyFor) { now } @Test - fun `exactly one fetch runs and no tree-touching call is made, whatever state the tree is in`() = runBlocking { + fun `exactly one fetch runs and no tree-touching call is made, whatever state the tree is in`() = runTest { val spy = Spy(FetchResult(true, 3).right()) val outcome = runner(spy).run(sampleConfig.graphId) @@ -70,7 +70,7 @@ class ColdSyncRunnerTest { } @Test - fun `the behind count, fetch time and fetch-only reason are persisted`() = runBlocking { + fun `the behind count, fetch time and fetch-only reason are persisted`() = runTest { runner(Spy(FetchResult(true, 5).right())).run(sampleConfig.graphId) val s = staleness.read(sampleConfig.graphId) @@ -81,13 +81,13 @@ class ColdSyncRunnerTest { } @Test - fun `a fetch with nothing new records zero behind`() = runBlocking { + fun `a fetch with nothing new records zero behind`() = runTest { runner(Spy(FetchResult(false, 0).right())).run(sampleConfig.graphId) assertEquals(0, staleness.read(sampleConfig.graphId).behindCount) } @Test - fun `a typed fetch error is recorded as the outcome and returned, never swallowed`() = runBlocking { + fun `a typed fetch error is recorded as the outcome and returned, never swallowed`() = runTest { val error = DomainError.GitError.RemoteBranchNotFound("origin", "main", emptyList()) val spy = Spy(error.left()) @@ -101,14 +101,14 @@ class ColdSyncRunnerTest { } @Test - fun `no git config means nothing to fetch`() = runBlocking { + fun `no git config means nothing to fetch`() = runTest { val spy = Spy() assertEquals(ColdSyncOutcome.NoConfig, runner(spy, config = null).run("g")) assertEquals(emptyList(), spy.calls) } @Test - fun `concurrent runs for the same repository never overlap and the losers are SyncInProgress`() = runBlocking { + fun `concurrent runs for the same repository never overlap and the losers are SyncInProgress`() = runTest { var inFlight = 0 var maxInFlight = 0 val spy = object : StubGitRepository() { @@ -132,7 +132,7 @@ class ColdSyncRunnerTest { } @Test - fun `a held gate makes the run a busy outcome with no fetch and no staleness write`() = runBlocking { + fun `a held gate makes the run a busy outcome with no fetch and no staleness write`() = runTest { val spy = Spy() val lease = gate.tryAcquire("repo-key", SyncOrigin.UiPress)!! @@ -146,7 +146,7 @@ class ColdSyncRunnerTest { } @Test - fun `an unresolvable git dir fails closed without fetching`() = runBlocking { + fun `an unresolvable git dir fails closed without fetching`() = runTest { val spy = Spy() val outcome = runner(spy, keyFor = { null }).run(sampleConfig.graphId) assertEquals(ColdSyncOutcome.Error(DomainError.GitError.SyncInProgress(null)), outcome) @@ -154,7 +154,7 @@ class ColdSyncRunnerTest { } @Test - fun `a throwing fetch still releases the gate`() = runBlocking { + fun `a throwing fetch still releases the gate`() = runTest { val boom = object : StubGitRepository() { override suspend fun fetch(config: GitConfig): Either = error("boom") } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/EntryPointGateTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/EntryPointGateTest.kt index 95de87d49..267596d05 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/EntryPointGateTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/EntryPointGateTest.kt @@ -14,7 +14,7 @@ import dev.stapler.stelekit.platform.security.CredentialStore import dev.stapler.stelekit.ui.screens.git.CloneMode import dev.stapler.stelekit.ui.screens.git.GitSetupFormSnapshot import dev.stapler.stelekit.ui.screens.git.testGitConnection -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -56,7 +56,7 @@ class EntryPointGateTest { ) @Test - fun testGitConnection_should_HoldTheGateDuringFetchAndReleaseAfter() = runBlocking { + fun testGitConnection_should_HoldTheGateDuringFetchAndReleaseAfter() = runTest { val repo = RecordingRepository(gate) val result = testGitConnection(form(), repo, CredentialStore(), gate) @@ -67,7 +67,7 @@ class EntryPointGateTest { } @Test - fun testGitConnection_should_ReturnSyncInProgressAndNotFetch_When_ASyncHoldsTheRepository() = runBlocking { + fun testGitConnection_should_ReturnSyncInProgressAndNotFetch_When_ASyncHoldsTheRepository() = runTest { val repo = RecordingRepository(gate) val hold = checkNotNull(gate.tryAcquire(checkNotNull(repo.gateKeyForRoot("/tmp/entry-point-gate-repo")), SyncOrigin.UiPress)) @@ -79,7 +79,7 @@ class EntryPointGateTest { } @Test - fun withExclusiveLease_should_RunNothing_When_TheKeyCannotBeResolved() = runBlocking { + fun withExclusiveLease_should_RunNothing_When_TheKeyCannotBeResolved() = runTest { var ran = false val result = gate.withExclusiveLease(null, SyncOrigin.Clone, DomainError.GitError.CloneFailed("no key")) { @@ -92,7 +92,7 @@ class EntryPointGateTest { } @Test - fun withExclusiveLease_should_ReleaseAndDropAQueuedFollowUp_When_APressCoalescedIntoIt() = runBlocking { + fun withExclusiveLease_should_ReleaseAndDropAQueuedFollowUp_When_APressCoalescedIntoIt() = runTest { val result = gate.withExclusiveLease("k", SyncOrigin.Clone, DomainError.GitError.CloneFailed("x")) { assertTrue(gate.requestRerun("k"), "a UI press coalescing into the clone queues one rerun") Unit.right() diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt index 7bab9ddc9..1e19ea78f 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt @@ -59,6 +59,7 @@ class GateKeyResolutionTest { gate = gate, ) + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun quiesceKey_should_EqualSyncKey_When_SameGraph() = runBlocking { val canonicalKey = assertNotNull(RepoOpGate.keyForOrNull(File(real, ".git"))) @@ -70,18 +71,19 @@ class GateKeyResolutionTest { val git = BlockingRepository(release) val svc = serviceFor(spelling, git) val run = scope.async { svc.sync("g") } - withTimeout(20_000) { git.entered.await() } + withTimeout(20_000) { git.entered.await() } // real-clock hang guard: awaits real threads assertTrue(gate.isHeld(canonicalKey), "sync under '$spelling' must hold the canonical key") assertEquals(canonicalKey, quiesceKeyFor(sampleConfig.copy(repoRoot = RepoRoot(spelling)))) assertEquals(canonicalKey, RepoOpGate.keyForOrNull(File(File(spelling), ".git")), "clone key for '$spelling'") release.complete(Unit) - withTimeout(20_000) { run.await() } + withTimeout(20_000) { run.await() } // real-clock hang guard: awaits real threads svc.shutdown() } } + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun syncKey_should_DifferForDifferentRepositories() = runBlocking { val other = File(base, "other").apply { mkdirs() } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterFetchOnlyTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterFetchOnlyTest.kt index 388e0f390..3177aa4db 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterFetchOnlyTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncBusyCounterFetchOnlyTest.kt @@ -66,6 +66,7 @@ class GitSyncBusyCounterFetchOnlyTest { ) } + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun `isBusy is true for the duration of fetchOnly`() = runBlocking { assumeTrue( @@ -88,15 +89,16 @@ class GitSyncBusyCounterFetchOnlyTest { assertFalse(counter.isBusy.value, "precondition: counter starts idle") val job = launch { service.fetchOnly("test-graph") } - withTimeout(5_000) { entered.await() } + withTimeout(5_000) { entered.await() } // real-clock hang guard: awaits real threads assertTrue(counter.isBusy.value, "isBusy must be true while fetchOnly is in flight") gate.complete(Unit) - withTimeout(5_000) { job.join() } + withTimeout(5_000) { job.join() } // real-clock hang guard: awaits real threads assertFalse(counter.isBusy.value, "counter must return to idle once fetchOnly completes") } + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun `isBusy returns to false even when fetchOnly throws`() = runBlocking { assumeTrue( 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 14e13a65e..f7e27745e 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt @@ -115,6 +115,7 @@ class GitSyncCancelBoundaryTest { latch.await() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun cancelDuringFetch_should_NotMerge_AndCancelBeforeCommitShouldNotCommit() = runBlocking { val entered = CompletableDeferred() @@ -123,7 +124,7 @@ class GitSyncCancelBoundaryTest { val svc = service(git) val run = scope.async { svc.sync("g") } - withTimeout(20_000) { entered.await() } + withTimeout(20_000) { entered.await() } // real-clock hang guard: awaits real threads run.cancel() latch.countDown() run.join() @@ -138,7 +139,7 @@ class GitSyncCancelBoundaryTest { val git2 = Repo(localChanges = true).apply { onStatus = blocking(statusEntered, statusLatch) } val svc2 = service(git2) val run2 = scope.async { svc2.sync("g") } - withTimeout(20_000) { statusEntered.await() } + withTimeout(20_000) { statusEntered.await() } // real-clock hang guard: awaits real threads run2.cancel() statusLatch.countDown() run2.join() @@ -147,6 +148,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun cancelThenImmediateRepress_should_NotOverlap_When_BlockingCallStillRunning() = runBlocking { val entered = CompletableDeferred() @@ -155,7 +157,7 @@ class GitSyncCancelBoundaryTest { val svc = service(git) val first = scope.async { svc.sync("g") } - withTimeout(20_000) { entered.await() } + withTimeout(20_000) { entered.await() } // real-clock hang guard: awaits real threads first.cancel() // Scheduled origin: a UI press would queue a follow-up rerun that re-acquires the gate after the first run ends. val second = withTimeout(20_000) { svc.sync("g", origin = SyncOrigin.Scheduled) } @@ -172,6 +174,7 @@ class GitSyncCancelBoundaryTest { assertEquals(0, git.count("fetch"), "the pipeline stops before fetch after the cancel") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun commit_should_CompleteAndPipelineStopBeforeFetch_When_CancelRequestedDuringCommit() = runBlocking { val entered = CompletableDeferred() @@ -180,7 +183,7 @@ class GitSyncCancelBoundaryTest { val svc = service(git) val run = scope.async { svc.sync("g") } - withTimeout(20_000) { entered.await() } + withTimeout(20_000) { entered.await() } // real-clock hang guard: awaits real threads run.cancel() proceed.complete(Unit) run.join() @@ -198,6 +201,7 @@ class GitSyncCancelBoundaryTest { rawContent = "<<<<<<< LOCAL\n- a\n=======\n- b\n>>>>>>> REMOTE\n", ) + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun mergeUnit_should_NotFallThroughToPush_When_ConflictOrCommitFailureExitsInsideNonCancellable() = runBlocking { val conflicted = Repo(remoteChanges = true).apply { @@ -218,6 +222,7 @@ class GitSyncCancelBoundaryTest { assertEquals(1, failing.count("abort")) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun mergeUnit_should_ReloadEveryChangedPathBeforeStopping_When_CancelArrivesRightAfterMerge() = runBlocking { val reloaded = CopyOnWriteArrayList() @@ -252,6 +257,7 @@ class GitSyncCancelBoundaryTest { return reloaded to (GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()) to fs) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveConflicts_should_ReloadResolvedFiles_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -272,6 +278,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun applyJournalMerge_should_ReloadTheFile_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -288,6 +295,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun commitLocalChanges_should_FinishTheCommit_When_CancelRequestedDuringIt() = runBlocking { val entered = CompletableDeferred() @@ -296,7 +304,7 @@ class GitSyncCancelBoundaryTest { val svc = service(git) val run = scope.async { svc.commitLocalChanges("g") } - withTimeout(20_000) { entered.await() } + withTimeout(20_000) { entered.await() } // real-clock hang guard: awaits real threads run.cancel() proceed.complete(Unit) run.join() @@ -305,6 +313,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun reloadMergedFiles_should_FlagReloadIncomplete_When_CancelledMidReload() = runBlocking { val fs = object : StubFileSystem() { @@ -320,13 +329,14 @@ 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveConflicts_should_KeepTheLease_UntilALateCommitFinishes_ThenReleaseAndClearTheFlag() = runBlocking { val late = CompletableDeferred() val git = Repo().apply { onCommit = { late.await() } } val svc = service(git).also { it.commitUnitTimeoutMs = 300 } - val result = withTimeout(20_000) { + val result = withTimeout(20_000) { // real-clock hang guard: awaits real threads svc.resolveConflicts("g", listOf(realConflict), sideResolutions = mapOf("/repo/real.md" to MergeSide.LOCAL)) } @@ -339,18 +349,19 @@ class GitSyncCancelBoundaryTest { assertEquals(1, git.count("commit.start")) late.complete(Unit) - withTimeout(20_000) { while (gate.isHeld(key()) || svc.reloadIncomplete.value) kotlinx.coroutines.delay(20) } + withTimeout(20_000) { while (gate.isHeld(key()) || svc.reloadIncomplete.value) kotlinx.coroutines.delay(20) } // real-clock hang guard: awaits real threads assertFalse(gate.isHeld(key())) assertFalse(svc.reloadIncomplete.value, "the sentinel clears when the abandoned unit ends") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_KeepTheLeaseAndNotFlagReload_When_TheMainCommitOutlivesTheWait() = runBlocking { val late = CompletableDeferred() val git = Repo(localChanges = true).apply { onCommit = { late.await() } } val svc = service(git).also { it.commitUnitTimeoutMs = 300 } - val result = withTimeout(20_000) { svc.sync("g") } + val result = withTimeout(20_000) { svc.sync("g") } // real-clock hang guard: awaits real threads assertIs(result.leftOrNull()) assertTrue(gate.isHeld(key())) @@ -358,10 +369,11 @@ class GitSyncCancelBoundaryTest { assertIs(svc.sync("g", origin = SyncOrigin.Scheduled).leftOrNull()) late.complete(Unit) - withTimeout(20_000) { while (gate.isHeld(key())) kotlinx.coroutines.delay(20) } + withTimeout(20_000) { while (gate.isHeld(key())) kotlinx.coroutines.delay(20) } // real-clock hang guard: awaits real threads } // PR #683 review m1: a later complete reload of other files must not clear an earlier incomplete one. + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun reloadIncomplete_should_StaySticky_UntilTheFailedPathsReloadCompletely() = runBlocking { val failing = java.util.concurrent.atomic.AtomicBoolean(true) @@ -404,6 +416,7 @@ class GitSyncCancelBoundaryTest { override fun observeConfig(graphId: String) = kotlinx.coroutines.flow.flowOf>(Either.Right(byGraph[graphId])) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun abandonedUnit_should_HoldOnlyItsOwnRunsLease_AndEndEverythingExactlyOnce() = runBlocking { val dirB = Files.createTempDirectory("cancel_boundary_b_").toFile() @@ -418,14 +431,14 @@ class GitSyncCancelBoundaryTest { isOnline = { true }, gate = gate, ).also { services += it; it.commitUnitTimeoutMs = 300 } - val a = withTimeout(20_000) { svc.sync("a") } + val a = withTimeout(20_000) { svc.sync("a") } // real-clock hang guard: awaits real threads assertIs(a.leftOrNull()) val keyB = checkNotNull(RepoOpGate.keyForOrNull("${dirB.absolutePath}/.git") { File(it).canonicalFile.path }) assertTrue(gate.isHeld(key()), "A's abandoned commit keeps A's lease") assertFalse(gate.isHeld(keyB), "B is a different repository and must not be held by A's unit") assertEquals(0, repo.ends[config.repoRoot.value]?.get() ?: 0, "A's record must not end while its unit runs") - val b = withTimeout(20_000) { svc.sync("b") } + val b = withTimeout(20_000) { svc.sync("b") } // real-clock hang guard: awaits real threads assertTrue(b.isRight(), "B runs independently while A's unit lingers, got $b") assertEquals(1, repo.ends[configB.repoRoot.value]?.get(), "B's record ends exactly once, on its own") assertFalse(gate.isHeld(keyB)) @@ -433,7 +446,7 @@ class GitSyncCancelBoundaryTest { assertEquals(0, repo.ends[config.repoRoot.value]?.get() ?: 0) late.complete(Unit) - withTimeout(20_000) { while (gate.isHeld(key())) kotlinx.coroutines.delay(20) } + withTimeout(20_000) { while (gate.isHeld(key())) kotlinx.coroutines.delay(20) } // real-clock hang guard: awaits real threads kotlinx.coroutines.delay(100) assertEquals(1, repo.ends[config.repoRoot.value]?.get(), "A's owner record ends exactly once") assertEquals(2, repo.begins.get(), "one claim per run") 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 c359eb508..3408e63d6 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt @@ -61,6 +61,7 @@ class GitSyncMergeUnitContainmentTest { graphLoader = GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()), ) + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun reload_should_ChunkAtMost200AndSetReloadIncomplete_When_BeginGitMergeThrows() = runBlocking { val seen = AtomicInteger() @@ -84,6 +85,7 @@ class GitSyncMergeUnitContainmentTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun reload_should_LogProgressPerChunkAndStayComplete_When_ThousandPathsReload() = runBlocking { val svc = service(pages(1000), StubFileSystem()) 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 29b47ace1..83291b7dc 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt @@ -74,6 +74,7 @@ class GitSyncServiceAutoCommitTest { ) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire 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 8028e5c99..be1d94416 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt @@ -71,6 +71,7 @@ class GitSyncServiceChangeBackTest { return service to configRepo } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `change back is refused when the previous branch is still not on the remote`() = runBlocking { val (service, configRepo) = repairedService(remoteBranches = listOf("master")) @@ -82,6 +83,7 @@ class GitSyncServiceChangeBackTest { service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `change back succeeds once the previous branch exists on the remote`() = runBlocking { val (service, configRepo) = repairedService(remoteBranches = listOf("master", "main")) 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 3829c9a60..4d86e3c68 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt @@ -103,6 +103,7 @@ class GitSyncServiceChangeGuardsTest { private val mutating = setOf("stage", "commit", "merge", "push") + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `sync in MERGING state returns RepairNeeded before any stage commit merge or push`() = runBlocking { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -116,6 +117,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a service built over an unsafe repository refuses even as a fresh instance`() = runBlocking { val spy = Spy(health = RepositoryHealth(false, "UNMERGED_PATHS")) @@ -127,6 +129,7 @@ class GitSyncServiceChangeGuardsTest { fresh.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `staged conflict markers refuse the commit and nothing is committed or pushed`() = runBlocking { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("journals/2026_10_08.md")))) @@ -142,6 +145,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `an incomplete marker scan fails closed`() = runBlocking { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Incomplete("big.md is larger than 2048 KiB"))) @@ -152,6 +156,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `markers in an existing local commit refuse the push even with a clean tree`() = runBlocking { val spy = Spy(dirty = false, markers = mutableMapOf(GuardScope.NetPush to MarkerScan.Found(listOf("a.md")))) @@ -164,6 +169,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a clean scan lets sync commit and push`() = runBlocking { val spy = Spy() @@ -174,6 +180,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `mass deletion above the default threshold blocks the commit`() = runBlocking { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(21, treeSize = 100))) @@ -187,6 +194,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `mass deletion at the push step blocks the push`() = runBlocking { val spy = Spy(deletions = mutableMapOf(GuardScope.NetPush to deletions(30, treeSize = 100))) @@ -197,6 +205,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `deletions within the threshold pass`() = runBlocking { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(20, treeSize = 100))) @@ -220,6 +229,7 @@ class GitSyncServiceChangeGuardsTest { assertEquals(10, blocked?.threshold) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `overridden thresholds change the verdict in both directions`() = runBlocking { val lowered = MapSettings().apply { putString(MassChangeThresholds.KEY_MIN_FILES, "3"); putString(MassChangeThresholds.KEY_PERCENT, "1") } @@ -244,6 +254,7 @@ class GitSyncServiceChangeGuardsTest { assertEquals(MassChangeThresholds(), MassChangeThresholds.from(settings)) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a foreground confirm lifts the mass-change guard once and a scheduled run cannot`() = runBlocking { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(40, treeSize = 100))) @@ -259,6 +270,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `commitLocalChanges is guarded by state markers and mass change`() = runBlocking { val unsafe = Spy(health = RepositoryHealth(false, "MERGING")) @@ -280,6 +292,7 @@ class GitSyncServiceChangeGuardsTest { massSvc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `resolveConflicts refuses to commit staged markers and still runs in MERGING`() = runBlocking { val spy = Spy(health = RepositoryHealth(false, "MERGING"), markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("x.md")))) @@ -292,6 +305,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `resolveConflicts commits in MERGING when the staged diff is clean`() = runBlocking { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -302,6 +316,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `applyJournalMerge guards the commit and the push`() = runBlocking { val commitBlocked = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("j.md")))) 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 502e511dc..69496bf0b 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt @@ -74,6 +74,7 @@ class GitSyncServiceConflictMarkerGuardTest { ) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `sync refuses to commit or push a file that still has conflict markers`() = runBlocking { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -88,6 +89,7 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `sync commits normally when the changed file has no conflict markers`() = runBlocking { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -121,6 +123,7 @@ class GitSyncServiceConflictMarkerGuardTest { assertEquals(null, clean.findUnresolved(sampleConfig, status)) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `applyJournalMerge refuses merged content that still has conflict markers`() = runBlocking { val calls = mutableListOf() @@ -133,6 +136,7 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `resolveConflicts refuses to commit when a resolved file still has conflict markers`() = runBlocking { val calls = mutableListOf() 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 25e544390..f3a5ba04d 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt @@ -71,6 +71,7 @@ class GitSyncServiceFirstSyncGateTest { return Fixture(service, firstSync, fetchCalls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `automatic sync is skipped while a first-sync review is pending and leaves state untouched`() = runBlocking { val f = fixture(reviewPending = true) @@ -85,6 +86,7 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `manual sync is not blocked by a pending review`() = runBlocking { val f = fixture(reviewPending = true) @@ -96,6 +98,7 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `automatic sync resumes once the review is confirmed`() = runBlocking { val f = fixture(reviewPending = true) 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 558c2d4b6..941dd7479 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt @@ -133,6 +133,7 @@ class GitSyncServiceLfsGuardTest { return Fixture(service, repo, fs, settings) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldRawBinaryAndCommitTheRest_When_AssetsAreLfsTracked() = runBlocking { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf("pages/a.md" to "# a".encodeToByteArray(), photo to png)) @@ -149,6 +150,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldUntrackedRawBinaryToo_When_FileIsNew() = runBlocking { val f = fixture(untracked = listOf(photo), modified = listOf("pages/a.md"), files = mapOf(photo to png)) @@ -159,6 +161,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldNothing_When_TrackedFileIsAValidPointer() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to pointer)) @@ -171,6 +174,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldNothing_When_TrackedFileIsEmpty() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to ByteArray(0))) @@ -181,6 +185,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_SkipTheCommit_When_EverythingStagedWasHeld() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -194,6 +199,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_NotConsultTheIndexForCommitNeed_When_NothingWasHeld() = runBlocking { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.anythingStaged = false }) @@ -204,6 +210,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HonourNestedGitattributes_When_RuleLivesInASubdirectory() = runBlocking { val f = fixture( @@ -222,6 +229,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_SeeAnUncommittedGitattributesEdit_When_TheWorkingTreeFileChanged() = runBlocking { val f = fixture(modified = listOf(".gitattributes", "x.png"), files = mapOf("x.png" to png), gitattributes = "*.png filter=lfs\n") @@ -232,6 +240,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_RefuseTheWholeCommit_When_HoldBackIsFlippedOff() = runBlocking { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { fs -> @@ -250,6 +259,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_JudgeNothing_When_ThePlatformGuardsInItsOwnWritePath() = runBlocking { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { it.files["/repo/.gitattributes"] = "* filter=lfs\n".encodeToByteArray() }, delegated = true) @@ -261,6 +271,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_NotJudgeTheWorkingFile_When_AutoModeAndACleanFilterIsActive() = runBlocking { val f = fixture( @@ -278,6 +289,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldAndUnstage_When_AutoModeFilterLeftRawBytesInTheIndex() = runBlocking { val escaped = LfsViolation("assets/b.bin", LfsViolationReason.RawBinary, ".gitattributes:1") @@ -295,6 +307,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_HoldTheWorkingFile_When_ModeIsGuardOnlyEvenIfACleanFilterIsReported() = runBlocking { val f = fixture( @@ -311,6 +324,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_FailClosed_When_TheIndexCannotBeVerified() = runBlocking { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.stagedThrows = true }) @@ -322,6 +336,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun commitLocalChanges_should_HoldRawBinaryAndStillCommit_When_AssetsAreLfsTracked() = runBlocking { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf(photo to png)) @@ -334,6 +349,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun commitLocalChanges_should_ReturnNullWithoutCommitting_When_OnlyHeldFilesChanged() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -345,6 +361,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveConflicts_should_RefuseBeforeMarkResolved_When_SideResolutionLeavesRawBinary() = runBlocking { val f = fixture(files = mapOf(photo to png)) @@ -361,6 +378,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveConflicts_should_RefuseBeforeMarkResolved_When_HunkResolutionWritesRawText() = runBlocking { val f = fixture(files = mapOf(photo to png)) @@ -376,6 +394,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveConflicts_should_StageAValidPointer_When_ResolvedSideIsAPointer() = runBlocking { val f = fixture(files = mapOf(photo to pointer)) @@ -391,6 +410,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun applyJournalMerge_should_RefuseBeforeMarkResolved_When_MergedContentLandsAtATrackedPath() = runBlocking { val f = fixture(gitattributes = "journals/** filter=lfs\n") @@ -403,6 +423,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_SurfaceRawBlobsThatWerePushedOutsideTheGuard_When_ThePushAuditFindsThem() = runBlocking { val pushed = LfsViolation("assets/sneaky.bin", LfsViolationReason.RawBinaryPushed, ".gitattributes:1") @@ -415,6 +436,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun syncState_should_ReturnToSuccess_When_TheHeldFileIsFixedBeforeTheNextSync() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png)) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePeriodicTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePeriodicTest.kt index 3ce09cecb..dbcc7b3d1 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePeriodicTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePeriodicTest.kt @@ -77,7 +77,7 @@ class GitSyncServicePeriodicTest { private fun runOneInterval(intervalMinutes: Int) { val expected = repo.fetches.get() + 1 scheduler.advanceTimeBy(intervalMinutes * 60_000L) - val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS + val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS // real-clock hang guard: awaits real threads while (!(repo.fetches.get() >= expected && service?.scheduledSyncStatus?.value?.tickInFlight == false)) { assertTrue(System.nanoTime() < deadline, "tick $expected never finished") scheduler.runCurrent() 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 9bb7a21d7..91db1f264 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt @@ -63,6 +63,7 @@ class GitSyncServicePublishFailureTest { ) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire private fun stateAfter(step: Step, error: DomainError.GitError, config: GitConfig = sampleConfig): SyncState = runBlocking { val svc = service(FailingAt(step, error), config) svc.sync("test-graph") @@ -103,6 +104,7 @@ class GitSyncServicePublishFailureTest { assertEquals(listOf("a.md"), (state as SyncState.ConflictPending).conflicts.map { it.filePath }) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `fetchOnly publishes rate limit and expiry the same way`() = runBlocking { val limited = service(FailingAt(Step.Fetch, DomainError.GitError.RateLimited(3600))) 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 aa4013456..fcbf3751a 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt @@ -97,6 +97,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `scheduleRateLimitRetry does not re-invoke fetchOnly before retryAfterSeconds elapses, then fires exactly once`() { requireOnline() + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire runBlocking { val counter = CallCounter() val repo = countingFetchRepo(counter) { count -> @@ -139,6 +140,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `shutdown cancels a pending scheduled retry before it fires`() { requireOnline() + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire runBlocking { val counter = CallCounter() val repo = countingFetchRepo(counter) { DomainError.GitError.RateLimited(retryAfterSeconds = 1).left() } @@ -160,6 +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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire runBlocking { val counter = CallCounter() // First call: rate limited (schedules a retry). Every subsequent call: success. @@ -193,6 +196,7 @@ class GitSyncServiceRateLimitRetryTest { @Test fun `sync when commit returns RateLimited schedules a retry that re-invokes sync, reaching commit again`() { requireOnline() + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire runBlocking { var commitCallCount = 0 val repo = object : StubGitRepository() { @@ -211,7 +215,7 @@ class GitSyncServiceRateLimitRetryTest { service.sync("test-graph") assertEquals(1, commitCallCount) - withTimeout(5_000) { + withTimeout(5_000) { // real-clock hang guard: awaits real threads while (commitCallCount < 2) delay(50) } assertEquals(2, commitCallCount, "the scheduled retry must re-invoke sync(), reaching commit() again") 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 f1099521e..382f77afb 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt @@ -144,6 +144,7 @@ class GitSyncServiceScheduledSyncTest { private fun policySkip(reason: ScheduledSkipReason) = TickOutcome.Skip(SkipReason.Policy(reason)) + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a held EditLock skips the tick with no repository call`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -157,6 +158,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a busy counter, a locked vault and being offline each skip with no repository call`() = runBlocking { val busy = Harness().also { it.confirmFirstSync(); it.busy.begin() } @@ -178,6 +180,7 @@ class GitSyncServiceScheduledSyncTest { offlineSvc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `an in-memory conflict skips further ticks without touching the repository`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -195,6 +198,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a fresh service over a MERGING repository skips with only a fetch`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -209,6 +213,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a fetch error while skipping for repo state is reported as a failure`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -220,6 +225,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `an unconfirmed first sync fetches only and never merges commits or pushes`() = runBlocking { val h = Harness() @@ -234,6 +240,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a confirmation stored by an earlier build is read unchanged and the next tick runs`() = runBlocking { val h = Harness() @@ -245,6 +252,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `changing the branch re-arms the first sync gate`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -256,6 +264,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a pending first-sync review blocks even a matching confirmation`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -266,6 +275,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a SAF graph, or one whose predicate throws, gets exactly one fetch`() = runBlocking { for (predicate in listOf<(RepoRoot) -> Boolean>({ false }, { error("unresolvable saf uri") })) { @@ -283,6 +293,7 @@ class GitSyncServiceScheduledSyncTest { } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `the default path predicate treats saf and content uris as not app-owned`() = runBlocking { for (root in listOf("saf://tree/notes", "content://com.android/tree/x")) { @@ -306,6 +317,7 @@ class GitSyncServiceScheduledSyncTest { } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `all clear runs sync once and merges the remote commits`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -322,6 +334,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a merged sync records lastMerged and zero behind while a fetch-only tick records only the fetch`() = runBlocking { val h = Harness(appOwned = { false }).also { it.confirmFirstSync() } @@ -347,6 +360,7 @@ class GitSyncServiceScheduledSyncTest { live.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `an app-closed marker left by the worker is cleared when the service starts`() = runBlocking { val h = Harness() @@ -356,6 +370,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `the review badge covers every unconfirmed config, not only a pending repair`() = runBlocking { val unconfirmed = Harness().service() @@ -376,6 +391,7 @@ class GitSyncServiceScheduledSyncTest { rebranched.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `autoCommit off with a dirty tree fetches only and commits nothing`() = runBlocking { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } @@ -388,6 +404,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `autoCommit off with a clean tree still syncs`() = runBlocking { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } @@ -398,6 +415,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a failed sync backs off the next ticks and the delay doubles`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -424,6 +442,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a scheduled run can never lift the mass-change guard`() = runBlocking { val h = Harness().also { it.confirmFirstSync() } @@ -439,6 +458,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a missing git config falls back to a harmless fetch tick`() = runBlocking { val spy = Spy() @@ -461,6 +481,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a vault provider that throws counts as available, like sync`() = runBlocking { val h = Harness(vaultProvider = { error("keystore unavailable") }).also { it.confirmFirstSync() } @@ -471,6 +492,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `going offline between the policy check and the sync is a skip, not a failure`() = runBlocking { val answers = ArrayDeque(listOf(true, true)) @@ -482,6 +504,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun `a review that becomes pending between the policy check and the sync is a first-sync skip`() = runBlocking { val gate = object : MapSettings() { 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 197767570..9a3251058 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt @@ -91,6 +91,7 @@ class GitSyncServiceSingleFlightTest { override suspend fun abortMerge(config: GitConfig) = Unit.right().also { calls += "abort" } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun everyMutatingEntryPoint_should_RunWithTheGateHeld_When_RepositoryAssertsIt() = runBlocking { val git = GateAssertingGitRepository(OkRepository(), gate, keyFor = { c -> checkNotNull(RepoOpGate.keyForOrNull("${c.repoRoot.value}/.git") { File(it).canonicalFile.path }) }) @@ -118,6 +119,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key()), "every entry point must release") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun gate_should_BeFreeAndSyncRunnable_When_BeginOwnedOperationThrows() = runBlocking { val git = OkRepository().apply { onBegin = { throw IllegalStateException("record write failed") } } @@ -131,6 +133,7 @@ class GitSyncServiceSingleFlightTest { assertTrue(svc.sync("g").isRight(), "a fresh sync must acquire and run") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun gate_should_BeFree_When_EndOwnedOperationThrowsAnything() = runBlocking { for (failure in listOf<() -> Throwable>({ RuntimeException("boom") }, { CancellationException("cancelled") })) { @@ -145,44 +148,46 @@ class GitSyncServiceSingleFlightTest { } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun gate_should_BeFreeAndSyncRunnable_When_RunIsCancelledMidCommit() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) val svc = service(git) git.blockAt(FakeGitOp.Commit) val first = scope.async { svc.sync("g") } - withTimeout(20_000) { git.awaitBlocked() } + withTimeout(20_000) { git.awaitBlocked() } // real-clock hang guard: awaits real threads assertTrue(gate.isHeld(key())) // The commit is non-cancellable (1.5a): cancellation lands once the blocked call returns, and the gate stays held until then. first.cancel() assertTrue(gate.isHeld(key()), "the gate is held while the blocking call runs") git.releaseBlocked() - withTimeout(20_000) { first.join() } + withTimeout(20_000) { first.join() } // real-clock hang guard: awaits real threads assertFalse(gate.isHeld(key()), "cancellation must release the lease") assertNull(svc.inFlight.value) - assertTrue(withTimeout(20_000) { svc.sync("g") }.isRight()) + assertTrue(withTimeout(20_000) { svc.sync("g") }.isRight()) // real-clock hang guard: awaits real threads } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun secondPress_should_LeaveInFlightAndStateUnchanged_When_FirstIsCommitting() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) val svc = service(git) git.blockAt(FakeGitOp.Commit) val first = scope.async { svc.sync("g") } - withTimeout(20_000) { git.awaitBlocked() } + withTimeout(20_000) { git.awaitBlocked() } // real-clock hang guard: awaits real threads val before = assertNotNull(svc.inFlight.value) assertEquals(SyncOrigin.UiPress, before.origin) assertEquals(SyncState.Committing, svc.syncState.value) - val second = withTimeout(20_000) { svc.sync("g") } + val second = withTimeout(20_000) { svc.sync("g") } // real-clock hang guard: awaits real threads assertEquals(DomainError.GitError.SyncInProgress(SyncOrigin.UiPress), second.leftOrNull()) assertEquals(before.copy(followUpQueued = true), svc.inFlight.value, "only the queued-follow-up bit may change") assertEquals(SyncState.Committing, svc.syncState.value) git.releaseBlocked() - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads // The queued press runs once after the first run, so the gate is free only after that follow-up. withTimeout(20_000) { while (svc.inFlight.value != null) kotlinx.coroutines.yield() } } @@ -200,40 +205,43 @@ class GitSyncServiceSingleFlightTest { git, StubConfigRepository(Either.Right(config)), SyncStalenessStore(MapSettings()), gate, { key() }, { 1L }, ) + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun servicePress_should_CoalesceAndNotInterruptTheFetch_When_AColdRunHoldsTheGate() = runBlocking { val cold = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } val running = scope.async { coldRunner(cold).run("g") } - withTimeout(20_000) { while (cold.calls.isEmpty()) kotlinx.coroutines.yield() } + withTimeout(20_000) { while (cold.calls.isEmpty()) kotlinx.coroutines.yield() } // real-clock hang guard: awaits real threads val live = OkRepository() val svc = service(live) - val pressed = withTimeout(20_000) { svc.sync("g") } + val pressed = withTimeout(20_000) { svc.sync("g") } // real-clock hang guard: awaits real threads assertEquals(DomainError.GitError.SyncInProgress(SyncOrigin.Cold), pressed.leftOrNull()) assertEquals(emptyList(), live.calls, "the coalesced press must not touch the repository") assertFalse(running.isCompleted, "the cold fetch keeps running") cold.fetchGate!!.complete(Unit) - assertIs(withTimeout(20_000) { running.await() }) + assertIs(withTimeout(20_000) { running.await() }) // real-clock hang guard: awaits real threads assertEquals(listOf("fetch"), cold.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun coldRun_should_ReturnBusyWithoutWaiting_When_ALiveSyncHoldsTheGate() = runBlocking { val live = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } val svc = service(live) val first = scope.async { svc.sync("g") } - withTimeout(20_000) { while (live.calls.isEmpty()) kotlinx.coroutines.yield() } + withTimeout(20_000) { while (live.calls.isEmpty()) kotlinx.coroutines.yield() } // real-clock hang guard: awaits real threads val cold = OkRepository() - val outcome = withTimeout(20_000) { coldRunner(cold).run("g") } + val outcome = withTimeout(20_000) { coldRunner(cold).run("g") } // real-clock hang guard: awaits real threads assertEquals(ColdSyncOutcome.Error(DomainError.GitError.SyncInProgress(SyncOrigin.UiPress)), outcome) assertEquals(emptyList(), cold.calls, "no second fetch is issued") live.fetchGate!!.complete(Unit) - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun claim_should_RefuseWithSyncInProgressAndRunNothing_When_OwnerAlive() = runBlocking { val git = OkRepository().apply { verdict = LockVerdict.OwnerAlive } @@ -248,6 +256,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun claim_should_PublishStaleLockFileWithVerdictAndDeleteNothing_When_OwnerUnknown() = runBlocking { val verdict = LockVerdict.OwnerUnknown(UnknownReason.RecoveryLockUnsupported) @@ -263,6 +272,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun record_should_BeEndedExactlyOncePerClaimedRun_AndNeverForACoalescedCall() = runBlocking { val git = OkRepository() @@ -279,7 +289,7 @@ class GitSyncServiceSingleFlightTest { } private suspend fun awaitFetches(git: OkRepository, n: Int) { - withTimeout(20_000) { while (git.calls.count { it == "fetch" } < n) kotlinx.coroutines.delay(10) } + withTimeout(20_000) { while (git.calls.count { it == "fetch" } < n) kotlinx.coroutines.delay(10) } // real-clock hang guard: awaits real threads } private suspend fun settle() = kotlinx.coroutines.delay(300) @@ -291,6 +301,7 @@ class GitSyncServiceSingleFlightTest { return first } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun threeUiPresses_should_YieldExactlyOneFollowUp_AndScheduledIsDropped() = runBlocking { val git = OkRepository() @@ -300,7 +311,7 @@ class GitSyncServiceSingleFlightTest { repeat(3) { assertIs(svc.sync("g").leftOrNull()) } assertIs(svc.sync("g", SyncTrigger.Automatic).leftOrNull()) git.fetchGate?.complete(Unit) - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads awaitFetches(git, 2) settle() @@ -309,6 +320,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun scheduledAlone_should_NotQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -317,12 +329,13 @@ class GitSyncServiceSingleFlightTest { assertIs(svc.sync("g", SyncTrigger.Automatic).leftOrNull()) git.fetchGate?.complete(Unit) - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads settle() assertEquals(1, git.calls.count { it == "fetch" }) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun liftedPress_should_BeRefusedAndNeverQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -331,13 +344,14 @@ class GitSyncServiceSingleFlightTest { val lifted = svc.sync("g", SyncTrigger.Manual, liftMassChangeGuard = true) git.fetchGate?.complete(Unit) - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads settle() assertEquals(DomainError.GitError.SyncInProgress(SyncOrigin.UiPress), lifted.leftOrNull()) assertEquals(1, git.calls.count { it == "fetch" }, "the lift flag must not ride a rerun") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun pressAgainstQuiesceHold_should_NeverSetTheRerunBit() = runBlocking { val git = OkRepository() @@ -353,6 +367,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(emptyList(), git.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun heartbeat_should_TouchWhileRunningAndStopBeforeTheRecordEnds() = runBlocking { val events = java.util.concurrent.CopyOnWriteArrayList() @@ -377,6 +392,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, events.count { it == "end" }) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun inFlight_should_CarryFollowUpQueuedOnlyForAQueuedUiPress() = runBlocking { val git = OkRepository() @@ -393,12 +409,13 @@ class GitSyncServiceSingleFlightTest { assertEquals(SyncOrigin.UiPress, svc.inFlight.value?.origin) git.fetchGate?.complete(Unit) - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads awaitFetches(git, 2) settle() assertNull(svc.inFlight.value) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun isGateHeld_should_FollowTheRepositoryGate_IncludingAForeignHolder() = runBlocking { val flight = SyncSingleFlight( @@ -439,6 +456,7 @@ class GitSyncServiceSingleFlightTest { gate = gate, ).also { services += it } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun confirmDialog_should_NotHoldGate_When_AwaitingUserConfirm() = runBlocking { val git = AbortRepository() @@ -447,17 +465,18 @@ class GitSyncServiceSingleFlightTest { val answer = kotlinx.coroutines.CompletableDeferred() val abort = scope.async { svc.abortActiveMerge("g") { confirmShown.complete(Unit); answer.await() } } - withTimeout(20_000) { confirmShown.await() } + withTimeout(20_000) { confirmShown.await() } // real-clock hang guard: awaits real threads assertFalse(gate.isHeld(key()), "an open dialog must not hold the gate") assertTrue(svc.sync("g").isRight(), "a tick during the dialog must run") answer.complete(true) - assertTrue(withTimeout(20_000) { abort.await() }.isRight()) + assertTrue(withTimeout(20_000) { abort.await() }.isRight()) // real-clock hang guard: awaits real threads assertTrue("abort" in git.calls) assertFalse(gate.isHeld(key())) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun abort_should_RefuseAndResetNothing_When_FilesChangeWhileTheDialogIsOpen() = runBlocking { val git = AbortRepository() 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 9e44d4eca..f103e1f03 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/PausedRetryNowAndDurabilityTest.kt @@ -225,8 +225,9 @@ class PausedRetryNowAndDurabilityTest { pausedRetryPolicy = PausedRetryPolicy(delays.toList()), ).also { services += it } - private suspend fun until(check: () -> Boolean) = withTimeout(20_000) { while (!check()) delay(10) } + private suspend fun until(check: () -> Boolean) = withTimeout(20_000) { while (!check()) delay(10) } // real-clock hang guard: awaits real threads + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun service_should_RetryTwiceAutomaticallyThenStayFailedWithTheLockError() = runBlocking { val repo = Repo() @@ -242,6 +243,7 @@ class PausedRetryNowAndDurabilityTest { assertIs(svc.syncState.value) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun service_should_ClearPausedAndSync_When_TheOwnerBecomesKnownBeforeTheRetry() = runBlocking { val repo = Repo() @@ -252,6 +254,7 @@ class PausedRetryNowAndDurabilityTest { until { svc.pausedRetry.value == null && svc.syncState.value !is SyncState.Error } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun retryNow_should_RunExtraAttemptsWithoutMovingTheTryNumber() = runBlocking { val repo = Repo() @@ -269,6 +272,7 @@ class PausedRetryNowAndDurabilityTest { assertIs((svc.syncState.value as SyncState.Error).error) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun rebuiltService_should_HaveNoPausedStateAndClaimAgain() = runBlocking { val repo = Repo() 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 1368ccc71..f99fb96a7 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt @@ -79,6 +79,7 @@ class ResolveGateKeyFailureTest { private fun repoKey(): String = checkNotNull(RepoOpGate.keyForOrNull("${gitDir.absolutePath}/.git") { File(it).canonicalFile.path }) + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_ConfigReadThrowsTwice() = runBlocking { val git = RecordingRepository { repoKey() } @@ -96,6 +97,7 @@ class ResolveGateKeyFailureTest { gate.releaseOrHandOff(holder) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_FailClosed_When_ConfigReadReturnsLeftTwice() = runBlocking { val git = RecordingRepository { repoKey() } @@ -110,6 +112,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_Resolve_When_OnlyTheFirstReadFails() = runBlocking { val git = RecordingRepository { repoKey() } @@ -120,6 +123,7 @@ class ResolveGateKeyFailureTest { assertTrue("fetch" in git.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_GitDirCannotBeCanonicalised() = runBlocking { val git = RecordingRepository { null } @@ -131,6 +135,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_CanonicalisationThrows() = runBlocking { val git = RecordingRepository { throw java.io.IOException("canonicalisation failed") } @@ -140,6 +145,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_Coalesce_When_ServiceIsRunningAndConfigBecomesUnreadable() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -147,19 +153,20 @@ class ResolveGateKeyFailureTest { val svc = service(configs, git) git.blockAt(FakeGitOp.Commit) val first = scope.async { svc.sync("g") } - withTimeout(20_000) { git.awaitBlocked() } + withTimeout(20_000) { git.awaitBlocked() } // real-clock hang guard: awaits real threads configs.failures = Int.MAX_VALUE val stateBefore = svc.syncState.value - val second = withTimeout(20_000) { svc.sync("g") } + val second = withTimeout(20_000) { svc.sync("g") } // real-clock hang guard: awaits real threads assertEquals(DomainError.GitError.SyncInProgress(SyncOrigin.UiPress), second.leftOrNull()) assertEquals(stateBefore, svc.syncState.value, "a coalesced call must not overwrite the running sync's state") git.releaseBlocked() - withTimeout(20_000) { first.await() } + withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads svc.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun resolveGateKey_should_RethrowCancellation_When_ConfigReadIsCancelled() = runBlocking { val git = RecordingRepository { repoKey() } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ScheduledSyncStackE2ETest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ScheduledSyncStackE2ETest.kt index e35b275d5..062463b3c 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ScheduledSyncStackE2ETest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ScheduledSyncStackE2ETest.kt @@ -127,7 +127,7 @@ class ScheduledSyncStackE2ETest { private fun runOneInterval(svc: GitSyncService) { val expected = repo.fetches.get() + 1 scheduler.advanceTimeBy(INTERVAL_MINUTES * MINUTE_MS) - val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS + val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS // real-clock hang guard: awaits real threads while (!(repo.fetches.get() >= expected && svc.scheduledSyncStatus.value.tickInFlight == false)) { assertTrue(System.nanoTime() < deadline, "tick $expected never finished") scheduler.runCurrent() @@ -192,7 +192,7 @@ class ScheduledSyncStackE2ETest { scheduler.runCurrent() scheduler.advanceTimeBy(INTERVAL_MINUTES * MINUTE_MS) - val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS + val deadline = System.nanoTime() + TICK_TIMEOUT_NANOS // real-clock hang guard: awaits real threads while (svc.scheduledSyncStatus.value.lastAttemptAtMs == null || svc.scheduledSyncStatus.value.tickInFlight) { assertTrue(System.nanoTime() < deadline, "tick never ran") scheduler.runCurrent() diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt index 7849f8b80..1a96bd060 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt @@ -46,6 +46,7 @@ class StaleLockRecoveryFollowUpTest { File(gitDir, "index.lock").apply { writeText(""); setLastModified(System.currentTimeMillis() - 60_000) } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun beginChecked_should_EndTheClaim_When_TheHealthCheckRefuses() = runBlocking { val gitDir = tempDir() @@ -62,6 +63,7 @@ class StaleLockRecoveryFollowUpTest { assertEquals(Either.Right(LockVerdict.NoLock), next, "the next claim must not see SyncInProgress") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun beginChecked_should_EndTheClaimAndRethrow_When_TheHealthCheckThrows() = runBlocking { val gitDir = tempDir() @@ -77,6 +79,7 @@ class StaleLockRecoveryFollowUpTest { } // The original bug's victims: a leftover index.lock with no owner record. + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun removeLockFile_should_UnwedgeSync_When_StaleLockHasNoRecord() = runBlocking { val root = tempDir() @@ -95,6 +98,7 @@ class StaleLockRecoveryFollowUpTest { assertTrue(synced.isRight(), "sync must proceed after the confirmed removal, got $synced") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun removeLockFile_should_Refuse_When_TheLockIsOnlyMinutesOld() = runBlocking { val root = tempDir() @@ -105,6 +109,7 @@ class StaleLockRecoveryFollowUpTest { assertTrue(lock.exists()) } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun removeLockFileAction_should_SurfaceTheRefusal_When_TheLockIsKept() = runBlocking { val root = tempDir() @@ -123,13 +128,14 @@ class StaleLockRecoveryFollowUpTest { actions.removeLockFile() - val event = kotlinx.coroutines.withTimeout(20_000) { events.await() } + val event = kotlinx.coroutines.withTimeout(20_000) { events.await() } // real-clock hang guard: awaits real threads assertIs(event) } finally { scope.coroutineContext[kotlinx.coroutines.Job]?.cancel() } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun removeLockFile_should_Refuse_When_TheLockWasJustTouched() = runBlocking { val root = tempDir() 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 b5b0c1a58..cdf459f9b 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt @@ -67,6 +67,7 @@ class SyncObservabilityLogTest { private fun logged(fragment: String) = lines.any { fragment in it } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun everyLockVerdict_should_LogOneLockVerdictLine() = runBlocking { val verdicts = listOf( @@ -82,12 +83,14 @@ class SyncObservabilityLogTest { } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun startedDecision_should_BeLogged_When_TheClaimSucceeds() = runBlocking { service(ScriptedRepository(LockVerdict.NoLock)).sync("g") assertTrue(logged("sync origin=UiPress decision=started"), "$lines") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun skippedDecision_should_BeLogged_When_TheOwnerIsUnknown() = runBlocking { val result = service(ScriptedRepository(LockVerdict.OwnerUnknown(UnknownReason.TornRecord))).sync("g") @@ -95,6 +98,7 @@ class SyncObservabilityLogTest { assertTrue(logged("sync origin=UiPress decision=skipped reason=StaleLockFile"), "$lines") } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun coalescedDecision_should_BeLogged_When_AnotherRunHoldsTheGate() = runBlocking { val repo = ScriptedRepository(LockVerdict.NoLock) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightCancellationTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightCancellationTest.kt index 55e2ff6f7..8f68efdff 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightCancellationTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightCancellationTest.kt @@ -76,33 +76,35 @@ class SyncSingleFlightCancellationTest { gitDir.deleteRecursively() } + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun sync_should_EndTheOwnedOperation_When_CancelledWhileTheClaimIsInFlight() = runBlocking { val job = scope.launch { service.sync("g", SyncTrigger.Manual) } - withTimeout(TIMEOUT_MS) { entered.await() } + withTimeout(TIMEOUT_MS) { entered.await() } // real-clock hang guard: awaits real threads job.cancel() latch.countDown() - withTimeout(TIMEOUT_MS) { job.join() } + withTimeout(TIMEOUT_MS) { job.join() } // real-clock hang guard: awaits real threads assertTrue(began.get() == 1, "the claim must have completed") assertEquals(1, ended.get(), "a claim that completed must be ended even though the caller was cancelled") } // PR #682 review M2: a hung push must not hold the gate forever once the sync is cancelled. + // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test fun sync_should_ReleaseTheGate_When_CancelledDuringAHungPush() = runBlocking { latch.countDown() pushHangs = true val job = scope.launch { service.sync("g", SyncTrigger.Manual) } - withTimeout(TIMEOUT_MS) { pushEntered.await() } + withTimeout(TIMEOUT_MS) { pushEntered.await() } // real-clock hang guard: awaits real threads job.cancel() - withTimeout(TIMEOUT_MS) { job.join() } + withTimeout(TIMEOUT_MS) { job.join() } // real-clock hang guard: awaits real threads assertEquals(1, ended.get()) pushHangs = false - val again = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } + val again = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } // real-clock hang guard: awaits real threads assertTrue(again.leftOrNull() !is DomainError.GitError.SyncInProgress, "gate must be free again, got $again") } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightModelTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightModelTest.kt index df7b7debc..ae5f41768 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightModelTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightModelTest.kt @@ -67,7 +67,7 @@ class SyncSingleFlightModelTest { delays.forEach { delay -> Thread { spin(delay); outcomes += press(gate) { runHeld(it) }; done.countDown() }.start() } - assertTrue(done.await(20, TimeUnit.SECONDS), "seed $seed did not finish") + assertTrue(done.await(20, TimeUnit.SECONDS), "seed $seed did not finish") // real-clock hang guard: awaits real threads val coalesced = outcomes.count { it == Outcome.Coalesced } assertEquals(pressCount, outcomes.size, "seed $seed: every press must end acquired or coalesced") 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 7df5fd9bb..0033bc24b 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt @@ -64,6 +64,7 @@ class SyncSingleFlightRegressionTest { r.leftOrNull() is DomainError.GitError.SyncInProgress private fun startFirstSync(): Deferred> = + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire runBlocking { CoroutineScopeHolder.scope.async(start = CoroutineStart.DEFAULT) { service.sync("g", SyncTrigger.Manual) } } private fun recordStates(): () -> List { @@ -71,15 +72,16 @@ class SyncSingleFlightRegressionTest { return { collector.cancel(); states.toList() } } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun secondManualSync_should_ReturnSyncInProgress_AndCreateNoLock_When_FirstBlockedInCommit() = runBlocking { repo.blockAt(FakeGitOp.Commit) val first = startFirstSync() - withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } + withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } // real-clock hang guard: awaits real threads val checksBefore = repo.removeStaleLockCalls val stop = recordStates() - val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } + val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } // real-clock hang guard: awaits real threads val seen = stop() assertTrue(isSyncInProgress(second), "second trigger must coalesce, got $second") @@ -87,57 +89,60 @@ class SyncSingleFlightRegressionTest { assertTrue(seen.none { it is SyncState.Error }, "a coalesced trigger must never publish Error, saw $seen") assertEquals(1, repo.maxConcurrent, "repository calls must never overlap") repo.releaseBlocked() - withTimeout(TIMEOUT_MS) { first.await() } + withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun liveLockOlderThan60s_should_NotBeDeleted_When_HeldByInFlightRun() = runBlocking { repo.blockAt(FakeGitOp.Commit) val first = startFirstSync() - withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } + withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } // real-clock hang guard: awaits real threads assertTrue(repo.indexLock.setLastModified(System.currentTimeMillis() - 90_000L)) - withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } + withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } // real-clock hang guard: awaits real threads assertTrue(repo.indexLock.exists(), "a live run's index.lock must survive a second trigger") repo.releaseBlocked() - withTimeout(TIMEOUT_MS) { first.await() } + withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstIsMergingAndRepositoryMidMerge() = runBlocking { repo.hasRemoteChanges = true repo.blockAt(FakeGitOp.Merge) val first = startFirstSync() - withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } + withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } // real-clock hang guard: awaits real threads repo.mergeInProgress = true assertEquals(SyncState.Merging, service.syncState.value) - val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } + val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } // real-clock hang guard: awaits real threads assertTrue(isSyncInProgress(second), "second trigger must coalesce, got $second") assertEquals(SyncState.Merging, service.syncState.value, "state must not become Error(RepairNeeded)") repo.releaseBlocked() - withTimeout(TIMEOUT_MS) { first.await() } + withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstFetchingAndOfflineAndVaultLocked() = runBlocking { repo.blockAt(FakeGitOp.Fetch) val first = startFirstSync() - withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } + withTimeout(TIMEOUT_MS) { repo.awaitBlocked() } // real-clock hang guard: awaits real threads online = false vaultAvailable = false assertEquals(SyncState.Fetching, service.syncState.value) - val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } + val second = withTimeout(TIMEOUT_MS) { service.sync("g", SyncTrigger.Manual) } // real-clock hang guard: awaits real threads assertTrue(isSyncInProgress(second), "second trigger must coalesce, got $second") assertEquals(SyncState.Fetching, service.syncState.value, "state must not become Error(Offline) or CredentialVaultLocked") assertNotNull(second.leftOrNull()) assertFalse(service.syncState.value is SyncState.Error) repo.releaseBlocked() - withTimeout(TIMEOUT_MS) { first.await() } + withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } private object CoroutineScopeHolder { diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/projectbridge/PostSyncProjectJobEntryPointTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/projectbridge/PostSyncProjectJobEntryPointTest.kt index 25c5a1ace..f704c9dce 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/projectbridge/PostSyncProjectJobEntryPointTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/projectbridge/PostSyncProjectJobEntryPointTest.kt @@ -104,7 +104,7 @@ class PostSyncProjectJobEntryPointTest { // runTest burns the barrier's virtual-time attempts while the sync still runs, so wait in real time. Safe only // because runSync keeps the sync off the test thread (blocking it here would starve the sync's own cleanup). private fun awaitSyncIdle(): Boolean { - val deadline = System.nanoTime() + 5_000_000_000L + val deadline = System.nanoTime() + 5_000_000_000L // real-clock hang guard: awaits real threads while (busyCounter.isBusy.value && System.nanoTime() < deadline) java.util.concurrent.locks.LockSupport.parkNanos(2_000_000L) return busyCounter.isBusy.value } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorCoalesceTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorCoalesceTest.kt index 5cd0b14eb..e32fecbe7 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorCoalesceTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorCoalesceTest.kt @@ -81,7 +81,7 @@ class GitSyncCoordinatorCoalesceTest { private suspend fun holdTheGate() { coordinator.triggerFetchOnly() entered.await() - withTimeout(5_000) { while (coordinator.syncState.value != SyncState.Fetching) yield() } + withTimeout(5_000) { while (coordinator.syncState.value != SyncState.Fetching) yield() } // real-clock hang guard: awaits real threads } private fun collectEvents(): MutableList { @@ -91,9 +91,10 @@ class GitSyncCoordinatorCoalesceTest { } private suspend fun awaitEvent(seen: List) { - withTimeout(5_000) { while (seen.isEmpty()) yield() } + withTimeout(5_000) { while (seen.isEmpty()) yield() } // real-clock hang guard: awaits real threads } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun triggerSync_should_EmitOneAlreadySyncing_AndChangeNoState_When_ARunHoldsTheGate() = runBlocking { val seen = collectEvents() @@ -109,6 +110,7 @@ class GitSyncCoordinatorCoalesceTest { assertFalse(jobs.jobs.first().any { it.state is JobState.Failed }, "a coalesced press is not a failed job") } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun triggerFetchOnly_should_EmitAlreadySyncing_When_ARunHoldsTheGate() = runBlocking { val seen = collectEvents() @@ -121,6 +123,7 @@ class GitSyncCoordinatorCoalesceTest { assertEquals(1, fetches.get()) } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun confirmMassChangeSync_should_BeRefusedAndKeepTheDialog_When_ARunIsInFlight() = runBlocking { val seen = collectEvents() @@ -136,6 +139,7 @@ class GitSyncCoordinatorCoalesceTest { assertEquals(1, fetches.get(), "the lifted press must never be carried through a coalesce or queued") } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun confirmMassChangeSync_should_CloseTheDialogWithoutRefusal_When_NothingIsInFlight() = runBlocking { release.complete(Unit) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt index 0f7eb67fa..62ec7a2fb 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt @@ -116,12 +116,13 @@ class GitSyncCoordinatorTest { } private suspend fun eventually(what: String, condition: () -> Boolean) { - withTimeout(AWAIT_MILLIS) { while (!condition()) yield() } + withTimeout(AWAIT_MILLIS) { while (!condition()) yield() } // real-clock hang guard: awaits real threads assertTrue(condition(), what) } private fun manyDeletions() = DeletionSummary(List(30) { "pages/p$it.md" }, previousTreeSize = 100) + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `openSyncDetails_should_OpenTheRepairDialog_When_StateIsRepairNeeded`() = runBlocking { val h = Harness(Spy().apply { health = RepositoryHealth(false, "MERGING") }) @@ -138,6 +139,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `openSyncDetails_should_DoNothing_When_StateHasNoDetailSurface`() = runBlocking { val h = Harness(Spy()) @@ -148,6 +150,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `abortInterruptedMerge_should_AbortAndCloseTheDialog_AndAllowTheNextSync`() = runBlocking { val h = Harness(Spy().apply { health = RepositoryHealth(false, "MERGING") }) @@ -164,6 +167,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `abortInterruptedMerge_should_ListUnrelatedEditsAndAbortOnlyAfterConfirmation_ThenRestoreThem`() = runBlocking { val spy = Spy().apply { health = RepositoryHealth(false, "MERGING"); workingFiles["notes.md"] = "mine".encodeToByteArray() } @@ -185,6 +189,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `abortInterruptedMerge_should_LeaveTheMergeAndTheDialogInPlace_WhenTheUserCancels`() = runBlocking { val spy = Spy().apply { health = RepositoryHealth(false, "MERGING"); workingFiles["notes.md"] = "mine".encodeToByteArray() } @@ -203,6 +208,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `confirmMassChangeSync_should_LiftTheGuardForOneManualRun_AndCloseTheConfirm`() = runBlocking { val h = Harness(Spy().apply { deletions = manyDeletions() }) @@ -225,6 +231,7 @@ class GitSyncCoordinatorTest { h.close() } + // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test fun `dismissals_should_CloseTheirDialogs`() = runBlocking { val h = Harness(Spy()) diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/cli/SyncMainClaimTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/cli/SyncMainClaimTest.kt index 5d2b79c89..d52c716bf 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/cli/SyncMainClaimTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/cli/SyncMainClaimTest.kt @@ -69,6 +69,7 @@ class SyncMainClaimTest { private val gitDir get() = File(root, ".git") + // runBlocking: cross-process claim over real files and threads @Test fun cliAndApp_should_CoalesceViaOwnerAlive_InBothDirections() = runBlocking { val app = instance("app") @@ -90,7 +91,7 @@ class SyncMainClaimTest { release.await() } } - withTimeout(30_000) { inBody.await() } + withTimeout(30_000) { inBody.await() } // real-clock hang guard: awaits real threads val verdict = instance("app2").beginOwnedOperation(config, OwnedOperationInfo("sync", SyncOrigin.UiPress)).getOrNull() assertEquals(LockVerdict.OwnerAlive, verdict) release.complete(Unit) @@ -98,6 +99,7 @@ class SyncMainClaimTest { assertFalse(File(gitDir, JavaIoLockFiles.RECORD_NAME).exists(), "the CLI releases its record when done") } + // runBlocking: cross-process claim over real files and threads @Test fun runOwned_should_BumpTheRecordHeartbeat_AndEndTheClaimOnFailure() = runBlocking { val record = File(gitDir, JavaIoLockFiles.RECORD_NAME) @@ -105,7 +107,7 @@ class SyncMainClaimTest { assertFailsWith { runOwned(RepoOpGate(), instance("cli"), config, output, notes, heartbeatIntervalMs = 50) { record.setLastModified(1_000L) - withTimeout(30_000) { while (record.lastModified() < 100_000L) yield() } + withTimeout(30_000) { while (record.lastModified() < 100_000L) yield() } // real-clock hang guard: awaits real threads stamped = record.lastModified() error("boom") } diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CloneEntryPointGateTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CloneEntryPointGateTest.kt index 460d323bc..e5b297656 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CloneEntryPointGateTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CloneEntryPointGateTest.kt @@ -8,7 +8,7 @@ import arrow.core.right import dev.stapler.stelekit.error.DomainError import dev.stapler.stelekit.error.SyncOrigin import dev.stapler.stelekit.git.testsupport.cloningStub -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import java.io.File import java.nio.file.Files import kotlin.test.Test @@ -24,7 +24,7 @@ class CloneEntryPointGateTest { private fun key(path: String) = checkNotNull(JvmGitRepository().gateKeyForRoot(path)) @Test - fun launcher_should_HoldTheGateDuringCloneAndReleaseAfter() = runBlocking { + fun launcher_should_HoldTheGateDuringCloneAndReleaseAfter() = runTest { var heldDuring = false val repo = cloningStub { _, path, _, _ -> heldDuring = gate.isHeld(key(path)) @@ -40,7 +40,7 @@ class CloneEntryPointGateTest { } @Test - fun launcher_should_ReturnSyncInProgressAndNotClone_When_TheDestinationIsHeld() = runBlocking { + fun launcher_should_ReturnSyncInProgressAndNotClone_When_TheDestinationIsHeld() = runTest { var cloned = false val repo = cloningStub { _, _, _, _ -> cloned = true; Unit.right() } val hold = checkNotNull(gate.tryAcquire(key(dest.path), SyncOrigin.UiPress)) diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CrossProcessSyncChildMain.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CrossProcessSyncChildMain.kt index 287be516c..97caacdc4 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CrossProcessSyncChildMain.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/CrossProcessSyncChildMain.kt @@ -51,6 +51,7 @@ object CrossProcessSyncChildMain { private fun configFor(repoDir: File) = GitConfig(graphId = GRAPH_ID, repoRoot = RepoRoot(repoDir.absolutePath), wikiSubdir = null, authType = GitAuthType.NONE) + // runBlocking: cross-process claim over real files and threads private fun seed(repoDir: File) = runBlocking { val verdict = JvmGitRepository().beginOwnedOperation(configFor(repoDir), OwnedOperationInfo("sync", SyncOrigin.UiPress)) check(verdict.getOrNull() == LockVerdict.NoLock) { "seed claim was $verdict" } @@ -69,6 +70,7 @@ object CrossProcessSyncChildMain { println("READY") System.out.flush() while (input.readLine() != "GO") Unit + // runBlocking: cross-process claim over real files and threads println(runBlocking { runOnce(mode, repoDir) }) System.out.flush() } 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 bd98b1b44..a160595d5 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt @@ -129,6 +129,7 @@ class GitSyncServiceLfsJvmTest { private fun remoteCommitCount(): Int = Git.open(origin).use { git -> git.log().call().count() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_PushTextNotesAndNeverTheRawBinary_When_AssetsAreLfsTracked() = runBlocking { File(work, "pages").mkdirs() @@ -155,6 +156,7 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_NotCreateEmptyCommits_When_OnlyAHeldFileIsPending() = runBlocking { File(work, "assets").mkdirs() @@ -170,6 +172,7 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } + // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test fun sync_should_PushTheFileAsAPointer_OnceTheRawFileIsReplaced() = runBlocking { File(work, "assets").mkdirs() diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateIntegrationTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateIntegrationTest.kt index 559a1cefa..7fe8dcc52 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateIntegrationTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateIntegrationTest.kt @@ -85,6 +85,7 @@ class StelekitViewModelSyncStateIntegrationTest { } } + // runBlocking: StelekitViewModel runs on its own real-dispatcher scope that virtual time cannot drive @Test fun `IT-4_3_2-A syncState mirrors GitSyncService state exactly when localChangesCountFlow is null`() = runBlocking { val gitRepository = object : StubGitRepository() { 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 dca946c4f..99b525147 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/ui/StelekitViewModelSyncStateTest.kt @@ -72,6 +72,7 @@ class StelekitViewModelSyncStateTest { // ── TC-4.3.2-A: Idle + nonzero count → LocalChangesPending ───────────────── + // runBlocking: StelekitViewModel runs on its own real-dispatcher scope that virtual time cannot drive @Test fun `TC-4_3_2-A syncState combine emits LocalChangesPending when raw state is Idle and count greater than zero`() = runBlocking { val countFlow = MutableStateFlow(0) @@ -90,6 +91,7 @@ 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 { val countFlow = MutableStateFlow(0) @@ -103,6 +105,7 @@ class StelekitViewModelSyncStateTest { // ── TC-4.3.2-B: in-progress state is never overridden ────────────────────── + // runBlocking: StelekitViewModel runs on its own real-dispatcher scope that virtual time cannot drive @Test fun `TC-4_3_2-B syncState combine never overrides an in-progress state with LocalChangesPending`() = runBlocking { // GitRepository whose status() reports local changes but stageSubdir() fails — diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt index 6555216ed..473eae33c 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt @@ -60,12 +60,14 @@ class DesktopTaskRootWiringTest { @AfterTest fun tearDown() { headless?.close() + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } private fun open(pollMinutes: Int) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, true) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -76,6 +78,7 @@ class DesktopTaskRootWiringTest { } fixture = wired graphId = wired.graphManager.graphRegistry.value.activeGraphId!!.value + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { wired.graphManager.createGitConfigRepository()!!.saveConfig(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = pollMinutes)) } headless = HeadlessComposition().also { composition -> composition.setContent { @@ -93,7 +96,7 @@ class DesktopTaskRootWiringTest { } } - private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { + private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { // real clock: the scheduler runs on its own dispatcher, no completion signal val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { if (System.nanoTime() > deadline) fail("timed out waiting for $what") @@ -129,16 +132,19 @@ class DesktopTaskRootWiringTest { val scheduler = createDesktopTaskScheduler(registry, shared) val key = TaskKey(GitSyncTask.KIND, TaskScope("g1")) try { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { scheduler.runOnce(key, TaskConstraints()) - val deadline = System.nanoTime() + 10_000_000_000L + val deadline = System.nanoTime() + 10_000_000_000L // real clock: the scheduler runs on its own dispatcher, no completion signal while (SettingsTaskRunLog(shared).recent(key).isEmpty() && System.nanoTime() < deadline) kotlinx.coroutines.delay(20) } } finally { scheduler.stop() } + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call assertTrue(runBlocking { SettingsTaskRunLog(shared).recent(key) }.isNotEmpty(), "the instance the UI reads sees the scheduler's run record") assertTrue( + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { SettingsTaskRunLog(separate).recent(key) }.isEmpty(), "a second PlatformSettings holds its own stale copy, which is why the root must share one", ) @@ -157,9 +163,11 @@ class DesktopTaskRootWiringTest { val controller = tasksState!!.controller val key = TaskKey(GitSyncTask.KIND, TaskScope(graphId)) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call assertEquals(SaveResult.Saved, runBlocking { controller.edit(key, PanelEdit.Interval(15)) }) awaitCondition("the running loop to take the 15 minute interval") { (nextCheckInMinutes() ?: -1L) in 14L..16L } + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call assertEquals(SaveResult.Saved, runBlocking { controller.edit(key, PanelEdit.Enabled(false)) }) awaitCondition("the running loop to stop") { stack?.gitSyncService?.scheduledSyncStatus?.value?.running == false } } diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopWiredAppFixtureTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopWiredAppFixtureTest.kt index a5b2df982..8afbacdfd 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopWiredAppFixtureTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopWiredAppFixtureTest.kt @@ -31,6 +31,7 @@ class DesktopWiredAppFixtureTest { @AfterTest fun tearDown() { headless?.close() + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } @@ -42,6 +43,7 @@ class DesktopWiredAppFixtureTest { @Test fun wiredAppFixtureDesktop_should_BehaveIdenticallyWithoutDisplay_When_StackComposed() { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop(dataDir) } fixture = wired val composition = HeadlessComposition().also { headless = it } diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncServiceRegistryBalanceTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncServiceRegistryBalanceTest.kt index 94285d0c5..c70f7e298 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncServiceRegistryBalanceTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncServiceRegistryBalanceTest.kt @@ -31,6 +31,7 @@ class GitSyncServiceRegistryBalanceTest { @AfterTest fun tearDown() { compositions.forEach { it.close() } + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } GitSyncServiceRegistry.registeredGraphIds().toList().forEach { GitSyncServiceRegistry.unregister(it) } dataDir.deleteRecursively() @@ -45,6 +46,7 @@ class GitSyncServiceRegistryBalanceTest { @Test fun gitSyncServiceRegistry_should_HoldOnlyActiveGraphService_When_FiveSwitchGraphCalls() { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop(dataDir, graphPath = "/test/graph-a") } fixture = wired val paths = listOf("/test/graph-b", "/test/graph-a", "/test/graph-b", "/test/graph-a", "/test/graph-b") @@ -56,6 +58,7 @@ class GitSyncServiceRegistryBalanceTest { var lastService: GitSyncService = first for (path in paths) { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { wired.graphManager.openGraph(path) } // The app swaps GraphContent under key(activeGraphId): new graph composes, then the old one leaves. val (next, nextStack) = compose(wired) @@ -74,6 +77,7 @@ class GitSyncServiceRegistryBalanceTest { @Test fun registry_should_KeepNewerRegistration_When_OldServiceUnregistersLate() { + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop(dataDir) } fixture = wired val (first, firstStack) = compose(wired) diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt index 15e5cc98e..b515bdb56 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt @@ -87,12 +87,14 @@ class GitSyncStackEntryPointTest { fun tearDown() { sinkHandle.close() headless?.close() + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } private fun open(flagOn: Boolean, pollMinutes: Int) { settings.putBoolean(SCHEDULED_SYNC_ENABLED_KEY, flagOn) + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call val wired = runBlocking { DesktopWiredAppFixture.desktop( dataDir, @@ -119,6 +121,7 @@ class GitSyncStackEntryPointTest { private fun saveInterval(minutes: Int) { val configRepo = fixture!!.graphManager.createGitConfigRepository()!! + // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call runBlocking { configRepo.saveConfig(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = minutes)) } } diff --git a/project_plans/scheduling-hygiene/requirements.md b/project_plans/scheduling-hygiene/requirements.md index 932d1de5c..04d326192 100644 --- a/project_plans/scheduling-hygiene/requirements.md +++ b/project_plans/scheduling-hygiene/requirements.md @@ -51,6 +51,13 @@ pattern appears in `GitSyncWorkerGateAndRecordTest` (10 s) and - Non-scheduling coroutine uses of `runBlocking` elsewhere in the codebase - Robolectric test configuration or WorkManager test harness rewrites +## Test scope (settled during review) + +"Scheduling and worker tests" means any test of `jobs.schedule`, workers, schedulers, git-sync runs +(service, coordinator, single-flight, repo gate), background-sync quiesce and model download, in every test +source set. Out of scope: `GraphRelocationCoordinator*`, `SidecarReconcileTest`, `ThreeStateSubscriptionTest`, +`StelekitViewModelShareExportTest`, `GitRepositoryUnshallowTest` (none schedules or runs background work). + ## Acceptance Criteria 1. No `runBlocking` exists in any production scheduling/worker source file diff --git a/project_plans/scheduling-hygiene/validate.md b/project_plans/scheduling-hygiene/validate.md index de4c90114..0fb9e94ef 100644 --- a/project_plans/scheduling-hygiene/validate.md +++ b/project_plans/scheduling-hygiene/validate.md @@ -6,6 +6,9 @@ ### AC-1: Production code has no runBlocking +**Correction:** the verification below was wrong. `androidMain/git/WorkManagerSyncScheduler.kt` had four +`runBlocking` calls, removed during implementation (see research.md). + VERIFIED by search: - `ScheduleStartup.run()` is `suspend fun` — no `runBlocking`. - `TaskWorker.doWork()` is a suspend function (`CoroutineWorker`) — no `runBlocking`. From 7efce5190609f837027cc85726137510bd761347 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 12:19:38 -0800 Subject: [PATCH 06/13] test(scheduling): cover the remaining test files from #642 Converts AndroidGitLegacyConfigSourceTest to runTest and annotates LfsTransferPolicyTest; drops the test-scope note from the requirements. --- .../stelekit/git/AndroidGitLegacyConfigSourceTest.kt | 12 ++++++------ .../stelekit/git/GitSyncServiceRateLimitRetryTest.kt | 2 +- .../stelekit/git/lfs/LfsTransferPolicyTest.kt | 6 ++++++ project_plans/scheduling-hygiene/requirements.md | 7 ------- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitLegacyConfigSourceTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitLegacyConfigSourceTest.kt index 2c4d07fe3..1a5a15ea4 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitLegacyConfigSourceTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/git/AndroidGitLegacyConfigSourceTest.kt @@ -6,7 +6,7 @@ package dev.stapler.stelekit.git import android.content.Context import androidx.test.core.app.ApplicationProvider import dev.stapler.stelekit.git.testsupport.sampleConfig -import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -26,7 +26,7 @@ class AndroidGitLegacyConfigSourceTest { AndroidGitLegacyConfigSource(context, databaseExists = { exists }, load = load) @Test - fun read_should_beUnavailable_When_DatabaseFileDoesNotExist() = runBlocking { + fun read_should_beUnavailable_When_DatabaseFileDoesNotExist() = runTest { var loaded = false val result = source(exists = false) { loaded = true; null }.read("g1") assertEquals(LegacyGitConfigResult.Unavailable, result) @@ -34,23 +34,23 @@ class AndroidGitLegacyConfigSourceTest { } @Test - fun read_should_beUnavailable_When_TheReadThrows() = runBlocking { + fun read_should_beUnavailable_When_TheReadThrows() = runTest { assertEquals(LegacyGitConfigResult.Unavailable, source { throw IllegalStateException("cannot open") }.read("g1")) } @Test - fun read_should_beUnavailable_When_TheRealDatabasePathIsUnopenable() = runBlocking { + fun read_should_beUnavailable_When_TheRealDatabasePathIsUnopenable() = runTest { // No database exists for this id in the test files dir, so the real existence check reports unavailable. assertEquals(LegacyGitConfigResult.Unavailable, AndroidGitLegacyConfigSource(context).read("no-such-graph")) } @Test - fun read_should_findNoRemote_When_TheDatabaseHasNoGitConfigRow() = runBlocking { + fun read_should_findNoRemote_When_TheDatabaseHasNoGitConfigRow() = runTest { assertEquals(LegacyGitConfigResult.Found(hasRemote = false, pollIntervalMinutes = 0), source { null }.read("g1")) } @Test - fun read_should_findRemoteAndInterval_When_TheDatabaseHasAGitConfigRow() = runBlocking { + fun read_should_findRemoteAndInterval_When_TheDatabaseHasAGitConfigRow() = runTest { val result = source { sampleConfig.copy(graphId = it, pollIntervalMinutes = 30) }.read("g1") assertEquals(LegacyGitConfigResult.Found(hasRemote = true, pollIntervalMinutes = 30), result) } 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 fcbf3751a..120c2588e 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceRateLimitRetryTest.kt @@ -122,7 +122,7 @@ class GitSyncServiceRateLimitRetryTest { assertEquals(1, counter.value, "must not re-invoke fetchOnly before the stated delay elapses") // After the delay elapses, exactly one retry should fire. - withTimeout(5_000) { + withTimeout(5_000) { // real-clock hang guard: awaits real threads while (counter.value < 2) delay(50) } assertEquals(2, counter.value, "must re-invoke fetchOnly exactly once after the delay") diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt index 315b270bd..1444ce222 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt @@ -65,6 +65,7 @@ class LfsTransferPolicyTest { val bytes = Random(size).nextBytes(size) File(a, ".gitattributes").writeText("*.bin filter=lfs diff=lfs merge=lfs -text\n") File(a, "img.bin").writeBytes(bytes) + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers runBlocking { val config = configFor(a) publisher.stageSubdir(config, emptySet()) @@ -87,11 +88,13 @@ class LfsTransferPolicyTest { Git.cloneRepository().setURI(origin.toURI().toString()).setDirectory(b).setNoCheckout(true).call().use { git -> git.repository.config.setString("lfs", null, "url", server.url) git.repository.config.save() + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers runBlocking { support.afterClone(git, null) } } return b } + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers private fun lastJob() = runBlocking { jobs.jobs.first().single() } @Test @@ -138,6 +141,7 @@ class LfsTransferPolicyTest { assertEquals(before, server.requests.size, "no request may reach the LFS server while metered") assertTrue(File(b, ".git/lfs/pending").exists()) + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers assertTrue(runBlocking { jobs.jobs.first() }.isEmpty()) } @@ -192,6 +196,7 @@ class LfsTransferPolicyTest { git.add().addFilepattern(".").call() git.commit().setMessage("p").call() + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers runBlocking { support.afterClone(git, null) } } @@ -255,6 +260,7 @@ class LfsTransferPolicyTest { val gitDir = File(root, "svc").also { it.mkdirs() } val http = HttpClient(OkHttp) { configureLfsTimeouts() } try { + // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers val result = runBlocking { LfsTransferService(LfsBatchClient(http, server.url, authHeader = null), LfsObjectStore(gitDir), gitDir).download(listOf(pointer)) } assertEquals(LfsDownloadResult(fetched = 1, skippedOversize = 0), result.getOrNull()) diff --git a/project_plans/scheduling-hygiene/requirements.md b/project_plans/scheduling-hygiene/requirements.md index 04d326192..932d1de5c 100644 --- a/project_plans/scheduling-hygiene/requirements.md +++ b/project_plans/scheduling-hygiene/requirements.md @@ -51,13 +51,6 @@ pattern appears in `GitSyncWorkerGateAndRecordTest` (10 s) and - Non-scheduling coroutine uses of `runBlocking` elsewhere in the codebase - Robolectric test configuration or WorkManager test harness rewrites -## Test scope (settled during review) - -"Scheduling and worker tests" means any test of `jobs.schedule`, workers, schedulers, git-sync runs -(service, coordinator, single-flight, repo gate), background-sync quiesce and model download, in every test -source set. Out of scope: `GraphRelocationCoordinator*`, `SidecarReconcileTest`, `ThreeStateSubscriptionTest`, -`StelekitViewModelShareExportTest`, `GitRepositoryUnshallowTest` (none schedules or runs background work). - ## Acceptance Criteria 1. No `runBlocking` exists in any production scheduling/worker source file From b7b4c3e2ef2bbd49abb437ec30f0114dfc4399f5 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 12:56:07 -0800 Subject: [PATCH 07/13] test(scheduling): correct runBlocking reasons, convert more to runTest, and fix SharePreviewPane race The share preview test waited on a flag set before the compute finished, so Copy could still be disabled when asserted (failed the Android job on #771). Also covers a cancelled caller of the quiesce release. --- .../db/AndroidGraphMoveQuiesceStrategyTest.kt | 20 ++++++++ .../stapler/stelekit/ui/TaskRunLogRowsTest.kt | 4 +- .../ui/components/SharePreviewPaneTest.kt | 6 +-- .../wiring/RepoGateSharedEntryPointTest.kt | 2 +- .../stelekit/git/GateKeyResolutionTest.kt | 4 +- .../stelekit/git/GitSyncCancelBoundaryTest.kt | 26 +++++------ .../git/GitSyncMergeUnitContainmentTest.kt | 4 +- .../git/GitSyncServiceAutoCommitTest.kt | 2 +- .../git/GitSyncServiceChangeBackTest.kt | 4 +- .../git/GitSyncServiceChangeGuardsTest.kt | 30 ++++++------ .../GitSyncServiceConflictMarkerGuardTest.kt | 8 ++-- .../git/GitSyncServiceFirstSyncGateTest.kt | 6 +-- .../git/GitSyncServiceLfsGuardTest.kt | 44 +++++++++--------- .../git/GitSyncServicePublishFailureTest.kt | 4 +- .../git/GitSyncServiceRateLimitRetryTest.kt | 8 ++-- .../git/GitSyncServiceScheduledSyncTest.kt | 46 +++++++++---------- .../git/GitSyncServiceSingleFlightTest.kt | 40 ++++++++-------- .../git/PausedRetryNowAndDurabilityTest.kt | 8 ++-- .../stelekit/git/ResolveGateKeyFailureTest.kt | 14 +++--- .../git/StaleLockRecoveryFollowUpTest.kt | 15 +++--- .../stelekit/git/SyncObservabilityLogTest.kt | 8 ++-- .../git/SyncSingleFlightRegressionTest.kt | 10 ++-- .../stelekit/ui/GitSyncCoordinatorTest.kt | 7 ++- .../stelekit/git/GitSyncServiceLfsJvmTest.kt | 6 +-- .../stelekit/git/lfs/LfsTransferPolicyTest.kt | 4 +- .../wiring/DesktopTaskRootWiringTest.kt | 2 +- 26 files changed, 174 insertions(+), 158 deletions(-) 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 149908a8b..a479c144e 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.yield import dev.stapler.stelekit.model.StorageLocation import dev.stapler.stelekit.model.StorageMoveOperation import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.runTest @@ -88,6 +89,25 @@ class AndroidGraphMoveQuiesceStrategyTest { } } + @Test + fun release_should_ResumeBackgroundSync_When_TheCallerIsAlreadyCancelled() = runTest { + var resumed = false + val strategy = AndroidGraphMoveQuiesceStrategy( + gitSyncBusyCounter = GitSyncBusyCounter(), + gate = RepoOpGate(), + gateKeyFor = { null }, + shadowWorktreeTarget = { null }, + resumeBackgroundSync = { resumed = true }, + ) + + launch { + cancel() + strategy.release(op) + }.join() + + assertTrue(resumed, "a cancelled caller must still resume background sync") + } + @Test fun quiesce_should_AwaitBusyCounterIdleAndDrainWriteBackQueue_When_GitWriteBackQueueHasInFlightEntry() = runTest { val queue = newQueue() diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt index 65268e5c4..76e1a334f 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt @@ -42,6 +42,7 @@ import dev.stapler.stelekit.ui.components.TaskRunLogSource import dev.stapler.stelekit.ui.components.rememberTaskRunRowsState import dev.stapler.stelekit.ui.components.settings.BackgroundTaskGraph import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.datetime.TimeZone import org.junit.After import org.junit.Rule @@ -208,9 +209,8 @@ class TaskRunLogRowsTest { rule.onNodeWithText("Git sync / Work notes / success").assertExists() } - // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call @Test - fun recentResult_should_beReadFailedWhileRecentStaysEmpty_When_SettingsReadThrows() = runBlocking { + fun recentResult_should_beReadFailedWhileRecentStaysEmpty_When_SettingsReadThrows() = runTest { append(record(now - minute)) settings.failReads = true assertTrue(runLog.recentResult(gitKey) is TaskRunReadResult.ReadFailed) diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/SharePreviewPaneTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/SharePreviewPaneTest.kt index bc78cad9f..88b5cdb13 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/SharePreviewPaneTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/components/SharePreviewPaneTest.kt @@ -59,7 +59,7 @@ class SharePreviewPaneTest { // compute runs on a background dispatcher, so idle-waiting alone can return before it finishes. @OptIn(androidx.compose.ui.test.ExperimentalTestApi::class) private fun waitForText(text: String) { - composeRule.waitUntilAtLeastOneExists(androidx.compose.ui.test.hasText(text), 5_000) + composeRule.waitUntilAtLeastOneExists(androidx.compose.ui.test.hasText(text, substring = true), 5_000) } private fun androidx.compose.ui.test.SemanticsNodeInteraction.assertDoesNotExistOrFail() = assertDoesNotExist() @@ -86,10 +86,8 @@ class SharePreviewPaneTest { composeRule.onNodeWithText("Copy").assertIsNotEnabled() // loading while the 600-block export is pending composeRule.onNodeWithText("Copy").assertExists() gate.complete(Unit) - composeRule.waitUntil(5_000) { computeThread != null } - composeRule.waitForIdle() + waitForText("- block 600") // computeThread is set before the gate, so it cannot signal completion composeRule.onNodeWithText("Copy").assertIsEnabled() assertEquals(true, computeThread !== mainThread, "compute ran on the main thread") - composeRule.onNodeWithText("- block 600", substring = true).assertExists() } } 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 ea1613dcd..a9f0967a7 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt @@ -84,7 +84,7 @@ class RepoGateSharedEntryPointTest { return outcome } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: builds the real app fixture, which opens a graph on real dispatchers @Test fun the_fixture_gate_is_the_one_in_the_platform_integrations() = runBlocking { val f = WiredAppFixture.android(context, dataDir).also { fixture = it } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt index 1e19ea78f..425448928 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GateKeyResolutionTest.kt @@ -16,6 +16,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 @@ -83,9 +84,8 @@ class GateKeyResolutionTest { } } - // runBlocking: real threads/dispatchers do the work under test; virtual time cannot order or await them @Test - fun syncKey_should_DifferForDifferentRepositories() = runBlocking { + fun syncKey_should_DifferForDifferentRepositories() = runTest { val other = File(base, "other").apply { mkdirs() } val a = assertNotNull(RepoOpGate.keyForOrNull(File(real, ".git"))) val b = assertNotNull(RepoOpGate.keyForOrNull(File(other, ".git"))) 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 f7e27745e..549ab6453 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt @@ -115,7 +115,7 @@ class GitSyncCancelBoundaryTest { latch.await() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun cancelDuringFetch_should_NotMerge_AndCancelBeforeCommitShouldNotCommit() = runBlocking { val entered = CompletableDeferred() @@ -148,7 +148,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun cancelThenImmediateRepress_should_NotOverlap_When_BlockingCallStillRunning() = runBlocking { val entered = CompletableDeferred() @@ -174,7 +174,7 @@ class GitSyncCancelBoundaryTest { assertEquals(0, git.count("fetch"), "the pipeline stops before fetch after the cancel") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun commit_should_CompleteAndPipelineStopBeforeFetch_When_CancelRequestedDuringCommit() = runBlocking { val entered = CompletableDeferred() @@ -201,7 +201,7 @@ class GitSyncCancelBoundaryTest { rawContent = "<<<<<<< LOCAL\n- a\n=======\n- b\n>>>>>>> REMOTE\n", ) - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun mergeUnit_should_NotFallThroughToPush_When_ConflictOrCommitFailureExitsInsideNonCancellable() = runBlocking { val conflicted = Repo(remoteChanges = true).apply { @@ -222,7 +222,7 @@ class GitSyncCancelBoundaryTest { assertEquals(1, failing.count("abort")) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun mergeUnit_should_ReloadEveryChangedPathBeforeStopping_When_CancelArrivesRightAfterMerge() = runBlocking { val reloaded = CopyOnWriteArrayList() @@ -257,7 +257,7 @@ class GitSyncCancelBoundaryTest { return reloaded to (GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()) to fs) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveConflicts_should_ReloadResolvedFiles_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -278,7 +278,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun applyJournalMerge_should_ReloadTheFile_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -295,7 +295,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun commitLocalChanges_should_FinishTheCommit_When_CancelRequestedDuringIt() = runBlocking { val entered = CompletableDeferred() @@ -313,7 +313,7 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun reloadMergedFiles_should_FlagReloadIncomplete_When_CancelledMidReload() = runBlocking { val fs = object : StubFileSystem() { @@ -329,7 +329,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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveConflicts_should_KeepTheLease_UntilALateCommitFinishes_ThenReleaseAndClearTheFlag() = runBlocking { val late = CompletableDeferred() @@ -354,7 +354,7 @@ class GitSyncCancelBoundaryTest { assertFalse(svc.reloadIncomplete.value, "the sentinel clears when the abandoned unit ends") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_KeepTheLeaseAndNotFlagReload_When_TheMainCommitOutlivesTheWait() = runBlocking { val late = CompletableDeferred() @@ -373,7 +373,7 @@ class GitSyncCancelBoundaryTest { } // PR #683 review m1: a later complete reload of other files must not clear an earlier incomplete one. - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun reloadIncomplete_should_StaySticky_UntilTheFailedPathsReloadCompletely() = runBlocking { val failing = java.util.concurrent.atomic.AtomicBoolean(true) @@ -416,7 +416,7 @@ class GitSyncCancelBoundaryTest { override fun observeConfig(graphId: String) = kotlinx.coroutines.flow.flowOf>(Either.Right(byGraph[graphId])) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @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 3408e63d6..731cb07cd 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt @@ -61,7 +61,7 @@ class GitSyncMergeUnitContainmentTest { graphLoader = GraphLoader(fs, InMemoryPageRepository(), InMemoryBlockRepository()), ) - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun reload_should_ChunkAtMost200AndSetReloadIncomplete_When_BeginGitMergeThrows() = runBlocking { val seen = AtomicInteger() @@ -85,7 +85,7 @@ class GitSyncMergeUnitContainmentTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun reload_should_LogProgressPerChunkAndStayComplete_When_ThousandPathsReload() = runBlocking { val svc = service(pages(1000), StubFileSystem()) 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 83291b7dc..263941130 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceAutoCommitTest.kt @@ -74,7 +74,7 @@ class GitSyncServiceAutoCommitTest { ) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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 be1d94416..86e91617a 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt @@ -71,7 +71,7 @@ class GitSyncServiceChangeBackTest { return service to configRepo } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val (service, configRepo) = repairedService(remoteBranches = listOf("master")) @@ -83,7 +83,7 @@ class GitSyncServiceChangeBackTest { service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val (service, configRepo) = repairedService(remoteBranches = listOf("master", "main")) 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 4d86e3c68..079a25078 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt @@ -103,7 +103,7 @@ class GitSyncServiceChangeGuardsTest { private val mutating = setOf("stage", "commit", "merge", "push") - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -117,7 +117,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(health = RepositoryHealth(false, "UNMERGED_PATHS")) @@ -129,7 +129,7 @@ class GitSyncServiceChangeGuardsTest { fresh.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("journals/2026_10_08.md")))) @@ -145,7 +145,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Incomplete("big.md is larger than 2048 KiB"))) @@ -156,7 +156,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(dirty = false, markers = mutableMapOf(GuardScope.NetPush to MarkerScan.Found(listOf("a.md")))) @@ -169,7 +169,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy() @@ -180,7 +180,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(21, treeSize = 100))) @@ -194,7 +194,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(deletions = mutableMapOf(GuardScope.NetPush to deletions(30, treeSize = 100))) @@ -205,7 +205,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun `deletions within the threshold pass`() = runBlocking { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(20, treeSize = 100))) @@ -229,7 +229,7 @@ class GitSyncServiceChangeGuardsTest { assertEquals(10, blocked?.threshold) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val lowered = MapSettings().apply { putString(MassChangeThresholds.KEY_MIN_FILES, "3"); putString(MassChangeThresholds.KEY_PERCENT, "1") } @@ -254,7 +254,7 @@ class GitSyncServiceChangeGuardsTest { assertEquals(MassChangeThresholds(), MassChangeThresholds.from(settings)) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(40, treeSize = 100))) @@ -270,7 +270,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val unsafe = Spy(health = RepositoryHealth(false, "MERGING")) @@ -292,7 +292,7 @@ class GitSyncServiceChangeGuardsTest { massSvc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(health = RepositoryHealth(false, "MERGING"), markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("x.md")))) @@ -305,7 +305,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -316,7 +316,7 @@ class GitSyncServiceChangeGuardsTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val commitBlocked = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("j.md")))) 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 69496bf0b..13cea9ef9 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt @@ -74,7 +74,7 @@ class GitSyncServiceConflictMarkerGuardTest { ) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -89,7 +89,7 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -123,7 +123,7 @@ class GitSyncServiceConflictMarkerGuardTest { assertEquals(null, clean.findUnresolved(sampleConfig, status)) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val calls = mutableListOf() @@ -136,7 +136,7 @@ class GitSyncServiceConflictMarkerGuardTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val calls = mutableListOf() 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 f3a5ba04d..c1d2ea22d 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt @@ -71,7 +71,7 @@ class GitSyncServiceFirstSyncGateTest { return Fixture(service, firstSync, fetchCalls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val f = fixture(reviewPending = true) @@ -86,7 +86,7 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val f = fixture(reviewPending = true) @@ -98,7 +98,7 @@ class GitSyncServiceFirstSyncGateTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val f = fixture(reviewPending = true) 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 941dd7479..d2869491f 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt @@ -133,7 +133,7 @@ class GitSyncServiceLfsGuardTest { return Fixture(service, repo, fs, settings) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldRawBinaryAndCommitTheRest_When_AssetsAreLfsTracked() = runBlocking { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf("pages/a.md" to "# a".encodeToByteArray(), photo to png)) @@ -150,7 +150,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldUntrackedRawBinaryToo_When_FileIsNew() = runBlocking { val f = fixture(untracked = listOf(photo), modified = listOf("pages/a.md"), files = mapOf(photo to png)) @@ -161,7 +161,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldNothing_When_TrackedFileIsAValidPointer() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to pointer)) @@ -174,7 +174,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldNothing_When_TrackedFileIsEmpty() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to ByteArray(0))) @@ -185,7 +185,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_SkipTheCommit_When_EverythingStagedWasHeld() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -199,7 +199,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_NotConsultTheIndexForCommitNeed_When_NothingWasHeld() = runBlocking { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.anythingStaged = false }) @@ -210,7 +210,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HonourNestedGitattributes_When_RuleLivesInASubdirectory() = runBlocking { val f = fixture( @@ -229,7 +229,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_SeeAnUncommittedGitattributesEdit_When_TheWorkingTreeFileChanged() = runBlocking { val f = fixture(modified = listOf(".gitattributes", "x.png"), files = mapOf("x.png" to png), gitattributes = "*.png filter=lfs\n") @@ -240,7 +240,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_RefuseTheWholeCommit_When_HoldBackIsFlippedOff() = runBlocking { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { fs -> @@ -259,7 +259,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_JudgeNothing_When_ThePlatformGuardsInItsOwnWritePath() = runBlocking { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { it.files["/repo/.gitattributes"] = "* filter=lfs\n".encodeToByteArray() }, delegated = true) @@ -271,7 +271,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_NotJudgeTheWorkingFile_When_AutoModeAndACleanFilterIsActive() = runBlocking { val f = fixture( @@ -289,7 +289,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldAndUnstage_When_AutoModeFilterLeftRawBytesInTheIndex() = runBlocking { val escaped = LfsViolation("assets/b.bin", LfsViolationReason.RawBinary, ".gitattributes:1") @@ -307,7 +307,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_HoldTheWorkingFile_When_ModeIsGuardOnlyEvenIfACleanFilterIsReported() = runBlocking { val f = fixture( @@ -324,7 +324,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_FailClosed_When_TheIndexCannotBeVerified() = runBlocking { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.stagedThrows = true }) @@ -336,7 +336,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun commitLocalChanges_should_HoldRawBinaryAndStillCommit_When_AssetsAreLfsTracked() = runBlocking { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf(photo to png)) @@ -349,7 +349,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun commitLocalChanges_should_ReturnNullWithoutCommitting_When_OnlyHeldFilesChanged() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -361,7 +361,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveConflicts_should_RefuseBeforeMarkResolved_When_SideResolutionLeavesRawBinary() = runBlocking { val f = fixture(files = mapOf(photo to png)) @@ -378,7 +378,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveConflicts_should_RefuseBeforeMarkResolved_When_HunkResolutionWritesRawText() = runBlocking { val f = fixture(files = mapOf(photo to png)) @@ -394,7 +394,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveConflicts_should_StageAValidPointer_When_ResolvedSideIsAPointer() = runBlocking { val f = fixture(files = mapOf(photo to pointer)) @@ -410,7 +410,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun applyJournalMerge_should_RefuseBeforeMarkResolved_When_MergedContentLandsAtATrackedPath() = runBlocking { val f = fixture(gitattributes = "journals/** filter=lfs\n") @@ -423,7 +423,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_SurfaceRawBlobsThatWerePushedOutsideTheGuard_When_ThePushAuditFindsThem() = runBlocking { val pushed = LfsViolation("assets/sneaky.bin", LfsViolationReason.RawBinaryPushed, ".gitattributes:1") @@ -436,7 +436,7 @@ class GitSyncServiceLfsGuardTest { f.service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun syncState_should_ReturnToSuccess_When_TheHeldFileIsFixedBeforeTheNextSync() = runBlocking { val f = fixture(modified = listOf(photo), files = mapOf(photo to png)) 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 91db1f264..dac7ba347 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServicePublishFailureTest.kt @@ -63,7 +63,7 @@ class GitSyncServicePublishFailureTest { ) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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,7 +104,7 @@ class GitSyncServicePublishFailureTest { assertEquals(listOf("a.md"), (state as SyncState.ConflictPending).conflicts.map { it.filePath }) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val limited = service(FailingAt(Step.Fetch, DomainError.GitError.RateLimited(3600))) 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 120c2588e..c0d1cb0c3 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive 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 382f77afb..7407f97b7 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt @@ -144,7 +144,7 @@ class GitSyncServiceScheduledSyncTest { private fun policySkip(reason: ScheduledSkipReason) = TickOutcome.Skip(SkipReason.Policy(reason)) - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -158,7 +158,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val busy = Harness().also { it.confirmFirstSync(); it.busy.begin() } @@ -180,7 +180,7 @@ class GitSyncServiceScheduledSyncTest { offlineSvc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -198,7 +198,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -213,7 +213,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -225,7 +225,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness() @@ -240,7 +240,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness() @@ -252,7 +252,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -264,7 +264,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -275,7 +275,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { for (predicate in listOf<(RepoRoot) -> Boolean>({ false }, { error("unresolvable saf uri") })) { @@ -293,7 +293,7 @@ class GitSyncServiceScheduledSyncTest { } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { for (root in listOf("saf://tree/notes", "content://com.android/tree/x")) { @@ -317,7 +317,7 @@ class GitSyncServiceScheduledSyncTest { } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -334,7 +334,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness(appOwned = { false }).also { it.confirmFirstSync() } @@ -360,7 +360,7 @@ class GitSyncServiceScheduledSyncTest { live.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness() @@ -370,7 +370,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val unconfirmed = Harness().service() @@ -391,7 +391,7 @@ class GitSyncServiceScheduledSyncTest { rebranched.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } @@ -404,7 +404,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness(config = sampleConfig.copy(autoCommit = false)).also { it.confirmFirstSync() } @@ -415,7 +415,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -442,7 +442,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness().also { it.confirmFirstSync() } @@ -458,7 +458,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val spy = Spy() @@ -481,7 +481,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val h = Harness(vaultProvider = { error("keystore unavailable") }).also { it.confirmFirstSync() } @@ -492,7 +492,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val answers = ArrayDeque(listOf(true, true)) @@ -504,7 +504,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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 { val gate = object : MapSettings() { 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 9a3251058..b5aa8666f 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt @@ -20,6 +20,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import java.io.File import java.nio.file.Files @@ -91,7 +92,7 @@ class GitSyncServiceSingleFlightTest { override suspend fun abortMerge(config: GitConfig) = Unit.right().also { calls += "abort" } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun everyMutatingEntryPoint_should_RunWithTheGateHeld_When_RepositoryAssertsIt() = runBlocking { val git = GateAssertingGitRepository(OkRepository(), gate, keyFor = { c -> checkNotNull(RepoOpGate.keyForOrNull("${c.repoRoot.value}/.git") { File(it).canonicalFile.path }) }) @@ -119,7 +120,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key()), "every entry point must release") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun gate_should_BeFreeAndSyncRunnable_When_BeginOwnedOperationThrows() = runBlocking { val git = OkRepository().apply { onBegin = { throw IllegalStateException("record write failed") } } @@ -133,7 +134,7 @@ class GitSyncServiceSingleFlightTest { assertTrue(svc.sync("g").isRight(), "a fresh sync must acquire and run") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun gate_should_BeFree_When_EndOwnedOperationThrowsAnything() = runBlocking { for (failure in listOf<() -> Throwable>({ RuntimeException("boom") }, { CancellationException("cancelled") })) { @@ -148,7 +149,7 @@ class GitSyncServiceSingleFlightTest { } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun gate_should_BeFreeAndSyncRunnable_When_RunIsCancelledMidCommit() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -169,7 +170,7 @@ class GitSyncServiceSingleFlightTest { assertTrue(withTimeout(20_000) { svc.sync("g") }.isRight()) // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun secondPress_should_LeaveInFlightAndStateUnchanged_When_FirstIsCommitting() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -205,7 +206,7 @@ class GitSyncServiceSingleFlightTest { git, StubConfigRepository(Either.Right(config)), SyncStalenessStore(MapSettings()), gate, { key() }, { 1L }, ) - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun servicePress_should_CoalesceAndNotInterruptTheFetch_When_AColdRunHoldsTheGate() = runBlocking { val cold = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } @@ -224,7 +225,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(listOf("fetch"), cold.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun coldRun_should_ReturnBusyWithoutWaiting_When_ALiveSyncHoldsTheGate() = runBlocking { val live = OkRepository().apply { fetchGate = kotlinx.coroutines.CompletableDeferred() } @@ -241,7 +242,7 @@ class GitSyncServiceSingleFlightTest { withTimeout(20_000) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun claim_should_RefuseWithSyncInProgressAndRunNothing_When_OwnerAlive() = runBlocking { val git = OkRepository().apply { verdict = LockVerdict.OwnerAlive } @@ -256,7 +257,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun claim_should_PublishStaleLockFileWithVerdictAndDeleteNothing_When_OwnerUnknown() = runBlocking { val verdict = LockVerdict.OwnerUnknown(UnknownReason.RecoveryLockUnsupported) @@ -272,7 +273,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun record_should_BeEndedExactlyOncePerClaimedRun_AndNeverForACoalescedCall() = runBlocking { val git = OkRepository() @@ -301,7 +302,7 @@ class GitSyncServiceSingleFlightTest { return first } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun threeUiPresses_should_YieldExactlyOneFollowUp_AndScheduledIsDropped() = runBlocking { val git = OkRepository() @@ -320,7 +321,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun scheduledAlone_should_NotQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -335,7 +336,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, git.calls.count { it == "fetch" }) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun liftedPress_should_BeRefusedAndNeverQueueAFollowUp() = runBlocking { val git = OkRepository() @@ -351,7 +352,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, git.calls.count { it == "fetch" }, "the lift flag must not ride a rerun") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun pressAgainstQuiesceHold_should_NeverSetTheRerunBit() = runBlocking { val git = OkRepository() @@ -367,7 +368,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun heartbeat_should_TouchWhileRunningAndStopBeforeTheRecordEnds() = runBlocking { val events = java.util.concurrent.CopyOnWriteArrayList() @@ -392,7 +393,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(1, events.count { it == "end" }) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun inFlight_should_CarryFollowUpQueuedOnlyForAQueuedUiPress() = runBlocking { val git = OkRepository() @@ -415,9 +416,8 @@ class GitSyncServiceSingleFlightTest { assertNull(svc.inFlight.value) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test - fun isGateHeld_should_FollowTheRepositoryGate_IncludingAForeignHolder() = runBlocking { + fun isGateHeld_should_FollowTheRepositoryGate_IncludingAForeignHolder() = runTest { val flight = SyncSingleFlight( gate, OkRepository(), StubConfigRepository(Either.Right(config)), GitSyncBusyCounter(), kotlinx.coroutines.flow.MutableStateFlow(null), { 0L }, publishError = {}, @@ -456,7 +456,7 @@ class GitSyncServiceSingleFlightTest { gate = gate, ).also { services += it } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun confirmDialog_should_NotHoldGate_When_AwaitingUserConfirm() = runBlocking { val git = AbortRepository() @@ -476,7 +476,7 @@ class GitSyncServiceSingleFlightTest { assertFalse(gate.isHeld(key())) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun abort_should_RefuseAndResetNothing_When_FilesChangeWhileTheDialogIsOpen() = runBlocking { val git = AbortRepository() 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 f103e1f03..7615b23a3 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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun service_should_RetryTwiceAutomaticallyThenStayFailedWithTheLockError() = runBlocking { val repo = Repo() @@ -243,7 +243,7 @@ class PausedRetryNowAndDurabilityTest { assertIs(svc.syncState.value) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @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 runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun retryNow_should_RunExtraAttemptsWithoutMovingTheTryNumber() = runBlocking { val repo = Repo() @@ -272,7 +272,7 @@ class PausedRetryNowAndDurabilityTest { assertIs((svc.syncState.value as SyncState.Error).error) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun rebuiltService_should_HaveNoPausedStateAndClaimAgain() = runBlocking { val repo = Repo() 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 f99fb96a7..501719827 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/ResolveGateKeyFailureTest.kt @@ -79,7 +79,7 @@ class ResolveGateKeyFailureTest { private fun repoKey(): String = checkNotNull(RepoOpGate.keyForOrNull("${gitDir.absolutePath}/.git") { File(it).canonicalFile.path }) - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_ConfigReadThrowsTwice() = runBlocking { val git = RecordingRepository { repoKey() } @@ -97,7 +97,7 @@ class ResolveGateKeyFailureTest { gate.releaseOrHandOff(holder) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_FailClosed_When_ConfigReadReturnsLeftTwice() = runBlocking { val git = RecordingRepository { repoKey() } @@ -112,7 +112,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_Resolve_When_OnlyTheFirstReadFails() = runBlocking { val git = RecordingRepository { repoKey() } @@ -123,7 +123,7 @@ class ResolveGateKeyFailureTest { assertTrue("fetch" in git.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_GitDirCannotBeCanonicalised() = runBlocking { val git = RecordingRepository { null } @@ -135,7 +135,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_FailClosedAndMakeNoGitCall_When_CanonicalisationThrows() = runBlocking { val git = RecordingRepository { throw java.io.IOException("canonicalisation failed") } @@ -145,7 +145,7 @@ class ResolveGateKeyFailureTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_Coalesce_When_ServiceIsRunningAndConfigBecomesUnreadable() = runBlocking { val git = GateAwareFakeGitRepository(gitDir) @@ -166,7 +166,7 @@ class ResolveGateKeyFailureTest { svc.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun resolveGateKey_should_RethrowCancellation_When_ConfigReadIsCancelled() = runBlocking { val git = RecordingRepository { repoKey() } diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt index 1a96bd060..5a0b297ac 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/StaleLockRecoveryFollowUpTest.kt @@ -12,6 +12,7 @@ import dev.stapler.stelekit.git.testsupport.StubConfigRepository import dev.stapler.stelekit.git.testsupport.sampleConfig import dev.stapler.stelekit.model.RepoRoot import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import org.eclipse.jgit.api.Git import java.io.File import java.nio.file.Files @@ -46,9 +47,8 @@ class StaleLockRecoveryFollowUpTest { File(gitDir, "index.lock").apply { writeText(""); setLastModified(System.currentTimeMillis() - 60_000) } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test - fun beginChecked_should_EndTheClaim_When_TheHealthCheckRefuses() = runBlocking { + fun beginChecked_should_EndTheClaim_When_TheHealthCheckRefuses() = runTest { val gitDir = tempDir() writeDeadOwner(gitDir) val registry = ActiveRunRegistry() @@ -63,9 +63,8 @@ class StaleLockRecoveryFollowUpTest { assertEquals(Either.Right(LockVerdict.NoLock), next, "the next claim must not see SyncInProgress") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire @Test - fun beginChecked_should_EndTheClaimAndRethrow_When_TheHealthCheckThrows() = runBlocking { + fun beginChecked_should_EndTheClaimAndRethrow_When_TheHealthCheckThrows() = runTest { val gitDir = tempDir() writeDeadOwner(gitDir) val registry = ActiveRunRegistry() @@ -79,7 +78,7 @@ class StaleLockRecoveryFollowUpTest { } // The original bug's victims: a leftover index.lock with no owner record. - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: real lock files and a GitSyncService on its own real dispatchers @Test fun removeLockFile_should_UnwedgeSync_When_StaleLockHasNoRecord() = runBlocking { val root = tempDir() @@ -98,7 +97,7 @@ class StaleLockRecoveryFollowUpTest { assertTrue(synced.isRight(), "sync must proceed after the confirmed removal, got $synced") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: real lock files and a GitSyncService on its own real dispatchers @Test fun removeLockFile_should_Refuse_When_TheLockIsOnlyMinutesOld() = runBlocking { val root = tempDir() @@ -109,7 +108,7 @@ class StaleLockRecoveryFollowUpTest { assertTrue(lock.exists()) } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: real lock files and a GitSyncService on its own real dispatchers @Test fun removeLockFileAction_should_SurfaceTheRefusal_When_TheLockIsKept() = runBlocking { val root = tempDir() @@ -135,7 +134,7 @@ class StaleLockRecoveryFollowUpTest { } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: real lock files and a GitSyncService on its own real dispatchers @Test fun removeLockFile_should_Refuse_When_TheLockWasJustTouched() = runBlocking { val root = tempDir() 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 cdf459f9b..1485194e3 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt @@ -67,7 +67,7 @@ class SyncObservabilityLogTest { private fun logged(fragment: String) = lines.any { fragment in it } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun everyLockVerdict_should_LogOneLockVerdictLine() = runBlocking { val verdicts = listOf( @@ -83,14 +83,14 @@ class SyncObservabilityLogTest { } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun startedDecision_should_BeLogged_When_TheClaimSucceeds() = runBlocking { service(ScriptedRepository(LockVerdict.NoLock)).sync("g") assertTrue(logged("sync origin=UiPress decision=started"), "$lines") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun skippedDecision_should_BeLogged_When_TheOwnerIsUnknown() = runBlocking { val result = service(ScriptedRepository(LockVerdict.OwnerUnknown(UnknownReason.TornRecord))).sync("g") @@ -98,7 +98,7 @@ class SyncObservabilityLogTest { assertTrue(logged("sync origin=UiPress decision=skipped reason=StaleLockFile"), "$lines") } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun coalescedDecision_should_BeLogged_When_AnotherRunHoldsTheGate() = runBlocking { val repo = ScriptedRepository(LockVerdict.NoLock) 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 0033bc24b..187e73fad 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncSingleFlightRegressionTest.kt @@ -64,7 +64,7 @@ class SyncSingleFlightRegressionTest { r.leftOrNull() is DomainError.GitError.SyncInProgress private fun startFirstSync(): Deferred> = - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // 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) } } private fun recordStates(): () -> List { @@ -72,7 +72,7 @@ class SyncSingleFlightRegressionTest { return { collector.cancel(); states.toList() } } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun secondManualSync_should_ReturnSyncInProgress_AndCreateNoLock_When_FirstBlockedInCommit() = runBlocking { repo.blockAt(FakeGitOp.Commit) @@ -92,7 +92,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun liveLockOlderThan60s_should_NotBeDeleted_When_HeldByInFlightRun() = runBlocking { repo.blockAt(FakeGitOp.Commit) @@ -107,7 +107,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstIsMergingAndRepositoryMidMerge() = runBlocking { repo.hasRemoteChanges = true @@ -125,7 +125,7 @@ class SyncSingleFlightRegressionTest { withTimeout(TIMEOUT_MS) { first.await() } // real-clock hang guard: awaits real threads } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun secondManualSync_should_CoalesceAndLeaveStateUnchanged_When_FirstFetchingAndOfflineAndVaultLocked() = runBlocking { repo.blockAt(FakeGitOp.Fetch) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt index 62ec7a2fb..8c10966b1 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/ui/GitSyncCoordinatorTest.kt @@ -33,6 +33,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withTimeout import kotlinx.coroutines.yield import kotlin.test.Test @@ -139,9 +140,8 @@ class GitSyncCoordinatorTest { h.close() } - // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test - fun `openSyncDetails_should_DoNothing_When_StateHasNoDetailSurface`() = runBlocking { + fun `openSyncDetails_should_DoNothing_When_StateHasNoDetailSurface`() = runTest { val h = Harness(Spy()) h.coordinator.safety.openSyncDetails() @@ -231,9 +231,8 @@ class GitSyncCoordinatorTest { h.close() } - // runBlocking: the coordinator runs on a real Dispatchers.Default scope the test has to wait on @Test - fun `dismissals_should_CloseTheirDialogs`() = runBlocking { + fun `dismissals_should_CloseTheirDialogs`() = runTest { val h = Harness(Spy()) h.uiState.value = AppState(repairNeededVisible = true, massChangeConfirmVisible = 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 a160595d5..88f6b735b 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt @@ -129,7 +129,7 @@ class GitSyncServiceLfsJvmTest { private fun remoteCommitCount(): Int = Git.open(origin).use { git -> git.log().call().count() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_PushTextNotesAndNeverTheRawBinary_When_AssetsAreLfsTracked() = runBlocking { File(work, "pages").mkdirs() @@ -156,7 +156,7 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_NotCreateEmptyCommits_When_OnlyAHeldFileIsPending() = runBlocking { File(work, "assets").mkdirs() @@ -172,7 +172,7 @@ class GitSyncServiceLfsJvmTest { service.shutdown() } - // runBlocking: GitSyncService runs on its own real-dispatcher scope and bounds commit units with a caller-side withTimeout that virtual time would expire + // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive @Test fun sync_should_PushTheFileAsAPointer_OnceTheRawFileIsReplaced() = runBlocking { File(work, "assets").mkdirs() diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt index 1444ce222..6a3c06f69 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/lfs/LfsTransferPolicyTest.kt @@ -94,7 +94,7 @@ class LfsTransferPolicyTest { return b } - // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers + // runBlocking: reads a flow from a non-suspend helper or test body private fun lastJob() = runBlocking { jobs.jobs.first().single() } @Test @@ -141,7 +141,7 @@ class LfsTransferPolicyTest { assertEquals(before, server.requests.size, "no request may reach the LFS server while metered") assertTrue(File(b, ".git/lfs/pending").exists()) - // runBlocking: blocking JGit and real HTTP against a local server, partly from non-suspend helpers + // runBlocking: reads a flow from a non-suspend helper or test body assertTrue(runBlocking { jobs.jobs.first() }.isEmpty()) } diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt index 473eae33c..04e254018 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt @@ -132,7 +132,7 @@ class DesktopTaskRootWiringTest { val scheduler = createDesktopTaskScheduler(registry, shared) val key = TaskKey(GitSyncTask.KIND, TaskScope("g1")) try { - // runBlocking: non-suspend UI/headless JUnit test; bridges a suspend setup, read or teardown call + // runBlocking: the scheduler runs on its own real dispatcher; polled on the wall clock runBlocking { scheduler.runOnce(key, TaskConstraints()) val deadline = System.nanoTime() + 10_000_000_000L // real clock: the scheduler runs on its own dispatcher, no completion signal From 59bb6b46c1525a1605b322cc8fdc2ed856f0d828 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 13:06:50 -0800 Subject: [PATCH 08/13] [claudesquad] work complete for "Scheduling hygiene: runBlocking audit and real-clock test polling" (pre-PR) --- .../dev/stapler/stelekit/db/DriverFactory.android.kt | 1 + .../dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt | 4 ++-- .../stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt | 9 +++------ .../kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt | 2 +- .../stelekit/wiring/RepoGateSharedEntryPointTest.kt | 2 +- .../stelekit/git/GitSyncServiceSingleFlightTest.kt | 2 +- .../stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt | 3 ++- .../stelekit/wiring/GitSyncStackEntryPointTest.kt | 2 +- .../stelekit/wiring/ScheduledSyncOriginE2ETest.kt | 2 +- .../wiring/TaskSchedulerDesktopEntryPointTest.kt | 2 +- 10 files changed, 14 insertions(+), 15 deletions(-) diff --git a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt index 9bfe5bc4f..9158de2b6 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/db/DriverFactory.android.kt @@ -234,6 +234,7 @@ actual class DriverFactory actual constructor() { } }, ) + // runBlocking: same non-suspend constraint; the driver must not be returned unmigrated. runBlocking { TelemetryMigrationRunner.applyAll(driver) } return driver } 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 16c66db72..1481442f4 100644 --- a/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt +++ b/kmp/src/androidMain/kotlin/dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt @@ -67,8 +67,8 @@ class WorkManagerSyncScheduler( /** * Persists intent through the port: jitter and constraints come from [TaskSettingsStore] (the spec - * defaults when nothing is stored), the interval is the caller's. The adapter guards every WorkManager - * failure itself, so this never throws. + * defaults when nothing is stored), the interval is the caller's. WorkManager failures are logged by the + * adapter, not thrown; cancellation propagates. */ @Deprecated("Use BackgroundTaskScheduler.apply(TaskKey(git-sync, graphId), config); kept for one release.") override suspend fun schedule(intervalMinutes: Int) { 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 a479c144e..c4697a8ef 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/db/AndroidGraphMoveQuiesceStrategyTest.kt @@ -314,9 +314,8 @@ class AndroidGraphMoveQuiesceStrategyTest { assertFalse(worktreeLock.isLocked, "release must free the worktree lock") } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test - fun quiesce_should_CoalesceTriggers_AndNeverSetRerun_While_QuiesceLeaseHeld() = runBlocking { + fun quiesce_should_CoalesceTriggers_AndNeverSetRerun_While_QuiesceLeaseHeld() = runTest { val gate = RepoOpGate() val strategy = gatedStrategy(gate, newTarget(newQueue()) { emptyList() }) @@ -351,9 +350,8 @@ class AndroidGraphMoveQuiesceStrategyTest { assertTrue(fresh != null, "a fresh sync must acquire after the cancelled quiesce") } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test - fun quiesce_should_ReleaseBothOnRelease_When_DrainReturnsError() = runBlocking { + fun quiesce_should_ReleaseBothOnRelease_When_DrainReturnsError() = runTest { val gate = RepoOpGate() val queue = newQueue().also { it.enqueue("pages/foo.md") } val flush = FailingFlush(queue) { DomainError.GitError.WorkingTreeConcurrentEditDetected(it) } @@ -368,9 +366,8 @@ class AndroidGraphMoveQuiesceStrategyTest { assertFalse(GitWorktreeLocks.lockFor(target.shadowKey).isLocked) } - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it @Test - fun quiesce_should_UseNoGate_When_GateKeyUnresolvable() = runBlocking { + fun quiesce_should_UseNoGate_When_GateKeyUnresolvable() = runTest { val gate = RepoOpGate() val strategy = AndroidGraphMoveQuiesceStrategy( gitSyncBusyCounter = GitSyncBusyCounter(), diff --git a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt index 76e1a334f..cbfcdf1e5 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/ui/TaskRunLogRowsTest.kt @@ -211,7 +211,7 @@ class TaskRunLogRowsTest { @Test fun recentResult_should_beReadFailedWhileRecentStaysEmpty_When_SettingsReadThrows() = runTest { - append(record(now - minute)) + runLog.append(record(now - minute)) settings.failReads = true assertTrue(runLog.recentResult(gitKey) is TaskRunReadResult.ReadFailed) assertEquals(emptyList(), runLog.recent(gitKey)) 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 a9f0967a7..6f6ef9cc6 100644 --- a/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt +++ b/kmp/src/androidUnitTest/kotlin/dev/stapler/stelekit/wiring/RepoGateSharedEntryPointTest.kt @@ -52,7 +52,7 @@ class RepoGateSharedEntryPointTest { @After fun tearDown() { - // runBlocking: quiesce hops to Dispatchers.IO and blocks on real locks; virtual time cannot order it + // runBlocking: non-suspend JUnit @After; bridges the suspend fixture close fixture?.let { runBlocking { it.close() } } dataDir.deleteRecursively() } 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 b5aa8666f..a18cb5417 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceSingleFlightTest.kt @@ -368,7 +368,7 @@ class GitSyncServiceSingleFlightTest { assertEquals(emptyList(), git.calls) } - // runBlocking: GitSyncService does its work on its own real-dispatcher scope, which virtual time cannot drive + // runBlocking: the heartbeat runs on a real-dispatcher scope; its beat and the body delay are real time @Test fun heartbeat_should_TouchWhileRunningAndStopBeforeTheRecordEnds() = runBlocking { val events = java.util.concurrent.CopyOnWriteArrayList() diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt index 04e254018..e17c3146d 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/DesktopTaskRootWiringTest.kt @@ -96,7 +96,8 @@ class DesktopTaskRootWiringTest { } } - private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { // real clock: the scheduler runs on its own dispatcher, no completion signal + // Wall-clock ceiling: the loop is on a virtual scheduler pumped here, but the IO and composition it waits on are real. + private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { if (System.nanoTime() > deadline) fail("timed out waiting for $what") diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt index b515bdb56..d372bf7fd 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/GitSyncStackEntryPointTest.kt @@ -125,7 +125,7 @@ class GitSyncStackEntryPointTest { runBlocking { configRepo.saveConfig(sampleConfig.copy(graphId = graphId, pollIntervalMinutes = minutes)) } } - /** Pumps Compose frames and the virtual scheduler until [condition] holds, failing at [timeoutMs]. */ + /** Pumps Compose frames and the virtual scheduler until [condition] holds, failing at [timeoutMs] (wall clock: the IO is real). */ private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt index 8aa5d1281..1540e674f 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/ScheduledSyncOriginE2ETest.kt @@ -113,7 +113,7 @@ class ScheduledSyncOriginE2ETest { } } - // Real-clock ceiling: real git processes and scheduler threads give no virtual-time or completion signal. + // Wall-clock ceiling: the loop is on a virtual scheduler pumped here, but the git and IO work it waits on are real. private fun awaitCondition(what: String, timeoutMs: Long = 60_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { diff --git a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt index 0ebe3e464..f0b557825 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/wiring/TaskSchedulerDesktopEntryPointTest.kt @@ -105,7 +105,7 @@ class TaskSchedulerDesktopEntryPointTest { } } - // Real-clock ceiling: the scheduler loop runs on its own real dispatcher and exposes no completion signal. + // Wall-clock ceiling: the loop is on a virtual scheduler pumped here, but the IO and composition it waits on are real. private fun awaitCondition(what: String, timeoutMs: Long = 30_000, condition: () -> Boolean) { val deadline = System.nanoTime() + timeoutMs * 1_000_000 while (!condition()) { From 7edd9e5c87022c3cd780135a6edaa3043f81c380 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 14:17:05 -0800 Subject: [PATCH 09/13] fix(storage-move): clear move-in-progress flag when cancelled during release --- .../db/FakeGraphMoveQuiesceStrategy.kt | 2 ++ ...phRelocationCoordinatorCancellationTest.kt | 23 +++++++++++++++++++ .../stelekit/db/GraphRelocationCoordinator.kt | 14 +++++++---- 3 files changed, 35 insertions(+), 4 deletions(-) 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/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) From b776b0617e8703779aa2582b8c0041afc513a6de Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 14:17:05 -0800 Subject: [PATCH 10/13] fix(scheduling): make the scheduler adapter's resume non-cancellable --- .../dev/stapler/stelekit/git/WorkManagerSyncScheduler.kt | 5 +---- .../stelekit/jobs/schedule/WorkManagerTaskScheduler.kt | 6 +++++- 2 files changed, 6 insertions(+), 5 deletions(-) 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) From 32ffb0c70e7228bcb30062bf436f22688d3fb149 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 14:17:05 -0800 Subject: [PATCH 11/13] test(scheduling): runTest where nothing needs real time, guard production runBlocking --- .../db/AndroidGraphMoveQuiesceStrategyTest.kt | 4 +- .../stelekit/db/QuiesceRealFlushTest.kt | 2 +- .../platform/ml/DepthModelDownloaderTest.kt | 12 ++-- .../wiring/RepoGateSharedEntryPointTest.kt | 2 +- .../dev/stapler/stelekit/AllBusinessTests.kt | 2 + .../audit/SchedulingNoRunBlockingAuditTest.kt | 39 +++++++++++ .../stelekit/git/GitSyncCancelBoundaryTest.kt | 28 ++++---- .../git/GitSyncMergeUnitContainmentTest.kt | 8 +-- .../git/GitSyncServiceAutoCommitTest.kt | 4 +- .../git/GitSyncServiceChangeBackTest.kt | 8 +-- .../git/GitSyncServiceChangeGuardsTest.kt | 47 +++++-------- .../GitSyncServiceConflictMarkerGuardTest.kt | 14 ++-- .../git/GitSyncServiceFirstSyncGateTest.kt | 11 ++- .../git/GitSyncServiceLfsGuardTest.kt | 68 +++++++----------- .../git/GitSyncServicePublishFailureTest.kt | 8 +-- .../git/GitSyncServiceRateLimitRetryTest.kt | 8 +-- .../git/GitSyncServiceScheduledSyncTest.kt | 69 +++++++------------ .../git/GitSyncServiceSingleFlightTest.kt | 41 +++++------ .../git/PausedRetryNowAndDurabilityTest.kt | 9 ++- .../stelekit/git/ResolveGateKeyFailureTest.kt | 21 +++--- .../stelekit/git/SyncObservabilityLogTest.kt | 14 ++-- .../git/SyncSingleFlightRegressionTest.kt | 12 ++-- .../stelekit/git/GitSyncServiceLfsJvmTest.kt | 11 ++- 23 files changed, 194 insertions(+), 248 deletions(-) create mode 100644 kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt 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..806bddaf8 --- /dev/null +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt @@ -0,0 +1,39 @@ +// 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 +import kotlin.test.assertTrue + +/** Production scheduling and worker code must not hold a WorkManager or main thread with `runBlocking`. */ +class SchedulingNoRunBlockingAuditTest { + private val scoped = Regex( + """(androidMain|commonMain)/.*/(jobs/schedule/.*|git/(GitSyncWorker|WorkManagerSyncScheduler|BackgroundSyncScheduler)[^/]*|platform/ml/DepthModelDownload[^/]*)""", + ) + + 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 + assertTrue(sources.keys.count(scoped::matches) > 10, "scope matched too few files, so the audit would pass vacuously") + assertEquals(emptyList(), violations(sources)) + } +} 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..bfed1dae6 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,7 +222,7 @@ class GitSyncCancelBoundaryTest { assertEquals(1, failing.count("abort")) } - // 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 mergeUnit_should_ReloadEveryChangedPathBeforeStopping_When_CancelArrivesRightAfterMerge() = runBlocking { val reloaded = CopyOnWriteArrayList() @@ -257,7 +257,7 @@ 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 + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun resolveConflicts_should_ReloadResolvedFiles_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -278,7 +278,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 applyJournalMerge_should_ReloadTheFile_When_CancelArrivesRightAfterCommit() = runBlocking { val (reloaded, loaderAndFs) = reloadingFixture() @@ -295,7 +295,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,7 +313,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 reloadMergedFiles_should_FlagReloadIncomplete_When_CancelledMidReload() = runBlocking { val fs = object : StubFileSystem() { @@ -329,7 +329,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 +354,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,7 +373,7 @@ 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 + // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @Test fun reloadIncomplete_should_StaySticky_UntilTheFailedPathsReloadCompletely() = runBlocking { val failing = java.util.concurrent.atomic.AtomicBoolean(true) @@ -416,7 +416,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..0656619a6 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceScheduledSyncTest.kt @@ -28,6 +28,7 @@ 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 +145,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 +158,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 +179,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 +196,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 +210,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 +221,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 +235,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 +246,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 +257,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 +267,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 +284,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 +307,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 +323,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 +348,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 +357,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 +377,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 +389,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 +399,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 +425,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 +440,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 +462,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 +472,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,7 +483,7 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // 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 `a review that becomes pending between the policy check and the sync is a first-sync skip`() = runBlocking { val gate = object : MapSettings() { 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/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() From 08bcaf0607da30d6620393c283a73760f0aa8f84 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 14:43:07 -0800 Subject: [PATCH 12/13] test(scheduling): restore runTest conversions lost in the main merge, convert 7 more The merge of main silently took the squash-merged #771 text in eight test files. --- .../stelekit/git/GitSyncCancelBoundaryTest.kt | 15 +++++-------- .../git/GitSyncMergeUnitContainmentTest.kt | 2 -- .../git/GitSyncServiceChangeBackTest.kt | 2 -- .../git/GitSyncServiceChangeGuardsTest.kt | 15 ------------- .../GitSyncServiceConflictMarkerGuardTest.kt | 4 ---- .../git/GitSyncServiceFirstSyncGateTest.kt | 3 --- .../git/GitSyncServiceLfsGuardTest.kt | 22 ------------------- .../git/GitSyncServiceScheduledSyncTest.kt | 4 +--- .../stelekit/git/SyncObservabilityLogTest.kt | 4 ---- .../stelekit/git/GitSyncServiceLfsJvmTest.kt | 3 --- .../ui/StelekitViewModelSyncStateTest.kt | 4 ++-- 11 files changed, 8 insertions(+), 70 deletions(-) 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 bfed1dae6..fcb38b2ed 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncCancelBoundaryTest.kt @@ -222,9 +222,8 @@ class GitSyncCancelBoundaryTest { assertEquals(1, failing.count("abort")) } - // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @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: this test times or races work on real dispatchers; virtual time would not wait for it @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: this test times or races work on real dispatchers; virtual time would not wait for it @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() } } @@ -313,9 +310,8 @@ class GitSyncCancelBoundaryTest { assertFalse(gate.isHeld(key())) } - // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @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") } } @@ -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: this test times or races work on real dispatchers; virtual time would not wait for it @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") } 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 8a8394cef..61cd32b54 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncMergeUnitContainmentTest.kt @@ -61,7 +61,6 @@ 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() = runTest { val seen = AtomicInteger() @@ -85,7 +84,6 @@ 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() = runTest { val svc = service(pages(1000), StubFileSystem()) 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 c11888ea7..cc26449d1 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeBackTest.kt @@ -71,7 +71,6 @@ 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`() = runTest { val (service, configRepo) = repairedService(remoteBranches = listOf("master")) @@ -83,7 +82,6 @@ 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`() = runTest { val (service, configRepo) = repairedService(remoteBranches = listOf("master", "main")) 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 2fa5c4b01..090b241b5 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceChangeGuardsTest.kt @@ -103,7 +103,6 @@ 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`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -117,7 +116,6 @@ 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`() = runTest { val spy = Spy(health = RepositoryHealth(false, "UNMERGED_PATHS")) @@ -129,7 +127,6 @@ 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`() = runTest { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("journals/2026_10_08.md")))) @@ -145,7 +142,6 @@ 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`() = runTest { val spy = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Incomplete("big.md is larger than 2048 KiB"))) @@ -156,7 +152,6 @@ 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`() = runTest { val spy = Spy(dirty = false, markers = mutableMapOf(GuardScope.NetPush to MarkerScan.Found(listOf("a.md")))) @@ -169,7 +164,6 @@ 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`() = runTest { val spy = Spy() @@ -180,7 +174,6 @@ 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`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(21, treeSize = 100))) @@ -194,7 +187,6 @@ 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`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.NetPush to deletions(30, treeSize = 100))) @@ -205,7 +197,6 @@ 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`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(20, treeSize = 100))) @@ -229,7 +220,6 @@ 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`() = runTest { val lowered = MapSettings().apply { putString(MassChangeThresholds.KEY_MIN_FILES, "3"); putString(MassChangeThresholds.KEY_PERCENT, "1") } @@ -254,7 +244,6 @@ 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`() = runTest { val spy = Spy(deletions = mutableMapOf(GuardScope.Staged to deletions(40, treeSize = 100))) @@ -270,7 +259,6 @@ 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`() = runTest { val unsafe = Spy(health = RepositoryHealth(false, "MERGING")) @@ -292,7 +280,6 @@ 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`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING"), markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("x.md")))) @@ -305,7 +292,6 @@ 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`() = runTest { val spy = Spy(health = RepositoryHealth(false, "MERGING")) @@ -316,7 +302,6 @@ 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`() = runTest { val commitBlocked = Spy(markers = mutableMapOf(GuardScope.Staged to MarkerScan.Found(listOf("j.md")))) 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 d613b355a..aab3b1c61 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceConflictMarkerGuardTest.kt @@ -74,7 +74,6 @@ 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`() = runTest { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -89,7 +88,6 @@ 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`() = runTest { assumeTrue("Skipped: requires network access for the NetworkMonitor.isOnline check", NetworkMonitor().isOnline) @@ -123,7 +121,6 @@ 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`() = runTest { val calls = mutableListOf() @@ -136,7 +133,6 @@ 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`() = runTest { val calls = mutableListOf() 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 576a21629..571a78ce2 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceFirstSyncGateTest.kt @@ -71,7 +71,6 @@ 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`() = runTest { val f = fixture(reviewPending = true) @@ -86,7 +85,6 @@ 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`() = runTest { val f = fixture(reviewPending = true) @@ -98,7 +96,6 @@ 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`() = runTest { val f = fixture(reviewPending = true) 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 4cecacda4..9f49cff5d 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsGuardTest.kt @@ -133,7 +133,6 @@ 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() = runTest { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf("pages/a.md" to "# a".encodeToByteArray(), photo to png)) @@ -150,7 +149,6 @@ 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() = runTest { val f = fixture(untracked = listOf(photo), modified = listOf("pages/a.md"), files = mapOf(photo to png)) @@ -161,7 +159,6 @@ 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() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to pointer)) @@ -174,7 +171,6 @@ 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() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to ByteArray(0))) @@ -185,7 +181,6 @@ 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() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -199,7 +194,6 @@ 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() = runTest { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.anythingStaged = false }) @@ -210,7 +204,6 @@ 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() = runTest { val f = fixture( @@ -229,7 +222,6 @@ 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() = runTest { val f = fixture(modified = listOf(".gitattributes", "x.png"), files = mapOf("x.png" to png), gitattributes = "*.png filter=lfs\n") @@ -240,7 +232,6 @@ 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() = runTest { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { fs -> @@ -259,7 +250,6 @@ 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() = runTest { val coordinator = LfsGuardCoordinator(MemoryFileSystem().also { it.files["/repo/.gitattributes"] = "* filter=lfs\n".encodeToByteArray() }, delegated = true) @@ -271,7 +261,6 @@ 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() = runTest { val f = fixture( @@ -289,7 +278,6 @@ 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() = runTest { val escaped = LfsViolation("assets/b.bin", LfsViolationReason.RawBinary, ".gitattributes:1") @@ -307,7 +295,6 @@ 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() = runTest { val f = fixture( @@ -324,7 +311,6 @@ 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() = runTest { val f = fixture(modified = listOf("pages/a.md"), files = mapOf("pages/a.md" to "x".encodeToByteArray()), configure = { it.stagedThrows = true }) @@ -336,7 +322,6 @@ 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() = runTest { val f = fixture(modified = listOf("pages/a.md", photo), files = mapOf(photo to png)) @@ -349,7 +334,6 @@ 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() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png), configure = { it.anythingStaged = false }) @@ -361,7 +345,6 @@ 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() = runTest { val f = fixture(files = mapOf(photo to png)) @@ -378,7 +361,6 @@ 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() = runTest { val f = fixture(files = mapOf(photo to png)) @@ -394,7 +376,6 @@ 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() = runTest { val f = fixture(files = mapOf(photo to pointer)) @@ -410,7 +391,6 @@ 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() = runTest { val f = fixture(gitattributes = "journals/** filter=lfs\n") @@ -423,7 +403,6 @@ 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() = runTest { val pushed = LfsViolation("assets/sneaky.bin", LfsViolationReason.RawBinaryPushed, ".gitattributes:1") @@ -436,7 +415,6 @@ 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() = runTest { val f = fixture(modified = listOf(photo), files = mapOf(photo to png)) 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 0656619a6..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,7 +23,6 @@ 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 @@ -483,9 +482,8 @@ class GitSyncServiceScheduledSyncTest { svc.shutdown() } - // runBlocking: this test times or races work on real dispatchers; virtual time would not wait for it @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/SyncObservabilityLogTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt index 42df99e96..2b46c9a33 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/git/SyncObservabilityLogTest.kt @@ -67,7 +67,6 @@ 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() = runTest { val verdicts = listOf( @@ -83,14 +82,12 @@ 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() = 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() = runTest { val result = service(ScriptedRepository(LockVerdict.OwnerUnknown(UnknownReason.TornRecord))).sync("g") @@ -98,7 +95,6 @@ class SyncObservabilityLogTest { 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() = runTest { val repo = ScriptedRepository(LockVerdict.NoLock) 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 2f46c4d86..c206a6211 100644 --- a/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt +++ b/kmp/src/jvmTest/kotlin/dev/stapler/stelekit/git/GitSyncServiceLfsJvmTest.kt @@ -129,7 +129,6 @@ 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() = runTest { File(work, "pages").mkdirs() @@ -156,7 +155,6 @@ 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() = runTest { File(work, "assets").mkdirs() @@ -172,7 +170,6 @@ 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() = runTest { File(work, "assets").mkdirs() 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), From b4199200e7ad5c64fe738f29c9d168bc62a6c425 Mon Sep 17 00:00:00 2001 From: Tyler Stapler Date: Thu, 26 Nov 2026 15:24:01 -0800 Subject: [PATCH 13/13] test(scheduling): widen the runBlocking guard's scope and cover link() cancel-during-release --- .../audit/SchedulingNoRunBlockingAuditTest.kt | 14 +++++-- .../db/GraphRelocationCoordinatorLinkTest.kt | 38 +++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt index 806bddaf8..c2c3c1ced 100644 --- a/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt +++ b/kmp/src/businessTest/kotlin/dev/stapler/stelekit/audit/SchedulingNoRunBlockingAuditTest.kt @@ -7,12 +7,19 @@ import dev.stapler.stelekit.wiring.WiringAudit import dev.stapler.stelekit.wiring.WiringInputs import kotlin.test.Test import kotlin.test.assertEquals -import kotlin.test.assertTrue /** Production scheduling and worker code must not hold a WorkManager or main thread with `runBlocking`. */ class SchedulingNoRunBlockingAuditTest { private val scoped = Regex( - """(androidMain|commonMain)/.*/(jobs/schedule/.*|git/(GitSyncWorker|WorkManagerSyncScheduler|BackgroundSyncScheduler)[^/]*|platform/ml/DepthModelDownload[^/]*)""", + """(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 @@ -33,7 +40,8 @@ class SchedulingNoRunBlockingAuditTest { @Test fun noProductionSchedulingSourceUsesRunBlocking() { val sources = WiringInputs.productionSources - assertTrue(sources.keys.count(scoped::matches) > 10, "scope matched too few files, so the audit would pass vacuously") + 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/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() + } } +