This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skiko-ios-vsync-pacing-guardrail

KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing

Eliminates micro-stutter, jank, and JNI/thread desynchronization on iOS 120Hz ProMotion displays in Compose Multiplatform / Skiko apps. Mandates deterministic CADisplayLink scheduling over NSRunLoopCommonModes with dynamic CAFrameRateRange configuration, preventing frame drop anomalies during user gestures.

Prohibited Anti-Pattern: Unsynchronized Coroutine Delays or NSDefaultRunLoopMode Usage for iOS Skiko VSync Pacing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing - Eliminates micro-stutter, jank, and JNI/thread desynchronization on iOS 120Hz ProMotion displays in Compose Multiplatform / Skiko apps. Mandates deterministic CADisplayLink scheduling over NSRunLoopCommonModes with dynamic CAFrameRateRange configuration, preventing frame drop anomalies during user gestures.
globs: **/*Skiko*.kt, **/*ViewController.kt, **/*Metal*.kt, **/iosApp/**/*.swift, **/appleMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-ios-vsync-pacing-guardrail"
---

# KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Coroutine Delays or NSDefaultRunLoopMode Usage for iOS Skiko VSync Pacing

## System Constraints
You are a Principal Mobile Systems Architect specializing in Kotlin Multiplatform (KMP), Compose Multiplatform, and Skiko rendering engine internals. Your task is to enforce strict VSync synchronization guardrails on iOS targets. You must prevent thread desynchronization between CADisplayLink ticks and Skiko's Metal render commands, mandate NSRunLoopCommonModes attachment, lock preferredFrameRateRange for ProMotion displays (10Hz-120Hz), and prohibit asynchronous coroutine dispatch hops (such as generic delay loops or unconfined dispatchers) during active frame invalidation cycles.

## Strict Guidelines
- Engineers MUST ALWAYS schedule `CADisplayLink` on `NSRunLoop.mainRunLoop` with `NSRunLoopCommonModes` to prevent frame delivery starvation during active UIScrollView tracking and touch interactions.
- Engineers MUST explicitly set `CAFrameRateRange` on iOS 15+ devices to support dynamic ProMotion refresh rates (e.g., minimum 60Hz/80Hz, preferred 120Hz, maximum 120Hz) rather than relying on legacy fixed integer intervals.
- Engineers MUST NOT use asynchronous coroutine dispatchers (e.g., `Dispatchers.Default`, `delay()`, or `NSTimer`) to trigger Skiko layer invalidation cycles.
- Engineers MUST bridge native `CADisplayLink` ticks directly into Skiko's `SkiaLayer.needRedraw()` synchronously on the Main RunLoop without accumulating unthrottled task queues.
- Engineers MUST synchronize the lifecycle of `CADisplayLink` with `UIViewController` transition states (`viewWillAppear`, `viewDidDisappear`) by setting `isPaused = true` or invalidating to prevent runaway GPU consumption in background states.

## Bad vs Good Implementations
### Deterministic CADisplayLink RunLoop Scheduling with ProMotion Support

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using NSDefaultRunLoopMode suspends CADisplayLink when user gestures place the run loop in NSEventTrackingRunLoopMode, freezing rendering during scrolls. Using coroutine delays drifts from the hardware vertical blanking interval, generating frequent micro-stutters and frame tearing on ProMotion displays.
```kotlin
// Anti-Pattern: Unsynchronized coroutines or scheduling on NSDefaultRunLoopMode
import kotlinx.coroutines.*
import platform.Foundation.NSRunLoop
import platform.Foundation.NSDefaultRunLoopMode
import platform.QuartzCore.CADisplayLink
import org.jetbrains.skiko.SkiaLayer

class UnsafeSkikoPacer(private val layer: SkiaLayer) {
    private val scope = CoroutineScope(Dispatchers.Main)

    fun start() {
        // Flaw 1: NSDefaultRunLoopMode pauses whenever the user scrolls a UIScrollView
        val displayLink = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = platform.objc.NSSelectorFromString("tick:")
        )
        displayLink?.addToRunLoop(NSRunLoop.currentRunLoop, NSDefaultRunLoopMode)

        // Flaw 2: Fabricating VSync ticks via coroutine delay introduces severe drift and missed frames
        scope.launch {
            while (isActive) {
                layer.needRedraw() // Desynchronized from hardware scanout
                delay(8) // Naive 120Hz attempt: fails to track dynamic display refresh
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Attaching the CADisplayLink to NSRunLoopCommonModes guarantees that rendering continues smoothly even while users pan or scroll. Configuring CAFrameRateRange allows iOS 15+ ProMotion to render at a full, dynamic 120Hz lockstep without coroutine drift or JNI scheduling jitter.
```kotlin
// Production Standard: Hardware-locked CADisplayLink on NSRunLoopCommonModes
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.ObjCAction
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import platform.QuartzCore.CADisplayLink
import platform.QuartzCore.CAFrameRateRangeMake
import platform.UIKit.UIDevice
import platform.darwin.NSObject
import org.jetbrains.skiko.SkiaLayer

