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

Compose Multiplatform Skiko Vulkan/Metal Surface Synchronization Guardrail

Enforces deterministic synchronization between off-screen GPU texture updates and native platform presentation surfaces (Metal CAMetalLayer and Vulkan VkSwapchainKHR) in Compose Multiplatform. Prevents visual tearing, thread deadlocks, and presentation jitter by mandating non-blocking Skiko render delegate synchronization and asynchronous command buffer completion fences.

Prohibited Anti-Pattern: Mutating GPU textures synchronously on application dispatchers without Skia GrDirectContext flush synchronization or native swapchain fences.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Vulkan/Metal Surface Synchronization Guardrail - Enforces deterministic synchronization between off-screen GPU texture updates and native platform presentation surfaces (Metal CAMetalLayer and Vulkan VkSwapchainKHR) in Compose Multiplatform. Prevents visual tearing, thread deadlocks, and presentation jitter by mandating non-blocking Skiko render delegate synchronization and asynchronous command buffer completion fences.
globs: **/skiko/**/*.kt, **/graphics/**/*.kt, **/render/**/*.kt, **/*Canvas*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-skiko-surface-synchronization-standard"
---

# Compose Multiplatform Skiko Vulkan/Metal Surface Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Mutating GPU textures synchronously on application dispatchers without Skia GrDirectContext flush synchronization or native swapchain fences.

## System Constraints
You are a Principal Mobile Systems Architect enforcing Compose Multiplatform Skiko Vulkan/Metal rendering invariants. Mandate non-blocking GPU texture transfers, explicit GrDirectContext flush fences, and deterministic synchronization with CAMetalDrawable / VkSwapchainKHR surfaces without stalling the Main UI dispatcher.

## Strict Guidelines
- Engineers MUST ALWAYS isolate off-screen pixel buffer and texture allocations to background graphics queues and transfer them to the render thread via asynchronous fences (e.g., MTLSharedEvent or VkSemaphore).
- Engineers MUST NOT invoke blocking Skia context synchronizations like 'GrDirectContext.flushAndSubmit(syncCpu = true)' or thread-blocking waits on the UI Main dispatcher.
- Code SHOULD request frame invalidations via 'SkiaLayer.needRedraw()' rather than manually triggering immediate synchronous rendering passes from event listeners.
- Services MUST ensure that all platform-native surface references (CAMetalLayer, ANativeWindow, VkSurfaceKHR) are validated for lifecycle teardown before submitting command buffers to avoid VK_ERROR_DEVICE_LOST or SIGSEGV crashes.
- Components NEVER draw directly to raw hardware surfaces without Skiko canvas encapsulation and an explicit lockstep semaphore mechanism coordinating native compositor frames.

## Bad vs Good Implementations
### Off-Screen Texture Upload and Skiko Surface Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing `directContext.flushAndSubmit(syncCpu = true)` on `Dispatchers.Main` stalls the primary UI thread while waiting for the GPU command pipeline. This drops frames, causes severe presentation stutter, and can deadlock the native Metal/Vulkan compositor.
```kotlin
import org.jetbrains.skia.*
import org.jetbrains.skiko.SkiaLayer
import kotlinx.coroutines.*

class UnsynchronizedTextureRenderer(private val skiaLayer: SkiaLayer) {
    private val directContext: DirectContext = DirectContext.makeGL() // or makeMetal

    fun updateTexture(pixelData: ByteArray, width: Int, height: Int) {
        // ANTI-PATTERN: Synchronously mutating texture on Main dispatcher and forcing a CPU-GPU sync block
        CoroutineScope(Dispatchers.Main).launch {
            val image = Image.makeFromEncoded(pixelData)
            val backendTexture = directContext.createBackendTexture(width, height, ColorType.RGBA_8888)
            // Blocks the entire Main thread awaiting GPU pipeline completion; causes UI lockup and frame drops
            directContext.flushAndSubmit(syncCpu = true)
            skiaLayer.needRedraw()
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Texture preparation is offloaded to a background dispatcher, and `directContext.flush` utilizes an asynchronous completion callback (`setFinishedProc`) with non-blocking submission (`syncCpu = false`). `skiaLayer.needRedraw()` coordinates cleanly with the native display compositor without UI thread lockup.
```kotlin
import org.jetbrains.skia.*
import org.jetbrains.skiko.SkiaLayer
import kotlinx.coroutines.*

class SynchronizedTextureRenderer(
    private val skiaLayer: SkiaLayer,
    private val directContext: DirectContext,
    private val renderDispatcher: CoroutineDispatcher = Dispatchers.Default
) {
    fun updateTextureAsync(pixelData: ByteArray, width: Int, height: Int) {
        // GOOD: Process decoding and command submission asynchronously off the Main dispatcher
        CoroutineScope(renderDispatcher).launch {
            val imageInfo = ImageInfo.makeN32Premul(width, height)
            val bitmap = Bitmap().apply {
                allocPixels(imageInfo)
                installPixels(pixelData)
            }
            val skImage = Image.makeFromBitmap(bitmap)

            // Flush operations to GPU asynchronously without stalling CPU threads
            directContext.flush(
                FlushInfo().apply {
                    setFinishedProc { 
                        // Notify compositor to invalidate surface only after GPU work is committed
                        skiaLayer.needRedraw()
                    }
                }
            )
            directContext.submit(syncCpu = false)
        }
    }
}
```

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 Vulkan/Metal Surface Synchronization Guardrail

Compose Multiplatform Skiko Vulkan/Metal Surface Synchronization Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic synchronization between off-screen GPU texture updates and native platform presentation surfaces (Metal CAMetalLayer and Vulkan VkSwapchainKHR) in Compose Multiplatform. Prevents visual tearing, thread deadlocks, and presentation jitter by mandating non-blocking Skiko render delegate synchronization and asynchronous command buffer completion fences. 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 GPU textures synchronously on application dispatchers without Skia GrDirectContext flush synchronization or native swapchain fences. 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 GPU textures synchronously on application dispatchers without Skia GrDirectContext flush synchronization or native swapchain fences.Critical
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 off-screen pixel buffer and texture allocations to background graphics queues and transfer them to the render thread via asynchronous fences (e.g., MTLSharedEvent or VkSemaphore).

Engineers MUST ALWAYS isolate off-screen pixel buffer and texture allocations to background graphics queues and transfer them to the render thread via asynchronous fences (e.g., MTLSharedEvent or VkSemaphore).

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 blocking Skia context synchronizations like 'GrDirectContext.flushAndSubmit(syncCpu = true)' or thread-blocking waits on the UI Main dispatcher.

Engineers MUST NOT invoke blocking Skia context synchronizations like 'GrDirectContext.flushAndSubmit(syncCpu = true)' or thread-blocking waits on the UI Main dispatcher.

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 request frame invalidations via 'SkiaLayer.needRedraw()' rather than manually triggering immediate synchronous rendering passes from event listeners.

Code SHOULD request frame invalidations via 'SkiaLayer.needRedraw()' rather than manually triggering immediate synchronous rendering passes from event listeners.

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 ensure that all platform-native surface references (CAMetalLayer, ANativeWindow, VkSurfaceKHR) are validated for lifecycle teardown before submitting command buffers to avoid VK_ERROR_DEVICE_LOST or SIGSEGV crashes.

Services MUST ensure that all platform-native surface references (CAMetalLayer, ANativeWindow, VkSurfaceKHR) are validated for lifecycle teardown before submitting command buffers to avoid VK_ERROR_DEVICE_LOST or SIGSEGV crashes.

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 draw directly to raw hardware surfaces without Skiko canvas encapsulation and an explicit lockstep semaphore mechanism coordinating native compositor frames.

Components NEVER draw directly to raw hardware surfaces without Skiko canvas encapsulation and an explicit lockstep semaphore mechanism coordinating native compositor frames.

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 Vulkan/Metal Surface Synchronization Guardrail critical for AI coding assistants?

Enforces deterministic synchronization between off-screen GPU texture updates and native platform presentation surfaces (Metal CAMetalLayer and Vulkan VkSwapchainKHR) in Compose Multiplatform. Prevents visual tearing, thread deadlocks, and presentation jitter by mandating non-blocking Skiko render delegate synchronization and asynchronous command buffer completion fences. 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 GPU textures synchronously on application dispatchers without Skia GrDirectContext flush synchronization or native swapchain fences.) 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