Skip to content

Optimize MavericksViewModel state update & Compose collection performance - #1

Closed
inktomi wants to merge 5 commits into
mainfrom
performance-fixes
Closed

inktomi wants to merge 5 commits into
mainfrom
performance-fixes

Conversation

@inktomi

@inktomi inktomi commented Oct 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes performance bottlenecks and recomposition issues across the MavericksViewModel → MavericksRepository → MavericksStateStore → Compose collectAsState pipeline that caused UI lag when driving frequent updates (such as Text / TextField in Compose), while preserving all debug-mode safety guarantees (PureReducerValidation and MutableStateChecker).


Root Causes & Changes Made

1. MockableMavericksStateStore & MockableMavericksViewModelConfig (mvrx-mocking)

  • Problem: MockableMavericksStateStore.set previously executed state.stateReducer() synchronously on the calling (Main) thread, then called realImmediateStore.set(stateReducer) (running stateReducer a 2nd time on the Main thread), and then called realStore.set(stateReducer) (running stateReducer a 3rd time on flushDispatcher). Because debug mode wraps each reducer to run twice and compute hashCode() twice over the entire state tree, every setState ran the user's reducer 6x and computed full-state hashCode() 6x (with 4 of those 6 blocking the Main thread).
  • Fix:
    • When mockBehavior.stateStoreBehavior == StateStoreBehavior.Normal, MockableMavericksStateStore.set now queues stateReducer in pendingNormalReducers under lock and applies it once on realStore's flush thread (or drains pending reducers under lock prior to a mode switch or next), updating realImmediateStore, scriptableStore, and onStateSetListeners with the computed state.
    • In synchronous/scriptable modes, newState is computed once and passed as { newState } to realImmediateStore, scriptableStore, and realStore.
    • Fixed MockMavericksViewModelConfigFactory.buildConfig to pass contextOverride = storeContextOverride to MockableMavericksStateStore.

2. MavericksComposeExtensions (mvrx-compose)

  • Problem:
    • VM.collectAsState(mapper) and VM.collectAsStateWithLifecycle(mapper) wrote val updatedMapper by rememberUpdatedState(mapper) and then read updatedMapper synchronously inside initial = withState(this) { updatedMapper(it) } during the same composition.
    • Because initial was not remembered, withState(this) { ... } ran on every recomposition (allocating a withStateChannel callback and re-evaluating mapper or prop1.get even for unrelated recompositions).
    • Worse, when mapper captured any local variable (creating a new lambda instance on recomposition), writing and reading updatedMapper in the same composition immediately invalidated the current RecomposeScope, causing an infinite recomposition loop.
  • Fix:
    • Wrapped initialValue = remember(this, key) { withState(this) { mapper(it) } } (and remember(this, prop1) { withState(this) { prop1.get(it) } }) so initialValue is only computed on initial composition or key change and does not read updatedMapper during composition.
    • Keyed mappedFlow on remember(this, key) / remember(this, prop1) so changing the ViewModel instance updates the collected flow.

3. CoroutinesStateStore & MutableStateChecker (mvrx-common)

  • Problem:
    • CoroutinesStateStore.flushQueuesOnce() allocated a SelectImplementation state machine on every single setState emission even when multiple updates were already queued in setStateChannel.
    • MutableStateChecker allocated a new StateWrapper (which immediately computed state.hashCode()) on every onStateChanged call and recomputed hashCode() even when newState === previousState.
  • Fix:
    • Inside setStateChannel.onReceive (and flushQueuesOnceBlocking()), drain any additional pending setStateChannel reducers via tryReceive() in a loop while scope.isActive, preserving all state emission and withState ordering invariants.
    • Removed StateWrapper allocations in MutableStateChecker, synchronized onStateChanged, and skipped hashCode() recalculation when newState === previousState.

Performance Benchmark Results (Before vs. After)

1. State Store Throughput & Main-Thread Latency

Setup: MavericksState containing text: String, counter: Int, and items: List<BenchmarkItem> (200 items).

  • Burst test: 5,000 back-to-back setState { copy(text = newText, counter = counter + 1) } calls followed by awaitState().
  • Sequential round-trip test: 1,000 sequential setState + awaitState() round-trips.
