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

Kotlin Multiplatform Swift Interop Concurrent Mutation and ABI Memory Safety

Prevents SIGSEGV native memory corruption, race conditions, and reference counting deadlocks across the Kotlin/Native and Swift Objective-C ABI boundary under aggressive background concurrency. Mandates strict value-type bridging or thread-confined isolation using Swift actors and Kotlin StateFlow to avoid concurrent mutation of shared ObjC-bridged heap pointers. Enforces thread-safe lifecycle containment to prevent deallocation races during asynchronous dispatch.

Prohibited Anti-Pattern: Directly Mutating Kotlin/Native Shared Mutable Objects Across Concurrent Swift GCD Queues or Async Tasks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Swift Interop Concurrent Mutation and ABI Memory Safety - Prevents SIGSEGV native memory corruption, race conditions, and reference counting deadlocks across the Kotlin/Native and Swift Objective-C ABI boundary under aggressive background concurrency. Mandates strict value-type bridging or thread-confined isolation using Swift actors and Kotlin StateFlow to avoid concurrent mutation of shared ObjC-bridged heap pointers. Enforces thread-safe lifecycle containment to prevent deallocation races during asynchronous dispatch.
globs: iosApp/**/*.swift, shared/**/*.kt, **/*Bridge*.swift, **/*Repository*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-swift-interop-concurrent-mutation-guardrail"
---

# Kotlin Multiplatform Swift Interop Concurrent Mutation and ABI Memory Safety

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Directly Mutating Kotlin/Native Shared Mutable Objects Across Concurrent Swift GCD Queues or Async Tasks

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety and thread containment at the Kotlin Multiplatform (K/N) to Swift ABI interop boundary. Kotlin Native objects exposed via the Objective-C runtime bridge are subject to dual garbage collection (Kotlin GC) and Automatic Reference Counting (ARC). You must strictly mandate that mutable K/N heap instances are never concurrently mutated across Swift async/await tasks or GCD queues. You must enforce immutable DTO transfers, Swift Actor isolation, and structured coroutine-to-AsyncSequence adapters.

## Strict Guidelines
- Engineers MUST ALWAYS isolate K/N bridged instances within a dedicated Swift `actor` or `@MainActor` context when instances contain internal state.
- Engineers MUST NEVER expose Kotlin mutable collections (e.g., `KtMutableList`, `KtMutableMap`) directly to Swift callers across thread boundaries.
- Engineers MUST project Kotlin reactive state via read-only `StateFlow` or `SharedFlow` transformed into immutable primitives or Swift value types (`struct`).
- Swift background tasks MUST NOT retain or mutate a Kotlin reference across detached `Task.detached` or unconstrained `DispatchQueue.global()` executions without thread confinement.
- Kotlin export models SHOULD implement `@ObjCName` and provide thread-safe factory methods or copy-on-write semantics for complex nested structures.

## Bad vs Good Implementations
### Concurrent Mutation across Swift Concurrency Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly invoking Kotlin Native instance methods from arbitrary Swift background GCD threads leads to concurrent mutation of non-synchronized native memory pointers. Although Kotlin 1.9+ features a new memory manager with shared heap, simultaneous read/write operations without synchronized wrappers cause Swift ARC retain/release races and memory corruption in the Objective-C bridging runtime.
```swift
import Shared

// ANTI-PATTERN: Directly sharing and mutating a Kotlin stateful class across GCD queues
class AccountSyncManager {
    let accountStore: SharedAccountStore // Kotlin/Native bridged class with internal mutable state

    init(accountStore: SharedAccountStore) {
        self.accountStore = accountStore
    }

    func synchronizeAll(accounts: [String]) {
        for accountId in accounts {
            DispatchQueue.global(qos: .userInitiated).async {
                // Concurrent invocation into Kotlin/Native runtime
                // Causes ARC race condition, native ref-count tearing, or memory corruption
                self.accountStore.updateSession(accountId: accountId, timestamp: Int64(Date().timeIntervalSince1970))
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: By encapsulating the Kotlin `SharedAccountStore` inside a Swift `actor`, all cross-thread dispatch is serialized under the actor's isolation domain. Furthermore, mutating operations are exposed as async suspend functions and converted immediately into a Swift `Sendable` value-type `struct`, preventing Kotlin heap pointer leaks across arbitrary thread boundaries.
```swift
import Shared

