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

Compose Multiplatform Skiko Native Surface and Buffer Recycling Invariant

Mandates the reuse and deterministic pooling of Skiko/Skia offscreen surfaces, render targets, and path objects during complex vector animations in Compose Multiplatform. Prevents Metal (iOS) and Vulkan/GLES (Android) unmanaged texture churn, GC-triggered finalizer stalls, and severe frame pacing drops during canvas transitions.

Prohibited Anti-Pattern: Instantiating Native Skia Surfaces and Bitmaps Inside Recomposition Loops and Uncached Draw Modifiers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Native Surface and Buffer Recycling Invariant - Mandates the reuse and deterministic pooling of Skiko/Skia offscreen surfaces, render targets, and path objects during complex vector animations in Compose Multiplatform. Prevents Metal (iOS) and Vulkan/GLES (Android) unmanaged texture churn, GC-triggered finalizer stalls, and severe frame pacing drops during canvas transitions.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-skiko-surface-recycling-standard"
---

# Compose Multiplatform Skiko Native Surface and Buffer Recycling Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Instantiating Native Skia Surfaces and Bitmaps Inside Recomposition Loops and Uncached Draw Modifiers

## System Constraints
You are a Principal Mobile Graphics Engineer enforcing the KMP Compose Multiplatform Skiko Surface Recycling Standard. You must guarantee that native Skia/Skiko rendering resources (Surfaces, RenderTargets, Textures, Paths, PictureRecorders) are never instantiated per-frame or inside naked draw scopes without deterministic lifecycle management and pooling, avoiding GPU VRAM thrashing and frame hitches across iOS and Android.

## Strict Guidelines
- Engineers MUST ALWAYS isolate offscreen Skia rendering into `Modifier.drawWithCache` to ensure backing allocations are tied to canvas dimension changes rather than draw passes.
- Engineers MUST NOT instantiate `Surface.makeRenderTarget`, `Surface.makeRasterN32Premul`, or `Image.makeFromBitmap` directly inside a Compose `Canvas` or `Modifier.drawBehind` block.
- Components NEVER allocate new `org.jetbrains.skia.Path` or `androidx.compose.ui.graphics.Path` instances inside the critical render path; mutable path state MUST be reused via `.reset()` and `.rewind()`.
- Code SHOULD leverage `androidx.compose.ui.graphics.drawscope.drawIntoCanvas` with a retained native surface cache or use Compose `PictureRecorder` / `GraphicsLayer` caching to defer GPU texture rasterization.
- Services and custom Canvas components MUST implement deterministic `AutoCloseable` or `DisposableEffect` cleanups on all retained Skia native wrappers to prevent Metal/Vulkan VRAM leaks across screen navigation transitions.

## Bad vs Good Implementations
### Complex Vector Morphing Surface Allocation in Compose Multiplatform

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating native Skia Surfaces, Bitmaps, and Paths inside the raw draw pass triggers continuous native heap allocations and VRAM re-allocations on Metal (iOS) and GLES/Vulkan (Android). Garbage collection and native finalizers fail to catch up with 120Hz/60Hz display links, resulting in severe frame stutter, pipeline stalls, and eventual out-of-memory crashes.
```kotlin
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import org.jetbrains.skia.Surface
import org.jetbrains.skia.Paint
import org.jetbrains.skia.Path

@Composable
fun VectorMorphTransition(progress: Float, modifier: Modifier = Modifier) {
    // ANTI-PATTERN: Native Path and offscreen Skia Surface allocated every frame
    Canvas(modifier = modifier) {
        val path = Path() // Triggers continuous unmanaged heap allocation
        path.moveTo(0f, 0f)
        path.lineTo(size.width * progress, size.height * progress)

        drawIntoCanvas { canvas ->
            // Allocates raw GPU/Raster backing texture per frame, causing massive VRAM thrashing
            val offscreenSurface = Surface.makeRasterN32Premul(size.width.toInt(), size.height.toInt())
            val surfaceCanvas = offscreenSurface.canvas
            val paint = Paint().apply { color = 0xFFFF0000.toInt() }
            
            surfaceCanvas.drawPath(path, paint)
            val image = offscreenSurface.makeImageSnapshot()
            canvas.nativeCanvas.drawImage(image, 0f, 0f)
            // Finalizers forced to deallocate GPU buffers asynchronously
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Reuses a single persistent Path container via reset() and confines raster layout calculations within drawWithCache. Avoids intermediate Skia surface allocations by rendering directly to the hardware-accelerated target frame buffer, guaranteeing consistent 120fps pacing and zero unmanaged texture thrashing.
```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke

