This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-native-mimalloc-arena-segregation

Kotlin Multiplatform Native Mimalloc Arena Segregation Guardrail

Enforces strict heap allocator arena segregation between Kotlin/Native background worker threads and Darwin Apple platform runtimes (CoreData, SQLite, GCD) during high-throughput parallel database synchronization. Disallows cross-allocator pointer sharing, unmanaged heap transfers without explicit arena release, and concurrent foreign memory references that induce lock inversion or mimalloc page corruption on iOS.

Prohibited Anti-Pattern: Cross-Boundary Raw Pointer Escaping and Shared Allocator Deadlocks Across Darwin GCD and K/Native Mimalloc Runtimes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Native Mimalloc Arena Segregation Guardrail - Enforces strict heap allocator arena segregation between Kotlin/Native background worker threads and Darwin Apple platform runtimes (CoreData, SQLite, GCD) during high-throughput parallel database synchronization. Disallows cross-allocator pointer sharing, unmanaged heap transfers without explicit arena release, and concurrent foreign memory references that induce lock inversion or mimalloc page corruption on iOS.
globs: shared/src/iosMain/**/*.kt, shared/src/nativeMain/**/*.kt, shared/src/appleMain/**/*.kt, iosApp/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-mimalloc-arena-segregation"
---

# Kotlin Multiplatform Native Mimalloc Arena Segregation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Boundary Raw Pointer Escaping and Shared Allocator Deadlocks Across Darwin GCD and K/Native Mimalloc Runtimes

## System Constraints
You are a Principal Mobile Systems Architect enforcing absolute allocator boundary integrity between Kotlin/Native's internal memory manager (mimalloc) and Apple Darwin system runtimes (libsystem_malloc, GCD pools, OSAutoreleasePool). You must ensure that parallel database synchronizations and bridge cross-calls never pass raw C-pointers, heap-pinned references, or native arena allocations without explicit ownership handoff and isolated lifecycles. Prevent thread-cache lock contention, double-free faults, and allocator deadlock scenarios across K/Native worker boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS isolate native heap allocations to their respective runtime arenas by wrapping K/Native low-level memory interactions within an explicit `memScoped` or `Arena` block that releases before crossing thread or interop boundaries.
- Engineers MUST NOT leak `NativePlacement.alloc` or `nativeHeap.alloc` references directly into Darwin GCD queues or Darwin-allocated callbacks, as Darwin deallocation routines invoke `free()` from `libsystem_malloc`, corrupting mimalloc arena metadata.
- Engineers MUST serialize high-frequency database synchronization payloads into self-contained immutable byte buffers (`ByteArray` or decoupled value types) instead of passing raw `COpaquePointer` or `CPointer<ByteVar>` across interop dispatch queues.
- Services MUST ensure that Darwin-originated callbacks invoke Kotlin bridge operations exclusively within an explicit `autoreleasepool` while decoupling Native allocations onto dedicated Kotlin worker dispatchers using `withContext(Dispatchers.Default.limitedParallelism(N))`.
- Components NEVER store long-lived C pointers across suspend function boundaries without defensive pinning (`StableRef`) and deterministic scoped cleanup (`StableRef.dispose()`) executed strictly on the originating allocation thread arena.

## Bad vs Good Implementations
### Preventing Mimalloc / libsystem_malloc Cross-Allocator Contention During iOS Database Sync

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating raw memory using `nativeHeap` and passing the bare pointer to Darwin's global dispatch queue exposes mimalloc arena metadata to thread-migration hazards. Freeing or mutating mimalloc-managed heap memory on uncoordinated Darwin OS threads triggers page metadata desynchronization and lock inversion deadlocks during high-frequency database synchronization.
```kotlin
import kotlinx.cinterop.*
import platform.Foundation.*
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_global_queue
import platform.darwin.DISPATCH_QUEUE_PRIORITY_HIGH

class UnsafeSyncCoordinator {
    // ANTI-PATTERN: Direct heap allocation via K/Native nativeHeap passed across 
    // Darwin GCD boundary without arena encapsulation or StableRef protection.
    fun dispatchDatabaseSyncPayload(rawRecords: List<String>) {
        val buffer = nativeHeap.allocArray<ByteVar>(rawRecords.size * 1024)
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH.toLong(), 0u)) {
            // Darwin thread attempts to process and mutate memory allocated in K/Native's mimalloc arena
            // Invoking native deallocation or Darwin sqlite bridge directly will cause allocator deadlocks
            processNativeRecords(buffer)
            nativeHeap.free(buffer) // Freeing on Darwin foreign thread corrupts mimalloc thread caches
        }
    }

    private fun processNativeRecords(ptr: CPointer<ByteVar>) {
        // DB writing logic using raw foreign pointers
    }
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation establishes complete allocator arena isolation. Memory is strictly bound to `memScoped` on a dedicated Kotlin CoroutineDispatcher (`limitedParallelism`), isolated within an `autoreleasepool` block. No raw pointers cross runtime boundaries, preventing libsystem_malloc / mimalloc allocator lock inversions during concurrent DB access.
```kotlin
import kotlinx.cinterop.*
import kotlinx.coroutines.*
import platform.darwin.autoreleasepool

