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

Bun 1.2 Native FFI Deterministic Pointer Ownership and Deallocation Standard

Establishes strict boundaries between JavaScriptCore (JSC) garbage-collected references and native C/Rust heap memory managed through `bun:ffi`. Mandates explicit ownership transfer, deterministic disposal using `Symbol.dispose` via TypeScript 5.2+ explicit resource management, and double-free mitigation via nullification invariants.

Prohibited Anti-Pattern: Implicit pointer lifetimes, unmanaged raw addresses, and asynchronous garbage-collection reliance causing memory leaks or use-after-free/double-free crashes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Bun 1.2 Native FFI Deterministic Pointer Ownership and Deallocation Standard - Establishes strict boundaries between JavaScriptCore (JSC) garbage-collected references and native C/Rust heap memory managed through `bun:ffi`. Mandates explicit ownership transfer, deterministic disposal using `Symbol.dispose` via TypeScript 5.2+ explicit resource management, and double-free mitigation via nullification invariants.
globs: src/**/*.{ts,mts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/bun-ffi-pointer-ownership-lifecycle-standard"
---

# Bun 1.2 Native FFI Deterministic Pointer Ownership and Deallocation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Implicit pointer lifetimes, unmanaged raw addresses, and asynchronous garbage-collection reliance causing memory leaks or use-after-free/double-free crashes.

## System Constraints
You are a Principal Systems Engineer enforcing strict pointer ownership and explicit lifetime management for Bun 1.2 Native FFI (`bun:ffi`). You must guarantee zero double-free bugs, zero memory leaks across JSC GC boundaries, zero use-after-free conditions, and consistent usage of TypeScript's `using` keyword backed by defensive null-pointer tracking.

## Strict Guidelines
- Engineers MUST wrap every raw non-null `bun:ffi` pointer (`FFIType.ptr`) into a dedicated class implementing `Disposable` (`[Symbol.dispose]()`) or `AsyncDisposable` (`[Symbol.asyncDispose]()`).
- Engineers MUST ALWAYS set internal pointer tracking variables to `null` or 0 (`ptr(0)`) immediately after invoking the native deallocation symbol to mathematically prevent double-free calls.
- Engineers MUST NOT rely on JavaScriptCore `FinalizationRegistry` for synchronous, mission-critical, or high-throughput native resource deallocation, as GC timing is non-deterministic.
- Code MUST validate pointers with `ptr === null || ptr === 0` prior to dereferencing or passing to native symbols, explicitly throwing an `Error` on invalidated references.
- Engineers MUST designate single-owner semantics across the boundary: Rust/C allocating functions must explicitly pair with their respective `free`/`dealloc` library exports rather than mixing with generic C `free` unless explicitly specified by the library ABI.

## Bad vs Good Implementations
### Deterministic Lifetime Management for Native Pointers using Disposable

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Raw pointer has no bounded ownership contract. If `process_buffer` throws an exception, `free_buffer` is bypassed, creating a memory leak in the unmanaged native heap. Additionally, `rawPtr` remains in scope without being invalidated, exposing the runtime to use-after-free or double-free defects.
```typescript
import { dlopen, FFIType } from 'bun:ffi';

const lib = dlopen('libnative.so', {
  create_buffer: { args: [FFIType.usize], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr], returns: FFIType.void },
  process_buffer: { args: [FFIType.ptr], returns: FFIType.i32 },
});

// ANTI-PATTERN: Leaks pointer or triggers double-free if exceptions occur
// Relies on manual deallocation without guards or scope containment
export function runTask(size: number): number {
  const rawPtr = lib.symbols.create_buffer(size);
  if (!rawPtr) throw new Error('Allocation failed');

  const result = lib.symbols.process_buffer(rawPtr);
  lib.symbols.free_buffer(rawPtr);
  // If another call runs lib.symbols.free_buffer(rawPtr), process panics with SIGSEGV/SIGABRT
  return result;
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulates the raw pointer within a class implementing TypeScript's `Disposable` interface. The `using` declaration guarantees deterministic deallocation on scope exit (even during thrown exceptions). Defensive nullification occurs before invoking `free_buffer`, preventing double-free panics and reentrancy bugs.
```typescript
import { dlopen, FFIType, type Pointer } from 'bun:ffi';

const lib = dlopen('libnative.so', {
  create_buffer: { args: [FFIType.usize], returns: FFIType.ptr },
  free_buffer: { args: [FFIType.ptr], returns: FFIType.void },
  process_buffer: { args: [FFIType.ptr], returns: FFIType.i32 },
});

export class NativeBuffer implements Disposable {
  #ptr: Pointer | null;

  constructor(size: number) {
    const raw = lib.symbols.create_buffer(size);
    if (!raw) {
      throw new Error('Failed to allocate native buffer');
    }
    this.#ptr = raw;
  }

  get pointer(): Pointer {
    if (this.#ptr === null) {
      throw new Error('Use-after-free attempt on invalidated NativeBuffer pointer');
    }
    return this.#ptr;
  }

  [Symbol.dispose](): void {
    if (this.#ptr !== null) {
      const address = this.#ptr;
      this.#ptr = null; // Invariant: Nullify prior to foreign invocation to eliminate reentrancy double-free
      lib.symbols.free_buffer(address);
    }
  }
}

// PRODUCTION-GRADE: Scoped deterministic cleanup via TC39/TS 5.2 Explicit Resource Management
export function runTask(size: number): number {
  using buffer = new NativeBuffer(size);
  return lib.symbols.process_buffer(buffer.pointer);
}
```

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 FFI Deterministic Pointer Ownership and Deallocation Standard

Bun 1.2 Native FFI Deterministic Pointer Ownership and Deallocation Standard defines an industrial-grade behavioral standard for backend engineering. Establishes strict boundaries between JavaScriptCore (JSC) garbage-collected references and native C/Rust heap memory managed through `bun:ffi`. Mandates explicit ownership transfer, deterministic disposal using `Symbol.dispose` via TypeScript 5.2+ explicit resource management, and double-free mitigation via nullification invariants. 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 pointer lifetimes, unmanaged raw addresses, and asynchronous garbage-collection reliance causing memory leaks or use-after-free/double-free crashes. 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 pointer lifetimes, unmanaged raw addresses, and asynchronous garbage-collection reliance causing memory leaks or use-after-free/double-free crashes.Critical
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 wrap every raw non-null `bun

Engineers MUST wrap every raw non-null `bun:ffi` pointer (`FFIType.ptr`) into a dedicated class implementing `Disposable` (`[Symbol.dispose]()`) or `AsyncDisposable` (`[Symbol.asyncDispose]()`).

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 ALWAYS set internal pointer tracking variables to `null` or 0 (`ptr(0)`) immediately after invoking the native deallocation symbol to mathematically prevent double-free calls.

Engineers MUST ALWAYS set internal pointer tracking variables to `null` or 0 (`ptr(0)`) immediately after invoking the native deallocation symbol to mathematically prevent double-free calls.

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 rely on JavaScriptCore `FinalizationRegistry` for synchronous, mission-critical, or high-throughput native resource deallocation, as GC timing is non-deterministic.

Engineers MUST NOT rely on JavaScriptCore `FinalizationRegistry` for synchronous, mission-critical, or high-throughput native resource deallocation, as GC timing is non-deterministic.

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 MUST validate pointers with `ptr === null || ptr === 0` prior to dereferencing or passing to native symbols, explicitly throwing an `Error` on invalidated references.

Code MUST validate pointers with `ptr === null || ptr === 0` prior to dereferencing or passing to native symbols, explicitly throwing an `Error` on invalidated references.

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 designate single-owner semantics across the boundary

Engineers MUST designate single-owner semantics across the boundary: Rust/C allocating functions must explicitly pair with their respective `free`/`dealloc` library exports rather than mixing with generic C `free` unless explicitly specified by the library ABI.

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 Deterministic Pointer Ownership and Deallocation Standard critical for AI coding assistants?

Establishes strict boundaries between JavaScriptCore (JSC) garbage-collected references and native C/Rust heap memory managed through `bun:ffi`. Mandates explicit ownership transfer, deterministic disposal using `Symbol.dispose` via TypeScript 5.2+ explicit resource management, and double-free mitigation via nullification invariants. 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 pointer lifetimes, unmanaged raw addresses, and asynchronous garbage-collection reliance causing memory leaks or use-after-free/double-free crashes.) 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