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

Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant

Enforces strict native GPU surface recycling and deterministic rasterization teardown for Kotlin Multiplatform Skiko runtimes across Android (Vulkan/GLES) and iOS (Metal). Eliminates severe GPU VRAM memory leaks, native driver crashes (e.g., VK_ERROR_DEVICE_LOST, Metal command buffer invalidations), and frame-pacing degradation caused by unmanaged surface reallocation across lifecycle transitions.

Prohibited Anti-Pattern: Orphaned Native Metal/Vulkan Render Targets and Leaked Skia GrDirectContext Instances Across Lifecycle Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant - Enforces strict native GPU surface recycling and deterministic rasterization teardown for Kotlin Multiplatform Skiko runtimes across Android (Vulkan/GLES) and iOS (Metal). Eliminates severe GPU VRAM memory leaks, native driver crashes (e.g., VK_ERROR_DEVICE_LOST, Metal command buffer invalidations), and frame-pacing degradation caused by unmanaged surface reallocation across lifecycle transitions.
globs: **/commonMain/**/*.kt, **/androidMain/**/*.kt, **/iosMain/**/*.kt, **/graphics/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-gpu-surface-lifecycle-invariants"
---

# Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Native Metal/Vulkan Render Targets and Leaked Skia GrDirectContext Instances Across Lifecycle Transitions

## System Constraints
You are a Principal Mobile Graphics Architect enforcing Skiko GPU Surface Lifecycle Invariants across Kotlin Multiplatform targets. You strictly mandate deterministic management of native Skia GrDirectContext, Metal render pipelines, and Android Vulkan/GLES surfaces. Never permit unmanaged Skia Surface instantiation, unreleased hardware framebuffers on background transition, or unsynchronized context disposal across Android Activity/Fragment and iOS UIViewController/UIApplication lifecycle boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS synchronize GPU rasterization teardown with OS lifecycle events (Android onStop/onDestroy, iOS viewDidDisappear/applicationDidEnterBackground) before releasing host views.
- Engineers MUST ALWAYS flush and submit pending native command buffers via context.flushAndSubmit(syncCpu = true) before invalidating or recycling underlying Vulkan images or Metal drawables.
- Engineers MUST NOT allocate unpooled org.jetbrains.skia.Surface instances inside render draw loops or recomposition passes.
- Components NEVER hold strong unmanaged references to SkiaLayer, SkiaRenderer, or GrDirectContext past view detachment.
- Surfaces MUST be returned to an explicit bounded SkiaSurfacePool or closed via AutoCloseable/Closeable semantics when viewport dimensions mutate or when the view enters a non-rendered state.
- Code SHOULD decouple the Skia GrDirectContext lifecycle from volatile View/ViewController lifecycles, maintaining context state while resetting underlying surface bindings during pause/resume cycles.

