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

KMP Compose Skiko Render Surface Lifecycle and Swapchain Invariant

Enforces synchronous swapchain invalidation and strict render target lifecycle synchronization across Kotlin Multiplatform Compose targets (iOS Metal, Android SurfaceView, Desktop AWT). Prevents SIGSEGV crashes, Metal validation layer panics, and native GPU context leaks caused by asynchronous render dispatches to destroyed surface handles.

Prohibited Anti-Pattern: Dispatching draw passes to unlinked native GPU surfaces or delaying SkiaLayer disposal after view hierarchy detachment

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Compose Skiko Render Surface Lifecycle and Swapchain Invariant - Enforces synchronous swapchain invalidation and strict render target lifecycle synchronization across Kotlin Multiplatform Compose targets (iOS Metal, Android SurfaceView, Desktop AWT). Prevents SIGSEGV crashes, Metal validation layer panics, and native GPU context leaks caused by asynchronous render dispatches to destroyed surface handles.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt, **/desktopMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-surface-lifecycle-guardrail"
---

# KMP Compose Skiko Render Surface Lifecycle and Swapchain Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dispatching draw passes to unlinked native GPU surfaces or delaying SkiaLayer disposal after view hierarchy detachment

## System Constraints
You are a Principal Software Architect enforcing deterministic GPU resource management in Kotlin Multiplatform (KMP) Compose applications powered by Skiko. You must mandate strict adherence to native surface lifecycles across iOS (CAMetalLayer), Android (SurfaceHolder/EGL/Vulkan), and Desktop (AWT/SkiaLayer). Any frame dispatch, coroutine animation loop, or offscreen render buffer that risks referencing a destroyed or unlinked surface handle must be blocked, synchronously cancelled, and finalized before platform view destruction completes.

## Strict Guidelines
- Engineers MUST ALWAYS synchronously detach Skiko render delegates and flush in-flight GPU commands during platform surface teardown callbacks (e.g., UIViewController.viewWillDisappear/deinit, SurfaceHolder.Callback.surfaceDestroyed, or ComponentListener.componentHidden).
- Engineers MUST NOT allow unmanaged Kotlin Coroutine contexts (e.g., GlobalScope or unconfined dispatchers) to drive Skia Canvas invalidations or frame request callbacks.
- Native interop bridges MUST verify swapchain validity (`isAttached`, `!isDisposed`, and valid surface dimensions > 0) immediately before acquiring the next GPU drawable or frame buffer.
- Components NEVER hold strong references to `SkiaLayer`, `MetalRedrawer`, or native render delegate wrappers inside long-lived dependency injection singletons or static companions.
- Custom native interop views embedded via UIKitView or AndroidView MUST implement explicit disposal hooks in onRelease/onReset that drain pending redraw requests and release GPU contexts.

## Bad vs Good Implementations
### iOS Metal Surface Lifecycle Teardown in Skiko Interop

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Asynchronous detachment in viewDidDisappear allows pending CADisplayLink frame ticks to invoke render passes on a detached or deallocated CAMetalLayer, provoking SIGSEGV inside the Skiko Metal redrawer and Metal validation panics.
```kotlin
// CRITICAL INVARIANT VIOLATION: Asynchronous lifecycle handling and dangling CADisplayLink/Metal delegate
class CustomSkikoMetalViewController(private val renderDelegate: SkikoRenderDelegate) : UIViewController(null, null) {
    private var skiaLayer: SkiaLayer? = SkiaLayer()

    override fun viewDidLoad() {
        super.viewDidLoad()
        skiaLayer?.renderDelegate = renderDelegate
        skiaLayer?.attachTo(this.view)
    }

    override fun viewDidDisappear(animated: Boolean) {
        super.viewDidDisappear(animated)
        // Flaw: Background coroutine/async cleanup leaks CAMetalLayer drawable handle
        CoroutineScope(Dispatchers.Default).launch {
            skiaLayer?.detach()
            skiaLayer = null
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Synchronously stops the redraw pump before view hierarchy transition and completely detaches the SkiaLayer delegate before the CAMetalLayer is unmapped, preventing out-of-order swapchain invalidation.
```kotlin
// PRODUCTION STANDARD: Synchronous swapchain invalidation and render-loop termination
class CustomSkikoMetalViewController(private val renderDelegate: SkikoRenderDelegate) : UIViewController(null, null) {
    private var skiaLayer: SkiaLayer? = SkiaLayer()

