This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: compose-predictive-back-lifecycle-fence

Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence

Enforces atomic state restoration and strict Lifecycle fences during predictive back gesture interactions on Android 15+ (API 35). Prevents zombie ViewModels, desynchronized NavBackStackEntry states, and memory leaks caused by canceled or aborted multi-window predictive back gestures.

Prohibited Anti-Pattern: Speculative State Mutating & Unfenced Coroutines During Aborted Predictive Back Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence - Enforces atomic state restoration and strict Lifecycle fences during predictive back gesture interactions on Android 15+ (API 35). Prevents zombie ViewModels, desynchronized NavBackStackEntry states, and memory leaks caused by canceled or aborted multi-window predictive back gestures.
globs: app/src/**/*.kt, feature/**/src/**/*.kt, core/**/src/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-predictive-back-lifecycle-fence"
---

# Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Speculative State Mutating & Unfenced Coroutines During Aborted Predictive Back Transitions

## System Constraints
You are a Principal Mobile Architect enforcing strict predictive back stack determinism and Lifecycle boundary fencing in Jetpack Compose for Android 15+. You must mandate that predictive back handlers isolate speculative gesture progress from architectural state, guarantee immediate cancellation cleanup upon gesture aborts, and prevent premature ViewModel disposal or zombie coroutines.

## Strict Guidelines
- Engineers MUST ALWAYS isolate predictive back gesture progress (BackEventCompat progress float) to UI visual transformation layers and NEVER mutate business logic, repository state, or ViewModel-persisted data during the gesture sequence.
- Engineers MUST utilize Compose Navigation 2.8+ built-in predictive back support or enforce atomic cancellation via PredictiveBackHandler { progressFlow -> try { progressFlow.collect { ... } } finally { /* deterministic abort reset */ } }.
- Engineers MUST NOT instantiate or trigger navigation side-effects (e.g., NavController.popBackStack() or navigate()) within the progress emission loop before the gesture completes successfully.
- Custom predictive gestures MUST strictly handle CancellationException to rollback transient animations to their exact pre-gesture state when an abort occurs in multi-window or gesture-cancel scenarios.
- ViewModels MUST NEVER bind long-running coroutines to NavBackStackEntry Lifecycle states that assume immediate destruction when a predictive back starts; speculative transitions must preserve ViewModelStoreOwner integrity until gesture commit.

## Bad vs Good Implementations
### Predictive Back Handling: Abort-Safe Progress Isolation vs State Mutation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mutating ViewModel state and calling popBackStack() during the progress collection violates back stack determinism. If the user aborts the gesture, the screen remains visible but the business logic has already discarded state, causing state corruption and zombie NavBackStackEntry instances.
```kotlin
@Composable
fun FlawedDetailScreen(navController: NavController, viewModel: DetailViewModel) {
    var isCancelling by remember { mutableStateOf(false) }
    
    // ANTI-PATTERN: Committing state mutations inside predictive back progress,
    // and mutating ViewModel state before the gesture finishes.
    PredictiveBackHandler(enabled = true) { progress: Flow<BackEventCompat> ->
        progress.collect { backEvent ->
            // Mutating business logic during speculative phase
            viewModel.markDraftDiscarded()
            // Direct UI state mutation tied to navigation stack prematurely
            if (backEvent.progress > 0.5f) {
                navController.popBackStack() // Violates predictive back contract; causes illegal state
            }
        }
        // Fails to handle cancellation / abort: if gesture aborts, draft is lost
        // and ViewModel is left in an inconsistent/orphaned state.
    }
}
```

