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

KMP to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail

Enforces strict weak-proxy patterns and explicit teardown protocols across the Kotlin/Native and Swift ARC boundary. Prevents zombie memory retention and background jetsam termination (EXC_RESOURCE CPUMONITOR / 0x8badf00d) caused by cross-runtime circular references bridging tracing GC and reference counting.

Prohibited Anti-Pattern: Direct Strong Bi-Directional Bridging Across Kotlin/Native and Swift Reference Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail - Enforces strict weak-proxy patterns and explicit teardown protocols across the Kotlin/Native and Swift ARC boundary. Prevents zombie memory retention and background jetsam termination (EXC_RESOURCE CPUMONITOR / 0x8badf00d) caused by cross-runtime circular references bridging tracing GC and reference counting.
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-arc-cycle-detection-guardrail"
---

# KMP to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Strong Bi-Directional Bridging Across Kotlin/Native and Swift Reference Boundaries

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and iOS native runtimes. You must prevent memory leaks, retain cycles, and background suspension kills across the Kotlin/Native and Swift ObjC bridge by mandating weak-proxy wrappers, explicit lifecycle disconnections, and ARC-safe listener interfaces.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Swift-conforming protocol implementations in a weak proxy (`WeakProxy<T>`) before passing callbacks or observers into Kotlin/Native objects.
- Engineers MUST NOT store strong references to Swift delegate implementations inside long-lived Kotlin/Native classes, ViewModels, or singletons; use `kotlin.native.ref.WeakReference` on iOS target sources.
- Swift ViewControllers and SwiftUI ViewModels MUST call an explicit `detach()` or `dispose()` method on bridged Kotlin presenters/coroutines during `viewDidDisappear` or `onDisappear`.
- Bridged callbacks escaping Kotlin Coroutine `Job` scopes MUST be canceled explicitly upon iOS background transition (`UIApplication.didEnterBackgroundNotification`).
- Components NEVER bridge raw closures capturing `self` directly into Kotlin lambda arguments that outlive the synchronous execution frame.

## Bad vs Good Implementations
### Bridged Delegate Cycle between Swift UI Controller and Kotlin Coroutine Presenter

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing 'self' directly as a delegate to the Kotlin ProfilePresenter creates an invisible cross-runtime cycle: Swift ARC retains ProfilePresenter (via lazy var), while Kotlin/Native retains ProfileUiListener (UserProfileViewController) as an Obj-C reference. Tracing GC on Kotlin and ARC on iOS cannot break cross-runtime cycles, causing silent memory leaks and jetsam termination during iOS suspension.
```swift
import UIKit
import SharedKit

final class UserProfileViewController: UIViewController, ProfileUiListener {
    // ANTI-PATTERN: Kotlin presenter retains strong reference to Swift UIViewController.
    // Swift holds strong reference to Kotlin presenter.
    // Neither GC nor ARC can reclaim this cycle during background suspension.
    private lazy var presenter: ProfilePresenter = ProfilePresenter(listener: self)

    override func viewDidLoad() {
        super.viewDidLoad()
        presenter.loadUserProfile()
    }

    func onProfileLoaded(profile: UserProfile) {
        // UI update logic
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using a dedicated WeakProfileUiListener ensures the Kotlin object only retains a proxy holding a weak ARC reference to the UIViewController. When the view controller is dismissed, the ARC reference count reaches zero immediately. Explicit 'detach()' terminates active coroutine scopes and releases references before background suspension.
```swift
import UIKit
import SharedKit

// 1. Weak proxy decouples the native ARC instance from Kotlin/Native runtime
final class WeakProfileUiListener: ProfileUiListener {
    private weak var target: ProfileUiListener?

    init(target: ProfileUiListener) {
        self.target = target
    }

    func onProfileLoaded(profile: UserProfile) {
        target?.onProfileLoaded(profile: profile)
    }
}

final class UserProfileViewController: UIViewController, ProfileUiListener {
    private var presenter: ProfilePresenter?
    private var proxy: WeakProfileUiListener?

    override func viewDidLoad() {
        super.viewDidLoad()
        let proxy = WeakProfileUiListener(target: self)
        self.proxy = proxy
        self.presenter = ProfilePresenter(listener: proxy)
        presenter?.loadUserProfile()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if isMovingFromParent || isBeingDismissed {
            // 2. Explicit lifecycle teardown breaks Kotlin Coroutine scopes
            presenter?.detach()
            presenter = nil
        }
    }

    func onProfileLoaded(profile: UserProfile) {
        // UI update logic
    }
}
```

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 to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail

KMP to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict weak-proxy patterns and explicit teardown protocols across the Kotlin/Native and Swift ARC boundary. Prevents zombie memory retention and background jetsam termination (EXC_RESOURCE CPUMONITOR / 0x8badf00d) caused by cross-runtime circular references bridging tracing GC and reference counting. 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 Strong Bi-Directional Bridging Across Kotlin/Native and Swift Reference 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 Strong Bi-Directional Bridging Across Kotlin/Native and Swift Reference 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-conforming protocol implementations in a weak proxy (`WeakProxy<T>`) before passing callbacks or observers into Kotlin/Native objects.

Engineers MUST ALWAYS wrap Swift-conforming protocol implementations in a weak proxy (`WeakProxy<T>`) before passing callbacks or observers into Kotlin/Native objects.

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 store strong references to Swift delegate implementations inside long-lived Kotlin/Native classes, ViewModels, or singletons

Engineers MUST NOT store strong references to Swift delegate implementations inside long-lived Kotlin/Native classes, ViewModels, or singletons; use `kotlin.native.ref.WeakReference` on iOS target sources.

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

Swift ViewControllers and SwiftUI ViewModels MUST call an explicit `detach()` or `dispose()` method on bridged Kotlin presenters/coroutines during `viewDidDisappear` or `onDisappear`.

Swift ViewControllers and SwiftUI ViewModels MUST call an explicit `detach()` or `dispose()` method on bridged Kotlin presenters/coroutines during `viewDidDisappear` or `onDisappear`.

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

Bridged callbacks escaping Kotlin Coroutine `Job` scopes MUST be canceled explicitly upon iOS background transition (`UIApplication.didEnterBackgroundNotification`).

Bridged callbacks escaping Kotlin Coroutine `Job` scopes MUST be canceled explicitly upon iOS background transition (`UIApplication.didEnterBackgroundNotification`).

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 bridge raw closures capturing `self` directly into Kotlin lambda arguments that outlive the synchronous execution frame.

Components NEVER bridge raw closures capturing `self` directly into Kotlin lambda arguments that outlive the synchronous execution frame.

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 to Swift-ObjC ARC Retain Cycle & Background Suspension Guardrail critical for AI coding assistants?

Enforces strict weak-proxy patterns and explicit teardown protocols across the Kotlin/Native and Swift ARC boundary. Prevents zombie memory retention and background jetsam termination (EXC_RESOURCE CPUMONITOR / 0x8badf00d) caused by cross-runtime circular references bridging tracing GC and reference counting. 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 Strong Bi-Directional Bridging Across Kotlin/Native and Swift Reference 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