This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-compose-skiko-render-thread-isolation-standard

Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard

Enforces strict boundary separation between Skiko graphics rendering pipelines and native host UI event loops across Kotlin Multiplatform targets. Eliminates main-thread rendering hitching and prevents cross-runtime memory leaks caused by bidirectional reference pinning between Apple Automated Reference Counting (ARC) and Kotlin Native Garbage Collector (GC).

Prohibited Anti-Pattern: Executing heavy composition or state evaluation directly inside the Skiko CADisplayLink frame callback while holding strong native UIKit references across coroutine boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard - Enforces strict boundary separation between Skiko graphics rendering pipelines and native host UI event loops across Kotlin Multiplatform targets. Eliminates main-thread rendering hitching and prevents cross-runtime memory leaks caused by bidirectional reference pinning between Apple Automated Reference Counting (ARC) and Kotlin Native Garbage Collector (GC).
globs: **/iosMain/**/*.kt, **/appleMain/**/*.kt, **/commonMain/**/ui/**/*.kt, **/render/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-skiko-render-thread-isolation-standard"
---

# Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing heavy composition or state evaluation directly inside the Skiko CADisplayLink frame callback while holding strong native UIKit references across coroutine boundaries

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform (KMP) and Compose Multiplatform rendering internals. Your role is to mandate strict render-thread isolation for Skiko pipelines and prevent cross-runtime memory retention cycles between Kotlin Native GC and iOS ARC. Disallow blocking operations on CADisplayLink triggers, prohibit strong reference cycles between native view controllers and Compose state, and mandate explicit lifecycle teardown for all Skiko redrawer instances.

## Strict Guidelines
- Engineers MUST ALWAYS isolate CPU-heavy state transformations and I/O operations away from the Skiko rendering pipeline by offloading them to Dispatchers.Default or Dispatchers.IO.
- Engineers MUST NOT hold strong references to native platform containers (UIViewController, UIView, CAMetalLayer) within long-lived Kotlin coroutine scopes or Compose snapshot states.
- Code SHOULD wrap native iOS UIViewController and platform delegates in `kotlin.native.ref.WeakReference` when bridging into Compose Multiplatform contexts to prevent ARC-GC zombie cycles.
- Services MUST ensure that Skiko redrawers (such as MetalRedrawer on iOS) are explicitly paused when the host view transitions out of visibility and fully disposed upon unmount.
- Components NEVER execute layout calculations, database reads, or cryptographic hashing synchronously within Skiko canvas draw passes or Skia onDraw callbacks.

## Bad vs Good Implementations
### Decoupled Skiko Metal Layer Rendering and ARC-GC Weak Bridging

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Holding a strong reference to UIViewController inside Compose remember creates a circular reference between Kotlin's GC and Apple's ARC runtime, preventing deallocation. Furthermore, calculating state synchronously on Dispatchers.Main inside the rendering loop starves Skiko's MetalRedrawer, causing severe frame drops (jank).
```kotlin
// CRITICAL FAILURE: Capturing strong UIViewController in Compose state,
// and dispatching computationally heavy drawing directly on the main thread.
import platform.UIKit.UIViewController
import androidx.compose.runtime.*
import kotlinx.coroutines.*

@Composable
fun NativeContainerBridge(controller: UIViewController) {
    // Anti-pattern 1: Strong native reference pinned in Compose state creates ARC-GC cycle
    val retainedController by remember { mutableStateOf(controller) }

    DisposableEffect(Unit) {
        // Anti-pattern 2: Blocking the host thread directly on frame pass
        val job = CoroutineScope(Dispatchers.Main).launch {
            while (isActive) {
                // Heavy computation blocking the Skiko frame callback
                val matrix = computeComplexProjectionMatrix()
                retainedController.view.setNeedsDisplay()
                delay(16)
            }
        }
        onDispose { job.cancel() }
    }
}

private fun computeComplexProjectionMatrix(): List<Float> {
    return (0..100000).map { it * 1.5f }
}
```

