This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-shared-flow-swift6-sendable-guardrail

Kotlin 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail

Enforces thread-safe, data-race-free interoperability between Kotlin Multiplatform 2.1 SharedFlow/StateFlow emissions and Swift 6 Complete Concurrency AsyncSequences. Eliminates cross-runtime thread pool exhaustion and cooperative thread starvation deadlocks caused by unmanaged coroutine collectors. Mandates strict Sendable isolation and deterministic cancellation bridging across the Darwin runtime boundary.

Prohibited Anti-Pattern: Unchecked Cross-Boundary Flow Bridging Causing Swift 6 Isolation Escapes and Cooperative Thread Starvation Deadlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail - Enforces thread-safe, data-race-free interoperability between Kotlin Multiplatform 2.1 SharedFlow/StateFlow emissions and Swift 6 Complete Concurrency AsyncSequences. Eliminates cross-runtime thread pool exhaustion and cooperative thread starvation deadlocks caused by unmanaged coroutine collectors. Mandates strict Sendable isolation and deterministic cancellation bridging across the Darwin runtime boundary.
globs: **/*.kt, **/*.swift, 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-shared-flow-swift6-sendable-guardrail"
---

# Kotlin 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Cross-Boundary Flow Bridging Causing Swift 6 Isolation Escapes and Cooperative Thread Starvation Deadlocks

## System Constraints
You are a Principal Software Architect enforcing Kotlin Multiplatform 2.1 and Swift 6 Concurrency boundaries. Your task is to enforce strict compile-time data race freedom across KMP Kotlin Coroutines (StateFlow/SharedFlow) and native Swift AsyncSequences. Prevent non-Sendable Objective-C bridged object escapes across Swift actors and eliminate runtime deadlocks originating from synchronous blocking on Swift's cooperative pool or unmanaged KMP Job lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS bridge Kotlin Flow instances to Swift using an AsyncStream or AsyncThrowingStream that deterministically cancels the underlying Kotlin kotlinx.coroutines.Job within `onTermination`.
- Engineers MUST NOT cross Swift 6 actor boundaries with mutable Kotlin reference classes; emitted payload models MUST be immutable, marked `@Sendable` on the Swift wrapper side, or strictly confined to the `@MainActor`.
- Code MUST NEVER invoke `runBlocking` or block a Swift cooperative thread awaiting a Kotlin suspend function or Flow emission.
- Services MUST route UI-bound Flow consumption explicitly through `@MainActor` isolated wrappers, preventing cross-thread mutation of Swift state by Kotlin Darwin workers.
- Components NEVER hold strong unmanaged references to Kotlin CoroutineScope instances inside Swift async contexts without structured lifetime binding.

## Bad vs Good Implementations
### Bridging Kotlin Flow to Swift 6 AsyncSequence with Sendable Safety and Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad code triggers Swift 6 complete concurrency warnings/errors because UserProfile bridged from Obj-C/KMP is non-Sendable across actor boundaries. Crucially, it omits `continuation.onTermination`, causing the Kotlin coroutine collector to leak indefinitely. If the caller's Task is cancelled, the Kotlin coroutine continues collecting, risking memory leaks and dispatch queue starvation.
```swift
// Anti-Pattern: Flow collection without Sendable conformance, leaking Job lifecycle and risking deadlock
import SharedKit

final class FlowBridge {
    func observeEvents(flow: SharedFlowWrapper<UserProfile>) -> AsyncStream<UserProfile> {
        AsyncStream { continuation in
            // Violates Swift 6: UserProfile is not Sendable, closure runs asynchronously across boundaries
            flow.collect { profile in
                continuation.yield(profile)
            }
            // BUG: No onTermination handler. Kotlin coroutine Job is never cancelled!
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The production code enforces Swift 6 data-race freedom by mapping the non-Sendable native Kotlin object into a Swift-native `Sendable` value type (`UserProfileDTO`). It isolates the stream construction and wires `continuation.onTermination` to synchronously invoke `cancellable.cancel()`, tearing down the Kotlin Coroutine Job and preventing memory leaks or deadlocks.
```swift
// Production Standard: Thread-safe, Sendable-isolated bridge with deterministic Job lifecycle
import SharedKit

