You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
refactor: improve maintainability across playback, native, downloads and quality gates - #795
Motivation. A full code review of master@b8855dfd3 produced an issue register of 47 items across architecture, playback, native, multi-ROM and performance (maintainability scored 5/10). This PR fixes the confirmed defects, restructures the entry points that were too large to read or change safely, and tightens the quality gates so that the same problems cannot quietly return. The change is kept as one PR at the maintainer's request.
Key changes
Playback (:playback:runtime, :playback:logic)
Cold start no longer opens SimpleCache on the initialization thread. Identity restore, directory preparation, index checks and the legacy import run in an IO warmup; paths that read cache contents call awaitPlaybackMediaCache(). Cache publication and detachment share one lock, so a release during warmup cannot leave a reference to a closed cache.
When the preference snapshot is missing, the cache limit is treated as unknown: the cache is read-only and never evicts until the real limit arrives. Previously the default 1 GiB limit could evict data for users with an unlimited cache.
Playback position and playing state are written only through PlaybackStatusOwner.publishPosition/publishPlaying(source, value); all 57 writers name their source. Values and timing are unchanged.
Lyric default offsets, fade preferences and the Listen Together playback gate moved out of PlayerManager into owner classes (atomic snapshots, a port for the gate). PlayerManager.kt went from 1998 to 1838 lines.
initializePlaybackEngine (505 lines) and observePlaybackSettings (415 lines) are now ordered tables of contents over lifecycle/engine/ and lifecycle/settings/.
Debug builds log off-main-thread PlayerManager calls (PlayerMainThreadContract); the playback request token advances under a lock.
Native (:native)
Crash forwarding calls the previous handler with the original siginfo/context; the crash-log claim is an atomic exchange.
frameBytes and the native stream generation are std::atomic with release/acquire.
DSP JNI handles are tokens in a registry, so a double release or a call after release no longer dereferences freed memory.
Symbols are hidden by default with a version script: each ABI exports exactly the 36 Java_* entry points; libusb_* exports dropped from about 100 to 0.
Five modules with no production caller are removed from lib_neri.so (sources and host tests kept). The reserve-transfer activation path is removed because the target count always equals the baseline by design; behavior is unchanged.
Multi-ROM and performance
Hidden API exemptions are installed in the main process only and narrowed from everything to four prefixes, derived from the reflection call sites and a scan of the release dex.
The XMSF network cut used for Super Island now holds a 60 s lease with an AlarmManager fallback that restores access even if the process is killed.
Xiaomi Super Island and ColorOS lock-screen lyric settings are hidden on devices without the capability (capability first, vendor second), including settings search.
The previous ANR is captured off the main thread after first interaction; blur reuses one RenderScript script and skips work at zero strength; Super Island artwork is scaled once off the main thread.
The @Composable keep rule is removed (release APK −4.9%, dex −7.5%); always-true SDK checks and the unused RenderScript build flags are removed.
Structure and gates
MainActivity.onCreate (~985 → 16 lines) and NeriAppContent (1529 → 179 lines) are split into named stages and NeriApp*.kt files; call order is unchanged.
Clear-downloads: 14 characterization tests were written and passed on the original code first, then the path was split into eight files (≤422 lines) and the 391-line function into named stages. The module README documents the stages and invariants.
The three platform playlist detail screens share a detail chrome and mutation helpers.
New gates: a function-length ratchet (120 lines, 200 for @Composable; baselined functions may only shrink) and a domain allowlist budget (new entries need a written reason). The CRAP scope and the allowlist are split per module, and line-budget tests scan directories instead of a hand-maintained list, which removes the most common merge conflicts.
34 copies of locateProjectFile are replaced by the :common test fixtures.
docs/architecture/module-graph.md is generated and checked for staleness; docs/architecture/README.md / README_EN.md is a one-page entry for maintainers and AI agents.
Risks and compatibility
No storage format, preference key, Room schema, Worker name or JNI symbol name changes.
Intended behavior changes: vendor lyric settings are hidden on unsupported devices; the crash dialog after an ANR may appear up to ~3 s later; XMSF access is restored after the lease expires.
The narrowed hidden API prefixes need checking on Flyme (status-bar lyrics flag), HyperOS with Shizuku (XMSF firewall) and an Android 9 device.
The USB exclusive changes passed the host gates but were not run against a real DAC.
Baseline Profiles reference a few renamed playback members and should be regenerated.
类型 / Type
Bug 修复 / Bug fix
新功能 / New feature
文档更新 / Documentation update
其他(请描述)/ Other (please describe): refactoring and new quality gates
修复或解决的问题 / Issues fixed or closed by this PR
None filed; the items come from an internal code review issue register.
清单 / Checklist
我已阅读并遵循贡献指南 / I have read and followed the contribution guidelines
我已在本地测试这些更改 / I have tested these changes locally
我已运行必要的构建、测试或静态检查 / I have run the required build, tests, or static checks
我已更新相关文档或注释(如适用)/ I have updated relevant documentation or comments (if applicable)
本次更改没有破坏原有行为 / This change does not break existing behavior
本次更改向下兼容(如适用)/ This change is backward compatible (if applicable)
改动只包含一个可独立审查的主题;超过 50 个文件或新增 1000 行时已拆分,或在下方说明无法拆分的原因 / The change covers one independently reviewable topic; above 50 files or 1,000 added lines it is split, or the reason it cannot be split is explained below
没有提交密钥、Token 或其他敏感信息 / No secrets, tokens, or other sensitive information are committed
UI 变更已附截图或录屏(如适用)/ UI changes include screenshots or recordings (if applicable)
AI 协助 / AI assistance
未使用 AI Agent 协助开发 / No AI agent was used for this change
使用了 AI Agent 协助开发 / An AI agent assisted with this change
使用的 AI 模型 / AI model(s) used:
Claude Opus 5.5 (claude-opus-5-5); GPT-6.2 Sol via Codex CLI for the native changes and an adversarial review of the playback changes
USB host gate: release-werror-asserts 37/37. asan-ubsan and tsan 35/37: usb_pcm_pipeline_test and usb_pcm_allocation_test time out locally on the unchanged base as well, and no PCM source changed here.
DSP host tests (Release and ASan/UBSan) pass, including the new crash-forwarding test. All four ABIs build in Debug and Release.
Emulator smoke test (API 37, release build signed with the debug key): 12-step onboarding including the Now Playing and lyrics previews, Home, YouTube Music playback, next track, Now Playing lyrics with translation, settings search. No crash, ANR or missing-class error; hidden API exemptions installed with no denial in logcat.
Not run:connectedDebugAndroidTest, real devices, a real USB DAC, Macrobenchmark. The androidTest sources compile.
Why one PR: the maintainer asked for a single PR. The work was produced as ten ordered topic patches (native, quality gates, playback ×2, downloads, review fixes, ROM/performance, follow-ups, app UI, UI follow-ups) and can be split along those lines later if needed.
Screenshots: release-build smoke screenshots are prepared locally and will be added in a comment, since they cannot be uploaded from the CLI.
Left for follow-up: the main-thread Room read in the lazy-initialization fallback (changing it alters command semantics), an explicit song source field (affects the sync identity format), an SPSC ring for the USB realtime path, TSan coverage of the USB session core, and about 17 files still between 1,900 and 1,999 lines.
…and quality gates
Address the code review issue register in a single change.
Playback:
- open the media cache off the initialization thread and await it where
cache contents are read; publish and detach the cache under one lock
- treat an unknown cache limit as read-only so default preferences never
evict an unlimited cache
- route playback position and playing-state writes through
PlaybackStatusOwner with an explicit writer source
- move lyric default offsets, fade preferences and the Listen Together
gate out of PlayerManager into owner classes
- split initializePlaybackEngine and observePlaybackSettings by stage and
topic; file misplaced extension functions by responsibility
- log off-main-thread PlayerManager calls in debug builds and advance the
playback request token under a lock
Native:
- forward crash signals to the previous handler with the original siginfo
and claim the crash log with an atomic exchange
- make frameBytes and the stream generation atomic
- replace raw DSP engine pointers with a token table
- export only Java_* symbols and drop never-called modules from lib_neri.so
- remove the unreachable reserve-transfer path and narrow feedback math to
128-bit
ROM and performance:
- install narrowed hidden API exemptions in the main process only
- restore XMSF network access through a 60 s lease with an alarm fallback
- hide Xiaomi Super Island and ColorOS lock-screen lyric settings on
devices without the capability
- capture the previous ANR off the main thread, reuse the blur script and
scale Super Island artwork off the main thread
- remove the @composable keep rule and dead SDK checks
Structure and quality gates:
- split MainActivity.onCreate, NeriAppContent and the clear-downloads path
into named stages, with characterization tests for clear-downloads
- share a detail chrome across the three platform playlist screens
- add a function-length ratchet and a domain allowlist budget, split the
CRAP scope and allowlist per module, and scan line budgets by directory
- deduplicate locateProjectFile into the :common test fixtures
- generate docs/architecture/module-graph.md and add an architecture
quick reference for maintainers and agents
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
本次变更新增并接入 PR 尺寸提示、函数长度、域依赖预算和模块图检查。应用启动、主界面、播放状态与歌单详情实现拆分为多个辅助组件。下载清理与全库删除恢复流程分阶段处理。缓存初始化改为延迟解析并支持异步预热。新增 ROM 歌词能力检测和 XMSF 网络租约。原生代码调整崩溃信号处理、DSP 句柄管理和 USB 传输实现,并补充相应测试。
Merge Risk: Low · up to 9c9cf · assessed changes only
Path filters excluded changed files. This rating applies only to the assessed changes.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
标题“refactor: improve maintainability across playback, native, downloads and quality gates”概括了本 PR 的主要内容:播放、原生层、下载及质量门禁的重构。标题涵盖多个领域,范围较宽,但与变更集一致,未描述不存在的内容,也不是空泛描述。
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
val latestOnLauncherShortcutRequestConsumed by rememberUpdatedState(onRequestConsumed)
+ val latestNavigateToMainTab by rememberUpdatedState(navigateToMainTab)
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Major · Stability & Availability · Heavy lift
Persisted full-library delete fence can stay after its intent is cleared.
If the fence clear fails after the intent is cleared, or the process exits between the two writes, the FULL fence remains with no pending intent. Download workers treat the active fence as a block. On later starts, the recovery routes reach the FULL recovery loop, which returns without releasing the fence. The fence can therefore block downloads across restarts.
The archived-intent failure is different: a later start clears its fence through the check at GlobalDownloadManagerFacadeBootstrap.kt:395-405. The cleared-intent case has no equivalent check.
Define a release rule for a persisted FULL fence that has no pending intent. The rule must bind release to the fence epoch. It must confirm the catalog state before releasing. Add it to the startup recovery path, so that a later start can release the fence.
The reason will be displayed to describe this comment to others. Learn more.
Checked this against the code. The "blocked across restarts" part does not hold:
A full delete persists the intent before the fence (GlobalDownloadManagerCatalogDelete.kt:166-194 → GlobalDownloadManagerCancellation.kt:705-723), and the intent is cleared only after the confirmed-empty catalog is persisted. A FULL fence without an intent therefore means the delete already finished; it is never a delete still in progress.
On the next start the bootstrap sees an active fence with no pending intent and takes the else branch (GlobalDownloadManagerFacadeBootstrap.kt:442-455): requestAllDownloadTaskCancellation(purpose = FULL_LIBRARY_DELETE, forceConvergence = true). That releases the fence through the epoch-bound clearIfCurrent and wakes the execution pump. A probe test that simulated a restart confirmed the fence is released and downloads unblock.
What remains is narrower. Within the same process, the fence stays until the next start, because the deferred FULL recovery loop returns when the intent is null. This logic is unchanged from master; it moved verbatim from GlobalDownloadManagerClear.kt. I'm keeping it out of this PR and tracking it as a follow-up.
- xmsf: retry a failed lease restore with backoff (1 min doubling up to
30 min) until networking is restored, also when the receiver times out
- crash: take the marker lock for reads and deletes so a concurrent check
cannot delete a marker that is still being written
- blur: release the input allocation when creating the output fails
- listen together: a resume started before a newer safety pause neither
applies its room state nor clears the newer pause; show localized room
notices as is instead of parsing them again; finishing a join clears
only the invite it handled
- shortcuts: navigate with the latest main-tab callback after waiting for
favorites
- quality: read and write baselines and registries as UTF-8, and keep
counting an expression body past an `if (...)` line
Addressed the grouped CodeRabbit comments in 9c9cf37. Items marked (pre-existing) behave the same on master; they are fixed here because each change is small.
function_length.py encoding: baseline, config and registry reads and writes pass encoding="utf-8". The same applies to module_graph.py, module_scope.py and domain_dependency_budget.py.
function_length.py, if (flag) on its own line: an expression body keeps counting when a line ends with the closing paren of an if condition. Regression test added.
MainActivity, room notice parsed twice(pre-existing): the localized notice is shown directly.
MainActivity, invite cleared unconditionally(pre-existing): finishing a join clears only the invite it handled; an invite opened in the meantime stays. Test added.
NeriAppNavigationHost, shortcut fallback(pre-existing): the effect reads navigateToMainTab through rememberUpdatedState.
CrashReportStore: marker reads, validity checks and deletes take the same lock as writes. The regression test holds the lock over an empty marker and checks that a concurrent check waits.
CustomBackground: the input allocation is released if creating the output allocation fails.
ListenTogetherPlaybackGate, stale completion(pre-existing): a completion settles only a resume that is still in flight, since a newer safety pause resets the in-flight flag. The resume owner also skips applying a response once a newer safety pause has superseded it. Tests are in ListenTogetherPlaybackGateTest and ListenTogetherSafetyPauseResumeOwnerTest.
Local checks: testDebugUnitTest, verifyCrap and lintDebug passed for :app, :playback:runtime and :listentogether (4,574, 2,773 and 477 tests, 0 failures). The function-length, module-boundary and module-graph checks and the quality script tests (198) also pass.
The reason will be displayed to describe this comment to others. Learn more.
Retry retained-cache migration when the cache limit becomes known
When playback initializes without a cached preference snapshot and cache warmup finishes before the settings flow emits, the owner opens read-only and migrateRetainedPlaybackCaches() returns because canWriteCache is false. Once the actual limit arrives, this method enables writes but only updates the existing evictor; it neither invokes the migration callback again nor schedules the skipped import. Consequently, audio in retained legacy or recovery stores remains unavailable for offline playback for the rest of that process, even when the user's cache setting permits importing it. Schedule the deferred migration when transitioning from an unknown limit to a writable cache.
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
描述 / Description
Motivation. A full code review of
master@b8855dfd3produced an issue register of 47 items across architecture, playback, native, multi-ROM and performance (maintainability scored 5/10). This PR fixes the confirmed defects, restructures the entry points that were too large to read or change safely, and tightens the quality gates so that the same problems cannot quietly return. The change is kept as one PR at the maintainer's request.Key changes
Playback (
:playback:runtime,:playback:logic)SimpleCacheon the initialization thread. Identity restore, directory preparation, index checks and the legacy import run in an IO warmup; paths that read cache contents callawaitPlaybackMediaCache(). Cache publication and detachment share one lock, so a release during warmup cannot leave a reference to a closed cache.PlaybackStatusOwner.publishPosition/publishPlaying(source, value); all 57 writers name their source. Values and timing are unchanged.PlayerManagerinto owner classes (atomic snapshots, a port for the gate).PlayerManager.ktwent from 1998 to 1838 lines.initializePlaybackEngine(505 lines) andobservePlaybackSettings(415 lines) are now ordered tables of contents overlifecycle/engine/andlifecycle/settings/.PlayerManagercalls (PlayerMainThreadContract); the playback request token advances under a lock.Native (
:native)siginfo/context; the crash-log claim is an atomic exchange.frameBytesand the native stream generation arestd::atomicwith release/acquire.Java_*entry points;libusb_*exports dropped from about 100 to 0.lib_neri.so(sources and host tests kept). The reserve-transfer activation path is removed because the target count always equals the baseline by design; behavior is unchanged.Multi-ROM and performance
AlarmManagerfallback that restores access even if the process is killed.@Composablekeep rule is removed (release APK −4.9%, dex −7.5%); always-true SDK checks and the unused RenderScript build flags are removed.Structure and gates
MainActivity.onCreate(~985 → 16 lines) andNeriAppContent(1529 → 179 lines) are split into named stages andNeriApp*.ktfiles; call order is unchanged.@Composable; baselined functions may only shrink) and a domain allowlist budget (new entries need a written reason). The CRAP scope and the allowlist are split per module, and line-budget tests scan directories instead of a hand-maintained list, which removes the most common merge conflicts.locateProjectFileare replaced by the:commontest fixtures.docs/architecture/module-graph.mdis generated and checked for staleness;docs/architecture/README.md/README_EN.mdis a one-page entry for maintainers and AI agents.Risks and compatibility
类型 / Type
修复或解决的问题 / Issues fixed or closed by this PR
None filed; the items come from an internal code review issue register.
清单 / Checklist
AI 协助 / AI assistance
使用的 AI 模型 / AI model(s) used:
Claude Opus 5.5 (claude-opus-5-5); GPT-6.2 Sol via Codex CLI for the native changes and an adversarial review of the playback changes
其他信息 / Additional information
How it was tested (all on the integrated tree)
./gradlew verifyModularization verifyFunctionLength verifyDomainDependencyBudget :native:externalNativeBuildDebug: passed. 17,602 JVM tests, 0 failures, 7 skipped; combined CRAP 16,269 scoped methods, 0 above 9; domain dependencies 0 violations; lint for app and all 15 owned libraries.release-werror-asserts37/37.asan-ubsanandtsan35/37:usb_pcm_pipeline_testandusb_pcm_allocation_testtime out locally on the unchanged base as well, and no PCM source changed here.:app:assembleRelease -PallowUnsignedRelease=true: R8 passes, 15,546,562 bytes.Not run:
connectedDebugAndroidTest, real devices, a real USB DAC, Macrobenchmark. The androidTest sources compile.Why one PR: the maintainer asked for a single PR. The work was produced as ten ordered topic patches (native, quality gates, playback ×2, downloads, review fixes, ROM/performance, follow-ups, app UI, UI follow-ups) and can be split along those lines later if needed.
Screenshots: release-build smoke screenshots are prepared locally and will be added in a comment, since they cannot be uploaded from the CLI.
Left for follow-up: the main-thread Room read in the lazy-initialization fallback (changing it alters command semantics), an explicit song source field (affects the sync identity format), an SPSC ring for the USB realtime path, TSan coverage of the USB session core, and about 17 files still between 1,900 and 1,999 lines.
PlaybackStatusOwner,由PlaybackStatusWriter标记来源。RomLyricSurfaceSupport设备能力隐藏。connectedDebugAndroidTest、真机、USB DAC 及 Macrobenchmark。