This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-ios-cadisplaylink-metal-vsync-production-standard

Compose Multiplatform iOS CADisplayLink Metal VSync Synchronization

Enforces strict synchronization between Skiko Metal render passes and Apple CADisplayLink hardware refresh boundaries on iOS. Prevents main-thread hitching, micro-stutter, and frame drops across variable refresh rate (VRR) ProMotion displays by aligning frame generation with target display presentation timestamps.

Prohibited Anti-Pattern: Unsynchronized Coroutine Loop or Unbounded Main Dispatcher CADisplayLink Triggering Skiko Redraws

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform iOS CADisplayLink Metal VSync Synchronization - Enforces strict synchronization between Skiko Metal render passes and Apple CADisplayLink hardware refresh boundaries on iOS. Prevents main-thread hitching, micro-stutter, and frame drops across variable refresh rate (VRR) ProMotion displays by aligning frame generation with target display presentation timestamps.
globs: **/iosMain/**/*.kt, **/iosApp/**/*.swift, **/skiko/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-ios-cadisplaylink-metal-vsync-production-standard"
---

# Compose Multiplatform iOS CADisplayLink Metal VSync Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Coroutine Loop or Unbounded Main Dispatcher CADisplayLink Triggering Skiko Redraws

## System Constraints
You are a Principal Mobile Architect enforcing hardware-synchronized rendering for Compose Multiplatform on iOS. Mandate that all Skiko Metal render passes tie directly to CADisplayLink with correct CAFrameRateRange parameters, runloop registration in NSRunLoopCommonModes, and non-blocking CAMetalDrawable acquisition to guarantee smooth 120Hz ProMotion pacing without frame jitter.

## Strict Guidelines
- Engineers MUST ALWAYS attach CADisplayLink to NSRunLoop.mainRunLoop (or NSRunLoop.currentRunLoop on main thread) using NSRunLoopCommonModes to prevent rendering starvation during UI interaction and scrolling.
- Engineers MUST explicitly configure CAFrameRateRange (minimum, maximum, preferred) when initializing CADisplayLink on iOS 15+ to properly utilize 120Hz ProMotion screens without locking rendering to 60Hz.
- Engineers MUST NOT rely on Kotlin Coroutines delay loops (e.g., delay(16)), Dispatchers.Main periodic polls, or NSTimer to schedule Skiko Metal redraw passes.
- Code MUST calculate frame pacing and canvas delta times using CADisplayLink.targetTimestamp and CADisplayLink.timestamp rather than wall-clock time (NSDate / CACurrentMediaTime).
- Services MUST ensure that CAMetalLayer.nextDrawable() is acquired just-in-time prior to encoding render commands, and never hold drawable instances across VSync boundaries.

## Bad vs Good Implementations
### Configuring CADisplayLink with ProMotion VRR Support for Skiko Metal Layer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Driving Compose Multiplatform frames via a coroutine delay loop on Dispatchers.Main introduces phase-jitter against the iOS display compositor. It ignores ProMotion 120Hz capabilities, throttles user interaction, and freezes during nested scroll events because it is not integrated into NSRunLoopCommonModes.
```kotlin
// BAD: Naive Coroutine-based frame loop; ignores ProMotion 120Hz and stutters during scrolling
class MetalFrameRenderer(private val skikoLayer: SkikoUIView) {
    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    fun start() {
        scope.launch {
            while (isActive) {
                // 60Hz lock via fixed delay; desynced from VSync
                delay(16)
                skikoLayer.setNeedsDisplay()
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Attaches CADisplayLink to NSRunLoopCommonModes so animation frames continue rendering uninterrupted during touches and scroll tracking. It configures CAFrameRateRangeMake to scale between 10Hz and 120Hz dynamically, utilizing targetTimestamp for deterministic Skiko Metal pacing.
```kotlin
// GOOD: Hardware-synchronized CADisplayLink with ProMotion range and NSRunLoopCommonModes
import platform.QuartzCore.CADisplayLink
import platform.QuartzCore.CAFrameRateRangeMake
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import platform.darwin.NSObject
import platform.objc.sel_registerName