#### Production Standard (Correct)
> **Standard**: The native controller is wrapped in a Kotlin Native WeakReference, breaking ARC-GC memory retention graphs. State calculation is offloaded strictly to Dispatchers.Default, leaving the Skiko render pipeline and native CADisplayLink free to composite frames without hitching.
```kotlin
// PRODUCTION STANDARD: WeakReference bridging, dedicated computation dispatch,
// and explicit teardown to ensure 60/120fps thread isolation.
import kotlin.native.ref.WeakReference
import platform.UIKit.UIViewController
import androidx.compose.runtime.*
import kotlinx.coroutines.*

@Composable
fun NativeContainerBridge(controller: UIViewController) {
    // Invariant 1: Prevent ARC-GC pinning via explicit WeakReference
    val weakController = remember(controller) { WeakReference(controller) }
    
    // Invariant 2: State generation isolated from Skiko render thread
    val renderState by produceState<List<Float>>(initialValue = emptyList()) {
        withContext(Dispatchers.Default) {
            while (isActive) {
                val transformed = computeComplexProjectionMatrix()
                value = transformed
                delay(16)
            }
        }
    }

    DisposableEffect(weakController) {
        onDispose {
            // Invariant 3: Explicit GC cleanup and unbinding on component unmount
            weakController.clear()
        }
    }
}

private fun computeComplexProjectionMatrix(): List<Float> {
    return (0..1000).map { it * 1.5f }
}
```

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: Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard

Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict boundary separation between Skiko graphics rendering pipelines and native host UI event loops across Kotlin Multiplatform targets. Eliminates main-thread rendering hitching and prevents cross-runtime memory leaks caused by bidirectional reference pinning between Apple Automated Reference Counting (ARC) and Kotlin Native Garbage Collector (GC). 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: Executing heavy composition or state evaluation directly inside the Skiko CADisplayLink frame callback while holding strong native UIKit references across coroutine boundaries 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 DriftExecuting heavy composition or state evaluation directly inside the Skiko CADisplayLink frame callback while holding strong native UIKit references across coroutine boundariesCritical
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 CPU-heavy state transformations and I/O operations away from the Skiko rendering pipeline by offloading them to Dispatchers.Default or Dispatchers.IO.

Engineers MUST ALWAYS isolate CPU-heavy state transformations and I/O operations away from the Skiko rendering pipeline by offloading them to Dispatchers.Default or Dispatchers.IO.

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 hold strong references to native platform containers (UIViewController, UIView, CAMetalLayer) within long-lived Kotlin coroutine scopes or Compose snapshot states.

Engineers MUST NOT hold strong references to native platform containers (UIViewController, UIView, CAMetalLayer) within long-lived Kotlin coroutine scopes or Compose snapshot states.

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 wrap native iOS UIViewController and platform delegates in `kotlin.native.ref.WeakReference` when bridging into Compose Multiplatform contexts to prevent ARC-GC zombie cycles.

Code SHOULD wrap native iOS UIViewController and platform delegates in `kotlin.native.ref.WeakReference` when bridging into Compose Multiplatform contexts to prevent ARC-GC zombie cycles.

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 Skiko redrawers (such as MetalRedrawer on iOS) are explicitly paused when the host view transitions out of visibility and fully disposed upon unmount.

Services MUST ensure that Skiko redrawers (such as MetalRedrawer on iOS) are explicitly paused when the host view transitions out of visibility and fully disposed upon unmount.

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 execute layout calculations, database reads, or cryptographic hashing synchronously within Skiko canvas draw passes or Skia onDraw callbacks.

Components NEVER execute layout calculations, database reads, or cryptographic hashing synchronously within Skiko canvas draw passes or Skia onDraw callbacks.

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 Compose Multiplatform Skiko Render Thread Isolation and ARC-GC Barrier Standard critical for AI coding assistants?

Enforces strict boundary separation between Skiko graphics rendering pipelines and native host UI event loops across Kotlin Multiplatform targets. Eliminates main-thread rendering hitching and prevents cross-runtime memory leaks caused by bidirectional reference pinning between Apple Automated Reference Counting (ARC) and Kotlin Native Garbage Collector (GC). 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 (Executing heavy composition or state evaluation directly inside the Skiko CADisplayLink frame callback while holding strong native UIKit references across coroutine boundaries) 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

Compose