This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-cadisplaylink-native-gc-sync-invariant

Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard

Enforces strict synchronization between Kotlin/Native concurrent garbage collection cycles and Apple iOS CADisplayLink frame deadlines to guarantee deterministic 120Hz (8.33ms) ProMotion rendering. Forbids unthrottled GC triggers and unbudgeted Kotlin allocations within the main render loop, ensuring background marking and sweeping operate only within designated idle slices. Protects cross-platform animation systems from micro-stutter, jank, and priority inversion caused by uncoordinated runtime sweeps.

Prohibited Anti-Pattern: Uncoordinated Kotlin/Native Garbage Collection Triggers Colliding with CoreAnimation Frame Deadlines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard - Enforces strict synchronization between Kotlin/Native concurrent garbage collection cycles and Apple iOS CADisplayLink frame deadlines to guarantee deterministic 120Hz (8.33ms) ProMotion rendering. Forbids unthrottled GC triggers and unbudgeted Kotlin allocations within the main render loop, ensuring background marking and sweeping operate only within designated idle slices. Protects cross-platform animation systems from micro-stutter, jank, and priority inversion caused by uncoordinated runtime sweeps.
globs: **/iosMain/**/*.kt, **/*Ios.kt, **/appleMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-cadisplaylink-native-gc-sync-invariant"
---

# Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Uncoordinated Kotlin/Native Garbage Collection Triggers Colliding with CoreAnimation Frame Deadlines

## System Constraints
You are a Principal Engineer and Mobile Runtime Architect specializing in Kotlin Multiplatform and Apple CoreAnimation rendering pipelines. Enforce the CADisplayLink Native GC Synchronization Invariant on iOS targets. Never allow Kotlin/Native runtime garbage collection to trigger arbitrarily on main render threads or during unmetered frame intervals. Ensure all explicit GC sweeps or scheduling decisions conform to the 8.33ms frame budget of 120Hz ProMotion displays by calculating residual idle times via CADisplayLink.targetTimestamp and CACurrentMediaTime().

## Strict Guidelines
- Engineers MUST ALWAYS inspect the CADisplayLink targetTimestamp delta against CACurrentMediaTime() to ensure a minimum of 2.5ms of idle frame margin before dispatching any synchronous or background GC phase.
- Engineers MUST NOT invoke kotlin.native.internal.GC.collect() or heavy object graph sweeps inside CADisplayLink frame callbacks, UIViewController lifecycle hooks, or GestureRecognizer handlers.
- Code SHOULD configure Kotlin/Native concurrent GC autotuning parameters during platform initialization to prevent automatic full-heap sweep interrupts during critical interaction modes.
- Services MUST suspend active non-urgent background garbage collection tasks whenever the iOS display enters high-frequency interaction phases (e.g., active touch tracking or inertial scrolling).
- Components NEVER bridge high-frequency CADisplayLink tick events directly into unmanaged Kotlin object allocations that overwhelm the young generation and force preemptive STW phases.

## Bad vs Good Implementations
### Frame-Budgeted Kotlin/Native GC Synchronization via CADisplayLink

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Triggering synchronous or unbudgeted GC collection inside the CADisplayLink callback without checking remaining frame time causes immediate main thread hitches. Creating thousands of temporary objects every 8.33ms guarantees frame drops below 120Hz.
```kotlin
import platform.QuartzCore.CADisplayLink
import kotlin.native.internal.GC

class DisplayFrameObserver {
    private var displayLink: CADisplayLink? = null

    fun start() {
        displayLink = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = platform.objc.sel_registerName("onFrame:")
        )
        // BAD: Adding blindly to common run loop without frame budget checks
        displayLink?.addToRunLoop(platform.Foundation.NSRunLoop.mainRunLoop, platform.Foundation.NSRunLoopCommonModes)
    }

    @platform.objc.ObjCAction
    fun onFrame(link: CADisplayLink) {
        // CRITICAL DEFECT: Allocates heavily and triggers full blocking GC directly inside the frame tick
        val temporaryAllocations = List(5000) { "render_data_point_$it" }
        GC.collect()
    }
}
```

