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

Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail

Enforces hardware-aligned vsync tick dispatching across iOS CADisplayLink and Android Choreographer within Compose Multiplatform Skiko render pipelines. Mandates explicit monotonic frame-clock binding to prevent coroutine-based delay drift, phase jitter, and double-buffering tearing. Eliminates non-deterministic render cycles by locking Skia Canvas flushes strictly to hardware display refresh intervals.

Prohibited Anti-Pattern: Synthetic Coroutine Delay Pacing Bypassing Hardware VSync Clocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail - Enforces hardware-aligned vsync tick dispatching across iOS CADisplayLink and Android Choreographer within Compose Multiplatform Skiko render pipelines. Mandates explicit monotonic frame-clock binding to prevent coroutine-based delay drift, phase jitter, and double-buffering tearing. Eliminates non-deterministic render cycles by locking Skia Canvas flushes strictly to hardware display refresh intervals.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt, **/skiko/**/*.kt, **/render/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-vsync-renderloop-sync-guardrail"
---

# Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Synthetic Coroutine Delay Pacing Bypassing Hardware VSync Clocks

## System Constraints
You are a Principal Mobile Graphics and Systems Architect enforcing strict VSync alignment across Compose Multiplatform (KMP) and Skiko rendering targets. You prohibit synthetic frame pacing loops (such as coroutine delay(16) or unanchored ScheduledExecutorService ticks) and mandate direct hardware vsync clock synchronization using CADisplayLink on iOS and Choreographer on Android to drive MonotonicFrameClock.

## Strict Guidelines
- Engineers MUST ALWAYS anchor Compose Multiplatform MonotonicFrameClock implementations directly to platform hardware vsync callbacks: Choreographer.FrameCallback on Android and CADisplayLink on iOS.
- Engineers MUST NOT utilize coroutine-based timers, Thread.sleep, or delay(16L) to emulate display refresh ticks or drive SkiaLayer redraw dispatching.
- Code MUST normalize platform vsync timestamps to nanosecond precision monotonically (using Choreographer frameTimeNanos on Android and CADisplayLink.targetTimestamp converted via mach_absolute_time / CACurrentMediaTime on iOS).
- Services MUST route dirty canvas redraw signals through an invalidation latch that schedules exactly one platform frame callback instead of posting immediate or synchronous SkiaLayer.needRedraw() invocations.
- Components NEVER drop or skip frame synchronization registration without cleaning up native platform hooks (e.g., calling CADisplayLink.invalidate() or Choreographer.removeFrameCallback) to avoid display pipeline resource leaks and thread starvation.

## Bad vs Good Implementations
### Hardware VSync Frame Pacing Synchronization in KMP Skiko

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using delay(16L) disregards variable hardware refresh rates (e.g., ProMotion 120Hz, 90Hz, or dynamic frame pacing) and accumulates time-slice drift against display hardware refresh boundaries, leading to frame judder, missed presentations, and buffer tearing.
```kotlin
// BAD: Synthetic coroutine-based delay loop drives rendering, drifting out of phase with VSync
class SyntheticFrameClock : MonotonicFrameClock {
    override suspend fun <R> withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R {
        // Unsynchronized sleep accumulates drift and causes tearing or dropped frames
        kotlinx.coroutines.delay(16L)
        val syntheticNanos = System.nanoTime()
        return onFrame(syntheticNanos)
    }
}

fun triggerRedraw(skiaLayer: org.jetbrains.skiko.SkiaLayer) {
    // Spams immediate redraws bypasses hardware latching
    skiaLayer.needRedraw()
}
```

