This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-swift-concurrency-actor-isolation-boundary-kotlin-multiplat-883

KMP and Swift Concurrency Actor Isolation Boundary

Strictly enforces isolation between Kotlin Multiplatform (KMP) Coroutine runtimes and native Swift actors under modern Swift 6 strict concurrency. Forbids passing unconstrained reference types across the FFI boundary, mandating defensive transformations into immutable Swift Sendable value types and explicit actor isolation.

Prohibited Anti-Pattern: Leaking Non-Sendable Kotlin Reference Types Directly Across Swift Async/Await Actor Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP and Swift Concurrency Actor Isolation Boundary - Strictly enforces isolation between Kotlin Multiplatform (KMP) Coroutine runtimes and native Swift actors under modern Swift 6 strict concurrency. Forbids passing unconstrained reference types across the FFI boundary, mandating defensive transformations into immutable Swift Sendable value types and explicit actor isolation.
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-swift-concurrency-actor-isolation-boundary-kotlin-multiplat-883"
---

# KMP and Swift Concurrency Actor Isolation Boundary

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaking Non-Sendable Kotlin Reference Types Directly Across Swift Async/Await Actor Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing absolute actor isolation between Kotlin Multiplatform (KMP) runtimes and native Swift Concurrency. Kotlin/Native Obj-C export does not synthesize Swift Sendable conformances for classes, creating severe thread-safety vulnerabilities when consumed inside Swift actors. You must enforce strict boundaries where Kotlin StateFlows, suspend functions, and shared references are defensively mapped into immutable Swift Sendable value types at the ingestion layer.

## Strict Guidelines
- Engineers MUST ALWAYS map Kotlin reference classes into Swift Sendable value types (structs) before crossing Swift actor isolation domains.
- Engineers MUST NOT expose raw mutable Kotlin StateFlow or SharedFlow objects directly to multi-actor Swift environments without thread-confinement wrappers.
- Engineers MUST annotate boundary-mediating Swift view models and coordinators with explicit global actor attributes (e.g., @MainActor) or isolate them within dedicated custom actors.
- Swift bridging code MUST cancel and detach KMP Kotlin CoroutineScope/Job instances deterministically inside actor deinitialization or task cancellation handlers to prevent dangling background worker threads.
- Components NEVER mutate Kotlin data structures from arbitrary Swift Task contexts; state transitions must be dispatched exclusively through isolated suspend calls or dedicated boundary ports.

## Bad vs Good Implementations
### Consuming KMP StateFlow in Swift Concurrency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin classes exported via KMP Objective-C interop are reference types that do not conform to Swift's Sendable protocol. Storing and crossing non-Sendable Kotlin references within a Swift actor invites unmanaged data races, crashes under Swift 6 complete concurrency checks, and bypasses Swift thread-sanitizer protections.
```swift
import Shared

// ANTI-PATTERN: Direct exposure of non-Sendable Kotlin class across actor boundaries
actor SessionManager {
    private var currentProfile: SharedUserProfile? // Kotlin class reference

    func updateProfile(from flowWrapper: SharedUserProfileFlowWrapper) async {
        // Direct observation of Kotlin flow inside actor without Sendable boundary enforcement
        for await profile in flowWrapper.stream {
            // Thread safety violation: Kotlin reference mutated or retained across thread pools
            self.currentProfile = profile
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Transforms the Kotlin reference type into an immutable Swift Sendable struct immediately upon ingestion. This guarantees that all state stored and handled within the Swift actor satisfies Swift 6 strict concurrency checks, preventing concurrent pointer manipulation and memory corruption.
```swift
import Shared

// PRODUCTION FIX: Explicit Sendable boundary DTO and strict Actor isolation
public struct UserProfileSnapshot: Sendable, Equatable {
    public let id: String
    public let displayName: String

    // Defensive transformation from Kotlin reference type to Swift value type
    init(from kotlinProfile: SharedUserProfile) {
        self.id = kotlinProfile.id
        self.displayName = kotlinProfile.displayName
    }
}

actor SessionManager {
    private(set) var currentSnapshot: UserProfileSnapshot?

    func observeProfileStream(adapter: SharedUserProfileFlowAdapter) async {
        // Stream converted to Swift AsyncSequence yielding immutable Sendable values
        for await kotlinProfile in adapter.asAsyncSequence() {
            let snapshot = UserProfileSnapshot(from: kotlinProfile)
            self.applySnapshot(snapshot)
        }
    }

    private func applySnapshot(_ snapshot: UserProfileSnapshot) {
        self.currentSnapshot = snapshot
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP and Swift Concurrency Actor Isolation Boundary

KMP and Swift Concurrency Actor Isolation Boundary defines an industrial-grade behavioral standard for mobile engineering. Strictly enforces isolation between Kotlin Multiplatform (KMP) Coroutine runtimes and native Swift actors under modern Swift 6 strict concurrency. Forbids passing unconstrained reference types across the FFI boundary, mandating defensive transformations into immutable Swift Sendable value types and explicit actor isolation. 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: Leaking Non-Sendable Kotlin Reference Types Directly Across Swift Async/Await Actor Boundaries 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 DriftLeaking Non-Sendable Kotlin Reference Types Directly Across Swift Async/Await Actor BoundariesCritical
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 map Kotlin reference classes into Swift Sendable value types (structs) before crossing Swift actor isolation domains.

Engineers MUST ALWAYS map Kotlin reference classes into Swift Sendable value types (structs) before crossing Swift actor isolation domains.

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 raw mutable Kotlin StateFlow or SharedFlow objects directly to multi-actor Swift environments without thread-confinement wrappers.

Engineers MUST NOT expose raw mutable Kotlin StateFlow or SharedFlow objects directly to multi-actor Swift environments without thread-confinement 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.
3

Engineers MUST annotate boundary-mediating Swift view models and coordinators with explicit global actor attributes (e.g., @MainActor) or isolate them within dedicated custom actors.

Engineers MUST annotate boundary-mediating Swift view models and coordinators with explicit global actor attributes (e.g., @MainActor) or isolate them within dedicated custom actors.

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 bridging code MUST cancel and detach KMP Kotlin CoroutineScope/Job instances deterministically inside actor deinitialization or task cancellation handlers to prevent dangling background worker threads.

Swift bridging code MUST cancel and detach KMP Kotlin CoroutineScope/Job instances deterministically inside actor deinitialization or task cancellation handlers to prevent dangling background worker threads.

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 mutate Kotlin data structures from arbitrary Swift Task contexts

Components NEVER mutate Kotlin data structures from arbitrary Swift Task contexts; state transitions must be dispatched exclusively through isolated suspend calls or dedicated boundary ports.

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 and Swift Concurrency Actor Isolation Boundary critical for AI coding assistants?

Strictly enforces isolation between Kotlin Multiplatform (KMP) Coroutine runtimes and native Swift actors under modern Swift 6 strict concurrency. Forbids passing unconstrained reference types across the FFI boundary, mandating defensive transformations into immutable Swift Sendable value types and explicit actor isolation. 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 (Leaking Non-Sendable Kotlin Reference Types Directly Across Swift Async/Await Actor Boundaries) 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