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

KMP StateFlow to Swift Actor ARC Bridge & Deadlock Prevention

Enforces strict memory boundary management and reentrancy safety when bridging Kotlin Coroutine StateFlow pipelines into Swift Actors and @MainActor view models. Eliminates bidirectional reference cycles across the Kotlin/Native ARC-GC boundary and prevents threading deadlocks caused by synchronous dispatch blocking on cooperative actor pools.

Prohibited Anti-Pattern: Escaping unmanaged Kotlin Coroutine Job closures into Swift Actor isolation contexts causing ARC retain leaks and dispatch deadlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP StateFlow to Swift Actor ARC Bridge & Deadlock Prevention - Enforces strict memory boundary management and reentrancy safety when bridging Kotlin Coroutine StateFlow pipelines into Swift Actors and @MainActor view models. Eliminates bidirectional reference cycles across the Kotlin/Native ARC-GC boundary and prevents threading deadlocks caused by synchronous dispatch blocking on cooperative actor pools.
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-memory-bridge-guardrail"
---

# KMP StateFlow to Swift Actor ARC Bridge & Deadlock Prevention

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Escaping unmanaged Kotlin Coroutine Job closures into Swift Actor isolation contexts causing ARC retain leaks and dispatch deadlocks

## System Constraints
You are a Principal Mobile Architect enforcing absolute isolation invariants for Kotlin Multiplatform (KMP) to Swift Concurrency bridges. You must strictly forbid capturing strong references to Swift Actors inside Kotlin Coroutine completion handlers, prevent synchronous blocking of Swift cooperative thread pools via Kotlin runBlocking/CFRunLoop dispatch, mandate explicit lifecycle-bound cancellation tokens across the Kotlin/Native GC and Swift ARC barrier, and require AsyncStream adaptors with structured Task cancellation for all StateFlow projections.

## Strict Guidelines
- Engineers MUST ALWAYS bridge Kotlin StateFlow to Swift via an AsyncStream or AsyncThrowingStream that encapsulates collection in a weak-referencing cancellation holder.
- Engineers MUST NOT capture strong self references to a Swift Actor or @MainActor class inside an escaping Kotlin Coroutine Flow collector closure.
- Engineers MUST ALWAYS decouple Kotlin CoroutineScope lifecycles from Swift Actor allocations by binding collection jobs to Swift Task cancellation handlers (withTaskCancellationHandler).
- Engineers MUST NOT invoke Kotlin suspending functions synchronously from a Swift Actor context using dispatch queue waits or runBlocking, as this starves the cooperative thread pool and induces priority inversion deadlocks.
- Bridging wrappers MUST expose explicit detach() or close() primitives invoked in Swift deinit or UI task lifecycles to release underlying Kotlin Native GC roots immediately.

## Bad vs Good Implementations
### Bridging StateFlow into a Swift @MainActor ViewModel

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin Native's exported watch closure retains the captured Swift closure context, which strongly retains self. The ViewModel retains watcherTask. This forms an ARC-to-Kotlin GC circular reference. deinit is never invoked, leaking both the Swift instance and the Kotlin Coroutine Job.
```swift
import Shared
import SwiftUI

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var state: ProfileState = .initial
    private let profileRepository: ProfileRepository
    private var watcherTask: Closeable? = nil

    init(repository: ProfileRepository) {
        self.profileRepository = repository
        // ANTI-PATTERN: Strong capture of self across the K/N ARC boundary.
        // Retains 'self' indefinitely because Kotlin Flow collector holds closure,
        // while ProfileViewModel holds the Closeable watcher, causing a cycle.
        self.watcherTask = repository.profileState.watch { [self] newState in
            self.state = newState
        }
    }

    deinit {
        // Unreachable if retain cycle is active; results in leak and runaway coroutine
        watcherTask?.close()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Transforms the CStateFlow into an AsyncStream with an onTermination hook. The Swift Actor uses weak self inside a structured Task. When the ViewModel is released, deinit cancels the task, terminating the stream and deterministically invoking Kotlin Closeable.close() to release GC roots.
```swift
import Shared
import SwiftUI

