This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: compose-multiplatform-skiko-buffer-reclaim-guardrail

Compose Multiplatform Skiko Offscreen Buffer Reclaim Invariant

Enforces deterministic GPU framebuffer, render target, and Skia surface disposal when native iOS (UIKit) and Android (Activity/Fragment) lifecycles transition to stopped or background states. Skiko offscreen buffers retain significant uncompressed VRAM that the OS compositor cannot evict under memory pressure, triggering jetsam (iOS) or Low Memory Killer (Android) terminations. This guardrail mandates explicit lifecycle-bound surface tearing and context suspension.

Prohibited Anti-Pattern: Retaining Skiko Render Targets and Skia Metal/OpenGL Surfaces Across Native App Pauses

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko Offscreen Buffer Reclaim Invariant - Enforces deterministic GPU framebuffer, render target, and Skia surface disposal when native iOS (UIKit) and Android (Activity/Fragment) lifecycles transition to stopped or background states. Skiko offscreen buffers retain significant uncompressed VRAM that the OS compositor cannot evict under memory pressure, triggering jetsam (iOS) or Low Memory Killer (Android) terminations. This guardrail mandates explicit lifecycle-bound surface tearing and context suspension.
globs: **/iosApp/**/*.kt, **/iosApp/**/*.swift, **/androidApp/**/*.kt, **/commonMain/**/graphics/**/*.kt, **/commonMain/**/ui/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-buffer-reclaim-guardrail"
---

# Compose Multiplatform Skiko Offscreen Buffer Reclaim Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Retaining Skiko Render Targets and Skia Metal/OpenGL Surfaces Across Native App Pauses

## System Constraints
You are a Principal Mobile Architect specializing in Compose Multiplatform and graphics runtime internals. You strictly mandate deterministic disposal of Skiko offscreen buffers, Skia surfaces, and underlying GPU draw contexts across Android and iOS application lifecycle events to prevent OOM process termination.

## Strict Guidelines
- Engineers MUST ALWAYS hook into native lifecycle boundaries (Activity.onStop / UIApplication.didEnterBackgroundNotification) to explicitly destroy or invalidate Skia/Skiko offscreen render buffers.
- Engineers MUST NOT cache Skiko offscreen bitmap buffers or Metal/Vulkan textures across background transitions under the assumption that the garbage collector or ARC will reclaim GPU allocations.
- Engineers MUST release references to Skia Surface (`org.jetbrains.skia.Surface`), Canvas, and Image instances immediately upon surface destruction callbacks before invoking super lifecycle methods.
- Components NEVER hold strong references to `SkiaLayer` or `MetalRedrawer` instances across Compose Multiplatform view controller detachment or fragment de-parenting.
- Code SHOULD leverage zero-allocation offscreen caching policies where buffers are lazily reallocated only upon native resume (`onResume` / `didBecomeActiveNotification`).

## Bad vs Good Implementations
### Android & iOS Lifecycle-Coupled Skiko Buffer Disposal

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to release native Skia surfaces during lifecycle backgrounding causes native GPU memory to persist, causing Android LMK or iOS Jetsam to kill the application while backgrounded.
```kotlin
// Anti-Pattern: Retaining offscreen Skia Surface across backgrounding
class OffscreenGraphicsPipeline {
    private var surface: org.jetbrains.skia.Surface? = null

    fun allocate(width: Int, height: Int) {
        if (surface == null) {
            surface = org.jetbrains.skia.Surface.makeRasterN32Premul(width, height)
        }
    }

    // Retains VRAM/RAM allocations indefinitely when Activity stops or app backgrounds
    fun render(block: (org.jetbrains.skia.Canvas) -> Unit) {
        surface?.canvas?.let(block)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Implementing DefaultLifecycleObserver guarantees that offscreen buffers and underlying native Skia C++ allocations are closed deterministically on onStop, dropping resident memory before OS background checks.
```kotlin
// Production Invariant: Explicit lifecycle-tied disposal of GPU-backed Skiko/Skia allocations
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import org.jetbrains.skia.Surface