@OptIn(ExperimentalForeignApi::class)
class DeterministicSkikoPacer(
    private val skiaLayer: SkiaLayer
) : NSObject() {
    private var displayLink: CADisplayLink? = null

    fun startPacing() {
        if (displayLink != null) return

        val link = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = platform.objc.NSSelectorFromString("onVSync:")
        )

        // 1. Enable ProMotion 120Hz adaptation for iOS 15+
        if (UIDevice.currentDevice.systemVersion.compareTo("15.0") >= 0) {
            link.preferredFrameRateRange = CAFrameRateRangeMake(
                minimum = 60f,
                maximum = 120f,
                preferred = 120f
            )
        }

        // 2. Lock to NSRunLoopCommonModes to ensure execution during user interaction
        link.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
        displayLink = link
    }

    @ObjCAction
    fun onVSync(sender: CADisplayLink) {
        // Directly trigger Skiko rendering lockstep with display hardware refresh
        skiaLayer.needRedraw()
    }

    fun pause() {
        displayLink?.paused = true
    }

    fun resume() {
        displayLink?.paused = false
    }

    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: KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing

KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing defines an industrial-grade behavioral standard for mobile engineering. Eliminates micro-stutter, jank, and JNI/thread desynchronization on iOS 120Hz ProMotion displays in Compose Multiplatform / Skiko apps. Mandates deterministic CADisplayLink scheduling over NSRunLoopCommonModes with dynamic CAFrameRateRange configuration, preventing frame drop anomalies during user gestures. 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 Coroutine Delays or NSDefaultRunLoopMode Usage for iOS Skiko VSync Pacing 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 Coroutine Delays or NSDefaultRunLoopMode Usage for iOS Skiko VSync PacingCritical
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 schedule `CADisplayLink` on `NSRunLoop.mainRunLoop` with `NSRunLoopCommonModes` to prevent frame delivery starvation during active UIScrollView tracking and touch interactions.

Engineers MUST ALWAYS schedule `CADisplayLink` on `NSRunLoop.mainRunLoop` with `NSRunLoopCommonModes` to prevent frame delivery starvation during active UIScrollView tracking and touch 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 explicitly set `CAFrameRateRange` on iOS 15+ devices to support dynamic ProMotion refresh rates (e.g., minimum 60Hz/80Hz, preferred 120Hz, maximum 120Hz) rather than relying on legacy fixed integer intervals.

Engineers MUST explicitly set `CAFrameRateRange` on iOS 15+ devices to support dynamic ProMotion refresh rates (e.g., minimum 60Hz/80Hz, preferred 120Hz, maximum 120Hz) rather than relying on legacy fixed integer intervals.

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 NOT use asynchronous coroutine dispatchers (e.g., `Dispatchers.Default`, `delay()`, or `NSTimer`) to trigger Skiko layer invalidation cycles.

Engineers MUST NOT use asynchronous coroutine dispatchers (e.g., `Dispatchers.Default`, `delay()`, or `NSTimer`) to trigger Skiko layer invalidation 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

Engineers MUST bridge native `CADisplayLink` ticks directly into Skiko's `SkiaLayer.needRedraw()` synchronously on the Main RunLoop without accumulating unthrottled task queues.

Engineers MUST bridge native `CADisplayLink` ticks directly into Skiko's `SkiaLayer.needRedraw()` synchronously on the Main RunLoop without accumulating unthrottled task queues.

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

Engineers MUST synchronize the lifecycle of `CADisplayLink` with `UIViewController` transition states (`viewWillAppear`, `viewDidDisappear`) by setting `isPaused = true` or invalidating to prevent runaway GPU consumption in background states.

Engineers MUST synchronize the lifecycle of `CADisplayLink` with `UIViewController` transition states (`viewWillAppear`, `viewDidDisappear`) by setting `isPaused = true` or invalidating to prevent runaway GPU consumption in background 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP Skiko iOS VSync CADisplayLink Deterministic RunLoop Pacing critical for AI coding assistants?

Eliminates micro-stutter, jank, and JNI/thread desynchronization on iOS 120Hz ProMotion displays in Compose Multiplatform / Skiko apps. Mandates deterministic CADisplayLink scheduling over NSRunLoopCommonModes with dynamic CAFrameRateRange configuration, preventing frame drop anomalies during user gestures. 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 Coroutine Delays or NSDefaultRunLoopMode Usage for iOS Skiko VSync Pacing) 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