extension CStateFlow {
    // Factory method converting CStateFlow into a cooperative Swift AsyncStream
    func asAsyncStream() -> AsyncStream<T> where T: AnyObject {
        AsyncStream { continuation in
            let closeable = self.watch { item in
                continuation.yield(item)
            }
            continuation.onTermination = { @Sendable _ in
                closeable.close()
            }
        }
    }
}

@MainActor
final class ProfileViewModel: ObservableObject {
    @Published private(set) var state: ProfileState = .initial
    private let profileRepository: ProfileRepository
    private var observationTask: Task<Void, Never>? = nil

    init(repository: ProfileRepository) {
        self.profileRepository = repository
        startObserving()
    }

    private func startObserving() {
        // GOOD: Structured Swift Task lifecycle with weak capture semantics
        let stream = profileRepository.profileState.asAsyncStream()
        observationTask = Task { [weak self] in
            for await newState in stream {
                guard let self else { break }
                self.state = newState
            }
        }
    }

    deinit {
        // Deterministic cancellation tears down the Swift AsyncStream and invokes closeable.close()
        observationTask?.cancel()
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP StateFlow to Swift Actor ARC Bridge & Deadlock Prevention

KMP StateFlow to Swift Actor ARC Bridge & Deadlock Prevention defines an industrial-grade behavioral standard for mobile engineering. Enforces strict memory boundary management and reentrancy safety when bridging Kotlin Coroutine StateFlow pipelines into Swift Actors and @MainActor view models. Eliminates bidirectional reference cycles across the Kotlin/Native ARC-GC boundary and prevents threading deadlocks caused by synchronous dispatch blocking on cooperative actor pools. 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: Escaping unmanaged Kotlin Coroutine Job closures into Swift Actor isolation contexts causing ARC retain leaks and dispatch 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 DriftEscaping unmanaged Kotlin Coroutine Job closures into Swift Actor isolation contexts causing ARC retain leaks and dispatch 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 StateFlow to Swift via an AsyncStream or AsyncThrowingStream that encapsulates collection in a weak-referencing cancellation holder.

Engineers MUST ALWAYS bridge Kotlin StateFlow to Swift via an AsyncStream or AsyncThrowingStream that encapsulates collection in a weak-referencing cancellation holder.

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 capture strong self references to a Swift Actor or @MainActor class inside an escaping Kotlin Coroutine Flow collector closure.

Engineers MUST NOT capture strong self references to a Swift Actor or @MainActor class inside an escaping Kotlin Coroutine Flow collector closure.

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 decouple Kotlin CoroutineScope lifecycles from Swift Actor allocations by binding collection jobs to Swift Task cancellation handlers (withTaskCancellationHandler).

Engineers MUST ALWAYS decouple Kotlin CoroutineScope lifecycles from Swift Actor allocations by binding collection jobs to Swift Task cancellation handlers (withTaskCancellationHandler).

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 invoke Kotlin suspending functions synchronously from a Swift Actor context using dispatch queue waits or runBlocking, as this starves the cooperative thread pool and induces priority inversion deadlocks.

Engineers MUST NOT invoke Kotlin suspending functions synchronously from a Swift Actor context using dispatch queue waits or runBlocking, as this starves the cooperative thread pool and induces priority inversion deadlocks.

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

Bridging wrappers MUST expose explicit detach() or close() primitives invoked in Swift deinit or UI task lifecycles to release underlying Kotlin Native GC roots immediately.

Bridging wrappers MUST expose explicit detach() or close() primitives invoked in Swift deinit or UI task lifecycles to release underlying Kotlin Native GC roots immediately.

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 StateFlow to Swift Actor ARC Bridge & Deadlock Prevention critical for AI coding assistants?

Enforces strict memory boundary management and reentrancy safety when bridging Kotlin Coroutine StateFlow pipelines into Swift Actors and @MainActor view models. Eliminates bidirectional reference cycles across the Kotlin/Native ARC-GC boundary and prevents threading deadlocks caused by synchronous dispatch blocking on cooperative actor pools. 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 (Escaping unmanaged Kotlin Coroutine Job closures into Swift Actor isolation contexts causing ARC retain leaks and dispatch 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

KMP