This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skiko-darwin-metal-queue-sync

KMP Skiko Metal Render Thread Darwin Main Queue Synchronization

Enforces strict synchronization boundaries between Kotlin Multiplatform Skiko Metal drawing routines and Darwin's Grand Central Dispatch (GCD) main queue. Failure to isolate and properly interop with the main thread during CAMetalLayer transactions causes GPU command buffer stalling, UI thread deadlock, and hitch rates exceeding 60 FPS cadences on iOS.

Prohibited Anti-Pattern: Direct CAMetalLayer Drawing or Synchronous Main Thread Blocking from Skiko Render Loop

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko Metal Render Thread Darwin Main Queue Synchronization - Enforces strict synchronization boundaries between Kotlin Multiplatform Skiko Metal drawing routines and Darwin's Grand Central Dispatch (GCD) main queue. Failure to isolate and properly interop with the main thread during CAMetalLayer transactions causes GPU command buffer stalling, UI thread deadlock, and hitch rates exceeding 60 FPS cadences on iOS.
globs: **/*Actual.kt, **/iosMain/**/*.kt, **/skiko/**/*.kt, **/metal/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-darwin-metal-queue-sync"
---

# KMP Skiko Metal Render Thread Darwin Main Queue Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct CAMetalLayer Drawing or Synchronous Main Thread Blocking from Skiko Render Loop

## System Constraints
You are a Principal Mobile Architect enforcing strict thread boundaries and dispatch invariants between JetBrains Skiko (Metal backend) and Darwin Grand Central Dispatch (GCD) in Kotlin Multiplatform iOS applications. You ensure all CAMetalLayer lifecycle operations, CADisplayLink interactions, and frame dispatch routines avoid main thread deadlock, memory inversion, and Metal command buffer race conditions.

## Strict Guidelines
- Engineers MUST ALWAYS dispatch CAMetalLayer frame buffer queries and presentation requests consistently within Darwin's native dispatch_async(dispatch_get_main_queue()) or coordinated Skiko RenderDelegate boundaries.
- Engineers MUST NOT execute dispatch_sync against dispatch_get_main_queue() from Skiko background rendering loops or Metal command buffer completion handlers, as this triggers irrecoverable OS-level priority inversion deadlocks.
- Engineers MUST verify NSThread.isMainThread before invoking Skiko rendering context mutation or layer resizing, delegating to dispatch_async when called from background coroutines or worker threads.
- Code MUST capture CAMetalDrawable references strictly inside the render pass boundary and invoke presentDrawable asynchronously on the scheduled command buffer rather than holding lock-guarded drawable references.
- Services MUST ensure that display synchronization through CADisplayLink is invalidated and decoupled on Darwin main queue dealloc to prevent dangling callbacks into destroyed Skia drawing contexts.

## Bad vs Good Implementations
### Coordinating Skiko Metal Frame Submission with Darwin Main Queue

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using dispatch_sync to acquire CAMetalDrawable or trigger Skia updates locks the Skiko render thread while Darwin's main queue may be waiting on GPU resources or handling user input, leading to hard OS deadlocks and watchdog kills.
```kotlin
import platform.darwin.dispatch_sync
import platform.darwin.dispatch_get_main_queue
import org.jetbrains.skiko.SkiaLayer
import platform.QuartzCore.CAMetalLayer

class MetalRenderBridge(private val layer: SkiaLayer, private val metalLayer: CAMetalLayer) {
    fun onFrameAvailable() {
        // CRITICAL ANTI-PATTERN: Synchronously dispatching to Darwin main queue
        // from Skiko's internal render thread causes immediate UI thread deadlock
        // if UIKit is awaiting a frame layout or presentation lock.
        dispatch_sync(dispatch_get_main_queue()) {
            val drawable = metalLayer.nextDrawable()
            if (drawable != null) {
                layer.update(drawable)
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Checks if the thread is already Darwin main; otherwise uses dispatch_async to ensure Skiko render calls do not block the worker thread while safely interacting with CAMetalLayer on the main runloop.
```kotlin
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_main_queue
import platform.Foundation.NSThread
import org.jetbrains.skiko.SkiaLayer
import platform.QuartzCore.CAMetalLayer

