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

Deterministic Skiko Native Resource Disposal in Compose Multiplatform

Enforces immediate and deterministic deallocation of native Skia/Skiko resources (such as Image, Surface, PictureRecorder, and NativePointer wrappers) across Compose Multiplatform iOS and Desktop targets. Mitigates native off-heap memory exhaustion and iOS Jetsam kills caused by Kotlin/Native GC latency when handling high-frequency view recycling. Guarantees that canvas raster buffers and transient graphics contexts are closed explicitly via lifecycle hooks rather than deferred finalizers.

Prohibited Anti-Pattern: Unbounded Native Buffer Accumulation via GC-Deferred Finalization in Skiko Rendering

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Skiko Native Resource Disposal in Compose Multiplatform - Enforces immediate and deterministic deallocation of native Skia/Skiko resources (such as Image, Surface, PictureRecorder, and NativePointer wrappers) across Compose Multiplatform iOS and Desktop targets. Mitigates native off-heap memory exhaustion and iOS Jetsam kills caused by Kotlin/Native GC latency when handling high-frequency view recycling. Guarantees that canvas raster buffers and transient graphics contexts are closed explicitly via lifecycle hooks rather than deferred finalizers.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/desktopMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-native-deallocation-guardrail"
---

# Deterministic Skiko Native Resource Disposal in Compose Multiplatform

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Native Buffer Accumulation via GC-Deferred Finalization in Skiko Rendering

## System Constraints
You are a Principal Software Architect enforcing deterministic native memory management in Kotlin Multiplatform projects utilizing Skiko and Compose Multiplatform. You must block any code that instantiates native Skia resources without an explicit lifecycle deallocation strategy, especially within scrollable containers, high-frequency animation loops, or custom Canvas drawing passes.

## Strict Guidelines
- Engineers MUST ALWAYS invoke `.close()` or `.use { ... }` on Skiko Managed objects (e.g., `org.jetbrains.skia.Image`, `org.jetbrains.skia.Surface`, `org.jetbrains.skia.PictureRecorder`) as soon as their lifecycle ends.
- Engineers MUST NOT allocate native Skia/Skiko buffers or decode raster data inside Compose draw phases (`Modifier.drawWithContent`, `Canvas`, or `DrawScope`) without pooling or retaining references in a lifecycle-bound state holder.
- Code SHOULD bind long-lived native Skia references to the composition lifecycle using `DisposableEffect`, ensuring that `onDispose` explicitly triggers `.close()`.
- Services MUST implement pooling mechanisms with bounded native off-heap memory quotas for reusable bitmaps and surfaces when rendering high-frequency collections (`LazyColumn`, `LazyRow`).
- Components NEVER rely on Kotlin/Native Garbage Collection or finalize routines to reclaim off-heap C++/Metal textures, as the GC scheduler is unaware of external native memory pressure.

## Bad vs Good Implementations
### Skiko Image Decoding in Recycled Canvas View

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a Skia `Image` inside the draw pass allocates native off-heap C++ buffers on every frame. Because the Kotlin/Native GC only sees a small Kotlin proxy object, it does not prioritize GC collections, resulting in an unmitigated off-heap memory spike and fatal iOS Jetsam SIGKILL termination during fast scrolling.
```kotlin
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import org.jetbrains.skia.Image

@Composable
fun RasterThumbnail(byteArray: ByteArray, modifier: Modifier = Modifier) {
    // ANTI-PATTERN: Decoding Skia Image on every draw loop or retaining without
    // explicit closing. Kotlin/Native GC only tracks the light pointer wrapper,
    // leading to rapid iOS Jetsam OOM under list scrolling.
    Canvas(modifier = modifier) {
        val skiaImage = Image.makeFromEncoded(byteArray)
        drawImage(skiaImage.toComposeImageBitmap())
        // Native memory remains allocated off-heap until asynchronous GC finalization
    }
}
```

