This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skiko-vram-texture-recycling-protocol

KMP Skiko VRAM Texture Recycling and Deterministic GPU Eviction

Enforces explicit lifecycle-bound disposal and object pooling of Skia/Skiko ImageBitmap, Surface, and RenderTarget handles in Compose Multiplatform. Prevents low-tier mobile VRAM exhaustion and uncatchable native aborts caused by asynchronous finalizer delays across screen transitions.

Prohibited Anti-Pattern: Relying on JVM/Kotlin Native Garbage Collection for Skiko Native GPU Textures and Bitmaps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko VRAM Texture Recycling and Deterministic GPU Eviction - Enforces explicit lifecycle-bound disposal and object pooling of Skia/Skiko ImageBitmap, Surface, and RenderTarget handles in Compose Multiplatform. Prevents low-tier mobile VRAM exhaustion and uncatchable native aborts caused by asynchronous finalizer delays across screen transitions.
globs: **/commonMain/**/*.kt, **/androidMain/**/*.kt, **/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-vram-texture-recycling-protocol"
---

# KMP Skiko VRAM Texture Recycling and Deterministic GPU Eviction

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Relying on JVM/Kotlin Native Garbage Collection for Skiko Native GPU Textures and Bitmaps

## System Constraints
You are a Principal Mobile Architect enforcing the Skiko VRAM Texture Recycling Protocol for Compose Multiplatform. In KMP targets (Android, iOS via Metal), Skia backing stores (org.jetbrains.skia.Image, org.jetbrains.skia.Surface, and androidx.compose.ui.graphics.ImageBitmap) allocate native off-heap GPU memory that the host GC/ARC cannot accurately account for. You must mandate deterministic, lifecycle-aware cleanup using DisposableEffect, scoped texture pools, and explicit .close() invocations to eliminate OOM aborts.

## Strict Guidelines
- Engineers MUST ALWAYS invoke explicit .close() or recycle native Skia/Skiko resources (org.jetbrains.skia.Image, Surface, Picture) inside DisposableEffect onDispose blocks during Composable unmount.
- Engineers MUST NOT allow native Skia bitmap allocations to dangle across navigation boundaries without eviction or handoff to a managed texture pool.
- Engineers MUST enforce a bounded, platform-aware size ceiling on cached GPU textures, registering active trim callbacks with Android ComponentCallbacks2 and iOS UIApplicationDidReceiveMemoryWarningNotification.
- Custom Canvas rendering logic using DrawScope.drawIntoCanvas with native Skiko surfaces MUST encapsulate intermediate scratch buffers into reusable, thread-confined pools instead of allocating per-frame.
- Engineers MUST NEVER capture heavy Skia Image references in persistent Compose remember {} lambdas across structural navigation changes without an explicit lifecycle owner.

## Bad vs Good Implementations
### Deterministic Skiko Image Disposal Across Composable Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Skia allocations exist in unmanaged C++/Metal/Vulkan heap. When navigating away, JVM/K-Native garbage collection runs lazily because host heap size appears low, leaving heavy VRAM textures allocated until SIGKILL occurs under VRAM pressure.
```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.foundation.Image
import androidx.compose.ui.graphics.toComposeImageBitmap
import org.jetbrains.skia.Image as SkiaImage

@Composable
fun RemoteSkiaRenderer(rawBytes: ByteArray) {
    // ANTI-PATTERN: Native VRAM is allocated via Skia, but never deterministically freed.
    // Compose GC cannot calculate GPU memory pressure, leading to Metal/OpenGL VRAM panics.
    val composeBitmap = remember(rawBytes) {
        val skiaImg = SkiaImage.makeFromEncoded(rawBytes)
        skiaImg.toComposeImageBitmap()
    }
    
    Image(bitmap = composeBitmap, contentDescription = null)
}
```

