This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-native-heap-continuation-lifecycle-fence

KMP Native Heap Continuation Lifecycle Fence for Swift-Kotlin Interop

Establishes deterministic lifecycle fencing and bidirectional cancellation propagation across the Kotlin Multiplatform (Kotlin/Native) and Swift interop boundary. Prevents native heap leaks, zombie coroutine executions, and dangling Swift continuation resumption crashes by enforcing synchronous cancellation unbinding when native consumers deallocate.

Prohibited Anti-Pattern: Unfenced Async Swift-Kotlin Bridge Invocation Causing Dangling Continuations and Native Memory Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Heap Continuation Lifecycle Fence for Swift-Kotlin Interop - Establishes deterministic lifecycle fencing and bidirectional cancellation propagation across the Kotlin Multiplatform (Kotlin/Native) and Swift interop boundary. Prevents native heap leaks, zombie coroutine executions, and dangling Swift continuation resumption crashes by enforcing synchronous cancellation unbinding when native consumers deallocate.
globs: iosApp/**/*.swift, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-heap-continuation-lifecycle-fence"
---

# KMP Native Heap Continuation Lifecycle Fence for Swift-Kotlin Interop

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unfenced Async Swift-Kotlin Bridge Invocation Causing Dangling Continuations and Native Memory Leaks

## System Constraints
You are a Principal Mobile Architect enforcing strict native memory fences and coroutine lifecycle boundaries between Swift and Kotlin Multiplatform (Kotlin/Native). You must mandate structural unbinding, cancellation propagation, and heap continuation protection on all Swift-Kotlin interop bridges.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift-side adaptations of Kotlin suspend functions in `withTaskCancellationHandler` to forward Swift Structured Concurrency cancellation to the underlying Kotlin `Job`.
- Engineers MUST NOT bridge Kotlin `suspend` functions using raw un-fenced `withCheckedContinuation` or `withUnsafeContinuation` without storing and invoking the returned `Cancellable` / `DisposableHandle`.
- Components bridge-binding Kotlin flows or suspend calls to Swift UI elements MUST explicitly unbind and cancel subscriptions within the Swift object's `deinit` or SwiftUI `.onDisappear` lifecycle phase.
- Kotlin/Native bridges MUST NEVER retain Swift completion closures in global native memory heaps without explicit boundary guarantees and timeout-based fail-safes.
- Engineers MUST wrap all completion callbacks across the FFI boundary with atomic single-resumption guards (`AtomicBoolean` / `os_unfair_lock`) to avoid fatal double-resumption panic exceptions.

## Bad vs Good Implementations
### Swift Bridge Continuation Lifecycle Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native continuation has no cancellation fence. If the Swift Task cancels or its enclosing scope is deallocated before Kotlin finishes, the Kotlin coroutine continues executing in the background, leaks allocated memory in the native heap, and attempts to resume a dangling Swift continuation pointer, triggering undefined behavior or a crash.
```swift
import SharedLibrary

final class UserRepository {
    private let sdk: KotlinUserSdk

    init(sdk: KotlinUserSdk) {
        self.sdk = sdk
    }

    func fetchUserProfile(id: String) async throws -> UserProfile {
        // CRITICAL ANTI-PATTERN: Leaks Kotlin coroutine on Swift Task cancellation.
        // If the Swift Task is cancelled or the calling view deallocates,
        // the Kotlin suspend function runs indefinitely, holding native heap references.
        // Resuming a deallocated Swift continuation causes EXC_BAD_ACCESS.
        return try await withCheckedThrowingContinuation { continuation in
            sdk.fetchUserProfile(id: id) { profile, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else if let profile = profile {
                    continuation.resume(returning: profile)
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses `withTaskCancellationHandler` to immediately signal cancellation to the Kotlin coroutine if the Swift Task cancels. Protects continuation resumption with an unfair lock to eliminate duplicate resume invocations and guarantees unbinding across the native heap boundary.
```swift
import SharedLibrary
import Foundation

final class UserRepository {
    private let sdk: KotlinUserSdk

    init(sdk: KotlinUserSdk) {
        self.sdk = sdk
    }

    func fetchUserProfile(id: String) async throws -> UserProfile {
        // LIFECYCLE FENCE: Binds Kotlin Job cancellation directly to Swift Task cancellation.
        // Prevents dangling Swift continuation pointers and frees Kotlin/Native heap objects.
        let cancellableHolder = AtomicReference<SharedLibrary.Cancellable?>(nil)

        return try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { continuation in
                let resumed = OSAllocatedUnfairLock(initial: false)
                let cancellable = sdk.fetchUserProfile(id: id) { profile, error in
                    resumed.withLock { isResumed in
                        guard !isResumed else { return }
                        isResumed = true
                        if let error = error {
                            continuation.resume(throwing: error)
                        } else if let profile = profile {
                            continuation.resume(returning: profile)
                        }
                    }
                }
                cancellableHolder.set(cancellable)
            }
        } onCancel: {
            cancellableHolder.get()?.cancel()
        }
    }
}

