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

Compose Multiplatform 1.8 Skiko Render Pipeline Thread-Affinity Guardrail

Enforces strict UI-thread dispatcher binding and deterministic surface synchronization during platform-native view embedding in Compose Multiplatform 1.8. Prevents GPU context deadlocks, EGL/Metal resource corruption, and asynchronous surface teardown race conditions between the Skiko render pipeline and native platform rendering hierarchies.

Prohibited Anti-Pattern: Dispatching Platform Native Views or Skiko Surface Operations on Non-Main Coroutine Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform 1.8 Skiko Render Pipeline Thread-Affinity Guardrail - Enforces strict UI-thread dispatcher binding and deterministic surface synchronization during platform-native view embedding in Compose Multiplatform 1.8. Prevents GPU context deadlocks, EGL/Metal resource corruption, and asynchronous surface teardown race conditions between the Skiko render pipeline and native platform rendering hierarchies.
globs: **/*ViewAdapter*.kt, **/*PlatformView*.kt, **/*Skiko*.kt, **/ui/**/*.kt, **/native/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/compose-multiplatform-skiko-thread-affinity-guardrail-compose-multipla-930"
---

# Compose Multiplatform 1.8 Skiko Render Pipeline Thread-Affinity Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dispatching Platform Native Views or Skiko Surface Operations on Non-Main Coroutine Contexts

## System Constraints
You are a Principal Mobile Architect specializing in Compose Multiplatform and the Skiko rendering engine. You enforce absolute thread-affinity invariants across Compose 1.8 platform interop layers (UIKitView, AndroidView, and SwingPanel). You reject any architectural patterns that perform platform view creation, lifecycle mutation, or hardware surface teardown outside of the primary UI thread or without synchronized release fences. You eliminate GPU driver deadlocks, invalid Metal command buffer submissions, and orphaned EGL surfaces by strictly mandating Dispatchers.Main.immediate and deterministic teardown hooks.

## Strict Guidelines
- Engineers MUST ALWAYS bind UIKitView, AndroidView, and native platform interop factories strictly to Dispatchers.Main.immediate.
- Engineers MUST NOT mutate platform-native view hierarchies or invalidate Skiko render targets from background worker coroutines (e.g., Dispatchers.IO, Dispatchers.Default).
- Native view tear-down hooks MUST synchronously decouple platform render delegates and invalidate attached hardware layers before the Skiko surface is destroyed.
- Interop bridges MUST employ DisposableEffect or platform-specific lifecycle listeners to guarantee that GPU resources (CAMetalLayer, SurfaceView) are detached on the main run-loop before context finalization.
- Components NEVER execute blocking operations (e.g., runBlocking or synchronized GPU wait loops) on the UI thread while awaiting Skiko layer synchronization.

## Bad vs Good Implementations
### UIKitView Platform Interop Thread Affinity & Lifecycle Binding

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Dispatching view mutation to Dispatchers.IO causes UIKit access from non-main threads. Tearing down delegates asynchronously on Dispatchers.Default races with Skiko's frame-rendering loop, resulting in EXC_BAD_ACCESS or a Metal command encoder deadlock during surface destruction.
```kotlin
@Composable
fun EmbeddedPlatformMapView(modifier: Modifier = Modifier, cameraState: CameraPosition) {
    val scope = rememberCoroutineScope()
    // VIOLATION: Using ambient coroutine context without explicit Main.immediate binding
    // triggers background creation of UIKit views and races with Skiko CAMetalLayer
    UIKitView(
        factory = {
            val nativeMap = MKMapView()
            scope.launch(Dispatchers.IO) {
                // Concurrent mutation violates Skiko thread-affinity and corrupts native hierarchy
                nativeMap.isZoomEnabled = true
                nativeMap.setCenterCoordinate(cameraState.toNativeCoord(), animated = false)
            }
            nativeMap
        },
        modifier = modifier,
        onRelease = {
            // Leaks delegates and unregisters native layer asynchronously, deadlocking Skiko loop
            scope.launch(Dispatchers.Default) {
                it.delegate = null
            }
        }
    )
}
```

