# Yokan performance and memory review

Reviewed app reader, archive, logging, media controller, software rendering, local media proxy,
and desktop Discord RPC resource ownership. This review applies to the app changes;
the vendored kmp-mpv changes are separate.

## Applied fixes

| Path | Finding | Change |
| --- | --- | --- |
| File logging | Every line read and rewrote the complete log, allocating buffers proportional to log history. | Append only the new line; serialize append and clear operations. Existing history is preserved. |
| Reader progress | Concurrent downloads could overwrite each other's progress. Unchanged percentages still copied the map, and indicators subscribed to every page. | Atomic updates, early unchanged-percent check, distinct per-URL flows, and lifecycle-aware collection. |
| Android/desktop archives | Page and EPUB metadata maps retained every opened archive. TAR extraction allocated the entire payload even for ignored entries, with an unsafe Long-to-Int conversion. | Weighted LRU caches (32 archives, 10,000 page records / 2,000 EPUB chapters) and streaming TAR extraction with at most a 64 KiB payload buffer. Oversized metadata is returned without being retained. Partial output is removed on copy failure. |
| mpv controller | A missing load-completion event could retain queued commands indefinitely; scrubbing queued obsolete seeks. Cleanup ran in an unrelated scope. | A 30-second preparation timeout, cancellation of obsolete seeks, and controller-owned cancellation-safe release. Collectors are cancelled on release and coroutine cancellation propagates through command handling. Repeated identical player errors are logged only once until the error changes. |
| Desktop/iOS software rendering | Rendering kept copying frames at the active rate while paused. ImageInfo was allocated every frame. | Reduce paused polling to four times per second, reuse ImageInfo for the output size, and close UI-owned Skia pixels when resized or disposed. Bitmap state is isolated per controller and output size so old cleanup cannot close a new surface's frame. |
| JVM media proxy | Each client spawned an unrestricted thread; stop did not close active/queued sockets. Playlist refreshes created duplicate registrations. | At most 16 workers and 32 queued clients, idle worker expiry, tracked socket closure, executor shutdown, and URL/header registration reuse. Expiry scans run at most once per minute during registration. |
| Desktop Discord RPC | A socket opened before a failed connect was not owned by shutdown and could leak its descriptor. | Assign ownership before connecting so failure cleanup closes the socket. |

## Regression verification

29 targeted desktop tests passed with no failures or errors:

- Cache recency, weight limits, and oversized replacement.
- Concurrent reader progress, unchanged percentages, and per-page flow isolation.
- Player preparation ordering, timeout, seek coalescing, immediate/repeated release, and removal of state/event collectors during a pending load.
- Log append without reading or rewriting existing data.
- Proxy registration reuse, authentication-header isolation, idle socket closure, and terminal shutdown.
- TAR extraction past an ignored sparse 3 GiB entry, truncated image payload rejection, plus existing RAR and reader stream regressions.

Compilation checks passed for desktop, Android debug, iOS simulator arm64, and WebAssembly.
Android compilation uses `ANDROID_HOME=/Users/duongph/Library/Android/sdk` in this workspace;
set it to the installed SDK on other machines. Existing deprecation warnings remain.

Reproduce with:

```sh
rtk ./gradlew :composeApp:desktopTest \
  --tests '*BoundedCacheTest' \
  --tests '*ReaderPageDownloadProgressTest' \
  --tests '*MediaPlayerInitializationTest' \
  --tests '*LogSinkAppendTest' \
  --tests '*JvmMediaStreamProxyTest' \
  --tests '*TarMemoryTest' \
  --tests '*RarArchiveExtractorTest' \
  --tests '*ReaderViewModelStreamTest'
```

## Profiling limits and follow-up

These are source-backed fixes and behavioral regression checks, not measured startup/FPS
improvements or proof that the app has no memory leaks. Physical-device heap/native allocation
profiling and long playback sessions were not run. In particular:

- Active desktop/iOS software playback still copies frames; a GPU rendering path requires separate work.
- Background rendering remains serviced while playback continues. Simply suspending render calls can disrupt mpv; reducing this work requires explicit frame-skipping support through the library's render API. See the [mpv render API contract](https://github.com/mpv-player/mpv/blob/master/include/mpv/render.h).
- Archive cache weights count metadata records, not exact retained bytes. Extracted files on disk are not evicted by the metadata LRU.
- Proxy registrations retain the existing 30-minute inactivity policy and expire on subsequent registrations. There is no strict cap on distinct segments, to avoid invalidating long VOD playlists.
- The proxy is an app-lifetime service. After stop, create a new instance to serve media again. Overload closes connections beyond the worker/queue limits.
- A slow load can time out before its eventual native completion; resume seeking is only applied when preparation completes inside the timeout.

For runtime verification, repeatedly enter/leave the reader and player, switch archives and
episodes, scrub, pause/resume, resize, and background/foreground the app. Compare retained
heap, native pixels, coroutine collectors, threads, and open descriptors after idle/GC across
repeated cycles using Android Studio Memory Profiler and Xcode Instruments. Check visible
playback and paused subtitle/OSD updates on desktop and iOS, as those rendering paths changed.
