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

KMP Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail

Enforces lifecycle-bound texture pooling, dirty-state synchronization, and explicit teardown for offscreen rendering surfaces in Compose Multiplatform across iOS (Metal) and Android (Vulkan). Eliminates unthrottled VSync invalidation loops and GPU VRAM exhaustion caused by orphaned hardware buffers, unreleased Skia surfaces, and asynchronous swapchain deadlocks.

Prohibited Anti-Pattern: Unbounded VSync Invalidation Loops and Leaked Metal/Vulkan Native Surfaces in Compose Multiplatform Custom Drawing Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail - Enforces lifecycle-bound texture pooling, dirty-state synchronization, and explicit teardown for offscreen rendering surfaces in Compose Multiplatform across iOS (Metal) and Android (Vulkan). Eliminates unthrottled VSync invalidation loops and GPU VRAM exhaustion caused by orphaned hardware buffers, unreleased Skia surfaces, and asynchronous swapchain deadlocks.
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-offscreen-surface-invalidation-guardrail"
---

# KMP Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded VSync Invalidation Loops and Leaked Metal/Vulkan Native Surfaces in Compose Multiplatform Custom Drawing Pipelines

## System Constraints
You are a Principal Mobile Graphics Architect enforcing strict hardware surface resource management in Kotlin Multiplatform (Compose Multiplatform) applications targeting iOS (Metal) and Android (Vulkan). You mandate that any offscreen rendering surface, Skia Image/Surface, or platform-native hardware buffer must be lifecycle-bound, throttled to actual state changes, and explicitly disposed of upon leaving composition.

## Strict Guidelines
- Engineers MUST ALWAYS tie custom native graphics resources (CAMetalLayer, Vulkan HardwareBuffers, Skia SkSurface) to Compose lifecycle via DisposableEffect or rememberObserver with explicit deallocation routines.
- Engineers MUST NOT trigger surface invalidation on unconstrained VSync loops or Compose recomposition passes without verifying dirty render state or explicit input changes.
- Code SHOULD implement dual-buffered texture swapping with deterministic size matching, ensuring reallocation occurs only when container dimensions mutate rather than on every draw phase pass.
- Components NEVER instantiate Skia Surfaces or hardware framebuffers directly inside the DrawScope lambda or DrawModifierNode.draw() invocation path.
- Services MUST monitor native application lifecycle (background/foreground transitions) and release offscreen VRAM allocations immediately upon background entry to avert OS-level OOM kills.

## Bad vs Good Implementations
### Offscreen Surface Lifecycle & Invalidation in Compose Multiplatform

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates a new raster/GPU surface on every frame inside DrawScope, generating massive VRAM churn and GC pressure. Continuously animates and redraws regardless of whether the underlying payload changed, causing thermal throttling and high battery drain on Metal and Vulkan pipelines without freeing native C++ pointers.
```kotlin
// BAD: Allocating offscreen SkSurface in draw phase and invalidating continuously on VSync
@Composable
fun MetalVulkanOffscreenRenderer(
    modifier: Modifier = Modifier,
    payload: RenderPayload
) {
    val infiniteTransition = rememberInfiniteTransition()
    val phase by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(tween(1000, easing = LinearEasing))
    )

    Canvas(modifier = modifier.fillMaxSize()) {
        // Re-allocating surface on every draw pass exhausts GPU VRAM rapidly
        val surface = org.jetbrains.skia.Surface.makeRasterN32Premul(
            size.width.toInt().coerceAtLeast(1),
            size.height.toInt().coerceAtLeast(1)
        )
        val canvas = surface.canvas
        canvas.clear(org.jetbrains.skia.Color.TRANSPARENT)
        // Drawing without checking dirty rects or caching hardware textures
        renderCustomPass(canvas, payload, phase)
        
        val image = surface.makeImageSnapshot()
        drawImage(image.toComposeImageBitmap())
        // Memory leak: surface and image native handles are abandoned to GC
    }
}
```

