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

Bun 1.2 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability

Enforces strict linearizable read-after-write consistency across multithreaded Bun worker isolates accessing in-process SQLite databases in Write-Ahead Logging (WAL) mode. Prevents stale index snapshot reads caused by cached shared-memory (.shm) state across isolated JavaScript heaps by mandating explicit transaction boundary synchronization, memory barrier pragmas, and managed checkpoint coordination.

Prohibited Anti-Pattern: Dirty Read Anomaly Across Bun Worker Isolates Due to Unsynchronized WAL Shared-Memory Reads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability - Enforces strict linearizable read-after-write consistency across multithreaded Bun worker isolates accessing in-process SQLite databases in Write-Ahead Logging (WAL) mode. Prevents stale index snapshot reads caused by cached shared-memory (.shm) state across isolated JavaScript heaps by mandating explicit transaction boundary synchronization, memory barrier pragmas, and managed checkpoint coordination.
globs: src/**/*.{ts,js}, workers/**/*.{ts,js}, lib/db/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-wal-shm-invalidation-invariant"
---

# Bun 1.2 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dirty Read Anomaly Across Bun Worker Isolates Due to Unsynchronized WAL Shared-Memory Reads

## System Constraints
You are a Principal Backend Architect enforcing strict multi-isolate concurrency invariants for Bun 1.2's native `bun:sqlite` engine. You must eliminate cross-worker read-after-write inconsistencies and stale page frame reads caused by SQLite WAL-index (.shm) caching across disparate OS threads and V8/JSC heaps. Mandate explicit transaction semantics, deterministic checkpointing, and barrier synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS configure SQLite instances with `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` before dispatching read or write operations across workers.
- Engineers MUST NOT rely on implicit or autocommit transactions for read-after-write sequences spanning multiple Bun `Worker` threads.
- Code MUST wrap cross-thread visible reads in explicit immediate or deferred transaction blocks (`BEGIN` / `COMMIT`) to force SQLite to invalidate its local WAL index frame pointers via fresh `.shm` re-reads.
- Workers writing to SQLite MUST broadcast transaction epoch sequences or leverage atomic notifications (e.g., `SharedArrayBuffer` with `Atomics.wait`/`notify` or explicit `worker.postMessage`) before dependent workers execute reads.
- Engineers MUST NEVER execute uncoordinated `PRAGMA wal_checkpoint` operations concurrently inside multiple worker threads; all checkpointing must be delegated to a dedicated database coordinator isolate.

## Bad vs Good Implementations
### Cross-Isolate Read-After-Write Synchronization in Bun 1.2

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In multithreaded Bun environments, independent Worker threads open isolated SQLite connections. A naked autocommit SELECT query can reuse a cached internal WAL-index read mark (.shm) without forcing an OS memory barrier, returning stale or missing data immediately following a commit from another worker.
```typescript
import { Database } from 'bun:sqlite';

// Anti-pattern: Relying on autocommit without WAL index cache synchronization
export function readLatestRecord(dbPath: string, entityId: string) {
  const db = new Database(dbPath);
  // Direct naked read may observe a stale WAL index snapshot
  // if another Bun worker isolate recently committed via a distinct connection
  const query = db.query('SELECT * FROM entities WHERE id = ?');
  return query.get(entityId);
}
```

#### Production Standard (Correct)
> **Standard**: Wrapping the read in an explicit transaction (`db.transaction()`) ensures that `bun:sqlite` executes a sqlite3_step transaction preamble, forcing the SQLite WAL subsystem to re-read the WAL-index header from `.shm` and observe newly appended log frames committed by other isolates.
```typescript
import { Database } from 'bun:sqlite';

export function readLinearizableRecord(dbPath: string, entityId: string) {
  const db = new Database(dbPath, { strict: true });
  
  // Enforce required PRAGMAs for shared memory coherency
  db.exec('PRAGMA journal_mode = WAL;');
  db.exec('PRAGMA synchronous = NORMAL;');

  // Explicit transaction boundary forces an shm barrier check and syncs WAL frame headers
  const readTx = db.transaction((id: string) => {
    const query = db.query('SELECT * FROM entities WHERE id = ?');
    return query.get(id);
  });

  return readTx(entityId);
}
```

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: Bun 1.2 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability

Bun 1.2 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability defines an industrial-grade behavioral standard for backend engineering. Enforces strict linearizable read-after-write consistency across multithreaded Bun worker isolates accessing in-process SQLite databases in Write-Ahead Logging (WAL) mode. Prevents stale index snapshot reads caused by cached shared-memory (.shm) state across isolated JavaScript heaps by mandating explicit transaction boundary synchronization, memory barrier pragmas, and managed checkpoint coordination. 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: Dirty Read Anomaly Across Bun Worker Isolates Due to Unsynchronized WAL Shared-Memory Reads 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 DriftDirty Read Anomaly Across Bun Worker Isolates Due to Unsynchronized WAL Shared-Memory ReadsCritical
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 SQLite instances with `PRAGMA journal_mode = WAL

Engineers MUST ALWAYS configure SQLite instances with `PRAGMA journal_mode = WAL;` and `PRAGMA synchronous = NORMAL;` before dispatching read or write operations across workers.

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 rely on implicit or autocommit transactions for read-after-write sequences spanning multiple Bun `Worker` threads.

Engineers MUST NOT rely on implicit or autocommit transactions for read-after-write sequences spanning multiple Bun `Worker` threads.

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 MUST wrap cross-thread visible reads in explicit immediate or deferred transaction blocks (`BEGIN` / `COMMIT`) to force SQLite to invalidate its local WAL index frame pointers via fresh `.shm` re-reads.

Code MUST wrap cross-thread visible reads in explicit immediate or deferred transaction blocks (`BEGIN` / `COMMIT`) to force SQLite to invalidate its local WAL index frame pointers via fresh `.shm` re-reads.

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

Workers writing to SQLite MUST broadcast transaction epoch sequences or leverage atomic notifications (e.g., `SharedArrayBuffer` with `Atomics.wait`/`notify` or explicit `worker.postMessage`) before dependent workers execute reads.

Workers writing to SQLite MUST broadcast transaction epoch sequences or leverage atomic notifications (e.g., `SharedArrayBuffer` with `Atomics.wait`/`notify` or explicit `worker.postMessage`) before dependent workers execute reads.

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 NEVER execute uncoordinated `PRAGMA wal_checkpoint` operations concurrently inside multiple worker threads

Engineers MUST NEVER execute uncoordinated `PRAGMA wal_checkpoint` operations concurrently inside multiple worker threads; all checkpointing must be delegated to a dedicated database coordinator isolate.

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 SQLite WAL Shared-Memory Invalidation and Cross-Isolate Linearizability critical for AI coding assistants?

Enforces strict linearizable read-after-write consistency across multithreaded Bun worker isolates accessing in-process SQLite databases in Write-Ahead Logging (WAL) mode. Prevents stale index snapshot reads caused by cached shared-memory (.shm) state across isolated JavaScript heaps by mandating explicit transaction boundary synchronization, memory barrier pragmas, and managed checkpoint coordination. 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 (Dirty Read Anomaly Across Bun Worker Isolates Due to Unsynchronized WAL Shared-Memory Reads) 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