This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-skie-flow-asyncstream-bridging-invariant

KMP SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant

Enforces deterministic bidirectional cancellation and bounded backpressure propagation across the Kotlin Multiplatform and Swift boundary using SKIE. Prevents orphan coroutine leaks, memory bloat from uncollected buffers, and actor deadlocks when consuming Kotlin Flows via Swift modern concurrency.

Prohibited Anti-Pattern: Leaked Kotlin Coroutine Jobs and Swift Actor Stalls via Unbound Flow Bridging or Unscoped Task Wrappers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant - Enforces deterministic bidirectional cancellation and bounded backpressure propagation across the Kotlin Multiplatform and Swift boundary using SKIE. Prevents orphan coroutine leaks, memory bloat from uncollected buffers, and actor deadlocks when consuming Kotlin Flows via Swift modern concurrency.
globs: **/*.kt, **/*.swift, **/build.gradle.kts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-skie-flow-asyncstream-bridging-invariant"
---

# KMP SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Leaked Kotlin Coroutine Jobs and Swift Actor Stalls via Unbound Flow Bridging or Unscoped Task Wrappers

## System Constraints
You are a Principal Mobile Architect and Rules Author enforcing strict Kotlin Multiplatform (KMP) and Swift concurrency interop standards. SKIE generates first-class Swift AsyncSequence wrappers around Kotlin Flows. You must enforce zero-leak cooperative cancellation, explicit backpressure handling, and proper actor isolation across the Kotlin-Native/Swift boundary.

## Strict Guidelines
- Engineers MUST ALWAYS leverage SKIE-generated direct `AsyncSequence` conformance on Kotlin `Flow` rather than legacy callback-based closures, manual `Continuation` wrappers, or home-grown `AsyncStream` adapters.
- Engineers MUST NEVER consume a SKIE bridged `Flow` inside an untracked, unscoped Swift `Task.detached` without binding its lifecycle to an explicit parent `Task` or owner token that cancels on view disappearance or component deinit.
- Kotlin-exposed `SharedFlow` and `StateFlow` primitives MUST define explicit buffer capacities and overflow strategies (e.g., `onBufferOverflow = BufferOverflow.DROP_OLDEST`) if emissions exceed the Swift consumption runloop throughput.
- Swift consumers MUST handle cooperative cancellation by allowing Swift `Task.cancel()` to propagate directly into the underlying Kotlin `Job`, which SKIE automatically wires only when using structured `for await` loops inside managed `Task` contexts.
- Engineers MUST NOT block Swift actor contexts with synchronous locks or thread-sleeping operations while awaiting SKIE flow emissions; all collections across the FFI bridge MUST remain suspension-point compliant.
- Hot Kotlin Flows consumed in Swift UI components MUST be isolated to `@MainActor` at the Swift collection boundary to prevent cross-thread state corruption during view tree invalidation.

## Bad vs Good Implementations
### Swift Consumption of Kotlin Flow: Anti-Pattern vs SKIE Native AsyncSequence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using Task.detached and collecting Kotlin Flows through legacy completion handlers breaks the structured concurrency lifecycle. If UserViewModel is deallocated, the underlying coroutine in Kotlin Native GC continues running, leaking memory and network connections, while ignoring Swift task cancellation.
```swift
import Shared

final class UserViewModel: ObservableObject {
    @Published var state: UserState = .initial
    private let repository: UserRepository

    init(repository: UserRepository) {
        self.repository = repository
        // VIOLATION: Task.detached breaks structured concurrency.
        // Manual callback wrapper drops cancellation; Kotlin Job remains alive indefinitely.
        Task.detached {
            self.repository.observeUserState().collect { newState in
                DispatchQueue.main.async {
                    self.state = newState
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Directly iterates the SKIE-generated AsyncSequence using modern Swift async/await. Cancellation of the parent Swift Task automatically signals cooperative cancellation across the bridge to the underlying Kotlin Coroutine Job, preventing memory leaks and orphaned operations.
```swift
import Shared
import SwiftUI

@MainActor
final class UserViewModel: ObservableObject {
    @Published private(set) var state: UserState = .initial
    private let repository: UserRepository
    private var observationTask: Task<Void, Never>?

    init(repository: UserRepository) {
        self.repository = repository
    }

    func startObserving() {
        observationTask?.cancel()
        observationTask = Task { [weak self, repository] in
            // INVARIANT: Native SKIE AsyncSequence with structured cancellation
            for await newState in repository.observeUserState() {
                guard !Task.isCancelled else { break }
                self?.state = newState
            }
        }
    }

    deinit {
        // Automatically cancels underlying Kotlin Job via SKIE cancellation bridge
        observationTask?.cancel()
    }
}
```

### Kotlin Side Flow Backpressure Declaration: Anti-Pattern vs Safe Bounded Flow

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A MutableSharedFlow without explicit replay and extraBufferCapacity defaults to suspending emitters if any downstream consumer (including the Swift SKIE collector) lags. Across native threads, this can cause deadlocks and frame drops when Swift's runloop cannot drain the queue fast enough.
```kotlin
package com.example.shared