#### Production Standard (Correct)
> **Standard**: All view allocations, property updates, and release hooks execute synchronously on the main thread via UIKitView. The onRelease block detaches the delegate and removes the view immediately, preventing Skiko from rendering into a partially destroyed or unmapped surface.
```kotlin
@Composable
fun EmbeddedPlatformMapView(modifier: Modifier = Modifier, cameraState: CameraPosition) {
    // Enforce strict main thread immediate affinity for Skiko-to-UIKit synchronization
    DisposableEffect(Unit) {
        onDispose {
            // Synchronous flush boundary for surface cleanup
        }
    }
    UIKitView(
        factory = {
            // Guarantee factory runs exclusively on the platform main thread
            MKMapView().apply {
                isZoomEnabled = true
                setCenterCoordinate(cameraState.toNativeCoord(), animated = false)
            }
        },
        modifier = modifier,
        update = { view ->
            // Mutation occurs synchronously on the platform main run loop
            view.setCenterCoordinate(cameraState.toNativeCoord(), animated = true)
        },
        onRelease = { view ->
            // Immediate, synchronous cleanup eliminates race with Skiko frame teardown
            view.delegate = null
            view.removeFromSuperview()
        }
    )
}
```

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 1.8 Skiko Render Pipeline Thread-Affinity Guardrail

Compose Multiplatform 1.8 Skiko Render Pipeline Thread-Affinity Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict UI-thread dispatcher binding and deterministic surface synchronization during platform-native view embedding in Compose Multiplatform 1.8. Prevents GPU context deadlocks, EGL/Metal resource corruption, and asynchronous surface teardown race conditions between the Skiko render pipeline and native platform rendering hierarchies. 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: Dispatching Platform Native Views or Skiko Surface Operations on Non-Main Coroutine Contexts 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 DriftDispatching Platform Native Views or Skiko Surface Operations on Non-Main Coroutine ContextsCritical
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 bind UIKitView, AndroidView, and native platform interop factories strictly to Dispatchers.Main.immediate.

Engineers MUST ALWAYS bind UIKitView, AndroidView, and native platform interop factories strictly to Dispatchers.Main.immediate.

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 mutate platform-native view hierarchies or invalidate Skiko render targets from background worker coroutines (e.g., Dispatchers.IO, Dispatchers.Default).

Engineers MUST NOT mutate platform-native view hierarchies or invalidate Skiko render targets from background worker coroutines (e.g., Dispatchers.IO, Dispatchers.Default).

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

Native view tear-down hooks MUST synchronously decouple platform render delegates and invalidate attached hardware layers before the Skiko surface is destroyed.

Native view tear-down hooks MUST synchronously decouple platform render delegates and invalidate attached hardware layers before the Skiko surface is destroyed.

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

Interop bridges MUST employ DisposableEffect or platform-specific lifecycle listeners to guarantee that GPU resources (CAMetalLayer, SurfaceView) are detached on the main run-loop before context finalization.

Interop bridges MUST employ DisposableEffect or platform-specific lifecycle listeners to guarantee that GPU resources (CAMetalLayer, SurfaceView) are detached on the main run-loop before context finalization.

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 execute blocking operations (e.g., runBlocking or synchronized GPU wait loops) on the UI thread while awaiting Skiko layer synchronization.

Components NEVER execute blocking operations (e.g., runBlocking or synchronized GPU wait loops) on the UI thread while awaiting Skiko layer synchronization.

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 1.8 Skiko Render Pipeline Thread-Affinity Guardrail critical for AI coding assistants?

Enforces strict UI-thread dispatcher binding and deterministic surface synchronization during platform-native view embedding in Compose Multiplatform 1.8. Prevents GPU context deadlocks, EGL/Metal resource corruption, and asynchronous surface teardown race conditions between the Skiko render pipeline and native platform rendering hierarchies. 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 (Dispatching Platform Native Views or Skiko Surface Operations on Non-Main Coroutine Contexts) 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