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

Compose Multiplatform iOS CAMetalLayer ProMotion Presentation Synchronization

Enforces strict temporal alignment between Kotlin Compose state dispatches, Skiko render passes, and Apple Metal presentation deadlines. Prevents main-thread hitching and buffer-swap tearing on 120Hz ProMotion displays by coupling CADisplayLink frame pacing directly to CAMetalDrawable acquisition.

Prohibited Anti-Pattern: Decoupled Coroutine State Mutations Causing VSYNC Drift and Metal Drawable Contention

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform iOS CAMetalLayer ProMotion Presentation Synchronization - Enforces strict temporal alignment between Kotlin Compose state dispatches, Skiko render passes, and Apple Metal presentation deadlines. Prevents main-thread hitching and buffer-swap tearing on 120Hz ProMotion displays by coupling CADisplayLink frame pacing directly to CAMetalDrawable acquisition.
globs: **/iosMain/**/*.kt, **/iosApp/**/*.swift, **/metal/**/*.kt, **/rendering/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-ios-metal-presentation-sync-guardrail"
---

# Compose Multiplatform iOS CAMetalLayer ProMotion Presentation Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Decoupled Coroutine State Mutations Causing VSYNC Drift and Metal Drawable Contention

## System Constraints
You are a Principal Mobile Architect specializing in Compose Multiplatform graphics sub-systems and Apple Metal engine integration. You mandate uncompromising enforcement of frame-presentation invariants on iOS ProMotion displays. You must eliminate all un-synchronized CADisplayLink executions, asynchronous off-thread CAMetalDrawable requests, and uncontrolled state mutation floods that induce hitching and tearing. All Skiko render phases must deterministically observe targetTimestamp budgets.

## Strict Guidelines
- Engineers MUST ALWAYS bind Compose UI state updates driving rendering to CADisplayLink callbacks with targetTimestamp budgeting, preventing multi-buffered state drift.
- Engineers MUST configure CAMetalLayer with maximumDrawableCount set to 3 (triple buffering) and displaySyncEnabled = true on ProMotion displays.
- Engineers MUST NOT invoke CAMetalDrawable acquisition (`nextDrawable()`) synchronously on the Kotlin Main dispatcher without a bounded wait timeout or frame budget check.
- Engineers MUST ensure Kotlin Coroutine dispatchers driving visual state (e.g., animations) consume the platform's MonotonicFrameClock tied to iOS CADisplayLink rather than standard Dispatchers.Default.
- Render pipelines MUST invoke `present(afterMinimumDuration:)` or `present(atTime:)` to schedule the presentation time against the exact display link target timestamp instead of calling immediate un-timed `present()`.
- Engineers MUST NOT dispatch uncontrolled recompositions across multiple independent coroutine contexts within the same 8.33ms (120Hz) frame window.

## Bad vs Good Implementations
### ProMotion-Aware Metal Layer Frame Synchronization in Swift / Kotlin Interop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to set CAFrameRateRange causes the CADisplayLink to miss dynamic ProMotion adjustments (24Hz-120Hz). Calling nextDrawable() directly without synchronization blocks the main run loop when all drawables are in-flight, inducing 8.33ms hitch spikes. Using immediate present() causes frame tearing.
```swift
// Anti-Pattern: Unsynchronized display loop and un-timed drawable presentation
import MetalKit
import QuartzCore

class UnsynchronizedMetalView: UIView {
    var metalLayer: CAMetalLayer! { layer as? CAMetalLayer }
    var displayLink: CADisplayLink?

    func startRenderLoop() {
        displayLink = CADisplayLink(target: self, selector: #selector(render))
        // Flaw: No frame rate range configured; default CADisplayLink drifts on ProMotion
        displayLink?.add(to: .main, forMode: .common)
    }

    @objc func render() {
        // Flaw: Synchronous unbudgeted nextDrawable blocks the main thread
        guard let drawable = metalLayer.nextDrawable() else {
            return
        }
        
        // Arbitrary state emission triggers out-of-order Kotlin Compose draw pass
        ComposeBridge.triggerDrawPass()
        
        let commandBuffer = CommandQueue.makeCommandBuffer()!
        // Flaw: Immediate present ignores display refresh interval, causing frame tearing
        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly sets triple buffering and CAFrameRateRange (60-120Hz) for ProMotion displays. Feeds Compose the exact CADisplayLink target timestamp via MonotonicFrameClock, and anchors Metal presentation to `present(drawable, atTime: targetTime)` to guarantee tear-free frame delivery.
```swift
// Production Invariant: Synchronized triple-buffered presentation with explicit frame pacing
import MetalKit
import QuartzCore

