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

Bun 1.2 Native SQLite Zero-Copy Off-Heap Buffer Invariant

Enforces strict buffer ownership transfer and zero-copy pinned allocations between the JavaScriptCore (JSC) heap and native SQLite pointers during high-throughput ingest in Bun 1.2+. Prevents JSC garbage collection stop-the-world pauses, double-free faults, and unaligned memory access by mandating direct Uint8Array slice reuse with SQLite native statement binding.

Prohibited Anti-Pattern: Implicit JSC Heap Allocation and Buffer Cloning During High-Volume SQLite Ingestion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native SQLite Zero-Copy Off-Heap Buffer Invariant - Enforces strict buffer ownership transfer and zero-copy pinned allocations between the JavaScriptCore (JSC) heap and native SQLite pointers during high-throughput ingest in Bun 1.2+. Prevents JSC garbage collection stop-the-world pauses, double-free faults, and unaligned memory access by mandating direct Uint8Array slice reuse with SQLite native statement binding.
globs: src/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-sqlite-zero-copy-off-heap-buffer-invariant"
---

# Bun 1.2 Native SQLite Zero-Copy Off-Heap Buffer Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit JSC Heap Allocation and Buffer Cloning During High-Volume SQLite Ingestion

## System Constraints
You are a Principal Systems Engineer enforcing strict zero-copy off-heap memory invariants in Bun 1.2 SQLite workloads. High-frequency write paths must bypass JSC GC churn by leveraging direct ArrayBuffer byte-slices, explicit memory pin/ownership patterns, and typed array bindings. Prevent any automatic string conversions, nested buffer copies, or un-finalized statement allocations.

## Strict Guidelines
- Engineers MUST ALWAYS bind raw typed arrays (Uint8Array) directly to native SQLite statements using positional parameters to leverage Bun's zero-copy C++ binding layer.
- Engineers MUST NOT convert binary blobs into Node.js Buffer instances or intermediate base64/hex strings before persisting to Bun SQLite.
- Engineers MUST NOT re-allocate typed arrays within ingest loops; pre-allocate a shared ring buffer or contiguous ArrayBuffer and bind views with `.subarray()`.
- Code SHOULD enforce batch transactions via `db.transaction()` to amortize SQLite disk fsync and keep off-heap allocations scoped to a single tick.
- Services MUST ensure that off-heap buffers passed to prepared statements are not mutated while query execution or transaction commits are in flight.
- Components NEVER rely on automatic JavaScriptCore garbage collection to reclaim prepared statement handles; explicitly execute statement lifecycle cleanups when dynamic queries are discarded.

## Bad vs Good Implementations
### Ingesting High-Throughput Binary Telemetry into Bun SQLite

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Buffer.from(chunk) forces an extra allocation on the JSC managed heap and incurs a deep memory copy. Inlining db.run inside the loop re-prepares the query repeatedly, preventing Bun's C++ SQLite layer from operating on zero-copy pinned pointers.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('telemetry.sqlite');
db.run('CREATE TABLE IF NOT EXISTS frames (id INTEGER PRIMARY KEY, payload BLOB);');

