This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-direct-memory-render-buffer-pacing-guardrail

Compose Multiplatform Direct-Memory Render Buffer Pacing Guardrail

Prevents catastrophic off-heap native memory exhaustion and micro-stutter during rapid vector path and bitmap render loops across Skia, Metal, and Vulkan backends. Enforces synchronous native surface handle recycling, double-buffering cadence synchronization, and strict disposal of intermediate org.jetbrains.skia graphics objects within Compose Multiplatform drawing routines.

Prohibited Anti-Pattern: Unmanaged Off-Heap Skia Allocations and Unthrottled Native Pixel Buffer Reallocations in Canvas Draw Loops

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Direct-Memory Render Buffer Pacing Guardrail - Prevents catastrophic off-heap native memory exhaustion and micro-stutter during rapid vector path and bitmap render loops across Skia, Metal, and Vulkan backends. Enforces synchronous native surface handle recycling, double-buffering cadence synchronization, and strict disposal of intermediate org.jetbrains.skia graphics objects within Compose Multiplatform drawing routines.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt, **/ui/**/*.kt, **/graphics/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-direct-memory-render-buffer-pacing-guardrail"
---

# Compose Multiplatform Direct-Memory Render Buffer Pacing Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unmanaged Off-Heap Skia Allocations and Unthrottled Native Pixel Buffer Reallocations in Canvas Draw Loops

## System Constraints
You are a Principal Mobile Graphics Engineer enforcing Compose Multiplatform Native Memory and Render Buffer Pacing standards. You must eliminate all off-heap native allocations inside Canvas draw loops, enforce strictly bounded object pooling for Skia/Skiko NativePointer structures (Image, Picture, Path, Surface), and mandate hardware frame synchronization across iOS (Metal/CADisplayLink) and Android (Vulkan/Choreographer). Reject any unmanaged Skia surface construction within recomposition scopes.

## Strict Guidelines
- Engineers MUST ALWAYS pre-allocate and reuse native Skia Path, Paint, and Shader instances outside Compose DrawScope or Canvas callbacks using remember { } lifecycle holders.
- Engineers MUST ALWAYS explicitly close and release native off-heap handles via `autoCloseScope { }` or explicit `.close()` / `.use { }` blocks when instantiating intermediate Skia PictureRecorder, Surface, or Image instances.
- Engineers MUST NOT instantiate direct native buffers, raw pixel byte arrays, or allocate org.jetbrains.skia.Image instances directly inside `Modifier.drawWithContent`, `Modifier.drawBehind`, or `Canvas()` draw passes.
- Render pipelines MUST synchronize rasterization updates to the display refresh cadence using platform frame tokens rather than unthrottled Kotlin Coroutine Dispatchers (such as Dispatchers.Default or Dispatchers.IO).
- Dynamic off-screen buffers (e.g., Skia Surface / Metal Texture targets) MUST implement fixed-size double-buffering with strict capacity caps and retain their backing buffers across consecutive frame cycles instead of re-allocating per frame.
- Components NEVER bridge raw C-pointers or Skia NativePointer representations across thread boundaries without holding a synchronized retain/release lock or checking isClosed status.

## Bad vs Good Implementations
### Skia Off-Screen Vector Buffer Rendering & Memory Management

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocating `Surface.makeRasterN32Premul`, `Path`, `Paint`, and `surface.makeImageSnapshot()` on every frame execution bypasses JVM garbage collection, causing rapid off-heap C++ memory spikes. This crashes Metal on iOS with Jetsam events and causes Severe Frame Drop (jank) on Android.
```kotlin
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import org.jetbrains.skia.Image
import org.jetbrains.skia.Surface

@Composable
fun DynamicVectorGraph(modifier: Modifier, rawData: FloatArray) {
    // ANTI-PATTERN: Native Skia Surface and Image created inside DrawScope every frame.
    // Bypasses Skiko buffer caches, leaking unmanaged Metal/Vulkan textures and triggering GC freezes.
    Canvas(modifier = modifier) {
        val width = size.width.toInt()
        val height = size.height.toInt()
        if (width <= 0 || height <= 0) return@Canvas

        val surface = Surface.makeRasterN32Premul(width, height)
        val canvas = surface.canvas
        
        // Direct drawing without pooling or handle management
        val path = org.jetbrains.skia.Path()
        rawData.forEachIndexed { i, value ->
            if (i == 0) path.moveTo(0f, value) else path.lineTo(i.toFloat(), value)
        }
        val paint = org.jetbrains.skia.Paint().apply { color = 0xFF00FF00.toInt() }
        canvas.drawPath(path, paint)

        val skiaImage = surface.makeImageSnapshot() // Off-heap buffer leak: never closed
        // Drawing directly into Compose Canvas...
    }
}
```

