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

Compose Multiplatform Skiko Render Loop & UI Thread Synchronization Guardrail

Enforces strict decoupling of Compose snapshot state mutations from Skiko GPU rasterization cycles across iOS, Desktop, and Android targets. Eliminates rendering thread deadlocks, CADisplayLink/Choreographer stalls, and VSync drops caused by synchronous state reconciliation or bridge blocking during Skia frame rendering.

Prohibited Anti-Pattern: Mutating Compose State or Invoking Synchronous Main Thread Dispatchers Inside Skiko Render Passes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Render Loop & UI Thread Synchronization Guardrail - Enforces strict decoupling of Compose snapshot state mutations from Skiko GPU rasterization cycles across iOS, Desktop, and Android targets. Eliminates rendering thread deadlocks, CADisplayLink/Choreographer stalls, and VSync drops caused by synchronous state reconciliation or bridge blocking during Skia frame rendering.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/desktopMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-render-loop-synchronization"
---

# Compose Multiplatform Skiko Render Loop & UI Thread Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating Compose State or Invoking Synchronous Main Thread Dispatchers Inside Skiko Render Passes

## System Constraints
You are a Principal Software Architect enforcing Compose Multiplatform and Skiko rendering engine invariants. Skiko interfaces directly with platform graphics layers (Metal on iOS/macOS, DirectX/Vulkan on Windows/Linux, and OpenGL/Vulkan on Android). You must prevent thread deadlocks, frame drops, and JNI/ObjC-bridge stalls caused by mixing UI snapshot reconciliation with Skiko hardware rasterization cycles.

## Strict Guidelines
- Engineers MUST ALWAYS isolate pure rendering commands from state mutation by computing drawing primitives before entering the Skiko/DrawScope rasterization phase.
- Engineers MUST NOT mutate Compose State (such as SnapshotState, MutableState, or StateFlow triggers) directly inside custom Skiko render callbacks, `DrawScope.drawIntoCanvas`, or `SkiaLayer.render`.
- Engineers MUST NOT invoke blocking thread primitives (`runBlocking`, `dispatch_sync`, mutex locks held across UI/Render boundaries) inside rendering delegates or platform canvas interop layers.
- Code SHOULD offload complex path computations, glyph shaping, and raster caching to background worker dispatchers (`Dispatchers.Default`), providing immutable render models to the draw phase.
- Components NEVER bridge synchronous platform-native events (e.g., iOS CADisplayLink, AppKit drawing callbacks) into synchronous Compose Snapshot state updates without queueing onto `Dispatchers.Main.immediate` asynchronously.

## Bad vs Good Implementations
### Decoupled Canvas Rendering vs Synchronous State Mutation in Render Pass

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating Compose state (`renderMetrics = ...`) inside the canvas draw phase causes snapshot invalidation during Skiko rasterization, triggering recursive layout/draw cycles and thread contention. Using `runBlocking` inside the rendering pipeline halts the VSync loop, causing dropped frames and potential UI/Render thread deadlocks.
```kotlin
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.nativeCanvas
import kotlinx.coroutines.runBlocking

// ANTI-PATTERN: Mutating Compose State and blocking render thread during Skiko draw pass
@Composable
fun FlawedSkikoCanvas(dataSource: NativeTelemetrySource) {
    var renderMetrics by remember { mutableStateOf(RenderMetrics.Empty) }
    
    androidx.compose.foundation.layout.Box(
        modifier = Modifier.drawBehind {
            drawIntoCanvas { canvas ->
                val nativeCanvas = canvas.nativeCanvas
                // CRITICAL: Synchronously blocking on another thread inside the render loop
                val telemetry = runBlocking { dataSource.fetchLatestFrameData() }
                
                // CRITICAL: Mutating Compose Snapshot state inside the draw pass forces immediate
                // invalidation during rasterization, causing recursive recomposition and deadlocks
                renderMetrics = RenderMetrics(fps = telemetry.fps, frameTime = telemetry.frameTime)
                
                nativeCanvas.drawCircle(100f, 100f, telemetry.radius, telemetry.paint)
            }
        }
    )
}
```

