This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skie-swift-concurrency-bridge-invariant

Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant

Enforces deterministic lifecycle management, cooperative cancellation, and leak-free memory semantics when bridging Kotlin Coroutines and Flows to Swift async/await and AsyncSequence via SKIE. Eliminates retain cycles caused by unmanaged Swift Task instances holding Kotlin Job references across the Native/Swift interop boundary.

Prohibited Anti-Pattern: Unscoped Swift Task Bridging of Kotlin Flows and Suspending Functions Inducing Memory Leaks and Zombie Coroutines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant - Enforces deterministic lifecycle management, cooperative cancellation, and leak-free memory semantics when bridging Kotlin Coroutines and Flows to Swift async/await and AsyncSequence via SKIE. Eliminates retain cycles caused by unmanaged Swift Task instances holding Kotlin Job references across the Native/Swift interop boundary.
globs: iosApp/**/*.swift, shared/src/commonMain/**/*.kt, shared/src/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skie-swift-concurrency-bridge-invariant"
---

# Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unscoped Swift Task Bridging of Kotlin Flows and Suspending Functions Inducing Memory Leaks and Zombie Coroutines

## System Constraints
You are a Principal Mobile Architect enforcing strict SKIE Swift Concurrency interop invariants between Kotlin Multiplatform and Swift. Mandate explicit task cancellation, weak self-binding in Swift Task contexts, structured cancellation bridging between Swift Task and Kotlin Job, and prevention of deadlock or leakage on Swift AsyncSequence consumption.

## Strict Guidelines
- Engineers MUST ALWAYS bind SKIE-generated Swift AsyncSequence iterations to a structured Swift Task lifecycle (e.g., SwiftUI .task modifier or an explicit cancellable Task property) to ensure cooperative cancellation propagates back to the underlying Kotlin Job.
- Engineers MUST NEVER capture strong references to Swift view models, controllers, or delegates inside long-running 'for await value in skieFlow' loops.
- Engineers MUST ALWAYS ensure Kotlin Coroutine APIs exposed via SKIE are backed by bounded StateFlow or SharedFlow rather than raw unbuffered Channels to prevent memory pressure from Swift backpressure mismatches.
- Engineers MUST NOT execute SKIE-bridged suspending calls inside Task.detached without passing an explicit cancellation bridge or managing Job lifecycle manually.
- Swift code consuming SKIE suspending functions from actors MUST isolate Kotlin interop calls to non-blocking execution paths and avoid re-entrant suspension locks on @MainActor.

## Bad vs Good Implementations
### Consuming SKIE Flow as Swift AsyncSequence in SwiftUI ViewModel

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Task.detached creates an unstructured concurrency context that does not inherit cancellation context. Capturing 'self' strongly in the infinite 'for await' loop prevents deallocation of the ViewModel, leaking the Kotlin Flow subscription and maintaining an active Kotlin Job across the Native bridge.
```swift
class UserProfileViewModel: ObservableObject {
    @Published var state: UserState = .loading
    private let repository: UserRepository

    init(repository: UserRepository) {
        self.repository = repository
        // ANTI-PATTERN: Detached task with strong self capture.
        // If ViewModel is deallocated, the Task and Kotlin Flow collector leak indefinitely.
        Task.detached {
            for await userState in self.repository.userStateFlow {
                await MainActor.run {
                    self.state = userState
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The Task is strictly tied to the ViewModel lifecycle, uses [weak self] to prevent retain cycles, checks Task.isCancelled cooperatively, and explicitly cancels the Task on stopObserving or deinit, triggering SKIE's coroutine job cancellation on the Kotlin side.
```swift
@MainActor
final class UserProfileViewModel: ObservableObject {
    @Published private(set) var state: UserState = .loading
    private let repository: UserRepository
    private var streamTask: Task<Void, Never>?

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

    func startObserving() {
        streamTask?.cancel()
        streamTask = Task { [weak self] in
            // SKIE generates Swift AsyncSequence from Kotlin Flow
            for await userState in self?.repository.userStateFlow ?? Empty().eraseToAnyPublisher().values {
                guard !Task.isCancelled, let self = self else { break }
                self.state = userState
            }
        }
    }

    func stopObserving() {
        streamTask?.cancel()
        streamTask = nil
    }

    deinit {
        streamTask?.cancel()
    }
}
```

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: Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant

Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic lifecycle management, cooperative cancellation, and leak-free memory semantics when bridging Kotlin Coroutines and Flows to Swift async/await and AsyncSequence via SKIE. Eliminates retain cycles caused by unmanaged Swift Task instances holding Kotlin Job references across the Native/Swift interop 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: Unscoped Swift Task Bridging of Kotlin Flows and Suspending Functions Inducing Memory Leaks and Zombie Coroutines 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 DriftUnscoped Swift Task Bridging of Kotlin Flows and Suspending Functions Inducing Memory Leaks and Zombie CoroutinesCritical
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 SKIE-generated Swift AsyncSequence iterations to a structured Swift Task lifecycle (e.g., SwiftUI .task modifier or an explicit cancellable Task property) to ensure cooperative cancellation propagates back to the underlying Kotlin Job.

Engineers MUST ALWAYS bind SKIE-generated Swift AsyncSequence iterations to a structured Swift Task lifecycle (e.g., SwiftUI .task modifier or an explicit cancellable Task property) to ensure cooperative cancellation propagates back 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 NEVER capture strong references to Swift view models, controllers, or delegates inside long-running 'for await value in skieFlow' loops.

Engineers MUST NEVER capture strong references to Swift view models, controllers, or delegates inside long-running 'for await value in skieFlow' loops.

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 ALWAYS ensure Kotlin Coroutine APIs exposed via SKIE are backed by bounded StateFlow or SharedFlow rather than raw unbuffered Channels to prevent memory pressure from Swift backpressure mismatches.

Engineers MUST ALWAYS ensure Kotlin Coroutine APIs exposed via SKIE are backed by bounded StateFlow or SharedFlow rather than raw unbuffered Channels to prevent memory pressure from Swift backpressure mismatches.

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

Engineers MUST NOT execute SKIE-bridged suspending calls inside Task.detached without passing an explicit cancellation bridge or managing Job lifecycle manually.

Engineers MUST NOT execute SKIE-bridged suspending calls inside Task.detached without passing an explicit cancellation bridge or managing Job lifecycle manually.

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

Swift code consuming SKIE suspending functions from actors MUST isolate Kotlin interop calls to non-blocking execution paths and avoid re-entrant suspension locks on @MainActor.

Swift code consuming SKIE suspending functions from actors MUST isolate Kotlin interop calls to non-blocking execution paths and avoid re-entrant suspension locks on @MainActor.

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 Kotlin Multiplatform SKIE Swift Concurrency Bridge & Memory Invariant critical for AI coding assistants?

Enforces deterministic lifecycle management, cooperative cancellation, and leak-free memory semantics when bridging Kotlin Coroutines and Flows to Swift async/await and AsyncSequence via SKIE. Eliminates retain cycles caused by unmanaged Swift Task instances holding Kotlin Job references across the Native/Swift interop 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 (Unscoped Swift Task Bridging of Kotlin Flows and Suspending Functions Inducing Memory Leaks and Zombie Coroutines) 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

Kotlin