@Composable
fun VectorMorphTransition(progress: Float, modifier: Modifier = Modifier) {
    // Retain path state across recompositions to avoid heap churn
    val reusablePath = remember { Path() }

    // DRAW WITH CACHE: Buffer drawing operations and prevent per-frame GPU reallocations
    Modifier
        .then(modifier)
        .drawWithCache {
            onDrawWithContent {
                reusablePath.reset()
                reusablePath.moveTo(0f, 0f)
                reusablePath.lineTo(size.width * progress, size.height * progress)

                // Direct vector rendering on existing backing layer; zero offscreen surface churn
                drawPath(
                    path = reusablePath,
                    color = Color.Red,
                    style = Stroke(width = 4f)
                )
            }
        }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Skiko Native Surface and Buffer Recycling Invariant

Compose Multiplatform Skiko Native Surface and Buffer Recycling Invariant defines an industrial-grade behavioral standard for mobile engineering. Mandates the reuse and deterministic pooling of Skiko/Skia offscreen surfaces, render targets, and path objects during complex vector animations in Compose Multiplatform. Prevents Metal (iOS) and Vulkan/GLES (Android) unmanaged texture churn, GC-triggered finalizer stalls, and severe frame pacing drops during canvas 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: Instantiating Native Skia Surfaces and Bitmaps Inside Recomposition Loops and Uncached Draw Modifiers 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 DriftInstantiating Native Skia Surfaces and Bitmaps Inside Recomposition Loops and Uncached Draw ModifiersCritical
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 isolate offscreen Skia rendering into `Modifier.drawWithCache` to ensure backing allocations are tied to canvas dimension changes rather than draw passes.

Engineers MUST ALWAYS isolate offscreen Skia rendering into `Modifier.drawWithCache` to ensure backing allocations are tied to canvas dimension changes rather than draw 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.
2

Engineers MUST NOT instantiate `Surface.makeRenderTarget`, `Surface.makeRasterN32Premul`, or `Image.makeFromBitmap` directly inside a Compose `Canvas` or `Modifier.drawBehind` block.

Engineers MUST NOT instantiate `Surface.makeRenderTarget`, `Surface.makeRasterN32Premul`, or `Image.makeFromBitmap` directly inside a Compose `Canvas` or `Modifier.drawBehind` block.

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

Components NEVER allocate new `org.jetbrains.skia.Path` or `androidx.compose.ui.graphics.Path` instances inside the critical render path

Components NEVER allocate new `org.jetbrains.skia.Path` or `androidx.compose.ui.graphics.Path` instances inside the critical render path; mutable path state MUST be reused via `.reset()` and `.rewind()`.

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

Code SHOULD leverage `androidx.compose.ui.graphics.drawscope.drawIntoCanvas` with a retained native surface cache or use Compose `PictureRecorder` / `GraphicsLayer` caching to defer GPU texture rasterization.

Code SHOULD leverage `androidx.compose.ui.graphics.drawscope.drawIntoCanvas` with a retained native surface cache or use Compose `PictureRecorder` / `GraphicsLayer` caching to defer GPU texture rasterization.

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 and custom Canvas components MUST implement deterministic `AutoCloseable` or `DisposableEffect` cleanups on all retained Skia native wrappers to prevent Metal/Vulkan VRAM leaks across screen navigation transitions.

Services and custom Canvas components MUST implement deterministic `AutoCloseable` or `DisposableEffect` cleanups on all retained Skia native wrappers to prevent Metal/Vulkan VRAM leaks across screen navigation transitions.

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 Skiko Native Surface and Buffer Recycling Invariant critical for AI coding assistants?

Mandates the reuse and deterministic pooling of Skiko/Skia offscreen surfaces, render targets, and path objects during complex vector animations in Compose Multiplatform. Prevents Metal (iOS) and Vulkan/GLES (Android) unmanaged texture churn, GC-triggered finalizer stalls, and severe frame pacing drops during canvas 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 (Instantiating Native Skia Surfaces and Bitmaps Inside Recomposition Loops and Uncached Draw Modifiers) 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