class MetalVSyncSynchronizer(
    private val onVsyncTick: (targetTimestamp: Double) -> Unit
) : NSObject() {
    private var displayLink: CADisplayLink? = null

    fun start() {
        stop()
        val link = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = sel_registerName("step:")
        )
        // Enable ProMotion dynamic refresh pacing (10Hz - 120Hz)
        link.preferredFrameRateRange = CAFrameRateRangeMake(
            minimum = 10f,
            maximum = 120f,
            preferred = 120f
        )
        // CommonModes prevents frame drop during tracking/scrolling gestures
        link.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
        displayLink = link
    }

    @OptIn(kotlinx.cinterop.BetaInteropApi::class)
    @Suppress("unused")
    fun step(link: CADisplayLink) {
        onVsyncTick(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 iOS CADisplayLink Metal VSync Synchronization

Compose Multiplatform iOS CADisplayLink Metal VSync Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization between Skiko Metal render passes and Apple CADisplayLink hardware refresh boundaries on iOS. Prevents main-thread hitching, micro-stutter, and frame drops across variable refresh rate (VRR) ProMotion displays by aligning frame generation with target display presentation timestamps. 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 Loop or Unbounded Main Dispatcher CADisplayLink Triggering Skiko Redraws 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 Loop or Unbounded Main Dispatcher CADisplayLink Triggering Skiko RedrawsCritical
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 attach CADisplayLink to NSRunLoop.mainRunLoop (or NSRunLoop.currentRunLoop on main thread) using NSRunLoopCommonModes to prevent rendering starvation during UI interaction and scrolling.

Engineers MUST ALWAYS attach CADisplayLink to NSRunLoop.mainRunLoop (or NSRunLoop.currentRunLoop on main thread) using NSRunLoopCommonModes to prevent rendering starvation during UI interaction and scrolling.

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 configure CAFrameRateRange (minimum, maximum, preferred) when initializing CADisplayLink on iOS 15+ to properly utilize 120Hz ProMotion screens without locking rendering to 60Hz.

Engineers MUST explicitly configure CAFrameRateRange (minimum, maximum, preferred) when initializing CADisplayLink on iOS 15+ to properly utilize 120Hz ProMotion screens without locking rendering to 60Hz.

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 rely on Kotlin Coroutines delay loops (e.g., delay(16)), Dispatchers.Main periodic polls, or NSTimer to schedule Skiko Metal redraw passes.

Engineers MUST NOT rely on Kotlin Coroutines delay loops (e.g., delay(16)), Dispatchers.Main periodic polls, or NSTimer to schedule Skiko Metal redraw passes.

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 calculate frame pacing and canvas delta times using CADisplayLink.targetTimestamp and CADisplayLink.timestamp rather than wall-clock time (NSDate / CACurrentMediaTime).

Code MUST calculate frame pacing and canvas delta times using CADisplayLink.targetTimestamp and CADisplayLink.timestamp rather than wall-clock time (NSDate / CACurrentMediaTime).

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 CAMetalLayer.nextDrawable() is acquired just-in-time prior to encoding render commands, and never hold drawable instances across VSync boundaries.

Services MUST ensure that CAMetalLayer.nextDrawable() is acquired just-in-time prior to encoding render commands, and never hold drawable instances across VSync 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Compose Multiplatform iOS CADisplayLink Metal VSync Synchronization critical for AI coding assistants?

Enforces strict synchronization between Skiko Metal render passes and Apple CADisplayLink hardware refresh boundaries on iOS. Prevents main-thread hitching, micro-stutter, and frame drops across variable refresh rate (VRR) ProMotion displays by aligning frame generation with target display presentation timestamps. 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 Loop or Unbounded Main Dispatcher CADisplayLink Triggering Skiko Redraws) 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