class MetalRenderBridge(private val layer: SkiaLayer, private val metalLayer: CAMetalLayer) {
    fun onFrameAvailable() {
        // PRODUCTION INVARIANT: Check execution context. Never block the caller.
        // Dispatch asynchronously to Darwin's main queue when cross-thread coordination is necessary.
        if (NSThread.isMainThread) {
            renderDirectly()
        } else {
            dispatch_async(dispatch_get_main_queue()) {
                renderDirectly()
            }
        }
    }

    private fun renderDirectly() {
        // MetalLayer presentation is bound to the render thread lifecycle safely
        val drawable = metalLayer.nextDrawable() ?: return
        layer.update(drawable)
    }
}
```

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 Skiko Metal Render Thread Darwin Main Queue Synchronization

KMP Skiko Metal Render Thread Darwin Main Queue Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization boundaries between Kotlin Multiplatform Skiko Metal drawing routines and Darwin's Grand Central Dispatch (GCD) main queue. Failure to isolate and properly interop with the main thread during CAMetalLayer transactions causes GPU command buffer stalling, UI thread deadlock, and hitch rates exceeding 60 FPS cadences 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: Direct CAMetalLayer Drawing or Synchronous Main Thread Blocking from Skiko Render Loop 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 DriftDirect CAMetalLayer Drawing or Synchronous Main Thread Blocking from Skiko Render LoopCritical
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 dispatch CAMetalLayer frame buffer queries and presentation requests consistently within Darwin's native dispatch_async(dispatch_get_main_queue()) or coordinated Skiko RenderDelegate boundaries.

Engineers MUST ALWAYS dispatch CAMetalLayer frame buffer queries and presentation requests consistently within Darwin's native dispatch_async(dispatch_get_main_queue()) or coordinated Skiko RenderDelegate 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 execute dispatch_sync against dispatch_get_main_queue() from Skiko background rendering loops or Metal command buffer completion handlers, as this triggers irrecoverable OS-level priority inversion deadlocks.

Engineers MUST NOT execute dispatch_sync against dispatch_get_main_queue() from Skiko background rendering loops or Metal command buffer completion handlers, as this triggers irrecoverable OS-level priority inversion deadlocks.

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 verify NSThread.isMainThread before invoking Skiko rendering context mutation or layer resizing, delegating to dispatch_async when called from background coroutines or worker threads.

Engineers MUST verify NSThread.isMainThread before invoking Skiko rendering context mutation or layer resizing, delegating to dispatch_async when called from background coroutines or worker threads.

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 MUST capture CAMetalDrawable references strictly inside the render pass boundary and invoke presentDrawable asynchronously on the scheduled command buffer rather than holding lock-guarded drawable references.

Code MUST capture CAMetalDrawable references strictly inside the render pass boundary and invoke presentDrawable asynchronously on the scheduled command buffer rather than holding lock-guarded drawable references.

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 ensure that display synchronization through CADisplayLink is invalidated and decoupled on Darwin main queue dealloc to prevent dangling callbacks into destroyed Skia drawing contexts.

Services MUST ensure that display synchronization through CADisplayLink is invalidated and decoupled on Darwin main queue dealloc to prevent dangling callbacks into destroyed Skia drawing contexts.

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 Skiko Metal Render Thread Darwin Main Queue Synchronization critical for AI coding assistants?

Enforces strict synchronization boundaries between Kotlin Multiplatform Skiko Metal drawing routines and Darwin's Grand Central Dispatch (GCD) main queue. Failure to isolate and properly interop with the main thread during CAMetalLayer transactions causes GPU command buffer stalling, UI thread deadlock, and hitch rates exceeding 60 FPS cadences 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 (Direct CAMetalLayer Drawing or Synchronous Main Thread Blocking from Skiko Render Loop) 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