final class SynchronizedMetalPresentationView: UIView {
    override static var layerClass: AnyClass { CAMetalLayer.self }
    var metalLayer: CAMetalLayer { layer as! CAMetalLayer }
    private var displayLink: CADisplayLink?

    func configurePresentationEngine() {
        metalLayer.maximumDrawableCount = 3
        metalLayer.presentsWithTransaction = false
        metalLayer.displaySyncEnabled = true
        metalLayer.pixelFormat = .bgra8Unorm

        displayLink = CADisplayLink(target: self, selector: #selector(handleVSync(_:)))
        // Enforce smooth dynamic ProMotion rates from 60Hz to 120Hz
        displayLink?.preferredFrameRateRange = CAFrameRateRange(minimum: 60.0, maximum: 120.0, preferred: 120.0)
        displayLink?.add(to: .main, forMode: .common)
    }

    @objc private func handleVSync(_ link: CADisplayLink) {
        let targetTime = link.targetTimestamp
        
        // Propagate precise frame clock timestamp to Compose Multiplatform Runtime
        ComposePlatformFrameClock.shared.dispatchFrame(timestamp: targetTime)
        
        guard let drawable = metalLayer.nextDrawable() else {
            // Gracefully drop frame buffer without blocking if GPU pipeline is backpressured
            return
        }

        let commandBuffer = CommandQueue.makeCommandBuffer()!
        // Deterministic synchronization: schedule drawable presentation at CADisplayLink deadline
        commandBuffer.present(drawable, atTime: targetTime)
        commandBuffer.commit()
    }
}
```

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 CAMetalLayer ProMotion Presentation Synchronization

Compose Multiplatform iOS CAMetalLayer ProMotion Presentation Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces strict temporal alignment between Kotlin Compose state dispatches, Skiko render passes, and Apple Metal presentation deadlines. Prevents main-thread hitching and buffer-swap tearing on 120Hz ProMotion displays by coupling CADisplayLink frame pacing directly to CAMetalDrawable acquisition. 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 Coroutine State Mutations Causing VSYNC Drift and Metal Drawable Contention 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 Coroutine State Mutations Causing VSYNC Drift and Metal Drawable ContentionCritical
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 Compose UI state updates driving rendering to CADisplayLink callbacks with targetTimestamp budgeting, preventing multi-buffered state drift.

Engineers MUST ALWAYS bind Compose UI state updates driving rendering to CADisplayLink callbacks with targetTimestamp budgeting, preventing multi-buffered state drift.

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 CAMetalLayer with maximumDrawableCount set to 3 (triple buffering) and displaySyncEnabled = true on ProMotion displays.

Engineers MUST configure CAMetalLayer with maximumDrawableCount set to 3 (triple buffering) and displaySyncEnabled = true on ProMotion displays.

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 CAMetalDrawable acquisition (`nextDrawable()`) synchronously on the Kotlin Main dispatcher without a bounded wait timeout or frame budget check.

Engineers MUST NOT invoke CAMetalDrawable acquisition (`nextDrawable()`) synchronously on the Kotlin Main dispatcher without a bounded wait timeout or frame budget check.

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 ensure Kotlin Coroutine dispatchers driving visual state (e.g., animations) consume the platform's MonotonicFrameClock tied to iOS CADisplayLink rather than standard Dispatchers.Default.

Engineers MUST ensure Kotlin Coroutine dispatchers driving visual state (e.g., animations) consume the platform's MonotonicFrameClock tied to iOS CADisplayLink rather than standard Dispatchers.Default.

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

Render pipelines MUST invoke `present(afterMinimumDuration

Render pipelines MUST invoke `present(afterMinimumDuration:)` or `present(atTime:)` to schedule the presentation time against the exact display link target timestamp instead of calling immediate un-timed `present()`.

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

Engineers MUST NOT dispatch uncontrolled recompositions across multiple independent coroutine contexts within the same 8.33ms (120Hz) frame window.

Engineers MUST NOT dispatch uncontrolled recompositions across multiple independent coroutine contexts within the same 8.33ms (120Hz) frame window.

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 CAMetalLayer ProMotion Presentation Synchronization critical for AI coding assistants?

Enforces strict temporal alignment between Kotlin Compose state dispatches, Skiko render passes, and Apple Metal presentation deadlines. Prevents main-thread hitching and buffer-swap tearing on 120Hz ProMotion displays by coupling CADisplayLink frame pacing directly to CAMetalDrawable acquisition. 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 Coroutine State Mutations Causing VSYNC Drift and Metal Drawable Contention) 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