#### Production Standard (Correct)
> **Standard**: Moves surface creation out of the draw cycle into a cached, reusable holder using `drawWithCache`. Surfaces are reallocated only when bounds change, rendered only when marked dirty, and natively freed immediately when leaving the composition hierarchy via `DisposableEffect`.
```kotlin
// GOOD: Pre-allocated, lifecycle-bound surface with dirty-flag checking and deterministic disposal
@Composable
fun MetalVulkanOffscreenRenderer(
    modifier: Modifier = Modifier,
    payload: RenderPayload
) {
    val density = LocalDensity.current
    // Retain and manage lifecycle of native graphics surface
    val surfaceHolder = remember { ManagedSurfaceHolder() }

    DisposableEffect(surfaceHolder) {
        onDispose {
            surfaceHolder.releaseResources()
        }
    }

    // Invalidate solely when payload content actually changes
    LaunchedEffect(payload) {
        surfaceHolder.markDirty()
    }

    Spacer(
        modifier = modifier
            .fillMaxSize()
            .drawWithCache {
                val width = size.width.toInt().coerceAtLeast(1)
                val height = size.height.toInt().coerceAtLeast(1)
                surfaceHolder.ensureCapacity(width, height)

                onDrawWithContent {
                    if (surfaceHolder.isDirty) {
                        surfaceHolder.renderOffscreen(payload)
                    }
                    surfaceHolder.drawToTarget(drawContext.canvas)
                }
            }
    )
}

private class ManagedSurfaceHolder : AutoCloseable {
    private var surface: org.jetbrains.skia.Surface? = null
    var isDirty: Boolean = true
        private set

    fun ensureCapacity(width: Int, height: Int) {
        if (surface == null || surface?.width != width || surface?.height != height) {
            surface?.close() // Release native C++ / GPU backing
            surface = org.jetbrains.skia.Surface.makeRenderTarget(
                org.jetbrains.skia.DirectContext.makeMetal(), // Or platform-abstracted context
                org.jetbrains.skia.Budgeted.YES,
                org.jetbrains.skia.ImageInfo.makeN32Premul(width, height)
            )
            isDirty = true
        }
    }

    fun markDirty() { isDirty = true }

    fun renderOffscreen(payload: RenderPayload) {
        val s = surface ?: return
        s.canvas.clear(org.jetbrains.skia.Color.TRANSPARENT)
        // Perform drawing into cached surface
        isDirty = false
    }

    fun drawToTarget(canvas: androidx.compose.ui.graphics.Canvas) {
        surface?.makeImageSnapshot()?.use { snapshot ->
            canvas.drawImage(snapshot.toComposeImageBitmap(), androidx.compose.ui.geometry.Offset.Zero, androidx.compose.ui.graphics.Paint())
        }
    }

    fun releaseResources() {
        surface?.close()
        surface = null
    }

    override fun close() = releaseResources()
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail

KMP Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces lifecycle-bound texture pooling, dirty-state synchronization, and explicit teardown for offscreen rendering surfaces in Compose Multiplatform across iOS (Metal) and Android (Vulkan). Eliminates unthrottled VSync invalidation loops and GPU VRAM exhaustion caused by orphaned hardware buffers, unreleased Skia surfaces, and asynchronous swapchain deadlocks. 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 VSync Invalidation Loops and Leaked Metal/Vulkan Native Surfaces in Compose Multiplatform Custom Drawing Pipelines 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 VSync Invalidation Loops and Leaked Metal/Vulkan Native Surfaces in Compose Multiplatform Custom Drawing PipelinesCritical
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 tie custom native graphics resources (CAMetalLayer, Vulkan HardwareBuffers, Skia SkSurface) to Compose lifecycle via DisposableEffect or rememberObserver with explicit deallocation routines.

Engineers MUST ALWAYS tie custom native graphics resources (CAMetalLayer, Vulkan HardwareBuffers, Skia SkSurface) to Compose lifecycle via DisposableEffect or rememberObserver with explicit deallocation routines.

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 trigger surface invalidation on unconstrained VSync loops or Compose recomposition passes without verifying dirty render state or explicit input changes.

Engineers MUST NOT trigger surface invalidation on unconstrained VSync loops or Compose recomposition passes without verifying dirty render state or explicit input changes.

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 implement dual-buffered texture swapping with deterministic size matching, ensuring reallocation occurs only when container dimensions mutate rather than on every draw phase pass.

Code SHOULD implement dual-buffered texture swapping with deterministic size matching, ensuring reallocation occurs only when container dimensions mutate rather than on every draw phase pass.

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 instantiate Skia Surfaces or hardware framebuffers directly inside the DrawScope lambda or DrawModifierNode.draw() invocation path.

Components NEVER instantiate Skia Surfaces or hardware framebuffers directly inside the DrawScope lambda or DrawModifierNode.draw() invocation path.

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 monitor native application lifecycle (background/foreground transitions) and release offscreen VRAM allocations immediately upon background entry to avert OS-level OOM kills.

Services MUST monitor native application lifecycle (background/foreground transitions) and release offscreen VRAM allocations immediately upon background entry to avert OS-level OOM kills.

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 Compose Multiplatform Offscreen Surface Invalidation & Lifecycle Guardrail critical for AI coding assistants?

Enforces lifecycle-bound texture pooling, dirty-state synchronization, and explicit teardown for offscreen rendering surfaces in Compose Multiplatform across iOS (Metal) and Android (Vulkan). Eliminates unthrottled VSync invalidation loops and GPU VRAM exhaustion caused by orphaned hardware buffers, unreleased Skia surfaces, and asynchronous swapchain deadlocks. 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 VSync Invalidation Loops and Leaked Metal/Vulkan Native Surfaces in Compose Multiplatform Custom Drawing Pipelines) 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