This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: bun-v12-ffi-lifetime-pointer-safety

Bun 1.2 Native FFI C-ABI Lifetime & Pointer Safety Standard

Enforces strict memory ownership boundaries, pinned buffer allocation, and deterministic lifecycle tracking across JavaScript runtime and C-ABI native shared libraries in Bun 1.2. Eliminates dangling pointers caused by V8/JSC garbage collector compaction and halts fatal double-free or use-after-free corruption through explicit FinalizationRegistry unregister semantics and branded pointer wrappers.

Prohibited Anti-Pattern: Passing unpinned TypedArray backing stores to asynchronous native workers or relying on nondeterministic GC finalizers for C heap reclamation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI C-ABI Lifetime & Pointer Safety Standard - Enforces strict memory ownership boundaries, pinned buffer allocation, and deterministic lifecycle tracking across JavaScript runtime and C-ABI native shared libraries in Bun 1.2. Eliminates dangling pointers caused by V8/JSC garbage collector compaction and halts fatal double-free or use-after-free corruption through explicit FinalizationRegistry unregister semantics and branded pointer wrappers.
globs: src/**/*.{ts,js,mts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-v12-ffi-lifetime-pointer-safety"
---

# Bun 1.2 Native FFI C-ABI Lifetime & Pointer Safety Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Passing unpinned TypedArray backing stores to asynchronous native workers or relying on nondeterministic GC finalizers for C heap reclamation

## System Constraints
You are a Principal Systems Engineer enforcing Bun 1.2 Native FFI C-ABI Lifetime & Pointer Safety Standards. Mandate deterministic ownership invariants, prevent GC-driven memory invalidation of buffers passed across the boundary, and enforce RAII-style lifecycle control for all raw pointers (`FFIType.ptr`).

## Strict Guidelines
- Engineers MUST ALWAYS track C-allocated heap memory using explicit RAII wrapper classes with `Symbol.dispose` (Explicit Resource Management) rather than relying exclusively on `FinalizationRegistry`.
- Engineers MUST NEVER pass raw `Uint8Array` or `ArrayBuffer` pointers to asynchronous or non-blocking native functions without pinning them via persistent references or explicit native-side allocations.
- Engineers MUST use `ptr()` and `toArrayBuffer()` with explicit byte offset and byte length bounds checking to prevent out-of-bounds reads into unmapped process memory.
- Engineers MUST explicitly unregister pointer tokens from `FinalizationRegistry` cleanup routines when manual deallocation (`free()` / `.dispose()`) is invoked to prevent fatal double-free memory panics.
- Services MUST validate that pointer addresses received from native routines are non-null (`ptr !== 0n && ptr !== null`) prior to dereferencing or wrapping into typed structures.
- Components NEVER store naked integer or bigint addresses in global application state; pointers must be encapsulated in nominal/branded types that record ownership semantics.

## Bad vs Good Implementations
### Manual RAII Pointer Lifecycle with Deterministic Disposal vs GC Finalizer Race

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relying purely on `FinalizationRegistry` provides no guarantee of timely execution before process exit or native heap exhaustion. Furthermore, if a caller manually deallocates `holder.handle` and drops the object, the finalizer later invokes `free_buffer` on an already-freed pointer, causing an abort or remote memory corruption.
```typescript
import { dlopen, FFIType, ptr } from "bun:ffi";

const lib = dlopen("libnative.so", {
  create_buffer: { args: [FFIType.u32], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr], returns: FFIType.void },
});

// Anti-pattern: Implicit GC-only reclamation risks high-water memory exhaustion and double-free races
const registry = new FinalizationRegistry((rawPtr: number) => {
  lib.symbols.free_buffer(rawPtr);
});

export function allocateContext(size: number) {
  const raw = lib.symbols.create_buffer(size);
  const holder = { handle: raw };
  registry.register(holder, raw);
  return holder; // Exposing raw handle without safe dereferencing or deterministic dispose
}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic RAII using TypeScript's `Disposable` interface (`Symbol.dispose`), ensuring memory can be immediately freed with `using` declarations. Nullifies the pointer reference after freeing and actively calls `registry.unregister` using an unregister token to guarantee that a subsequent GC sweep never triggers a double-free bug.
```typescript
import { dlopen, FFIType, ptr, toArrayBuffer } from "bun:ffi";

declare const BrandSymbol: unique symbol;
type NativePointer<T extends string> = bigint & { readonly [BrandSymbol]: T };

const lib = dlopen("libnative.so", {
  create_buffer: { args: [FFIType.u32], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr], returns: FFIType.void },
});