#### Production Standard (Correct)
> **Standard**: By utilizing `use { ... }`, the native C++ Skia Image handle is explicitly deallocated immediately after its pixel contents are transferred to Compose's managed texture format. The native memory is returned synchronously without relying on the non-deterministic Kotlin GC cycle.
```kotlin
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import org.jetbrains.skia.Image

@Composable
fun RasterThumbnail(byteArray: ByteArray, modifier: Modifier = Modifier) {
    // DETERMINISTIC: Native resource allocation tied strictly to DisposableEffect lifecycle
    val imageBitmap: ImageBitmap? = remember(byteArray) {
        val skiaImage = Image.makeFromEncoded(byteArray)
        skiaImage.use { image ->
            // Copies raster data to Compose ImageBitmap abstraction and promptly frees underlying native Skia buffer
            image.toComposeImageBitmap()
        }
    }

    DisposableEffect(byteArray) {
        onDispose {
            // Guarantees immediate cleanup if underlying bitmaps are managed as pooled Skia objects
        }
    }

    imageBitmap?.let {
        Canvas(modifier = modifier) {
            drawImage(it)
        }
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Skiko Native Resource Disposal in Compose Multiplatform

Deterministic Skiko Native Resource Disposal in Compose Multiplatform defines an industrial-grade behavioral standard for mobile engineering. Enforces immediate and deterministic deallocation of native Skia/Skiko resources (such as Image, Surface, PictureRecorder, and NativePointer wrappers) across Compose Multiplatform iOS and Desktop targets. Mitigates native off-heap memory exhaustion and iOS Jetsam kills caused by Kotlin/Native GC latency when handling high-frequency view recycling. Guarantees that canvas raster buffers and transient graphics contexts are closed explicitly via lifecycle hooks rather than deferred finalizers. 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: Unbounded Native Buffer Accumulation via GC-Deferred Finalization in Skiko Rendering 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 DriftUnbounded Native Buffer Accumulation via GC-Deferred Finalization in Skiko RenderingCritical
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 `.close()` or `.use { ... }` on Skiko Managed objects (e.g., `org.jetbrains.skia.Image`, `org.jetbrains.skia.Surface`, `org.jetbrains.skia.PictureRecorder`) as soon as their lifecycle ends.

Engineers MUST ALWAYS invoke `.close()` or `.use { ... }` on Skiko Managed objects (e.g., `org.jetbrains.skia.Image`, `org.jetbrains.skia.Surface`, `org.jetbrains.skia.PictureRecorder`) as soon as their lifecycle ends.

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 allocate native Skia/Skiko buffers or decode raster data inside Compose draw phases (`Modifier.drawWithContent`, `Canvas`, or `DrawScope`) without pooling or retaining references in a lifecycle-bound state holder.

Engineers MUST NOT allocate native Skia/Skiko buffers or decode raster data inside Compose draw phases (`Modifier.drawWithContent`, `Canvas`, or `DrawScope`) without pooling or retaining references in a lifecycle-bound state holder.

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 SHOULD bind long-lived native Skia references to the composition lifecycle using `DisposableEffect`, ensuring that `onDispose` explicitly triggers `.close()`.

Code SHOULD bind long-lived native Skia references to the composition lifecycle using `DisposableEffect`, ensuring that `onDispose` explicitly triggers `.close()`.

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 implement pooling mechanisms with bounded native off-heap memory quotas for reusable bitmaps and surfaces when rendering high-frequency collections (`LazyColumn`, `LazyRow`).

Services MUST implement pooling mechanisms with bounded native off-heap memory quotas for reusable bitmaps and surfaces when rendering high-frequency collections (`LazyColumn`, `LazyRow`).

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 rely on Kotlin/Native Garbage Collection or finalize routines to reclaim off-heap C++/Metal textures, as the GC scheduler is unaware of external native memory pressure.

Components NEVER rely on Kotlin/Native Garbage Collection or finalize routines to reclaim off-heap C++/Metal textures, as the GC scheduler is unaware of external native memory pressure.

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 Deterministic Skiko Native Resource Disposal in Compose Multiplatform critical for AI coding assistants?

Enforces immediate and deterministic deallocation of native Skia/Skiko resources (such as Image, Surface, PictureRecorder, and NativePointer wrappers) across Compose Multiplatform iOS and Desktop targets. Mitigates native off-heap memory exhaustion and iOS Jetsam kills caused by Kotlin/Native GC latency when handling high-frequency view recycling. Guarantees that canvas raster buffers and transient graphics contexts are closed explicitly via lifecycle hooks rather than deferred finalizers. 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 (Unbounded Native Buffer Accumulation via GC-Deferred Finalization in Skiko Rendering) 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

Deterministic