    override fun viewDidLoad() {
        super.viewDidLoad()
        skiaLayer?.let { layer ->
            layer.renderDelegate = renderDelegate
            layer.attachTo(this.view)
        }
    }

    override fun viewWillDisappear(animated: Boolean) {
        // Synchronously stop the redraw pump before the platform view hierarchy begins tearing down surfaces
        skiaLayer?.stopRedrawer()
        super.viewWillDisappear(animated)
    }

    override fun viewDidDisappear(animated: Boolean) {
        super.viewDidDisappear(animated)
        // Synchronously detach native layer and nullify to release the Metal pipeline state
        skiaLayer?.let { layer ->
            layer.detach()
            layer.renderDelegate = null
        }
        skiaLayer = null
    }
}
```

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 Compose Skiko Render Surface Lifecycle and Swapchain Invariant

KMP Compose Skiko Render Surface Lifecycle and Swapchain Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces synchronous swapchain invalidation and strict render target lifecycle synchronization across Kotlin Multiplatform Compose targets (iOS Metal, Android SurfaceView, Desktop AWT). Prevents SIGSEGV crashes, Metal validation layer panics, and native GPU context leaks caused by asynchronous render dispatches to destroyed surface handles. 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: Dispatching draw passes to unlinked native GPU surfaces or delaying SkiaLayer disposal after view hierarchy detachment 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 DriftDispatching draw passes to unlinked native GPU surfaces or delaying SkiaLayer disposal after view hierarchy detachmentCritical
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 synchronously detach Skiko render delegates and flush in-flight GPU commands during platform surface teardown callbacks (e.g., UIViewController.viewWillDisappear/deinit, SurfaceHolder.Callback.surfaceDestroyed, or ComponentListener.componentHidden).

Engineers MUST ALWAYS synchronously detach Skiko render delegates and flush in-flight GPU commands during platform surface teardown callbacks (e.g., UIViewController.viewWillDisappear/deinit, SurfaceHolder.Callback.surfaceDestroyed, or ComponentListener.componentHidden).

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 allow unmanaged Kotlin Coroutine contexts (e.g., GlobalScope or unconfined dispatchers) to drive Skia Canvas invalidations or frame request callbacks.

Engineers MUST NOT allow unmanaged Kotlin Coroutine contexts (e.g., GlobalScope or unconfined dispatchers) to drive Skia Canvas invalidations or frame request callbacks.

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

Native interop bridges MUST verify swapchain validity (`isAttached`, `!isDisposed`, and valid surface dimensions > 0) immediately before acquiring the next GPU drawable or frame buffer.

Native interop bridges MUST verify swapchain validity (`isAttached`, `!isDisposed`, and valid surface dimensions > 0) immediately before acquiring the next GPU drawable or frame buffer.

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

Components NEVER hold strong references to `SkiaLayer`, `MetalRedrawer`, or native render delegate wrappers inside long-lived dependency injection singletons or static companions.

Components NEVER hold strong references to `SkiaLayer`, `MetalRedrawer`, or native render delegate wrappers inside long-lived dependency injection singletons or static companions.

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

Custom native interop views embedded via UIKitView or AndroidView MUST implement explicit disposal hooks in onRelease/onReset that drain pending redraw requests and release GPU contexts.

Custom native interop views embedded via UIKitView or AndroidView MUST implement explicit disposal hooks in onRelease/onReset that drain pending redraw requests and release GPU contexts.

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 Compose Skiko Render Surface Lifecycle and Swapchain Invariant critical for AI coding assistants?

Enforces synchronous swapchain invalidation and strict render target lifecycle synchronization across Kotlin Multiplatform Compose targets (iOS Metal, Android SurfaceView, Desktop AWT). Prevents SIGSEGV crashes, Metal validation layer panics, and native GPU context leaks caused by asynchronous render dispatches to destroyed surface handles. 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 (Dispatching draw passes to unlinked native GPU surfaces or delaying SkiaLayer disposal after view hierarchy detachment) 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