// Sendable DTO guaranteed to be deep-copied or immutable across boundary
public struct UserProfileDTO: Sendable, Equatable {
    public let id: String
    public let name: String
}

extension SharedFlowWrapper where T == NativeUserProfile {
    @MainActor
    public func makeAsyncSequence() -> AsyncStream<UserProfileDTO> {
        AsyncStream(UserProfileDTO.self) { continuation in
            let cancellable = self.collect(onEmit: { nativeProfile in
                let dto = UserProfileDTO(id: nativeProfile.id, name: nativeProfile.name)
                continuation.yield(dto)
            })
            
            continuation.onTermination = { @Sendable _ in
                // Deterministically cancel the underlying Kotlin Job across the boundary
                cancellable.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 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail

Kotlin 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces thread-safe, data-race-free interoperability between Kotlin Multiplatform 2.1 SharedFlow/StateFlow emissions and Swift 6 Complete Concurrency AsyncSequences. Eliminates cross-runtime thread pool exhaustion and cooperative thread starvation deadlocks caused by unmanaged coroutine collectors. Mandates strict Sendable isolation and deterministic cancellation bridging across the Darwin 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: Unchecked Cross-Boundary Flow Bridging Causing Swift 6 Isolation Escapes and Cooperative Thread Starvation Deadlocks 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 DriftUnchecked Cross-Boundary Flow Bridging Causing Swift 6 Isolation Escapes and Cooperative Thread Starvation DeadlocksCritical
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 bridge Kotlin Flow instances to Swift using an AsyncStream or AsyncThrowingStream that deterministically cancels the underlying Kotlin kotlinx.coroutines.Job within `onTermination`.

Engineers MUST ALWAYS bridge Kotlin Flow instances to Swift using an AsyncStream or AsyncThrowingStream that deterministically cancels the underlying Kotlin kotlinx.coroutines.Job within `onTermination`.

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 cross Swift 6 actor boundaries with mutable Kotlin reference classes

Engineers MUST NOT cross Swift 6 actor boundaries with mutable Kotlin reference classes; emitted payload models MUST be immutable, marked `@Sendable` on the Swift wrapper side, or strictly confined to the `@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.
3

Code MUST NEVER invoke `runBlocking` or block a Swift cooperative thread awaiting a Kotlin suspend function or Flow emission.

Code MUST NEVER invoke `runBlocking` or block a Swift cooperative thread awaiting a Kotlin suspend function or Flow emission.

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

Services MUST route UI-bound Flow consumption explicitly through `@MainActor` isolated wrappers, preventing cross-thread mutation of Swift state by Kotlin Darwin workers.

Services MUST route UI-bound Flow consumption explicitly through `@MainActor` isolated wrappers, preventing cross-thread mutation of Swift state by Kotlin Darwin workers.

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 hold strong unmanaged references to Kotlin CoroutineScope instances inside Swift async contexts without structured lifetime binding.

Components NEVER hold strong unmanaged references to Kotlin CoroutineScope instances inside Swift async contexts without structured lifetime 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin 2.1 SharedFlow & Swift 6 AsyncSequence Sendable Isolation Guardrail critical for AI coding assistants?

Enforces thread-safe, data-race-free interoperability between Kotlin Multiplatform 2.1 SharedFlow/StateFlow emissions and Swift 6 Complete Concurrency AsyncSequences. Eliminates cross-runtime thread pool exhaustion and cooperative thread starvation deadlocks caused by unmanaged coroutine collectors. Mandates strict Sendable isolation and deterministic cancellation bridging across the Darwin 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 (Unchecked Cross-Boundary Flow Bridging Causing Swift 6 Isolation Escapes and Cooperative Thread Starvation Deadlocks) 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