This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: compose-multiplatform-skiko-displaylink-vsync-invariant

Compose Multiplatform Skiko CADisplayLink VSync Frame Pacing Invariant

Enforces strict synchronization between iOS CADisplayLink callbacks and Skiko rendering pipelines on ProMotion displays. Prevents compositor thread contention, tearing, and micro-stutter by binding Skia Metal draw passes directly to native display refresh cycles with explicit CAFrameRateRange parameters.

Prohibited Anti-Pattern: Decoupled Timer-Driven or Asynchronous Redraw Invocations Causing Metal Compositor Stalls

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko CADisplayLink VSync Frame Pacing Invariant - Enforces strict synchronization between iOS CADisplayLink callbacks and Skiko rendering pipelines on ProMotion displays. Prevents compositor thread contention, tearing, and micro-stutter by binding Skia Metal draw passes directly to native display refresh cycles with explicit CAFrameRateRange parameters.
globs: **/iosMain/**/*.kt, **/*Skiko*.kt, **/*ViewController*.kt, **/*ViewAdapter*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-displaylink-vsync-invariant"
---

# Compose Multiplatform Skiko CADisplayLink VSync Frame Pacing Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Decoupled Timer-Driven or Asynchronous Redraw Invocations Causing Metal Compositor Stalls

## System Constraints
You are a Principal Mobile Architect enforcing strict VSync alignment between Apple's CoreAnimation pipeline and Compose Multiplatform's Skiko rendering engine. Mandate that CADisplayLink drives the Skiko frame clock without intermediate decoupled timers, ensure dynamic CAFrameRateRange configuration for ProMotion displays, and enforce thread affinity for all Skia-to-Metal command buffer commits.

## Strict Guidelines
- Engineers MUST ALWAYS schedule CADisplayLink on NSRunLoop.mainRunLoop with NSRunLoopCommonModes to ensure continuous rendering during user touch tracking and gesture recognizer evaluation.
- Engineers MUST configure CAFrameRateRange (minimum, preferred, maximum) explicitly for ProMotion hardware to avoid iOS system-level downclocking of the Metal drawable presentation to 60Hz.
- Engineers MUST NOT invoke SkikoView.needRedraw() or trigger direct render passes via NSTimer, DispatchSourceTimer, or unaligned coroutines in iosMain.
- Code SHOULD propagate CADisplayLink.targetTimestamp into the Compose MonotonicFrameClock to align Compose recomposition and animation velocity with the exact physical screen refresh interval.
- Services MUST ensure that Skia GPU context flushes and MTLCommandBuffer presentations execute strictly on the CADisplayLink invocation thread without blocking the main RunLoop or creating lock inversion with CoreAnimation.
- Components NEVER instantiate duplicate or unmanaged CADisplayLink loops across nested Compose UI view controllers or offscreen render targets.

## Bad vs Good Implementations
### Decoupled Coroutine Timer vs. CADisplayLink ProMotion Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using an asynchronous coroutine delay completely decouples frame generation from the hardware VSync cycle. On 120Hz ProMotion screens, this causes severe micro-stutter, duplicate or missed frames, and Metal compositor queue backpressure.
```kotlin
import kotlinx.coroutines.*
import org.jetbrains.skiko.SkiaLayer

// ANTI-PATTERN: Decoupled coroutine timer driving Skiko renders.
// Causes frame drops, jitter on 120Hz ProMotion screens, and command buffer starvation.
class BadSkikoRenderer(private val skiaLayer: SkiaLayer) {
    private val scope = CoroutineScope(Dispatchers.Main)
    private var isRunning = false

    fun start() {
        isRunning = true
        scope.launch {
            while (isRunning) {
                // Arbitrary 60FPS delay; completely desynchronized from CADisplayLink phase
                delay(16L)
                skiaLayer.needRedraw()
            }
        }
    }

    fun stop() {
        isRunning = false
        scope.cancel()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Attaches a native CADisplayLink directly to NSRunLoopCommonModes, ensuring frames render fluidly during user interactions. Configures CAFrameRateRange to unlock 120Hz ProMotion and synchronizes the Skiko redraw trigger directly to the hardware VSync.
```kotlin
import platform.QuartzCore.*
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import platform.darwin.NSObject
import org.jetbrains.skiko.SkiaLayer
import kotlinx.cinterop.ExportObjCClass
import kotlinx.cinterop.ObjCAction

// PRODUCTION INVARIANT: Native CADisplayLink driving SkiaLayer VSync with ProMotion bounds
@ExportObjCClass
class ProductionSkikoFrameSync(
    private val skiaLayer: SkiaLayer
) : NSObject() {
    private var displayLink: CADisplayLink? = null

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

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

        // Explicitly set dynamic refresh rate range for 120Hz ProMotion displays
        link.preferredFrameRateRange = CAFrameRateRangeMake(
            minimum = 60.0f,
            maximum = 120.0f,
            __preferred = 120.0f
        )

        // Bind to common modes to sustain animation through scrolling/tracking
        link.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
        displayLink = link
    }

    @ObjCAction
    fun onDisplayLinkStep(link: CADisplayLink) {
        // Invariant: Native VSync phase alignment directly schedules the Skiko redraw pass
        skiaLayer.needRedraw()
    }

    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 CADisplayLink VSync Frame Pacing Invariant

Compose Multiplatform Skiko CADisplayLink VSync Frame Pacing Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization between iOS CADisplayLink callbacks and Skiko rendering pipelines on ProMotion displays. Prevents compositor thread contention, tearing, and micro-stutter by binding Skia Metal draw passes directly to native display refresh cycles with explicit CAFrameRateRange parameters. 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: Decoupled Timer-Driven or Asynchronous Redraw Invocations Causing Metal Compositor Stalls 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 DriftDecoupled Timer-Driven or Asynchronous Redraw Invocations Causing Metal Compositor StallsCritical
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 ensure continuous rendering during user touch tracking and gesture recognizer evaluation.

Engineers MUST ALWAYS schedule CADisplayLink on NSRunLoop.mainRunLoop with NSRunLoopCommonModes to ensure continuous rendering during user touch tracking and gesture recognizer evaluation.

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 configure CAFrameRateRange (minimum, preferred, maximum) explicitly for ProMotion hardware to avoid iOS system-level downclocking of the Metal drawable presentation to 60Hz.

Engineers MUST configure CAFrameRateRange (minimum, preferred, maximum) explicitly for ProMotion hardware to avoid iOS system-level downclocking of the Metal drawable presentation 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 invoke SkikoView.needRedraw() or trigger direct render passes via NSTimer, DispatchSourceTimer, or unaligned coroutines in iosMain.

Engineers MUST NOT invoke SkikoView.needRedraw() or trigger direct render passes via NSTimer, DispatchSourceTimer, or unaligned coroutines in iosMain.

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 SHOULD propagate CADisplayLink.targetTimestamp into the Compose MonotonicFrameClock to align Compose recomposition and animation velocity with the exact physical screen refresh interval.

Code SHOULD propagate CADisplayLink.targetTimestamp into the Compose MonotonicFrameClock to align Compose recomposition and animation velocity with the exact physical screen refresh interval.

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 Skia GPU context flushes and MTLCommandBuffer presentations execute strictly on the CADisplayLink invocation thread without blocking the main RunLoop or creating lock inversion with CoreAnimation.

Services MUST ensure that Skia GPU context flushes and MTLCommandBuffer presentations execute strictly on the CADisplayLink invocation thread without blocking the main RunLoop or creating lock inversion with CoreAnimation.

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.
6

Components NEVER instantiate duplicate or unmanaged CADisplayLink loops across nested Compose UI view controllers or offscreen render targets.

Components NEVER instantiate duplicate or unmanaged CADisplayLink loops across nested Compose UI view controllers or offscreen render targets.

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 CADisplayLink VSync Frame Pacing Invariant critical for AI coding assistants?

Enforces strict synchronization between iOS CADisplayLink callbacks and Skiko rendering pipelines on ProMotion displays. Prevents compositor thread contention, tearing, and micro-stutter by binding Skia Metal draw passes directly to native display refresh cycles with explicit CAFrameRateRange parameters. 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 (Decoupled Timer-Driven or Asynchronous Redraw Invocations Causing Metal Compositor Stalls) 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