#### Production Standard (Correct)
> **Standard**: The good example sets a 120Hz preferred frame rate range and strictly checks the time differential between targetTimestamp and CACurrentMediaTime(). If and only if the current frame has at least 2.5ms of unused budget, non-blocking concurrent collection is scheduled, preventing 120Hz display jank.
```kotlin
import platform.QuartzCore.CADisplayLink
import platform.QuartzCore.CACurrentMediaTime
import platform.Foundation.NSRunLoop
import platform.Foundation.NSRunLoopCommonModes
import kotlin.native.internal.GC
import kotlinx.cinterop.ExperimentalForeignApi

@OptIn(ExperimentalForeignApi::class)
class CadenceDisplaySync {
    private var displayLink: CADisplayLink? = null
    private val minGcSlackSeconds: Double = 0.0025 // 2.5ms safety budget threshold

    fun start() {
        displayLink = CADisplayLink.displayLinkWithTarget(
            target = this,
            selector = platform.objc.sel_registerName("onRenderTick:")
        ).apply {
            // Target 120Hz ProMotion natively
            preferredFrameRateRange = platform.QuartzCore.CAFrameRateRangeMake(60.0f, 120.0f, 120.0f)
            addToRunLoop(NSRunLoop.mainRunLoop, NSRunLoopCommonModes)
        }
    }

    @platform.objc.ObjCAction
    fun onRenderTick(link: CADisplayLink) {
        val currentTime = CACurrentMediaTime()
        val frameDeadline = link.targetTimestamp
        val remainingSlack = frameDeadline - currentTime

        // INVARIANT: Only schedule concurrent GC sweeps if frame budget exhibits safe residual idle time
        if (remainingSlack >= minGcSlackSeconds) {
            GC.schedule()
        }
    }

    fun dispose() {
        displayLink?.invalidate()
        displayLink = null
    }
}
```

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: Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard

Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization between Kotlin/Native concurrent garbage collection cycles and Apple iOS CADisplayLink frame deadlines to guarantee deterministic 120Hz (8.33ms) ProMotion rendering. Forbids unthrottled GC triggers and unbudgeted Kotlin allocations within the main render loop, ensuring background marking and sweeping operate only within designated idle slices. Protects cross-platform animation systems from micro-stutter, jank, and priority inversion caused by uncoordinated runtime sweeps. 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: Uncoordinated Kotlin/Native Garbage Collection Triggers Colliding with CoreAnimation Frame Deadlines 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 DriftUncoordinated Kotlin/Native Garbage Collection Triggers Colliding with CoreAnimation Frame DeadlinesCritical
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 inspect the CADisplayLink targetTimestamp delta against CACurrentMediaTime() to ensure a minimum of 2.5ms of idle frame margin before dispatching any synchronous or background GC phase.

Engineers MUST ALWAYS inspect the CADisplayLink targetTimestamp delta against CACurrentMediaTime() to ensure a minimum of 2.5ms of idle frame margin before dispatching any synchronous or background GC phase.

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 invoke kotlin.native.internal.GC.collect() or heavy object graph sweeps inside CADisplayLink frame callbacks, UIViewController lifecycle hooks, or GestureRecognizer handlers.

Engineers MUST NOT invoke kotlin.native.internal.GC.collect() or heavy object graph sweeps inside CADisplayLink frame callbacks, UIViewController lifecycle hooks, or GestureRecognizer handlers.

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 configure Kotlin/Native concurrent GC autotuning parameters during platform initialization to prevent automatic full-heap sweep interrupts during critical interaction modes.

Code SHOULD configure Kotlin/Native concurrent GC autotuning parameters during platform initialization to prevent automatic full-heap sweep interrupts during critical interaction modes.

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 suspend active non-urgent background garbage collection tasks whenever the iOS display enters high-frequency interaction phases (e.g., active touch tracking or inertial scrolling).

Services MUST suspend active non-urgent background garbage collection tasks whenever the iOS display enters high-frequency interaction phases (e.g., active touch tracking or inertial scrolling).

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 bridge high-frequency CADisplayLink tick events directly into unmanaged Kotlin object allocations that overwhelm the young generation and force preemptive STW phases.

Components NEVER bridge high-frequency CADisplayLink tick events directly into unmanaged Kotlin object allocations that overwhelm the young generation and force preemptive STW phases.

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 Kotlin/Native CADisplayLink Frame Budget GC Synchronization Standard critical for AI coding assistants?

Enforces strict synchronization between Kotlin/Native concurrent garbage collection cycles and Apple iOS CADisplayLink frame deadlines to guarantee deterministic 120Hz (8.33ms) ProMotion rendering. Forbids unthrottled GC triggers and unbudgeted Kotlin allocations within the main render loop, ensuring background marking and sweeping operate only within designated idle slices. Protects cross-platform animation systems from micro-stutter, jank, and priority inversion caused by uncoordinated runtime sweeps. 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 (Uncoordinated Kotlin/Native Garbage Collection Triggers Colliding with CoreAnimation Frame Deadlines) 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

Kotlin/Native