import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow

class SensorRepository {
    // VIOLATION: Unbuffered SharedFlow will suspend or drop based on default policies
    // that can deadlock Swift consumer runloops when backpressured across the bridge
    private val _sensorEvents = MutableSharedFlow<SensorData>()
    val sensorEvents: SharedFlow<SensorData> = _sensorEvents.asSharedFlow()
}
```

#### Production Standard (Correct)
> **Standard**: Defines an explicit backpressure overflow strategy. When bridging to Swift modern concurrency, burst emissions will drop stale frames instead of stalling the Kotlin producer or locking up Swift Task queues.
```kotlin
package com.example.shared

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow

class SensorRepository {
    // INVARIANT: Explicit buffer and non-suspending drop strategy protects bridge throughput
    private val _sensorEvents = MutableSharedFlow<SensorData>(
        replay = 1,
        extraBufferCapacity = 64,
        onBufferOverflow = BufferOverflow.DROP_OLDEST
    )
    val sensorEvents: SharedFlow<SensorData> = _sensorEvents.asSharedFlow()
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant

KMP SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic bidirectional cancellation and bounded backpressure propagation across the Kotlin Multiplatform and Swift boundary using SKIE. Prevents orphan coroutine leaks, memory bloat from uncollected buffers, and actor deadlocks when consuming Kotlin Flows via Swift modern concurrency. 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: Leaked Kotlin Coroutine Jobs and Swift Actor Stalls via Unbound Flow Bridging or Unscoped Task Wrappers 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 DriftLeaked Kotlin Coroutine Jobs and Swift Actor Stalls via Unbound Flow Bridging or Unscoped Task WrappersCritical
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 leverage SKIE-generated direct `AsyncSequence` conformance on Kotlin `Flow` rather than legacy callback-based closures, manual `Continuation` wrappers, or home-grown `AsyncStream` adapters.

Engineers MUST ALWAYS leverage SKIE-generated direct `AsyncSequence` conformance on Kotlin `Flow` rather than legacy callback-based closures, manual `Continuation` wrappers, or home-grown `AsyncStream` adapters.

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 NEVER consume a SKIE bridged `Flow` inside an untracked, unscoped Swift `Task.detached` without binding its lifecycle to an explicit parent `Task` or owner token that cancels on view disappearance or component deinit.

Engineers MUST NEVER consume a SKIE bridged `Flow` inside an untracked, unscoped Swift `Task.detached` without binding its lifecycle to an explicit parent `Task` or owner token that cancels on view disappearance or component deinit.

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

Kotlin-exposed `SharedFlow` and `StateFlow` primitives MUST define explicit buffer capacities and overflow strategies (e.g., `onBufferOverflow = BufferOverflow.DROP_OLDEST`) if emissions exceed the Swift consumption runloop throughput.

Kotlin-exposed `SharedFlow` and `StateFlow` primitives MUST define explicit buffer capacities and overflow strategies (e.g., `onBufferOverflow = BufferOverflow.DROP_OLDEST`) if emissions exceed the Swift consumption runloop throughput.

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

Swift consumers MUST handle cooperative cancellation by allowing Swift `Task.cancel()` to propagate directly into the underlying Kotlin `Job`, which SKIE automatically wires only when using structured `for await` loops inside managed `Task` contexts.

Swift consumers MUST handle cooperative cancellation by allowing Swift `Task.cancel()` to propagate directly into the underlying Kotlin `Job`, which SKIE automatically wires only when using structured `for await` loops inside managed `Task` contexts.

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

Engineers MUST NOT block Swift actor contexts with synchronous locks or thread-sleeping operations while awaiting SKIE flow emissions

Engineers MUST NOT block Swift actor contexts with synchronous locks or thread-sleeping operations while awaiting SKIE flow emissions; all collections across the FFI bridge MUST remain suspension-point compliant.

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.
6

Hot Kotlin Flows consumed in Swift UI components MUST be isolated to `@MainActor` at the Swift collection boundary to prevent cross-thread state corruption during view tree invalidation.

Hot Kotlin Flows consumed in Swift UI components MUST be isolated to `@MainActor` at the Swift collection boundary to prevent cross-thread state corruption during view tree invalidation.

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 SKIE Flow-to-Swift AsyncStream Cooperative Cancellation & Backpressure Invariant critical for AI coding assistants?

Enforces deterministic bidirectional cancellation and bounded backpressure propagation across the Kotlin Multiplatform and Swift boundary using SKIE. Prevents orphan coroutine leaks, memory bloat from uncollected buffers, and actor deadlocks when consuming Kotlin Flows via Swift modern concurrency. 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 (Leaked Kotlin Coroutine Jobs and Swift Actor Stalls via Unbound Flow Bridging or Unscoped Task Wrappers) 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