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

Compose Multiplatform iOS Metal Layer & CADisplayLink Synchronization Standard

Enforces deterministic frame pacing and double/triple-buffered Metal texture presentation between Kotlin Native rendering loops and CADisplayLink. Prohibits blocking the main thread during CAMetalDrawable acquisition and mandates backpressure bounds to eliminate VSync deadline misses and frame hitches.

Prohibited Anti-Pattern: Unbounded Main-Thread CAMetalDrawable Blocking & Asynchronous Kotlin Draw Loop Race

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform iOS Metal Layer & CADisplayLink Synchronization Standard - Enforces deterministic frame pacing and double/triple-buffered Metal texture presentation between Kotlin Native rendering loops and CADisplayLink. Prohibits blocking the main thread during CAMetalDrawable acquisition and mandates backpressure bounds to eliminate VSync deadline misses and frame hitches.
globs: **/iosApp/**/*.{swift,m,mm}, **/shared/src/iosMain/**/*.{kt,swift}, **/compose-ui/src/iosMain/**/*.{kt,swift}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-ios-metal-displaylink-sync-standard"
---

# Compose Multiplatform iOS Metal Layer & CADisplayLink Synchronization Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Main-Thread CAMetalDrawable Blocking & Asynchronous Kotlin Draw Loop Race

## System Constraints
You are a Principal Mobile Graphics Architect enforcing strict Metal layer frame pacing and CADisplayLink synchronization for Compose Multiplatform on iOS. Your mandate is to prevent UI hitching, eliminate main-thread stalls caused by nextDrawable() contention, and enforce asynchronous frame completion accounting.

## Strict Guidelines
- Engineers MUST ALWAYS synchronize Kotlin Native recomposition and layout commits with CADisplayLink target timestamps to maintain exact VSync alignment.
- Engineers MUST NEVER synchronously invoke `CAMetalLayer.nextDrawable()` on the main thread while holding open Compose transaction locks or active rendering locks.
- Code MUST employ a bounded DispatchSemaphore (maximum 2 or 3 in-flight frames) signaled exclusively inside Metal command buffer `addCompletedHandler` blocks to apply render backpressure.
- Engineers MUST explicitly set `CAMetalLayer.presentsWithTransaction = false` unless orchestrating UIKit frame-synchronized transitions.
- Components NEVER execute raw Skia canvas draw calls directly inside CADisplayLink callbacks without checking for command buffer pool readiness.

## Bad vs Good Implementations
### Metal Layer Frame Synchronization & Bounded Backpressure

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling `metalLayer.nextDrawable()` on the main thread blocks CPU execution until a free drawable is available from the compositor. When the GPU is under load, this causes CADisplayLink deadline misses, skipping entire frames and inducing critical hitching.
```swift
// BAD: Synchronously acquiring CAMetalDrawable on main thread inside CADisplayLink
// Causes main-thread hitching whenever the GPU is saturated or Compose recomposition stalls
class UnsynchronizedComposeView: UIView {
    var displayLink: CADisplayLink?
    var metalLayer: CAMetalLayer { layer as! CAMetalLayer }

    override static var layerClass: AnyClass { CAMetalLayer.self }

    func startRenderLoop() {
        displayLink = CADisplayLink(target: self, selector: #selector(renderFrame))
        displayLink?.add(to: .main, forMode: .common)
    }

    @objc private func renderFrame() {
        // Synchronously blocks main thread if next drawable is unavailable (GPU bound)
        guard let drawable = metalLayer.nextDrawable() else { return }
        
        // Direct call to Kotlin Compose render engine on the main thread
        ComposeBridge.render(into: drawable.texture)
        
        let commandBuffer = metalLayer.device!.makeCommandQueue()!.makeCommandBuffer()!
        commandBuffer.present(drawable)
        commandBuffer.commit()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Implements double/triple-buffering using a DispatchSemaphore to throttle in-flight frames without blocking the main run loop. Drops incoming VSync triggers non-destructively when the GPU is saturated, uses explicit presentation timestamps (`atTime: link.targetTimestamp`), and deallocates drawables safely via `addCompletedHandler`.
```swift
// GOOD: Bounded in-flight frame tracking with semaphore and scheduled presentation
final class SynchronizedComposeView: UIView {
    private var displayLink: CADisplayLink?
    private var commandQueue: MTLCommandQueue?
    private let inFlightSemaphore = DispatchSemaphore(value: 3) // Triple-buffering
    
