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

Kotlin Multiplatform & Swift 6 Actor Boundary Memory and Deadlock Guardrail

Enforces strict isolation boundaries when bridging Kotlin Native coroutines and Swift 6 actors across the Objective-C/C export interface. Prevents ARC race conditions, double frees, and cooperative thread-pool starvation caused by passing mutable reference graphs across the interop boundary without explicit value semantics or unconfined thread dispatching.

Prohibited Anti-Pattern: Passing Mutable Kotlin Objects to Swift Actors or Bridging Suspend Calls on Main Dispatchers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform & Swift 6 Actor Boundary Memory and Deadlock Guardrail - Enforces strict isolation boundaries when bridging Kotlin Native coroutines and Swift 6 actors across the Objective-C/C export interface. Prevents ARC race conditions, double frees, and cooperative thread-pool starvation caused by passing mutable reference graphs across the interop boundary without explicit value semantics or unconfined thread dispatching.
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-swift-concurrency-actor-boundary-standard"
---

# Kotlin Multiplatform & Swift 6 Actor Boundary Memory and Deadlock Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Passing Mutable Kotlin Objects to Swift Actors or Bridging Suspend Calls on Main Dispatchers

## System Constraints
You are a Principal Mobile Architect enforcing strict memory safety and concurrency invariants across Kotlin Multiplatform and Swift 6 actor boundaries. Kotlin Native objects exposed to Swift via Objective-C headers retain ARC-managed pointers that are NOT natively Sendable under Swift 6 strict concurrency checks. You must mandate immutable data transfer objects, dedicated boundary wrappers with isolated dispatchers, explicit task cancellations, and zero bidirectional retain cycles between Swift actors and Kotlin CoroutineScopes.

## Strict Guidelines
- Engineers MUST NEVER expose mutable Kotlin classes across the interop boundary; all cross-boundary payloads MUST be deeply immutable value objects or Kotlin data classes exported as immutable representations.
- Engineers MUST wrap all Kotlin Native suspend functions using SKIE or explicit Swift async bridges that dispatch onto `Task.detached` or an isolated actor, never blocking the Swift cooperative thread pool (`TaskPriority`) or Kotlin's `Dispatchers.Main` synchronously.
- Engineers MUST mark Swift wrapper types containing Kotlin references as `@unchecked Sendable` ONLY when guaranteed thread-safe via frozen Kotlin state or synchronized access, and document the safety invariant explicitly.
- Engineers MUST use explicit cancellation propagation: Swift `Task` cancellations MUST immediately invoke the corresponding Kotlin `Job.cancel()` to prevent orphan background coroutines holding Swift completions.
- Components NEVER store direct Swift `actor` references inside long-lived Kotlin singletons or listeners; communication from Kotlin back to Swift MUST occur via thread-safe callbacks scheduled explicitly on the target actor or `@MainActor` via `MainActor.run`.

## Bad vs Good Implementations
### Bridging Kotlin Suspend APIs to Swift 6 Actors Without Deadlocks or Memory Races

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly referencing a mutable Kotlin Native object within a Swift actor and bridging coroutine continuations without cancellation wiring or thread isolation risks cooperative thread starvation and Swift 6 ARC data races.
```swift
// BAD: Direct invocation of Kotlin suspend wrapper inside Swift actor.
// Passing mutable state back and forth leads to ARC race conditions and
// potentially starves Swift's cooperative thread pool if Kotlin blocks on Dispatchers.Main.
actor UserSessionActor {
    private let repository: UserRepositoryKt // Kotlin mutable reference directly retained

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

    func updateProfile(name: String) async throws -> UserProfileModel {
        // Blocking or unconfined continuation directly bridging Objective-C async block
        // UserProfileModel is a mutable reference type across the boundary: ARC violation in Swift 6
        return try await withCheckedThrowingContinuation { continuation in
            repository.fetchProfile(name: name) { result, error in
                if let error = error {
                    continuation.resume(throwing: error)
                } else {
                    continuation.resume(returning: result!)
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Decouples Swift actor isolation from Kotlin Native ARC state by using detached tasks, explicit Swift-to-Kotlin cancellation handles, and immediate projection into Sendable Swift value types.
```swift
// GOOD: Immutable boundary mapping, cancellation bridging, and safe Sendable handling.
struct UserProfileDTO: Sendable {
    let id: String
    let name: String
}

