This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-skia-texture-lifecycle-eviction

Compose Multiplatform Skia Texture Deterministic Disposal and Context Eviction

Enforces deterministic disposal and reference-counted lifecycle tracking of unmanaged native Skia textures and surfaces across platform window context loss. Prevents silent native off-heap memory leaks and driver SIGSEGV crashes caused by garbage collection delays during Android Surface destruction, iOS MetalKit unbinding, and desktop window resizing.

Prohibited Anti-Pattern: Retaining Raw Skia Native Pointers in Compose Memory Caches Without Explicit GPU Eviction

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skia Texture Deterministic Disposal and Context Eviction - Enforces deterministic disposal and reference-counted lifecycle tracking of unmanaged native Skia textures and surfaces across platform window context loss. Prevents silent native off-heap memory leaks and driver SIGSEGV crashes caused by garbage collection delays during Android Surface destruction, iOS MetalKit unbinding, and desktop window resizing.
globs: **/src/**/{commonMain,androidMain,iosMain,desktopMain}/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-skia-texture-lifecycle-eviction"
---

# Compose Multiplatform Skia Texture Deterministic Disposal and Context Eviction

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Raw Skia Native Pointers in Compose Memory Caches Without Explicit GPU Eviction

## System Constraints
You are a Principal Mobile Architect enforcing Compose Multiplatform Skia graphics invariants. Native Skia allocations (org.jetbrains.skia.Image, Bitmap, Surface) manage unmanaged off-heap C++ and GPU driver memory that ART and Kotlin/Native garbage collectors cannot monitor or promptly scavenge. You must strictly enforce deterministic eviction, explicit AutoCloseable lifecycle bounds, and platform-native context synchronization to prevent low-memory termination (OOM) and SIGSEGV driver crashes during surface transitions.

## Strict Guidelines
- Engineers MUST ALWAYS wrap Skia native graphics primitives (Image, Surface, Bitmap) in ref-counted wrappers implementing AutoCloseable.
- Engineers MUST ALWAYS invoke .close() synchronously on underlying Skia allocations inside DisposableEffect onDispose blocks or when evicted from LRU memory caches.
- Engineers MUST NOT rely on Kotlin/Native WeakReference, FinalizationRegistry, or JVM/ART finalize() to evict GPU textures.
- Components NEVER store naked Skia Image or Surface instances in standard Composition remember { mutableStateOf(...) } blocks without attaching a deterministic cleanup lifecycle.
- Services MUST register lifecycle listeners to native surface destruction (Android SurfaceHolder.Callback, iOS Metal view controller transitions) to flush and invalidate GPU texture caches before the rendering context is invalidated.

## Bad vs Good Implementations
### Deterministic Disposal of Skia Textures via Managed Texture Container

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Skia Image holds native GPU memory pointers. Storing it in an untracked remember{} block causes native off-heap leaks when the composable leaves the composition. If the native window or rendering surface collapses before the garbage collector discovers the unmanaged reference, subsequent native driver invalidation causes SIGSEGV or out-of-memory crashes on low-spec mobile devices.
```kotlin
import androidx.compose.runtime.*
import org.jetbrains.skia.Image
import org.jetbrains.skia.Bitmap

@Composable
fun RemoteSkiaRenderer(rawBytes: ByteArray) {
    // ANTI-PATTERN: Raw Skia Image held in Compose memory.
    // Recomposition or screen exit leaks the underlying native C++ SkImage on the GPU off-heap,
    // risking SIGSEGV upon surface context destruction before the JVM/Native GC collects it.
    val skiaImage = remember(rawBytes) {
        Image.makeFromEncoded(rawBytes)
    }

    androidx.compose.foundation.Canvas(modifier = androidx.compose.ui.Modifier) { 
        // Direct drawing without texture validity checks
    }
}
```