export async function ingestFrames(frameStream: AsyncIterable<ArrayBuffer>) {
  for await (const chunk of frameStream) {
    // ANTI-PATTERN: Wrapping in Node.js Buffer copies data into the JSC heap,
    // and dynamic SQL execution forces re-compilation and per-row GC churn.
    const nodeBuf = Buffer.from(chunk);
    db.run('INSERT INTO frames (payload) VALUES (?)', [nodeBuf]);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Reuses a single prepared statement bound directly to Uint8Array instances. Bun 1.2 binds Uint8Array to sqlite3_bind_blob directly using off-heap native pointers without copying to the JSC heap, eliminating GC pauses.
```typescript
import { Database } from 'bun:sqlite';

const db = new Database('telemetry.sqlite');
db.run('PRAGMA journal_mode = WAL;');
db.run('CREATE TABLE IF NOT EXISTS frames (id INTEGER PRIMARY KEY, payload BLOB);');

const insertStmt = db.prepare('INSERT INTO frames (payload) VALUES (?1);');

export async function ingestFrames(frameStream: AsyncIterable<Uint8Array>) {
  const batchSize = 1000;
  const transaction = db.transaction((batch: Uint8Array[]) => {
    for (let i = 0; i < batch.length; i++) {
      // PROD STANDARD: Uint8Array view is bound directly to native SQLite pointer
      // without JSC heap promotion or memory copying.
      insertStmt.run(batch[i]);
    }
  });

  let pending: Uint8Array[] = [];
  for await (const chunk of frameStream) {
    // Reference contiguous zero-copy subarray view
    pending.push(chunk.subarray(0, chunk.byteLength));
    if (pending.length >= batchSize) {
      transaction(pending);
      pending = [];
    }
  }
  if (pending.length > 0) {
    transaction(pending);
  }
  insertStmt.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 Native SQLite Zero-Copy Off-Heap Buffer Invariant

Bun 1.2 Native SQLite Zero-Copy Off-Heap Buffer Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict buffer ownership transfer and zero-copy pinned allocations between the JavaScriptCore (JSC) heap and native SQLite pointers during high-throughput ingest in Bun 1.2+. Prevents JSC garbage collection stop-the-world pauses, double-free faults, and unaligned memory access by mandating direct Uint8Array slice reuse with SQLite native statement binding. 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: Implicit JSC Heap Allocation and Buffer Cloning During High-Volume SQLite Ingestion 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 DriftImplicit JSC Heap Allocation and Buffer Cloning During High-Volume SQLite IngestionCritical
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 bind raw typed arrays (Uint8Array) directly to native SQLite statements using positional parameters to leverage Bun's zero-copy C++ binding layer.

Engineers MUST ALWAYS bind raw typed arrays (Uint8Array) directly to native SQLite statements using positional parameters to leverage Bun's zero-copy C++ binding layer.

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 convert binary blobs into Node.js Buffer instances or intermediate base64/hex strings before persisting to Bun SQLite.

Engineers MUST NOT convert binary blobs into Node.js Buffer instances or intermediate base64/hex strings before persisting to Bun SQLite.

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 NOT re-allocate typed arrays within ingest loops

Engineers MUST NOT re-allocate typed arrays within ingest loops; pre-allocate a shared ring buffer or contiguous ArrayBuffer and bind views with `.subarray()`.

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 enforce batch transactions via `db.transaction()` to amortize SQLite disk fsync and keep off-heap allocations scoped to a single tick.

Code SHOULD enforce batch transactions via `db.transaction()` to amortize SQLite disk fsync and keep off-heap allocations scoped to a single tick.

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 off-heap buffers passed to prepared statements are not mutated while query execution or transaction commits are in flight.

Services MUST ensure that off-heap buffers passed to prepared statements are not mutated while query execution or transaction commits are in flight.

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

Components NEVER rely on automatic JavaScriptCore garbage collection to reclaim prepared statement handles

Components NEVER rely on automatic JavaScriptCore garbage collection to reclaim prepared statement handles; explicitly execute statement lifecycle cleanups when dynamic queries are discarded.

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 Native SQLite Zero-Copy Off-Heap Buffer Invariant critical for AI coding assistants?

Enforces strict buffer ownership transfer and zero-copy pinned allocations between the JavaScriptCore (JSC) heap and native SQLite pointers during high-throughput ingest in Bun 1.2+. Prevents JSC garbage collection stop-the-world pauses, double-free faults, and unaligned memory access by mandating direct Uint8Array slice reuse with SQLite native statement binding. 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 (Implicit JSC Heap Allocation and Buffer Cloning During High-Volume SQLite Ingestion) 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