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

Compose Multiplatform Skiko GPU Surface Lifecycle Invariant

Enforces deterministic teardown and re-instantiation of Skiko rendering delegates and hardware surfaces across Android and iOS lifecycle transitions. Prevents fatal GPU driver termination (SIGKILL 0xdead10cc on iOS Metal, VK_ERROR_DEVICE_LOST/EGL_BAD_SURFACE on Android) caused by mid-flight draw calls dispatched to invalidated swapchains during rapid background-foreground swaps.

Prohibited Anti-Pattern: Orphaned Skia Metal/OpenGL swapchains attempting buffer presentation after OS lifecycle backgrounding

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Skiko GPU Surface Lifecycle Invariant - Enforces deterministic teardown and re-instantiation of Skiko rendering delegates and hardware surfaces across Android and iOS lifecycle transitions. Prevents fatal GPU driver termination (SIGKILL 0xdead10cc on iOS Metal, VK_ERROR_DEVICE_LOST/EGL_BAD_SURFACE on Android) caused by mid-flight draw calls dispatched to invalidated swapchains during rapid background-foreground swaps.
globs: **/iosApp/**/*.swift, **/commonMain/**/*.kt, **/androidMain/**/*.kt, **/iosMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-gpu-surface-lifecycle-guardrail"
---

# Compose Multiplatform Skiko GPU Surface Lifecycle Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Orphaned Skia Metal/OpenGL swapchains attempting buffer presentation after OS lifecycle backgrounding

## System Constraints
You are a Principal Mobile Graphics Architect enforcing Skiko GPU surface lifecycle integrity in Compose Multiplatform. You must prevent native OS graphics context leaks, CAMetalDrawable race conditions, and GPU driver crashes by ensuring all hardware surfaces, Skia layers, and render delegates strictly synchronize with host OS foreground/background lifecycle states.

## Strict Guidelines
- Engineers MUST ALWAYS suspend the Skiko render loop and synchronously release or detach the CAMetalLayer or SurfaceHolder when the host application moves to the background.
- Engineers MUST NOT dispatch render commands or invoke Skia Canvas redraw operations from background threads without verifying active surface availability via a thread-safe lifecycle latch.
- Code SHOULD wrap ComposeUIViewController or Skiko-backed native views inside explicit platform lifecycle listeners (e.g., DefaultLifecycleObserver on Android, viewDidDisappear / sceneDidEnterBackground notifications on iOS).
- Services MUST flush pending graphics queues and invalidate hardware-bound SkSurface references prior to relinquishing control back to the OS background transition handler.
- Components NEVER capture strong references to native platform context handles (MTLDevice, EGLContext, or Android Surface) across Compose recomposition boundaries.

## Bad vs Good Implementations
### iOS ComposeUIViewController Hosting without Metal Surface Teardown (Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to notify Compose Multiplatform / Skiko runtime of application suspension causes the internal CADisplayLink and Skia Metal renderer to dispatch draw passes to an invalidated CAMetalDrawable when backgrounded, causing an immediate kernel driver abort.
```swift
import UIKit
import shared

class ComposeHostViewController: UIViewController {
    private var composeController: UIViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Anti-pattern: Instantiating ComposeUIViewController without hooking
        // into scene/app lifecycle for Skiko GPU surface release.
        let controller = MainViewControllerKt.MainViewController()
        addChild(controller)
        view.addSubview(controller.view)
        controller.view.frame = view.bounds
        controller.didMove(toParent: self)
        self.composeController = controller
    }
    // Fatal: App backgrounding causes CAMetalLayer render pass to fail
    // with SIGKILL (0xdead10cc) due to presentation of unrendered frame.
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly propagates foreground and background appearance transitions to ComposeUIViewController, guaranteeing that Skiko's internal display link is paused and underlying Metal render layers are detached prior to background lock.
```swift
import UIKit
import shared

