This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-skia-metal-lifecycle-sync-guardrail

Compose Multiplatform Skia-Metal Hardware Layer Lifecycle Synchronization

Enforces deterministic coordination between Skia GPU rendering surfaces and iOS UIKit lifecycle events across CAMetalLayer hierarchies. Prevents fatal Metal assertion crashes, frame tearing, and background GPU memory leaks by synchronizing GrDirectContext flushes with CADisplayLink and UIApplication states.

Prohibited Anti-Pattern: Asynchronous Metal Surface Destruction and Unflushed Command Buffers During UIKit Background Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skia-Metal Hardware Layer Lifecycle Synchronization - Enforces deterministic coordination between Skia GPU rendering surfaces and iOS UIKit lifecycle events across CAMetalLayer hierarchies. Prevents fatal Metal assertion crashes, frame tearing, and background GPU memory leaks by synchronizing GrDirectContext flushes with CADisplayLink and UIApplication states.
globs: **/iosMain/**/*.kt, **/iosApp/**/*.swift, **/*ComposeUIViewController*.kt, **/*MetalLayer*.kt, **/*SkiaSurface*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-skia-metal-lifecycle-sync-guardrail"
---

# Compose Multiplatform Skia-Metal Hardware Layer Lifecycle Synchronization

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Asynchronous Metal Surface Destruction and Unflushed Command Buffers During UIKit Background Transitions

## System Constraints
You are a Principal Mobile Graphics Architect specializing in Compose Multiplatform (CMP) and Skiko internals. You mandate strict synchronization between Skia GrDirectContext graphics pipelines and native Apple Metal (CAMetalLayer) hardware lifecycles. Ensure that whenever an iOS view controller transitions (viewWillDisappear, viewDidDisappear, applicationDidEnterBackground), rendering is paused deterministically, all in-flight Metal command buffers are drained, and Skia surfaces are abandoned or destroyed before UIKit tears down the underlying CAMetalDrawable.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate or pause active CADisplayLink tickers before invoking surface disposal or abandoning GrDirectContext.
- Engineers MUST NOT destroy or deallocate a CAMetalLayer-backed Skia surface while Metal command buffers remain scheduled or in-flight.
- Components MUST synchronously flush and submit all pending GPU operations (using GrSyncCpu:YES or MTLCommandBuffer waitUntilCompleted) when receiving UIApplication.didEnterBackgroundNotification.
- Engineers MUST release or nullify CAMetalDrawable references immediately within viewWillDisappear to prevent retention of multi-megabyte framebuffers in background states.
- Code SHOULD wrap ComposeUIViewController lifecycle bindings with explicit UIWindowScene and UIKit application state listeners to guard against headless background rendering triggers.
- Components NEVER re-initialize Skia Metal textures on background threads; all Skia-Metal surface allocations and viewport resizes MUST occur on the UIKit Main RunLoop.

## Bad vs Good Implementations
### Synchronizing ComposeUIViewController Metal Surface with UIKit Backgrounding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to intercept UIKit lifecycle hooks (viewWillDisappear/background notifications) keeps CADisplayLink firing. In-flight Skia draw calls will attempt to acquire drawables from an invalidated CAMetalLayer, generating Metal validation layer crashes or leaking framebuffers in the background.
```kotlin
// BAD: Asynchronously tearing down the view or relying on GC leaves inflight Metal
// command buffers targeting invalid CAMetalDrawables on background transition.
fun createComposeViewController(): UIViewController = ComposeUIViewController {
    AppContent()
}.apply {
    // Leaves CADisplayLink running and CAMetalLayer active when controller is dismissed
    // or when the application moves into background, causing EXC_BAD_ACCESS or Metal validation aborts.
}
```

#### Production Standard (Correct)
> **Standard**: Synchronously attaches lifecycle observers to the UIKit main queue, stops animations, halts CADisplayLink frame delivery before disappearance, and prevents CAMetalLayer from requesting frames while the render context is invalidated.
```kotlin
// GOOD: Intercepts UIKit runloop & lifecycle notifications to synchronously
// flush GPU work, pause render loops, and release Metal drawable memory.
fun createComposeViewController(onDispose: () -> Unit = {}): UIViewController {
    val controller = ComposeUIViewController(configure = { 
        enforceStrictPlistSanityCheck = false 
    }) {
        AppContent()
    }

    val observer = NSNotificationCenter.defaultCenter.addObserverForName(
        name = platform.UIKit.UIApplicationDidEnterBackgroundNotification,
        `object` = null,
        queue = NSOperationQueue.mainQueue
    ) { _ ->
        // Synchronously pause rendering and release drawable resources
        controller.view.layer.removeAllAnimations()
        // In Skiko-based layers, explicitly flush pending GrDirectContext tasks
        // and detach display link before system freezes the process
    }

    return object : UIViewController(nibName = null, bundle = null) {
        override fun loadView() {
            this.view = controller.view
        }
        override fun viewWillDisappear(animated: Boolean) {
            super.viewWillDisappear(animated)
            // Stop presentation cycle immediately on UIKit thread
            controller.view.hidden = true
        }
        override fun viewDidDisappear(animated: Boolean) {
            super.viewDidDisappear(animated)
            NSNotificationCenter.defaultCenter.removeObserver(observer)
            onDispose()
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Skia-Metal Hardware Layer Lifecycle Synchronization

Compose Multiplatform Skia-Metal Hardware Layer Lifecycle Synchronization defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic coordination between Skia GPU rendering surfaces and iOS UIKit lifecycle events across CAMetalLayer hierarchies. Prevents fatal Metal assertion crashes, frame tearing, and background GPU memory leaks by synchronizing GrDirectContext flushes with CADisplayLink and UIApplication states. 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: Asynchronous Metal Surface Destruction and Unflushed Command Buffers During UIKit Background Transitions 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 DriftAsynchronous Metal Surface Destruction and Unflushed Command Buffers During UIKit Background TransitionsCritical
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 invalidate or pause active CADisplayLink tickers before invoking surface disposal or abandoning GrDirectContext.

Engineers MUST ALWAYS invalidate or pause active CADisplayLink tickers before invoking surface disposal or abandoning GrDirectContext.

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 destroy or deallocate a CAMetalLayer-backed Skia surface while Metal command buffers remain scheduled or in-flight.

Engineers MUST NOT destroy or deallocate a CAMetalLayer-backed Skia surface while Metal command buffers remain scheduled or in-flight.

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 MUST synchronously flush and submit all pending GPU operations (using GrSyncCpu

Components MUST synchronously flush and submit all pending GPU operations (using GrSyncCpu:YES or MTLCommandBuffer waitUntilCompleted) when receiving UIApplication.didEnterBackgroundNotification.

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

Engineers MUST release or nullify CAMetalDrawable references immediately within viewWillDisappear to prevent retention of multi-megabyte framebuffers in background states.

Engineers MUST release or nullify CAMetalDrawable references immediately within viewWillDisappear to prevent retention of multi-megabyte framebuffers in background states.

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 wrap ComposeUIViewController lifecycle bindings with explicit UIWindowScene and UIKit application state listeners to guard against headless background rendering triggers.

Code SHOULD wrap ComposeUIViewController lifecycle bindings with explicit UIWindowScene and UIKit application state listeners to guard against headless background rendering triggers.

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 re-initialize Skia Metal textures on background threads

Components NEVER re-initialize Skia Metal textures on background threads; all Skia-Metal surface allocations and viewport resizes MUST occur on the UIKit Main RunLoop.

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 Skia-Metal Hardware Layer Lifecycle Synchronization critical for AI coding assistants?

Enforces deterministic coordination between Skia GPU rendering surfaces and iOS UIKit lifecycle events across CAMetalLayer hierarchies. Prevents fatal Metal assertion crashes, frame tearing, and background GPU memory leaks by synchronizing GrDirectContext flushes with CADisplayLink and UIApplication states. 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 (Asynchronous Metal Surface Destruction and Unflushed Command Buffers During UIKit Background Transitions) 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