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

KMP Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard

Regulates cross-platform shared Kotlin/Wasm runtime heap allocations against host browser memory-pressure events to avert silent tab terminations. Mandates cooperative coroutine yielding to browser event loop cycles and proactive cache eviction under host memory constraints.

Prohibited Anti-Pattern: Unyielding synchronous allocation loops in Kotlin/Wasm starving host browser GC and triggering mobile browser tab terminations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard - Regulates cross-platform shared Kotlin/Wasm runtime heap allocations against host browser memory-pressure events to avert silent tab terminations. Mandates cooperative coroutine yielding to browser event loop cycles and proactive cache eviction under host memory constraints.
globs: **/wasmJsMain/**/*.kt, **/wasmMain/**/*.kt, **/commonMain/**/*.kt, **/webMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-wasm-cooperative-gc-memory-pressure-standard"
---

# KMP Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unyielding synchronous allocation loops in Kotlin/Wasm starving host browser GC and triggering mobile browser tab terminations

## System Constraints
You are a Principal Engineer enforcing the KMP Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard. You must mandate strict memory invariants for Kotlin/Wasm running within constrained browser and mobile WebView engines. Ensure all intensive memory allocations cooperatively yield to the host JavaScript event loop so the host engine (V8/SpiderMonkey/JavaScriptCore) can schedule WasmGC collection sweeps before the operating system's Low Memory Killer (LMK) issues a SIGKILL to the renderer process.

## Strict Guidelines
- Engineers MUST ALWAYS interleave high-throughput batch allocations or stream decoders with cooperative suspension points (`kotlinx.coroutines.yield()` or host `requestIdleCallback`) to release the main thread for host WasmGC sweeps.
- Engineers MUST NOT execute synchronous, long-running loops that continuously allocate Kotlin/Wasm managed objects without periodic memory budget checkpoints.
- Code SHOULD implement an explicit cooperative memory monitor in `wasmJsMain` that interrogates host heap metadata (e.g., `performance.memory` or `navigator.deviceMemory`) and downscales memory pools dynamically.
- Services MUST clear transient caches, decoded pixel maps, and intermediate serialization buffers upon receiving a browser or mobile host memory-warning event.
- Components NEVER hold long-lived global references to large `ByteArray` or primitive array allocations that span across multiple suspension cycles without explicit lifecycle disposal.

## Bad vs Good Implementations
### Cooperative Chunked Processing with Browser Yielding vs. Monolithic Synchronous Allocation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Running a long synchronous allocation loop inside Kotlin/Wasm blocks the host browser event loop entirely. The WasmGC collector (integrated into the browser engine) cannot perform interleaved minor GC cycles, escalating linear memory and heap usage until the mobile OS kills the browser tab with zero error diagnostics.
```kotlin
// wasmJsMain/BatchPayloadProcessor.kt
package com.example.kmp.wasm

class BatchPayloadProcessor {
    fun processLargeBatch(items: List<ByteArray>): List<ProcessedData> {
        val results = mutableListOf<ProcessedData>()
        // ANTI-PATTERN: Tight synchronous loop allocating heavily in WasmGC heap.
        // Starves host JS event loop; garbage cannot be reclaimed by host engine GC.
        // Causes silent tab termination (OOM kill) on mobile browsers.
        for (item in items) {
            val decoded = decodePayload(item) // Allocates thousands of transient Wasm objects
            results.add(transform(decoded))
        }
        return results
    }

    private fun decodePayload(bytes: ByteArray): IntermediateNode = IntermediateNode(bytes)
    private fun transform(node: IntermediateNode): ProcessedData = ProcessedData(node.hashCode())
}
```

