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

KMP Native Objective-C Interop ARC Autoreleasepool Boundary Standard

High-frequency bridge traversals between Kotlin Native and Swift/Objective-C allocate intermediate bridged objects within the active thread's top-level autorelease pool. Without explicit pool boundaries during streaming payload ingestion or tight iteration loops, unbounded retention of transient Objective-C objects occurs, triggering memory pressure crashes and rapid OOM termination on iOS targets.

Prohibited Anti-Pattern: Unbounded Transient Allocation Accumulation in Thread-Level Autorelease Pools During High-Frequency KMP Bridge Crossings

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Native Objective-C Interop ARC Autoreleasepool Boundary Standard - High-frequency bridge traversals between Kotlin Native and Swift/Objective-C allocate intermediate bridged objects within the active thread's top-level autorelease pool. Without explicit pool boundaries during streaming payload ingestion or tight iteration loops, unbounded retention of transient Objective-C objects occurs, triggering memory pressure crashes and rapid OOM termination on iOS targets.
globs: **/*iosMain*/**/*.kt, **/*appleMain*/**/*.kt, **/*nativeMain*/**/*.kt, **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-objc-autoreleasepool-boundary-standard"
---

# KMP Native Objective-C Interop ARC Autoreleasepool Boundary Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Transient Allocation Accumulation in Thread-Level Autorelease Pools During High-Frequency KMP Bridge Crossings

## System Constraints
You are a Principal Mobile Architect enforcing ARC autorelease boundaries across Kotlin Multiplatform Native and Apple Objective-C/Swift interop layers. High-throughput event streams, binary chunk ingestion, and tight bridge iterations must enforce scoped autoreleasepool blocks at both boundary interfaces to ensure deterministic deallocation and avoid catastrophic OOM terminations.

## Strict Guidelines
- Engineers MUST ALWAYS wrap iterative or streaming Kotlin-to-Objective-C bridged calls in `autoreleasepool { ... }` blocks when processing high-frequency data chunks or collections on Apple targets.
- Engineers MUST NOT cross the KMP interop boundary inside tight unbuffered loops (e.g., iterating raw packet buffers or WebSocket frames) without explicit batching or pool draining boundaries.
- Code SHOULD enforce chunked batch draining (e.g., flushing pools every N elements) when processing continuous streaming payloads to minimize the allocation overhead of creating autorelease pools.
- Services MUST ensure that background coroutines dispatching to native Apple frameworks (`NSData`, `NSString`, custom Objective-C protocols) release bridged references before thread-pool workers suspend or yield.
- Components NEVER expose long-lived Swift or Objective-C delegates to Kotlin callbacks without verifying that transient bridged parameters are deallocated immediately post-invocation.

## Bad vs Good Implementations
### Streaming Payload Ingestion Across KMP Apple Native Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Each iteration instantiates a bridged NSData instance that gets registered in the surrounding dispatch queue thread's autoreleasepool. During a multi-megabyte stream, thousands of NSData references survive until the coroutine terminates, precipitating an iOS Jetsam memory kill.
```kotlin
import kotlinx.cinterop.*
import platform.Foundation.NSData
import platform.Foundation.create

fun ingestPayloadStream(chunks: Sequence<ByteArray>, sink: (NSData) -> Unit) {
    chunks.forEach { rawBytes ->
        // Anti-pattern: Interop allocations accumulate in the thread-level autoreleasepool
        // until the run-loop or thread terminates, causing catastrophic OOM on large streams.
        val pinned = rawBytes.pin()
        val data = NSData.create(bytes = pinned.addressOf(0), length = rawBytes.size.toULong())
        pinned.unpin()
        sink(data)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping each bridged payload transformation inside platform.darwin.autoreleasepool guarantees that transient ARC allocations (NSData and associated bridge stubs) are flushed immediately upon exiting the block, stabilizing memory residency at constant levels.
```kotlin
import kotlinx.cinterop.*
import platform.Foundation.NSData
import platform.Foundation.create
import platform.darwin.autoreleasepool

fun ingestPayloadStream(chunks: Sequence<ByteArray>, sink: (NSData) -> Unit) {
    chunks.forEach { rawBytes ->
        // Invariant: Wrap bridge boundary in autoreleasepool to reclaim ARC-managed NSData immediately
        autoreleasepool {
            val pinned = rawBytes.pin()
            try {
                val data = NSData.create(bytes = pinned.addressOf(0), length = rawBytes.size.toULong())
                sink(data)
            } finally {
                pinned.unpin()
            }
        }
    }
}
```

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 Native Objective-C Interop ARC Autoreleasepool Boundary Standard

KMP Native Objective-C Interop ARC Autoreleasepool Boundary Standard defines an industrial-grade behavioral standard for mobile engineering. High-frequency bridge traversals between Kotlin Native and Swift/Objective-C allocate intermediate bridged objects within the active thread's top-level autorelease pool. Without explicit pool boundaries during streaming payload ingestion or tight iteration loops, unbounded retention of transient Objective-C objects occurs, triggering memory pressure crashes and rapid OOM termination on iOS targets. 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: Unbounded Transient Allocation Accumulation in Thread-Level Autorelease Pools During High-Frequency KMP Bridge Crossings 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 DriftUnbounded Transient Allocation Accumulation in Thread-Level Autorelease Pools During High-Frequency KMP Bridge CrossingsCritical
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 iterative or streaming Kotlin-to-Objective-C bridged calls in `autoreleasepool { ... }` blocks when processing high-frequency data chunks or collections on Apple targets.

Engineers MUST ALWAYS wrap iterative or streaming Kotlin-to-Objective-C bridged calls in `autoreleasepool { ... }` blocks when processing high-frequency data chunks or collections on Apple targets.

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 the KMP interop boundary inside tight unbuffered loops (e.g., iterating raw packet buffers or WebSocket frames) without explicit batching or pool draining boundaries.

Engineers MUST NOT cross the KMP interop boundary inside tight unbuffered loops (e.g., iterating raw packet buffers or WebSocket frames) without explicit batching or pool draining 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

Code SHOULD enforce chunked batch draining (e.g., flushing pools every N elements) when processing continuous streaming payloads to minimize the allocation overhead of creating autorelease pools.

Code SHOULD enforce chunked batch draining (e.g., flushing pools every N elements) when processing continuous streaming payloads to minimize the allocation overhead of creating autorelease pools.

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 ensure that background coroutines dispatching to native Apple frameworks (`NSData`, `NSString`, custom Objective-C protocols) release bridged references before thread-pool workers suspend or yield.

Services MUST ensure that background coroutines dispatching to native Apple frameworks (`NSData`, `NSString`, custom Objective-C protocols) release bridged references before thread-pool workers suspend or yield.

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 expose long-lived Swift or Objective-C delegates to Kotlin callbacks without verifying that transient bridged parameters are deallocated immediately post-invocation.

Components NEVER expose long-lived Swift or Objective-C delegates to Kotlin callbacks without verifying that transient bridged parameters are deallocated immediately post-invocation.

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 Native Objective-C Interop ARC Autoreleasepool Boundary Standard critical for AI coding assistants?

High-frequency bridge traversals between Kotlin Native and Swift/Objective-C allocate intermediate bridged objects within the active thread's top-level autorelease pool. Without explicit pool boundaries during streaming payload ingestion or tight iteration loops, unbounded retention of transient Objective-C objects occurs, triggering memory pressure crashes and rapid OOM termination on iOS targets. 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 (Unbounded Transient Allocation Accumulation in Thread-Level Autorelease Pools During High-Frequency KMP Bridge Crossings) 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