// PRODUCTION FIX: Confining Kotlin access to a Swift Actor and passing immutable value DTOs
actor AccountSyncManager {
    private let accountStore: SharedAccountStore

    init(accountStore: SharedAccountStore) {
        self.accountStore = accountStore
    }

    // All mutations are serial and isolated to the actor's execution context
    func synchronize(accountId: String, timestamp: Int64) async throws -> AccountSessionSnapshot {
        // Kotlin method invoked safely under actor isolation
        let kmpSnapshot = try await accountStore.updateSessionAsync(accountId: accountId, timestamp: timestamp)
        
        // Project into a pure Swift immutable struct before crossing concurrency boundaries
        return AccountSessionSnapshot(
            id: kmpSnapshot.id,
            lastUpdated: kmpSnapshot.timestamp,
            isActive: kmpSnapshot.isActive
        )
    }
}

struct AccountSessionSnapshot: Sendable {
    let id: String
    let lastUpdated: Int64
    let isActive: Bool
}
```

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 Interop Concurrent Mutation and ABI Memory Safety

Kotlin Multiplatform Swift Interop Concurrent Mutation and ABI Memory Safety defines an industrial-grade behavioral standard for mobile engineering. Prevents SIGSEGV native memory corruption, race conditions, and reference counting deadlocks across the Kotlin/Native and Swift Objective-C ABI boundary under aggressive background concurrency. Mandates strict value-type bridging or thread-confined isolation using Swift actors and Kotlin StateFlow to avoid concurrent mutation of shared ObjC-bridged heap pointers. Enforces thread-safe lifecycle containment to prevent deallocation races during asynchronous dispatch. 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: Directly Mutating Kotlin/Native Shared Mutable Objects Across Concurrent Swift GCD Queues or Async Tasks 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 DriftDirectly Mutating Kotlin/Native Shared Mutable Objects Across Concurrent Swift GCD Queues or Async TasksCritical
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 isolate K/N bridged instances within a dedicated Swift `actor` or `@MainActor` context when instances contain internal state.

Engineers MUST ALWAYS isolate K/N bridged instances within a dedicated Swift `actor` or `@MainActor` context when instances contain internal state.

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 NEVER expose Kotlin mutable collections (e.g., `KtMutableList`, `KtMutableMap`) directly to Swift callers across thread boundaries.

Engineers MUST NEVER expose Kotlin mutable collections (e.g., `KtMutableList`, `KtMutableMap`) directly to Swift callers across thread boundaries.

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 project Kotlin reactive state via read-only `StateFlow` or `SharedFlow` transformed into immutable primitives or Swift value types (`struct`).

Engineers MUST project Kotlin reactive state via read-only `StateFlow` or `SharedFlow` transformed into immutable primitives or Swift value types (`struct`).

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 background tasks MUST NOT retain or mutate a Kotlin reference across detached `Task.detached` or unconstrained `DispatchQueue.global()` executions without thread confinement.

Swift background tasks MUST NOT retain or mutate a Kotlin reference across detached `Task.detached` or unconstrained `DispatchQueue.global()` executions without thread confinement.

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

Kotlin export models SHOULD implement `@ObjCName` and provide thread-safe factory methods or copy-on-write semantics for complex nested structures.

Kotlin export models SHOULD implement `@ObjCName` and provide thread-safe factory methods or copy-on-write semantics for complex nested structures.

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 Interop Concurrent Mutation and ABI Memory Safety critical for AI coding assistants?

Prevents SIGSEGV native memory corruption, race conditions, and reference counting deadlocks across the Kotlin/Native and Swift Objective-C ABI boundary under aggressive background concurrency. Mandates strict value-type bridging or thread-confined isolation using Swift actors and Kotlin StateFlow to avoid concurrent mutation of shared ObjC-bridged heap pointers. Enforces thread-safe lifecycle containment to prevent deallocation races during asynchronous dispatch. 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 (Directly Mutating Kotlin/Native Shared Mutable Objects Across Concurrent Swift GCD Queues or Async Tasks) 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