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

Kotlin Multiplatform Native Memory Pacing and Concurrent Sweeper Guardrail

Enforces strict backpressure pacing on high-throughput background pipelines in Kotlin Multiplatform targeting Darwin/iOS. Binds rapid object allocations to the Kotlin/Native concurrent garbage collector's epoch sweep phases to eliminate UI hitching and safeguard Darwin main-thread CADisplayLink frame budgets.

Prohibited Anti-Pattern: Unbounded Background Ingestion Overwhelming Kotlin/Native Concurrent GC Epochs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Native Memory Pacing and Concurrent Sweeper Guardrail - Enforces strict backpressure pacing on high-throughput background pipelines in Kotlin Multiplatform targeting Darwin/iOS. Binds rapid object allocations to the Kotlin/Native concurrent garbage collector's epoch sweep phases to eliminate UI hitching and safeguard Darwin main-thread CADisplayLink frame budgets.
globs: **/*.kt, **/*.ios.kt, **/*.native.kt, **/gradle.properties
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-native-memory-pacing-sweeper-invariant"
---

# Kotlin Multiplatform Native Memory Pacing and Concurrent Sweeper Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Ingestion Overwhelming Kotlin/Native Concurrent GC Epochs

## System Constraints
You are a Principal Mobile Architect enforcing runtime memory invariants on Kotlin Multiplatform (KMP) runtimes targeting iOS and Android. Your mandate is to prevent unbounded object creation on background dispatchers that outpaces the Kotlin/Native Concurrent Garbage Collector's sweep epoch, triggering emergency STW (Stop-The-World) GC pauses on the Darwin main thread. You must enforce explicit chunk pacing, allocation-free object reuse buffers, and Darwin memory monitoring integration across all high-throughput native pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS configure Kotlin/Native concurrent mark-and-sweep GC via 'kotlin.native.binary.gc=cms' in gradle.properties and verify native memory allocator runtime flags.
- Engineers MUST NOT run unbounded 'Dispatchers.Default' or custom background dispatch loops that allocate short-lived native wrapper objects without pacing backpressure against GC collection epochs.
- Background streaming pipelines processing high-frequency frames, telemetry, or bulk database syncs MUST use chunked processing with cooperative suspension points ('yield()' or channel-driven token bucket pacing) to grant GC sweeper threads CPU slice priority.
- High-throughput native routines MUST leverage reusable byte/object buffers or primitive pools instead of instantiating transient domain objects inside inner loops.
- Pipelines bridging Kotlin/Native to Swift/Objective-C MUST NEVER bridge intermediate collections across foreign function boundaries without explicitly scoping autorelease pools via 'autoreleasepool { ... }'.

## Bad vs Good Implementations
### Unbounded Background Ingestion vs. Paced Batch Processing with GC Yielding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Iterating over an unmetered high-frequency stream on Dispatchers.Default creates transient Kotlin/Native heap objects faster than the concurrent sweeper can process GC epochs. Once native page limits approach system thresholds, the collector degrades to a blocking Stop-The-World phase that freezes the iOS main thread.
```kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

class TelemetryIngestor {
    fun streamPackets(packetStream: Flow<ByteArray>, scope: CoroutineScope) {
        scope.launch(Dispatchers.Default) {
            // ANTI-PATTERN: Unbounded rapid allocation of wrappers in a tight loop.
            // Exhausts Darwin memory pages before Native CMS sweeper collects unreferenced objects,
            // triggering an emergency Stop-The-World fallback on Main CADisplayLink.
            packetStream.collect { rawBytes ->
                val parsed = ParsedPacket(payload = rawBytes, timestamp = currentTimeMillis())
                database.insert(parsed)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Batching allocations into reusable structures and cooperatively yielding CPU time via 'yield()' gives concurrent GC worker threads sufficient scheduling epochs to sweep unreachable native memory, preventing GC queue saturation and avoiding iOS frame drops.
```kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlin.native.concurrent.*

class TelemetryIngestor {
    companion object {
        private const val GC_PACING_CHUNK_SIZE = 128
    }

