This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-atomic-sqlite-wal-rekeying-standard

KMP Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard

Enforces atomic, crash-resilient cryptographic key rotation for SQLCipher and SQLite databases operating in WAL mode across Android Keystore and iOS Secure Enclave/Keychain. Mandates full WAL truncation checkpoints, connection pool evacuation, and two-phase key state markers to prevent unrecoverable database corruption and torn-key reads.

Prohibited Anti-Pattern: Executing in-place PRAGMA rekey on active WAL connections without checkpoint truncation or atomic key-phase synchronization.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard - Enforces atomic, crash-resilient cryptographic key rotation for SQLCipher and SQLite databases operating in WAL mode across Android Keystore and iOS Secure Enclave/Keychain. Mandates full WAL truncation checkpoints, connection pool evacuation, and two-phase key state markers to prevent unrecoverable database corruption and torn-key reads.
globs: **/database/**/*.kt, **/storage/**/*.kt, **/security/**/*.kt, **/crypto/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-atomic-sqlite-wal-rekeying-standard"
---

# KMP Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing in-place PRAGMA rekey on active WAL connections without checkpoint truncation or atomic key-phase synchronization.

## System Constraints
You are a Principal Mobile Systems Architect enforcing the KMP Atomic SQLite WAL Re-Keying Standard. In Kotlin Multiplatform applications using SQLCipher/SQLite in Write-Ahead Logging (WAL) mode, re-keying is inherently non-atomic across process crashes if WAL frames remain unmerged or connection pools remain open. You must enforce strict connection drainage, explicit WAL checkpoint truncation (TRUNCATE), hardware keystore two-phase state commitment, and rollback protection.