actor UserSessionActor {
    // Isolated client wrapper ensuring Kotlin interop occurs away from cooperative pool limits
    private let client: KotlinBridgeClient

    init(client: KotlinBridgeClient) {
        self.client = client
    }

    func fetchProfile(id: String) async throws -> UserProfileDTO {
        // Propagate cancellation across boundaries and isolate foreign ARC lifetime
        return try await withTaskCancellationHandler {
            try await Task.detached(priority: .userInitiated) {
                let rawProfile = try await self.client.fetchProfile(id: id)
                // Map immediately from Kotlin ARC pointer to Swift Sendable value type
                return UserProfileDTO(id: rawProfile.id, name: rawProfile.name)
            }.value
        } onCancel: {
            // Cancel active Kotlin job explicitly to avoid zombie memory retain cycles
            Task { [client] in
                await client.cancelActiveJob(for: id)
            }
        }
    }
}
```

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 & Swift 6 Actor Boundary Memory and Deadlock Guardrail

Kotlin Multiplatform & Swift 6 Actor Boundary Memory and Deadlock Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation boundaries when bridging Kotlin Native coroutines and Swift 6 actors across the Objective-C/C export interface. Prevents ARC race conditions, double frees, and cooperative thread-pool starvation caused by passing mutable reference graphs across the interop boundary without explicit value semantics or unconfined thread dispatching. 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: Passing Mutable Kotlin Objects to Swift Actors or Bridging Suspend Calls on Main Dispatchers 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 DriftPassing Mutable Kotlin Objects to Swift Actors or Bridging Suspend Calls on Main DispatchersCritical
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 NEVER expose mutable Kotlin classes across the interop boundary

Engineers MUST NEVER expose mutable Kotlin classes across the interop boundary; all cross-boundary payloads MUST be deeply immutable value objects or Kotlin data classes exported as immutable representations.

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 wrap all Kotlin Native suspend functions using SKIE or explicit Swift async bridges that dispatch onto `Task.detached` or an isolated actor, never blocking the Swift cooperative thread pool (`TaskPriority`) or Kotlin's `Dispatchers.Main` synchronously.

Engineers MUST wrap all Kotlin Native suspend functions using SKIE or explicit Swift async bridges that dispatch onto `Task.detached` or an isolated actor, never blocking the Swift cooperative thread pool (`TaskPriority`) or Kotlin's `Dispatchers.Main` synchronously.

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 mark Swift wrapper types containing Kotlin references as `@unchecked Sendable` ONLY when guaranteed thread-safe via frozen Kotlin state or synchronized access, and document the safety invariant explicitly.

Engineers MUST mark Swift wrapper types containing Kotlin references as `@unchecked Sendable` ONLY when guaranteed thread-safe via frozen Kotlin state or synchronized access, and document the safety invariant explicitly.

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 use explicit cancellation propagation

Engineers MUST use explicit cancellation propagation: Swift `Task` cancellations MUST immediately invoke the corresponding Kotlin `Job.cancel()` to prevent orphan background coroutines holding Swift completions.

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 store direct Swift `actor` references inside long-lived Kotlin singletons or listeners

Components NEVER store direct Swift `actor` references inside long-lived Kotlin singletons or listeners; communication from Kotlin back to Swift MUST occur via thread-safe callbacks scheduled explicitly on the target actor or `@MainActor` via `MainActor.run`.

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 & Swift 6 Actor Boundary Memory and Deadlock Guardrail critical for AI coding assistants?

Enforces strict isolation boundaries when bridging Kotlin Native coroutines and Swift 6 actors across the Objective-C/C export interface. Prevents ARC race conditions, double frees, and cooperative thread-pool starvation caused by passing mutable reference graphs across the interop boundary without explicit value semantics or unconfined thread dispatching. 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 (Passing Mutable Kotlin Objects to Swift Actors or Bridging Suspend Calls on Main Dispatchers) 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