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

Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant

Enforces deterministic frame pacing across platforms by binding Compose Multiplatform custom render loops and animation drivers directly to platform hardware VSync primitives. Disallows decoupled coroutine clocks and non-vsync periodic timers to guarantee zero frame-drift and jitter-free 120Hz ProMotion (iOS CADisplayLink) and Smooth Display (Android Choreographer) synchronization.

Prohibited Anti-Pattern: Decoupled Wall-Clock Frame Dispatch Causing Display Jitter and Dropped VSync Cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant - Enforces deterministic frame pacing across platforms by binding Compose Multiplatform custom render loops and animation drivers directly to platform hardware VSync primitives. Disallows decoupled coroutine clocks and non-vsync periodic timers to guarantee zero frame-drift and jitter-free 120Hz ProMotion (iOS CADisplayLink) and Smooth Display (Android Choreographer) synchronization.
globs: **/commonMain/**/animation/**/*.kt, **/commonMain/**/graphics/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt, **/compose/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-hardware-vsync-pacing-guardrail"
---

# Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Decoupled Wall-Clock Frame Dispatch Causing Display Jitter and Dropped VSync Cycles

## System Constraints
You are a Principal Mobile Architect enforcing hardware-synchronized rendering pipelines in Kotlin Multiplatform (KMP) Compose applications. You must prevent animation clock drift, micro-stutter, and torn frame boundaries by mandating that all frame timing passes derive directly from iOS CADisplayLink and Android Choreographer hardware interrupts. Disallow reliance on decoupled coroutine delays, arbitrary system monotonic timers, or unsynchronized platform dispatchers for rendering passes.

## Strict Guidelines
- Engineers MUST ALWAYS drive custom animation frame pulses and canvas draw passes using Android's Choreographer.postFrameCallback and iOS's CADisplayLink with preferredFrameRateRange configured up to 120Hz.
- Engineers MUST NOT rely on kotlinx.coroutines.delay, fixed-interval ticker channels, or Thread.sleep to schedule frame steps or synthetic display refreshes.
- Custom MonotonicFrameClock implementations MUST propagate the actual hardware timestamp (nanoseconds) delivered by the platform VSync callback rather than calling System.nanoTime() or Clock.System.now() at execution time.
- iOS Compose integration code MUST set CADisplayLink.preferredFrameRateRange to CAFrameRateRangeMake(minimum = 60f, maximum = 120f, preferred = 120f) on ProMotion-capable displays, binding to NSRunLoop.mainRunLoop in NSRunLoopCommonModes.
- Android MonotonicFrameClock bridges MUST post callbacks via Choreographer.getInstance().postFrameCallback and handle choreographer re-registration strictly on the Main thread to eliminate dropped frames during choreographer queue starvation.

## Bad vs Good Implementations
### Hardware-Synchronized Custom VSync MonotonicFrameClock across iOS and Android

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using kotlinx.coroutines.delay introduces wall-clock scheduling jitter, accumulates phase-drift against hardware rasterization, and fails to adapt dynamically to 60Hz/90Hz/120Hz ProMotion variable refresh rates.
```kotlin
// Anti-pattern: Coroutine-driven synthetic clock decoupled from hardware VSync
package com.example.rendering

import androidx.compose.runtime.MonotonicFrameClock
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.milliseconds

class SyntheticFrameClock : MonotonicFrameClock {
    override suspend fun <R> withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R {
        // Defect: delay(8) drifts relative to actual display hardware refreshes (e.g. 120Hz = 8.33ms)
        // Causes phase mismatch with display scanout, micro-stutter, and missed vsync deadlines.
        delay(8.milliseconds)
        val syntheticNanos = kotlin.system.getTimeNanos()
        return onFrame(syntheticNanos)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Delegates tick delivery strictly to hardware VSync interrupts via expect/actual pacer abstractions. For iOS, CADisplayLink locks into ProMotion refresh intervals (up to 120Hz), while Android binds directly to Choreographer's hardware frame pulses.
```kotlin
// Production standard: Hardware-driven VSync clock binding CADisplayLink / Choreographer
package com.example.rendering

import androidx.compose.runtime.MonotonicFrameClock
import kotlin.coroutines.suspendCoroutine
import kotlin.coroutines.resume

