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

Bun 1.2 Isolated Native SQLite Prepared Statement Finalization Invariant

Enforces deterministic statement finalization and strict per-worker database isolation when using bun:sqlite in concurrent Bun 1.2 workloads. Failing to explicitly finalize prepared statements or attempting to share Database instances across concurrent Bun worker threads triggers native memory leaks, segmentation faults, and unresolved SQLITE_BUSY locking contention.

Prohibited Anti-Pattern: Leaking unfinalized native SQLite statement pointers and sharing database handles across Bun worker threads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Isolated Native SQLite Prepared Statement Finalization Invariant - Enforces deterministic statement finalization and strict per-worker database isolation when using bun:sqlite in concurrent Bun 1.2 workloads. Failing to explicitly finalize prepared statements or attempting to share Database instances across concurrent Bun worker threads triggers native memory leaks, segmentation faults, and unresolved SQLITE_BUSY locking contention.
globs: src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-statement-finalization-invariant"
---

# Bun 1.2 Isolated Native SQLite Prepared Statement Finalization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking unfinalized native SQLite statement pointers and sharing database handles across Bun worker threads

## System Constraints
You are a Principal Engineer enforcing Bun 1.2 Isolated Native SQLite Prepared Statement Finalization Invariant. Mandate invariants that prevent native C-level handle leakage and cross-thread SQLite corruption.

## Strict Guidelines
- Engineers MUST ALWAYS explicitly finalize prepared statements via statement.finalize() inside a finally block or utilize explicit Disposable wrappers (using statement = db.prepare(...)) when creating ephemeral queries.
- Engineers MUST NOT share a Database instance between Bun Worker threads; SQLite connections MUST be worker-isolated or managed via an explicit dedicated connection coordinator pattern.
- Engineers MUST configure WAL mode (PRAGMA journal_mode = WAL) and a non-zero busy timeout (PRAGMA busy_timeout = 5000) on every isolated native connection initialization to prevent instant SQLITE_BUSY failures under concurrency.
- Code SHOULD maintain a bounded StatementCache for recurring queries per worker instead of dynamically compiling identical SQL strings repeatedly in request loops.
- Services MUST ensure that all open statements are finalized prior to calling db.close(), preventing silent native resource hanging and database file lock retention on shutdown.

## Bad vs Good Implementations
### Ad-hoc query compilation leak vs deterministic statement scoping and pooling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Preparing statements per request without caching or calling .finalize() leaves the underlying sqlite3_stmt pointers active in native memory until unpredictable GC cycles, exhausting file descriptors and causing native thread locks.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('app.db');

export async function handleRequest(userId: string) {
  // Anti-pattern: dynamically prepares statement every invocation without finalization
  // In Bun 1.2, abandoned Statement instances retain native C++ handles, causing memory bloat
  const query = db.prepare('SELECT id, name, email FROM users WHERE id = ?1');
  const user = query.get(userId);
  return user;
}
```

#### Production Standard (Correct)
> **Standard**: Reuses compiled prepared statements within the isolated thread and explicitly provides clean teardown lifecycle hooks, avoiding native handle thrashing and memory leaks.
```typescript
import { Database, Statement } from 'bun:sqlite';

// Initialize isolated native connection with robust concurrency pragmas
const db = new Database('app.db', { strict: true });
db.exec('PRAGMA journal_mode = WAL;');
db.exec('PRAGMA busy_timeout = 5000;');

// Pre-compile and reuse statically within the worker context
const getUserStmt = db.prepare<[string], { id: string; name: string; email: string }>(
  'SELECT id, name, email FROM users WHERE id = ?1'
);

export async function handleRequest(userId: string) {
  return getUserStmt.get(userId);
}

export function teardownWorker() {
  // Deterministically finalize on teardown
  getUserStmt.finalize();
  db.close();
}
```

### Ephemeral statement management with explicit Symbol.dispose pattern

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If errors occur or the function exits, the ephemeral dynamic statement remains active in SQLite's native statement tracking table, causing subsequent schema locks.
```typescript
import { Database } from 'bun:sqlite';

export function executeDynamicFilter(db: Database, dynamicSql: string, params: unknown[]) {
  const stmt = db.prepare(dynamicSql);
  const rows = stmt.all(...params);
  // If execution throws or returns, stmt is never finalized
  return rows;
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees that regardless of query exceptions or execution branches, the native statement handle is immediately finalized, freeing lock claims and native memory.
```typescript
import { Database, Statement } from 'bun:sqlite';

export function executeDynamicFilter(db: Database, dynamicSql: string, params: unknown[]) {
  const stmt = db.prepare(dynamicSql);
  try {
    return stmt.all(...params);
  } finally {
    // Deterministic finalization immediately releases SQLite native resources
    stmt.finalize();
  }
}
```

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 Isolated Native SQLite Prepared Statement Finalization Invariant

Bun 1.2 Isolated Native SQLite Prepared Statement Finalization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic statement finalization and strict per-worker database isolation when using bun:sqlite in concurrent Bun 1.2 workloads. Failing to explicitly finalize prepared statements or attempting to share Database instances across concurrent Bun worker threads triggers native memory leaks, segmentation faults, and unresolved SQLITE_BUSY locking contention. 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: Leaking unfinalized native SQLite statement pointers and sharing database handles across Bun worker threads 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 DriftLeaking unfinalized native SQLite statement pointers and sharing database handles across Bun worker threadsCritical
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 explicitly finalize prepared statements via statement.finalize() inside a finally block or utilize explicit Disposable wrappers (using statement = db.prepare(...)) when creating ephemeral queries.

Engineers MUST ALWAYS explicitly finalize prepared statements via statement.finalize() inside a finally block or utilize explicit Disposable wrappers (using statement = db.prepare(...)) when creating ephemeral queries.

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 share a Database instance between Bun Worker threads

Engineers MUST NOT share a Database instance between Bun Worker threads; SQLite connections MUST be worker-isolated or managed via an explicit dedicated connection coordinator pattern.

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 configure WAL mode (PRAGMA journal_mode = WAL) and a non-zero busy timeout (PRAGMA busy_timeout = 5000) on every isolated native connection initialization to prevent instant SQLITE_BUSY failures under concurrency.

Engineers MUST configure WAL mode (PRAGMA journal_mode = WAL) and a non-zero busy timeout (PRAGMA busy_timeout = 5000) on every isolated native connection initialization to prevent instant SQLITE_BUSY failures under concurrency.

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 maintain a bounded StatementCache for recurring queries per worker instead of dynamically compiling identical SQL strings repeatedly in request loops.

Code SHOULD maintain a bounded StatementCache for recurring queries per worker instead of dynamically compiling identical SQL strings repeatedly in request loops.

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

Services MUST ensure that all open statements are finalized prior to calling db.close(), preventing silent native resource hanging and database file lock retention on shutdown.

Services MUST ensure that all open statements are finalized prior to calling db.close(), preventing silent native resource hanging and database file lock retention on shutdown.

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 Isolated Native SQLite Prepared Statement Finalization Invariant critical for AI coding assistants?

Enforces deterministic statement finalization and strict per-worker database isolation when using bun:sqlite in concurrent Bun 1.2 workloads. Failing to explicitly finalize prepared statements or attempting to share Database instances across concurrent Bun worker threads triggers native memory leaks, segmentation faults, and unresolved SQLITE_BUSY locking contention. 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 (Leaking unfinalized native SQLite statement pointers and sharing database handles across Bun worker threads) 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