final class AtomicReference<T>: @unchecked Sendable {
    private let lock = NSLock()
    private var value: T
    init(_ value: T) { self.value = value }
    func set(_ newValue: T) { lock.withLock { value = newValue } }
    func get() -> T { lock.withLock { value } }
}
```

### Kotlin/Native Interop Bridge Cancellation Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: GlobalScope launches root-level coroutines with no parent lifecycle, retaining parameters and closures on the native heap indefinitely. Swift callers cannot cancel ongoing background work, causing native leaks and thread pool exhaustion.
```kotlin
package com.example.shared

import kotlinx.coroutines.*

class KotlinUserSdk {
    // CRITICAL ANTI-PATTERN: Spawning unconfined Jobs in GlobalScope across the native bridge.
    // Swift has no handle to cancel this coroutine when the UI view dismisses.
    fun fetchUserProfile(id: String, onComplete: (UserProfile?, Exception?) -> Unit) {
        GlobalScope.launch(Dispatchers.Default) {
            try {
                val profile = apiService.getUser(id)
                onComplete(profile, null)
            } catch (e: Exception) {
                onComplete(null, e)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Provides a clean `Cancellable` contract across the FFI boundary, executes within a scoped context, honors `CancellationException`, and prevents zombie callbacks into the Swift runtime.
```kotlin
package com.example.shared

import kotlinx.coroutines.*

interface Cancellable {
    fun cancel()
}

class KotlinUserSdk(private val coroutineScope: CoroutineScope) {
    // LIFECYCLE FENCE: Exposes a deterministic Cancellable handle back to the Swift runtime
    // and ties execution to an unbindable, structured CoroutineScope.
    fun fetchUserProfile(id: String, onComplete: (UserProfile?, Exception?) -> Unit): Cancellable {
        val job = coroutineScope.launch(Dispatchers.Default) {
            try {
                val profile = apiService.getUser(id)
                ensureActive()
                onComplete(profile, null)
            } catch (e: CancellationException) {
                // Propagate clean cancellation without invoking the completion callback
                throw e
            } catch (e: Exception) {
                onComplete(null, e)
            }
        }

        return object : Cancellable {
            override fun cancel() {
                job.cancel()
            }
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Native Heap Continuation Lifecycle Fence for Swift-Kotlin Interop

KMP Native Heap Continuation Lifecycle Fence for Swift-Kotlin Interop defines an industrial-grade behavioral standard for mobile engineering. Establishes deterministic lifecycle fencing and bidirectional cancellation propagation across the Kotlin Multiplatform (Kotlin/Native) and Swift interop boundary. Prevents native heap leaks, zombie coroutine executions, and dangling Swift continuation resumption crashes by enforcing synchronous cancellation unbinding when native consumers deallocate. 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: Unfenced Async Swift-Kotlin Bridge Invocation Causing Dangling Continuations and Native Memory Leaks 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 DriftUnfenced Async Swift-Kotlin Bridge Invocation Causing Dangling Continuations and Native Memory LeaksCritical
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 wrap Swift-side adaptations of Kotlin suspend functions in `withTaskCancellationHandler` to forward Swift Structured Concurrency cancellation to the underlying Kotlin `Job`.

Engineers MUST ALWAYS wrap Swift-side adaptations of Kotlin suspend functions in `withTaskCancellationHandler` to forward Swift Structured Concurrency cancellation to the underlying Kotlin `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.
2

Engineers MUST NOT bridge Kotlin `suspend` functions using raw un-fenced `withCheckedContinuation` or `withUnsafeContinuation` without storing and invoking the returned `Cancellable` / `DisposableHandle`.

Engineers MUST NOT bridge Kotlin `suspend` functions using raw un-fenced `withCheckedContinuation` or `withUnsafeContinuation` without storing and invoking the returned `Cancellable` / `DisposableHandle`.

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

Components bridge-binding Kotlin flows or suspend calls to Swift UI elements MUST explicitly unbind and cancel subscriptions within the Swift object's `deinit` or SwiftUI `.onDisappear` lifecycle phase.

Components bridge-binding Kotlin flows or suspend calls to Swift UI elements MUST explicitly unbind and cancel subscriptions within the Swift object's `deinit` or SwiftUI `.onDisappear` lifecycle phase.

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

Kotlin/Native bridges MUST NEVER retain Swift completion closures in global native memory heaps without explicit boundary guarantees and timeout-based fail-safes.

Kotlin/Native bridges MUST NEVER retain Swift completion closures in global native memory heaps without explicit boundary guarantees and timeout-based fail-safes.

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

Engineers MUST wrap all completion callbacks across the FFI boundary with atomic single-resumption guards (`AtomicBoolean` / `os_unfair_lock`) to avoid fatal double-resumption panic exceptions.

Engineers MUST wrap all completion callbacks across the FFI boundary with atomic single-resumption guards (`AtomicBoolean` / `os_unfair_lock`) to avoid fatal double-resumption panic exceptions.

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 Heap Continuation Lifecycle Fence for Swift-Kotlin Interop critical for AI coding assistants?

Establishes deterministic lifecycle fencing and bidirectional cancellation propagation across the Kotlin Multiplatform (Kotlin/Native) and Swift interop boundary. Prevents native heap leaks, zombie coroutine executions, and dangling Swift continuation resumption crashes by enforcing synchronous cancellation unbinding when native consumers deallocate. 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 (Unfenced Async Swift-Kotlin Bridge Invocation Causing Dangling Continuations and Native Memory Leaks) 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