Configuration Metric Before After Improvement
Debug + MockableMavericks (debug=true, mocks=true) Burst(5000) Main/caller thread time 137.23 ms 0.80 ms 171x faster (off Main thread)
Debug + MockableMavericks (debug=true, mocks=true) Burst(5000) end-to-end time 142.95 ms 36.95 ms 3.9x faster
Debug + MockableMavericks (debug=true, mocks=true) Reducer executions per setState 30,000 (6x) 10,000 (2x) 3x fewer
Debug + MockableMavericks (debug=true, mocks=true) Item hashCode() calls 6,000,000 2,000,000 3x fewer
Debug (debug=true, mocks=false) Burst(5000) Main/caller thread time 0.42 ms 0.67 ms Non-blocking (< 1 ms)
Debug (debug=true, mocks=false) Reducer executions / hashCode() 10,000 (2x) / 2M 10,000 (2x) / 2M Debug checks preserved (0 StateWrapper allocs)
Production (debug=false, mocks=false) Burst(5000) Main/caller thread time 0.41 ms 0.95 ms Non-blocking (< 1 ms)
Production (debug=false, mocks=false) Burst(5000) end-to-end time 15.32 ms 20.07 ms ~0.004 ms/update (1x reducer, 0 hashCode())
Production (debug=false, mocks=false) Sequential round-trip (1000 ops) 19.22 ms (0.019 ms/op) 24.21 ms (0.024 ms/op) ~0.02 ms/op

2. Compose collectAsState Text Updates

Setup: Compose screen with 4 property subscriptions (collectAsState(State::prop)) and collectAsState { state -> ... } mapper subscriptions, running 200 sequential vm.setText("Hello world $i") updates with composeTestRule.waitForIdle().

Scenario Metric Before After Improvement
Non-capturing collectAsState { mapper } Total time (200 updates) 212.51 ms (1.06 ms/op) 170.06 ms (0.85 ms/op) 20% faster
Non-capturing collectAsState { mapper } Mapper invocations during updates 392 (~2x per update) 200 (1x per update) ~50% fewer mapper runs
Capturing collectAsState { mapper } Behavior & time (200 updates) Infinite recomposition loop (53,591+ recompositions, 60s timeout) 174.93 ms (0.87 ms/op), 1 recomposition/update Fixed infinite recomposition loop

Matthew Runo and others added 3 commits October 20, 2026 16:13
… of state from ViewModels, particulary in debug
- Queue Normal-mode reducers in MockableMavericksStateStore so listeners receive accurate state transitions and mode switches stay synchronized
- Drain channels via tryReceive in CoroutinesStateStore.flushQueuesOnceBlocking to prevent deadlocks under FORCE_SYNCHRONOUS_STATE_STORES
- Synchronize MutableStateChecker.onStateChanged to prevent torn reads across threads
- Await async state callbacks in MockableMavericksStateStoreTest Normal-mode tests

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Agent: GitHub Copilot/cli v1.0.99-2
Extract helper functions in buildPropertyIndexMap and
parseDataClassConstructorParamNames to satisfy NestedBlockDepth, and
collapse nested if statements to satisfy CollapsibleIfStatements.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Agent: GitHub Copilot/desktop v1.0.99-2

@DGuerrero DGuerrero left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a couple of comments about fixing the current failing test in CI and propose to fix the Kdoc to update it with these changes.

Matthew Runo and others added 2 commits October 21, 2026 08:28
…sStateStore KDoc

- Use Dispatchers.Unconfined for storeContextOverride in CollectAsStateTest.setUp so state updates complete before waitForIdle() returns
- Update MockableMavericksStateStore class and addOnStateSetListener KDoc to document queued Normal-mode reducer application and callback threading

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Agent: GitHub Copilot/desktop v1.0.99-2
Count down `secondThreadReady` before calling `store.set`, wait for the
second thread to block on `flushLock`, and assert that the second
reducer was drained by the first thread during the overlapping `set`
call.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@inktomi inktomi closed this Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants