This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-coroutine-cancellation-swift-interop

Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries

Enforces deterministic structured concurrency propagation and memory cleanup between Kotlin Coroutines and Swift Concurrency (async/await and Tasks). Unbridged cancellation leads to orphaned Kotlin Jobs, background CPU/battery drain, and memory leaks caused by circular references across the Objective-C runtime boundary.

Prohibited Anti-Pattern: Orphaned Kotlin Jobs and Retain Cycles from Unbridged Swift Task Cancellation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries - Enforces deterministic structured concurrency propagation and memory cleanup between Kotlin Coroutines and Swift Concurrency (async/await and Tasks). Unbridged cancellation leads to orphaned Kotlin Jobs, background CPU/battery drain, and memory leaks caused by circular references across the Objective-C runtime boundary.
globs: shared/src/**/*.kt, iosApp/**/*.swift, **/interop/**/*.kt, **/interop/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-coroutine-cancellation-swift-interop"
---

# Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Kotlin Jobs and Retain Cycles from Unbridged Swift Task Cancellation

## System Constraints
You are a Principal Mobile Architect enforcing robust Kotlin Multiplatform (KMP) to Swift concurrency interop. Mandate deterministic cancellation bridging between Swift Task and Kotlin Coroutine Jobs, zero dangling references across the ARC/Kotlin GC boundary, and standardized error translation without swallowing CancellationException.

## Strict Guidelines
- Engineers MUST ALWAYS bind Swift Task cancellation to Kotlin Job cancellation using an interop bridge tool (e.g., SKIE or KMP-NativeCoroutines) or explicit `withTaskCancellationHandler` wrappers.
- Engineers MUST NOT expose naked Kotlin `suspend` functions directly through default Objective-C export headers without a cancellation-token bridge or lifetime handle.
- Kotlin code MUST NEVER catch `CancellationException` generically without rethrowing, as this suppresses cooperative cancellation signals originating from Swift.
- Swift caller contexts MUST catch and translate Kotlin `CancellationException` into Swift `CancellationError` to preserve native Task tree cancellation semantics.
- Engineers MUST break retain cycles across foreign-function interfaces by ensuring Kotlin delegates or callbacks held in native Swift runtimes are cleared in a `finally` block or Swift `defer` statement.
- Services exposing cold Kotlin `Flow`s to Swift MUST invoke terminal flow cancellation immediately upon Swift `AsyncSequence` iteration termination or Task cancellation.

## Bad vs Good Implementations
### Manual Swift-to-Kotlin Suspend Cancellation via withTaskCancellationHandler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The continuation bridges standard completion, but if the calling Swift Task is cancelled before the Kotlin coroutine finishes, the Kotlin Job continues running unmonitored. This creates background resource leaks and potential race conditions.
```swift
import Shared

func loadUserData(userId: String) async throws -> UserProfile {
    // ANTI-PATTERN: Default Kotlin/Native Obj-C export exposes completion-handler wrappers.
    // Swift async wrapper does not propagate Task cancellation to the underlying Kotlin Job,
    // leaving the coroutine running indefinitely in the KMP background dispatcher.
    return try await withCheckedThrowingContinuation { continuation in
        UserRepositoryKt.fetchUserProfile(userId: userId) { profile, error in
            if let error = error {
                continuation.resume(throwing: error)
            } else if let profile = profile {
                continuation.resume(returning: profile)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly attaches `withTaskCancellationHandler` to forward Swift Task cancellation to the Kotlin cancellation handle, and maps Kotlin `CancellationException` back to native Swift `CancellationError`.
```swift
import Shared

func loadUserData(userId: String) async throws -> UserProfile {
    let handleHolder = CancellationHandleHolder()
    
    return try await withTaskCancellationHandler {
        try Task.checkCancellation()
        return try await withCheckedThrowingContinuation { continuation in
            let job = UserRepositoryBridge.fetchUserProfileCancellable(
                userId: userId,
                onSuccess: { profile in continuation.resume(returning: profile) },
                onError: { error in
                    if error.isKotlinCancellation() {
                        continuation.resume(throwing: CancellationError())
                    } else {
                        continuation.resume(throwing: error)
                    }
                }
            )
            handleHolder.setHandle(job)
        }
    } onCancel: {
        handleHolder.cancel()
    }
}
```

### Kotlin Side Cancellation Token Retention and Bridge Exposure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Catching `Exception` without rethrowing `CancellationException` breaks cooperative cancellation, preventing the Kotlin coroutine hierarchy from terminating cleanly when cancelled by Swift.
```kotlin
// ANTI-PATTERN: Exposes suspend function directly or hides the Job handle from Native interop
class UserRepository(private val api: ApiClient) {
    suspend fun fetchUserProfile(userId: String): UserProfile {
        return try {
            api.getUser(userId)
        } catch (e: Exception) {
            // Swallows CancellationException and prevents cancellation cleanup
            UserProfile.EMPTY
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Kotlin bridge exposes a concrete `CancellationHandle` back to Swift, strictly rethrows `CancellationException` to maintain structured concurrency, and ensures failures and cancellations propagate back across the FFI.
```kotlin
class UserRepository(private val api: ApiClient) {
    suspend fun fetchUserProfile(userId: String): UserProfile {
        return api.getUser(userId)
    }
}

// Explicit FFI-friendly export bridge
class CancellableBridge(private val scope: CoroutineScope) {
    fun fetchUserProfileCancellable(
        repository: UserRepository,
        userId: String,
        onSuccess: (UserProfile) -> Unit,
        onError: (Throwable) -> Unit
    ): CancellationHandle {
        val job = scope.launch {
            try {
                val profile = repository.fetchUserProfile(userId)
                onSuccess(profile)
            } catch (e: CancellationException) {
                onError(e)
                throw e
            } catch (t: Throwable) {
                onError(t)
            }
        }
        return CancellationHandle { job.cancel() }
    }
}

fun interface CancellationHandle {
    fun cancel()
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries

Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic structured concurrency propagation and memory cleanup between Kotlin Coroutines and Swift Concurrency (async/await and Tasks). Unbridged cancellation leads to orphaned Kotlin Jobs, background CPU/battery drain, and memory leaks caused by circular references across the Objective-C runtime boundary. 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: Orphaned Kotlin Jobs and Retain Cycles from Unbridged Swift Task Cancellation 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 DriftOrphaned Kotlin Jobs and Retain Cycles from Unbridged Swift Task CancellationCritical
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 bind Swift Task cancellation to Kotlin Job cancellation using an interop bridge tool (e.g., SKIE or KMP-NativeCoroutines) or explicit `withTaskCancellationHandler` wrappers.

Engineers MUST ALWAYS bind Swift Task cancellation to Kotlin Job cancellation using an interop bridge tool (e.g., SKIE or KMP-NativeCoroutines) or explicit `withTaskCancellationHandler` wrappers.

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 expose naked Kotlin `suspend` functions directly through default Objective-C export headers without a cancellation-token bridge or lifetime handle.

Engineers MUST NOT expose naked Kotlin `suspend` functions directly through default Objective-C export headers without a cancellation-token bridge or lifetime handle.

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

Kotlin code MUST NEVER catch `CancellationException` generically without rethrowing, as this suppresses cooperative cancellation signals originating from Swift.

Kotlin code MUST NEVER catch `CancellationException` generically without rethrowing, as this suppresses cooperative cancellation signals originating from 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.
4

Swift caller contexts MUST catch and translate Kotlin `CancellationException` into Swift `CancellationError` to preserve native Task tree cancellation semantics.

Swift caller contexts MUST catch and translate Kotlin `CancellationException` into Swift `CancellationError` to preserve native Task tree cancellation semantics.

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 break retain cycles across foreign-function interfaces by ensuring Kotlin delegates or callbacks held in native Swift runtimes are cleared in a `finally` block or Swift `defer` statement.

Engineers MUST break retain cycles across foreign-function interfaces by ensuring Kotlin delegates or callbacks held in native Swift runtimes are cleared in a `finally` block or Swift `defer` statement.

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.
6

Services exposing cold Kotlin `Flow`s to Swift MUST invoke terminal flow cancellation immediately upon Swift `AsyncSequence` iteration termination or Task cancellation.

Services exposing cold Kotlin `Flow`s to Swift MUST invoke terminal flow cancellation immediately upon Swift `AsyncSequence` iteration termination or Task cancellation.

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 Deterministic Coroutine Cancellation and Memory Cleanup Across Swift-Kotlin FFI Boundaries critical for AI coding assistants?

Enforces deterministic structured concurrency propagation and memory cleanup between Kotlin Coroutines and Swift Concurrency (async/await and Tasks). Unbridged cancellation leads to orphaned Kotlin Jobs, background CPU/battery drain, and memory leaks caused by circular references across the Objective-C runtime boundary. 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 (Orphaned Kotlin Jobs and Retain Cycles from Unbridged Swift Task Cancellation) 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

Deterministic