This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-native-coroutines-leak-immunity-standard

KMP Native Coroutines Memory-Leak Immunity Standard

Enforces strict lifecycle boundaries and deterministic cancellation contracts between Kotlin Multiplatform Coroutines and Swift/Objective-C runtime memory management. Eliminates uncollected ARC reference cycles and detached Job retention across Apple native foreign-function interfaces by mandating explicit disposable tokens and scope deallocation hooks.

Prohibited Anti-Pattern: Retaining Long-Lived Kotlin Job Continuations via Escaping Swift Closures and Strong Scope Capture

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Coroutines Memory-Leak Immunity Standard - Enforces strict lifecycle boundaries and deterministic cancellation contracts between Kotlin Multiplatform Coroutines and Swift/Objective-C runtime memory management. Eliminates uncollected ARC reference cycles and detached Job retention across Apple native foreign-function interfaces by mandating explicit disposable tokens and scope deallocation hooks.
globs: shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-coroutines-leak-immunity-standard"
---

# KMP Native Coroutines Memory-Leak Immunity Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Long-Lived Kotlin Job Continuations via Escaping Swift Closures and Strong Scope Capture

## System Constraints
You are a Principal Mobile Architect enforcing the Kotlin Multiplatform Native Coroutines Memory-Leak Immunity Standard. You must strictly prevent cross-runtime memory leaks where Swift ARC and Kotlin Native garbage collection form uncollected cyclic references. Intercept any exposed Kotlin Flow, Suspend function, or CoroutineScope bridging into Swift that fails to implement deterministic teardown hooks, auto-cancellation tokens, or weak-reference capture.

## Strict Guidelines
- Engineers MUST ALWAYS expose a deterministic cancellation handle (e.g., CancellationToken, Closeable, or JobDisposable) for any Kotlin Coroutine or Flow bridge consumed by Swift.
- Engineers MUST NOT capture strong self references inside Swift completion handlers or async iterators bridging Kotlin Coroutine continuations.
- Code MUST bind Kotlin CoroutineScope lifecycles directly to host platform components (such as SwiftUI .task / onDisappear or UIViewController deinit) ensuring job.cancel() execution on teardown.
- Services MUST leverage KMP-NativeCoroutines (@NativeCoroutines, @NativeCoroutineScope) or custom Disposable wrappers to guarantee unregistration of continuous streams when the native UI detaches.
- Components NEVER bridge raw GlobalScope or Unconfined CoroutineContexts to native iOS callers without an explicit parent Job.

## Bad vs Good Implementations
### SwiftUI Consumption of Shared KMP Flow without Deterministic Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native holds an internal continuation callback referencing the Swift closure, which strongly captures 'self'. Without explicit cancellation on deinit or view dismissal, both the Kotlin Job and the Swift ViewModel become immortal across ARC and Kotlin GC roots.
```swift
import SwiftUI
import SharedKit

final class ProfileViewModel: ObservableObject {
    @Published var state: ProfileState = .loading
    private let repository = ProfileRepository()

    func observeUpdates() {
        // CRITICAL BUG: Kotlin Coroutine collector closure captures strong self
        // and never cancels the underlying KMP Job on view deallocation.
        repository.watchProfileStream().watch { [self] profile in
            self.state = .success(profile)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Breaks the ARC retain cycle by using [weak self] and binds the cancellation token directly to the Swift lifecycle via explicit disposal in deinit and stopObserving, freeing both Swift and Kotlin Native resources.
```swift
import SwiftUI
import SharedKit

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published var state: ProfileState = .loading
    private let repository: ProfileRepository
    private var profileTaskHandle: DisposableHandle?

    init(repository: ProfileRepository = ProfileRepository()) {
        self.repository = repository
    }

    func startObserving() {
        profileTaskHandle?.dispose()
        // Capture weak self and store disposable cancellation handle
        profileTaskHandle = repository.watchProfileStream().watch { [weak self] profile in
            guard let self = self else { return }
            self.state = .success(profile)
        }
    }

    func stopObserving() {
        profileTaskHandle?.dispose()
        profileTaskHandle = nil
    }

    deinit {
        profileTaskHandle?.dispose()
    }
}
```

### Kotlin Side Cross-Platform Scope Management for Native Export

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: GlobalScope causes the coroutine to survive indefinitely on native threads, rendering Swift-side lifecycle cleanup completely ineffective and leaking closures.
```kotlin
package com.example.shared

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class UserRepository {
    // CRITICAL BUG: GlobalScope creates unmanaged detached Jobs that bypass iOS lifecycle teardown
    fun observeUser(onUpdate: (String) -> Unit) {
        GlobalScope.launch(Dispatchers.Main) {
            userFlow().collect { onUpdate(it) }
        }
    }

    private fun userFlow(): Flow<String> = flow { emit("User") }
}
```

#### Production Standard (Correct)
> **Standard**: Provides a scoped SupervisorJob and returns an explicit DisposableHandle so the native consumer can deterministically cancel the execution frame, eliminating leaks across runtime boundaries.
```kotlin
package com.example.shared

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