    fun streamPackets(packetStream: Flow<ByteArray>, scope: CoroutineScope) {
        scope.launch(Dispatchers.Default) {
            // INVARIANT: Bound ingestion into sized batches, yielding execution
            // to allow the concurrent sweeper to complete sweeps without STW degradation.
            var allocationCounter = 0
            val batchBuffer = ArrayList<ParsedPacket>(GC_PACING_CHUNK_SIZE)

            packetStream.collect { rawBytes ->
                batchBuffer.add(ParsedPacket(payload = rawBytes, timestamp = currentTimeMillis()))
                allocationCounter++

                if (allocationCounter >= GC_PACING_CHUNK_SIZE) {
                    database.insertBatch(batchBuffer)
                    batchBuffer.clear()
                    allocationCounter = 0
                    // Yield thread slice to prevent starvation of Native GC sweeper threads
                    yield()
                }
            }

            if (batchBuffer.isNotEmpty()) {
                database.insertBatch(batchBuffer)
                batchBuffer.clear()
            }
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Native Memory Pacing and Concurrent Sweeper Guardrail

Kotlin Multiplatform Native Memory Pacing and Concurrent Sweeper Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict backpressure pacing on high-throughput background pipelines in Kotlin Multiplatform targeting Darwin/iOS. Binds rapid object allocations to the Kotlin/Native concurrent garbage collector's epoch sweep phases to eliminate UI hitching and safeguard Darwin main-thread CADisplayLink frame budgets. 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 Background Ingestion Overwhelming Kotlin/Native Concurrent GC Epochs 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 Background Ingestion Overwhelming Kotlin/Native Concurrent GC EpochsCritical
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 configure Kotlin/Native concurrent mark-and-sweep GC via 'kotlin.native.binary.gc=cms' in gradle.properties and verify native memory allocator runtime flags.

Engineers MUST ALWAYS configure Kotlin/Native concurrent mark-and-sweep GC via 'kotlin.native.binary.gc=cms' in gradle.properties and verify native memory allocator runtime flags.

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 run unbounded 'Dispatchers.Default' or custom background dispatch loops that allocate short-lived native wrapper objects without pacing backpressure against GC collection epochs.

Engineers MUST NOT run unbounded 'Dispatchers.Default' or custom background dispatch loops that allocate short-lived native wrapper objects without pacing backpressure against GC collection epochs.

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

Background streaming pipelines processing high-frequency frames, telemetry, or bulk database syncs MUST use chunked processing with cooperative suspension points ('yield()' or channel-driven token bucket pacing) to grant GC sweeper threads CPU slice priority.

Background streaming pipelines processing high-frequency frames, telemetry, or bulk database syncs MUST use chunked processing with cooperative suspension points ('yield()' or channel-driven token bucket pacing) to grant GC sweeper threads CPU slice priority.

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

High-throughput native routines MUST leverage reusable byte/object buffers or primitive pools instead of instantiating transient domain objects inside inner loops.

High-throughput native routines MUST leverage reusable byte/object buffers or primitive pools instead of instantiating transient domain objects inside inner loops.

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

Pipelines bridging Kotlin/Native to Swift/Objective-C MUST NEVER bridge intermediate collections across foreign function boundaries without explicitly scoping autorelease pools via 'autoreleasepool { ... }'.

Pipelines bridging Kotlin/Native to Swift/Objective-C MUST NEVER bridge intermediate collections across foreign function boundaries without explicitly scoping autorelease pools via 'autoreleasepool { ... }'.

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 Memory Pacing and Concurrent Sweeper Guardrail critical for AI coding assistants?

Enforces strict backpressure pacing on high-throughput background pipelines in Kotlin Multiplatform targeting Darwin/iOS. Binds rapid object allocations to the Kotlin/Native concurrent garbage collector's epoch sweep phases to eliminate UI hitching and safeguard Darwin main-thread CADisplayLink frame budgets. 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 Background Ingestion Overwhelming Kotlin/Native Concurrent GC Epochs) 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