class LifecycleAwareSkiaSurfaceHolder : DefaultLifecycleObserver {
    private var surface: Surface? = null

    fun acquireSurface(width: Int, height: Int): Surface {
        val existing = surface
        if (existing != null && !existing.isClosed && existing.width == width && existing.height == height) {
            return existing
        }
        releaseSurface()
        return Surface.makeRasterN32Premul(width, height).also { surface = it }
    }

    private fun releaseSurface() {
        surface?.close() // Explicitly release Skiko C++ / native GPU backing allocation
        surface = null
    }

    override fun onStop(owner: LifecycleOwner) {
        releaseSurface() // Deterministically free buffers before OS memory triage
        super.onStop(owner)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        releaseSurface()
        owner.lifecycle.removeObserver(this)
        super.onDestroy(owner)
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Skiko Offscreen Buffer Reclaim Invariant

Compose Multiplatform Skiko Offscreen Buffer Reclaim Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic GPU framebuffer, render target, and Skia surface disposal when native iOS (UIKit) and Android (Activity/Fragment) lifecycles transition to stopped or background states. Skiko offscreen buffers retain significant uncompressed VRAM that the OS compositor cannot evict under memory pressure, triggering jetsam (iOS) or Low Memory Killer (Android) terminations. This guardrail mandates explicit lifecycle-bound surface tearing and context suspension. 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 Skiko Render Targets and Skia Metal/OpenGL Surfaces Across Native App Pauses 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 Skiko Render Targets and Skia Metal/OpenGL Surfaces Across Native App PausesCritical
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 hook into native lifecycle boundaries (Activity.onStop / UIApplication.didEnterBackgroundNotification) to explicitly destroy or invalidate Skia/Skiko offscreen render buffers.

Engineers MUST ALWAYS hook into native lifecycle boundaries (Activity.onStop / UIApplication.didEnterBackgroundNotification) to explicitly destroy or invalidate Skia/Skiko offscreen render buffers.

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 cache Skiko offscreen bitmap buffers or Metal/Vulkan textures across background transitions under the assumption that the garbage collector or ARC will reclaim GPU allocations.

Engineers MUST NOT cache Skiko offscreen bitmap buffers or Metal/Vulkan textures across background transitions under the assumption that the garbage collector or ARC will reclaim GPU allocations.

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 release references to Skia Surface (`org.jetbrains.skia.Surface`), Canvas, and Image instances immediately upon surface destruction callbacks before invoking super lifecycle methods.

Engineers MUST release references to Skia Surface (`org.jetbrains.skia.Surface`), Canvas, and Image instances immediately upon surface destruction callbacks before invoking super lifecycle methods.

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 references to `SkiaLayer` or `MetalRedrawer` instances across Compose Multiplatform view controller detachment or fragment de-parenting.

Components NEVER hold strong references to `SkiaLayer` or `MetalRedrawer` instances across Compose Multiplatform view controller detachment or fragment de-parenting.

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

Code SHOULD leverage zero-allocation offscreen caching policies where buffers are lazily reallocated only upon native resume (`onResume` / `didBecomeActiveNotification`).

Code SHOULD leverage zero-allocation offscreen caching policies where buffers are lazily reallocated only upon native resume (`onResume` / `didBecomeActiveNotification`).

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 Offscreen Buffer Reclaim Invariant critical for AI coding assistants?

Enforces deterministic GPU framebuffer, render target, and Skia surface disposal when native iOS (UIKit) and Android (Activity/Fragment) lifecycles transition to stopped or background states. Skiko offscreen buffers retain significant uncompressed VRAM that the OS compositor cannot evict under memory pressure, triggering jetsam (iOS) or Low Memory Killer (Android) terminations. This guardrail mandates explicit lifecycle-bound surface tearing and context suspension. 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 Skiko Render Targets and Skia Metal/OpenGL Surfaces Across Native App Pauses) 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