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

KMP Skiko Metal Surface Lifecycle Synchronization Invariant

Enforces strict synchronization between iOS UIViewController lifecycle transitions, CADisplayLink rendering loops, and Compose Multiplatform Skiko Metal layers. Eliminates command buffer acquisition race conditions, dropped drawables, and GPU execution panics during interactive modal dismissals and navigation transitions.

Prohibited Anti-Pattern: Unsynchronized Metal Command Buffer Scheduling During iOS Lifecycle and View Hierarchy Transitions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko Metal Surface Lifecycle Synchronization Invariant - Enforces strict synchronization between iOS UIViewController lifecycle transitions, CADisplayLink rendering loops, and Compose Multiplatform Skiko Metal layers. Eliminates command buffer acquisition race conditions, dropped drawables, and GPU execution panics during interactive modal dismissals and navigation transitions.
globs: **/iosMain/**/*.kt, **/iosApp/**/*.swift, **/*ViewController*.swift, **/*Metal*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-metal-surface-lifecycle-synchronization"
---

# KMP Skiko Metal Surface Lifecycle Synchronization Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unsynchronized Metal Command Buffer Scheduling During iOS Lifecycle and View Hierarchy Transitions

## System Constraints
You are a Principal Software Architect enforcing zero-defect GPU rendering synchronization between native iOS view lifecycle events and Jetpack Compose Multiplatform's Skiko Metal rendering engine. You must enforce deterministic lifecycle draining, CADisplayLink suspension, and synchronous in-flight command buffer completion before surface destruction.

## Strict Guidelines
- Engineers MUST ALWAYS suspend Skiko CADisplayLink updates and wait for in-flight Metal command buffers to complete before deallocating or detaching CAMetalLayer instances.
- Engineers MUST NOT allow Skiko or Compose rendering passes to acquire CAMetalDrawables when UIViewController.view is not in the window hierarchy or when view.bounds is CGRect.zero.
- Code MUST synchronously drain the Skiko rendering queue on viewWillDisappear and UIApplication.willResignActiveNotification to prevent background Metal execution crashes.
- Services MUST ensure that interactive transition coordinators (e.g., UINavigationController swipe-back) pause or throttle Skiko redraws until the transition completes or cancels cleanly.
- Components NEVER invoke CAMetalLayer.nextDrawable() asynchronously without handling nil drawables and validating underlying MTLDevice state validity.

## Bad vs Good Implementations
### Synchronizing Compose UIViewController with CAMetalLayer Lifecycle

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to coordinate ComposeUIViewController's render pipeline with native transition states causes CADisplayLink callbacks to request drawables while the view is being detached or resized. This triggers fatal Metal validation errors (`MTLCommandBufferStatusError`) and GPU panics when entering the background.
```swift
import UIKit
import shared

final class ComposeContainerViewController: UIViewController {
    private var composeController: UIViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // CRITICAL FLAW: Child controller added without lifecycle synchronization.
        // Skiko will continuously render via CADisplayLink even when disappearing
        // or during interactive pop transitions, attempting to acquire drawables
        // from a detached CAMetalLayer, causing MTLCommandBuffer crashes.
        let controller = ComposeMainKt.MainViewController()
        composeController = controller
        addChild(controller)
        view.addSubview(controller.view)
        controller.view.frame = view.bounds
        controller.didMove(toParent: self)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // No GPU queue draining, display link remains active during pop gesture
    }
}
```