#### Production Standard (Correct)
> **Standard**: The native Skia texture is encapsulated within a lifecycle-aware RetainedSkiaTexture that tracks disposal state and synchronously releases native GPU handles inside DisposableEffect.onDispose. This guarantees deterministic eviction from native graphics memory the moment the composition leaves the hierarchy or key dependencies change, preventing native memory leaks across window and surface transitions.
```kotlin
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.foundation.Canvas
import org.jetbrains.skia.Image

class RetainedSkiaTexture(private val image: Image) : AutoCloseable {
    private var isDisposed = false

    fun acquire(): Image? = if (isDisposed) null else image

    override fun close() {
        if (!isDisposed) {
            isDisposed = true
            image.close() // Synchronously unbinds and frees C++ SkImage / GPU texture
        }
    }
}

@Composable
fun RemoteSkiaRenderer(rawBytes: ByteArray, modifier: Modifier = Modifier) {
    // INVARIANT: Deterministic acquisition and lifecycle-bound disposal via DisposableEffect
    val textureHolder = remember(rawBytes) {
        RetainedSkiaTexture(Image.makeFromEncoded(rawBytes))
    }

    DisposableEffect(textureHolder) {
        onDispose {
            textureHolder.close()
        }
    }

    Canvas(modifier = modifier) {
        val nativeImage = textureHolder.acquire() ?: return@Canvas
        // Safe rendering with deterministic resource lifecycle verified
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Skia Texture Deterministic Disposal and Context Eviction

Compose Multiplatform Skia Texture Deterministic Disposal and Context Eviction defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic disposal and reference-counted lifecycle tracking of unmanaged native Skia textures and surfaces across platform window context loss. Prevents silent native off-heap memory leaks and driver SIGSEGV crashes caused by garbage collection delays during Android Surface destruction, iOS MetalKit unbinding, and desktop window resizing. 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: Retaining Raw Skia Native Pointers in Compose Memory Caches Without Explicit GPU Eviction 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 DriftRetaining Raw Skia Native Pointers in Compose Memory Caches Without Explicit GPU EvictionCritical
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 wrap Skia native graphics primitives (Image, Surface, Bitmap) in ref-counted wrappers implementing AutoCloseable.

Engineers MUST ALWAYS wrap Skia native graphics primitives (Image, Surface, Bitmap) in ref-counted wrappers implementing AutoCloseable.

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 invoke .close() synchronously on underlying Skia allocations inside DisposableEffect onDispose blocks or when evicted from LRU memory caches.

Engineers MUST ALWAYS invoke .close() synchronously on underlying Skia allocations inside DisposableEffect onDispose blocks or when evicted from LRU memory caches.

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 rely on Kotlin/Native WeakReference, FinalizationRegistry, or JVM/ART finalize() to evict GPU textures.

Engineers MUST NOT rely on Kotlin/Native WeakReference, FinalizationRegistry, or JVM/ART finalize() to evict GPU textures.

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 store naked Skia Image or Surface instances in standard Composition remember { mutableStateOf(...) } blocks without attaching a deterministic cleanup lifecycle.

Components NEVER store naked Skia Image or Surface instances in standard Composition remember { mutableStateOf(...) } blocks without attaching a deterministic cleanup lifecycle.

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

Services MUST register lifecycle listeners to native surface destruction (Android SurfaceHolder.Callback, iOS Metal view controller transitions) to flush and invalidate GPU texture caches before the rendering context is invalidated.

Services MUST register lifecycle listeners to native surface destruction (Android SurfaceHolder.Callback, iOS Metal view controller transitions) to flush and invalidate GPU texture caches before the rendering context is invalidated.

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 Skia Texture Deterministic Disposal and Context Eviction critical for AI coding assistants?

Enforces deterministic disposal and reference-counted lifecycle tracking of unmanaged native Skia textures and surfaces across platform window context loss. Prevents silent native off-heap memory leaks and driver SIGSEGV crashes caused by garbage collection delays during Android Surface destruction, iOS MetalKit unbinding, and desktop window resizing. 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 (Retaining Raw Skia Native Pointers in Compose Memory Caches Without Explicit GPU Eviction) 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