interface DisposableHandle {
    fun dispose()
}

class UserRepository(private val parentScope: CoroutineScope? = null) {
    private val scope = parentScope ?: CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    fun observeUser(onUpdate: (String) -> Unit): DisposableHandle {
        val job = scope.launch {
            userFlow().collect { onUpdate(it) }
        }
        return object : DisposableHandle {
            override fun dispose() {
                job.cancel()
            }
        }
    }

    fun close() {
        scope.cancel()
    }

    private fun userFlow(): Flow<String> = flow { emit("User") }
}
```

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: KMP Native Coroutines Memory-Leak Immunity Standard

KMP Native Coroutines Memory-Leak Immunity Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict lifecycle boundaries and deterministic cancellation contracts between Kotlin Multiplatform Coroutines and Swift/Objective-C runtime memory management. Eliminates uncollected ARC reference cycles and detached Job retention across Apple native foreign-function interfaces by mandating explicit disposable tokens and scope deallocation hooks. 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: Retaining Long-Lived Kotlin Job Continuations via Escaping Swift Closures and Strong Scope Capture 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 DriftRetaining Long-Lived Kotlin Job Continuations via Escaping Swift Closures and Strong Scope CaptureCritical
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 expose a deterministic cancellation handle (e.g., CancellationToken, Closeable, or JobDisposable) for any Kotlin Coroutine or Flow bridge consumed by Swift.

Engineers MUST ALWAYS expose a deterministic cancellation handle (e.g., CancellationToken, Closeable, or JobDisposable) for any Kotlin Coroutine or Flow bridge consumed by Swift.

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 NOT capture strong self references inside Swift completion handlers or async iterators bridging Kotlin Coroutine continuations.

Engineers MUST NOT capture strong self references inside Swift completion handlers or async iterators bridging Kotlin Coroutine continuations.

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

Code MUST bind Kotlin CoroutineScope lifecycles directly to host platform components (such as SwiftUI .task / onDisappear or UIViewController deinit) ensuring job.cancel() execution on teardown.

Code MUST bind Kotlin CoroutineScope lifecycles directly to host platform components (such as SwiftUI .task / onDisappear or UIViewController deinit) ensuring job.cancel() execution on teardown.

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

Services MUST leverage KMP-NativeCoroutines (@NativeCoroutines, @NativeCoroutineScope) or custom Disposable wrappers to guarantee unregistration of continuous streams when the native UI detaches.

Services MUST leverage KMP-NativeCoroutines (@NativeCoroutines, @NativeCoroutineScope) or custom Disposable wrappers to guarantee unregistration of continuous streams when the native UI detaches.

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

Components NEVER bridge raw GlobalScope or Unconfined CoroutineContexts to native iOS callers without an explicit parent Job.

Components NEVER bridge raw GlobalScope or Unconfined CoroutineContexts to native iOS callers without an explicit parent Job.

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 KMP Native Coroutines Memory-Leak Immunity Standard critical for AI coding assistants?

Enforces strict lifecycle boundaries and deterministic cancellation contracts between Kotlin Multiplatform Coroutines and Swift/Objective-C runtime memory management. Eliminates uncollected ARC reference cycles and detached Job retention across Apple native foreign-function interfaces by mandating explicit disposable tokens and scope deallocation hooks. 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 (Retaining Long-Lived Kotlin Job Continuations via Escaping Swift Closures and Strong Scope Capture) 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

KMP