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

KMP Skiko Compose Surface Destruction Reentrancy Barrier

Enforces strict atomic lifecycle synchronization between native display surfaces (Android SurfaceHolder/iOS CAMetalLayer) and the Skiko Skia rendering pipeline in Compose Multiplatform. Prevents native GPU context deadlocks (EGL/Metal), SIGSEGV access violations, and render-thread tearing during rapid fragment disposal, orientation changes, and back-navigation gestures.

Prohibited Anti-Pattern: Unsynchronized native surface destruction triggering concurrent Skia render passes and UI thread deadlocks.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko Compose Surface Destruction Reentrancy Barrier - Enforces strict atomic lifecycle synchronization between native display surfaces (Android SurfaceHolder/iOS CAMetalLayer) and the Skiko Skia rendering pipeline in Compose Multiplatform. Prevents native GPU context deadlocks (EGL/Metal), SIGSEGV access violations, and render-thread tearing during rapid fragment disposal, orientation changes, and back-navigation gestures.
globs: **/*SkiaLayer*.kt, **/*Surface*.kt, **/*PlatformView*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-compose-surface-destruction-barrier"
---

# KMP Skiko Compose Surface Destruction Reentrancy Barrier

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized native surface destruction triggering concurrent Skia render passes and UI thread deadlocks.

## System Constraints
You are a Principal Software Architect enforcing zero-crash native rendering standards for Kotlin Multiplatform (KMP) using Skiko and Compose Multiplatform. You must enforce atomic, non-blocking synchronization barriers between the native platform surface lifecycle (Android SurfaceHolder.Callback / iOS CAMetalLayer lifecycle) and Skiko's asynchronous render pump. Mandate that GPU context resources are never detached while a render pass is in-flight, and native surface invalidation never performs a synchronous wait on the Main/UI thread that can deadlock with Skiko's dispatcher.

## Strict Guidelines
- Engineers MUST ALWAYS implement an explicit atomic state machine (e.g., ATTACHED, INVALIDATING, DETACHED) to gate frame generation before notifying native surface destruction.
- Engineers MUST NOT synchronously block the Main/UI thread (e.g., runBlocking, Thread.join, CountDownLatch.await) waiting for Skiko render loop completion inside surfaceDestroyed or viewDidDisappear.
- Code MUST cancel pending frame draw requests and drain or abort in-flight Skia command buffers before unbinding the native window/MetalLayer handle.
- Services MUST ensure that native surface handles are marked invalid prior to triggering Skia context deconstruction to fail-fast inside any concurrent render pass.
- Components NEVER execute reentrant surface recreation callbacks while a teardown sequence is actively invalidating Skia or platform render resources.

## Bad vs Good Implementations
### Skiko Android/iOS Native Surface Destruction Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling runBlocking on the UI thread during surfaceDestroyed blocks the native window callback. If Skiko's rendering thread is awaiting a Choreographer pulse, VSync token, or main-thread lock, the app enters an unrecoverable deadlock or SIGSEGV when the native window is freed underneath the GPU context.
```kotlin
// ANTI-PATTERN: Blocking the main UI thread during surface destruction,
// causing reentrancy deadlocks when Skiko's render loop requests UI thread sync.
class NativeComposeViewRenderer : SurfaceHolder.Callback {
    private var skiaLayer: SkiaLayer? = SkiaLayer()

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // Catastrophic: synchronous block on UI thread deadlocks Skiko's internal render pump
        // if the render thread is simultaneously waiting for a Choreographer frame or UI dispatch.
        runBlocking {
            skiaLayer?.stop()
            skiaLayer?.dispose()
            skiaLayer = null
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        skiaLayer?.attachTo(holder)
        skiaLayer?.start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
}
```

#### Production Standard (Correct)
> **Standard**: The atomic state machine instantly blocks new render dispatches upon surfaceDestroyed. The native handle is immediately unbound, and heavyweight GPU deconstruction is offloaded without holding the main thread hostage, eliminating both SIGSEGV access violations and render thread deadlocks.
```kotlin
// PRODUCTION STANDARD: Lock-free atomic lifecycle barrier with immediate render-pass gating.
enum class SurfaceLifecycleState { UNINITIALIZED, ATTACHED, DESTROYING, DETACHED }

class NativeComposeViewRenderer : SurfaceHolder.Callback {
    private val lifecycleState = java.util.concurrent.atomic.AtomicReference(SurfaceLifecycleState.UNINITIALIZED)
    private var skiaLayer: SkiaLayer? = null
    private val renderScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default + kotlinx.coroutines.SupervisorJob())

    override fun surfaceCreated(holder: SurfaceHolder) {
        lifecycleState.set(SurfaceLifecycleState.ATTACHED)
        val layer = SkiaLayer().apply {
            attachTo(holder)
            start()
        }
        skiaLayer = layer
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // 1. Immediately flip atomic barrier so render loop skips target drawing
        if (!lifecycleState.compareAndSet(SurfaceLifecycleState.ATTACHED, SurfaceLifecycleState.DESTROYING)) {
            return
        }
        val targetLayer = skiaLayer
        skiaLayer = null

        // 2. Detach native handle synchronously without blocking wait
        targetLayer?.detach()

        // 3. Dispose GPU resources asynchronously off the main thread
        renderScope.launch {
            try {
                targetLayer?.stop()
                targetLayer?.dispose()
            } finally {
                lifecycleState.set(SurfaceLifecycleState.DETACHED)
            }
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        if (lifecycleState.get() == SurfaceLifecycleState.ATTACHED) {
            skiaLayer?.updateSize(width, height)
        }
    }
}
```

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: KMP Skiko Compose Surface Destruction Reentrancy Barrier

KMP Skiko Compose Surface Destruction Reentrancy Barrier defines an industrial-grade behavioral standard for mobile engineering. Enforces strict atomic lifecycle synchronization between native display surfaces (Android SurfaceHolder/iOS CAMetalLayer) and the Skiko Skia rendering pipeline in Compose Multiplatform. Prevents native GPU context deadlocks (EGL/Metal), SIGSEGV access violations, and render-thread tearing during rapid fragment disposal, orientation changes, and back-navigation gestures. 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: Unsynchronized native surface destruction triggering concurrent Skia render passes and UI thread deadlocks. 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 DriftUnsynchronized native surface destruction triggering concurrent Skia render passes and UI thread deadlocks.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 implement an explicit atomic state machine (e.g., ATTACHED, INVALIDATING, DETACHED) to gate frame generation before notifying native surface destruction.

Engineers MUST ALWAYS implement an explicit atomic state machine (e.g., ATTACHED, INVALIDATING, DETACHED) to gate frame generation before notifying native surface destruction.

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 synchronously block the Main/UI thread (e.g., runBlocking, Thread.join, CountDownLatch.await) waiting for Skiko render loop completion inside surfaceDestroyed or viewDidDisappear.

Engineers MUST NOT synchronously block the Main/UI thread (e.g., runBlocking, Thread.join, CountDownLatch.await) waiting for Skiko render loop completion inside surfaceDestroyed or viewDidDisappear.

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 cancel pending frame draw requests and drain or abort in-flight Skia command buffers before unbinding the native window/MetalLayer handle.

Code MUST cancel pending frame draw requests and drain or abort in-flight Skia command buffers before unbinding the native window/MetalLayer handle.

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 native surface handles are marked invalid prior to triggering Skia context deconstruction to fail-fast inside any concurrent render pass.

Services MUST ensure that native surface handles are marked invalid prior to triggering Skia context deconstruction to fail-fast inside any concurrent render pass.

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 execute reentrant surface recreation callbacks while a teardown sequence is actively invalidating Skia or platform render resources.

Components NEVER execute reentrant surface recreation callbacks while a teardown sequence is actively invalidating Skia or platform render resources.

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 KMP Skiko Compose Surface Destruction Reentrancy Barrier critical for AI coding assistants?

Enforces strict atomic lifecycle synchronization between native display surfaces (Android SurfaceHolder/iOS CAMetalLayer) and the Skiko Skia rendering pipeline in Compose Multiplatform. Prevents native GPU context deadlocks (EGL/Metal), SIGSEGV access violations, and render-thread tearing during rapid fragment disposal, orientation changes, and back-navigation gestures. 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 (Unsynchronized native surface destruction triggering concurrent Skia render passes and UI thread deadlocks.) 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

KMP