ASTRA_FINDINGS.md
docs/reviews/ASTRA_FINDINGS.md
1# Yokan code review23Reviewed 2026-09-07, against commit `3cbd712` and the current working tree.45The review identified **nine correctness/reliability findings** and **four project-structure recommendations**. The most urgent problems concern database concurrency, loss of user changes during refresh/restore, and unsigned Android release artifacts.67Priority: **P1** = fix before release because of data loss, deadlock, or an unusable release artifact; **P2** = actionable functional/reliability defect. Structural recommendations are separate from these bug priorities.89## Remediation status — 2026-09-071011All F1–F9 findings were addressed in the follow-up change set. This includes guarded snapshot replacement and Room write serialization, refresh-state preservation, fail-safe restore, signed release artifacts, integrity-marked downloads, reader-session cleanup, and browser persistence recovery. The implementation is covered by the desktop suite (452 tests), Android JVM unit tests, Android/Wasm/iOS compilation, and release-signing checks with a temporary key.1213S1 and S2 remain deliberate incremental refactoring recommendations; no module split or broad UI-state migration was included. Browser storage remains `localStorage`, not an IndexedDB migration. iOS uses a bounded `Dispatchers.Default` view for Room because `Dispatchers.IO` is not public for this Kotlin/Native target; its native filesystem path compiles, but device-level filesystem failure testing remains future work.1415## Findings1617### F1 — P1: Sync and library updates acquire database locks in opposite orders1819Locations:2021- `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/database/room/RoomYokanDatabase.kt:303–308`22- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/InMemoryYokanDatabase.kt:293–305`23- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt:311–312`24- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt:203`2526`RoomYokanDatabase.batch` acquires `batchLock` and then the in-memory delegate's lock. `applyRemote` acquires the delegate's lock first; hub sync calls `database.batch` inside that block, requesting `batchLock` second. A library refresh or local-library scan can run concurrently with sync.2728The deadlock is a concrete two-thread interleaving:2930| Operation | Lock held | Lock requested |31|---|---|---|32| Library update enters `database.batch` | Room `batchLock` | Delegate lock |33| Sync enters `database.applyRemote { database.batch { … } }` | Delegate lock | Room `batchLock` |3435Neither operation can finish. Subsequent reads/writes waiting for the delegate also block, potentially freezing UI actions.3637**Recommendation:** establish one lock order across the Room facade, including `applyRemote`, ordinary writes, and batches. Ensure all callers acquire the outer serialization lock before the delegate lock. Add a concurrent sync/update test with a bounded completion deadline.3839**Validation:** high-confidence static lock/caller trace; not reproduced as a live application hang.4041### F2 — P1: Concurrent writes can persist in a different order from their in-memory mutations4243Location: `composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/database/room/RoomYokanDatabase.kt:329–345`; the same separation exists in `upsertSource` at lines 205–208 and other untracked writes.4445`tracked` mutates the delegate under its lock, releases that lock, and only then acquires `batchLock` to enqueue persistence. Serial execution of the queue therefore does not guarantee the same ordering as the mutations it represents.4647For example, thread A updates a chapter to version A and is descheduled before `queueWrite`. Thread B updates it to version B and enqueues B. A resumes and enqueues A. Memory now contains B, but SQLite finishes with A. Restarting restores stale progress; synced outbox rows can also be overwritten in this reversed order.4849**Recommendation:** serialize the entire mutate/capture/enqueue operation, consistently with F1. Cover every mutation method, not only `tracked`. Add a test that forces two writes to the same row to interleave and compares the live state with the reopened database.5051**Validation:** high-confidence static interleaving analysis; the existing Room test checks a completed bulk replacement, not competing ordinary writes.5253### F3 — P1: Library refresh overwrites user edits made while the source request is running5455Location: `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LibraryUpdaterService.kt:180–234`.5657`updateTitle` captures the manga and chapters before fetching remote details. `updateLibrary` captures its candidate titles and chapter map even earlier, before processing the work list. After the request finishes, `updateOne` copies those old objects back into the database, including local fields such as `favorite`, `isRead`, and `lastPageRead`.5859If the user reads a chapter, bookmarks it, or removes a favorite during a slow update, the response can revert that newer state. The final `database.batch` does not help because the values were captured before the network request.6061**Recommendation:** fetch remote metadata first, then read the current local records inside the mutation boundary and update only source-owned fields. Do not resurrect a title deleted while the request was pending.6263**Validation:** reproduced with the actual updater and an extension fake that changed the database during `detail()`. A favorite changed to `false` returned to `true`; a chapter changed to read at page `8` returned to unread with an empty page position.6465**Regression check:** pause a detail response, change favorite/read/bookmark state, resume the response, and assert the local edits survive.6667### F4 — P1: Restore silently proceeds when its promised safety backup cannot be written6869Locations:7071- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupService.kt:465–492`72- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/SettingsScreens.kt:4167–4170`7374The confirmation promises an automatic safety backup so the change can be rolled back. However, `applyBackupInternal` catches every error from `recordSafetySnapshot` and continues with replacement. If the backup directory is unwritable or storage is full, a successful replacement discards the old library without a recoverable safety snapshot. The later rollback block only runs when applying the new snapshot fails; it does not protect a successful destructive restore.7576**Recommendation:** fail before replacement when the safety snapshot cannot be created, and show the error. If proceeding without one is supported, require an explicit choice after explaining that rollback will be unavailable. Preserve cancellation as well.7778**Validation:** reproduced using the actual backup service, a valid exported empty backup, and a file service whose writes throw `Disk full`. Replace completed, removed the existing title, and left no safety snapshot.7980**Regression check:** inject failure on the safety-file write and verify the original database remains unchanged.8182### F5 — P1: Android release workflows publish an unsigned APK8384Locations:8586- `composeApp/build.gradle.kts:218–242`87- `.github/workflows/release.yml:51–57`88- `.forgejo/workflows/release.yml:41–47`8990The application defines no release signing configuration. Both workflows run `assembleRelease`, rename the resulting APK, and upload it without a signing step. The released APK consequently cannot be installed as a normal Android application. Android requires release APK signing; renaming the unsigned output does not provide it. See the [official command-line build and signing documentation](https://developer.android.com/build/building-cmdline?hl=en).9192**Recommendation:** configure a stable release signing key through CI secrets, or explicitly sign the built artifact before uploading. Verify the exact final artifact using `apksigner verify` and fail publication if verification fails.9394**Validation:** `rtk ./gradlew :composeApp:signingReport --console=plain` reported:9596```text97Variant: release98Config: null99Store: null100Alias: null101```102103No release was published or installed during this review.104105### F6 — P2: Interrupted downloads are accepted as complete based only on file existence106107Location: `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadService.kt:296–301` and `443–468`.108109`attemptDownload` streams directly into the final page filename. If the process terminates after the first chunk, that filename remains with incomplete content. On retry after restart, `runDownload` sees `files.exists(targetPath)`, increments `succeeded`, and skips the HTTP request. There is no completeness marker, expected-length check, or temporary-file promotion.110111The chapter can therefore be marked downloaded, and potentially archived to CBZ, with a truncated image or video. This applies to ordinary page/file downloads; HLS takes a separate path.112113**Recommendation:** stream into a temporary filename and promote it only after a successful complete response. Remove/restart leftover temporary files on recovery. Do not use final-name existence as proof of a completed transfer unless final-name creation guarantees completion.114115**Validation:** static trace of the writer and recovery branch.116117**Regression check:** simulate process interruption after one chunk, create a new downloader over the same files, retry, and assert a new transfer occurs and the final bytes match the full response.118119### F7 — P2: Reopening a reader route reuses a closed session and stale chapter state120121Locations:122123- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderRoute.kt:31–47`124- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ReaderViewModel.kt:365–380`125126`ReaderRoute` obtains a ViewModel keyed only by manga/chapter IDs from the ambient owner. The custom navigation does not supply a separate `ViewModelStoreOwner` per reader entry or clear its store on exit. A ViewModel outlives the removal of its composable, as documented by the [AndroidX `viewModel` implementation](https://android.googlesource.com/platform/frameworks/support/+/06f1103d80734d4dd2a7741f7fe8df6f0db79fe4/lifecycle/lifecycle-viewmodel-compose/src/main/java/androidx/lifecycle/viewmodel/compose/ViewModel.kt).127128On exit, `Disposed` permanently sets `sessionClosed = true`. Opening the same key retrieves that instance, and `ReadingResumed` refuses to restart the session. Subsequent close calls return without saving the final position/time. Furthermore, seamless navigation can change the ViewModel's active chapter while retaining its original route key: opening chapter A, advancing into B, exiting, and reopening A can return the old state showing B.129130**Recommendation:** align ViewModel ownership with actual navigation-entry lifetime and clear popped entries, or implement an explicit, complete session reinitialization on re-entry. Merely adding another key leaves retained instances accumulating in the owner.131132**Validation:** static route/owner/session trace. Existing reader tests instantiate ViewModels directly and do not exercise leaving and reopening a composable route. An Android/Compose navigation reproduction remains necessary.133134### F8 — P2: Browser backup restore always fails for both Merge and Replace135136Locations:137138- `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/database/PersistentDatabase.wasm.kt:32–43`139- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/InMemoryYokanDatabase.kt:48–50`140- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/BackupService.kt:492–496`141142The browser constructs `InMemoryYokanDatabase(atomicPersistence = false)`. Backup apply unconditionally calls `replaceAllAtomically`, which throws `ATOMIC_SNAPSHOT_PERSISTENCE_UNAVAILABLE` for that configuration. The comment intends to make local-entry management preview-only, but the same restriction blocks backup restore and cloud-backup restore. The shared settings screen still lets the user select, preview, and apply a backup.143144**Recommendation:** give the browser a persistence operation that commits the replacement before publishing success, and wire backup restore to it. Until supported, disable restore with an explicit capability explanation before file selection. Do not simply advertise atomic persistence while writes remain deferred.145146**Validation:** reproduced against the exact database configuration used by Wasm, using the shared backup implementation on the JVM. Both restore modes threw the stated error for a valid exported backup. This was a contract test, not a browser UI test.147148### F9 — P2: Browser persistence failures silently discard subsequent changes149150Location: `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/database/PersistentDatabase.wasm.kt:24–27`.151152`save` ignores the result of `runCatching { localStorage.setItem(...) }`. When storage rejects a write, the app continues updating memory without reporting that nothing was saved. Reloading restores the last successful snapshot and loses the intervening library, settings, and reading-progress changes. The existing comment acknowledges the limitation, but provides no user-visible recovery path.153154**Recommendation:** surface persistence failure, retain a dirty/unsaved state for retry, and provide a working export path. Moving to IndexedDB can address capacity separately; reporting failed saves is needed even with a different storage backend.155156**Validation:** static error-path inspection; browser quota exhaustion was not exercised. No exact cross-browser quota size is assumed.157158## Project files and architecture159160### S1 — Split feature ownership inside the existing module before adding modules161162The platform source-set layout is appropriate for a KMP app. The largest maintenance problem is concentrated responsibility inside shared UI files:163164| File under `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/` | Lines | Suggested boundary |165|---|---:|---|166| `ui/screens/settings/SettingsScreens.kt` | 7,204 | Separate appearance, downloads, tracking, sync, and backup/storage settings |167| `ui/screens/RouteScreens.kt` | 3,572 | Move screen implementations into their existing feature packages; retain route dispatch |168| `ui/screens/detail/DetailScreen.kt` | 3,090 | Separate state/async work from detail content and dialogs |169| `ui/AppState.kt` | 2,702 | Keep navigation in the app store; move library, download, migration, and settings work to feature owners |170171`YokanStore` mixes navigation, repository access, background work, settings, and feature progress. It owns Compose mutable state and an independent `Dispatchers.Default` scope (`AppState.kt:289–296`), while a few screens use ViewModels. `LibraryViewModel` still delegates to that store, and `LibraryScreen` receives the entire store (`LibraryRoute.kt:24–31`). This leaves state ownership and lifetime split across two systems; F7 shows a concrete lifetime consequence.172173Use the repository's ViewModel/StateFlow guidance when moving a feature, and pass explicit state/actions into its content composables. Keep the current Gradle module initially. Package/file separation and narrower dependencies will provide most of the benefit without a large build-system refactor.174175### S2 — Reuse the existing JVM shared source set for duplicated archive operations176177`androidMain` and `desktopMain` each contain `services/files/JvmLocalArchiveService.kt` and `JvmLocalFileService.kt`. They are not identical: Android has legitimate SAF/content-URI behavior and desktop has desktop shell integration. However, ZIP/TAR extraction, CBZ creation, and ordinary filesystem operations are substantially duplicated.178179For example, `extractZip` is at Android line 283 and desktop line 138; `extractTar` is at Android line 303 and desktop line 158. A parsing or archive-safety correction must currently be made twice.180181Move the shared file-backed operations into `jvmCommonMain`, following the existing `RarArchiveExtractor.kt` pattern. Keep SAF staging and platform launch/open behavior in the platform source sets. Prefer a few shared functions to a new abstraction hierarchy.182183### S3 — The documented developer guide is excluded from the repository184185`.gitignore:11` ignores `docs`, while `README.md:72–79` advertises a developer-guide website there and gives a command to serve it. `git ls-files docs` returns no files. A fresh clone cannot use those instructions even though a local `docs/` directory exists in this workspace.186187Either track the intended guide sources and ignore only generated output, or remove/change the README instructions to identify where the guide actually lives. Do not commit the entire local directory without checking its contents.188189### S4 — CI does not cover the project's platform-specific test structure190191`.forgejo/workflows/ci.yml:32–33` runs only `:composeApp:desktopTest`. That is useful coverage for shared logic and `nonWebTest`, but it does not execute `androidUnitTest`, `iosTest`, or `wasmJsTest`. `composeApp/build.gradle.kts:189–202` explicitly connects `nonWebTest` to desktop and iOS; Android unit tests do not inherit that source set. GitHub's checked-in workflows provide release/source-update automation, not a pull-request test workflow.192193Add platform compilation/test gates to the CI host actually used for development, prioritizing Android unit tests and a Wasm check, then iOS simulator tests on an available macOS runner. Wire compatible non-web tests into Android deliberately. Include lifecycle/navigation coverage and the failure scenarios above: many current tests exercise shared logic with `InMemoryYokanDatabase`, which cannot reveal Room's independent write queue or platform ViewModel ownership problems.194195## Validation and review limits196197- Reviewed the application/build layout, bootstrap, repository/database contracts, Room persistence, hub/cloud sync integration, library refresh, backup/restore, download recovery, reader state/lifetime, platform file adapters, and release/CI configuration. CodeGraph was used first to locate symbols and callers, followed by direct source inspection.198- Executed `rtk ./gradlew :composeApp:desktopTest --rerun --console=plain`: **423 tests across 92 suites, zero failures/errors/skips**. The explicit rerun executed the test task rather than accepting an up-to-date result.199- Executed three temporary diagnostic tests against the real implementations: F3's lost edits, F4's missing safety backup, and F8's rejected browser persistence contract. All three confirmed the described behavior. The probes asserted observed defects, not desired behavior. They were removed after the review so the deliverable remains this report; the reproduction details above describe the regression tests to add with fixes.200- Executed the Android signing report; release signing was unset. No signing credentials were changed.201- Rechecked the existing desktop suite after removing the probes; Gradle successfully restored the original compilation/test results from cache (423 tests). The earlier explicit rerun was the fresh execution. No application source or build configuration remains changed.202- The pre-existing untracked state inside `vendor/kmp-mpv` was preserved. Vendor implementation internals were not exhaustively reviewed.203- This is a targeted repository review, not an exhaustive line-by-line audit or a dedicated security scan. No Android device, iOS simulator, browser UI, live sync server, or release installation was exercised. Static findings are identified as such; passing desktop tests do not establish platform correctness.204205Recommended order: repair the Room lock/order boundary together (F1/F2), preserve local edits during refresh and restore (F3/F4), fix release signing (F5), then address reader/download/browser defects. Apply the structural improvements incrementally alongside those fixes.206