const registry = new FinalizationRegistry((address: bigint) => {
  lib.symbols.free_buffer(Number(address));
});

export class NativeAllocation implements Disposable {
  #ptr: bigint | null;
  #size: number;
  #token: object = {};

  constructor(size: number) {
    const raw = lib.symbols.create_buffer(size);
    if (!raw || raw === 0) {
      throw new Error("Native allocation failed: NULL pointer returned");
    }
    this.#ptr = BigInt(raw);
    this.#size = size;
    registry.register(this.#token, this.#ptr, this.#token);
  }

  get view(): Uint8Array {
    if (this.#ptr === null) throw new Error("Access after free: pointer is disposed");
    return new Uint8Array(toArrayBuffer(Number(this.#ptr), 0, this.#size));
  }

  [Symbol.dispose](): void {
    if (this.#ptr !== null) {
      registry.unregister(this.#token);
      lib.symbols.free_buffer(Number(this.#ptr));
      this.#ptr = null;
    }
  }
}
```

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 Native FFI C-ABI Lifetime & Pointer Safety Standard

Bun 1.2 Native FFI C-ABI Lifetime & Pointer Safety Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict memory ownership boundaries, pinned buffer allocation, and deterministic lifecycle tracking across JavaScript runtime and C-ABI native shared libraries in Bun 1.2. Eliminates dangling pointers caused by V8/JSC garbage collector compaction and halts fatal double-free or use-after-free corruption through explicit FinalizationRegistry unregister semantics and branded pointer wrappers. 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: Passing unpinned TypedArray backing stores to asynchronous native workers or relying on nondeterministic GC finalizers for C heap reclamation 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 DriftPassing unpinned TypedArray backing stores to asynchronous native workers or relying on nondeterministic GC finalizers for C heap reclamationCritical
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 track C-allocated heap memory using explicit RAII wrapper classes with `Symbol.dispose` (Explicit Resource Management) rather than relying exclusively on `FinalizationRegistry`.

Engineers MUST ALWAYS track C-allocated heap memory using explicit RAII wrapper classes with `Symbol.dispose` (Explicit Resource Management) rather than relying exclusively on `FinalizationRegistry`.

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 NEVER pass raw `Uint8Array` or `ArrayBuffer` pointers to asynchronous or non-blocking native functions without pinning them via persistent references or explicit native-side allocations.

Engineers MUST NEVER pass raw `Uint8Array` or `ArrayBuffer` pointers to asynchronous or non-blocking native functions without pinning them via persistent references or explicit native-side allocations.

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 use `ptr()` and `toArrayBuffer()` with explicit byte offset and byte length bounds checking to prevent out-of-bounds reads into unmapped process memory.

Engineers MUST use `ptr()` and `toArrayBuffer()` with explicit byte offset and byte length bounds checking to prevent out-of-bounds reads into unmapped process memory.

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

Engineers MUST explicitly unregister pointer tokens from `FinalizationRegistry` cleanup routines when manual deallocation (`free()` / `.dispose()`) is invoked to prevent fatal double-free memory panics.

Engineers MUST explicitly unregister pointer tokens from `FinalizationRegistry` cleanup routines when manual deallocation (`free()` / `.dispose()`) is invoked to prevent fatal double-free memory panics.

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 validate that pointer addresses received from native routines are non-null (`ptr !== 0n && ptr !== null`) prior to dereferencing or wrapping into typed structures.

Services MUST validate that pointer addresses received from native routines are non-null (`ptr !== 0n && ptr !== null`) prior to dereferencing or wrapping into typed structures.

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 store naked integer or bigint addresses in global application state

Components NEVER store naked integer or bigint addresses in global application state; pointers must be encapsulated in nominal/branded types that record ownership semantics.

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 FFI C-ABI Lifetime & Pointer Safety Standard critical for AI coding assistants?

Enforces strict memory ownership boundaries, pinned buffer allocation, and deterministic lifecycle tracking across JavaScript runtime and C-ABI native shared libraries in Bun 1.2. Eliminates dangling pointers caused by V8/JSC garbage collector compaction and halts fatal double-free or use-after-free corruption through explicit FinalizationRegistry unregister semantics and branded pointer wrappers. 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 (Passing unpinned TypedArray backing stores to asynchronous native workers or relying on nondeterministic GC finalizers for C heap reclamation) 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