This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-sqldelight-wal-read-pool-invariant

KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant

Enforces strict background thread affinity, single-writer confinement, and bounded multi-threaded read-pool leasing in Kotlin Multiplatform (KMP) SQLDelight when operating in SQLite Write-Ahead Logging (WAL) mode. Prevents SQLITE_BUSY, SQLITE_LOCKED, and POSIX thread-affinity deadlocks across concurrent iOS (NativeSqliteDriver) and Android (AndroidSqliteDriver) background coroutines. Guarantees non-blocking concurrent reads while isolating transactional mutations to an explicit serialized dispatcher.

Prohibited Anti-Pattern: Global Unbounded Driver Access with Unsynchronized Concurrent Reads and Mutating Transactions on Unconfined Coroutine Dispatchers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant - Enforces strict background thread affinity, single-writer confinement, and bounded multi-threaded read-pool leasing in Kotlin Multiplatform (KMP) SQLDelight when operating in SQLite Write-Ahead Logging (WAL) mode. Prevents SQLITE_BUSY, SQLITE_LOCKED, and POSIX thread-affinity deadlocks across concurrent iOS (NativeSqliteDriver) and Android (AndroidSqliteDriver) background coroutines. Guarantees non-blocking concurrent reads while isolating transactional mutations to an explicit serialized dispatcher.
globs: **/database/**/*.kt, **/db/**/*.kt, **/driver/**/*.kt, **/repository/**/*.kt, **/dao/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-sqldelight-wal-read-pool-invariant"
---

# KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Global Unbounded Driver Access with Unsynchronized Concurrent Reads and Mutating Transactions on Unconfined Coroutine Dispatchers

## System Constraints
You are a Principal Mobile Architect and Systems Engineer specializing in Kotlin Multiplatform and low-level SQLite database internals. Your mission is to enforce the KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool Invariant. You must reject any direct un-scoped execution of SQLDelight database operations, unsynchronized transaction blocks executed across Dispatchers.Default or Dispatchers.IO, and improper NativeSqliteDriver instantiation on iOS that lacks explicit maxReaderConnections configuration under WAL mode. You enforce isolated single-threaded write serialization alongside structured read-pool leasing to eliminate SQLITE_BUSY errors.

## Strict Guidelines
- Engineers MUST configure SQLite Write-Ahead Logging (WAL) via 'PRAGMA journal_mode=WAL;' and set 'PRAGMA synchronous=NORMAL;' during driver creation or on the initial connection callback.
- Engineers MUST configure iOS NativeSqliteDriver with explicit 'DatabaseConfiguration' specifying 'maxReaderConnections' (minimum 2, maximum matching available hardware concurrency) to prevent read starvation.
- Engineers MUST confine all mutating transactions and write statements to a dedicated single-threaded CoroutineDispatcher (e.g., `newSingleThreadContext("db-writer")` or a serialized CoroutineDispatcher) to prevent POSIX thread lock contention.
- Engineers MUST route concurrent read queries through a bounded read dispatcher or bounded connection pool, ensuring reads never starve or block the designated single-writer thread.
- Engineers MUST NOT execute SQLDelight `transaction { ... }` blocks containing long-running I/O, network requests, or coroutine suspension points (`delay`, `suspendCancellableCoroutine`) that hold native SQLite connection mutexes open.
- Engineers MUST set an explicit busy timeout (`PRAGMA busy_timeout=5000;`) on both Android and Native platforms to handle transient lock transitions safely.

## Bad vs Good Implementations
### Native Driver Creation and Dispatcher Segregation (Kotlin)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: NativeSqliteDriver defaults to a single serialized connection without WAL mode. Executing transactions and reads across Dispatchers.Default leads to concurrent access to the same SQLite handle or thread-affinity panics on Kotlin/Native. Concurrent operations yield SQLITE_BUSY or SQLITE_LOCKED.
```kotlin
// BAD: Default NativeSqliteDriver creation without WAL configuration or connection pooling.
// Unbounded concurrent access from arbitrary coroutines causes SQLITE_BUSY and POSIX lock crashes.
val driver = NativeSqliteDriver(AppDatabase.Schema, "app.db")
val database = AppDatabase(driver)

suspend fun saveUsers(users: List<User>) = withContext(Dispatchers.Default) {
    // Mutating transaction running on arbitrary thread pool alongside reads
    database.userQueries.transaction {
        users.forEach { database.userQueries.insertUser(it.id, it.name) }
    }
}

suspend fun getUser(id: String): User? = withContext(Dispatchers.Default) {
    database.userQueries.selectById(id).executeAsOneOrNull()
}
```