## Bad vs Good Implementations
### Skiko Surface Disposal & Pool Management Across Native Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Instantiating Skia Surfaces directly on resize without explicitly releasing prior BackendRenderTarget/Surface allocations leaks native GPU VRAM. Failing to synchronize and release graphics surfaces upon app backgrounding leads to platform watchdog termination, GPU context invalidation crashes, and severe frame-pacing degradation on resume.
```kotlin
// Anti-Pattern: Unmanaged surface creation with naive garbage collection release
class LeakProneSkikoView : SkiaLayer() {
    private var surface: Surface? = null

    fun renderFrame(width: Int, height: Int) {
        // Reallocating surface every resize without releasing old native buffer
        if (surface == null || surface?.width != width || surface?.height != height) {
            val renderTarget = BackendRenderTarget.makeMetal(width, height, 0)
            // Leaks previous native texture references and Skia GrDirectContext bindings
            surface = Surface.makeRenderTarget(renderContext, false, renderTarget)
        }

        surface?.canvas?.let { canvas ->
            canvas.clear(Color.WHITE)
            // Render frame contents...
        }
    }

    // Native lifecycle event unhandled: Backgrounding app leaves surface active in VRAM
    fun onBackgrounded() {
        // No-op: Relies on JVM/Kotlin Native GC, triggering native GPU OOM or VK_ERROR_DEVICE_LOST
    }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly wraps Skia Surface and BackendRenderTarget allocations in a synchronized lifecycle-aware holder. Transitions (suspend/stop) invoke `context.flushAndSubmit(syncCpu = true)` and immediately free native GPU buffers, protecting against out-of-memory crashes and context destruction.
```kotlin
// Production Fix: Bounded surface recycling with synchronized lifecycle management
class ResilientSkikoSurfaceHolder(
    private val context: DirectContext
) : AutoCloseable {
    private var currentSurface: Surface? = null
    private var currentRenderTarget: BackendRenderTarget? = null
    private val lock = Any()

    fun acquireSurface(width: Int, height: Int, createTarget: () -> BackendRenderTarget): Surface = synchronized(lock) {
        if (currentSurface != null && currentSurface?.width == width && currentSurface?.height == height) {
            return currentSurface!!
        }
        releaseSurfaceInternal()
        
        val target = createTarget()
        currentRenderTarget = target
        currentSurface = Surface.makeRenderTarget(context, false, target) ?: run {
            target.close()
            error("Failed to allocate Skia GPU RenderTarget [${width}x${height}]")
        }
        return currentSurface!!
    }

    fun onLifecycleSuspend() = synchronized(lock) {
        // Flush GPU pipelines and submit to GPU before releasing framebuffer
        context.flushAndSubmit(syncCpu = true)
        releaseSurfaceInternal()
        context.resetContext()
    }

    private fun releaseSurfaceInternal() {
        currentSurface?.close()
        currentSurface = null
        currentRenderTarget?.close()
        currentRenderTarget = null
    }

    override fun close() = synchronized(lock) {
        onLifecycleSuspend()
    }
}
```

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: Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant

Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict native GPU surface recycling and deterministic rasterization teardown for Kotlin Multiplatform Skiko runtimes across Android (Vulkan/GLES) and iOS (Metal). Eliminates severe GPU VRAM memory leaks, native driver crashes (e.g., VK_ERROR_DEVICE_LOST, Metal command buffer invalidations), and frame-pacing degradation caused by unmanaged surface reallocation across lifecycle transitions. 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: Orphaned Native Metal/Vulkan Render Targets and Leaked Skia GrDirectContext Instances Across Lifecycle Transitions 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 DriftOrphaned Native Metal/Vulkan Render Targets and Leaked Skia GrDirectContext Instances Across Lifecycle TransitionsCritical
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 synchronize GPU rasterization teardown with OS lifecycle events (Android onStop/onDestroy, iOS viewDidDisappear/applicationDidEnterBackground) before releasing host views.

Engineers MUST ALWAYS synchronize GPU rasterization teardown with OS lifecycle events (Android onStop/onDestroy, iOS viewDidDisappear/applicationDidEnterBackground) before releasing host views.

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 ALWAYS flush and submit pending native command buffers via context.flushAndSubmit(syncCpu = true) before invalidating or recycling underlying Vulkan images or Metal drawables.

Engineers MUST ALWAYS flush and submit pending native command buffers via context.flushAndSubmit(syncCpu = true) before invalidating or recycling underlying Vulkan images or Metal drawables.

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 allocate unpooled org.jetbrains.skia.Surface instances inside render draw loops or recomposition passes.

Engineers MUST NOT allocate unpooled org.jetbrains.skia.Surface instances inside render draw loops or recomposition passes.

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 unmanaged references to SkiaLayer, SkiaRenderer, or GrDirectContext past view detachment.

Components NEVER hold strong unmanaged references to SkiaLayer, SkiaRenderer, or GrDirectContext past view detachment.

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

Surfaces MUST be returned to an explicit bounded SkiaSurfacePool or closed via AutoCloseable/Closeable semantics when viewport dimensions mutate or when the view enters a non-rendered state.

Surfaces MUST be returned to an explicit bounded SkiaSurfacePool or closed via AutoCloseable/Closeable semantics when viewport dimensions mutate or when the view enters a non-rendered state.

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.
6

Code SHOULD decouple the Skia GrDirectContext lifecycle from volatile View/ViewController lifecycles, maintaining context state while resetting underlying surface bindings during pause/resume cycles.

Code SHOULD decouple the Skia GrDirectContext lifecycle from volatile View/ViewController lifecycles, maintaining context state while resetting underlying surface bindings during pause/resume cycles.

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 Kotlin Multiplatform Skiko GPU Surface Pooling and Lifecycle Invariant critical for AI coding assistants?

Enforces strict native GPU surface recycling and deterministic rasterization teardown for Kotlin Multiplatform Skiko runtimes across Android (Vulkan/GLES) and iOS (Metal). Eliminates severe GPU VRAM memory leaks, native driver crashes (e.g., VK_ERROR_DEVICE_LOST, Metal command buffer invalidations), and frame-pacing degradation caused by unmanaged surface reallocation across lifecycle transitions. 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 (Orphaned Native Metal/Vulkan Render Targets and Leaked Skia GrDirectContext Instances Across Lifecycle Transitions) 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

Kotlin