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

KMP 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract

Enforces strict isolation barriers and actor boundaries when bridging Kotlin Coroutines Flows and suspend functions into Swift via KMP 2.1 Swift-Export. Unfenced consumption across direct native boundaries induces Swift 6 data races, untracked Task deallocations, and thread-pool pool desynchronization. Native bridge calls must explicitly establish AsyncSequence fences bound to explicit Swift Actors.

Prohibited Anti-Pattern: Direct Unscoped Flow Collection and Unfenced Continuation Resumptions Across Native Swift-Export Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract - Enforces strict isolation barriers and actor boundaries when bridging Kotlin Coroutines Flows and suspend functions into Swift via KMP 2.1 Swift-Export. Unfenced consumption across direct native boundaries induces Swift 6 data races, untracked Task deallocations, and thread-pool pool desynchronization. Native bridge calls must explicitly establish AsyncSequence fences bound to explicit Swift Actors.
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-export-concurrency-barrier"
---

# KMP 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Unscoped Flow Collection and Unfenced Continuation Resumptions Across Native Swift-Export Boundaries

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety and structured concurrency across Kotlin Multiplatform 2.1 Direct Swift-Export native boundaries. Direct invocation of Kotlin suspend functions or raw Flow collectors across the Objective-C/Swift interop layer without explicit actor isolation triggers catastrophic memory safety violations under Swift 6 strict concurrency checks. You must mandate actor-isolated bridging wrappers, explicit Task cancellation propagation, and AsyncSequence barriers.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift-Export generated Flows into an actor-isolated AsyncSequence wrapper before consumption in the UI or service layer.
- Engineers MUST NOT invoke Swift-Export async functions directly from non-isolated synchronous contexts or fire-and-forget Task blocks without explicit MainActor or custom Actor binding.
- Bridge adapters MUST enforce bidirectional cancellation: cancelling the Swift Task MUST immediately invoke the Kotlin Job.cancel() handle to prevent coroutine leaks.
- Flow collection crossing the native barrier MUST pass through a dedicated @Sendable memory fence ensuring all emitted values conform to Sendable.
- Engineers MUST NOT rely on implicit thread hop semantics; native Kotlin Dispatchers.Main and Swift @MainActor must be explicitly synchronized across boundary crossings.

## Bad vs Good Implementations
### Swift-Export Flow Bridging into Actor-Isolated AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly collecting a Kotlin Multiplatform Flow in an unscoped Swift Task bypasses Swift 6 strict concurrency checking. It introduces unsafe concurrent mutations to ViewModel state, does not guarantee thread jumping back to the MainActor, and permanently leaks the underlying Kotlin Job when the ViewModel deinitializes.
```swift
import SwiftUI
import SharedKit // Generated via Swift-Export

@Observable
final class DeviceTelemetryViewModel {
    var telemetryData: String = ""
    
    func startObserving() {
        // ANTI-PATTERN: Non-isolated Task collecting directly from Kotlin Flow export
        // Missing memory barrier, no Sendable enforcement, and leaking coroutine execution on dealloc
        Task {
            let flow = TelemetryRepository().observeMetrics()
            flow.collect { data in
                // Direct mutation without actor boundary verification
                self.telemetryData = data.description
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation wraps the Kotlin Flow emission pipeline into an actor-fenced AsyncThrowingStream. It bounds emissions to @MainActor, guarantees thread safety under Swift 6 strict checking, and wires up continuation.onTermination directly to cancel the Kotlin coroutine Job upon Swift Task teardown.
```swift
import SwiftUI
import SharedKit

@MainActor
@Observable
final class DeviceTelemetryViewModel {
    private(set) var telemetryData: String = ""
    private var observationTask: Task<Void, Never>?

    func startObserving(repository: TelemetryRepository) {
        observationTask?.cancel()
        
        observationTask = Task { [weak self] in
            // PRODUCTION BARRIER: Adapter converts KMP Flow into Actor-fenced AsyncSequence with cancellation link
            let stream = AsyncThrowingStream<TelemetryMetrics, Error> { continuation in
                let job = repository.observeMetrics().subscribe(
                    onEach: { item in continuation.yield(item) },
                    onCompletion: { error in
                        if let error { continuation.finish(throwing: error) }
                        else { continuation.finish() }
                    }
                )
                continuation.onTermination = { @Sendable _ in
                    job.cancel()
                }
            }
            
            do {
                for try await metric in stream {
                    guard !Task.isCancelled else { break }
                    self?.telemetryData = metric.description
                }
            } catch {
                // Structured error handling on MainActor
            }
        }
    }
    
    deinit {
        observationTask?.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: KMP 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract

KMP 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation barriers and actor boundaries when bridging Kotlin Coroutines Flows and suspend functions into Swift via KMP 2.1 Swift-Export. Unfenced consumption across direct native boundaries induces Swift 6 data races, untracked Task deallocations, and thread-pool pool desynchronization. Native bridge calls must explicitly establish AsyncSequence fences bound to explicit Swift Actors. 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: Direct Unscoped Flow Collection and Unfenced Continuation Resumptions Across Native Swift-Export 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 DriftDirect Unscoped Flow Collection and Unfenced Continuation Resumptions Across Native Swift-Export 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 wrap Swift-Export generated Flows into an actor-isolated AsyncSequence wrapper before consumption in the UI or service layer.

Engineers MUST ALWAYS wrap Swift-Export generated Flows into an actor-isolated AsyncSequence wrapper before consumption in the UI or service layer.

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 invoke Swift-Export async functions directly from non-isolated synchronous contexts or fire-and-forget Task blocks without explicit MainActor or custom Actor binding.

Engineers MUST NOT invoke Swift-Export async functions directly from non-isolated synchronous contexts or fire-and-forget Task blocks without explicit MainActor or custom Actor binding.

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

Bridge adapters MUST enforce bidirectional cancellation

Bridge adapters MUST enforce bidirectional cancellation: cancelling the Swift Task MUST immediately invoke the Kotlin Job.cancel() handle to prevent coroutine leaks.

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

Flow collection crossing the native barrier MUST pass through a dedicated @Sendable memory fence ensuring all emitted values conform to Sendable.

Flow collection crossing the native barrier MUST pass through a dedicated @Sendable memory fence ensuring all emitted values conform to Sendable.

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 NOT rely on implicit thread hop semantics

Engineers MUST NOT rely on implicit thread hop semantics; native Kotlin Dispatchers.Main and Swift @MainActor must be explicitly synchronized across boundary crossings.

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 2.1 Swift-Export Actor-Bound Concurrency Barrier Contract critical for AI coding assistants?

Enforces strict isolation barriers and actor boundaries when bridging Kotlin Coroutines Flows and suspend functions into Swift via KMP 2.1 Swift-Export. Unfenced consumption across direct native boundaries induces Swift 6 data races, untracked Task deallocations, and thread-pool pool desynchronization. Native bridge calls must explicitly establish AsyncSequence fences bound to explicit Swift Actors. 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 (Direct Unscoped Flow Collection and Unfenced Continuation Resumptions Across Native Swift-Export 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