This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skiko-render-loop-frame-budget-isolation

KMP Skiko Render Loop Frame Budget Isolation Guardrail

Isolates Skiko render loop dispatchers and Compose Multiplatform UI thread schedules from shared background coroutine pools (Dispatchers.Default and Dispatchers.IO). Prevents thread starvation and priority inversion during heavy network synchronization or disk I/O, guaranteeing a deterministic 16ms (60 FPS) / 8.33ms (120 FPS) VSync frame deadline across iOS, Android, and Desktop targets.

Prohibited Anti-Pattern: Executing Unbounded Data Synchronization or Shared Coroutine Dispatches on UI/Skiko Rendering Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Skiko Render Loop Frame Budget Isolation Guardrail - Isolates Skiko render loop dispatchers and Compose Multiplatform UI thread schedules from shared background coroutine pools (Dispatchers.Default and Dispatchers.IO). Prevents thread starvation and priority inversion during heavy network synchronization or disk I/O, guaranteeing a deterministic 16ms (60 FPS) / 8.33ms (120 FPS) VSync frame deadline across iOS, Android, and Desktop targets.
globs: **/commonMain/**/*.kt, **/iosMain/**/*.kt, **/androidMain/**/*.kt, **/desktopMain/**/*.kt, **/*ViewModel.kt, **/*Repository.kt, **/*SyncWorker.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skiko-render-loop-frame-budget-isolation"
---

# KMP Skiko Render Loop Frame Budget Isolation Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Unbounded Data Synchronization or Shared Coroutine Dispatches on UI/Skiko Rendering Contexts

## System Constraints
You are a Principal Software Architect enforcing the Kotlin Multiplatform Compose Render Loop Frame Budget Isolation Guardrail. You must ensure that Compose Multiplatform UI drawing, layout passes, and Skiko rendering sequences are strictly segregated from background compute, heavy deserialization, database transactions, and network streaming. Never allow coroutines launched in UI scopes to execute I/O or CPU-heavy work without explicitly switching to dedicated, rate-limited background dispatchers. Flag any usage of shared thread pools that could starve Skiko's VSync delivery.

## Strict Guidelines
- Engineers MUST ALWAYS isolate background work into explicitly configured, bounded background CoroutineDispatchers (e.g., Dispatchers.IO or custom limitedParallelism workers) using `withContext`.
- Engineers MUST NOT execute heavy data transformations, database transactions (Room/SQLDelight), or JSON deserialization within `Dispatchers.Main`, `Dispatchers.Main.immediate`, or unconfined Compose snapshot scopes.
- Code SHOULD enforce strict frame budget monitoring using Skiko's frame clock or Compose `withFrameNanos` / `withFrameMillis` callbacks, ensuring layout and drawing passes do not exceed the 16.6ms threshold.
- Services MUST implement cooperative cancellation and bounded thread concurrency (via `Dispatcher.limitedParallelism`) for background sync routines to prevent native thread exhaustion across Apple/Posix runtimes.
- Components NEVER collect unthrottled or unbuffered background StateFlows/Channels directly in Composable scopes without backpressure buffers (`buffer(Channel.CONFLATED)`) or explicit lifecycle-aware downstream flattening.

## Bad vs Good Implementations
### Segregating Database Sync and JSON Deserialization from UI Dispatcher

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing CPU-heavy operations and blocking database I/O directly within `viewModelScope.launch` defaults execution to `Dispatchers.Main.immediate`. On Compose Multiplatform (especially Skiko targets on iOS and Desktop), this stalls the Skiko frame clock callback, causing dropped frames (jank) and violating the 16ms budget.
```kotlin
class SyncViewModel(
    private val repository: AccountRepository
) : ViewModel() {
    // ANTI-PATTERN: viewModelScope runs on Dispatchers.Main.immediate.
    // Heavy JSON parsing and database writes starve Skiko's VSync render loop.
    fun syncUserData() {
        viewModelScope.launch {
            val rawData = repository.fetchRemotePayload() // Network call implicitly yielding to main
            val parsed = rawData.map { parseHeavyPayload(it) } // CPU-bound work blocking UI/Skiko
            repository.batchInsertToDatabase(parsed) // Database I/O blocking Main thread
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using `withContext(ioDispatcher)` completely offloads network operations, CPU parsing, and disk writes to an isolated background thread pool. The Skiko render thread remains unblocked and can fulfill layout and draw calls within the 16ms VSync window.
```kotlin
class SyncViewModel(
    private val repository: AccountRepository,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
    // PRODUCTION INVARIANT: UI dispatcher is instantly relieved.
    // Heavy sync work is isolated to an independent, bounded I/O dispatcher.
    fun syncUserData() {
        viewModelScope.launch {
            withContext(ioDispatcher) {
                val rawData = repository.fetchRemotePayload()
                val parsed = rawData.map { parseHeavyPayload(it) }
                repository.batchInsertToDatabase(parsed)
            }
        }
    }
}
```

### Conflating High-Frequency Sensor/State Streams in Compose Recomposition

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an upstream producer emits events faster than Skiko's refresh rate (e.g., 60Hz or 120Hz), naive collection forces continuous snapshot state invalidations and triggers infinite layout/recomposition cycles, starving the Skiko drawing pipeline.
```kotlin
@Composable
fun SensorMonitorScreen(sensorStream: Flow<SensorReading>) {
    // ANTI-PATTERN: Collecting an unbuffered, high-frequency stream (e.g. 1000Hz)
    // directly into Compose state overloads the Compose Snapshot system and skips frames.
    val state by sensorStream.collectAsState(initial = SensorReading.Empty)
    
    Canvas(modifier = Modifier.fillMaxSize()) {
        drawSensorGraph(state)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Applying `.conflate()` discards intermediate readings when the UI thread is busy rendering, while `.flowOn(Dispatchers.Default)` keeps stream computations off the Main dispatcher. `collectAsStateWithLifecycle` ensures Compose only samples the latest frame within its allowed budget.
```kotlin
@Composable
fun SensorMonitorScreen(sensorStream: Flow<SensorReading>) {
    // PRODUCTION INVARIANT: Downstream backpressure conflation.
    // State updates are bounded to prevent recomposition thrashing beyond VSync capabilities.
    val state by remember(sensorStream) {
        sensorStream
            .conflate()
            .flowOn(Dispatchers.Default)
    }.collectAsStateWithLifecycle(
        initialValue = SensorReading.Empty
    )
    
    Canvas(modifier = Modifier.fillMaxSize()) {
        drawSensorGraph(state)
    }
}
```

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 Render Loop Frame Budget Isolation Guardrail

KMP Skiko Render Loop Frame Budget Isolation Guardrail defines an industrial-grade behavioral standard for mobile engineering. Isolates Skiko render loop dispatchers and Compose Multiplatform UI thread schedules from shared background coroutine pools (Dispatchers.Default and Dispatchers.IO). Prevents thread starvation and priority inversion during heavy network synchronization or disk I/O, guaranteeing a deterministic 16ms (60 FPS) / 8.33ms (120 FPS) VSync frame deadline across iOS, Android, and Desktop targets. 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: Executing Unbounded Data Synchronization or Shared Coroutine Dispatches on UI/Skiko Rendering 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 DriftExecuting Unbounded Data Synchronization or Shared Coroutine Dispatches on UI/Skiko Rendering 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 isolate background work into explicitly configured, bounded background CoroutineDispatchers (e.g., Dispatchers.IO or custom limitedParallelism workers) using `withContext`.

Engineers MUST ALWAYS isolate background work into explicitly configured, bounded background CoroutineDispatchers (e.g., Dispatchers.IO or custom limitedParallelism workers) using `withContext`.

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 execute heavy data transformations, database transactions (Room/SQLDelight), or JSON deserialization within `Dispatchers.Main`, `Dispatchers.Main.immediate`, or unconfined Compose snapshot scopes.

Engineers MUST NOT execute heavy data transformations, database transactions (Room/SQLDelight), or JSON deserialization within `Dispatchers.Main`, `Dispatchers.Main.immediate`, or unconfined Compose snapshot scopes.

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 enforce strict frame budget monitoring using Skiko's frame clock or Compose `withFrameNanos` / `withFrameMillis` callbacks, ensuring layout and drawing passes do not exceed the 16.6ms threshold.

Code SHOULD enforce strict frame budget monitoring using Skiko's frame clock or Compose `withFrameNanos` / `withFrameMillis` callbacks, ensuring layout and drawing passes do not exceed the 16.6ms threshold.

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 implement cooperative cancellation and bounded thread concurrency (via `Dispatcher.limitedParallelism`) for background sync routines to prevent native thread exhaustion across Apple/Posix runtimes.

Services MUST implement cooperative cancellation and bounded thread concurrency (via `Dispatcher.limitedParallelism`) for background sync routines to prevent native thread exhaustion across Apple/Posix runtimes.

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 collect unthrottled or unbuffered background StateFlows/Channels directly in Composable scopes without backpressure buffers (`buffer(Channel.CONFLATED)`) or explicit lifecycle-aware downstream flattening.

Components NEVER collect unthrottled or unbuffered background StateFlows/Channels directly in Composable scopes without backpressure buffers (`buffer(Channel.CONFLATED)`) or explicit lifecycle-aware downstream flattening.

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 Render Loop Frame Budget Isolation Guardrail critical for AI coding assistants?

Isolates Skiko render loop dispatchers and Compose Multiplatform UI thread schedules from shared background coroutine pools (Dispatchers.Default and Dispatchers.IO). Prevents thread starvation and priority inversion during heavy network synchronization or disk I/O, guaranteeing a deterministic 16ms (60 FPS) / 8.33ms (120 FPS) VSync frame deadline across iOS, Android, and Desktop targets. 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 (Executing Unbounded Data Synchronization or Shared Coroutine Dispatches on UI/Skiko Rendering 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

KMP