#### Production Standard (Correct)
> **Standard**: The native Skia resources (Path, Paint) are allocated once, reused continuously, and explicitly torn down on Composable disposal via `DisposableEffect { onDispose { ... } }`. Zero allocation occurs in the draw loop, entirely preventing unmanaged Metal/Skia buffer bloat.
```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.asComposePath
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import org.jetbrains.skia.Paint
import org.jetbrains.skia.Path

@Composable
fun DynamicVectorGraph(modifier: Modifier, rawData: FloatArray) {
    // PRODUCTION FIX: Reuse single path and paint references across recomposition.
    // Native lifecycle bound to Composable lifecycle via remember and DisposableEffect.
    val nativePath = remember { Path() }
    val nativePaint = remember {
        Paint().apply {
            color = 0xFF00FF00.toInt()
            isAntiAlias = true
        }
    }

    DisposableEffect(nativePath, nativePaint) {
        onDispose {
            nativePath.close()
            nativePaint.close()
        }
    }

    Canvas(modifier = modifier) {
        if (rawData.isEmpty()) return@Canvas

        nativePath.reset()
        rawData.forEachIndexed { i, value ->
            val x = i.toFloat()
            if (i == 0) nativePath.moveTo(x, value) else nativePath.lineTo(x, value)
        }

        drawIntoCanvas { canvas ->
            canvas.nativeCanvas.drawPath(nativePath, nativePaint)
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Direct-Memory Render Buffer Pacing Guardrail

Compose Multiplatform Direct-Memory Render Buffer Pacing Guardrail defines an industrial-grade behavioral standard for mobile engineering. Prevents catastrophic off-heap native memory exhaustion and micro-stutter during rapid vector path and bitmap render loops across Skia, Metal, and Vulkan backends. Enforces synchronous native surface handle recycling, double-buffering cadence synchronization, and strict disposal of intermediate org.jetbrains.skia graphics objects within Compose Multiplatform drawing routines. 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: Unmanaged Off-Heap Skia Allocations and Unthrottled Native Pixel Buffer Reallocations in Canvas Draw Loops 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 DriftUnmanaged Off-Heap Skia Allocations and Unthrottled Native Pixel Buffer Reallocations in Canvas Draw LoopsCritical
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 pre-allocate and reuse native Skia Path, Paint, and Shader instances outside Compose DrawScope or Canvas callbacks using remember { } lifecycle holders.

Engineers MUST ALWAYS pre-allocate and reuse native Skia Path, Paint, and Shader instances outside Compose DrawScope or Canvas callbacks using remember { } lifecycle holders.

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 explicitly close and release native off-heap handles via `autoCloseScope { }` or explicit `.close()` / `.use { }` blocks when instantiating intermediate Skia PictureRecorder, Surface, or Image instances.

Engineers MUST ALWAYS explicitly close and release native off-heap handles via `autoCloseScope { }` or explicit `.close()` / `.use { }` blocks when instantiating intermediate Skia PictureRecorder, Surface, or Image instances.

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 instantiate direct native buffers, raw pixel byte arrays, or allocate org.jetbrains.skia.Image instances directly inside `Modifier.drawWithContent`, `Modifier.drawBehind`, or `Canvas()` draw passes.

Engineers MUST NOT instantiate direct native buffers, raw pixel byte arrays, or allocate org.jetbrains.skia.Image instances directly inside `Modifier.drawWithContent`, `Modifier.drawBehind`, or `Canvas()` 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.
4

Render pipelines MUST synchronize rasterization updates to the display refresh cadence using platform frame tokens rather than unthrottled Kotlin Coroutine Dispatchers (such as Dispatchers.Default or Dispatchers.IO).

Render pipelines MUST synchronize rasterization updates to the display refresh cadence using platform frame tokens rather than unthrottled Kotlin Coroutine Dispatchers (such as Dispatchers.Default or Dispatchers.IO).

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

Dynamic off-screen buffers (e.g., Skia Surface / Metal Texture targets) MUST implement fixed-size double-buffering with strict capacity caps and retain their backing buffers across consecutive frame cycles instead of re-allocating per frame.

Dynamic off-screen buffers (e.g., Skia Surface / Metal Texture targets) MUST implement fixed-size double-buffering with strict capacity caps and retain their backing buffers across consecutive frame cycles instead of re-allocating per frame.

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.
6

Components NEVER bridge raw C-pointers or Skia NativePointer representations across thread boundaries without holding a synchronized retain/release lock or checking isClosed status.

Components NEVER bridge raw C-pointers or Skia NativePointer representations across thread boundaries without holding a synchronized retain/release lock or checking isClosed status.

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 Direct-Memory Render Buffer Pacing Guardrail critical for AI coding assistants?

Prevents catastrophic off-heap native memory exhaustion and micro-stutter during rapid vector path and bitmap render loops across Skia, Metal, and Vulkan backends. Enforces synchronous native surface handle recycling, double-buffering cadence synchronization, and strict disposal of intermediate org.jetbrains.skia graphics objects within Compose Multiplatform drawing routines. 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 (Unmanaged Off-Heap Skia Allocations and Unthrottled Native Pixel Buffer Reallocations in Canvas Draw Loops) 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