#### Production Standard (Correct)
> **Standard**: Wraps the Skia native handle in a holder bound to DisposableEffect. When the Composable leaves the composition tree, nativeRef.close() releases underlying GPU textures immediately without waiting for host garbage collection.
```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.DisposableEffect
import androidx.compose.foundation.Image
import androidx.compose.ui.graphics.toComposeImageBitmap
import androidx.compose.ui.graphics.ImageBitmap
import org.jetbrains.skia.Image as SkiaImage

@Composable
fun RemoteSkiaRenderer(rawBytes: ByteArray) {
    // PRODUCTION FIX: Explicit lifecycle ownership and deterministic native VRAM deallocation
    val holder = remember(rawBytes) {
        val skiaImg = SkiaImage.makeFromEncoded(rawBytes)
        val composeBitmap = skiaImg.toComposeImageBitmap()
        object {
            val nativeRef: SkiaImage = skiaImg
            val bitmap: ImageBitmap = composeBitmap
        }
    }

    DisposableEffect(holder) {
        onDispose {
            // Closes native backend texture handle immediately on recomposition or screen exit
            holder.nativeRef.close()
        }
    }

    Image(bitmap = holder.bitmap, contentDescription = null)
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Skiko VRAM Texture Recycling and Deterministic GPU Eviction

KMP Skiko VRAM Texture Recycling and Deterministic GPU Eviction defines an industrial-grade behavioral standard for mobile engineering. Enforces explicit lifecycle-bound disposal and object pooling of Skia/Skiko ImageBitmap, Surface, and RenderTarget handles in Compose Multiplatform. Prevents low-tier mobile VRAM exhaustion and uncatchable native aborts caused by asynchronous finalizer delays across screen 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: Relying on JVM/Kotlin Native Garbage Collection for Skiko Native GPU Textures and Bitmaps 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 DriftRelying on JVM/Kotlin Native Garbage Collection for Skiko Native GPU Textures and BitmapsCritical
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 invoke explicit .close() or recycle native Skia/Skiko resources (org.jetbrains.skia.Image, Surface, Picture) inside DisposableEffect onDispose blocks during Composable unmount.

Engineers MUST ALWAYS invoke explicit .close() or recycle native Skia/Skiko resources (org.jetbrains.skia.Image, Surface, Picture) inside DisposableEffect onDispose blocks during Composable unmount.

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 native Skia bitmap allocations to dangle across navigation boundaries without eviction or handoff to a managed texture pool.

Engineers MUST NOT allow native Skia bitmap allocations to dangle across navigation boundaries without eviction or handoff to a managed texture pool.

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 enforce a bounded, platform-aware size ceiling on cached GPU textures, registering active trim callbacks with Android ComponentCallbacks2 and iOS UIApplicationDidReceiveMemoryWarningNotification.

Engineers MUST enforce a bounded, platform-aware size ceiling on cached GPU textures, registering active trim callbacks with Android ComponentCallbacks2 and iOS UIApplicationDidReceiveMemoryWarningNotification.

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

Custom Canvas rendering logic using DrawScope.drawIntoCanvas with native Skiko surfaces MUST encapsulate intermediate scratch buffers into reusable, thread-confined pools instead of allocating per-frame.

Custom Canvas rendering logic using DrawScope.drawIntoCanvas with native Skiko surfaces MUST encapsulate intermediate scratch buffers into reusable, thread-confined pools instead of allocating per-frame.

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

Engineers MUST NEVER capture heavy Skia Image references in persistent Compose remember {} lambdas across structural navigation changes without an explicit lifecycle owner.

Engineers MUST NEVER capture heavy Skia Image references in persistent Compose remember {} lambdas across structural navigation changes without an explicit lifecycle owner.

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 VRAM Texture Recycling and Deterministic GPU Eviction critical for AI coding assistants?

Enforces explicit lifecycle-bound disposal and object pooling of Skia/Skiko ImageBitmap, Surface, and RenderTarget handles in Compose Multiplatform. Prevents low-tier mobile VRAM exhaustion and uncatchable native aborts caused by asynchronous finalizer delays across screen 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 (Relying on JVM/Kotlin Native Garbage Collection for Skiko Native GPU Textures and Bitmaps) 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