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

Compose Multiplatform SKIKO Metal Render-Thread CADisplayLink Synchronization Standard

Mandates deterministic vsync synchronization between Apple Metal command buffers in SKIKO and UIKit run loops using CADisplayLink. Enforces strict frame-pacing and buffer locks to eliminate visual tearing and render-thread contention across native interoperability boundaries.

Prohibited Anti-Pattern: Unsynchronized Main-Thread Render Loops and Ad-Hoc Timers Leading to Metal Buffer Contention and Frame Tearing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform SKIKO Metal Render-Thread CADisplayLink Synchronization Standard - Mandates deterministic vsync synchronization between Apple Metal command buffers in SKIKO and UIKit run loops using CADisplayLink. Enforces strict frame-pacing and buffer locks to eliminate visual tearing and render-thread contention across native interoperability boundaries.
globs: **/*Ios.kt, **/*Native.kt, **/skiko/**/*.kt, **/metal/**/*.kt, **/*.ios.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-skiko-metal-render-synchronization-standard"
---

# Compose Multiplatform SKIKO Metal Render-Thread CADisplayLink Synchronization Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Main-Thread Render Loops and Ad-Hoc Timers Leading to Metal Buffer Contention and Frame Tearing

## System Constraints
You are a Principal Engineer enforcing the Compose Multiplatform SKIKO Metal Render-Thread Synchronization Standard. Mandate that all Metal drawing passes and Skia canvas rendering cycles bind directly to platform-native vsync pulses (CADisplayLink) on iOS. Strictly prevent unbounded coroutines or decoupled dispatch queues from pumping render frames out of sync with the display refresh rate.

## Strict Guidelines
- Engineers MUST ALWAYS bind SKIKO rendering triggers directly to a CADisplayLink registered with NSRunLoop.mainRunLoop in NSRunLoopCommonModes to prevent frame drops during UIKit scroll interactions.
- Engineers MUST NEVER dispatch Metal draw passes via unthrottled coroutine frame loops (e.g., while(isActive) { delay(16); needRedraw() }) across the Kotlin/Native boundary.
- Code MUST release or present CAMetalDrawable instances immediately after encoding to prevent exhaustion of the Metal drawable triple-buffer pool.
- Services MUST ensure that interoperability layers (e.g., UIKitView inside Compose) synchronize their layout and commit phases within the same CATransaction to eliminate tearing during gestures.
- Components NEVER invoke blocking synchronization primitives (such as MTLCommandBuffer.waitUntilCompleted() or thread-blocking locks) inside the CADisplayLink frame dispatch callback.

## Bad vs Good Implementations
### CADisplayLink Vsync Synchronization for SKIKO Metal Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Driving Compose canvas updates using an arbitrary coroutine delay decouples rendering from the hardware refresh rate (ignoring ProMotion 120Hz and 60Hz limits), desynchronizes with the UIKit run loop during scrolling gestures, and triggers frame tearing or lock contention on the Metal command queue.
```kotlin
// ANTI-PATTERN: Coroutine-driven frame loop decoupled from iOS vsync pipeline.
// Causes jitter, frame drops during UIKit gestures, and Metal drawable starvation.
class CoroutineRenderPump(private val layer: SkiaLayer) {
    private val scope = CoroutineScope(Dispatchers.Main)
    
    fun start() {
        scope.launch {
            while (isActive) {
                // Arbitrary 60Hz timing ignores variable refresh rates (ProMotion 120Hz)
                // and loses synchronization during native UI gestures.
                delay(16)
                layer.needRedraw()
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Binding to CADisplayLink using NSRunLoopCommonModes guarantees that frame callbacks match display vsync cycles (adapting natively to 60Hz or 120Hz ProMotion screens) and maintains draw cycle alignment even while native UIKit views are performing continuous scroll tracking.
```kotlin
// PRODUCTION STANDARD: Deterministic CADisplayLink frame synchronization.
// Binds directly to the Metal drawable lifecycle and common run loop modes.
import platform.QuartzCore.CADisplayLink
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import platform.darwin.NSObject

class MetalVsyncSynchronizer(
    private val onVsyncFrame: (timestamp: Double, targetTimestamp: Double) -> Unit
) : NSObject() {
    private var displayLink: CADisplayLink? = null

    fun start() {
        stop()
        val link = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = platform.objc.sel_registerName("onDisplayLinkStep:")
        )
        // Bind to common modes to ensure rendering continues during UIScrollView tracking
        link.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
        displayLink = link
    }

    @OptIn(kotlinx.cinterop.BetaInteropApi::class)
    @platform.objc.ObjCAction
    fun onDisplayLinkStep(link: CADisplayLink) {
        // Pass deterministic hardware timestamps to throttle SKIKO redraw passes
        onVsyncFrame(link.timestamp, link.targetTimestamp)
    }

    fun stop() {
        displayLink?.invalidate()
        displayLink = null
    }
}
```

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 Metal Render-Thread CADisplayLink Synchronization Standard

Compose Multiplatform SKIKO Metal Render-Thread CADisplayLink Synchronization Standard defines an industrial-grade behavioral standard for mobile engineering. Mandates deterministic vsync synchronization between Apple Metal command buffers in SKIKO and UIKit run loops using CADisplayLink. Enforces strict frame-pacing and buffer locks to eliminate visual tearing and render-thread contention across native interoperability boundaries. 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: Unsynchronized Main-Thread Render Loops and Ad-Hoc Timers Leading to Metal Buffer Contention and Frame Tearing 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 DriftUnsynchronized Main-Thread Render Loops and Ad-Hoc Timers Leading to Metal Buffer Contention and Frame TearingCritical
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 bind SKIKO rendering triggers directly to a CADisplayLink registered with NSRunLoop.mainRunLoop in NSRunLoopCommonModes to prevent frame drops during UIKit scroll interactions.

Engineers MUST ALWAYS bind SKIKO rendering triggers directly to a CADisplayLink registered with NSRunLoop.mainRunLoop in NSRunLoopCommonModes to prevent frame drops during UIKit scroll interactions.

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 NEVER dispatch Metal draw passes via unthrottled coroutine frame loops (e.g., while(isActive) { delay(16)

Engineers MUST NEVER dispatch Metal draw passes via unthrottled coroutine frame loops (e.g., while(isActive) { delay(16); needRedraw() }) across the Kotlin/Native boundary.

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 MUST release or present CAMetalDrawable instances immediately after encoding to prevent exhaustion of the Metal drawable triple-buffer pool.

Code MUST release or present CAMetalDrawable instances immediately after encoding to prevent exhaustion of the Metal drawable triple-buffer pool.

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 interoperability layers (e.g., UIKitView inside Compose) synchronize their layout and commit phases within the same CATransaction to eliminate tearing during gestures.

Services MUST ensure that interoperability layers (e.g., UIKitView inside Compose) synchronize their layout and commit phases within the same CATransaction to eliminate tearing during gestures.

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 invoke blocking synchronization primitives (such as MTLCommandBuffer.waitUntilCompleted() or thread-blocking locks) inside the CADisplayLink frame dispatch callback.

Components NEVER invoke blocking synchronization primitives (such as MTLCommandBuffer.waitUntilCompleted() or thread-blocking locks) inside the CADisplayLink frame dispatch callback.

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 Metal Render-Thread CADisplayLink Synchronization Standard critical for AI coding assistants?

Mandates deterministic vsync synchronization between Apple Metal command buffers in SKIKO and UIKit run loops using CADisplayLink. Enforces strict frame-pacing and buffer locks to eliminate visual tearing and render-thread contention across native interoperability boundaries. 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 (Unsynchronized Main-Thread Render Loops and Ad-Hoc Timers Leading to Metal Buffer Contention and Frame Tearing) 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