kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

TestCoroutineScheduler leaks canceled delayed jobs

Open pyricau opened this issue 2 years ago • 3 comments

Jobs that are cancelled are expected to become garbage collectable. Unfortunately, TestCoroutineScheduler does not listen to any job cancellation signal. TestCoroutineScheduler keeps cancelled jobs in its queue (TestCoroutineScheduler#events) until the current time of TestCoroutineScheduler is advanced past the original planned time of the job that was cancelled.

I'm providing a unit test that reproduces this issue here: https://github.com/Kotlin/kotlinx.coroutines/pull/3399

This is unfortunately a major bug for us at Square / Block, because:

  • TestCoroutineScheduler is used by Compose in its provided test rules
  • Compose clickable element in scrollable containers set their pressed state using a delayed cancellable job (source) and that delayed cancellable job has a transitive strong reference to the backing AndroidComposeView.
  • As a result, if said AndroidComposeView gets detached, the TestCoroutineScheduler will prevent it from being garbage collected until its time is past the clickable timeout. In our UI tests, automatic leak detection triggers in between (as the view gets detached) and fails the test.
  • So basically we ended up having to disable leak detection in all our Compose tests due to this TestCoroutineScheduler bug.

If we reach into TestCoroutineScheduler#events using reflection to clear all canceled jobs from the queue, the jobs do become garbage collectable and we can keep leak detection enabled in our Compose test (which is a huge deal for us)

We initially filed this as a Compose bug here: https://issuetracker.google.com/issues/238277402

pyricau avatar Aug 09 '22 23:08 pyricau

Thanks for the detailed report! @dkhalanskyjb who is the main maintainer of the test module is on vacation right now, so delayed (he-he) answer here is expected

qwwdfsad avatar Aug 10 '22 08:08 qwwdfsad

Thank you! Yes, this is a bug in the test module. The fix, as is common, a single line of code.

dkhalanskyjb avatar Sep 06 '22 11:09 dkhalanskyjb

Nice fix, thanks!

pyricau avatar Sep 13 '22 19:09 pyricau