Every conversion writes a full-size file into <cacheDir>/conversions/. save()
published it and deleted it, but reset() -- what the "Start over" button on the
Converted and Joined states calls -- dropped the File reference and left the file
behind. Converting something and deciding not to save it is an ordinary path
through the UI, so it leaked a full-size copy every time. cacheDir is evictable,
so this was never unbounded growth; it was the app relying on the OS to clean up
after it, and on a device under no storage pressure "eventually" means never.
OutputPublisher.clearStaging() was written for exactly this and called from
nowhere. It is NOT wired up here -- it is deleted. It emptied the directory
unconditionally, and the convert tab, the join tab and ConcatEngine's
concat_list.txt all share that directory with no per-job namespacing (D8), so a
blanket delete could take a file out from under a running job. Two narrower
methods replace it:
discardStaged(file) one file, guarded. The handle reaches the ViewModel as a
path string in WorkInfo.outputData and becomes a File with
nothing checking where it points, so this compares the
CANONICAL parent against the staging dir -- the naive
string comparison accepts conversions/../elsewhere.
sweepStaging(now) age-based, for orphans no ViewModel is left to clean up.
The cleanup handle is a ViewModel field, not something read back out of the state
machine, because the state machine cannot answer it on the path that needs it
most: a failed save lands on Failed(message), which carries no file reference at
all. On that path the file is deliberately kept -- it may be the only copy of an
hour of transcoding and the destination did not receive it, so deleting to tidy a
cache directory would destroy the work. It stays collectable by a later reset()
or by the sweep.
The sweep runs once per process from a new Application subclass, off the main
thread. The reason it cannot race a live job is the grace period, not ordering:
WorkManager initialises through androidx.startup's InitializationProvider, a
ContentProvider, so it is already up before onCreate() and can be resuming a
worker in this same process while the sweep runs. StagingSweep only collects a
file nothing has written to for 24 hours. Outputs are written continuously and
keep their own mtime fresh; concat_list.txt is the one file written once and then
only read, and a WorkManager attempt is capped by the six-hour foreground-service
budget with retries restarting doWork() from the top, so no attempt can hold a
file still for a day. sweepStaging() also re-reads each timestamp immediately
before deleting, closing the window between listing the directory and acting on
the list -- unlinking an inode a running job still holds open would end with the
job reporting success for a path that no longer exists.
The rule itself is a pure function over (name, lastModifiedMs) pairs and a clock.
Timestamps are values rather than Files so the tests measure the arithmetic --
the grace boundary, and a clock that moved backwards -- rather than the
filesystem's mtime granularity.
Tests cover the tool AND the wiring, because the wiring is where the defect was.
A pure rule test and a Robolectric test of OutputPublisher both stay green when
the discardStaged call is deleted from reset(), which would have made the number
read as coverage of a bug that was still there. So both ViewModels are driven --
through a real WorkManager, to Converted/Joined -- and then asserted on the
filesystem: Start over deletes the staged file; a successful save leaves nothing
to delete twice; a failed save keeps the file and a later reset collects it, which
pins the argued decision above rather than leaving it as a comment. Verified by
deleting the discardStaged line from both reset() methods: 4 of the 6 fail with
"reset() should have discarded exactly the staged file expected:<[...]> but
was:<[]>", and the two save-path tests correctly stay green.
Three things made that reachable, all reusing what was already here:
- Both ViewModels now resolve their publisher through ConversionDependencies,
like the workers already did. They were the only place bypassing the seam.
- MediaProbe joins that seam too. It spawns FFprobe, and FFmpegKit's loader
throws a bare java.lang.Error when the native library is absent -- which its
own `catch (e: Exception)` cannot catch, so every JVM test died on the file
pick. Instrumented tests are unaffected and still get the real probe.
That error path is a LATENT PRODUCTION HAZARD, recorded in the KDoc and
deliberately not fixed here: onInputPicked does not catch it either, so a
missing .so would surface as an uncaught error rather than the "could not read
this file" the code was written to give. It cannot fire on a device that ships
the libraries, so widening MediaProbe's catch to Throwable would change the
pick path on the strength of a condition no user meets. Its own commit.
- reset()'s cleanup dispatcher is a constructor parameter defaulting to
Dispatchers.IO, which makes the delete assertable and states the ordering --
Idle is published synchronously, the delete is dispatched -- as a decision
rather than an accident. @JvmOverloads keeps the single-argument constructor
that viewModel()'s AndroidViewModelFactory looks up reflectively.
androidx-work-testing was already in the catalog and already inside the prerelease
guard via its androidx. group, so it needed no new pinning argument.
Robolectric is added for the one assertion no pure function can make: that the
file is really gone from a real cacheDir. It is PINNED at 4.16.1 and belongs with
ktlint/detekt/jacoco rather than the floating libraries. The prerelease guard in
app/build.gradle.kts only covers androidx., junit and com.arthenica, so
org.robolectric is unguarded and a "4.+" would resolve to 4.17-beta-3; beyond
that, a bump changes which android-all jar the tests execute against, which is the
same "a tool moved under a diff that cannot explain it" failure the linters are
pinned for.
Two things Robolectric needed. testOptions did not exist in this module at all;
it now sets isIncludeAndroidResources so the merged manifest and resource table
reach the JVM tests, and grants --enable-native-access, which Java 25 otherwise
warns about four times per run when Robolectric's native runtime calls
System.load(). And robolectric.properties pins sdk=36: Robolectric defaults to the
manifest's targetSdk of 37, there is no android-all jar for 37, and the class
fails to initialise before any test body runs. 36 is where CI's emulator matrix
already stops, so this does not widen the gap -- API 37 was already a manual check
on the Pixel 10 Pro XL before each release.
Known and left alone: a conversion that fails inside the worker never reaches
Converted, so pendingStaged is never set and any partial output relies on the
sweep alone. reset()'s delete is also fire-and-forget on viewModelScope, so it is
cancelled if the Activity finishes first. The sweep is the backstop for both.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
119 lines
4.7 KiB
Kotlin
119 lines
4.7 KiB
Kotlin
package org.libremediaconverter.convert
|
|
|
|
import android.app.Application
|
|
import android.net.Uri
|
|
import androidx.media3.common.util.UnstableApi
|
|
import androidx.work.workDataOf
|
|
import kotlinx.coroutines.Dispatchers
|
|
import org.junit.After
|
|
import org.junit.Assert.assertEquals
|
|
import org.junit.Assert.assertFalse
|
|
import org.junit.Assert.assertTrue
|
|
import org.junit.Before
|
|
import org.junit.Test
|
|
import org.junit.runner.RunWith
|
|
import org.libremediaconverter.model.InputProbe
|
|
import org.libremediaconverter.work.ConversionWorker
|
|
import org.robolectric.RobolectricTestRunner
|
|
import org.robolectric.RuntimeEnvironment
|
|
import java.io.File
|
|
|
|
/**
|
|
* That `reset()` actually deletes — the wiring, not the tool.
|
|
*
|
|
* D2 was never that `OutputPublisher` could not delete a file. It was that "Start over"
|
|
* dropped the reference without calling anything. So this drives the real ViewModel through
|
|
* a real `WorkManager` to `Converted` and then asserts on the filesystem.
|
|
*/
|
|
@UnstableApi
|
|
@RunWith(RobolectricTestRunner::class)
|
|
class ConversionViewModelCleanupTest {
|
|
|
|
private lateinit var app: Application
|
|
private lateinit var publisher: RecordingPublisher
|
|
private lateinit var staged: File
|
|
|
|
@Before
|
|
fun setUp() {
|
|
app = RuntimeEnvironment.getApplication()
|
|
publisher = RecordingPublisher(app)
|
|
ConversionDependencies.publisher = { publisher }
|
|
// MediaProbe spawns FFprobe, whose loader throws a bare java.lang.Error with no
|
|
// native library present. Without this the pick dies before the test starts.
|
|
ConversionDependencies.probe = { _, _ -> InputProbe() }
|
|
|
|
staged = publisher.createStagingFile("holiday.mp4").apply { writeBytes(ByteArray(4096)) }
|
|
installTestWorkManager(app, workDataOf(ConversionWorker.KEY_OUTPUT_PATH to staged.absolutePath))
|
|
}
|
|
|
|
@After
|
|
fun tearDown() {
|
|
ConversionDependencies.reset()
|
|
}
|
|
|
|
@Test
|
|
fun `start over on a finished conversion deletes the staged file`() {
|
|
val viewModel = convertedViewModel()
|
|
assertTrue("the conversion should have produced a staged file", staged.exists())
|
|
|
|
viewModel.reset()
|
|
|
|
assertEquals(ConversionState.Idle, viewModel.state.value)
|
|
assertEquals("reset() should have discarded exactly the staged file", listOf(staged), publisher.discarded)
|
|
assertFalse("Start over must not leave a full-size copy in cache", staged.exists())
|
|
}
|
|
|
|
@Test
|
|
fun `reset after a successful save does not try to delete again`() {
|
|
val viewModel = convertedViewModel()
|
|
viewModel.save(DESTINATION)
|
|
awaitState(viewModel.state, "Saved") { it is ConversionState.Saved }
|
|
|
|
// save() deletes the staged file itself, through File.delete() rather than through
|
|
// the publisher, so assert the disappearance as well as the absent second discard.
|
|
assertFalse("a successful save should have removed the staged file", staged.exists())
|
|
|
|
viewModel.reset()
|
|
|
|
// Discarding again would be a delete aimed at a path this ViewModel no longer owns.
|
|
assertEquals(emptyList<File>(), publisher.discarded)
|
|
assertFalse(staged.exists())
|
|
}
|
|
|
|
@Test
|
|
fun `a failed save keeps the staged file, and a later reset collects it`() {
|
|
val viewModel = convertedViewModel()
|
|
publisher.publishFailure = IllegalStateException("destination volume full")
|
|
|
|
viewModel.save(DESTINATION)
|
|
awaitState(viewModel.state, "Failed") { it is ConversionState.Failed }
|
|
|
|
// The deliberate decision, pinned: the staged file may be the only copy of an hour
|
|
// of transcoding, and the destination did not receive it.
|
|
assertTrue("a failed save must not destroy the only copy", staged.exists())
|
|
assertEquals(emptyList<File>(), publisher.discarded)
|
|
|
|
// Failed carries no file reference at all, so this only works because the handle is
|
|
// a ViewModel field rather than something read back out of the state machine.
|
|
viewModel.reset()
|
|
|
|
assertEquals(listOf(staged), publisher.discarded)
|
|
assertFalse(staged.exists())
|
|
}
|
|
|
|
/** A ViewModel driven all the way to [ConversionState.Converted]. */
|
|
private fun convertedViewModel(): ConversionViewModel {
|
|
// Unconfined so reset()'s delete runs inline instead of on a real IO thread.
|
|
val viewModel = ConversionViewModel(app, Dispatchers.Unconfined)
|
|
viewModel.onInputPicked(Uri.parse("content://test/holiday.mp4"))
|
|
awaitState(viewModel.state, "Ready") { it is ConversionState.Ready }
|
|
viewModel.convert()
|
|
awaitState(viewModel.state, "Converted") { it is ConversionState.Converted }
|
|
return viewModel
|
|
}
|
|
|
|
private companion object {
|
|
val DESTINATION: Uri = Uri.parse("content://test/destination.mp4")
|
|
}
|
|
}
|