#### Production Standard (Correct)
> **Standard**: Anchoring directly to CADisplayLink (and Choreographer on Android) aligns frame synthesis precisely to the device's presentation refresh cycle, supports dynamic ProMotion/high-refresh rates natively, and guarantees drift-free, zero-tear Skia composition.
```kotlin
// GOOD: Hardware-anchored MonotonicFrameClock driven by platform VSync primitives
// iosMain
import platform.QuartzCore.CADisplayLink
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import androidx.compose.runtime.MonotonicFrameClock
import kotlin.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

class IosHardwareVsyncFrameClock : MonotonicFrameClock {
    override suspend fun <R> withFrameNanos(onFrame: (frameTimeNanos: Long) -> R): R {
        return suspendCancellableCoroutine { continuation ->
            val displayLink = CADisplayLink.displayLinkWithTarget(
                target = object : platform.darwin.NSObject() {
                    @Suppress("UNUSED_PARAMETER")
                    fun onVsync(link: CADisplayLink) {
                        link.invalidate()
                        val frameNanos = (link.targetTimestamp * 1_000_000_000.0).toLong()
                        continuation.resume(runCatching { onFrame(frameNanos) })
                    }
                },
                selector = platform.objc.NSSelectorFromString("onVsync:")
            )
            displayLink.addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
            continuation.invokeOnCancellation { displayLink.invalidate() }
        }.getOrThrow()
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail

Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces hardware-aligned vsync tick dispatching across iOS CADisplayLink and Android Choreographer within Compose Multiplatform Skiko render pipelines. Mandates explicit monotonic frame-clock binding to prevent coroutine-based delay drift, phase jitter, and double-buffering tearing. Eliminates non-deterministic render cycles by locking Skia Canvas flushes strictly to hardware display refresh intervals. 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: Synthetic Coroutine Delay Pacing Bypassing Hardware VSync Clocks 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 DriftSynthetic Coroutine Delay Pacing Bypassing Hardware VSync ClocksCritical
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 anchor Compose Multiplatform MonotonicFrameClock implementations directly to platform hardware vsync callbacks

Engineers MUST ALWAYS anchor Compose Multiplatform MonotonicFrameClock implementations directly to platform hardware vsync callbacks: Choreographer.FrameCallback on Android and CADisplayLink on iOS.

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 utilize coroutine-based timers, Thread.sleep, or delay(16L) to emulate display refresh ticks or drive SkiaLayer redraw dispatching.

Engineers MUST NOT utilize coroutine-based timers, Thread.sleep, or delay(16L) to emulate display refresh ticks or drive SkiaLayer redraw dispatching.

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 normalize platform vsync timestamps to nanosecond precision monotonically (using Choreographer frameTimeNanos on Android and CADisplayLink.targetTimestamp converted via mach_absolute_time / CACurrentMediaTime on iOS).

Code MUST normalize platform vsync timestamps to nanosecond precision monotonically (using Choreographer frameTimeNanos on Android and CADisplayLink.targetTimestamp converted via mach_absolute_time / CACurrentMediaTime on iOS).

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

Services MUST route dirty canvas redraw signals through an invalidation latch that schedules exactly one platform frame callback instead of posting immediate or synchronous SkiaLayer.needRedraw() invocations.

Services MUST route dirty canvas redraw signals through an invalidation latch that schedules exactly one platform frame callback instead of posting immediate or synchronous SkiaLayer.needRedraw() invocations.

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 drop or skip frame synchronization registration without cleaning up native platform hooks (e.g., calling CADisplayLink.invalidate() or Choreographer.removeFrameCallback) to avoid display pipeline resource leaks and thread starvation.

Components NEVER drop or skip frame synchronization registration without cleaning up native platform hooks (e.g., calling CADisplayLink.invalidate() or Choreographer.removeFrameCallback) to avoid display pipeline resource leaks and thread 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 Deterministic Skiko RenderLoop Hardware VSync Synchronization Guardrail critical for AI coding assistants?

Enforces hardware-aligned vsync tick dispatching across iOS CADisplayLink and Android Choreographer within Compose Multiplatform Skiko render pipelines. Mandates explicit monotonic frame-clock binding to prevent coroutine-based delay drift, phase jitter, and double-buffering tearing. Eliminates non-deterministic render cycles by locking Skia Canvas flushes strictly to hardware display refresh intervals. 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 (Synthetic Coroutine Delay Pacing Bypassing Hardware VSync Clocks) 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

Deterministic