class SafeSyncCoordinator(
    private val syncDispatcher: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(4)
) {
    // PRODUCTION INVARIANT: Complete allocator arena segregation.
    // Payloads are passed across boundaries via immutable byte copies, 
    // and any native interop is scoped deterministically within Kotlin's arena.
    suspend fun dispatchDatabaseSyncPayload(rawRecords: List<String>): Result<Int> = withContext(syncDispatcher) {
        runCatching {
            autoreleasepool {
                // Segregated into an ephemeral stack-based memory scope on the Kotlin worker thread
                memScoped {
                    val serializedPayloads = rawRecords.map { it.encodeToByteArray() }
                    var processedCount = 0
                    
                    for (payload in serializedPayloads) {
                        // Arena allocation is scoped strictly to this execution frame
                        val nativeBuffer = allocArray<ByteVar>(payload.size)
                        payload.usePinned { pinned ->
                            platform.posix.memcpy(nativeBuffer, pinned.addressOf(0), payload.size.convert())
                        }
                        
                        executeScopedDatabaseWrite(nativeBuffer, payload.size)
                        processedCount++
                    }
                    processedCount
                } // memScoped deterministically cleans up mimalloc arena before exiting dispatcher boundary
            }
        }
    }

    private fun executeScopedDatabaseWrite(buffer: CPointer<ByteVar>, length: Int) {
        // Safely performs atomic SQLite operation within current worker thread arena
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Native Mimalloc Arena Segregation Guardrail

Kotlin Multiplatform Native Mimalloc Arena Segregation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict heap allocator arena segregation between Kotlin/Native background worker threads and Darwin Apple platform runtimes (CoreData, SQLite, GCD) during high-throughput parallel database synchronization. Disallows cross-allocator pointer sharing, unmanaged heap transfers without explicit arena release, and concurrent foreign memory references that induce lock inversion or mimalloc page corruption on iOS. 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: Cross-Boundary Raw Pointer Escaping and Shared Allocator Deadlocks Across Darwin GCD and K/Native Mimalloc Runtimes 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 DriftCross-Boundary Raw Pointer Escaping and Shared Allocator Deadlocks Across Darwin GCD and K/Native Mimalloc RuntimesCritical
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 native heap allocations to their respective runtime arenas by wrapping K/Native low-level memory interactions within an explicit `memScoped` or `Arena` block that releases before crossing thread or interop boundaries.

Engineers MUST ALWAYS isolate native heap allocations to their respective runtime arenas by wrapping K/Native low-level memory interactions within an explicit `memScoped` or `Arena` block that releases before crossing thread or interop 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.
2

Engineers MUST NOT leak `NativePlacement.alloc` or `nativeHeap.alloc` references directly into Darwin GCD queues or Darwin-allocated callbacks, as Darwin deallocation routines invoke `free()` from `libsystem_malloc`, corrupting mimalloc arena metadata.

Engineers MUST NOT leak `NativePlacement.alloc` or `nativeHeap.alloc` references directly into Darwin GCD queues or Darwin-allocated callbacks, as Darwin deallocation routines invoke `free()` from `libsystem_malloc`, corrupting mimalloc arena metadata.

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 serialize high-frequency database synchronization payloads into self-contained immutable byte buffers (`ByteArray` or decoupled value types) instead of passing raw `COpaquePointer` or `CPointer<ByteVar>` across interop dispatch queues.

Engineers MUST serialize high-frequency database synchronization payloads into self-contained immutable byte buffers (`ByteArray` or decoupled value types) instead of passing raw `COpaquePointer` or `CPointer<ByteVar>` across interop dispatch queues.

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 Darwin-originated callbacks invoke Kotlin bridge operations exclusively within an explicit `autoreleasepool` while decoupling Native allocations onto dedicated Kotlin worker dispatchers using `withContext(Dispatchers.Default.limitedParallelism(N))`.

Services MUST ensure that Darwin-originated callbacks invoke Kotlin bridge operations exclusively within an explicit `autoreleasepool` while decoupling Native allocations onto dedicated Kotlin worker dispatchers using `withContext(Dispatchers.Default.limitedParallelism(N))`.

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 long-lived C pointers across suspend function boundaries without defensive pinning (`StableRef`) and deterministic scoped cleanup (`StableRef.dispose()`) executed strictly on the originating allocation thread arena.

Components NEVER store long-lived C pointers across suspend function boundaries without defensive pinning (`StableRef`) and deterministic scoped cleanup (`StableRef.dispose()`) executed strictly on the originating allocation thread arena.

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 Native Mimalloc Arena Segregation Guardrail critical for AI coding assistants?

Enforces strict heap allocator arena segregation between Kotlin/Native background worker threads and Darwin Apple platform runtimes (CoreData, SQLite, GCD) during high-throughput parallel database synchronization. Disallows cross-allocator pointer sharing, unmanaged heap transfers without explicit arena release, and concurrent foreign memory references that induce lock inversion or mimalloc page corruption on iOS. 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 (Cross-Boundary Raw Pointer Escaping and Shared Allocator Deadlocks Across Darwin GCD and K/Native Mimalloc Runtimes) 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