From adf49762df22f2dd7fd33fc1edf7382974dce05f Mon Sep 17 00:00:00 2001 From: Ilya Nekrasov Date: Thu, 12 Nov 2026 11:19:54 +0000 Subject: [PATCH 1/3] Fix null arguments, state retention and dropped state updates --- CHANGELOG.md | 15 ++++ README.md | 6 +- gradle.properties | 2 +- .../ru/kode/reactivetasks/ReactiveTasks.kt | 43 +++++------ .../reactivetasks/ObserveStateChangesTest.kt | 25 +++++++ .../ru/kode/reactivetasks/SchedulerTest.kt | 71 ++++++++++++++----- 6 files changed, 117 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43de9bb..747af15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 2.0.1 - 2026-11-12 + +### Fixed + +- `launch`, `launchLatest`, `launchIfIdle`, `start`, `startIfIdle` threw `NullPointerException` on JVM/Android when + the argument was `null`. A `null` argument now works everywhere, and `relaunch` re-runs a job with a `null` argument + instead of returning `JobHandle.NIL`. +- Memory leak: a scheduler kept the argument and the state of every job ever started. The argument is now stored in + the `JobHandle`, and `Scheduler.taskJobState` keeps only the last finished job of each task (plus jobs which are + still running). States of older finished jobs and of cancelled jobs are removed. Read finished states with + `finishedStates` / `results` instead of looking up old job ids in `taskJobState`. +- A job could get dropped and `start` could hang forever when an observer of the task (`results`, `finishedStates`, + ...) started the next job from inside its collector. State updates to observers no longer suspend the job which + publishes them. + ## 2.0.0 - 2026-11-12 ### Changed (breaking) diff --git a/README.md b/README.md index 82561af..394e600 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A library for scheduling, executing and observing repeateble reactive tasks. Kotlin Multiplatform: JVM, Android, iOS (`iosX64`, `iosArm64`, `iosSimulatorArm64`). ```kotlin -implementation("ru.kode:reactive-tasks:2.0.0") +implementation("ru.kode:reactive-tasks:2.0.1") ``` # How to use @@ -172,7 +172,7 @@ reactive-tasks drops the `ReactiveModel` base class and `kotlin-result`, and add // before implementation("ru.kode:remo:1.2.0") // or ru.kode:remo:9.0.1, ru.kode.android:remo:9.1.0 // after -implementation("ru.kode:reactive-tasks:2.0.0") +implementation("ru.kode:reactive-tasks:2.0.1") ``` remo 1.2.0 and 9.x differ only in how a model gets its scope; tasks and `JobFlow` are the same. @@ -180,7 +180,7 @@ Below `scheduler` is a `Scheduler`, `fetch` is a `TaskHandle`. ## API map -| remo 1.2.0 | remo 9.0.1 | reactive-tasks 2.0.0 | +| remo 1.2.0 | remo 9.0.1 | reactive-tasks 2.0.1 | |---|---|---| | `class M : ReactiveModel(dispatcher)` | `class M(scope) : ReactiveModel(scope)` | `class M(scheduler: Scheduler)`, no base class | | `model.start(parentScope)`, `Job.cancel()` to stop, can be started again with a new scope | constructor `scope`, cancel it to stop | `Scheduler(scope)`, cancel `scope` to stop for good; to stop and start again: `scheduler.bindTo(parentScope)` on each start | diff --git a/gradle.properties b/gradle.properties index 3248f2b..9b7fd85 100644 --- a/gradle.properties +++ b/gradle.properties @@ -11,7 +11,7 @@ kotlin.mpp.enableCInteropCommonization=true android.useAndroidX=true android.nonTransitiveRClass=true #Publishing -versionName=2.0.0 +versionName=2.0.1 pomGroupId=ru.kode pomName=Reactive Tasks pomDescription=Kotlin Multiplatform library for scheduling, executing and observing reactive tasks diff --git a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt index f2aa1a6..777a4ef 100644 --- a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt +++ b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt @@ -59,6 +59,7 @@ class TaskHandle( @OptIn(ExperimentalUuidApi::class) class JobHandle( val taskHandle: TaskHandle, + internal val argument: Any? = null, val id: Uuid, internal val job: Job, ) { @@ -200,17 +201,17 @@ class Scheduler( e.printStackTrace() } ) { - // TODO use configurable entry count? /** - * A map from either JobHandle.id or TaskHandle.id to an argument object. + * A map from TaskHandle.id to a single-element list holding the most recent argument (a list, because + * concurrent maps do not accept null values and null is a valid argument). */ - private val argumentCache: MutableMap = createConcurrentMutableMap() + private val lastArgument: MutableMap> = createConcurrentMutableMap() - // TODO evict states after some time/entry-count? private val _taskJobState: MutableMap = createConcurrentMutableMap() /** - * A map of jobId to task job states + * A map of jobId to task job states. Only the last finished job of each task is kept, plus jobs which are still + * running. States of older finished jobs and of cancelled jobs are removed. */ val taskJobState: Map = _taskJobState @@ -320,8 +321,7 @@ class Scheduler( */ suspend fun start(handle: TaskHandle, argument: A, tag: Any? = null): JobState { val jobId = Uuid.random() - argumentCache.put(jobId, argument as Any?) - argumentCache.put(handle.id, argument as Any?) + lastArgument[handle.id] = listOf(argument) return executeWrappedBody(handle, jobId, argument, tag) } @@ -374,8 +374,7 @@ class Scheduler( private fun startInternal(handle: TaskHandle, argument: A, tag: Any?, cancelPrevious: Boolean): JobHandle { val jobId = Uuid.random() - argumentCache.put(jobId, argument as Any?) - argumentCache.put(handle.id, argument as Any?) + lastArgument[handle.id] = listOf(argument) // NOTE @dz there can be a race if children will change between we get them here and // before new job gets scheduled val previousJobs = handle.scope.coroutineContext.job.children.toList() @@ -401,6 +400,7 @@ class Scheduler( handle as TaskHandle, jobId, job, + argument, ) } @@ -410,7 +410,8 @@ class Scheduler( if (state.runState == RunState.Running) { runningTaskState[handle.id] = state } else { - finishedTaskState[handle.id] = state + // only the last finished job of a task is kept + finishedTaskState.put(handle.id, state)?.let { if (it.jobId != jobId) _taskJobState.remove(it.jobId) } forgetRunning(handle.id, jobId) } stateChangeListeners.forEach { it.onJobStateChanged(state) } @@ -427,6 +428,7 @@ class Scheduler( } } catch (e: CancellationException) { forgetRunning(handle.id, jobId) + _taskJobState.remove(jobId) throw e } } @@ -449,13 +451,9 @@ class Scheduler( * Note that there is an overload which accepts [JobHandle] instead and it will use the argument from the particular job start. */ fun relaunch(handle: TaskHandle): JobHandle { + val last = lastArgument[handle.id] ?: return JobHandle.NIL @Suppress("UNCHECKED_CAST") - val arg = argumentCache[handle.id] as? A? - return if (arg != null) { - launch(handle, arg) - } else { - JobHandle.NIL - } + return launch(handle, last[0] as A) } /** @@ -464,12 +462,8 @@ class Scheduler( * Note that there is an overload which accepts [TaskHandle] instead and it will use the argument from the most recent task start. */ fun relaunch(handle: JobHandle): JobHandle { - val arg = argumentCache[handle.id] - return if (arg != null) { - launch(handle.taskHandle, arg) - } else { - JobHandle.NIL - } + if (handle.id == Uuid.NIL) return JobHandle.NIL + return launch(handle.taskHandle, handle.argument) } /** @@ -653,7 +647,8 @@ private fun Scheduler.stateChanges( return callbackFlow { val listener = object : TaskStateChangeListener { override suspend fun onJobStateChanged(state: JobState) { - if (state.taskId == handle.id) send(state) + // never suspends and never throws into the job which publishes the state + if (state.taskId == handle.id) trySend(state) } override fun onJobCancelled(taskId: Uuid, jobId: Uuid) { @@ -672,5 +667,5 @@ private fun Scheduler.stateChanges( } replayed?.let { listener.onJobStateChanged(it) } awaitClose { this@stateChanges.removeTaskStateChangeListener(listener) } - } + }.buffer(Channel.UNLIMITED) } diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt index d325c49..086477b 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -366,4 +366,29 @@ class ObserveStateChangesTest { assertEquals(listOf(false, true, false), running) } + + @Test + fun observerStartingNextJobOnResultDoesNotDropJobs() = runTest { + val scheduler = testScheduler() + val ran = mutableListOf() + val task = scheduler.registerTask("chain") { n: Int -> ran += n; n } + // observer A, subscribed first + val a = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + scheduler.results(task, replayLast = false).first() + } + // observer B starts the next job when the first result arrives and waits for it + var second: JobState? = null + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + scheduler.results(task, replayLast = false).first() + second = scheduler.start(task, 2) + } + runCurrent() + + scheduler.launch(task, 1) + advanceUntilIdle() + + assertTrue(a.isCompleted) + assertEquals(listOf(1, 2), ran) + assertEquals(RunState.FinishedSuccess, second?.runState) + } } diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt index 1876d3c..5f86a3e 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/SchedulerTest.kt @@ -29,6 +29,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue @@ -165,8 +166,9 @@ class SchedulerTest { assertEquals(RunState.Running, scheduler.taskJobState.getValue(second.id).runState) advanceUntilIdle() - assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(first.id).runState) - assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(second.id).runState) + // only the last finished job of a task is kept in taskJobState + assertEquals(1, scheduler.taskJobState.size) + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.values.single().runState) } @Test @@ -218,8 +220,9 @@ class SchedulerTest { listener.events, ) assertTrue(first.job.isCancelled) - // quirk: a cancelled job's state stays Running forever - assertEquals(RunState.Running, scheduler.taskJobState.getValue(first.id).runState) + // state of a cancelled job is removed, only the last finished job is kept + assertNull(scheduler.taskJobState[first.id]) + assertEquals(RunState.FinishedSuccess, scheduler.taskJobState.getValue(second.id).runState) } // endregion @@ -326,20 +329,54 @@ class SchedulerTest { } @Test - fun restartAfterNullArgument() = runTest { + fun nullArgumentWorksEverywhere() = runTest { val scheduler = testScheduler() - val task = scheduler.registerTask("nullable") { _: String? -> } - - val started = runCatching { scheduler.launch(task, null) } - // quirk: JVM/Android argumentCache is a ConcurrentHashMap, which rejects null values, so start throws NPE. - // iOS LockedMap accepts null, but restart treats a null argument as "never started" and returns NIL. - val error = started.exceptionOrNull() - if (error != null) { - assertIs(error) - } else { - assertSame(JobHandle.NIL, scheduler.relaunch(task)) - assertSame(JobHandle.NIL, scheduler.relaunch(started.getOrThrow())) - } + val seen = mutableListOf() + val task = scheduler.registerTask("nullable") { a: String? -> seen += a; a } + + scheduler.launch(task, null) + scheduler.launchLatest(task, null) + assertNull(scheduler.launchIfIdle(task, null)) // dropped, two jobs running + advanceUntilIdle() + assertNotNull(scheduler.launchIfIdle(task, null)) + advanceUntilIdle() + assertNull(scheduler.start(task, null).argument) + assertNull(scheduler.startIfIdle(task, null)?.argument) + assertEquals(5, seen.size) + assertTrue(seen.all { it == null }) + } + + @Test + fun relaunchReRunsWithNullArgument() = runTest { + val scheduler = testScheduler() + var runs = 0 + val task = scheduler.registerTask("nullable") { _: String? -> runs++ } + + val first = scheduler.launch(task, null) + val byTask = scheduler.relaunch(task) + val byJob = scheduler.relaunch(first) + advanceUntilIdle() + + assertNotEquals(JobHandle.NIL, byTask) + assertNotEquals(JobHandle.NIL, byJob) + assertEquals(3, runs) + } + + @Test + fun launchDoesNotRetainOldStatesOrArguments() = runTest { + val scheduler = testScheduler() + val task = scheduler.registerTask("echo") { s: String -> s } + + val handles = (1..50).map { scheduler.launch(task, "arg$it") } + advanceUntilIdle() + + assertEquals(1, scheduler.taskJobState.size) + assertEquals(1, scheduler.finishedTaskState.size) + assertEquals(scheduler.finishedTaskState.getValue(task.id).jobId, scheduler.taskJobState.keys.single()) + // the argument lives only in the handle, relaunch by an old handle still works + val again = scheduler.relaunch(handles.first()) + advanceUntilIdle() + assertEquals("arg1", scheduler.taskJobState.getValue(again.id).result) } // endregion From 30ae16203f0ec6a4742a9364409b2beaa553fd45 Mon Sep 17 00:00:00 2001 From: Ilya Nekrasov Date: Thu, 12 Nov 2026 11:22:38 +0000 Subject: [PATCH 2/3] Fix JobHandle constructor parameter order --- .../commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt index 777a4ef..41da0ec 100644 --- a/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt +++ b/library/src/commonMain/kotlin/ru/kode/reactivetasks/ReactiveTasks.kt @@ -59,9 +59,9 @@ class TaskHandle( @OptIn(ExperimentalUuidApi::class) class JobHandle( val taskHandle: TaskHandle, - internal val argument: Any? = null, val id: Uuid, internal val job: Job, + internal val argument: Any? = null, ) { companion object { /** From ded92b6f473323d742ea8b55addd08d01b467971 Mon Sep 17 00:00:00 2001 From: Ilya Nekrasov Date: Thu, 12 Nov 2026 11:25:05 +0000 Subject: [PATCH 3/3] Add missing test import --- .../kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt index 086477b..7c4f4f5 100644 --- a/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt +++ b/library/src/commonTest/kotlin/ru/kode/reactivetasks/ObserveStateChangesTest.kt @@ -8,6 +8,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope