This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-sqlite-wal-mmap-boundary-guardrail

Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail

Protects Bun 1.2 multi-threaded SQLite deployments from SIGBUS kernel aborts and WAL shared memory (-shm) corruption during concurrent write bursts. Enforces isolated single-writer coordination, explicit busy timeout locks, disabled auto-checkpointing during worker operations, and synchronized memory-mapped region access.

Prohibited Anti-Pattern: Uncoordinated Parallel Writes and Automatic WAL Checkpoints Across Multi-Threaded Bun Workers Triggering SIGBUS and WAL Index Corruption

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail - Protects Bun 1.2 multi-threaded SQLite deployments from SIGBUS kernel aborts and WAL shared memory (-shm) corruption during concurrent write bursts. Enforces isolated single-writer coordination, explicit busy timeout locks, disabled auto-checkpointing during worker operations, and synchronized memory-mapped region access.
globs: src/**/*.ts, src/**/*.worker.ts, workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-mmap-boundary-guardrail"
---

# Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated Parallel Writes and Automatic WAL Checkpoints Across Multi-Threaded Bun Workers Triggering SIGBUS and WAL Index Corruption

## System Constraints
You are a Principal Software Architect enforcing Bun 1.2 SQLite memory safety invariants. In multi-threaded Bun environments, concurrent SQLite write bursts over shared WAL files can cause SIGBUS crashes and -shm file corruption when background worker threads access uncoordinated mmap regions while another thread truncates or checkpoints the write-ahead log. You must enforce single-writer message-passing pipelines, read-only connections for worker pools, explicit busy timeouts, and detached, passive WAL checkpoints.

## Strict Guidelines
- Engineers MUST ALWAYS configure `PRAGMA busy_timeout = 5000;` and `PRAGMA journal_mode = WAL;` on every initialized `bun:sqlite` Database instance.
- Engineers MUST NOT allow multiple worker threads to execute concurrent writes directly on shared SQLite database files.
- Services MUST route all mutating transactions through a dedicated single-writer worker or bounded serialized queue.
- Code SHOULD disable SQLite automatic checkpointing via `PRAGMA wal_autocheckpoint = 0;` during high-throughput parallel ingestion and invoke explicit non-blocking checkpoints (`PRAGMA wal_checkpoint(PASSIVE);`) from a isolated management thread.
- Components NEVER modify `PRAGMA mmap_size` dynamically after worker threads have initialized active prepared statements.

## Bad vs Good Implementations
### Uncoordinated Multi-Worker Direct Writes vs. Dedicated Writer Queue with Controlled WAL Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct concurrent database instantiations across Bun worker threads without busy timeouts or checkpoint controls induce race conditions on the WAL index (`-shm`) and memory-mapped pages, resulting in SIGBUS kernel panics when one thread truncates the WAL while another accesses an mmapped buffer.
```typescript
import { Database } from 'bun:sqlite';

// ANTI-PATTERN: Multiple workers instantiate read-write handles and write concurrently.
// Default autocheckpoint triggers dynamic WAL truncation, invalidating mmap boundaries
// for concurrent readers/writers, causing SIGBUS memory access violations.
export function handleWorkerWrite(dbPath: string, payload: { id: string; val: string }) {
  const db = new Database(dbPath);
  db.exec('PRAGMA journal_mode = WAL;');
  
  // Unprotected write: no busy_timeout, uncontrolled WAL autocheckpoint
  const stmt = db.prepare('INSERT INTO telemetry (id, val) VALUES (?, ?)');
  stmt.run(payload.id, payload.val);
  db.close();
}
```

#### Production Standard (Correct)
> **Standard**: Disabling SQLite auto-checkpoints prevents mid-burst file truncations that trigger SIGBUS errors on mmapped memory pages. Writes are strictly serialized through an in-process queue with explicit busy timeouts, and checkpoints are executed safely in non-blocking PASSIVE mode.
```typescript
import { Database } from 'bun:sqlite';

// PRODUCTION INVARIANT: Read-only handles for workers, single-thread dedicated writer,
// manual WAL boundary control with busy_timeout and PASSIVE checkpoints.
export class SafeDatabaseManager {
  private static instance: SafeDatabaseManager;
  private writerDb: Database;
  private writeQueue: Array<{ sql: string; params: unknown[]; resolve: () => void; reject: (err: unknown) => void }> = [];
  private isProcessing = false;

  private constructor(dbPath: string) {
    this.writerDb = new Database(dbPath, { strict: true });
    
    // Establish durable WAL boundaries
    this.writerDb.exec(`
      PRAGMA journal_mode = WAL;
      PRAGMA synchronous = NORMAL;
      PRAGMA busy_timeout = 5000;
      PRAGMA wal_autocheckpoint = 0;
    `);
  }

  public static getInstance(dbPath: string): SafeDatabaseManager {
    if (!SafeDatabaseManager.instance) {
      SafeDatabaseManager.instance = new SafeDatabaseManager(dbPath);
    }
    return SafeDatabaseManager.instance;
  }

  public createReadOnlyHandle(dbPath: string): Database {
    const reader = new Database(dbPath, { readonly: true, strict: true });
    reader.exec('PRAGMA busy_timeout = 5000;');
    return reader;
  }

  public async executeWrite(sql: string, params: unknown[] = []): Promise<void> {
    return new Promise((resolve, reject) => {
      this.writeQueue.push({ sql, params, resolve, reject });
      this.processQueue();
    });
  }

  private processQueue() {
    if (this.isProcessing || this.writeQueue.length === 0) return;
    this.isProcessing = true;

    while (this.writeQueue.length > 0) {
      const item = this.writeQueue.shift()!;
      try {
        const stmt = this.writerDb.prepare(item.sql);
        stmt.run(...(item.params as [any]));
        item.resolve();
      } catch (error) {
        item.reject(error);
      }
    }

    this.isProcessing = false;
  }

  public safeCheckpoint(): void {
    // Non-blocking checkpoint guarantees no mmap invalidation for concurrent reads
    this.writerDb.exec('PRAGMA wal_checkpoint(PASSIVE);');
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail

Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail defines an industrial-grade behavioral standard for backend engineering. Protects Bun 1.2 multi-threaded SQLite deployments from SIGBUS kernel aborts and WAL shared memory (-shm) corruption during concurrent write bursts. Enforces isolated single-writer coordination, explicit busy timeout locks, disabled auto-checkpointing during worker operations, and synchronized memory-mapped region access. 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 Parallel Writes and Automatic WAL Checkpoints Across Multi-Threaded Bun Workers Triggering SIGBUS and WAL Index Corruption 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 Parallel Writes and Automatic WAL Checkpoints Across Multi-Threaded Bun Workers Triggering SIGBUS and WAL Index CorruptionCritical
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 configure `PRAGMA busy_timeout = 5000

Engineers MUST ALWAYS configure `PRAGMA busy_timeout = 5000;` and `PRAGMA journal_mode = WAL;` on every initialized `bun:sqlite` Database instance.

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 allow multiple worker threads to execute concurrent writes directly on shared SQLite database files.

Engineers MUST NOT allow multiple worker threads to execute concurrent writes directly on shared SQLite database files.

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

Services MUST route all mutating transactions through a dedicated single-writer worker or bounded serialized queue.

Services MUST route all mutating transactions through a dedicated single-writer worker or bounded serialized queue.

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

Code SHOULD disable SQLite automatic checkpointing via `PRAGMA wal_autocheckpoint = 0

Code SHOULD disable SQLite automatic checkpointing via `PRAGMA wal_autocheckpoint = 0;` during high-throughput parallel ingestion and invoke explicit non-blocking checkpoints (`PRAGMA wal_checkpoint(PASSIVE);`) from a isolated management 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

Components NEVER modify `PRAGMA mmap_size` dynamically after worker threads have initialized active prepared statements.

Components NEVER modify `PRAGMA mmap_size` dynamically after worker threads have initialized active prepared statements.

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 Bun 1.2 Multi-Threaded SQLite WAL Memory-Mapped Region Boundary Guardrail critical for AI coding assistants?

Protects Bun 1.2 multi-threaded SQLite deployments from SIGBUS kernel aborts and WAL shared memory (-shm) corruption during concurrent write bursts. Enforces isolated single-writer coordination, explicit busy timeout locks, disabled auto-checkpointing during worker operations, and synchronized memory-mapped region access. 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 Parallel Writes and Automatic WAL Checkpoints Across Multi-Threaded Bun Workers Triggering SIGBUS and WAL Index Corruption) 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.

1 Rule in Stack

Bun