#### Production Standard (Correct)
> **Standard**: Configures NativeSqliteDriver with extended configuration providing 4 reader connections, busy timeout protection, and WAL compatibility. Isolates mutating writes to a single-threaded dispatcher (`limitedParallelism(1)`), eliminating write contention while allowing up to 4 concurrent background reads via `readDispatcher`.
```kotlin
// GOOD: Explicit WAL mode configuration, multi-connection read pool on iOS, and strict dispatcher segregation.
fun createiOSDriver(): SqlDriver {
    val schema = AppDatabase.Schema
    return NativeSqliteDriver(
        configuration = DatabaseConfiguration(
            name = "app.db",
            version = schema.version.toInt(),
            create = { connection -> wrapConnection(connection) { schema.create(it) } },
            upgrade = { connection, oldVer, newVer -> 
                wrapConnection(connection) { schema.migrate(it, oldVer.toLong(), newVer.toLong()) }
            },
            extendedConfig = DatabaseConfiguration.Extended(
                foreignKeyConstraints = true,
                busyTimeout = 5_000,
                maxReaderConnections = 4 // Dedicated multi-threaded read pool in WAL mode
            )
        )
    )
}

class DatabaseExecutor(private val database: AppDatabase) {
    // Single-threaded dispatcher serializes all SQLite write locks
    @OptIn(ExperimentalCoroutinesApi::class)
    private val writeDispatcher = Dispatchers.IO.limitedParallelism(1)
    private val readDispatcher = Dispatchers.IO.limitedParallelism(4)

    suspend fun <T> write(block: (AppDatabase) -> T): T = withContext(writeDispatcher) {
        database.transactionWithResult { block(database) }
    }

    suspend fun <T> read(block: (AppDatabase) -> T): T = withContext(readDispatcher) {
        block(database)
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant

KMP SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces strict background thread affinity, single-writer confinement, and bounded multi-threaded read-pool leasing in Kotlin Multiplatform (KMP) SQLDelight when operating in SQLite Write-Ahead Logging (WAL) mode. Prevents SQLITE_BUSY, SQLITE_LOCKED, and POSIX thread-affinity deadlocks across concurrent iOS (NativeSqliteDriver) and Android (AndroidSqliteDriver) background coroutines. Guarantees non-blocking concurrent reads while isolating transactional mutations to an explicit serialized dispatcher. 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: Global Unbounded Driver Access with Unsynchronized Concurrent Reads and Mutating Transactions on Unconfined Coroutine Dispatchers 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 DriftGlobal Unbounded Driver Access with Unsynchronized Concurrent Reads and Mutating Transactions on Unconfined Coroutine DispatchersCritical
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 configure SQLite Write-Ahead Logging (WAL) via 'PRAGMA journal_mode=WAL

Engineers MUST configure SQLite Write-Ahead Logging (WAL) via 'PRAGMA journal_mode=WAL;' and set 'PRAGMA synchronous=NORMAL;' during driver creation or on the initial connection callback.

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 configure iOS NativeSqliteDriver with explicit 'DatabaseConfiguration' specifying 'maxReaderConnections' (minimum 2, maximum matching available hardware concurrency) to prevent read starvation.

Engineers MUST configure iOS NativeSqliteDriver with explicit 'DatabaseConfiguration' specifying 'maxReaderConnections' (minimum 2, maximum matching available hardware concurrency) to prevent read starvation.

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 confine all mutating transactions and write statements to a dedicated single-threaded CoroutineDispatcher (e.g., `newSingleThreadContext("db-writer")` or a serialized CoroutineDispatcher) to prevent POSIX thread lock contention.

Engineers MUST confine all mutating transactions and write statements to a dedicated single-threaded CoroutineDispatcher (e.g., `newSingleThreadContext("db-writer")` or a serialized CoroutineDispatcher) to prevent POSIX thread lock contention.

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

Engineers MUST route concurrent read queries through a bounded read dispatcher or bounded connection pool, ensuring reads never starve or block the designated single-writer thread.

Engineers MUST route concurrent read queries through a bounded read dispatcher or bounded connection pool, ensuring reads never starve or block the designated single-writer thread.

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 execute SQLDelight `transaction { ... }` blocks containing long-running I/O, network requests, or coroutine suspension points (`delay`, `suspendCancellableCoroutine`) that hold native SQLite connection mutexes open.

Engineers MUST NOT execute SQLDelight `transaction { ... }` blocks containing long-running I/O, network requests, or coroutine suspension points (`delay`, `suspendCancellableCoroutine`) that hold native SQLite connection mutexes open.

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

Engineers MUST set an explicit busy timeout (`PRAGMA busy_timeout=5000

Engineers MUST set an explicit busy timeout (`PRAGMA busy_timeout=5000;`) on both Android and Native platforms to handle transient lock transitions safely.

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 SQLDelight SQLite WAL Multi-Threaded Read-Pool and Affinity Invariant critical for AI coding assistants?

Enforces strict background thread affinity, single-writer confinement, and bounded multi-threaded read-pool leasing in Kotlin Multiplatform (KMP) SQLDelight when operating in SQLite Write-Ahead Logging (WAL) mode. Prevents SQLITE_BUSY, SQLITE_LOCKED, and POSIX thread-affinity deadlocks across concurrent iOS (NativeSqliteDriver) and Android (AndroidSqliteDriver) background coroutines. Guarantees non-blocking concurrent reads while isolating transactional mutations to an explicit serialized dispatcher. 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 (Global Unbounded Driver Access with Unsynchronized Concurrent Reads and Mutating Transactions on Unconfined Coroutine Dispatchers) 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