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

Compose Multiplatform Skiko Render Thread Isolation Invariant

Enforces strict isolation of Compose Multiplatform Skiko hardware rendering contexts (DirectX, Metal, OpenGL, Software) from non-deterministic concurrent coroutine dispatches. Dispatches to background thread pools (e.g., Dispatchers.Default or Dispatchers.IO) must never acquire, manipulate, or await graphical surfaces directly, eliminating pipeline deadlocks, context thrashing, and frame drops.

Prohibited Anti-Pattern: Interleaving Off-Thread Coroutine Processing with Skiko Graphics Layer Mutations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Render Thread Isolation Invariant - Enforces strict isolation of Compose Multiplatform Skiko hardware rendering contexts (DirectX, Metal, OpenGL, Software) from non-deterministic concurrent coroutine dispatches. Dispatches to background thread pools (e.g., Dispatchers.Default or Dispatchers.IO) must never acquire, manipulate, or await graphical surfaces directly, eliminating pipeline deadlocks, context thrashing, and frame drops.
globs: **/*View.kt, **/*Canvas.kt, **/*Render*.kt, **/ui/**/*.kt, **/graphics/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-render-thread-isolation"
---

# Compose Multiplatform Skiko Render Thread Isolation Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Interleaving Off-Thread Coroutine Processing with Skiko Graphics Layer Mutations

## System Constraints
You are a Principal Engineer enforcing the Compose Multiplatform Skiko Render Thread Isolation Invariant. Mandate strict segregation between rendering loops and asynchronous computations. Prevent non-deterministic graphics pipeline halts caused by cross-thread mutations of Skia/Skiko canvas states, bitmaps, and native surface handles.

## Strict Guidelines
- Engineers MUST ALWAYS isolate heavy image decodes, vector calculations, and data parsing into Dispatchers.Default or Dispatchers.IO before channeling finished immutable models to the UI layer.
- Engineers MUST NOT invoke org.jetbrains.skia.* or org.jetbrains.skiko.* graphics context state mutations (such as Canvas.draw*, Surface.flushAndSubmit, or PictureRecorder) from worker dispatchers.
- Code SHOULD leverage snapshotFlow or Compose state holders rather than dispatching low-level drawing calls across thread barriers.
- Services MUST deliver fully rendered immutable pixel arrays or pure state primitives to Dispatchers.Main before committing them to the Skia Canvas.
- Components NEVER bridge raw Skiko rendering contexts directly into asynchronous coroutines without explicit surface validity locks and render-thread synchronization.

## Bad vs Good Implementations
### Off-Thread Skia Canvas Mutation vs Isolated Bitmap Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing and drawing directly on the native Skia Surface from Dispatchers.Default violates Skiko's render loop invariant, inducing race conditions on the GPU context and catastrophic frame drops.
```kotlin
class BadChartRenderer(private val scope: CoroutineScope) {
    fun renderToSkikoSurface(surface: org.jetbrains.skia.Surface, dataPoints: List<Float>) {
        scope.launch(Dispatchers.Default) {
            // ANTI-PATTERN: Direct manipulation of graphics surface on a worker dispatcher
            // Causes race conditions, context thrashing, and Skiko rendering stalls
            val canvas = surface.canvas
            val paint = org.jetbrains.skia.Paint().apply { color = 0xFF00FF00.toInt() }
            dataPoints.forEachIndexed { index, value ->
                canvas.drawCircle(index * 10f, value, 4f, paint)
            }
            surface.flushAndSubmit(syncCpu = true)
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Records drawing commands into an immutable org.jetbrains.skia.Picture on Dispatchers.Default and transfers the finished artifact to Dispatchers.Main, preserving render thread isolation and preventing pipeline contention.
```kotlin
class SafeChartRenderer(
    private val scope: CoroutineScope,
    private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
    fun renderChart(dataPoints: List<Float>, onFrameReady: (org.jetbrains.skia.Picture) -> Unit) {
        scope.launch(Dispatchers.Default) {
            // Compute pure geometric layout off-thread without mutating active render surfaces
            val recorder = org.jetbrains.skia.PictureRecorder()
            val recordingCanvas = recorder.beginRecording(org.jetbrains.skia.Rect.makeWH(800f, 600f))
            val paint = org.jetbrains.skia.Paint().apply { color = 0xFF00FF00.toInt() }
            
            dataPoints.forEachIndexed { index, value ->
                recordingCanvas.drawCircle(index * 10f, value, 4f, paint)
            }
            val picture = recorder.finishRecordingAsPicture()
            
            // Dispatch immutable picture command list back to Main thread for deterministic presentation
            withContext(mainDispatcher) {
                onFrameReady(picture)
            }
        }
    }
}
```

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 Skiko Render Thread Isolation Invariant

Compose Multiplatform Skiko Render Thread Isolation Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict isolation of Compose Multiplatform Skiko hardware rendering contexts (DirectX, Metal, OpenGL, Software) from non-deterministic concurrent coroutine dispatches. Dispatches to background thread pools (e.g., Dispatchers.Default or Dispatchers.IO) must never acquire, manipulate, or await graphical surfaces directly, eliminating pipeline deadlocks, context thrashing, and frame drops. 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: Interleaving Off-Thread Coroutine Processing with Skiko Graphics Layer Mutations 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 DriftInterleaving Off-Thread Coroutine Processing with Skiko Graphics Layer MutationsCritical
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 heavy image decodes, vector calculations, and data parsing into Dispatchers.Default or Dispatchers.IO before channeling finished immutable models to the UI layer.

Engineers MUST ALWAYS isolate heavy image decodes, vector calculations, and data parsing into Dispatchers.Default or Dispatchers.IO before channeling finished immutable models to the UI layer.

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 invoke org.jetbrains.skia.* or org.jetbrains.skiko.* graphics context state mutations (such as Canvas.draw*, Surface.flushAndSubmit, or PictureRecorder) from worker dispatchers.

Engineers MUST NOT invoke org.jetbrains.skia.* or org.jetbrains.skiko.* graphics context state mutations (such as Canvas.draw*, Surface.flushAndSubmit, or PictureRecorder) from worker dispatchers.

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 SHOULD leverage snapshotFlow or Compose state holders rather than dispatching low-level drawing calls across thread barriers.

Code SHOULD leverage snapshotFlow or Compose state holders rather than dispatching low-level drawing calls across thread barriers.

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 deliver fully rendered immutable pixel arrays or pure state primitives to Dispatchers.Main before committing them to the Skia Canvas.

Services MUST deliver fully rendered immutable pixel arrays or pure state primitives to Dispatchers.Main before committing them to the Skia Canvas.

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 raw Skiko rendering contexts directly into asynchronous coroutines without explicit surface validity locks and render-thread synchronization.

Components NEVER bridge raw Skiko rendering contexts directly into asynchronous coroutines without explicit surface validity locks and render-thread synchronization.

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 Thread Isolation Invariant critical for AI coding assistants?

Enforces strict isolation of Compose Multiplatform Skiko hardware rendering contexts (DirectX, Metal, OpenGL, Software) from non-deterministic concurrent coroutine dispatches. Dispatches to background thread pools (e.g., Dispatchers.Default or Dispatchers.IO) must never acquire, manipulate, or await graphical surfaces directly, eliminating pipeline deadlocks, context thrashing, and frame drops. 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 (Interleaving Off-Thread Coroutine Processing with Skiko Graphics Layer Mutations) 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