#### Production Standard (Correct)
> **Standard**: By breaking the processing loop into disciplined chunks and suspending via `yield()`, the Kotlin/Wasm runtime relinquishes execution back to the host browser thread. This cooperative yield gives the browser engine an opportunity to perform GC passes, drain microtask queues, and avert OS-level OOM kills.
```kotlin
// wasmJsMain/BatchPayloadProcessor.kt
package com.example.kmp.wasm

import kotlinx.coroutines.yield
import kotlinx.browser.window
import kotlin.js.Promise

class BatchPayloadProcessor(
    private val yieldIntervalItems: Int = 50
) {
    suspend fun processLargeBatch(items: List<ByteArray>): List<ProcessedData> {
        val results = ArrayList<ProcessedData>(items.size)
        
        for ((index, item) in items.withIndex()) {
            val decoded = decodePayload(item)
            results.add(transform(decoded))
            
            // INVARIANT: Periodically yield control to host JS runtime
            // Allows V8/JSC microtask queues to flush and WasmGC to collect dead instances
            if (index > 0 && index % yieldIntervalItems == 0) {
                cooperativeYieldToHost()
            }
        }
        return results
    }

    private suspend fun cooperativeYieldToHost() {
        // Cooperative coroutine suspension
        yield()
    }

    private fun decodePayload(bytes: ByteArray): IntermediateNode = IntermediateNode(bytes)
    private fun transform(node: IntermediateNode): ProcessedData = ProcessedData(node.hashCode())
}
```

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 Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard

KMP Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard defines an industrial-grade behavioral standard for mobile engineering. Regulates cross-platform shared Kotlin/Wasm runtime heap allocations against host browser memory-pressure events to avert silent tab terminations. Mandates cooperative coroutine yielding to browser event loop cycles and proactive cache eviction under host memory constraints. 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: Unyielding synchronous allocation loops in Kotlin/Wasm starving host browser GC and triggering mobile browser tab terminations 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 DriftUnyielding synchronous allocation loops in Kotlin/Wasm starving host browser GC and triggering mobile browser tab terminationsCritical
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 interleave high-throughput batch allocations or stream decoders with cooperative suspension points (`kotlinx.coroutines.yield()` or host `requestIdleCallback`) to release the main thread for host WasmGC sweeps.

Engineers MUST ALWAYS interleave high-throughput batch allocations or stream decoders with cooperative suspension points (`kotlinx.coroutines.yield()` or host `requestIdleCallback`) to release the main thread for host WasmGC sweeps.

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 execute synchronous, long-running loops that continuously allocate Kotlin/Wasm managed objects without periodic memory budget checkpoints.

Engineers MUST NOT execute synchronous, long-running loops that continuously allocate Kotlin/Wasm managed objects without periodic memory budget checkpoints.

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 implement an explicit cooperative memory monitor in `wasmJsMain` that interrogates host heap metadata (e.g., `performance.memory` or `navigator.deviceMemory`) and downscales memory pools dynamically.

Code SHOULD implement an explicit cooperative memory monitor in `wasmJsMain` that interrogates host heap metadata (e.g., `performance.memory` or `navigator.deviceMemory`) and downscales memory pools dynamically.

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 clear transient caches, decoded pixel maps, and intermediate serialization buffers upon receiving a browser or mobile host memory-warning event.

Services MUST clear transient caches, decoded pixel maps, and intermediate serialization buffers upon receiving a browser or mobile host memory-warning event.

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 hold long-lived global references to large `ByteArray` or primitive array allocations that span across multiple suspension cycles without explicit lifecycle disposal.

Components NEVER hold long-lived global references to large `ByteArray` or primitive array allocations that span across multiple suspension cycles without explicit lifecycle disposal.

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 Kotlin/Wasm Cooperative GC Browser Memory Pressure Yield Standard critical for AI coding assistants?

Regulates cross-platform shared Kotlin/Wasm runtime heap allocations against host browser memory-pressure events to avert silent tab terminations. Mandates cooperative coroutine yielding to browser event loop cycles and proactive cache eviction under host memory constraints. 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 (Unyielding synchronous allocation loops in Kotlin/Wasm starving host browser GC and triggering mobile browser tab terminations) 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