#### Production Standard (Correct)
> **Standard**: State acquisition and snapshot mutations are isolated to the coroutine layer via `produceState` on the main UI dispatcher. The `drawBehind` pass functions as a pure rasterization function referencing immutable data, completely freeing the Skiko render loop from locks, blocking JNI/bridge hops, and re-entrant invalidations.
```kotlin
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.nativeCanvas
import kotlinx.coroutines.flow.collectLatest

// PRODUCTION INVARIANT: Decoupled immutable state stream with pure drawing phase
@Immutable
data class FrameRenderState(val radius: Float, val paint: org.jetbrains.skia.Paint)

@Composable
fun DecoupledSkikoCanvas(dataSource: NativeTelemetrySource) {
    val renderState by produceState<FrameRenderState?>(initialValue = null, dataSource) {
        // Asynchronously poll or collect telemetry outside the render loop on the UI Dispatcher
        dataSource.telemetryFlow.collectLatest { telemetry ->
            value = FrameRenderState(radius = telemetry.radius, paint = telemetry.paint)
        }
    }

    androidx.compose.foundation.layout.Box(
        modifier = Modifier.drawBehind {
            val state = renderState ?: return@drawBehind
            drawIntoCanvas { canvas ->
                // PURE RENDER: Read precomputed immutable values directly. No snapshot mutations, no blocking calls.
                val nativeCanvas = canvas.nativeCanvas
                nativeCanvas.drawCircle(100f, 100f, state.radius, state.paint)
            }
        }
    )
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Skiko Render Loop & UI Thread Synchronization Guardrail

Compose Multiplatform Skiko Render Loop & UI Thread Synchronization Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict decoupling of Compose snapshot state mutations from Skiko GPU rasterization cycles across iOS, Desktop, and Android targets. Eliminates rendering thread deadlocks, CADisplayLink/Choreographer stalls, and VSync drops caused by synchronous state reconciliation or bridge blocking during Skia frame rendering. 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: Mutating Compose State or Invoking Synchronous Main Thread Dispatchers Inside Skiko Render Passes 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 DriftMutating Compose State or Invoking Synchronous Main Thread Dispatchers Inside Skiko Render PassesCritical
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 isolate pure rendering commands from state mutation by computing drawing primitives before entering the Skiko/DrawScope rasterization phase.

Engineers MUST ALWAYS isolate pure rendering commands from state mutation by computing drawing primitives before entering the Skiko/DrawScope rasterization phase.

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 mutate Compose State (such as SnapshotState, MutableState, or StateFlow triggers) directly inside custom Skiko render callbacks, `DrawScope.drawIntoCanvas`, or `SkiaLayer.render`.

Engineers MUST NOT mutate Compose State (such as SnapshotState, MutableState, or StateFlow triggers) directly inside custom Skiko render callbacks, `DrawScope.drawIntoCanvas`, or `SkiaLayer.render`.

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 blocking thread primitives (`runBlocking`, `dispatch_sync`, mutex locks held across UI/Render boundaries) inside rendering delegates or platform canvas interop layers.

Engineers MUST NOT invoke blocking thread primitives (`runBlocking`, `dispatch_sync`, mutex locks held across UI/Render boundaries) inside rendering delegates or platform canvas interop layers.

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 offload complex path computations, glyph shaping, and raster caching to background worker dispatchers (`Dispatchers.Default`), providing immutable render models to the draw phase.

Code SHOULD offload complex path computations, glyph shaping, and raster caching to background worker dispatchers (`Dispatchers.Default`), providing immutable render models to the draw phase.

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 bridge synchronous platform-native events (e.g., iOS CADisplayLink, AppKit drawing callbacks) into synchronous Compose Snapshot state updates without queueing onto `Dispatchers.Main.immediate` asynchronously.

Components NEVER bridge synchronous platform-native events (e.g., iOS CADisplayLink, AppKit drawing callbacks) into synchronous Compose Snapshot state updates without queueing onto `Dispatchers.Main.immediate` asynchronously.

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 Render Loop & UI Thread Synchronization Guardrail critical for AI coding assistants?

Enforces strict decoupling of Compose snapshot state mutations from Skiko GPU rasterization cycles across iOS, Desktop, and Android targets. Eliminates rendering thread deadlocks, CADisplayLink/Choreographer stalls, and VSync drops caused by synchronous state reconciliation or bridge blocking during Skia frame rendering. 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 (Mutating Compose State or Invoking Synchronous Main Thread Dispatchers Inside Skiko Render Passes) 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