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

Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail

Enforces synchronous GPU pipeline fencing and swapchain invalidation during asynchronous native lifecycle suspension in Compose Multiplatform 1.8. Prevents fatal GPU hardware driver hangs (VK_ERROR_SURFACE_LOST_KHR) and CAMetalLayer memory faults by blocking surface destruction until in-flight command buffers retire and the swap barrier is safely quarantined.

Prohibited Anti-Pattern: Asynchronous Surface Teardown Triggering Orphaned GPU Submissions and Swapchain Deadlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail - Enforces synchronous GPU pipeline fencing and swapchain invalidation during asynchronous native lifecycle suspension in Compose Multiplatform 1.8. Prevents fatal GPU hardware driver hangs (VK_ERROR_SURFACE_LOST_KHR) and CAMetalLayer memory faults by blocking surface destruction until in-flight command buffers retire and the swap barrier is safely quarantined.
globs: **/src/commonMain/**/*.kt, **/src/androidMain/**/*.kt, **/src/iosMain/**/*.kt, **/graphics/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-vulkan-metal-surface-synchronization"
---

# Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Asynchronous Surface Teardown Triggering Orphaned GPU Submissions and Swapchain Deadlocks

## System Constraints
You are a Principal Graphics and Platform Engineer enforcing strict hardware-accelerated surface lifecycle invariants in Compose Multiplatform 1.8. You must ensure that no frame presentation, CAMetalDrawable acquisition, or VkQueuePresentKHR call occurs without deterministic synchronization against platform lifecycle transitions. Never allow native surface destructions (ANativeWindow / CAMetalLayer) to race against Skia/Skiko render passes.

## Strict Guidelines
- Engineers MUST ALWAYS synchronize Skiko/Skia render loop suspension with native OS lifecycle signals (e.g., onStop/surfaceDestroyed on Android, applicationDidEnterBackground on iOS) prior to releasing native window handles.
- Engineers MUST NOT acquire CAMetalDrawable or VkSurfaceKHR handles asynchronously without holding an atomic lock or barrier confirming the underlying surface is fully resident and active.
- Engineers MUST execute a GPU pipeline drain (e.g., vkQueueWaitIdle or MTLCommandBuffer waitUntilCompleted) synchronously before releasing the underlying NativeWindow or MetalLayer to prevent VK_ERROR_DEVICE_LOST.
- Code MUST isolate frame dispatchers and drain pending Choreographer or CADisplayLink frame callbacks immediately upon entering the background state.
- Components NEVER resume swapchain allocation until the platform dispatch loop affirmatively signals surface recreate and render target re-binding.

## Bad vs Good Implementations
### Synchronous Surface Barrier vs Asynchronous Surface Release in Compose Multiplatform Layer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Releasing or pausing the render loop without blocking until the GPU queue empties causes in-flight draw commands to target an invalid native window handle, triggering unrecoverable VK_ERROR_SURFACE_LOST_KHR or native SIGSEGV in libvulkan/libGLES.
```kotlin
// Anti-Pattern: Surface is released asynchronously or without waiting for GPU execution.
// Leaks in-flight command buffers targeting destroyed ANativeWindow/CAMetalLayer.
class FlawedSurfaceManager(private val renderLoop: SkikoRenderLoop) : SurfaceHolder.Callback {
    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // Defect: Signal stop asynchronously without waiting for the GPU queue to drain
        renderLoop.pause()
        // Native surface is destroyed immediately while GPU may still be executing DrawFrame
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        renderLoop.resume()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees deterministic barrier invalidation by setting an atomic flag and synchronously flushing and awaiting pending GPU operations via flushAndSubmit(sync = true) before allowing Android/iOS to tear down the underlying native handle.
```kotlin
// Production-Grade: Deterministic fence wait and atomic swap-barrier invalidation
class SynchronizedSurfaceManager(
    private val renderController: SkikoRenderController,
    private val graphicsContext: GraphicsContext
) : SurfaceHolder.Callback {
    private val surfaceLock = Mutex()
    private val isSurfaceValid = AtomicBoolean(false)

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        // 1. Immediately invalidate submission barrier
        isSurfaceValid.set(false)

        // 2. Synchronously pause rendering and block until current pipeline drains
        runBlocking(Dispatchers.Main.immediate) {
            renderController.suspendRendering()
            // Ensure all queued Vulkan/Metal command buffers have fully completed
            graphicsContext.flushAndSubmit(sync = true)
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        runBlocking(Dispatchers.Main.immediate) {
            graphicsContext.bindSurface(holder.surface)
            isSurfaceValid.set(true)
            renderController.resumeRendering()
        }
    }
}
```

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: Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail

Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces synchronous GPU pipeline fencing and swapchain invalidation during asynchronous native lifecycle suspension in Compose Multiplatform 1.8. Prevents fatal GPU hardware driver hangs (VK_ERROR_SURFACE_LOST_KHR) and CAMetalLayer memory faults by blocking surface destruction until in-flight command buffers retire and the swap barrier is safely quarantined. 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 Surface Teardown Triggering Orphaned GPU Submissions and Swapchain Deadlocks 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 Surface Teardown Triggering Orphaned GPU Submissions and Swapchain DeadlocksCritical
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 synchronize Skiko/Skia render loop suspension with native OS lifecycle signals (e.g., onStop/surfaceDestroyed on Android, applicationDidEnterBackground on iOS) prior to releasing native window handles.

Engineers MUST ALWAYS synchronize Skiko/Skia render loop suspension with native OS lifecycle signals (e.g., onStop/surfaceDestroyed on Android, applicationDidEnterBackground on iOS) prior to releasing native window handles.

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 acquire CAMetalDrawable or VkSurfaceKHR handles asynchronously without holding an atomic lock or barrier confirming the underlying surface is fully resident and active.

Engineers MUST NOT acquire CAMetalDrawable or VkSurfaceKHR handles asynchronously without holding an atomic lock or barrier confirming the underlying surface is fully resident and active.

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 execute a GPU pipeline drain (e.g., vkQueueWaitIdle or MTLCommandBuffer waitUntilCompleted) synchronously before releasing the underlying NativeWindow or MetalLayer to prevent VK_ERROR_DEVICE_LOST.

Engineers MUST execute a GPU pipeline drain (e.g., vkQueueWaitIdle or MTLCommandBuffer waitUntilCompleted) synchronously before releasing the underlying NativeWindow or MetalLayer to prevent VK_ERROR_DEVICE_LOST.

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

Code MUST isolate frame dispatchers and drain pending Choreographer or CADisplayLink frame callbacks immediately upon entering the background state.

Code MUST isolate frame dispatchers and drain pending Choreographer or CADisplayLink frame callbacks immediately upon entering the background state.

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 resume swapchain allocation until the platform dispatch loop affirmatively signals surface recreate and render target re-binding.

Components NEVER resume swapchain allocation until the platform dispatch loop affirmatively signals surface recreate and render target re-binding.

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 Deterministic Vulkan/Metal Swapchain and Surface Invalidation Guardrail critical for AI coding assistants?

Enforces synchronous GPU pipeline fencing and swapchain invalidation during asynchronous native lifecycle suspension in Compose Multiplatform 1.8. Prevents fatal GPU hardware driver hangs (VK_ERROR_SURFACE_LOST_KHR) and CAMetalLayer memory faults by blocking surface destruction until in-flight command buffers retire and the swap barrier is safely quarantined. 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 Surface Teardown Triggering Orphaned GPU Submissions and Swapchain Deadlocks) 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

Deterministic