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

Kotlin/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement

Enforces deterministic native memory boundaries and Objective-C autorelease pool wrapping across Kotlin/Native background processing on iOS. Prevents process termination by iOS Jetsam (OOM) caused by deferred Kotlin/Native garbage collector transitions and accumulated Objective-C bridged allocations during high-throughput loops.

Prohibited Anti-Pattern: Unbounded Interop Allocations and Missing Autorelease Pools in KMP Background Coroutines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement - Enforces deterministic native memory boundaries and Objective-C autorelease pool wrapping across Kotlin/Native background processing on iOS. Prevents process termination by iOS Jetsam (OOM) caused by deferred Kotlin/Native garbage collector transitions and accumulated Objective-C bridged allocations during high-throughput loops.
globs: **/iosMain/**/*.kt, **/appleMain/**/*.kt, **/nativeMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-memory-deallocation-boundary-standard"
---

# Kotlin/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Interop Allocations and Missing Autorelease Pools in KMP Background Coroutines

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Darwin native internals. You must enforce strict native memory boundaries, explicit autorelease pool scoping, and deterministic CPointer lifecycle barriers on all Kotlin/Native code targeting iOS. Reject any implementation where high-throughput background tasks generate platform objects or interop pointers without explicit drainage barriers.

## Strict Guidelines
- Engineers MUST ALWAYS wrap intensive interop calls (Objective-C/Cocoa Touch/CoreGraphics) within `autoreleasepool { ... }` blocks when running inside loops or long-lived coroutines on iOS.
- Engineers MUST ALWAYS confine native heap structures and C pointers (`CPointer`, `CValuesRef`) to `memScoped { ... }` blocks, ensuring automatic reclamation upon block exit.
- Engineers MUST NOT rely on the Kotlin/Native concurrent garbage collector to opportunistically drain Darwin autorelease pools or release heavy foreign bridge objects.
- Code executing iterative batch workloads across thread hops SHOULD chunk executions and invoke `yield()` or explicit memory reclamation triggers to avoid spiking high-water memory marks.
- Services MUST explicitly call `.free()` on manual `nativeHeap.alloc` calls within `try/finally` blocks if `memScoped` lifetime does not fit the asynchronous lifecycle.
- Components NEVER bridge raw Objective-C bitmaps, byte buffers, or Foundation types into unbound state variables without defining an explicit invalidation and release path.

## Bad vs Good Implementations
### Batch Image Buffer Processing on iOS

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Each iteration constructs an Objective-C NSData bridged instance. In a Kotlin coroutine worker thread without an explicit autorelease pool, these autoreleased references remain retained until the thread context resets, driving heap usage beyond the iOS foreground/background memory limit.
```kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import platform.Foundation.NSData
import platform.Foundation.dataWithBytes
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned

suspend fun processImageBatches(rawFrames: List<ByteArray>): List<NSData> = withContext(Dispatchers.Default) {
    // ANTI-PATTERN: Native NSData allocations accumulate in the thread-local autorelease pool.
    // In high-frequency background coroutines, the pool is never drained, causing iOS Jetsam OOM crashes.
    rawFrames.map { frame ->
        frame.usePinned { pinned ->
            NSData.dataWithBytes(pinned.addressOf(0), frame.size.toULong())
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: By bounding chunk processing within both `autoreleasepool` and `memScoped`, native memory allocations and bridged Foundation instances are deterministically released at the boundary of every chunk, preventing heap accumulation and eliminating Jetsam terminations.
```kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import kotlinx.cinterop.autoreleasepool
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.allocArrayOf
import platform.Foundation.NSData
import platform.Foundation.dataWithBytes

suspend fun processImageBatches(rawFrames: List<ByteArray>): List<NSData> = withContext(Dispatchers.Default) {
    val results = mutableListOf<NSData>()
    val batchThreshold = 50

    rawFrames.chunked(batchThreshold).forEach { chunk ->
        // PRODUCTION INVARIANT: Encapsulate chunk within explicit autoreleasepool
        // to force immediate native deallocation of bridged Obj-C objects.
        autoreleasepool {
            memScoped {
                for (frame in chunk) {
                    val nativeBuffer = allocArrayOf(frame)
                    val nsData = NSData.dataWithBytes(nativeBuffer, frame.size.toULong())
                    results.add(nsData)
                }
            }
        }
        // Yield control to allow native thread scheduler and GC cooperatively sweep
        yield()
    }
    results
}
```

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/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement

Kotlin/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic native memory boundaries and Objective-C autorelease pool wrapping across Kotlin/Native background processing on iOS. Prevents process termination by iOS Jetsam (OOM) caused by deferred Kotlin/Native garbage collector transitions and accumulated Objective-C bridged allocations during high-throughput loops. 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 Interop Allocations and Missing Autorelease Pools in KMP Background Coroutines 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 Interop Allocations and Missing Autorelease Pools in KMP Background CoroutinesCritical
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 intensive interop calls (Objective-C/Cocoa Touch/CoreGraphics) within `autoreleasepool { ... }` blocks when running inside loops or long-lived coroutines on iOS.

Engineers MUST ALWAYS wrap intensive interop calls (Objective-C/Cocoa Touch/CoreGraphics) within `autoreleasepool { ... }` blocks when running inside loops or long-lived coroutines on iOS.

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 ALWAYS confine native heap structures and C pointers (`CPointer`, `CValuesRef`) to `memScoped { ... }` blocks, ensuring automatic reclamation upon block exit.

Engineers MUST ALWAYS confine native heap structures and C pointers (`CPointer`, `CValuesRef`) to `memScoped { ... }` blocks, ensuring automatic reclamation upon block exit.

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 NOT rely on the Kotlin/Native concurrent garbage collector to opportunistically drain Darwin autorelease pools or release heavy foreign bridge objects.

Engineers MUST NOT rely on the Kotlin/Native concurrent garbage collector to opportunistically drain Darwin autorelease pools or release heavy foreign bridge 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.
4

Code executing iterative batch workloads across thread hops SHOULD chunk executions and invoke `yield()` or explicit memory reclamation triggers to avoid spiking high-water memory marks.

Code executing iterative batch workloads across thread hops SHOULD chunk executions and invoke `yield()` or explicit memory reclamation triggers to avoid spiking high-water memory marks.

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

Services MUST explicitly call `.free()` on manual `nativeHeap.alloc` calls within `try/finally` blocks if `memScoped` lifetime does not fit the asynchronous lifecycle.

Services MUST explicitly call `.free()` on manual `nativeHeap.alloc` calls within `try/finally` blocks if `memScoped` lifetime does not fit the asynchronous lifecycle.

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.
6

Components NEVER bridge raw Objective-C bitmaps, byte buffers, or Foundation types into unbound state variables without defining an explicit invalidation and release path.

Components NEVER bridge raw Objective-C bitmaps, byte buffers, or Foundation types into unbound state variables without defining an explicit invalidation and release path.

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/Native Explicit Memory Reclamation and Autorelease Boundary Enforcement critical for AI coding assistants?

Enforces deterministic native memory boundaries and Objective-C autorelease pool wrapping across Kotlin/Native background processing on iOS. Prevents process termination by iOS Jetsam (OOM) caused by deferred Kotlin/Native garbage collector transitions and accumulated Objective-C bridged allocations during high-throughput loops. 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 Interop Allocations and Missing Autorelease Pools in KMP Background Coroutines) 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/Native