#### Production Standard (Correct)
> **Standard**: Guards against zero-bound frame allocations, observes UINavigationController transition cancellation state, flushes the CoreAnimation/Metal transaction buffer, and guarantees orderly tear-down of the Skiko-backed child view hierarchy without leaking inflight command buffers.
```swift
import UIKit
import Metal
import shared

final class ComposeContainerViewController: UIViewController {
    private var composeController: UIViewController?
    private var isInTransition = false

    override func viewDidLoad() {
        super.viewDidLoad()
        let controller = ComposeMainKt.MainViewController()
        composeController = controller
        addChild(controller)
        view.addSubview(controller.view)
        controller.view.frame = view.bounds
        controller.didMove(toParent: self)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // Enforce valid geometry before allowing draw passes
        guard view.bounds.width > 0, view.bounds.height > 0 else {
            composeController?.view.isHidden = true
            return
        }
        composeController?.view.isHidden = false
        composeController?.view.frame = view.bounds
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        isInTransition = true
        
        // Drain GPU pipeline if navigating away or popping
        if let transitionCoordinator = transitionCoordinator {
            transitionCoordinator.animate(alongsideTransition: nil) { [weak self] context in
                if context.isCancelled {
                    self?.isInTransition = false
                } else {
                    self?.drainMetalWorkload()
                }
            }
        } else {
            drainMetalWorkload()
        }
    }

    private func drainMetalWorkload() {
        // Synchronously inform Compose Multiplatform runtime to detach and drain
        composeController?.view.setNeedsDisplay()
        CATransaction.flush()
    }

    deinit {
        // Ensure child controller is explicitly unparented before dealloc
        composeController?.willMove(toParent: nil)
        composeController?.view.removeFromSuperview()
        composeController?.removeFromParent()
    }
}
```

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: KMP Skiko Metal Surface Lifecycle Synchronization Invariant

KMP Skiko Metal Surface Lifecycle Synchronization Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization between iOS UIViewController lifecycle transitions, CADisplayLink rendering loops, and Compose Multiplatform Skiko Metal layers. Eliminates command buffer acquisition race conditions, dropped drawables, and GPU execution panics during interactive modal dismissals and navigation transitions. 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: Unsynchronized Metal Command Buffer Scheduling During iOS Lifecycle and View Hierarchy 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 DriftUnsynchronized Metal Command Buffer Scheduling During iOS Lifecycle and View Hierarchy 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 suspend Skiko CADisplayLink updates and wait for in-flight Metal command buffers to complete before deallocating or detaching CAMetalLayer instances.

Engineers MUST ALWAYS suspend Skiko CADisplayLink updates and wait for in-flight Metal command buffers to complete before deallocating or detaching CAMetalLayer 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.
2

Engineers MUST NOT allow Skiko or Compose rendering passes to acquire CAMetalDrawables when UIViewController.view is not in the window hierarchy or when view.bounds is CGRect.zero.

Engineers MUST NOT allow Skiko or Compose rendering passes to acquire CAMetalDrawables when UIViewController.view is not in the window hierarchy or when view.bounds is CGRect.zero.

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 MUST synchronously drain the Skiko rendering queue on viewWillDisappear and UIApplication.willResignActiveNotification to prevent background Metal execution crashes.

Code MUST synchronously drain the Skiko rendering queue on viewWillDisappear and UIApplication.willResignActiveNotification to prevent background Metal execution crashes.

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 ensure that interactive transition coordinators (e.g., UINavigationController swipe-back) pause or throttle Skiko redraws until the transition completes or cancels cleanly.

Services MUST ensure that interactive transition coordinators (e.g., UINavigationController swipe-back) pause or throttle Skiko redraws until the transition completes or cancels cleanly.

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 invoke CAMetalLayer.nextDrawable() asynchronously without handling nil drawables and validating underlying MTLDevice state validity.

Components NEVER invoke CAMetalLayer.nextDrawable() asynchronously without handling nil drawables and validating underlying MTLDevice state validity.

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

Enforces strict synchronization between iOS UIViewController lifecycle transitions, CADisplayLink rendering loops, and Compose Multiplatform Skiko Metal layers. Eliminates command buffer acquisition race conditions, dropped drawables, and GPU execution panics during interactive modal dismissals and navigation transitions. 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 (Unsynchronized Metal Command Buffer Scheduling During iOS Lifecycle and View Hierarchy 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

KMP