## Strict Guidelines
- Engineers MUST ALWAYS execute a synchronous `PRAGMA wal_checkpoint(TRUNCATE)` prior to calling `PRAGMA rekey` or attaching migration tables to eliminate residual WAL frames encrypted under the old key.
- Engineers MUST NOT execute re-keying operations on shared connection pools or active background coroutines; all reader and writer connections MUST be drained and locked behind an exclusive migration mutex.
- Code SHOULD verify database integrity via `PRAGMA quick_check` immediately following the re-keying operation and before committing the new key alias as active in hardware storage.
- Services MUST persist a two-phase rotation token (`REKEY_IN_PROGRESS` vs `REKEY_COMMITTED`) in Android KeyStore (SharedPreferences backed by EncryptedSharedPreferences/MasterKey) and iOS Keychain with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`.
- Components NEVER expose SQLite raw memory keys or retain unencrypted byte arrays in KMP heap allocations beyond the scoped cryptographic execution block.

## Bad vs Good Implementations
### Unsafe in-place WAL re-keying vs. atomic two-phase checkpointed rotation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing PRAGMA rekey directly on an active WAL database causes torn writes. If background threads write frames or if the application crashes before checkpointing, WAL frames encrypted with the old key cannot be recovered by the new key, causing irreversible database corruption.
```kotlin
class DatabaseRekeyService(private val db: SQLiteDatabase, private val keyProvider: KeyProvider) {
    // ANTI-PATTERN: Re-keying while active WAL frames and pooled connections exist
    fun rotateDatabaseKey() {
        val newKey = keyProvider.generateAndStoreNewKey() // Immediately replaces old key
        // Throws or corrupts if background threads are writing to WAL frames
        db.execSQL("PRAGMA rekey = '${newKey.toHex()}';") 
        // If the process crashes here, WAL frames are encrypted under oldKey, but master record has newKey
    }
}
```

#### Production Standard (Correct)
> **Standard**: Acquires an exclusive lock on the connection pool, truncates the WAL file completely, records a pending rotation state in hardware-backed storage, executes the re-keying, verifies database integrity, and zeroizes key buffers in memory.
```kotlin
class DatabaseRekeyService(
    private val pool: DatabaseConnectionPool,
    private val keyManager: HardwareKeyManager
) {
    suspend fun rotateKeySafely(): Result<Unit> = pool.withExclusiveLock { conn ->
        val (oldKey, candidateKey) = keyManager.prepareCandidateKey()
        try {
            // 1. Drain & truncate WAL file to prevent mixed-key frames
            conn.rawQuery("PRAGMA wal_checkpoint(TRUNCATE);", null).use { it.moveToFirst() }
            conn.execSQL("PRAGMA locking_mode = EXCLUSIVE;")

            // 2. Mark hardware rotation state as PENDING
            keyManager.markRotationPending(candidateKey.alias)

            // 3. Atomically rekey
            conn.execSQL("PRAGMA rekey = ?", arrayOf(candidateKey.rawBytes))

            // 4. Validate page integrity
            conn.rawQuery("PRAGMA quick_check;", null).use { cursor ->
                if (!cursor.moveToFirst() || cursor.getString(0) != "ok") {
                    throw SQLiteException("Integrity check failed post-rekey")
                }
            }

            // 5. Finalize state in Hardware Keystore / Secure Enclave
            keyManager.commitKeyPromotion(candidateKey.alias)
            Result.success(Unit)
        } catch (e: Throwable) {
            keyManager.rollbackCandidateKey(candidateKey.alias)
            Result.failure(e)
        } finally {
            conn.execSQL("PRAGMA locking_mode = NORMAL;")
            candidateKey.rawBytes.fill(0.toByte()) // Zeroize sensitive memory
        }
    }
}
```

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 Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard

KMP Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces atomic, crash-resilient cryptographic key rotation for SQLCipher and SQLite databases operating in WAL mode across Android Keystore and iOS Secure Enclave/Keychain. Mandates full WAL truncation checkpoints, connection pool evacuation, and two-phase key state markers to prevent unrecoverable database corruption and torn-key reads. 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 in-place PRAGMA rekey on active WAL connections without checkpoint truncation or atomic key-phase synchronization. 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 in-place PRAGMA rekey on active WAL connections without checkpoint truncation or atomic key-phase synchronization.Critical
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 execute a synchronous `PRAGMA wal_checkpoint(TRUNCATE)` prior to calling `PRAGMA rekey` or attaching migration tables to eliminate residual WAL frames encrypted under the old key.

Engineers MUST ALWAYS execute a synchronous `PRAGMA wal_checkpoint(TRUNCATE)` prior to calling `PRAGMA rekey` or attaching migration tables to eliminate residual WAL frames encrypted under the old key.

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 re-keying operations on shared connection pools or active background coroutines

Engineers MUST NOT execute re-keying operations on shared connection pools or active background coroutines; all reader and writer connections MUST be drained and locked behind an exclusive migration mutex.

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 verify database integrity via `PRAGMA quick_check` immediately following the re-keying operation and before committing the new key alias as active in hardware storage.

Code SHOULD verify database integrity via `PRAGMA quick_check` immediately following the re-keying operation and before committing the new key alias as active in hardware storage.

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 persist a two-phase rotation token (`REKEY_IN_PROGRESS` vs `REKEY_COMMITTED`) in Android KeyStore (SharedPreferences backed by EncryptedSharedPreferences/MasterKey) and iOS Keychain with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`.

Services MUST persist a two-phase rotation token (`REKEY_IN_PROGRESS` vs `REKEY_COMMITTED`) in Android KeyStore (SharedPreferences backed by EncryptedSharedPreferences/MasterKey) and iOS Keychain with `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`.

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 expose SQLite raw memory keys or retain unencrypted byte arrays in KMP heap allocations beyond the scoped cryptographic execution block.

Components NEVER expose SQLite raw memory keys or retain unencrypted byte arrays in KMP heap allocations beyond the scoped cryptographic execution block.

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 Atomic SQLite WAL Re-Keying & Hardware-Backed Key Rotation Standard critical for AI coding assistants?

Enforces atomic, crash-resilient cryptographic key rotation for SQLCipher and SQLite databases operating in WAL mode across Android Keystore and iOS Secure Enclave/Keychain. Mandates full WAL truncation checkpoints, connection pool evacuation, and two-phase key state markers to prevent unrecoverable database corruption and torn-key reads. 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 in-place PRAGMA rekey on active WAL connections without checkpoint truncation or atomic key-phase synchronization.) 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