expect class PlatformVsyncPacer() {
    fun requestFrame(callback: (frameTimeNanos: Long) -> Unit)
}

class HardwareVsyncMonotonicClock(
    private val pacer: PlatformVsyncPacer
) : MonotonicFrameClock {
    override suspend fun <R> withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R {
        return suspendCoroutine { continuation ->
            pacer.requestFrame { hardwareNanos ->
                try {
                    val result = onFrame(hardwareNanos)
                    continuation.resume(result)
                } catch (t: Throwable) {
                    continuation.resumeWith(Result.failure(t))
                }
            }
        }
    }
}

// iOS implementation using CADisplayLink:
// val displayLink = CADisplayLink.displayLinkWithTarget(target, selector)
// displayLink.preferredFrameRateRange = CAFrameRateRangeMake(60.0f, 120.0f, 120.0f)
// displayLink.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant

Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic frame pacing across platforms by binding Compose Multiplatform custom render loops and animation drivers directly to platform hardware VSync primitives. Disallows decoupled coroutine clocks and non-vsync periodic timers to guarantee zero frame-drift and jitter-free 120Hz ProMotion (iOS CADisplayLink) and Smooth Display (Android Choreographer) synchronization. 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 Wall-Clock Frame Dispatch Causing Display Jitter and Dropped VSync Cycles 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 Wall-Clock Frame Dispatch Causing Display Jitter and Dropped VSync CyclesCritical
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 drive custom animation frame pulses and canvas draw passes using Android's Choreographer.postFrameCallback and iOS's CADisplayLink with preferredFrameRateRange configured up to 120Hz.

Engineers MUST ALWAYS drive custom animation frame pulses and canvas draw passes using Android's Choreographer.postFrameCallback and iOS's CADisplayLink with preferredFrameRateRange configured up to 120Hz.

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 NOT rely on kotlinx.coroutines.delay, fixed-interval ticker channels, or Thread.sleep to schedule frame steps or synthetic display refreshes.

Engineers MUST NOT rely on kotlinx.coroutines.delay, fixed-interval ticker channels, or Thread.sleep to schedule frame steps or synthetic display refreshes.

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

Custom MonotonicFrameClock implementations MUST propagate the actual hardware timestamp (nanoseconds) delivered by the platform VSync callback rather than calling System.nanoTime() or Clock.System.now() at execution time.

Custom MonotonicFrameClock implementations MUST propagate the actual hardware timestamp (nanoseconds) delivered by the platform VSync callback rather than calling System.nanoTime() or Clock.System.now() at execution time.

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

iOS Compose integration code MUST set CADisplayLink.preferredFrameRateRange to CAFrameRateRangeMake(minimum = 60f, maximum = 120f, preferred = 120f) on ProMotion-capable displays, binding to NSRunLoop.mainRunLoop in NSRunLoopCommonModes.

iOS Compose integration code MUST set CADisplayLink.preferredFrameRateRange to CAFrameRateRangeMake(minimum = 60f, maximum = 120f, preferred = 120f) on ProMotion-capable displays, binding to NSRunLoop.mainRunLoop in NSRunLoopCommonModes.

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

Android MonotonicFrameClock bridges MUST post callbacks via Choreographer.getInstance().postFrameCallback and handle choreographer re-registration strictly on the Main thread to eliminate dropped frames during choreographer queue starvation.

Android MonotonicFrameClock bridges MUST post callbacks via Choreographer.getInstance().postFrameCallback and handle choreographer re-registration strictly on the Main thread to eliminate dropped frames during choreographer queue starvation.

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 Kotlin Multiplatform Compose Hardware VSync Frame Pacing Invariant critical for AI coding assistants?

Enforces deterministic frame pacing across platforms by binding Compose Multiplatform custom render loops and animation drivers directly to platform hardware VSync primitives. Disallows decoupled coroutine clocks and non-vsync periodic timers to guarantee zero frame-drift and jitter-free 120Hz ProMotion (iOS CADisplayLink) and Smooth Display (Android Choreographer) synchronization. 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 Wall-Clock Frame Dispatch Causing Display Jitter and Dropped VSync Cycles) 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

Kotlin