    var metalLayer: CAMetalLayer { layer as! CAMetalLayer }
    override static var layerClass: AnyClass { CAMetalLayer.self }

    func setupMetal(device: MTLDevice) {
        metalLayer.device = device
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.framebufferOnly = true
        metalLayer.presentsWithTransaction = false
        self.commandQueue = device.makeCommandQueue()
        
        displayLink = CADisplayLink(target: self, selector: #selector(onDisplayLink(_:)))
        displayLink?.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: 120, preferred: 120)
        displayLink?.add(to: .main, forMode: .common)
    }

    @objc private func onDisplayLink(_ link: CADisplayLink) {
        // Non-blocking attempt to acquire pipeline slot
        guard inFlightSemaphore.wait(timeout: .now()) == .success else {
            // Drop frame gracefully if GPU is running behind; prevents main thread freeze
            return
        }

        guard let queue = commandQueue,
              let drawable = metalLayer.nextDrawable(),
              let commandBuffer = queue.makeCommandBuffer() else {
            inFlightSemaphore.signal()
            return
        }

        commandBuffer.addCompletedHandler { [weak self] _ in
            self?.inFlightSemaphore.signal()
        }

        // Target presentation time matches VSync deadline
        commandBuffer.present(drawable, atTime: link.targetTimestamp)
        
        // Dispatch Kotlin Skia rendering with valid pipeline lock
        ComposeBridge.render(to: drawable.texture, commandBuffer: commandBuffer)
        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 Metal Layer & CADisplayLink Synchronization Standard

Compose Multiplatform iOS Metal Layer & CADisplayLink Synchronization Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic frame pacing and double/triple-buffered Metal texture presentation between Kotlin Native rendering loops and CADisplayLink. Prohibits blocking the main thread during CAMetalDrawable acquisition and mandates backpressure bounds to eliminate VSync deadline misses and frame hitches. 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: Unbounded Main-Thread CAMetalDrawable Blocking & Asynchronous Kotlin Draw Loop Race 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 DriftUnbounded Main-Thread CAMetalDrawable Blocking & Asynchronous Kotlin Draw Loop RaceCritical
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 synchronize Kotlin Native recomposition and layout commits with CADisplayLink target timestamps to maintain exact VSync alignment.

Engineers MUST ALWAYS synchronize Kotlin Native recomposition and layout commits with CADisplayLink target timestamps to maintain exact VSync alignment.

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 synchronously invoke `CAMetalLayer.nextDrawable()` on the main thread while holding open Compose transaction locks or active rendering locks.

Engineers MUST NEVER synchronously invoke `CAMetalLayer.nextDrawable()` on the main thread while holding open Compose transaction locks or active rendering locks.

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 employ a bounded DispatchSemaphore (maximum 2 or 3 in-flight frames) signaled exclusively inside Metal command buffer `addCompletedHandler` blocks to apply render backpressure.

Code MUST employ a bounded DispatchSemaphore (maximum 2 or 3 in-flight frames) signaled exclusively inside Metal command buffer `addCompletedHandler` blocks to apply render backpressure.

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 explicitly set `CAMetalLayer.presentsWithTransaction = false` unless orchestrating UIKit frame-synchronized transitions.

Engineers MUST explicitly set `CAMetalLayer.presentsWithTransaction = false` unless orchestrating UIKit frame-synchronized transitions.

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 execute raw Skia canvas draw calls directly inside CADisplayLink callbacks without checking for command buffer pool readiness.

Components NEVER execute raw Skia canvas draw calls directly inside CADisplayLink callbacks without checking for command buffer pool readiness.

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

Enforces deterministic frame pacing and double/triple-buffered Metal texture presentation between Kotlin Native rendering loops and CADisplayLink. Prohibits blocking the main thread during CAMetalDrawable acquisition and mandates backpressure bounds to eliminate VSync deadline misses and frame hitches. 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 (Unbounded Main-Thread CAMetalDrawable Blocking & Asynchronous Kotlin Draw Loop Race) 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