class ComposeHostViewController: UIViewController {
    private var composeController: UIViewController?
    private var notificationObservers: [NSObjectProtocol] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        attachComposeHierarchy()
        observeLifecycleState()
    }

    private func attachComposeHierarchy() {
        let controller = MainViewControllerKt.MainViewController()
        addChild(controller)
        view.addSubview(controller.view)
        controller.view.frame = view.bounds
        controller.didMove(toParent: self)
        self.composeController = controller
    }

    private func observeLifecycleState() {
        let center = NotificationCenter.default
        let bgObserver = center.addObserver(
            forName: UIApplication.didEnterBackgroundNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            // Synchronously invalidate and detach presentation surfaces
            self?.composeController?.view.isHidden = true
            self?.composeController?.beginAppearanceTransition(false, animated: false)
            self?.composeController?.endAppearanceTransition()
        }

        let fgObserver = center.addObserver(
            forName: UIApplication.willEnterForegroundNotification,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.composeController?.beginAppearanceTransition(true, animated: false)
            self?.composeController?.view.isHidden = false
            self?.composeController?.endAppearanceTransition()
        }

        notificationObservers.append(contentsOf: [bgObserver, fgObserver])
    }

    deinit {
        notificationObservers.forEach { NotificationCenter.default.removeObserver($0) }
    }
}
```

### Android Custom Skiko/Compose Surface Lifecycle Disposal (Production Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When surfaceDestroyed is invoked, ongoing or queued Skia raster commands continue to reference the destroyed EGL/Vulkan surface, triggering fatal VK_ERROR_DEVICE_LOST or ANR graphics freezes.
```kotlin
// Anti-pattern: Storing raw native Surface/SkSurface in Compose state
// without synchronizing with LifecycleOwner pause/destroy events.
@Composable
fun UnsafeSkikoCanvasView(modifier: Modifier = Modifier) {
    val surfaceHolder = remember { mutableStateOf<SurfaceHolder?>(null) }
    
    AndroidView(
        factory = { context ->
            SurfaceView(context).apply {
                holder.addCallback(object : SurfaceHolder.Callback {
                    override fun surfaceCreated(holder: SurfaceHolder) {
                        surfaceHolder.value = holder
                    }
                    override fun surfaceDestroyed(holder: SurfaceHolder) {
                        // Leak: Nullified reference without stopping rendering coroutine
                        surfaceHolder.value = null
                    }
                    override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hgt: Int) {}
                })
            }
        },
        modifier = modifier
    )
}
```

#### Production Standard (Correct)
> **Standard**: Leverages DisposableEffect synchronized with the Android Lifecycle and a concurrency lock, guaranteeing that hardware surface rendering is cut off before the Android platform destroys the underlying Surface.
```kotlin
@Composable
fun SafeSkikoCanvasView(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    modifier: Modifier = Modifier
) {
    val renderLock = remember { Any() }
    var isSurfaceValid by remember { mutableStateOf(false) }

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_PAUSE || event == Lifecycle.Event.ON_STOP) {
                synchronized(renderLock) {
                    isSurfaceValid = false
                }
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            synchronized(renderLock) {
                isSurfaceValid = false
            }
        }
    }

    AndroidView(
        factory = { context ->
            SurfaceView(context).apply {
                holder.addCallback(object : SurfaceHolder.Callback {
                    override fun surfaceCreated(holder: SurfaceHolder) {
                        synchronized(renderLock) { isSurfaceValid = true }
                    }
                    override fun surfaceDestroyed(holder: SurfaceHolder) {
                        synchronized(renderLock) {
                            isSurfaceValid = false
                            // Ensure pipeline drain before returning to native window manager
                        }
                    }
                    override fun surfaceChanged(h: SurfaceHolder, format: Int, width: Int, height: Int) {}
                })
            }
        },
        modifier = modifier
    )
}
```

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 Skiko GPU Surface Lifecycle Invariant

Compose Multiplatform Skiko GPU Surface Lifecycle Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic teardown and re-instantiation of Skiko rendering delegates and hardware surfaces across Android and iOS lifecycle transitions. Prevents fatal GPU driver termination (SIGKILL 0xdead10cc on iOS Metal, VK_ERROR_DEVICE_LOST/EGL_BAD_SURFACE on Android) caused by mid-flight draw calls dispatched to invalidated swapchains during rapid background-foreground swaps. 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: Orphaned Skia Metal/OpenGL swapchains attempting buffer presentation after OS lifecycle backgrounding 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 DriftOrphaned Skia Metal/OpenGL swapchains attempting buffer presentation after OS lifecycle backgroundingCritical
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 suspend the Skiko render loop and synchronously release or detach the CAMetalLayer or SurfaceHolder when the host application moves to the background.

Engineers MUST ALWAYS suspend the Skiko render loop and synchronously release or detach the CAMetalLayer or SurfaceHolder when the host application moves to the background.

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 dispatch render commands or invoke Skia Canvas redraw operations from background threads without verifying active surface availability via a thread-safe lifecycle latch.

Engineers MUST NOT dispatch render commands or invoke Skia Canvas redraw operations from background threads without verifying active surface availability via a thread-safe lifecycle latch.

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 wrap ComposeUIViewController or Skiko-backed native views inside explicit platform lifecycle listeners (e.g., DefaultLifecycleObserver on Android, viewDidDisappear / sceneDidEnterBackground notifications on iOS).

Code SHOULD wrap ComposeUIViewController or Skiko-backed native views inside explicit platform lifecycle listeners (e.g., DefaultLifecycleObserver on Android, viewDidDisappear / sceneDidEnterBackground notifications on iOS).

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

Services MUST flush pending graphics queues and invalidate hardware-bound SkSurface references prior to relinquishing control back to the OS background transition handler.

Services MUST flush pending graphics queues and invalidate hardware-bound SkSurface references prior to relinquishing control back to the OS background transition handler.

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

Components NEVER capture strong references to native platform context handles (MTLDevice, EGLContext, or Android Surface) across Compose recomposition boundaries.

Components NEVER capture strong references to native platform context handles (MTLDevice, EGLContext, or Android Surface) across Compose recomposition boundaries.

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 GPU Surface Lifecycle Invariant critical for AI coding assistants?

Enforces deterministic teardown and re-instantiation of Skiko rendering delegates and hardware surfaces across Android and iOS lifecycle transitions. Prevents fatal GPU driver termination (SIGKILL 0xdead10cc on iOS Metal, VK_ERROR_DEVICE_LOST/EGL_BAD_SURFACE on Android) caused by mid-flight draw calls dispatched to invalidated swapchains during rapid background-foreground swaps. 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 (Orphaned Skia Metal/OpenGL swapchains attempting buffer presentation after OS lifecycle backgrounding) 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