#### Production Standard (Correct)
> **Standard**: Decouples transient gesture progress from persistent state. The try/catch/finally block guarantees that gesture aborts roll back UI visual state cleanly, rethrows CancellationException for Compose runtime determinism, and defers navigation/ViewModel mutation until the gesture commits.
```kotlin
@Composable
fun DeterministicDetailScreen(
    onBackCommitted: () -> Unit,
    modifier: Modifier = Modifier
) {
    // GOOD: Visual state isolated strictly to the local UI layer
    var gestureProgress by remember { mutableFloatStateOf(0f) }

    PredictiveBackHandler(enabled = true) { progressFlow: Flow<BackEventCompat> ->
        try {
            progressFlow.collect { backEvent ->
                // Drive visual interpolation ONLY; no business state mutations
                gestureProgress = backEvent.progress
            }
            // Gesture committed: execute single atomic back navigation callback
            onBackCommitted()
        } catch (e: CancellationException) {
            // Gesture aborted: atomically rollback visual transformations
            gestureProgress = 0f
            throw e // Re-throw to allow Compose runtime fence to maintain correct Lifecycle state
        }
    }

    Box(
        modifier = modifier.graphicsLayer {
            scaleX = 1f - (gestureProgress * 0.1f)
            scaleY = 1f - (gestureProgress * 0.1f)
            alpha = 1f - (gestureProgress * 0.2f)
        }
    ) {
        // Content remains bound to its stable, unmutated ViewModel
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence

Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence defines an industrial-grade behavioral standard for mobile engineering. Enforces atomic state restoration and strict Lifecycle fences during predictive back gesture interactions on Android 15+ (API 35). Prevents zombie ViewModels, desynchronized NavBackStackEntry states, and memory leaks caused by canceled or aborted multi-window predictive back gestures. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Speculative State Mutating & Unfenced Coroutines During Aborted Predictive Back Transitions Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftSpeculative State Mutating & Unfenced Coroutines During Aborted Predictive Back TransitionsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate predictive back gesture progress (BackEventCompat progress float) to UI visual transformation layers and NEVER mutate business logic, repository state, or ViewModel-persisted data during the gesture sequence.

Engineers MUST ALWAYS isolate predictive back gesture progress (BackEventCompat progress float) to UI visual transformation layers and NEVER mutate business logic, repository state, or ViewModel-persisted data during the gesture sequence.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST utilize Compose Navigation 2.8+ built-in predictive back support or enforce atomic cancellation via PredictiveBackHandler { progressFlow -> try { progressFlow.collect { ... } } finally { /* deterministic abort reset */ } }.

Engineers MUST utilize Compose Navigation 2.8+ built-in predictive back support or enforce atomic cancellation via PredictiveBackHandler { progressFlow -> try { progressFlow.collect { ... } } finally { /* deterministic abort reset */ } }.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT instantiate or trigger navigation side-effects (e.g., NavController.popBackStack() or navigate()) within the progress emission loop before the gesture completes successfully.

Engineers MUST NOT instantiate or trigger navigation side-effects (e.g., NavController.popBackStack() or navigate()) within the progress emission loop before the gesture completes successfully.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Custom predictive gestures MUST strictly handle CancellationException to rollback transient animations to their exact pre-gesture state when an abort occurs in multi-window or gesture-cancel scenarios.

Custom predictive gestures MUST strictly handle CancellationException to rollback transient animations to their exact pre-gesture state when an abort occurs in multi-window or gesture-cancel scenarios.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

ViewModels MUST NEVER bind long-running coroutines to NavBackStackEntry Lifecycle states that assume immediate destruction when a predictive back starts

ViewModels MUST NEVER bind long-running coroutines to NavBackStackEntry Lifecycle states that assume immediate destruction when a predictive back starts; speculative transitions must preserve ViewModelStoreOwner integrity until gesture commit.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Jetpack Compose Predictive Back Stack Determinism & Lifecycle Fence critical for AI coding assistants?

Enforces atomic state restoration and strict Lifecycle fences during predictive back gesture interactions on Android 15+ (API 35). Prevents zombie ViewModels, desynchronized NavBackStackEntry states, and memory leaks caused by canceled or aborted multi-window predictive back gestures. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Speculative State Mutating & Unfenced Coroutines During Aborted Predictive Back Transitions) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Jetpack